def CompHyperPlane(V,K):
	# compute the outwards normal direction
	#V: vertex; K: vertex index for each facet
	ns = zeros((shape(K)[0],shape(V)[1]+1)) # normal of each hyperplane and offset
	NP=[] #invalid hyperplane
	nbCol= shape(V)[1]
	for i in range(shape(K)[0]):
		tmp = zeros((shape(V[K[i,:],:])[0],nbCol+1))
		tmp[:,0:nbCol] = V[K[i,:],:]
		tmp[:,nbCol]= ones((shape(V[K[i,:],:])[0]))
		tmp1= nullspace(tmp)
		tmp1 = transpose(tmp1)
		if shape(tmp1)[0]== 0:
			print "Oops! Not Valid......"
		if shape(tmp1)[0]>1:
			ns[i,:] = tmp1[0,:]
			NP.append(i)
		else:
			ns[i,:] = tmp1[0,:]

		#check the normal and it is outwards direction:
		"""
		If V is a normal, b is an offset, and x is a point inside the convex hull, then Vx+b <0.
		In the newer version of scipy, this hyperplane is given as an output.
		"""
		if dot(ns[i,0:6],V[K[i,0],:])<0:
			ns[i,:] = -ns[i,:]
	ns = numpy.delete(ns,NP,0)
	K = numpy.delete(K, NP,0)
	return ns, K
Exemplo n.º 2
0
 def SetT(self):
     if self.H_hat.shape[0] != 0:
         NS = nullspace(self.H_hat)
         if rank(NS) >= self.Nj:
             self.PrecodingT = NS[:, 0:self.Nj]
         else:
             self.PrecodingT = [None]
     else:
         self.PrecodingT = [None]
Exemplo n.º 3
0
 def extractVoltage(self, y):
     # Construct matrix A, work out the math more carefully
     A = np.zeros((self.COUNT, self.COUNT))
     for i in range(len(y)):
         A -= y[i] * self.F_MATRICES[i]
     A += np.identity(self.COUNT)
     # Find the null space of matrix A
     ns = nullspace(A)
     return ns
Exemplo n.º 4
0
def checkit(a):
    print "a:"
    print a
    r = rank(a)
    print "rank is", r
    ns = nullspace(a)
    print "nullspace:"
    print ns
    if ns.size > 0:
        res = np.abs(np.dot(a, ns)).max()
        print "max residual is", res    
def circumference(c,r,Nvec,np):
    """
    Function that generates the coordinates of a circunference as a 
    3xnumberOfPoints matrix.
    ---Inputs---
    c - center of circumfarence.
    r - radius of circumference.
    Nvec - vector normal to the circumference, used to rotate the circunfarence (vortex ring)
    np - number of points defining the circumference
    ---
    C.Losada de la Lastra 2014
    
    NOTE: For the purpose of this project the matrix 'C' contains np+1 columns.
    This is to take into account the need to close the circunference when 
    plotting the circunference or calculating the induced velocity due to the vortex ring.
    """
    from rank_nullspace import nullspace #.pyc file where nullspace is defined

    #range of angles corresponding to the points on the circumference
    theta = N.array([i*(2*M.pi/np) for i in range(np)])
        
    thet_cos = N.array([M.cos(theta[i]) for i in range(len(theta))])
    theta_cos = N.array([thet_cos,])
    thet_sin = N.array([M.sin(theta[i]) for i in range(len(theta))])
    theta_sin = N.array([thet_sin,])
    #rotation of the circunference with respect to the vector normal to the ring    
    rot = N.array(nullspace(Nvec))#rotation vecors y & z  
    rot_y = N.array([rot[:,0],]).transpose()
    rot_z = N.array([rot[:,1],]).transpose()
    
    #rotation of the x,y,z coordinates of the cirumference
    C_origin =  N.array([c,]*(np)).transpose()
    C_y = r*N.dot(rot_y,theta_cos)
    C_z = r*N.dot(rot_z,theta_sin) 

    C = C_origin + C_y + C_z
    #points in the middle of the segments forming the circumference
    #where the velocity will be induced from (more realistic)    
    C_iVel = N.zeros_like(C)
    for i in range(len(C_y[0])):
        pnt = N.array([C[0][i],C[1][i],C[2][i]])
        pnt0 = N.array([C[0][i-1],C[1][i-1],C[2][i-1]])
        vect = pnt0-pnt
        vect_u = vect/LA.norm(vect)
        
        ivel_pnt = pnt + vect_u*(LA.norm(vect)/2)
        
        C_iVel[0][i]=ivel_pnt[0]        
        C_iVel[1][i]=ivel_pnt[1]        
        C_iVel[2][i]=ivel_pnt[2]        
   
    return N.array([C, C_iVel])
def ContactPrimitive(p,np, mu, nb):
	W = zeros((6,nb))
	ns = nullspace(np)
	X=transpose(ns[:,0])
	Z=np
	Y =cross(Z, X)
	R=ones((3,3))
	R[0:3,0] = X
	R[0:3,1] = Y
	R[0:3,2] = Z
	for i in range(nb):
		W[0,i]= mu*cos(float(i)/nb*2.0*pi)
		W[1,i]= mu*sin(float(i)/nb*2*pi)
		W[2,i]= 1
		W[0:3,i] = dot(R,W[0:3,i])
		W[3:6,i] = cross(p,W[0:3,i])
	return transpose(W)
Exemplo n.º 7
0
def calculate_knfst(K, labels):
    '''
    Calculates projection matrix of KNFST
    '''
    classes = np.unique(labels)
    if len(classes) < 2:
        raise Exception("KNFST requires 2 or more classes")
    n, m = K.shape
    if n != m:
        raise Exception("Kernel matrix must be quadratic")
    
    centered_k = KernelCenterer().fit_transform(K)
    basis_values, basis_vecs = np.linalg.eig(centered_k)

    idx = basis_values.argsort()[::-1]
    basis_values = basis_values[idx]
    basis_vecs = basis_vecs[:, idx]

    basis_vecs = basis_vecs[:,basis_values > 1e-12]
    basis_values = basis_values[basis_values > 1e-12]
 
    basis_values = np.diag(1.0/np.sqrt(basis_values))
    basis_vecs  = basis_vecs.dot(basis_values)

    L = np.zeros([n,n])
    for cl in classes:
        for idx1, x in enumerate(labels == cl):
            for idx2, y in enumerate(labels == cl):
                if x and y:
                    L[idx1, idx2] = 1.0/np.sum(labels==cl)
    
    M = np.ones([m,m])/m
    H = ((np.eye(m,m)-M).dot(basis_vecs)).T.dot(K).dot(np.eye(n,m)-L)
    
    t_sw = H.dot(H.T)
    
    eigenvecs = nullspace(t_sw)
    if eigenvecs.shape[1] < 1:
        eigenvals, eigenvecs = np.linalg.eig(t_sw)
        eigenvals = np.diag(eigenvals)
        min_idx = eigenvals.argsort()[0]
        eigenvecs = eigenvecs[:, min_idx]
        
    proj = (np.eye(m,m)-M).dot(basis_vecs).dot(eigenvecs)
    return proj
Exemplo n.º 8
0
def calculate_knfst(K, labels):
    '''
    Calculates projection matrix of KNFST
    '''
    classes = np.unique(labels)
    if len(classes) < 2:
        raise Exception("KNFST requires 2 or more classes")
    n, m = K.shape
    if n != m:
        raise Exception("Kernel matrix must be quadratic")

    centered_k = KernelCenterer().fit_transform(K)
    basis_values, basis_vecs = np.linalg.eig(centered_k)

    idx = basis_values.argsort()[::-1]
    basis_values = basis_values[idx]
    basis_vecs = basis_vecs[:, idx]

    basis_vecs = basis_vecs[:, basis_values > 1e-12]
    basis_values = basis_values[basis_values > 1e-12]

    basis_values = np.diag(1.0 / np.sqrt(basis_values))
    basis_vecs = basis_vecs.dot(basis_values)

    L = np.zeros([n, n])
    for cl in classes:
        for idx1, x in enumerate(labels == cl):
            for idx2, y in enumerate(labels == cl):
                if x and y:
                    L[idx1, idx2] = 1.0 / np.sum(labels == cl)

    M = np.ones([m, m]) / m
    H = ((np.eye(m, m) - M).dot(basis_vecs)).T.dot(K).dot(np.eye(n, m) - L)

    t_sw = H.dot(H.T)

    eigenvecs = nullspace(t_sw)
    if eigenvecs.shape[1] < 1:
        eigenvals, eigenvecs = np.linalg.eig(t_sw)
        eigenvals = np.diag(eigenvals)
        min_idx = eigenvals.argsort()[0]
        eigenvecs = eigenvecs[:, min_idx]

    proj = (np.eye(m, m) - M).dot(basis_vecs).dot(eigenvecs)
    return proj
Exemplo n.º 9
0
def get_prob_dist(M):
    '''
    Input:
        M : matrix
    Output:
        dist : prob normalised nullspace vector of M
    '''
    nullspace = rank_nullspace.nullspace(M, rtol=1e-9)
    if (nullspace.shape[1] > 0):
        #non-trivial nullspace exists for M
        # dist is prob distribution
        dist = nullspace[:, 0] / nullspace[:, 0].sum(axis=0)
    else:
        #nullspace is trivial, in this case there is no stable prob. distribution,
        #In case raised, try changing the rtol parameter
        raise ValueError(
            'Nullspace of Markov matrix is trivial. No probability distribution exists'
        )
    return dist
Exemplo n.º 10
0
 def get_prob_dist(self):
     '''
     Output:
         dist : prob normalised nullspace vector of M
     '''
     # Adjacency matrix, caution not the Markov matrix
     A = nx.to_numpy_matrix(self.G)
     # look at this carefully
     M =  A.T - np.diag(np.array(A.sum(axis=1)).reshape((A.shape[0])))
 
     try:
         nullspace = rank_nullspace.nullspace(M,rtol=1e-9,atol=1e-9)  
         if (nullspace.shape[1] > 0):
             #non-trivial nullspace exists for M
             # dist is prob distribution
             self.dist = nullspace[:,0]/nullspace[:,0].sum(axis=0)
         else:
             #nullspace is trivial, in this case there is no stable prob. distribution,
             #In case raised, try changing the rtol parameter
             raise ValueError('Nullspace of Markov matrix is trivial. No probability distribution exists')
     except (ValueError,np.linalg.LinAlgError) as e:
         raise exceptions.InvalidChargeState
     return self.dist
Exemplo n.º 11
0

print
print '*****'
# now show a under-determined system allows more solutions
kFlips = 7
# confirm more probs would completely determine this situation
# (will be by analogy to the moment curve)
print '***** nSides =',nSides,'kFlips =',kFlips
sU = freqSystem(nSides,kFlips)
print 'is full rank'
print rank(sU['a'].T * sU['a'])==kFlips+1
print 'can extend to full rank'
sCheck = freqSystem(nSides,kFlips,stepMult=2)
print rank(sCheck['a'].T * sCheck['a'])==kFlips+1
wiggleRoom = nullspace(sU['a'])
print 'confirm null vecs'
wiggleDim = wiggleRoom.shape[1]
print (wiggleRoom.shape[0]==kFlips+1) & \
   (wiggleDim + nSides-1==kFlips+1) & \
   (numpy.matrix.max(abs(sU['a'] * wiggleRoom))<1.0e-12)
baseSoln = empiricalMeansEstimates(nSides,kFlips)
print 'empirical solution'
printEsts(baseSoln)
baseLosses = losses(nSides,baseSoln)
print 'empirical solution losses'
printLosses(baseLosses)

def wsoln(x):
   return baseSoln + matMulFlatten(wiggleRoom,x)
Exemplo n.º 12
0
def compute_paths(T, econ):
    """
    Compute simulated time paths for exogenous and endogenous variables.

    Parameters
    ===========
    T: int
        Length of the simulation

    econ: a namedtuple of type 'Economy', containing
         beta       - Discount factor
         Sg         - Govt spending selector matrix
         Sd         - Exogenous endowment selector matrix
         Sb         - Utility parameter selector matrix
         Ss         - Coupon payments selector matrix
         discrete   - Discrete exogenous process (True or False)
         proc       - Stochastic process parameters

    Returns
    ========
    path: a namedtuple of type 'Path', containing
         g            - Govt spending
         d            - Endowment
         b            - Utility shift parameter
         s            - Coupon payment on existing debt
         c            - Consumption
         l            - Labor
         p            - Price
         tau          - Tax rate
         rvn          - Revenue
         B            - Govt debt
         R            - Risk free gross return
         pi           - One-period risk-free interest rate
         Pi           - Cumulative rate of return, adjusted
         xi           - Adjustment factor for Pi

        The corresponding values are flat numpy ndarrays.

    """

    # == Simplify names == #
    beta, Sg, Sd, Sb, Ss = econ.beta, econ.Sg, econ.Sd, econ.Sb, econ.Ss

    if econ.discrete:
        P, x_vals = econ.proc
    else:
        A, C = econ.proc

    # == Simulate the exogenous process x == #
    if econ.discrete:
        state = mc_tools.sample_path(P, init=0, sample_size=T)
        x = x_vals[:, state]
    else:
        # == Generate an initial condition x0 satisfying x0 = A x0 == #
        nx, nx = A.shape
        x0 = nullspace((eye(nx) - A))
        x0 = -x0 if (x0[nx - 1] < 0) else x0
        x0 = x0 / x0[nx - 1]

        # == Generate a time series x of length T starting from x0 == #
        nx, nw = C.shape
        x = zeros((nx, T))
        w = randn(nw, T)
        x[:, 0] = x0.T
        for t in range(1, T):
            x[:, t] = dot(A, x[:, t - 1]) + dot(C, w[:, t])

    # == Compute exogenous variable sequences == #
    g, d, b, s = (dot(S, x).flatten() for S in (Sg, Sd, Sb, Ss))

    # == Solve for Lagrange multiplier in the govt budget constraint == #
    ## In fact we solve for nu = lambda / (1 + 2*lambda).  Here nu is the
    ## solution to a quadratic equation a(nu**2 - nu) + b = 0 where
    ## a and b are expected discounted sums of quadratic forms of the state.
    Sm = Sb - Sd - Ss
    # == Compute a and b == #
    if econ.discrete:
        ns = P.shape[0]
        F = scipy.linalg.inv(np.identity(ns) - beta * P)
        a0 = 0.5 * dot(F, dot(Sm, x_vals).T ** 2)[0]
        H = dot(Sb - Sd + Sg, x_vals) * dot(Sg - Ss, x_vals)
        b0 = 0.5 * dot(F, H.T)[0]
        a0, b0 = float(a0), float(b0)
    else:
        H = dot(Sm.T, Sm)
        a0 = 0.5 * var_quadratic_sum(A, C, H, beta, x0)
        H = dot((Sb - Sd + Sg).T, (Sg + Ss))
        b0 = 0.5 * var_quadratic_sum(A, C, H, beta, x0)

    # == Test that nu has a real solution before assigning == #
    warning_msg = """
    Hint: you probably set government spending too {}.  Elect a {}
    Congress and start over.
    """
    disc = a0 ** 2 - 4 * a0 * b0
    if disc >= 0:
        nu = 0.5 * (a0 - sqrt(disc)) / a0
    else:
        print "There is no Ramsey equilibrium for these parameters."
        print warning_msg.format("high", "Republican")
        sys.exit(0)

    # == Test that the Lagrange multiplier has the right sign == #
    if nu * (0.5 - nu) < 0:
        print "Negative multiplier on the government budget constraint."
        print warning_msg.format("low", "Democratic")
        sys.exit(0)

    # == Solve for the allocation given nu and x == #
    Sc = 0.5 * (Sb + Sd - Sg - nu * Sm)
    Sl = 0.5 * (Sb - Sd + Sg - nu * Sm)
    c = dot(Sc, x).flatten()
    l = dot(Sl, x).flatten()
    p = dot(Sb - Sc, x).flatten()  # Price without normalization
    tau = 1 - l / (b - c)
    rvn = l * tau

    # == Compute remaining variables == #
    if econ.discrete:
        H = dot(Sb - Sc, x_vals) * dot(Sl - Sg, x_vals) - dot(Sl, x_vals) ** 2
        temp = dot(F, H.T).flatten()
        B = temp[state] / p
        H = dot(P[state, :], dot(Sb - Sc, x_vals).T).flatten()
        R = p / (beta * H)
        temp = dot(P[state, :], dot(Sb - Sc, x_vals).T).flatten()
        xi = p[1:] / temp[: T - 1]
    else:
        H = dot(Sl.T, Sl) - dot((Sb - Sc).T, Sl - Sg)
        L = np.empty(T)
        for t in range(T):
            L[t] = var_quadratic_sum(A, C, H, beta, x[:, t])
        B = L / p
        Rinv = (beta * dot(dot(Sb - Sc, A), x)).flatten() / p
        R = 1 / Rinv
        AF1 = dot(Sb - Sc, x[:, 1:])
        AF2 = dot(dot(Sb - Sc, A), x[:, : T - 1])
        xi = AF1 / AF2
        xi = xi.flatten()

    pi = B[1:] - R[: T - 1] * B[: T - 1] - rvn[: T - 1] + g[: T - 1]
    Pi = cumsum(pi * xi)

    # == Prepare return values == #
    path = Path(g=g, d=d, b=b, s=s, c=c, l=l, p=p, tau=tau, rvn=rvn, B=B, R=R, pi=pi, Pi=Pi, xi=xi)

    return path
def circumference(c, r, Nvec, np):
    """
    Function that generates the coordinates of a circunference as a 
    3xnumberOfPoints matrix.
    ---Inputs---
    c - center of circumfarence.
    r - radius of circumference.
    Nvec - vector normal to the circumference, used to rotate the circunfarence (vortex ring)
    np - number of points defining the circumference
    ---
    C.Losada de la Lastra 2014
    
    NOTE: For the purpose of this project the matrix 'C' contains np+1 columns.
    This is to take into account the need to close the circunference when 
    plotting the circunference or calculating the induced velocity due to the vortex ring.
    """
    from rank_nullspace import nullspace  #.pyc file where nullspace is defined

    #range of angles corresponding to the points on the circumference
    theta = N.array([i * (2 * M.pi / np) for i in range(np)])

    thet_cos = N.array([M.cos(theta[i]) for i in range(len(theta))])
    theta_cos = N.array([
        thet_cos,
    ])
    thet_sin = N.array([M.sin(theta[i]) for i in range(len(theta))])
    theta_sin = N.array([
        thet_sin,
    ])
    #rotation of the circunference with respect to the vector normal to the ring
    rot = N.array(nullspace(Nvec))  #rotation vecors y & z
    rot_y = N.array([
        rot[:, 0],
    ]).transpose()
    rot_z = N.array([
        rot[:, 1],
    ]).transpose()

    #rotation of the x,y,z coordinates of the cirumference
    C_origin = N.array([
        c,
    ] * (np)).transpose()
    C_y = r * N.dot(rot_y, theta_cos)
    C_z = r * N.dot(rot_z, theta_sin)

    C = C_origin + C_y + C_z
    #points in the middle of the segments forming the circumference
    #where the velocity will be induced from (more realistic)
    C_iVel = N.zeros_like(C)
    for i in range(len(C_y[0])):
        pnt = N.array([C[0][i], C[1][i], C[2][i]])
        pnt0 = N.array([C[0][i - 1], C[1][i - 1], C[2][i - 1]])
        vect = pnt0 - pnt
        vect_u = vect / LA.norm(vect)

        ivel_pnt = pnt + vect_u * (LA.norm(vect) / 2)

        C_iVel[0][i] = ivel_pnt[0]
        C_iVel[1][i] = ivel_pnt[1]
        C_iVel[2][i] = ivel_pnt[2]

    return N.array([C, C_iVel])
Exemplo n.º 14
0
X_scaler = StandardScaler().fit(X_raw)
X_std = X_scaler.transform(X_raw)  # cf .inverse_transform()
# Acoustics
Y_scaler = StandardScaler().fit(Y_raw)
Y_std = Y_scaler.transform(Y_raw)

# PCA
pca = PCA(n_components=3)
pca.fit(X_std)
X_reduced = pca.transform(X_std)

# Linear Regression
#  X*w = y
W = np.dot(np.linalg.pinv(X_reduced), Y_std)
# Get null space
nullvec = nullspace(W.T)

# Compute median articulation & acoustic values
medianArtic = np.zeros((len(vowel_list), 14))
medianAcous = np.zeros((len(vowel_list), 2))
for i, v in enumerate(vowel_list):
    x = df.loc[df.Label == v, artic_col].values
    y = df.loc[df.Label == v, acous_col].values
    medianArtic[i, :] = np.median(x, axis=0)  # 7x14
    medianAcous[i, :] = np.median(y, axis=0)  # 7x2

# Estimate F1, F2 for each vowel
y_scaled_vowels = np.dot(pca.transform(X_scaler.transform(medianArtic)), W)
y_vowels = Y_scaler.inverse_transform(y_scaled_vowels)  # 7x2

Exemplo n.º 15
0
def compute_paths(T, econ):
    """
    Compute simulated time paths for exogenous and endogenous variables.

    Parameters
    ===========
    T: int
        Length of the simulation

    econ: a namedtuple of type 'Economy', containing
         beta       - Discount factor
         Sg         - Govt spending selector matrix
         Sd         - Exogenous endowment selector matrix
         Sb         - Utility parameter selector matrix
         Ss         - Coupon payments selector matrix
         discrete   - Discrete exogenous process (True or False)
         proc       - Stochastic process parameters

    Returns
    ========
    path: a namedtuple of type 'Path', containing
         g            - Govt spending
         d            - Endowment
         b            - Utility shift parameter
         s            - Coupon payment on existing debt
         c            - Consumption
         l            - Labor
         p            - Price
         tau          - Tax rate
         rvn          - Revenue
         B            - Govt debt
         R            - Risk free gross return
         pi           - One-period risk-free interest rate
         Pi           - Cumulative rate of return, adjusted
         xi           - Adjustment factor for Pi

        The corresponding values are flat numpy ndarrays.

    """

    # == Simplify names == #
    beta, Sg, Sd, Sb, Ss = econ.beta, econ.Sg, econ.Sd, econ.Sb, econ.Ss

    if econ.discrete:
        P, x_vals = econ.proc
    else:
        A, C = econ.proc

    # == Simulate the exogenous process x == #
    if econ.discrete:
        state = mc_tools.sample_path(P, init=0, sample_size=T)
        x = x_vals[:,state]
    else:
        # == Generate an initial condition x0 satisfying x0 = A x0 == #
        nx, nx = A.shape
        x0 = nullspace((eye(nx) - A))
        x0 = -x0 if (x0[nx-1] < 0) else x0
        x0 = x0 / x0[nx-1]

        # == Generate a time series x of length T starting from x0 == #
        nx, nw = C.shape
        x = zeros((nx, T))
        w = randn(nw, T)    
        x[:, 0] = x0.T    
        for t in range(1,T):    
            x[:, t] = dot(A, x[:, t-1]) + dot(C, w[:, t])

    # == Compute exogenous variable sequences == #
    g, d, b, s = (dot(S, x).flatten() for S in (Sg, Sd, Sb, Ss))
        
    # == Solve for Lagrange multiplier in the govt budget constraint == #
    ## In fact we solve for nu = lambda / (1 + 2*lambda).  Here nu is the 
    ## solution to a quadratic equation a(nu**2 - nu) + b = 0 where
    ## a and b are expected discounted sums of quadratic forms of the state.
    Sm = Sb - Sd - Ss    
    # == Compute a and b == #
    if econ.discrete:
        ns = P.shape[0]
        F = scipy.linalg.inv(np.identity(ns) - beta * P)
        a0 = 0.5 * dot(F, dot(Sm, x_vals).T**2)[0]
        H = dot(Sb - Sd + Sg, x_vals) * dot(Sg - Ss, x_vals)
        b0 = 0.5 * dot(F, H.T)[0]
        a0, b0 = float(a0), float(b0)
    else:
        H = dot(Sm.T, Sm)
        a0 = 0.5 * var_quadratic_sum(A, C, H, beta, x0)
        H = dot((Sb - Sd + Sg).T, (Sg + Ss))
        b0 = 0.5 * var_quadratic_sum(A, C, H, beta, x0)

    # == Test that nu has a real solution before assigning == #
    warning_msg = """
    Hint: you probably set government spending too {}.  Elect a {}
    Congress and start over.
    """
    disc = a0**2 - 4 * a0 * b0
    if disc >= 0:  
        nu = 0.5 * (a0 - sqrt(disc)) / a0
    else:
        print "There is no Ramsey equilibrium for these parameters."
        print warning_msg.format('high', 'Republican')
        sys.exit(0)

    # == Test that the Lagrange multiplier has the right sign == #
    if nu * (0.5 - nu) < 0:  
        print "Negative multiplier on the government budget constraint."
        print warning_msg.format('low', 'Democratic')
        sys.exit(0)

    # == Solve for the allocation given nu and x == #
    Sc = 0.5 * (Sb + Sd - Sg - nu * Sm)    
    Sl = 0.5 * (Sb - Sd + Sg - nu * Sm)   
    c = dot(Sc, x).flatten()
    l = dot(Sl, x).flatten()
    p = dot(Sb - Sc, x).flatten()  # Price without normalization
    tau = 1 - l / (b - c)
    rvn = l * tau  

    # == Compute remaining variables == #
    if econ.discrete:
        H = dot(Sb - Sc, x_vals) * dot(Sl - Sg, x_vals) - dot(Sl, x_vals)**2
        temp = dot(F, H.T).flatten()
        B = temp[state] / p
        H = dot(P[state, :], dot(Sb - Sc, x_vals).T).flatten()
        R = p / (beta * H)
        temp = dot(P[state,:], dot(Sb - Sc, x_vals).T).flatten()
        xi = p[1:] / temp[:T-1]
    else:
        H = dot(Sl.T, Sl) - dot((Sb - Sc).T, Sl - Sg) 
        L = np.empty(T)
        for t in range(T):
            L[t] = var_quadratic_sum(A, C, H, beta, x[:, t])
        B = L / p
        Rinv = (beta * dot(dot(Sb - Sc, A), x)).flatten() / p
        R = 1 / Rinv
        AF1 = dot(Sb - Sc, x[:, 1:])
        AF2 = dot(dot(Sb - Sc, A), x[:, :T-1])
        xi =  AF1 / AF2
        xi = xi.flatten()

    pi = B[1:] - R[:T-1] * B[:T-1] - rvn[:T-1] + g[:T-1]
    Pi = cumsum(pi * xi)

    # == Prepare return values == #
    path = Path(g=g, 
            d=d,
            b=b,
            s=s,
            c=c,
            l=l,
            p=p,
            tau=tau,
            rvn=rvn,
            B=B,
            R=R,
            pi=pi,
            Pi=Pi,
            xi=xi)

    return path
Exemplo n.º 16
0
    print

print
print '*****'
# now show a under-determined system allows more solutions
kFlips = 7
# confirm more probs would completely determine this situation
# (will be by analogy to the moment curve)
print '***** nSides =', nSides, 'kFlips =', kFlips
sU = freqSystem(nSides, kFlips)
print 'is full rank'
print rank(sU['a'].T * sU['a']) == kFlips + 1
print 'can extend to full rank'
sCheck = freqSystem(nSides, kFlips, stepMult=2)
print rank(sCheck['a'].T * sCheck['a']) == kFlips + 1
wiggleRoom = nullspace(sU['a'])
print 'confirm null vecs'
wiggleDim = wiggleRoom.shape[1]
print (wiggleRoom.shape[0]==kFlips+1) & \
   (wiggleDim + nSides-1==kFlips+1) & \
   (numpy.matrix.max(abs(sU['a'] * wiggleRoom))<1.0e-12)
baseSoln = empiricalMeansEstimates(nSides, kFlips)
print 'empirical solution'
printEsts(baseSoln)
baseLosses = losses(nSides, baseSoln)
print 'empirical solution losses'
printLosses(baseLosses)
print(sum(baseLosses))
print(max(baseLosses))