Advertisement
Guest User

marriage_analysis

a guest
Aug 6th, 2013
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. import numpy as np
  2. data = np.loadtxt('marriage.txt').reshape((4, 5, 5))
  3.  
  4. def rake(A, epsilon=0.001):
  5.     """Return a raked version of a given array, i.e., with row and column
  6.    sums adjusted to unity.
  7.    """
  8.     B = np.empty(A.shape)
  9.     B[:,:] = A[:,:]
  10.     while (abs(B.sum(axis=0) - 1).max() > epsilon or
  11.            abs(B.sum(axis=1) - 1).max() > epsilon):
  12.         B = B / B.sum(axis=0)
  13.         B = (B.transpose() / B.sum(axis=1)).transpose()
  14.     return B
  15.  
  16. def frac_data(A):
  17.     """Return the fractions of population found in the lower triangle, the
  18.    main diagonal, and the upper triangle.
  19.    """
  20.     assert len(A.shape) == 2
  21.     assert A.shape[0] == A.shape[1]
  22.     n = A.shape[0]
  23.     diag = np.trace(A) / A.sum()
  24.     lower = (np.tril(A).sum() - np.trace(A)) / A.sum()
  25.     upper = (np.triu(A).sum() - np.trace(A)) / A.sum()
  26.     return lower, diag, upper
  27.    
  28. def split_data(A):
  29.     """Return the mean values found in the lower triangle, the
  30.    main diagonal, and the upper triangle.
  31.    """
  32.     assert len(A.shape) == 2
  33.     assert A.shape[0] == A.shape[1]
  34.     n = A.shape[0]
  35.     diag = np.trace(A) / n
  36.     lower = (np.tril(A).sum() - np.trace(A)) / ((n * n - n) / 2)
  37.     upper = (np.triu(A).sum() - np.trace(A)) / ((n * n - n) / 2)
  38.     return lower, diag, upper
  39.    
  40. def high_vals(A):
  41.     """Return a version of A with all "low" values set to zero (i.e., all values with
  42.    (i + j) < n).  N.B. the cross diagonal will not be set to zero.
  43.    """
  44.     B = np.empty(A.shape)
  45.     B[:,:] = A[:,:]
  46.     n = len(A)
  47.     for i in range(n):
  48.         for j in range(n-i-1):
  49.             B[i,j] = 0
  50.     return B
  51.  
  52. def low_vals(A):
  53.     """Return a version of A with all "high" values set to zero (i.e., all values with
  54.    (i + j) >= n-1).  N.B. the cross diagonal will not be set to zero.
  55.    """
  56.     B = np.empty(A.shape)
  57.     B[:,:] = A[:,:]
  58.     n = len(A)
  59.     for i in range(n):
  60.         for j in range(n-i, n):
  61.             B[i,j] = 0
  62.     return B
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement