def prob_1():
	#problem 1
	#part 1
	A = np.array([[.75, .5], [.25, .5]])
	print A.dot(A)[0,0]
	#part 2
	print la.matrix_power(A, 20)[0,0]
Example #2
0
    def make_propagators(pb=0.0, kex=0.0, dw=0.0, r_hxy=5.0, dr_hxy=0.0,
                         r_cz=1.5, r_2hzcz=0.0, etaxy=0.0, etaz=0.0,
                         j_hc=0.0, cs_offset=0.0):

        w1 = 2.0 * pi / (4.0 * pw)

        l_free, l_w1x, l_w1y = compute_liouvillians(
            pb=pb,
            kex=kex,
            dw=dw,
            r_hxy=r_hxy,
            dr_hxy=dr_hxy,
            r_cz=r_cz,
            r_2hzcz=r_2hzcz,
            etaxy=etaxy,
            etaz=etaz,
            j_hc=j_hc,
            cs_offset=cs_offset,
            w1=w1
        )

        p_neg = expm(l_free * -2.0 * pw / pi)
        p_90px = expm((l_free + l_w1x) * pw)
        p_90py = expm((l_free + l_w1y) * pw)
        p_90mx = expm((l_free - l_w1x) * pw)
        p_180py = matrix_power(p_90py, 2)
        p_180pmx = 0.5 * (matrix_power(p_90px, 2) +
                          matrix_power(p_90mx, 2))

        ps = p_neg, p_90px, p_90py, p_90mx, p_180py, p_180pmx

        return l_free, ps
Example #3
0
def jointpmf2(pe, pb, n):
    # pWL(w, l) = Pr{W = w, L = l}
    #           = Pr{W = w | L = l} * Pr{L = l}
    #           = pW(w - 2; l - 2) * pL(l; n)

    T = mmbittm(pe, pb)
    Pss = mmss(T)

    pW = errpmf(pe, pb, n)

    pWL = np.zeros((n + 1, n + 1))
    pWL[0, 0] = pW[0]
    pWL[1, 1] = pW[1]

    for l in range(2, n + 1):
        Tw = mmstep(T, l - 2)
        #print('Tw =\n', Tw)
        for x in range(n - l + 1):
            y = n - l - x
            #print('0' * x + '1' + 'x' * (l - 2) + '1' + '0' * y)
            Tx = LA.matrix_power(T[0], x)
            Ty = LA.matrix_power(T[0], y)
            #Twl = Tx.dot(T[1]).dot(Tw).dot(T[1]).dot(Ty)
            #print('Tx =\n', Tx)
            #print('Ty =\n', Ty)
            #print('Twl =\n', Twl)
            #Pwl = Pss.dot(Twl).sum(axis=1)
            for w in range(2, l + 1):
                Twl = Tx.dot(T[1]).dot(Tw[w - 2]).dot(T[1]).dot(Ty)
                Pwl = Pss.dot(Twl).sum()
                #print('Twl =\n', Twl)
                #print('Pwl =\n', Pwl)
                pWL[w, l] += Pwl

    return pWL
Example #4
0
    def make_propagators(pb=0.0, pc=0.0, kex_ab=0.0, kex_bc=0.0, kex_ac=0.0,
                         dw_ab=0.0, dw_ac=0.0, r_nxy=5.0, dr_nxy_ab=0.0,
                         dr_nxy_ac=0.0, r_nz=1.5, r_2hznz=5.0, etaxy=0.0,
                         etaz=0.0, j_hn=-93.0, dj_hn_ab=0.0, dj_hn_ac=0.0,
                         cs_offset=0.0):

        w1 = 2.0 * pi / (4.0 * pw)
        l_free, l_w1x, l_w1y = compute_liouvillians(
            pb=pb, pc=pc, kex_ab=kex_ab, kex_bc=kex_bc, kex_ac=kex_ac,
            dw_ab=dw_ab, dw_ac=dw_ac, r_nxy=r_nxy, dr_nxy_ab=dr_nxy_ab,
            dr_nxy_ac=dr_nxy_ac, r_nz=r_nz, r_2hznz=r_2hznz, etaxy=etaxy,
            etaz=etaz, j_hn=j_hn, dj_hn_ab=dj_hn_ab, dj_hn_ac=dj_hn_ac,
            cs_offset=cs_offset, w1=w1,
        )

        p_equil = expm(l_free * time_equil)
        p_neg = expm(l_free * -2.0 * pw / pi)
        p_taub = expm(l_free * (taub - 2.0 * pw - 2.0 * pw / pi))
        p_90px = expm((l_free + l_w1x) * pw)
        p_90py = expm((l_free + l_w1y) * pw)
        p_90mx = expm((l_free - l_w1x) * pw)
        p_90my = expm((l_free - l_w1y) * pw)
        p_180px = matrix_power(p_90px, 2)
        p_180py = matrix_power(p_90py, 2)

        p_element = reduce(dot, [P180_S, p_taub, p_90py, p_90px, P180_S, p_90px,
                                 p_90py, p_taub])

        ps = (p_equil, p_neg, p_90px, p_90py, p_90mx, p_90my, p_180px, p_180py,
              p_element)

        return l_free, ps
Example #5
0
    def make_propagators(pb=0.0, kex=0.0, dw=0.0, r_coxy=5.0, dr_coxy=0.0,
                         r_nz=1.5, r_2coznz=0.0, etaxy=0.0, etaz=0.0,
                         j_nco=0.0, dj_nco=0.0, cs_offset=0.0):

        w1 = 2.0 * pi / (4.0 * pwco90)
        l_free, l_w1x, l_w1y = compute_liouvillians(pb=pb, kex=kex, dw=dw,
                                                    r_coxy=r_coxy, dr_coxy=dr_coxy,
                                                    r_nz=r_nz, r_2coznz=r_2coznz,
                                                    etaxy=etaxy, etaz=etaz,
                                                    j_nco=j_nco, dj_nco=dj_nco,
                                                    cs_offset=cs_offset, w1=w1)

        p_equil = expm(l_free * time_equil)
        p_taucc = expm(l_free * taucc)
        p_neg = expm(l_free * -2.0 * pwco90 / pi)
        p_90py = expm((l_free + l_w1y) * pwco90)
        p_90my = expm((l_free - l_w1y) * pwco90)
        p_180px = P180X  # Perfect 180 for CPMG blocks
        p_180py = matrix_power(p_90py, 2)
        p_180my = matrix_power(p_90py, 2)

        ps = (p_equil, p_taucc, p_neg, p_90py, p_90my,
              p_180px, p_180py, p_180my)

        return l_free, ps
Example #6
0
 def test_regress_mutation_probability_endpoint_conditioning(self):
     ngenerations = 10
     selection = 2.0
     mutation = 0.0001
     recombination = 0.001
     nchromosomes = 2
     npositions = 4
     K_initial = np.array([
         [1,1,1,1],
         [0,0,0,0]], dtype=np.int8)
     K_final = np.array([
         [1,1,0,0],
         [0,0,1,1]], dtype=np.int8)
     #
     ngenboundaries = ngenerations - 1
     no_mutation_prior = (1 - mutation)**(
             npositions*ngenboundaries*nchromosomes)
     #
     initial_long = popgenmarkov.bin2d_to_int(K_initial)
     final_long = popgenmarkov.bin2d_to_int(K_final)
     ci_to_short, short_to_count, sorted_chrom_lists = get_state_space_info(
             nchromosomes, npositions)
     initial_ci = chroms_to_index(
             sorted(popgenmarkov.bin_to_int(row) for row in K_initial),
             npositions)
     initial_short = ci_to_short[initial_ci]
     final_ci = chroms_to_index(
             sorted(popgenmarkov.bin_to_int(row) for row in K_final),
             npositions)
     final_short = ci_to_short[final_ci]
     # get an answer using the less efficient methods
     P_sr = popgenmarkov.get_selection_recombination_transition_matrix(
             selection, recombination, nchromosomes, npositions)
     P_m = popgenmarkov.get_mutation_transition_matrix(
             mutation, nchromosomes, npositions)
     p_b_given_a = linalg.matrix_power(np.dot(P_sr, P_m), ngenerations-1)[
             initial_long, final_long]
     p_b_given_a_no_mutation = linalg.matrix_power(P_sr, ngenerations-1)[
             initial_long, final_long]
     no_mutation_posterior = (
             no_mutation_prior * p_b_given_a_no_mutation) / p_b_given_a
     # get an answer using the more efficient methods
     P_sr_s = get_selection_recombination_transition_matrix_s(
             ci_to_short, short_to_count, sorted_chrom_lists,
             selection, recombination, nchromosomes, npositions)
     P_m_s = get_mutation_transition_matrix_s(
             ci_to_short, short_to_count, sorted_chrom_lists,
             mutation, nchromosomes, npositions)
     p_b_given_a_s = linalg.matrix_power(
             np.dot(P_sr_s, P_m_s), ngenerations-1)[
                     initial_short, final_short]
     p_b_given_a_no_mutation_s = linalg.matrix_power(
             P_sr_s, ngenerations-1)[
                     initial_short, final_short]
     no_mutation_posterior_s = (
             no_mutation_prior * p_b_given_a_no_mutation_s) / p_b_given_a_s
     #
     self.assertTrue(
             np.allclose(no_mutation_posterior, no_mutation_posterior_s))
Example #7
0
 def test_matrix_power_operator(self):
     random.seed(1234)
     n = 5
     k = 2
     p = 3
     nsamples = 10
     for i in range(nsamples):
         A = np.random.randn(n, n)
         B = np.random.randn(n, k)
         op = MatrixPowerOperator(A, p)
         assert_allclose(op.matmat(B), matrix_power(A, p).dot(B))
         assert_allclose(op.T.matmat(B), matrix_power(A, p).T.dot(B))
Example #8
0
    def __call__(self, options, pars):
        """Evaluate the model for a given set of parameters."""
        self.max_T = int(pars.get('max_T', 100))    # range of sample sizes
        T = np.arange(1., self.max_T + 1)
        N = map(int, np.floor(T))
        self.set_statespace(pars)                   # threshold and state space

        # which option is sampled first? [0, 1, None]
        firstoption = pars.get('firstoption', None)

        # evaluate the starting distribution
        Z = self.Z(self.m, {'theta': self.theta + 1, 'tau': pars.get('tau', .5)})

        # repeat Z for both options, and re-normalize
        if firstoption is None:
            Z = np.concatenate((Z, Z), axis=1)
        elif firstoption is 0:
            Z = np.concatenate((Z, np.matrix(np.zeros(self.m - 2))), axis=1)
        elif firstoption is 1:
            Z = np.concatenate((np.matrix(np.zeros(self.m - 2)), Z), axis=1)
        Z = Z / float(np.sum(Z))


        # transition matrix
        tm = self.transition_matrix_reflecting(options, pars)

        # min-steps
        if 'minsamplesize' in pars:
            min_ss = pars.get('minsamplesize')
            if min_ss == 2:
                Z = Z * tm
            else:
                Z = Z * matrix_power(tm, min_ss - 1)
            assert np.isclose(Z.sum(), 1.)

        # evaluate evolution in states
        M = [Z * matrix_power(tm, 0)]
        for n in N[1:]:
            M.append( np.dot(M[-1], tm) )
        p_state_t = np.array(M).reshape((len(N), self.m * 2))

        p_0 = p_state_t[:,self.theta] + p_state_t[:,self.m + self.theta]
        p_L = p_state_t[:,:self.theta].sum(axis=1) + p_state_t[:,self.m:(self.m+self.theta)].sum(axis=1) + p_0 * 0.5
        p_H = p_state_t[:,(1+self.theta):self.m].sum(axis=1) + p_state_t[:,(self.m+self.theta+1):].sum(axis=1) + p_0 * 0.5
        p_LH = np.transpose((p_L, p_H))

        assert np.isclose(p_LH.sum(), p_LH.shape[0])

        return {'T': T,
                'states_t': p_state_t,
                'p_resp_t': p_LH}
def DiagonalNewton(d0,d1,Q,tolerance):

    if tolerance <= 0:
            print "tolerance <= 0, algorithm won't terminate"
            return None

    #verify if Q is positive semidefinite, correct dimensions
    try:
        y = linalg.cholesky(Q)
    except linalg.LinAlgError:
        print "Matrix is either not positive semidefinite, or nonsquare"
        return None

    e = np.ones(d1.size)
    w = linalg.norm(d1 -d0)
    D = np.diag(d1)
    w = linalg.norm(np.dot(np.dot(np.dot(D,Q),D),e)-e)
    iterationcounter = 0
    while(w > tolerance):
        d0 = d1
        D = np.diag(d1)


        try:
       
            y = np.dot(linalg.matrix_power((linalg.matrix_power(D,-2)+Q),-1), np.diag( linalg.matrix_power(D,-1 ))-np.dot(Q,d1))

        except:

            return None
      
          
       # print  np.dot(np.dot(np.transpose(y) ,linalg.matrix_power(D,-2)),y)
        
        lamb = np.dot(
                    np.dot(np.transpose(y) ,linalg.matrix_power(D,-2)),
                            y) + np.dot(np.dot(np.transpose(y),Q),y) #computing lambda
        #lamb < 1, a = 1 lamb >=1 1, a = 1/2
        
        #print lamb
        if lamb > 1:
            d1 = d0 + float(1)/(1 + lamb**(0.5))*y

        else:
            d1 = d0 + y
        w = linalg.norm(np.dot(np.dot(np.dot(D,Q),D),e)-e)

        iterationcounter += 1

    return (w, d1,iterationcounter)
Example #10
0
def randmatstat(t):
    n = 5
    v = zeros(t)
    w = zeros(t)
    for i in range(t):
        a = randn(n, n)
        b = randn(n, n)
        c = randn(n, n)
        d = randn(n, n)
        P = concatenate((a, b, c, d), axis=1)
        Q = concatenate((concatenate((a, b), axis=1), concatenate((c, d), axis=1)), axis=0)
        v[i] = trace(matrix_power(dot(P.T,P), 4))
        w[i] = trace(matrix_power(dot(Q.T,Q), 4))
    return (std(v)/mean(v), std(w)/mean(w))
def directed_weighted_clustering(g,weightString):
	
	
	n = g.number_of_nodes()
	from numpy import linalg as LA
	#adjacency matrix
	A = nx.to_numpy_matrix(g,nodelist=g.nodes(),weight=None)
	A2 = LA.matrix_power(A,2)
	AT = A.T
	Asum = AT + A
	cVector = [i for i in range(n)]
	cVector = np.asmatrix(cVector)
	
	kin = {i:np.dot(AT[i],cVector.T) for i in range(n)}
	kout = {i:np.dot(A[i],cVector.T)for i in range(n)}
	kparallel = {i:np.dot(Asum[i],cVector.T)for i in range(n)}

	#print "kin"
	#print kin
	#weight matrix
	W = nx.to_numpy_matrix(g,nodelist=g.nodes(),weight=weightString)
	WT = W.T
	W2 = LA.matrix_power(W,2)
	W3 = LA.matrix_power(W,3)
			
	WWTW =  W*WT*W
	WTW2 = WT*W2
	W2WT = W2*WT
	
	ccycle = {i:0 for i in range(n)}
	cmiddle = {i:0 for i in range(n)}
	cin = {i:0 for i in range(n)}
	cout = {i:0 for i in range(n)}

	for i in range(n):
			
			if kin[i]*kout[i]  - kparallel[i] > 0:
				ccycle[i] = W3[i,i] / float((kin[i]*kout[i] - kparallel[i]))
				cmiddle[i] = WWTW[i,i] / float((kin[i]*kout[i] - kparallel[i]))
			if kin[i] > 1: 
				cin[i] = WTW2[i,i] / float((kin[i]*(kin[i]-1)))
			if kout[i] > 1: 
				cout[i] = W2WT[i,i] / float((kout[i]*(kout[i]-1))) 
	#print type((np.mean(ccycle.values()),np.mean(cmiddle.values()),np.mean(cin.values()),np.mean(cout.values())))
	#print "here"
	#input()
	#return (np.mean(ccycle.values()),np.mean(cmiddle.values()),np.mean(cin.values()),np.mean(cout.values()))
	return (ccycle,cmiddle,cin,cout)
Example #12
0
        def _calc_observable(pb=0.0, kex=0.0, dwh=0.0, dwc=0.0, r_2hxycxy=5.0, dr_2hxycxy=0.0, ncyc=0):
            """
            Calculate the intensity in presence of exchange during a cpmg-type pulse
            train. Based on the sequence "hmqc_CH3_exchange_bigprotein_600_lek_v2.c".
            Parameter names from the sequence are:

            chemex      procpar
            ------      -------
            time_T2     time_T2
            ncyc        ncyc_cp

            Parameters
            ----------
            i0 : float
                Initial intensity
            pb : float
                Fractional population of state b
            kex : float
                Exchange rate between state a and b in /s
            dwh : float
                Proton chemical shift difference between states A and B in ppm
            dwc : float
                Carbon chemical shift difference between states A and B in ppm
            r_2hxycxy : float
                Multiple quantum relaxation rate in /s
            dr_2hxycxy : float
                Multiple quantum relaxation rate difference between a and b in /s
            smallflg: string ['y', 'n']
               Flag to include small_protein_flg block in fitting

            Returns
            -------
            out : float
                Intensity after the CPMG block

            """

            dwh *= ppm_to_rads_h
            dwc *= ppm_to_rads_c

            l_free = make_propagators(
                pb=pb, kex=kex, dwh=dwh, dwc=dwc, r_2hxycxy=r_2hxycxy, dr_2hxycxy=dr_2hxycxy,
            )

            mag_eq = compute_2hxcy_eq(pb)

            if ncyc == 0:
                mag = mag_eq

            else:

                t_cp = time_t2 / (4.0 * ncyc)
                p_free = expm(l_free * t_cp)
                p_cpy = matrix_power(p_free.dot(P180_CY).dot(p_free), ncyc)

                mag = reduce(dot, [p_cpy, P180_HX, p_cpy, mag_eq])

            magz_a, _ = get_2hxcy(mag)

            return magz_a
def build_rand_sparse_diag_mat_and_multiply():
    array = diags(random.random_sample(25).tolist(), 0).toarray()
    #print array
    heat_map_data1 = [go.Heatmap(z=np.flipud(array).tolist())]
    heat_map_data2 = [go.Heatmap(z=np.flipud((LA.matrix_power(array, 2))).tolist())] #multiply with itself.
    plot_url = plotly.offline.plot(heat_map_data1, filename='basic-heatmap1.html')
    plot_url = plotly.offline.plot(heat_map_data2, filename='basic-heatmap2.html')
Example #14
0
def simulate_evolution(dna_sequence, alpha, time, dt, threads=1):
    tree = Tree([PhylogeneticNode(dna_sequence)], [])
    transition_matrix = build_transition_matrix(alpha)
    power_matrix = LA.matrix_power(transition_matrix, dt)

    while time > 0:
        i = 0
        fixed_length = len(tree.get_nodes())
        node_list = tree.get_nodes()
        if fixed_length > 10:
            return tree

        while i < fixed_length:
            node = node_list[i]
            origin_sequence = node.get_sequence()
            wrapper = list(origin_sequence)
            next_node = mutate_module(power_matrix, wrapper, threads=threads)

            if next_node != -1:
                tree.add_node(next_node)
                tree.add_edge(node, next_node)

            gc.collect()
            i += 1
        time -= dt
        print time

    return tree
    def calc_normal(self, data, power):
        """ The normal way to do the calculation """

        # Extract shapes from data.
        NE, NS, NM, NO, ND, Row, Col = data.shape

        # Make array to store results
        calc = zeros([NE, NS, NM, NO, ND, Row, Col])

        # Normal way, by loop of loops.
        for ei in range(NE):
            for si in range(NS):
                for mi in range(NM):
                    for oi in range(NO):
                        for di in range(ND):
                            # Get the outer square data matrix,
                            data_i = data[ei, si, mi, oi, di]

                            # Get the power.
                            power_i = power[ei, si, mi, oi, di]

                            # Do power calculation with numpy method.
                            data_power_i = matrix_power(data_i, power_i)

                            # Store result.
                            calc[ei, si, mi, oi, di] = data_power_i

        return calc
    def calc_strided(self, data, power):
        """ The strided way to do the calculation """

        # Extract shapes from data.
        NE, NS, NM, NO, ND, Row, Col = data.shape

        # Make array to store results
        calc = zeros([NE, NS, NM, NO, ND, Row, Col])

        # Get the data view, from the helper function.
        data_view = self.stride_help_square_matrix(data)

        # Get the power view, from the helpwer function.
        power_view = self.stride_help_element(power)

        # The index view could be pre formed in init.
        index = self.index
        index_view = self.stride_help_array(index)

        # Zip them together and iterate over them.
        for data_i, power_i, index_i in zip(data_view, power_view, index_view):
            # Do power calculation with numpy method.
            data_power_i = matrix_power(data_i, int(power_i))

            # Extract index from index_view.
            ei, si, mi, oi, di = index_i

            # Store the result.
            calc[ei, si, mi, oi, di] = data_power_i

        return calc
Example #17
0
def basis(H, v):

	basisset=[]
	for l in range(M):
		basisset.extend(np.dot(LA.matrix_power(H,l),v))
	basisset=np.reshape(basisset,(M,2*N))
	return (basisset)
def power_method(file_name, error_tol, u0):

    # Creates a matrix from the .dat file
    A = np.genfromtxt(file_name, delimiter=" ")

    m = int(A.shape[0]) #rows of A

    u = np.asarray(np.asmatrix(u0))
    uRows = int(u.shape[0]) #rows of u
    uCols = int(u.shape[1]) #columns of u

    # Sets the tolerance
    tol = error_tol

    # Sets the initial number of iterations
    iteration = 0

    # Sets an array with one entry 0 to use for the error in the while loop
    eigenvalues = [0]

    # While number of iterations is less than 100, the matrix
    # A is raised to a power equal to the iteration and multiplied
    # by the original u0 that was given as an input. The dominant
    # eigenvector is found and from that, the dominant eigenvalue
    # is found.
    while iteration < 100:
        copyA = LA.matrix_power(A, iteration+1)
        x = np.zeros(shape=(m, uCols))
        for i in range(m):
            for j in range(uCols):
                for k in range(uRows):
                    x[i][j] += (copyA[i][k] * u[k][j]) #Multiplies matrix A and u
        eigenvector = x / LA.norm(x) # Finds the dominant eigenvector
        eigenRows = int(eigenvector.shape[0]) #rows of dominant eigenvector
        eigenCols = int(eigenvector.shape[1]) #columns of eigenvector

        Ax = np.zeros(shape = (m, eigenCols))

        for i in range(m):
            for j in range(eigenCols):
                for k in range(eigenRows):
                    Ax[i][j] += A[i][k] * eigenvector[k][j]
        Axx = np.vdot(Ax, eigenvector)
        xx = np.vdot(eigenvector, eigenvector)
        eigenvalue = Axx / xx # Finds the dominant eigenvalue

        eigenvalues.append(eigenvalue)

        if (np.absolute(eigenvalues[iteration+1] - eigenvalues[iteration])) <= tol:
            break

        iteration += 1

    print "Dominant eigenvalue = ", eigenvalue
    print "Dominant eigenvector =\n", eigenvector

    if iteration >= 100:
        print "Did not converge after 100 iterations."
    else:
        print "Took " + str(iteration) + " iterations to converge."
Example #19
0
 def spectralAnalysis(self):
     # Assumes adjacency matrix is already made
     for i in range(2,self.numNodes+1):
         m = linalg.matrix_power(self.adjMatrix,i)/i
     print "Spectral analysis, k= " + str(i) + ":\n" + str(m)
     print ""
     return m.diagonal()
def prob_3:
	#problem 3
	A = np.array([[0, 0, 1, 0, 1, 0, 1],
				  [1, 0, 0, 0, 0, 1, 0],
				  [0, 0, 0, 0, 0, 1, 0],
				  [1, 0, 0, 0, 1, 0, 0],
				  [0, 0, 0, 1, 0, 0, 0],
				  [0, 0, 1, 0, 0, 0, 1],
				  [0, 1, 0, 0, 0, 0, 0]], dtype=np.int64)
	A5 = la.matrix_power(A,5)
	coords = np.where(A5==np.max(A5))
	#note: indexing from 0
	print "maximum of 5 step connections at: ", zip(coords[0], coords[1])
	A7 = la.matrix_power(A,7)
	coords = np.where(A7==0)
	print "no 7 step connection for: ", zip(coords[0], coords[1])
Example #21
0
def pam_matrix(d, scale=float(np.log(2)/2), as_ints=False):
	"""Creates PAM scoring matrix.

	Values calculated from (natural) log-odds ratio of PAM{d}:PAM{inf}. The
	output will be this matrix *divided* by the scale parameter (this seems
	to be the convention, but I am not sure why).

	Args:
		d: int. Mutation distance (number of time steps in the Markov chain
			model).
		scale: float. Units of returned matrix, relative to "natural" units
			of the log-odds ration. Returned matrix will be the log-odds
			values *divided* by the scale. Defaults to ln(2)/2 (half-bit
			units), because that's what I've seen everywhere.
		as_ints: bool. If true, entries will be rounded to the nearest integer.
	"""
	# Calculate matrix
	dayhoff_n = matrix_power(dayhoff_matrix, d)
	matrix = np.log(dayhoff_n / dayhoff_stationary[:, None]) / scale

	# Doesn't seem to be completely symmetrical, hopefully just due to
	# floating-point errors. Fudge it a bit.
	matrix += matrix.transpose()
	matrix *= .5

	# Round if requested
	if as_ints:
		matrix = np.round(matrix)

	return SubstitutionMatrix(aa_symbols, matrix.astype(np.float32))
Example #22
0
    def _calc_observable(pb=0.0, kex=0.0, dw=0.0, r_ixy=5.0, dr_ixy=0.0,
                         ncyc=0):
        """
        Calculate the intensity in presence of exchange during a cpmg-type pulse
        train.

        Parameters
        ----------
        i0 : float
            Initial intensity.
        pb : float
            Fractional population of state B,
            0.0 for 0%, 1.0 for 100%
        kex : float
            Exchange rate between state A and B in /s.
        dw : float
            Chemical shift difference between states A and B in rad/s.
        r_ixy : float
            Transverse relaxation rate of state a in /s.
        dr_ixy : float
            Transverse relaxation rate difference between states a and b in /s.

        Returns
        -------
        out : float
            Intensity after the CPMG block

        """

        dw *= ppm_to_rads

        mag_eq = compute_iy_eq(pb)

        if ncyc == 0:

            mag = mag_eq

        else:

            l_free = compute_liouvillians(
                pb=pb,
                kex=kex,
                dw=dw,
                r_ixy=r_ixy,
                dr_ixy=dr_ixy
            )

            t_cp = time_t2 / (4.0 * ncyc)
            p_free = expm(l_free * t_cp)

            mag = matrix_power(
                p_free
                .dot(P_180Y)
                .dot(p_free),
                2 * ncyc
            ).dot(mag_eq)

        magy_a, _ = get_iy(mag)

        return magy_a
Example #23
0
    def _calculate_unscaled_profile(self, params_local, **kwargs):
        """TODO: class docstring."""

        self.liouv.update(params_local)

        # Calculation of the propagators corresponding to all the delays
        delays = dict(zip(self.delays, self.liouv.delays(self.delays)))
        d_zeta = delays[self.t_zeta]

        # Calculation of the propagators corresponding to all the pulses
        p180_sx = self.liouv.perfect180["sx"]
        p180_ix = self.liouv.perfect180["ix"]
        p180_iy = self.liouv.perfect180["iy"]

        # Calculate starting magnetization vector
        mag0 = self.liouv.compute_mag_eq(params_local, term="2iysx")

        if self.small_protein:
            mag0 = d_zeta @ p180_sx @ p180_ix @ d_zeta @ mag0

        # Calculating the cpmg trains
        cp = {0: self.liouv.identity}

        for ncyc in set(self.data["ncycs"][~self.reference]):
            tau_cp = delays[self.tau_cps[ncyc]]
            echo = tau_cp @ p180_iy @ tau_cp
            cp_train = la.matrix_power(echo, int(ncyc))
            cp[ncyc] = cp_train @ p180_sx @ cp_train

        profile = [
            self.liouv.collapse(self.detect @ cp[ncyc] @ mag0)
            for ncyc in self.data["ncycs"]
        ]

        return np.asarray(profile)
Example #24
0
 def apply_to_char(self, char):
     assert char in ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
     char_map = {'A':0, 'R':1, 'N':2, 'D':3, 'C':4, 'Q':5, 'E':6, 'G':7, 'H':8, 'I':9, 'L':10, 'K':11, 'M':12, 'F':13, 'P':14, 'S':15, 'T':16, 'W':17, 'Y':18, 'V':19}
     base_vector = [.074, .042, .044, .059, .033, .058, .037, .074, .029, .038, .076, .072, .018, .04, .05, .081, .062, .013, .033, .068] #observed frequencies in vertebrates
     power_matrix = LA.matrix_power(self.transition_matrix, self.time)
     transformation_vector = power_matrix[index]
     new_char = np.random.choice(char_map.keys(), p=transformation_vector)
     return new_char
def rand_mat_stat(t):
    n = 5
    v = np.empty(t)
    w = np.empty(t)
    for i in range(t):
        a = randn(n, n)
        b = randn(n, n)
        c = randn(n, n)
        d = randn(n, n)
        P = concatenate((a, b, c, d), axis=1)
        Q = concatenate((concatenate((a, b), axis=1),
                         concatenate((c, d), axis=1)), axis=0)
#        v[i] = trace(matrix_power(P.T @ P, 4))
#        w[i] = trace(matrix_power(Q.T @ Q, 4))
        v[i] = trace(matrix_power(dot(P.T, P), 4))
        w[i] = trace(matrix_power(dot(Q.T, Q), 4))
    return np.std(v)/np.mean(v), np.std(w)/np.mean(w)
Example #26
0
def approximate_stationary(N, d, iterations=None, power_multiple=15):
    """Approximate the stationary distribution by computing a large power of 
the transition matrix, using successive squaring."""
    power = int((log(N) + power_multiple) / log(2))
    # Use successive squaring to a large power
    m = matrix_power(d, 2**power)
    # Each row is the stationary distribution
    return m[0]
Example #27
0
    def _calc_observable(pb=0.0, kex=0.0, dw=0.0, r_cxy=5.0, dr_cxy=0.0, r_cz=1.5, cs=0.0, ncyc=0):
        """
        Calculate the intensity in presence of exchange during a cpmg-type pulse train.
                _______________________________________________________________________
        1H :   |  /   /   /   /   /   /   /   /   CW   /   /   /   /   /   /   /   /   |
        15N:    Nx { tauc  2Ny  tauc }*ncyc 2Nx { tauc  2Ny  tauc }*ncyc -Nx time_equil

        Parameters
        ----------
        i0 : float
            Initial intensity.
        pb : float
            Fractional population of state B,
            0.0 for 0%, 1.0 for 100%
        kex : float
            Exchange rate between state A and B in /s.
        dw : float
            Chemical shift difference between states A and B in rad/s.
        r_cz : float
            Longitudinal relaxation rate of state {a,b} in /s.
        r_cxy : float
            Transverse relaxation rate of state a in /s.
        dr_cxy : float
            Transverse relaxation rate difference between states a and b in /s.
        cs_offset : float
            Offset from the carrier in rad/s.
        Returns
        -------
        out : float
            Intensity after the CPMG block

        """

        dw *= ppm_to_rads
        cs_offset = (cs - carrier) * ppm_to_rads

        l_free, ps = make_propagators(pb=pb, kex=kex, dw=dw, r_cxy=r_cxy, dr_cxy=dr_cxy, r_cz=r_cz, cs_offset=cs_offset)

        p_equil, p_neg, p_90px, p_90mx, p_180pmx, p_180py = ps

        mag_eq = compute_cz_eq(pb)

        if ncyc == 0:
            # The +/- phase cycling of the first 90 and the receiver is taken care
            # by setting the thermal equilibrium to 0
            mag = reduce(dot, [p_equil, p_90px, p_180pmx, p_90px, mag_eq])

        else:

            t_cp = time_t2 / (4.0 * ncyc) - pw
            p_free = expm(l_free * t_cp)
            p_cp = matrix_power(p_free.dot(p_180py).dot(p_free), ncyc)

            mag = reduce(dot, [p_equil, p_90px, p_neg, p_cp, p_180pmx, p_cp, p_neg, p_90px, mag_eq])

        magz_a, _ = get_cz(mag)

        return magz_a
Example #28
0
def LagkJointMomentsFromMRAP (H, K=0, L=1):
    """
    Returns the lag-L joint moments of a marked rational 
    arrival process.
    
    Parameters
    ----------
    H : list/cell of matrices of shape(M,M), length(N)
        The H0...HN matrices of the MRAP to check
    K : int, optional
        The dimension of the matrix of joint moments to 
        compute. If K=0, the MxM joint moments will be 
        computed. The default value is 0
    L : int, optional
        The lag at which the joint moments are computed.
        The default value is 1
    prec : double, optional
        Numerical precision to check if the input is valid. 
        The default value is 1e-14
    
    Returns
    -------
    Nm : list/cell of matrices of shape(K+1,K+1), length(N)
        The matrices containing the lag-L joint moments,
        starting from moment 0.
    """

    if butools.checkInput and not CheckMRAPRepresentation (H):
        raise Exception("LagkJointMomentsFromMRAP: Input is not a valid MRAP representation!")    

    if K==0:
        K = H[0].shape[0]-1
    M = len(H)-1
    H0 = H[0]
    sumH = ml.zeros(H[0].shape)
    for i in range(M):
        sumH += H[i+1]

    H0i = la.inv(-H0)
    P = H0i*sumH
    pi = DRPSolve(P)
    
    Pw = ml.eye(H0.shape[0])
    H0p = [ml.matrix(Pw)]
    for i in range(1,K+1):
        Pw *= i*H0i
        H0p.append(ml.matrix(Pw))

    Pl = la.matrix_power (P, L-1)

    Nm = []
    for m in range(M):
        Nmm = ml.zeros ((K+1,K+1))
        for i in range(K+1):
            for j in range(K+1):
                Nmm[i,j] = np.sum (pi * H0p[i] * H0i * H[m+1] * Pl * H0p[j])
        Nm.append(ml.matrix(Nmm))
    return Nm
    def converge(self, tol=1e-12, maxiter = 100):
        '''
        :return: converged transition matrix

        uses the method of exponentiation by squaring
        '''

        u = la.matrix_power(self.transition_matrix, 2**20)
        u[u<1e-6] = 0
        return u
def cycle_mobility(g):
	
	from numpy import linalg as LA
	
	A = nx.to_numpy_matrix(g)
	A2 = LA.matrix_power(A,2)
	A3 = LA.matrix_power(A,3)
	
	
	Ap = A
	for i in range(g.number_of_nodes()):
		for j in range(g.number_of_nodes()):
			Ap[i,j] = 0
			Ap[i,j] = A[i,j]*A[j,i]
	
	Ap3 = LA.matrix_power(Ap,3)	
	cycleMobility = 0.5*A3.trace() - np.trace(Ap*A2) + np.trace(Ap*Ap*A2) - 0.33333333333 *np.trace(Ap3)
	
	return float(cycleMobility)
Example #31
0
C = np.array([[-4, 1], [6, 5]])
D = np.array([[-6, 3, 1], [8, 9, -2], [6, -1, 5]])
print('a')
print((A @ B).T)
print('b')
print((B @ C).T)
print('c')
print(C - C.T)
print('d')
print(D - D.T)
print('e')
print(D.T.T)
print('f')
print((2 * C).T)
print('g')
print(A.T + B)
print('h')
print(A + B.T)
print('i')
print((A.T + B).T)
print('j')
print((2 * A.T - 5 * B).T)
print('k')
print((-D).T)
print('l')
print(-D.T)
print('m')
print(matrix_power(C, 2).T)
print('n')
print(matrix_power(C.T, 2))
Example #32
0
def get_Avg_system(R, u10, u11):
    p1 = np.array([u10, u11])
    total_avg = 0
    for ind in range(1, 500):
        total_avg += ind * np.sum(np.dot(p1, matrix_power(R, ind - 1)))
    return total_avg
Example #33
0
import numpy as np
from numpy.linalg import matrix_power
import matrix_power
P=np.matrix([[0.25, 0.40],[0.75, 0.60]])
print(P)
N=np.matrix([[50],[50]])
print(N)
N=P*N
print(N)
P10=matrix_power(P,10)
N=P10*N
print(N)
N=P10*N
print(N)
Example #34
0
 def eigen(self):
     powmatrix = LA.matrix_power(self.adjMatrix, 1)
     powmatrix = np.transpose(powmatrix)
     eigenval, eigenvec = LA.eig(powmatrix)
     return eigenval, eigenvec
Example #35
0
#indices = np.array([20,70,90]) * nx//100

numindices = len(indices)

Khatlarge = np.zeros((numindices*nt,nx))
yinlarge = np.zeros(numindices*nt)

for numid in range(numindices):
    print('Processing timeseries %i ' % (numid+1))
    i = indices[numid]
    yinlarge[numid*nt:(numid+1)*nt] = m1.results[:,i]
    
    K = np.zeros((nt,2*nx))
    for ni in range(nt):
        #print(ni)
        K[ni] = matrix_power(F,ni)[i]

    Khat = K[:,100:]
    
    Khatlarge[numid*nt:(numid+1)*nt,:] = Khat

# add additive and multiplicative noise
yinlarge = yinlarge * (1 + noisemult * np.random.uniform(low=-1,high=1,size=len(yinlarge))) + noiseadd * np.random.uniform(low=-1,high=1,size=len(yinlarge))
# Compute best estimate
xa = np.zeros(nx) # all zeros, no prior knowledge

#Sa = np.diag(sigmaxa*np.ones(2*nx))
Sa = np.diag(sigmaxa*np.ones(nx))
Se = np.diag(sigmaxe*np.ones(nt*numindices))

print('Computing best estimate')
Example #36
0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0
], [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0
], [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0
], [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0
])

sum1 = sum
for x in range(1, 31):
    current = (LA.matrix_power(graph1, x))
    sum1 = current + sum1

output = np.count_nonzero(sum1)
if (output == 900):  # If there's 900 nonzero elements, graph is connected.
    print('Graph 1 is connected.')
else:
    print('Graph 1 is disconnected')

graph2 = ([
    0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
    1, 0, 1, 0, 1
], [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 0, 0
], [
Example #37
0
def laplacian(A):
    S = np.sum(A, 0)
    D = np.diag(S)
    D = LA.matrix_power(D, -1)
    L = np.dot(D, A)
    return L
Example #38
0
def mat_rot(angle):
    nb = angle // 90
    ang = np.radians(90)
    r = np.array(( (int(np.cos(ang)), int(-np.sin(ang))),
                   (int(np.sin(ang)),  int(np.cos(ang))) ))
    return alg.matrix_power(r,nb).astype(int)
Example #39
0
                           (x[1] * np.cos(t) + y[1] * np.sin(t))**2)
            z1 = self.head[0] + (1 / phi**2) * (x[0] * np.cos(t) +
                                                y[0] * np.sin(t)) / norm
            z2 = self.head[1] + (1 / phi**2) * (x[1] * np.cos(t) +
                                                y[1] * np.sin(t)) / norm
            plt.plot(z1, z2, color='tab:orange', linestyle='-', alpha=0.6)


ace = [
    Kite(orient=15).translate(e2),
    Kite(orient=11).translate(e2),
    Dart(orient=3).translate(-(1 / phi) * e2)
]

deuce = [
    Kite(orient=19).translate(matrix_power(m, 11) @ e1),
    Kite(orient=7).translate(matrix_power(m, 19) @ e1),
    Dart(orient=11).translate(e2),
    Dart(orient=15).translate(e2)
]

sun = [
    Kite(orient=3),
    Kite(orient=7),
    Kite(orient=11),
    Kite(orient=15),
    Kite(orient=19)
]

star = [
    Dart(orient=3),
Example #40
0
    if len(edge) == 4:
        if edge[3][:-1] == "1":
            A1[edge[0], edge[1]] += 1
        elif edge[3][:-1] == "0":
            A0[edge[0], edge[1]] += 1

# to improve this I'd like to read the final states

A = A0 + A1

numstr = np.int64(2**n2)

prod = np.zeros((n**2,n**2), dtype=np.int64)

for j in range(n2):
    prod += np.kron(LA.matrix_power(np.transpose(A), n2-(j+1)),LA.matrix_power(A, j))

G0 = np.zeros((n,n), dtype=np.int64)

for k in range(n):
    for l in range(n):
        G0 += prod[k*n:(k+1)*n,l*n:(l+1)*n]*A0[k,l]

num0s = G0.dot(np.ones((n,1)))

G1 = np.zeros((n,n), dtype=np.int64)

for k in range(n):
    for l in range(n):
        G1 += prod[k*n:(k+1)*n,l*n:(l+1)*n]*A1[k,l]
def markovCalculate(singles, doubles, triples, hr, walks, hbp, plateAppearences):
   pSingle = singles/float(plateAppearences) if singles else 0
   pDouble = doubles/float(plateAppearences) if doubles else 0
   pTriple = triples/float(plateAppearences) if triples else 0
   pHR = hr/float(plateAppearences) if hr else 0
   pOut = 1 - ((singles+doubles+triples+hr + walks)/float(plateAppearences)) if singles+doubles+triples+hr+walks else 0
   pWalk = (walks + hbp)/float(plateAppearences) if walks+hbp else 0
   pWalkSingle = (walks+singles+hbp)/float(plateAppearences) if walks+singles+hbp else 0

   #print("Stats", pSingle, pDouble, pTriple, pHR, pWalkSingle, pOut, pWalk, (pSingle + pDouble + pTriple + pHR + pWalkSingle + pOut + pWalk))


   transition = numpy.matrix([
                              [pHR,pWalkSingle,pDouble,pTriple,0,0,0,0,pOut,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                              [pHR,0,0,pTriple,pWalkSingle,0,pDouble,0,0,pOut,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                              [pHR,pSingle,pDouble,pTriple,pWalk,0,0,0,0,0,pOut,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
                              [pHR,pSingle,pDouble,pTriple,0,pWalk,0,0,0,0,0,pOut,0,0,0,0,0,0,0,0,0,0,0,0,0],
                              [pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,0,0,0,0,pOut,0,0,0,0,0,0,0,0,0,0,0,0],
                              [pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,0,0,0,0,0,pOut,0,0,0,0,0,0,0,0,0,0,0],
                              [pHR,pSingle,pDouble,pTriple,0,0,0,pWalk,0,0,0,0,0,0,pOut,0,0,0,0,0,0,0,0,0,0],
                              [pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,0,0,0,0,0,0,0,pOut,0,0,0,0,0,0,0,0,0],
                              [0,0,0,0,0,0,0,0,pHR,pWalkSingle,pDouble,pTriple,0,0,0,0,pOut,0,0,0,0,0,0,0,0],
                              [0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pWalkSingle,0,pDouble,0,0,pOut,0,0,0,0,0,0,0],
                              [0,0,0,0,0,0,0,0,pHR,pSingle,pDouble,pTriple,pWalk,0,0,0,0,0,pOut,0,0,0,0,0,0],
                              [0,0,0,0,0,0,0,0,pHR,pSingle,pDouble,pTriple,0,pWalk,0,0,0,0,0,pOut,0,0,0,0,0],
                              [0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,0,0,0,0,pOut,0,0,0,0],
                              [0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,0,0,0,0,0,pOut,0,0,0],
                              [0,0,0,0,0,0,0,0,pHR,pSingle,pDouble,pTriple,0,0,0,pWalk,0,0,0,0,0,0,pOut,0,0],
                              [0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,0,0,0,0,0,0,0,pOut,0],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,pWalkSingle,pDouble,pTriple,0,0,0,0,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pWalkSingle,0,pDouble,0,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,pSingle,pDouble,pTriple,pWalk,0,0,0,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,pSingle,pDouble,pTriple,0,pWalk,0,0,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,pSingle,pDouble,pTriple,0,0,0,pWalk,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pHR,0,0,pTriple,pSingle,0,pDouble,pWalk,pOut],
                              [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
                              ])

   runVector  = numpy.matrix([
                              [pHR],
                              [2*pHR + pTriple],
                              [2*pHR + pSingle + pDouble + pTriple],
                              [2*pHR + pSingle + pDouble + pTriple],
                              [3*pHR + pSingle + pDouble + 2*pTriple],
                              [3*pHR + pSingle + pDouble + 2*pTriple],
                              [3*pHR + 2*pSingle + 2*pDouble + 2*pTriple],
                              [4*pHR + 2*pSingle + 2*pDouble + 3*pTriple + pWalk],
                              [pHR],
                              [2*pHR + pTriple],
                              [2*pHR + pSingle + pDouble + pTriple],
                              [2*pHR + pSingle + pDouble + pTriple],
                              [3*pHR + pSingle + pDouble + 2*pTriple],
                              [3*pHR + pSingle + pDouble + 2*pTriple],
                              [3*pHR + 2*pSingle + 2*pDouble + 2*pTriple],
                              [4*pHR + 2*pSingle + 2*pDouble + 3*pTriple + pWalk],
                              [pHR],
                              [2*pHR + pTriple],
                              [2*pHR + pSingle + pDouble + pTriple],
                              [2*pHR + pSingle + pDouble + pTriple],
                              [3*pHR + pSingle + pDouble + 2*pTriple],
                              [3*pHR + pSingle + pDouble + 2*pTriple],
                              [3*pHR + 2*pSingle + 2*pDouble + 2*pTriple],
                              [4*pHR + 2*pSingle + 2*pDouble + 3*pTriple + pWalk],
                              [0]
                              ])

   resultMatrix = runVector
   for z in  range(1,12):
       curentTransition = linalg.matrix_power(transition, z)
       tempMatrix = numpy.dot(curentTransition,runVector)
       resultMatrix = numpy.add(resultMatrix,tempMatrix)

   return resultMatrix
Example #42
0
 def test_large_power(self):
     assert_equal(matrix_power(self.R90, 2**100 + 2**10 + 2**5 + 1),
                  self.R90)
Example #43
0
 def tz(M):
     mz = matrix_power(M, -1)
     assert_almost_equal(identity(M.shape[0]), dot(mz, M))
Example #44
0
      transProb[i][j] = trans[i][j] / sum(list(trans[i]))
  return transProb

# B
transitionMatrix = getMatrixTransitions(acciones)
print(transitionMatrix)

# # C
[autovalores,autovectores] = LA.eig(transitionMatrix)
# como |lambak| < 1 con k-1 pi p = pi
print(autovectores)
print(np.transpose(autovectores))
print(autovalores)

# pelevado = autovectores * matrix_power(autovaloresMat,100) * matrix_power(np.transpose(autovectores),-1)
print(matrix_power(transitionMatrix,100))

#D

difAccionA = list(accionesA["DeltaA"])
difAccionA.pop(0)
plt.title("Diferencia Acciones A")
plt.hist(difAccionA,bins=100)
plt.show()

difAccionB = list(accionesB["DeltaB"])
difAccionB.pop(0)
plt.title("Diferencia Acciones B")
plt.hist(difAccionB,bins=100)
plt.show()
Example #45
0
 def tz(M):
     mz = matrix_power(M, 2)
     assert_equal(mz, dot(M, M))
     assert_equal(mz.dtype, M.dtype)
def gaussSeidel(tolerance, x0, iterations, matrix, b, rel):
    n = len(matrix)
    det = linalg.det(matrix)
    if det == 0:
        return (
            1,
            "The system does not have an unique solution. Determinant is ZERO")

    diagonal_matrix = diag(diag(matrix))
    l_matrix = diagonal_matrix - tril(matrix)
    u_matrix = diagonal_matrix - triu(matrix)
    helper = diagonal_matrix - (rel * l_matrix)
    helper2 = ((1 - rel) * diagonal_matrix) + (rel * u_matrix)

    power = linalg.matrix_power(helper, -1)
    t_matrix = matmul(power, helper2)

    Z = [[abs(matrix[i][j]) for i in range(n)] for j in range(n)]
    helper3 = asarray(Z)
    suma = helper3.sum(axis=1)
    a = 0

    for i in range(n):
        aux2 = (2 * (Z[i][i]))
        if all(aux2 > suma):
            a = 1
        else:
            a = 2

    RE = 0
    if a == 2:
        RE = max(abs(LA.eigvals(t_matrix)))
        if RE > 1:
            return (1, "The spectral radio is larger than 1 (" + str(RE) +
                    "). Method won't converge\n \
                    The matrix is not dominant on its diagonal")

    title = ['n']
    aux = 0
    cont = 0
    while aux < len(x0):
        title.append("x" + str(aux))
        aux += 1
    title.append("Error")
    table = PrettyTable(title)
    result = [title]
    table.add_row([cont] + x0 + ["Doesn't exist"])
    result.append([cont] + x0 + ["Doesn't exist"])
    error = tolerance + 1
    while error > tolerance and cont < iterations:
        x1 = newGaussSeidel(x0, matrix, b, rel)
        error = norma(x0, x1)
        cont += 1
        table.add_row([cont] + x1 + ['%.2E' % Decimal(str(error))])
        result.append([cont] + x1 + ['%.2E' % Decimal(str(error))])
        x0 = copy(x1)

    return 0, x0, result, cont, t_matrix, RE


# m = [[5,3,1],[3,4,-1],[1,-1,4]]
# b = [24,30,-24]
# gaussSeidel(6e-063, [0,0,0], 40, m, b, 1)
Example #47
0
def Rodrigues(w_hat, theta):
    return (np.identity(3) + w_hat * np.sin(theta) + matrix_power(w_hat, 2) *
            (1 - np.cos(theta)))
    def _calc_observable(pb=0.0,
                         kex=0.0,
                         dw=0.0,
                         r_nxy=5.0,
                         dr_nxy=0.0,
                         r_nz=1.5,
                         r_2hznz=0.0,
                         etaxy=0.0,
                         etaz=0.0,
                         j_hn=0.0,
                         dj_hn=0.0,
                         cs=0.0,
                         ncyc=0):
        """
        Calculate the intensity in presence of exchange during a cpmg-type pulse train.
                _______________________________________________________________________
        1H :   |  /   /   /   /   /   /   /   /   CW   /   /   /   /   /   /   /   /   |
        15N:    Nx { tauc  2Ny  tauc }*ncyc 2Nx { tauc  2Ny  tauc }*ncyc -Nx time_equil

        Parameters
        ----------
        i0 : float
            Initial intensity.
        pb : float
            Fractional population of state B,
            0.0 for 0%, 1.0 for 100%
        kex : float
            Exchange rate between state A and B in /s.
        dw : float
            Chemical shift difference between states A and B in rad/s.
        r_nz : float
            Longitudinal relaxation rate of state {a,b} in /s.
        r_nxy : float
            Transverse relaxation rate of state a in /s.
        dr_nxy : float
            Transverse relaxation rate difference between states a and b in /s.
        cs_offset : float
            Offset from the carrier in rad/s.
        Returns
        -------
        out : float
            Intensity after the CPMG block

        """

        dw *= ppm_to_rads
        cs_offset = (cs - carrier) * ppm_to_rads - pi * j_hn

        l_free, ps = make_propagators(pb=pb,
                                      kex=kex,
                                      dw=dw,
                                      r_nxy=r_nxy,
                                      dr_nxy=dr_nxy,
                                      r_nz=r_nz,
                                      r_2hznz=r_2hznz,
                                      etaxy=etaxy,
                                      etaz=etaz,
                                      j_hn=j_hn,
                                      dj_hn=dj_hn,
                                      cs_offset=cs_offset)

        (p_equil, p_neg, p_90px, p_90py, p_90mx, p_90my, p_180px, p_180py,
         p_element) = ps

        mag_eq = compute_2hznz_eq(pb)

        if ncyc == 0:

            # The +/- phase cycling of the first 90 and the receiver is taken care
            # by setting the thermal equilibrium to 0
            mag = -reduce(dot, [p_equil, p_90py, p_element, p_90px, mag_eq])

        else:

            t_cp = time_t2 / (4.0 * ncyc) - pw
            p_free = expm(l_free * t_cp)
            p_cpx = matrix_power(p_free.dot(p_180px).dot(p_free), ncyc)
            p_cpy = matrix_power(p_free.dot(p_180py).dot(p_free), ncyc)
            p_element_pc = 0.5 * (p_90px.dot(p_element).dot(p_90py) +
                                  p_90mx.dot(p_element).dot(p_90my))

            mag = -reduce(dot, [
                p_equil, p_90py, p_neg, p_cpx, p_neg, p_element_pc, p_neg,
                p_cpy, p_neg, p_90px, mag_eq
            ])

        magz_a, _magz_b = get_atrz(mag)

        return magz_a
Example #49
0
 def raisematrix(self, nth):
     #raise transition matrix to the "nth" power
     powmatrix = LA.matrix_power(self.adjMatrix, nth)
     return powmatrix
Example #50
0
    def MPC(
        trajectory,
        heading_error,
        lateral_error,
        dt,
        state_matrix,
        input_matrix,
        drift_matrix,
        prediction_horizon=5,
    ):
        # Implementation of MPC, please see the following ref:
        # Convex Optimization – Boyd and Vandenberghe
        # https://markcannon.github.io/assets/downloads/teaching/C21_Model_Predictive_Control/mpc_notes.pdf
        matrix_A = np.eye(state_matrix.shape[0]) + dt * state_matrix
        matrix_B = dt * input_matrix
        matrix_B0 = dt * drift_matrix
        matrix_M = matrix_A
        matrix_C = np.concatenate(
            (
                matrix_B,
                np.zeros([
                    matrix_B.shape[0],
                    (prediction_horizon - 1) * matrix_B.shape[1]
                ]),
            ),
            axis=1,
        )

        matrix_T_tilde = matrix_B0[:, 0]

        for i in range(prediction_horizon - 1):
            matrix_M = np.concatenate(
                (matrix_M, matrix_power(matrix_A, i + 2)), axis=0)
            matrix_T_tilde = np.concatenate(
                (
                    matrix_T_tilde,
                    np.matmul(
                        matrix_A,
                        matrix_T_tilde[matrix_T_tilde.shape[0] -
                                       matrix_B0.shape[0]:matrix_T_tilde.
                                       shape[0]],
                        matrix_B0[:, i + 1],
                    ),
                ),
                axis=0,
            )
            temp = np.matmul(matrix_power(matrix_A, i + 1), matrix_B)
            for j in range(i + 1, 0, -1):
                temp = np.concatenate(
                    (temp, np.matmul(matrix_power(matrix_A, j - 1), matrix_B)),
                    axis=1)
            temp = np.concatenate(
                (
                    temp,
                    np.zeros([
                        matrix_B.shape[0],
                        (prediction_horizon - i - 2) * matrix_B.shape[1],
                    ]),
                ),
                axis=1,
            )
            matrix_C = np.concatenate((matrix_C, temp), axis=0)

        # Q_tilde contains the MPC state cost weights. The ordering of
        # gains are as [lateral_error,lateral_velocity,heading_error,yaw_rate].
        # Increasing the lateral_error weight can cause oscillations which can
        # be damped out by increasing yaw_rate weight.
        Q_tilde = np.kron(np.eye(prediction_horizon),
                          0.1 * np.diag([354, 0, 14, 250]))
        # R_tilde contain the steering input weight.
        R_tilde = np.kron(np.eye(prediction_horizon), np.eye(1))
        matrix_H = (
            np.transpose(matrix_C)).dot(Q_tilde).dot(matrix_C) + R_tilde
        matrix_F = (np.transpose(matrix_C)).dot(Q_tilde).dot(matrix_M)

        matrix_F1 = (np.transpose(matrix_C)).dot(Q_tilde).dot(matrix_T_tilde)

        # This is the solution to the unconstrained optimization problem
        # for the MPC.
        unconstrained_optimal_solution = np.matmul(
            np.linalg.inv(2 * matrix_H),
            np.matmul(matrix_F,
                      np.array([[lateral_error], [0], [heading_error], [0]])) +
            np.reshape(matrix_F1, (-1, 1)),
        )[0][0]

        return np.clip(-unconstrained_optimal_solution, -1, 1)
Example #51
0
        def _calc_observable(pb=0.0,
                             kex=0.0,
                             dwh=0.0,
                             dwc=0.0,
                             r_2hxycxy=5.0,
                             dr_2hxycxy=0.0,
                             ncyc=0):
            """
            Calculate the intensity in presence of exchange during a cpmg-type pulse
            train. Based on the sequence "hmqc_CH3_exchange_bigprotein_600_lek_v2.c".
            Parameter names from the sequence are:

            chemex      procpar
            ------      -------
            time_T2     time_T2
            ncyc        ncyc_cp

            Parameters
            ----------
            i0 : float
                Initial intensity
            pb : float
                Fractional population of state b
            kex : float
                Exchange rate between state a and b in /s
            dwh : float
                Proton chemical shift difference between states A and B in ppm
            dwc : float
                Carbon chemical shift difference between states A and B in ppm
            r_2hxycxy : float
                Multiple quantum relaxation rate in /s
            dr_2hxycxy : float
                Multiple quantum relaxation rate difference between a and b in /s
            smallflg: string ['y', 'n']
               Flag to include small_protein_flg block in fitting

            Returns
            -------
            out : float
                Intensity after the CPMG block

            """

            dwh *= ppm_to_rads_h
            dwc *= ppm_to_rads_c

            l_free = make_propagators(
                pb=pb,
                kex=kex,
                dwh=dwh,
                dwc=dwc,
                r_2hxycxy=r_2hxycxy,
                dr_2hxycxy=dr_2hxycxy,
            )

            mag_eq = compute_2hxcy_eq(pb)

            if ncyc == 0:
                mag = mag_eq

            else:

                t_cp = time_t2 / (4.0 * ncyc)
                p_free = expm(l_free * t_cp)
                p_cpy = matrix_power(p_free.dot(P180_CY).dot(p_free), ncyc)

                mag = reduce(dot, [p_cpy, P180_HX, p_cpy, mag_eq])

            magz_a, _ = get_2hxcy(mag)

            return magz_a
Example #52
0
 def test_square(self):
     A = array([[True, False], [True, True]])
     assert_equal(matrix_power(A, 2), A)
Example #53
0
 def energy_H(H):
     S = 0
     for i in range(distance):
         S += weights[i] * LA.norm(H_vec_observed[i] -
                                   LA.matrix_power(H, i + 1))
     return S
Example #54
0
 def test_invert_noninvertible(self):
     import numpy.linalg
     assert_raises(numpy.linalg.linalg.LinAlgError,
                   lambda: matrix_power(self.noninv, -1))
Example #55
0
 def test_large_power_trailing_zero(self):
     assert_equal(matrix_power(self.R90, 2**100 + 2**10 + 2**5),
                  identity(2))
 def test_returntype(self):
     a = np.array([[0, 1], [0, 0]])
     assert_(type(matrix_power(a, 2)) is np.ndarray)
     a = mat(a)
     assert_(type(matrix_power(a, 2)) is matrix)
Example #57
0
 def tz(M):
     mz = matrix_power(M, 0)
     assert_equal(mz, identity(M.shape[0]))
     assert_equal(mz.dtype, M.dtype)
Example #58
0
 def tz(M):
     mz = matrix_power(M, 1)
     assert_equal(mz, M)
     assert_equal(mz.dtype, M.dtype)
 def test_list(self):
     assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]])
Example #60
0
    def _find_erg_sets(self):
        """
        This method finds all of the ergodic sets for a given transition
        matrix P.  It saves the ergodic sets in the class object.

        Note: This method is still undergoing testing and improvement. If
        you find a bug or an example where it doesn't work please let us
        know so we can amend our code to do the right thing.

        Parameters
        ----------
        self

        Returns
        -------
        None
        """
        P = self.P
        num_states = P.shape[0]

        # We are going to use graph theory to find ergodic sets
        # We first find where there is positive probability of
        # the sets
        pos_prob_P = np.where(P > 0)

        # Put a one in a matrix everywhere there is positive
        # probability of going from state i to state j
        connect_mat = np.zeros(P.shape)
        connect_mat[pos_prob_P] = 1.
        sets_mat = np.zeros(P.shape)

        # We want to know whether they can get from any given
        # state to the other so we need to add each exponent
        # of connect_mat^n for n up to the num_states.  This is
        # equivalent to (I - P)^{-1}(I - P^n)
        # TODO: If matrix is singular that doesn't work
        for i in xrange(num_states):
            sets_mat += matrix_power(connect_mat, i + 1)

        # Now we know where they really are connected in num_states steps
        true_connected = np.zeros(P.shape)
        true_index = np.where(sets_mat > 0)
        true_connected[true_index] = 1.

        # Create a dictionary where every state will have a set
        # we will use these sets to establish which sets of
        # elements are in the same ergodic set
        conn_states = {'state_%s' % st: set() for st in xrange(num_states)}

        possible_ergodic = set(np.arange(num_states))
        trans_states = set()
        ergodic_sets = []
        num_erg_sets = 0

        # We need to first remove the transient states
        # TODO: Think more about this loop.  Can this be vectorized?

        # Find all of the connected both ways states and the ones that
        # aren't connected both ways should be transient
        for row in possible_ergodic:
            for col in possible_ergodic:
                if abs(true_connected[row, col] - 1) < 1e-10 \
                and abs(true_connected[col, row] - 1) < 1e-10:
                    conn_states['state_%s' % row].add(col)

                elif abs(true_connected[row, col] - 1) > 1e-10 \
                and abs(true_connected.T[row, col] - 1) < 1e-10:
                    trans_states.add(col)

        # Take the transient states out of the possible ergodic states
        for i in trans_states:
            possible_ergodic.remove(i)

        # Now we need to see whether the sets match up like we want them to
        for i in possible_ergodic:
            check_equiv = []
            for t in conn_states['state_%s' % i]:
                if conn_states['state_%s' % i] == conn_states['state_%s' % t]:
                    check_equiv.append(t)

            if conn_states['state_%s' %i] == set(check_equiv) \
            and check_equiv not in ergodic_sets:
                ergodic_sets.append(check_equiv)

        self.ergodic_sets = ergodic_sets
        return None