示例#1
1
def align_magnetism(m, vectors):
    """ Rotates a matrix, to align its components with the direction
  of the magnetism """
    if not len(m) == 2 * len(vectors):  # stop if they don't have
        # compatible dimensions
        raise
    # pauli matrices
    from scipy.sparse import csc_matrix, bmat

    sx = csc_matrix([[0.0, 1.0], [1.0, 0.0]])
    sy = csc_matrix([[0.0, -1j], [1j, 0.0]])
    sz = csc_matrix([[1.0, 0.0], [0.0, -1.0]])
    n = len(m) / 2  # number of sites
    R = [[None for i in range(n)] for j in range(n)]  # rotation matrix
    from scipy.linalg import expm  # exponenciate matrix

    for (i, v) in zip(range(n), vectors):  # loop over sites
        vv = np.sqrt(v.dot(v))  # norm of v
        if vv > 0.000001:  # if nonzero scale
            u = v / vv
        else:  # if zero put to zero
            u = np.array([0.0, 0.0, 0.0])
        #    rot = u[0]*sx + u[1]*sy + u[2]*sz
        uxy = np.sqrt(u[0] ** 2 + u[1] ** 2)  # component in xy plane
        phi = np.arctan2(u[1], u[0])
        theta = np.arctan2(uxy, u[2])
        r1 = phi * sz / 2.0  # rotate along z
        r2 = theta * sy / 2.0  # rotate along y
        # a factor 2 is taken out due to 1/2 of S
        rot = expm(1j * r2) * expm(1j * r1)
        R[i][i] = rot  # save term
    R = bmat(R)  # convert to full sparse matrix
    mout = R * csc_matrix(m) * R.H  # rotate matrix
    return mout.todense()  # return dense matrix
示例#2
0
    def _solve_numericaly(self, u, x0, t, t_list, t0, dps=2):
        """ returns the numeric evaluation of the system for input u, know state x0 at time t0 and times t_list
        """
        result = []
        for t_i in t_list:
            # we use the arbitrary precision module mpmath for numercial evaluation of the matrix exponentials
            first = (
                np.array(np.array(self.represent[2]), np.float)
                .dot(expm(np.array(np.array((self.represent[0] * (t_i - t0)).evalf()), np.float)))
                .dot(np.array(np.array(x0), np.float))
            )

            second = np.array(np.array((self.represent[3] * u.subs(t, t_i)).evalf()), np.float)

            integrand = (
                lambda tau: np.array(np.array(self.represent[2]), np.float)
                .dot(expm(np.array(np.array((self.represent[0] * (t_i - tau)).evalf()), np.float)))
                .dot(np.array(np.array(self.represent[1]), np.float))
                .dot(np.array(np.array(u.subs(t, tau).evalf()), np.float))
            )

            # the result must have the same shape as D:
            integral = zeros(self.represent[2].rows, 1)

            # Loop through every entry and evaluate the integral using mpmath.quad()
            for row_idx in xrange(self.represent[2].rows):

                integral[row_idx, 0] = quad(lambda x: integrand(x)[row_idx, 0], t0, t_i)[0]

            result.append(Matrix(first) + Matrix(second) + integral)

        # return sum of results
        return result
示例#3
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
示例#4
0
    def _learnStep(self):
        """ Main part of the algorithm. """
        I = eye(self.numParameters)
        self._produceSamples()
        utilities = self.shapingFunction(self._currentEvaluations)
        utilities /= sum(utilities)  # make the utilities sum to 1
        if self.uniformBaseline:
            utilities -= 1./self.batchSize
        samples = array(map(self._base2sample, self._population))

        dCenter = dot(samples.T, utilities)
        covGradient = dot(array([outer(s,s) - I for s in samples]).T, utilities)
        covTrace = trace(covGradient)
        covGradient -= covTrace/self.numParameters * I
        dA = 0.5 * (self.scaleLearningRate * covTrace/self.numParameters * I
                    +self.covLearningRate * covGradient)

        self._lastLogDetA = self._logDetA
        self._lastInvA = self._invA

        self._center += self.centerLearningRate * dot(self._A, dCenter)
        self._A = dot(self._A, expm(dA))
        self._invA = dot(expm(-dA), self._invA)
        self._logDetA += 0.5 * self.scaleLearningRate * covTrace
        if self.storeAllDistributions:
            self._allDistributions.append((self._center.copy(), self._A.copy()))
def transfer_f(dw,aas,aai,eps,deltaw,f):
    """
    Args:
    dw: size of the grid spacing
    aas=relative slowness of the signal mode
    aai=relative slowness of the idler mode
    lnl=inverse of the strength of the nonlinearity
    deltaw:  specifies the size of the frequency grid going from
    -deltaw to deltaw for each frequency
    f: shape of the pump function
    """
    ddws=np.arange(-deltaw-dw/2,deltaw+dw/2,dw)
    deltaks=aas*ddws
    ddwi=np.arange(-deltaw-dw/2,deltaw+dw/2,dw)
    deltaki=aai*ddwi
    ds=np.diag(deltaks)
    di=np.diag(deltaki)


    def ff(x,y):
        return f(x+y)
    
    v=eps*(dw)*ff(ddwi[:,None],ddws[None,:])
    G=1j*np.concatenate((np.concatenate((ds,v),axis=1),np.concatenate((-v,-di),axis=1)),axis=0)
    z=1;
    dsi=np.concatenate((deltaks,-deltaki),axis=0)
    U0=linalg.expm(-1j*np.diag(dsi)*z/2)
    GG=np.dot(np.dot(U0,linalg.expm(G)),U0)
    n=len(ddws)
    return (GG[0:n,0:n],GG[n:2*n,0:n],GG[0:n,n:2*n],GG[n:2*n,n:2*n])
示例#6
0
def make_random_su(N):
    
    A = spla.expm(2 * np.pi * 1j * npr.random((N, N)))
    B = (A - np.trace(A) * np.identity(N) / N)
    C = 0.5 * (B - np.conj(B.T))
    
    return spla.expm(C)
def Iterate_LS_Strain(xys0_pix, xys1_pix, num = 10):
    solve = Get_LS_DGradient(xys0_pix, xys1_pix)
    for j in range(0,num):
        xy_pix = Simulate_Shifted_Spots(xys0_pix, linalg.expm(solve), det2lab_mat)
        dsolve = Get_LS_DGradient(xy_pix, xys1_pix)
        solve = solve+dsolve
    return linalg.expm(solve)
示例#8
0
def Char_Gate(NV,res ,B_field=400):
    """
    Characterize the gate, take the NV centre, the resonance paramters and the Bfield as input
    returns the fidelity with which an x-gate can be implemented.
    """


    #data = np.loadtxt("NV_Sim_8.dat") #Placeholder data to test the script
    #NV = np.vstack((data[:,3],data[:,4]))
    #physical constants
    gamma_c = 1.071e3 #g-factor for C13 in Hz/G
    #Model parameters
    omega_larmor = 2*np.pi*gamma_c*B_field
    tau_larmor = 2*np.pi/omega_larmor
    tau = res[0]
    n_pulses = int(res[1]*2) #So that we do a pi -pulse

    Ix = 0.5 * np.array([[0,1],[1,0]])
    Iz = 0.5* np.array([[1,0],[0,-1]])
    H0 = (omega_larmor)*Iz
    exH0 =linalg.expm(-1j*H0*tau)

    S_final =1
    for idC in range(np.shape(NV)[1]):
        A= 2*np.pi*NV[0,idC]
        B= 2*np.pi*NV[1,idC]  #Converts to radial frequency in Hz/G
        H1 = (A+omega_larmor) *Iz +B*Ix
        exH1 = linalg.expm(-1j*H1*tau)
        V0 = exH0.dot(exH1.dot(exH1.dot(exH0)))
        V1 = exH1.dot(exH0.dot(exH0.dot(exH1)))
        S = np.real(np.trace(np.dot(np.linalg.matrix_power(V0,n_pulses),np.linalg.matrix_power(V1,n_pulses)))/2)
        S_final = S_final *S
    F = (1-(S_final+1)/2) #Converting from probability of measuring +X to fidelity of -X (x-rotation)
    return F
示例#9
0
def ghz_simult_trajectory(stages):
    rhos = []
    for stage in stages:
        U = np.eye(8, dtype=complex)
        I = pyle.tomo.sigmaI
        X = pyle.tomo.sigmaX
        Y = pyle.tomo.sigmaY
        couple = (pyle.tensor((X,X,I)) + pyle.tensor((Y,Y,I)) +
                  pyle.tensor((X,I,X)) + pyle.tensor((Y,I,Y)) +
                  pyle.tensor((I,X,X)) + pyle.tensor((I,Y,Y))) / 2.0
        
        if stage > 0:
            fraction = np.clip(stage-0, 0, 1)
            H = -1j * (np.pi/2)/2 * (pyle.tensor((Y,I,I)) + pyle.tensor((I,Y,I)) + pyle.tensor((I,I,Y)))
            U = np.dot(expm(fraction * H), U)
    
        if stage > 1:
            fraction = np.clip(stage-1, 0, 1)
            H = -1j * np.pi/2 * couple
            U = np.dot(expm(fraction * H), U)
        
        if stage > 2:
            fraction = np.clip(stage-2, 0, 1)
            H = -1j * (np.pi/2)/2 * (pyle.tensor((X,I,I)) + pyle.tensor((I,X,I)) + pyle.tensor((I,I,X)))
            U = np.dot(expm(fraction * H), U)
    
        psi0 = np.array([1,0,0,0,0,0,0,0], dtype=complex)
        psi_th = np.dot(U, psi0)
        rho_th = pyle.ket2rho(psi_th)
        rhos.append(rho_th)
    return np.array(rhos)
示例#10
0
    def pdf(self, x):
        """ probability density function """
        if not np.isscalar(x):
            x = np.asarray(x)
            res = np.zeros_like(x)
            nz = (x > 0)
            if np.any(nz):
                if self.method == 'sum':
                    factor = np.exp(-x[nz, None] * self.rates[..., :]) \
                                / self.rates[..., :]
                    res[nz] = np.sum(self._terms[..., :] * factor, axis=1)
                else:
                    Theta = (np.diag(-self.rates, 0) + 
                             np.diag(self.rates[:-1], 1))
                    for i in np.flatnonzero(nz):
                        res.flat[i] = \
                                1 - linalg.expm(x.flat[i]*Theta)[0, :].sum()
 
        elif x == 0:
            res = 0
        else:
            if self.method == 'sum':
                factor = np.exp(-x*self.rates)/self.ratesx
                res[nz] = np.sum(self._terms * factor)
            else:
                Theta = np.diag(-self.rates, 0) + np.diag(self.rates[:-1], 1)
                res = 1 - linalg.expm(x*Theta)[0, :].sum()
        return res
示例#11
0
def linear_ode_discretation(F, L=None, Q=None, dt=1):
    n = F.shape[0]

    if L is None:
        L = eye(n)

    if Q is None:
        Q = zeros((n,n))

    A = expm(F*dt)

    phi = zeros((2*n, 2*n))

    phi[0:n,     0:n] = F
    phi[0:n,   n:2*n] = L.dot(Q).dot(L.T)
    phi[n:2*n, n:2*n] = -F.T

    zo = vstack((zeros((n,n)), eye(n)))

    CD = expm(phi*dt).dot(zo)

    C = CD[0:n,:]
    D = CD[n:2*n,:]
    q = C.dot(inv(D))

    return (A, q)
示例#12
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
示例#13
0
文件: crlb.py 项目: anlif/filtersim
def discretize(F,G,Q,Ts):
    Phi = sp_linalg.expm(F*Ts)

    # Control matrix Lambda, not to be used
    L = np.zeros((F.shape[0],1))

    A_z = np.zeros((L.shape[1], F.shape[1]+L.shape[1]))
    A1 = np.vstack((np.hstack((F,L)),A_z))

    Loan1 = sp_linalg.expm(A1*Ts)
    Lambda = Loan1[0:L.shape[0], F.shape[1]:F.shape[1]+L.shape[1]]

    # Covariance
    Qc = symmetrize(np.dot(G, np.dot(Q, G.T)))
    dim = F.shape[0]
    A2 = np.vstack((np.hstack((-F, Qc)), np.hstack((np.zeros((dim,dim)), F.T))))
    Loan2 = sp_linalg.expm(A2*Ts)
    G2 = Loan2[0:dim, dim:2*dim]
    F3 = Loan2[dim:2*dim, dim:2*dim]

    # Calculate Gamma*Gamma.T
    Qd = symmetrize(np.dot(F3.T, G2))
    L = np.linalg.cholesky(Qd)
    
    return Phi, Qd, L
示例#14
0
 def test_padecases_float(self):
     # test single-precision cases
     a1 = eye(3, dtype=float)*1e-1; e1 = exp(1e-1)*eye(3)
     a2 = eye(3, dtype=float);      e2 = exp(1.0)*eye(3)
     a3 = eye(3, dtype=float)*10;   e3 = exp(10.)*eye(3)
     assert_array_almost_equal(expm(a1),e1)
     assert_array_almost_equal(expm(a2),e2)
     assert_array_almost_equal(expm(a3),e3)
示例#15
0
    def test_consistency(self):
        a = array([[0.,1],[-1,0]])
        assert_array_almost_equal(expm(a), expm2(a))
        assert_array_almost_equal(expm(a), expm3(a))

        a = array([[1j,1],[-1,-2j]])
        assert_array_almost_equal(expm(a), expm2(a))
        assert_array_almost_equal(expm(a), expm3(a))
示例#16
0
def test_QobjExpmExplicitDense():
    "Qobj expm (explicit dense)"
    data = np.random.random(
        (15, 15)) + 1j * np.random.random((15, 15)) - (0.5 + 0.5j)
    A = Qobj(data)
    B = A.expm(method='dense')
    assert_((B.data.todense() - np.matrix(la.expm(data)) < 1e-10).all())
    B = A.expm(method='scipy-delse')
    assert_((B.data.todense() - np.matrix(la.expm(data)) < 1e-10).all())
示例#17
0
def KPMF(input_matrix, approx=50, iterations=30, learning_rate=.001, adjacency_width=5, adjacency_strength=.5):
    A = input_matrix
    Z = np.asarray(A > 0,dtype=np.int)
    A1d = np.ravel(A)
    mean = np.mean(A1d)
    A = A-mean
    K = approx
    R = itr = iterations
    l = learning_rate
    N = A.shape[0]
    M = A.shape[1]
    U = np.random.randn(N,K)
    V = np.random.randn(K,M)
    #KPMF using gradient descent as per paper
    #Kernelized Probabilistic Matrix Factorization: Exploiting Graphs and Side Information
    #T. Zhou, H. Shan, A. Banerjee, G. Sapiro
    #Using diffusion kernel
    #U are the rows, we use an adjacency matrix CU to reprent connectivity
    #This matrix connects rows +-adjacency_width
    #V are the columns, connected columns are CV
    #Operate on graph laplacian L, which is the degree matrix D - C
    #Applying the diffusion kernel to L, this forms a spatial smoothness graph
    bw = adjacency_width
    #Use scipy.sparse.diags to generate band matrix with bandwidth = 2*adjacency_width+1
    #Example of adjacency_width = 1, N = 4
    #[1 1 0 0]
    #[1 1 1 0]
    #[0 1 1 1]
    #[0 0 1 1]
    print "Running KPMF with:"
    print "learning rate=" + `l`
    print "bandwidth=" + `bw`
    print "beta=" + `b`
    print "approximation rank=" + `K`
    print "iterations=" + `R`
    print ""
    CU = sp.diags([1]*(2*bw+1),range(-bw,bw+1),shape=(N,N)).todense()
    DU = np.diagflat(np.sum(CU,1))
    CV = sp.diags([1]*(2*bw+1),range(-bw,bw+1),shape=(M,M)).todense()
    DV = np.diagflat(np.sum(CV,1))
    LU = DU - CU
    LV = DV - CV
    beta = adjacency_strength
    KU = sl.expm(beta*LU)
    KV = sl.expm(beta*LV)
    SU = np.linalg.pinv(KU)
    SV = np.linalg.pinv(KV)
    for r in range(R):
        for i in range(N):
            for j in range(M):
                if Z[i,j] > 0:
                    e = A[i,j] - np.dot(U[i,:],V[:,j])
                    U[i,:] = U[i,:] + l*(e*V[:,j] - np.dot(SU[i,:],U))
                    V[:,j] = V[:,j] + l*(e*U[i,:] - np.dot(V,SV[:,j]))
    A_ = np.dot(U,V)
    return A_+mean
示例#18
0
 def get_symmetry(self,x):
     """Return the symmetry operator"""
     if self.real: 
         M = v2O(x,exp=self.discrete)
         if self.discrete: return M # return the operator
         else: return lg.expm(M) # return the operator
     else:
         M = v2U(x,exp=self.discrete)
         if self.discrete: return M # return the operator
         else: return lg.expm(1j*M) # return the operator
    def test_consistency(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            a = array([[0.,1],[-1,0]])
            assert_array_almost_equal(expm(a), expm2(a))
            assert_array_almost_equal(expm(a), expm3(a))

            a = array([[1j,1],[-1,-2j]])
            assert_array_almost_equal(expm(a), expm2(a))
            assert_array_almost_equal(expm(a), expm3(a))
示例#20
0
 def gibbsstate(self):
     nb=self.p.nbar
     hbar=self.p.hbar
     kb=self.p.kb
     nu=self.p.nu
     T=hbar*nu/(kb*np.log((nb + 1.)/nb))
     Z=np.trace(expm(-hbar*nu*self.ada/(kb*T)))
     result = np.kron(expm(-hbar*nu*self.ada/(kb*T)),[[0,0],[0,1]])/Z
     if result[2*(self.p.nmax+1)-1,2*(self.p.nmax+1)-1]>0.0001:
         print 'Warning: nmax may not be high enough for chosen value of nbar'
     return result
示例#21
0
def get_plot_array(N_diploid, Nr, theta_values, Ns_values):
    """
    Compute expected hitting times.
    Theta is 4*N*mu, and the units of time are 4*N*mu generations.
    @param N_diploid: diploid population size
    @param Nr: recombination rate
    @param theta_values: mutation rates
    @param Ns_values: selection values
    @return: arr[i][j] gives time for Ns_values[i] and theta_values[j]
    """
    # set up the state space
    k = 4
    M = multinomstate.get_sorted_states(2 * N_diploid, k)
    T = multinomstate.get_inverse_map(M)
    nstates = M.shape[0]
    lmcs = wfengine.get_lmcs(M)
    # precompute rate matrices
    R_rate = wfcompens.create_recomb(M, T)
    M_rate = wfcompens.create_mutation(M, T)
    # precompute a recombination probability matrix
    R_prob = linalg.expm(Nr * R_rate / float((2 * N_diploid) ** 2))
    #
    arr = []
    for theta in theta_values:
        # Compute the expected number of mutation events per generation.
        mu = theta / 2
        # Precompute the mutation matrix
        # and the product of mutation and recombination.
        M_prob = linalg.expm(mu * M_rate / float(2 * 2 * N_diploid))
        MR_prob = np.dot(M_prob, R_prob)
        #
        row = []
        for Ns in Ns_values:
            s = Ns / float(N_diploid)
            lps = wfcompens.create_selection(s, M)
            S_prob = np.exp(wfengine.create_genic(lmcs, lps, M))
            P = np.dot(MR_prob, S_prob)
            # compute the stationary distribution
            v = MatrixUtil.get_stationary_distribution(P)
            # compute the transition matrix limit at time infinity
            # P_inf = np.outer(np.ones_like(v), v)
            # compute the fundamental matrix Z
            # Z = linalg.inv(np.eye(nstates) - (P - P_inf)) - P_inf
            #
            # Use broadcasting instead of constructing P_inf.
            Z = linalg.inv(np.eye(nstates) - (P - v)) - v
            # compute the hitting time from state AB to state ab.
            i = 0
            j = 3
            hitting_time_generations = (Z[j, j] - Z[i, j]) / v[j]
            hitting_time = hitting_time_generations * theta
            row.append(hitting_time)
        arr.append(row)
    return arr
示例#22
0
 def test_padecases_double(self):
     # test double-precision cases
     a1 = eye(3, dtype=double)*1e-2; e1 = exp(1e-2)*eye(3)
     a2 = eye(3, dtype=double)*1e-1; e2 = exp(1e-1)*eye(3)
     a3 = eye(3, dtype=double)*5e-1; e3 = exp(5e-1)*eye(3)
     a4 = eye(3, dtype=double);      e4 = exp(1.)*eye(3)
     a5 = eye(3, dtype=double)*10;   e5 = exp(10.)*eye(3)
     assert_array_almost_equal(expm(a1),e1)
     assert_array_almost_equal(expm(a2),e2)
     assert_array_almost_equal(expm(a3),e3)
     assert_array_almost_equal(expm(a4),e4)
     assert_array_almost_equal(expm(a5),e5)
def q(dt, prmtr, num_states, prmtr_size_dict,skip_mapping=0):
    '''computing Q matrix'''
    if num_states == 4:
        a, Kp, lmda, Phi, sigma11, sigma22, sigma33, sigma44, Sigma, thetap = extract_vars(prmtr, num_states, prmtr_size_dict, skip_mapping=skip_mapping)
    elif num_states == 6:
        a, Kp, lmda, lmda2, Phi, sigma11, sigma22, sigma22_2, sigma33, sigma33_2, sigma44, Sigma, thetap = extract_vars(prmtr, num_states, prmtr_size_dict, skip_mapping=skip_mapping)
    qout = np.empty((num_states,num_states)) * np.nan
    tempfunc = lambda x, r, c: (expm(-Kp * x)*Sigma*(Sigma.transpose())*(expm(-Kp * x).transpose()))[r, c]
    for r in range(num_states):
        for c in range(num_states):
            qout[r, c] = integrate.quad(tempfunc, 0, dt, args=(r, c))[0]
    return qout
示例#24
0
 def __get_ps(self):
     """
     Return the list of probabilities for each time slice
     :return: the list of probabilities for each time slice
     """
     to_return = [expm(self.q_iso * self.sin_breaks[0])]
     to_return.extend([expm(self.q_sin * (self.sin_breaks[i + 1] - self.sin_breaks[i]))
                      for i in
                      xrange(len(self.sin_breaks) - 1)])
     p_end = numpy.zeros(shape=self.q_sin.shape)
     p_end[:, END[PS.single][0]] = 1.0
     to_return.append(p_end)
     return to_return
示例#25
0
def get_plot_array(N_diploid, Nr, theta_values, Ns_values):
    """
    @param N_diploid: diploid population size
    @param Nr: recombination rate
    @param theta_values: mutation rates
    @param Ns_values: selection values
    @return: arr[i][j] gives time for Ns_values[i] and theta_values[j]
    """
    # set up the state space
    k = 4
    M = multinomstate.get_sorted_states(2 * N_diploid, k)
    T = multinomstate.get_inverse_map(M)
    nstates = M.shape[0]
    lmcs = wfengine.get_lmcs(M)
    # precompute rate matrices
    R_rate = wfcompens.create_recomb(M, T)
    M_rate = wfcompens.create_mutation(M, T)
    # precompute a recombination probability matrix
    R_prob = linalg.expm(Nr * R_rate / float((2 * N_diploid) ** 2))
    #
    arr = []
    for theta in theta_values:
        # Compute the expected number of mutation events per generation.
        mu = theta / 2
        # Precompute the mutation matrix
        # and the product of mutation and recombination.
        M_prob = linalg.expm(mu * M_rate / float(2 * 2 * N_diploid))
        MR_prob = np.dot(M_prob, R_prob)
        #
        row = []
        for Ns in Ns_values:
            s = Ns / float(N_diploid)
            lps = wfcompens.create_selection(s, M)
            S_prob = np.exp(wfengine.create_genic(lmcs, lps, M))
            P = np.dot(MR_prob, S_prob)
            # compute the stochastic complement
            X = linalg.solve(np.eye(nstates - k) - P[k:, k:], P[k:, :k])
            H = P[:k, :k] + np.dot(P[:k, k:], X)
            # condition on not looping
            np.fill_diagonal(H, 0)
            v = np.sum(H, axis=1)
            H /= v[:, np.newaxis]
            # let ab be an absorbing state
            # and compute the expected number of returns to AB
            Q = H[:3, :3]
            I = np.eye(3)
            N = linalg.inv(I - Q)
            #
            row.append(N[0, 0] - 1)
        arr.append(row)
    return arr
示例#26
0
def _B2formula(Ac, t1, t2, B2):
    if t1 == 0 and t2 == 0:
        term = B2
        return term
    n = Ac.shape[0]
    tmp = np.eye(n) - expm(-Ac)
    if cond(tmp) < 1000000.0:
        term = np.dot(((expm(-Ac * t1) - expm(-Ac * t2)) * inv(tmp)), B2)
        return term
    # Numerical trouble. Perturb slightly and check the result
    ntry = 0
    k = np.sqrt(eps)
    Ac0 = Ac
    while ntry < 2:
        Ac = Ac0 + k * rand(n, n)
        tmp = np.eye(n) - expm(-Ac)
        if cond(tmp) < 1 / np.sqrt(eps):
            ntry = ntry + 1
            if ntry == 1:
                term = np.dot(np.dot(expm(-Ac * t1) - expm(-Ac * t2), inv(tmp)), B2)
            else:
                term1 = np.dot(np.dot(expm(-Ac * t1) - expm(-Ac * t2), inv(tmp)), B2)
        k = k * np.sqrt(2)

    if norm(term1 - term) > 0.001:
        warn("Inaccurate calculation in mapCtoD.")
    return term
示例#27
0
 def test_opposite_sign_complex_eigenvalues(self):
     # See gh-6113
     E = [[0, 1], [-1, 0]]
     L = [[0, np.pi*0.5], [-np.pi*0.5, 0]]
     assert_allclose(expm(L), E, atol=1e-14)
     assert_allclose(logm(E), L, atol=1e-14)
     E = [[1j, 4], [0, -1j]]
     L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]]
     assert_allclose(expm(L), E, atol=1e-14)
     assert_allclose(logm(E), L, atol=1e-14)
     E = [[1j, 0], [0, -1j]]
     L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]]
     assert_allclose(expm(L), E, atol=1e-14)
     assert_allclose(logm(E), L, atol=1e-14)
示例#28
0
def test_PHS_TRIM():
    """Test the function that makes particle-hole symmetric modes at a TRIM. """
    np.random.seed(10)
    for n in (4, 8, 16, 40, 60):
        for sym in kwant.rmt.sym_list:
            if kwant.rmt.p(sym):
                p_mat = np.array(kwant.rmt.h_p_matrix[sym])
                p_mat = np.kron(np.identity(n // len(p_mat)), p_mat)
                P_squared = 1 if np.all(np.abs(p_mat.conj().dot(p_mat) -
                                               np.eye(*p_mat.shape)) < 1e-10) else -1
                if P_squared == 1:
                    for nmodes in (1, 3, n//4, n//2, n):
                        # Random matrix of 'modes.' Take part of a unitary matrix to
                        # ensure that the modes form a basis.
                        modes = np.random.rand(n, n) + 1j*np.random.rand(n, n)
                        modes = la.expm(1j*(modes + modes.T.conj()))[:n, :nmodes]
                        # Ensure modes are particle-hole symmetric and normalized
                        modes = modes + p_mat.dot(modes.conj())
                        modes = np.array([col/np.linalg.norm(col) for col in modes.T]).T
                        # Mix the modes with a random unitary transformation
                        U = np.random.rand(nmodes, nmodes) + 1j*np.random.rand(nmodes, nmodes)
                        U = la.expm(1j*(U + U.T.conj()))
                        modes = modes.dot(U)
                        # Make the modes PHS symmetric using the method for a TRIM.
                        phs_modes = leads.phs_symmetrization(modes, p_mat)[0]
                        assert_almost_equal(phs_modes, p_mat.dot(phs_modes.conj()),
                                            err_msg='PHS broken at a TRIM in ' + sym)
                        assert_almost_equal(phs_modes.T.conj().dot(phs_modes), np.eye(phs_modes.shape[1]),
                                           err_msg='Modes are not orthonormal, TRIM PHS in ' + sym)
                elif P_squared == -1:
                    # Need even number of modes =< n
                    for nmodes in (2, 4, n//2, n):
                        # Random matrix of 'modes.' Take part of a unitary matrix to
                        # ensure that the modes form a basis.
                        modes = np.random.rand(n, n) + 1j*np.random.rand(n, n)
                        modes = la.expm(1j*(modes + modes.T.conj()))[:n, :nmodes]
                        # Ensure modes are particle-hole symmetric and orthonormal.
                        modes[:, nmodes//2:] = p_mat.dot(modes[:, :nmodes//2].conj())
                        modes = la.qr(modes, mode='economic')[0]
                        # Mix the modes with a random unitary transformation
                        U = np.random.rand(nmodes, nmodes) + 1j*np.random.rand(nmodes, nmodes)
                        U = la.expm(1j*(U + U.T.conj()))
                        modes = modes.dot(U)
                        # Make the modes PHS symmetric using the method for a TRIM.
                        phs_modes = leads.phs_symmetrization(modes, p_mat)[0]
                        assert_almost_equal(phs_modes[:, 1::2], p_mat.dot(phs_modes[:, ::2].conj()),
                                            err_msg='PHS broken at a TRIM in ' + sym)
                        assert_almost_equal(phs_modes.T.conj().dot(phs_modes), np.eye(phs_modes.shape[1]),
                                           err_msg='Modes are not orthonormal, TRIM PHS in ' + sym)
示例#29
0
def Find_Res(HyperfineStr=[1.4680e+4,2.9361e3] ,B_field =400 ,tau_max=6*1e-6,tau_step = 0.005*1e-6, max_gate_time = 8000*1e-6):
    """
    Finds resonant driving conditions and number of pulses required for a hyperfine strength
    input HyperfineStr in real freq
    but number of pulses unreliable because of dependency on timestep
    """
    #physical constants
    gamma_c = 1.071e3 #g-factor for C13 in MHz/G
    #Model parameters
    timesteps = np.arange(tau_step,tau_max,tau_step)
    omega_larmor = 2*np.pi*gamma_c*B_field
    tau_larmor = 2*np.pi/omega_larmor

    A= 2*np.pi*HyperfineStr[0]
    B= 2*np.pi*HyperfineStr[1]  #Converts to radial frequency in Hz

    Ix = 0.5 * np.array([[0,1],[1,0]])
    Iz = 0.5* np.array([[1,0],[0,-1]])
    H0 = (omega_larmor)*Iz
    H1 = (A+omega_larmor) *Iz +B*Ix

    li_n0 = []
    li_n1=[]
    ax_prod = np.zeros(np.size(timesteps))
    #Char evolution
    for idt, tau in enumerate(timesteps):
        exH0 =linalg.expm(-1j*H0*tau)
        exH1 = linalg.expm(-1j*H1*tau)
        V0 = exH0.dot(exH1.dot(exH1.dot(exH0)))
        V1 = exH1.dot(exH0.dot(exH0.dot(exH1)))
        #li_V0.append(V0)#appending takes shitloads of time. Maybe dump this line
        #li_V1.append(V1)

        n0 = Calc_axis(V0)
        n1 =Calc_axis(V1)
        ax_prod[idt] = np.dot(n0,n1)
    #Find Resonances as minima
    dip_ind = find_mins(ax_prod)
    theta = np.zeros(np.size(dip_ind))
    for idi, ind in enumerate(dip_ind):  #Either save V0's and calc only needed theta or calc all and not save V0
        tau = timesteps[ind]
        exH0 =linalg.expm(-1j*H0*tau)
        exH1 = linalg.expm(-1j*H1*tau)
        V0 = exH0.dot(exH1.dot(exH1.dot(exH0)))
        theta[idi] = np.real(2*np.arccos(np.trace(V0)/2))
    n_pulses = np.divide(np.pi,(2*(np.pi-np.abs(np.pi-theta)))).astype(int)
    tlist = timesteps[dip_ind]
    res = check_pulse_t(tlist, n_pulses, max_gate_time)
    return res
示例#30
0
def help_get_lhood_diff(T, root, root_distn1d, node_to_data_fvec1d, edge_to_Q,
        edge_to_rate, special_edge):
    edge_to_P = {}
    for edge in T.edges():
        edge_rate = edge_to_rate[edge]
        edge_Q = edge_to_Q[edge]
        Q = edge_rate * edge_Q
        if edge == special_edge:
            P = np.dot(edge_Q, expm(Q))
        else:
            P = expm(Q)
        edge_to_P[edge] = P
    lhood = get_lhood(T, edge_to_P, root, root_distn1d,
            node_to_data_fvec1d)
    return lhood
示例#31
0
def mat_exp(mat):
    return expm(mat)
def continous_time_least_norm_input(A, B, xr, t1, dt):
    times = np.arange(0, t1, dt)
    Gc = gram_ctrb(A, B)
    uln_t = [B.T * la.expm(A.T * (t1 - t)) * Gc.I * xr for t in times]
    return uln_t
    length = int(107)

elif protein == '1pek':
    pi_nuc = [0.20853, 0.34561, 0.25835, 0.18750]
    GTR = helpers.MutationMatrix(pi_nuc, 0.90382, 1, 1, 1, 1, 0.90382)
    num_taxa = int(12)
    length = int(279)

Neff = int(1e2)
IN, IS = IndicatorMatrix()
M = Q_matrix(np.ones(61), GTR, Neff)

#Calculate neutral frequencies based on GTR model
F_neutral = np.ones((61))
Q_neutral = Q_matrix(F_neutral, GTR, Neff)
P_neutral = linalg.expm(np.multiply(Q_neutral, 40))
p_neutral = P_neutral[0]

#%%############################################################################
####                    calculate E[dN/dS] for S-SI                        ####
###############################################################################
full_Kn = np.zeros((50, length))
full_Ln = np.zeros((50, length))
for trial in range(1, 51):
    KN = []
    LN = []
    print(trial)
    full_ssFit = pickle.load(
        open(path_to_ssFit + 'ssFit_seqfile' + str(trial) + '.pkl', 'rb'))
    ssFit = np.mean(full_ssFit, axis=1)
    for site in range(length):
affine = np.identity(4)
rot = np.radians(fitpars[3:])
rotation_matrices = np.apply_along_axis(create_rotation_matrix_3d, axis=0, arr=rot).transpose([-1, 0, 1])
tt = fitpars[0:3, :].transpose([1, 0])
affs = np.tile(affine, [fitpars.shape[1], 1, 1])
affs[:,0:3,0:3] = rotation_matrices
affs[:, 0:3, 3] = tt

from scipy.linalg import logm, expm
weights, matrices = ss[0], affs

logs = [w * logm(A) for (w, A) in zip(weights, matrices)]
logs = np.array(logs)
logs_sum = logs.sum(axis=0)
expm(logs_sum/np.sum(weights, axis=0) )
#a 10-2 pres c'est bien l'identite !

rp_files = gfile('/data/romain/HCPdata/suj_274542/Motion_ms','^rp')
rp_files = gfile('/data/romain/HCPdata/suj_274542/mot_separate','^rp')

rpf = rp_files[10]
res = pd.DataFrame()
for rpf in rp_files:
    dirpath,name = get_parent_path([rpf])
    fout = dirpath[0] + '/check/'+name[0][3:-4] + '.nii'

    t = RandomMotionFromTimeCourse(fitpars=rpf, nufft=True, oversampling_pct=0, keep_original=True, verbose=True)
    dataset = ImagesDataset(suj, transform=t)
    sample = dataset[0]
    dicm = sample['T1']['metrics']
示例#35
0
def spectralrad(M):
    """M is a matrix : returns the spectral radius"""
    return(np.absolute(LA.eigvals(M)).max())

def vecetspectralrad(M):
    l,w=LA.eig(M)
    al=np.absolute(l)
    im=np.where(al==al.max())[0][0]
    v=w[:,im]
    v=v/sum(v)
    return(al[im],v)

#et on teste

D=np.array([[-2, 2], [1, -1]])
E=expm((2*np.log(2)/3)*D)
spectralrad(E.transpose())

A=np.array([[1, -1], [4, 2]])
B=np.diag((1, 2, 3))
C=np.array([[0.1,0.9],[0.3,0.7]])

ei=LA.eigvals(A)
z=ei[0]
rei=ei.real

np.exp(spectralabc(A))
spectralrad(expm(A)) #doit donner la même chose

#un premier modele de covid avec deux classes Asymptomatique et Infectieux
def tauxcontacper(beta,p,cbeta,T):
示例#36
0
    def step(self, niter):
        """ xNES """
        f = self.f
        mu, sigma, bmat = self.mu, self.sigma, self.bmat
        eta_mu, eta_sigma, eta_bmat = self.eta_mu, self.eta_sigma, self.eta_bmat
        npop = self.npop
        dim = self.dim
        sigma_old = self.sigma_old

        eyemat = eye(dim)

        with joblib.Parallel(n_jobs=self.n_jobs) as parallel:

            for i in range(niter):
                s_try = randn(npop, dim)
                z_try = mu + sigma * dot(s_try, bmat)     # broadcast

                f_try = parallel(joblib.delayed(f)(z) for z in z_try)
                f_try = asarray(f_try)

                # save if best
                fitness = mean(f_try)
                if fitness - 1e-8 > self.fitness_best:
                    self.fitness_best = fitness
                    self.mu_best = mu.copy()
                    self.counter = 0
                else: self.counter += 1
                if self.counter > self.patience:
                    self.done = True
                    return

                isort = argsort(f_try)
                f_try = f_try[isort]
                s_try = s_try[isort]
                z_try = z_try[isort]

                u_try = self.utilities if self.use_fshape else f_try

                if self.use_adasam and sigma_old is not None:  # sigma_old must be available
                    eta_sigma = self.adasam(eta_sigma, mu, sigma, bmat, sigma_old, z_try)

                dj_delta = dot(u_try, s_try)
                dj_mmat = dot(s_try.T, s_try*u_try.reshape(npop,1)) - sum(u_try)*eyemat
                dj_sigma = trace(dj_mmat)*(1.0/dim)
                dj_bmat = dj_mmat - dj_sigma*eyemat

                sigma_old = sigma

                # update
                mu += eta_mu * sigma * dot(bmat, dj_delta)
                sigma *= exp(0.5 * eta_sigma * dj_sigma)
                bmat = dot(bmat, expm(0.5 * eta_bmat * dj_bmat))

                # logging
                self.history['fitness'].append(fitness)
                self.history['sigma'].append(sigma)
                self.history['eta_sigma'].append(eta_sigma)

        # keep last results
        self.mu, self.sigma, self.bmat = mu, sigma, bmat
        self.eta_sigma = eta_sigma
        self.sigma_old = sigma_old
示例#37
0
 def ExpMatrix(self, *time):
     self.Solution = self.eAt = numpy.array([
         (linalg.expm(self.A * _t)).dot(self.u0) for _t in time
     ])
     self.t = numpy.array([time])
     return self.eAt
示例#38
0
    def VISLAM(self):

        time = np.transpose(self.t)
        velocity = np.transpose(self.linear_velocity)
        omega = np.transpose(self.rotational_velocity)

        #EKF prediction of the IMU
        mu_list, cov_list = self.prediction(
        )  #world in imu prediction (imu state)
        noise_w = 1e-5 * np.eye(6)  #imu noise covariance

        #Initialize EKF update
        M = getM(self.K, self.b)
        mu_world_feature_0 = np.zeros(
            (4, self.feature_num
             ))  #initial state of the landmark --> visualization
        mu = np.zeros((4, self.feature_num +
                       4))  #fused state: 4 x num of features, 4 x 4 for pose
        cov = np.eye(
            3 * self.feature_num +
            6)  #fused observation covariance 3 x num of features + 6 DOF
        noise_v = 1e1 * np.eye(4)  #landmarks noise covariance

        #Save the pose world_T_imu
        pose_list = []
        world_T_imu = np.linalg.inv(mu_list[0])
        pose_list.append(world_T_imu)

        #Update landmarks for first observation (first frame)
        indices = np.flatnonzero(self.features[0, :, 0] != -1)

        feature = self.features[:, indices, 0]  #feature in image frame
        Z = getz(feature, M)
        x = (feature[0] - M[0, 2]) * Z / M[0, 0]
        y = (feature[1] - M[1, 2]) * Z / M[1, 1]
        feature_cam = np.vstack(
            (x, y, Z, np.ones(x.shape)))  #feature in camera frame
        imu_T_cam = np.linalg.inv(self.cam_T_imu)
        world_T_imu = np.linalg.inv(mu_list[0])
        feature_world = world_T_imu @ imu_T_cam @ feature_cam  #feature in world frame

        mu_world_feature_0[:, indices] = feature_world
        mu[:, indices] = feature_world

        for i in range(self.t_len - 2):
            #EKF IMU pose prediction
            dt = time[i + 1] - time[i]
            omega_hat = gethatmap(omega[i])
            u_head = getu_head(omega_hat, velocity[i])

            v_hat = gethatmap(velocity[i])
            u_vee = getu_vee(omega_hat, v_hat)

            mu_list[i + 1] = getpredict_mu(dt, u_head,
                                           mu_list[i])  #world to body
            cov_list[i + 1] = getpredict_cov(dt, u_vee, cov_list[i], noise_w)

            #Update covariance in fused state
            cov[-6:, -6:] = cov_list[i]
            cov[:3 * self.feature_num,
                3 * self.feature_num:] = cov[:3 * self.feature_num, 3 *
                                             self.feature_num:] @ np.transpose(
                                                 expm(-dt * u_vee))
            cov[3 * self.feature_num:, :3 * self.feature_num] = np.transpose(
                cov[:3 * self.feature_num, 3 * self.feature_num:])

            #EKF mean update landmarks and pose
            indices = np.flatnonzero(self.features[0, :, i + 1] != -1)
            z = self.features[:, indices, i + 1]
            N_t = len(indices)

            if N_t:
                #First observed new features
                indices_new = indices[np.flatnonzero(
                    mu_world_feature_0[-1, indices] == 0)]
                z_new = self.features[:, indices_new,
                                      i + 1]  #new feature in image frame

                if len(z_new):
                    Z = getz(z_new, M)
                    x = (z_new[0] - M[0, 2]) * Z / M[0, 0]
                    y = (z_new[1] - M[1, 2]) * Z / M[1, 1]
                    feature_cam = np.vstack(
                        (x, y, Z,
                         np.ones(x.shape)))  #new feature in camera frame
                    imu_T_cam = np.linalg.inv(self.cam_T_imu)
                    world_T_imu = np.linalg.inv(mu_list[i + 1])
                    feature_world = world_T_imu @ imu_T_cam @ feature_cam  #new feature in world frame
                    mu_world_feature_0[:, indices_new] = feature_world
                    mu[:, indices_new] = feature_world

                #EKF update landmarks and pose
                H = np.zeros((4 * N_t, 3 * self.feature_num + 6))

                cam_T_imu_T_world = self.cam_T_imu @ mu_list[i + 1]
                z_hat = M @ cam_T_imu_T_world @ mu[:, indices]
                z_hat = z_hat / z_hat[2]

                for j in range(N_t):
                    #landmarks update of H
                    H[4*j:4*j+4, 3*indices[j]:3*indices[j]+3] = M @ jacobian(self.cam_T_imu @ mu_list[i+1] @ mu[:,indices[j]].reshape(4,-1)) @ \
                                                                 self.cam_T_imu @ mu_list[i+1] @ self.D
                    #imu pose update of H
                    H[4*j:4*j+4, -6:] = M @ jacobian(self.cam_T_imu @ mu_list[i+1] @ mu[:, indices[j]]) @ \
                                            self.cam_T_imu @ getcircle(mu_list[i+1] @ mu[:, indices[j]].reshape(4, -1))
                k_gain = cov @ np.transpose(H) @ np.linalg.pinv(
                    H @ cov @ np.transpose(H) + np.kron(np.eye(N_t), noise_v))

                #Update landmarks mean
                mu[:, :self.feature_num] = (mu[:, :self.feature_num].flatten('F') + np.kron(np.eye(self.feature_num), self.D) @ k_gain[:3*self.feature_num, :] @ \
                                           (z - z_hat).flatten('F')).reshape(self.feature_num, 4).T

                #Update IMU pose mean
                mu[:, self.feature_num:] = expm(
                    hatoperation(k_gain[-6:, :]
                                 @ (z - z_hat).flatten('F'))) @ mu_list[i + 1]

                #Update fused state covariance
                cov = (np.eye(3 * self.feature_num + 6) - k_gain @ H) @ cov

                #Update all
                mu_list[i + 1] = mu[:, self.feature_num:]
                pose_list.append(np.linalg.inv(mu_list[i + 1]))
                cov_list[i + 1] = cov[-6:, -6:]

        feature_list = mu[:, :self.feature_num]
        poses_list = np.stack((pose_list), axis=-1)
        plt.scatter(feature_list[0, :],
                    feature_list[1, :],
                    label="updated feature with VISLAM")
        visualize_trajectory_2d(poses_list, path_name="VISLAM", show_ori=True)
        return poses_list
示例#39
0
 def test_multiexp(self):
     A = multisym(rnd.randn(self.k, self.m, self.m))
     e = np.zeros((self.k, self.m, self.m))
     for i in range(self.k):
         e[i] = expm(A[i])
     np_testing.assert_allclose(multiexp(A, sym=True), e)
示例#40
0
def van_loan_discretization(F, G, dt):

    """ Discretizes a linear differential equation which includes white noise
    according to the method of C. F. van Loan [1]. Given the continuous
    model

        x' =  Fx + Gu

    where u is the unity white noise, we compute and return the sigma and Q_k
    that discretizes that equation.


    Examples
    --------

        Given y'' + y = 2u(t), we create the continuous state model of

        x' = [ 0 1] * x + [0]*u(t)
             [-1 0]       [2]

        and a time step of 0.1:


        >>> F = np.array([[0,1],[-1,0]], dtype=float)
        >>> G = np.array([[0.],[2.]])
        >>> phi, Q = van_loan_discretization(F, G, 0.1)

        >>> phi
        array([[ 0.99500417,  0.09983342],
               [-0.09983342,  0.99500417]])

        >>> Q
        array([[ 0.00133067,  0.01993342],
               [ 0.01993342,  0.39866933]])

        (example taken from Brown[2])


    References
    ----------

    [1] C. F. van Loan. "Computing Integrals Involving the Matrix Exponential."
        IEEE Trans. Automomatic Control, AC-23 (3): 395-404 (June 1978)

    [2] Robert Grover Brown. "Introduction to Random Signals and Applied
        Kalman Filtering." Forth edition. John Wiley & Sons. p. 126-7. (2012)
    """


    n = F.shape[0]

    A = zeros((2*n, 2*n))

    # we assume u(t) is unity, and require that G incorporate the scaling term
    # for the noise. Hence W = 1, and GWG' reduces to GG"

    A[0:n,     0:n] = -F.dot(dt)
    A[0:n,   n:2*n] = G.dot(G.T).dot(dt)
    A[n:2*n, n:2*n] = F.T.dot(dt)

    B=expm(A)

    sigma = B[n:2*n, n:2*n].T

    Q = sigma.dot(B[0:n, n:2*n])

    return (sigma, Q)
示例#41
0
文件: gdc_gcn.py 项目: zrt/cogdl
 def _get_heat_matrix(self, adj_matrix, t=5.0):
     num_nodes = adj_matrix.shape[0]
     A_tilde = adj_matrix + np.eye(num_nodes)
     D_tilde = np.diag(1 / np.sqrt(A_tilde.sum(axis=1)))
     H = D_tilde @ A_tilde @ D_tilde
     return expm(-t * (np.eye(num_nodes) - H))
示例#42
0
               return v/norm
        if(deltap1+deltap2+deltap3+deltap4==0): #evitar que la normalización se indefina si ambos deltap son 0
          deltasum = 0.001
        else:
          deltasum = deltap1+deltap2+deltap3+deltap4
        if(rn1<deltasum):
           if(rn2<=(deltap1/deltasum)):
              vec=tongo(np.matmul(S1,vec))
           elif(rn2<=((deltap1+deltap2)/deltasum)):
              vec=tongo(np.matmul(S2,vec))
           elif(rn2<=((deltap1+deltap2+deltap3)/deltasum)):
              vec=tongo(np.matmul(S3,vec))
           else:
              vec=tongo(np.matmul(S4,vec))
        else:
           vec=tongo(np.matmul(expm(-1j*deltat*Hju),vec))
        aver_gg= np.matmul(sigmen,vec)
        aver_ee= np.matmul(sigmas,vec)
        aver_00= np.matmul(a,vec)
        aver_11= np.matmul(adag,vec)
        eqju_gg.append(np.abs(np.dot(aver_gg,aver_gg)))
        eqju_ee.append(np.abs(np.dot(aver_ee,aver_ee)))
        eqju_00.append(np.abs(np.dot(aver_00,aver_00)))
        eqju_11.append(np.abs(np.dot(aver_11,aver_11)))
        e1 = vec
        eqav_gg[n]=eqav_gg[n]+(np.abs(np.dot(aver_gg,aver_gg)))/nst
        eqav_ee[n]=eqav_ee[n]+(np.abs(np.dot(aver_ee,aver_ee)))/nst
        eqav_00[n]=eqav_00[n]+(np.abs(np.dot(aver_00,aver_00)))/nst
        eqav_11[n]=eqav_11[n]+(np.abs(np.dot(aver_11,aver_11)))/nst
    e1 = np.array([0,1,0,0])
	F = open("MathLinDiss.txt","r")
	HDISS = F.read()
	HDISS = eval(HDISS)
	HDISS=np.transpose(HDISS)

	File1 = open("MathLinDiss3.txt","r")
	HMain = File1.read()
	HMain = eval(HMain)
	Heff = np.asarray(HDISS) + np.asarray(HMain)
	Czas = []
	Evolution1 = []
	for i in range(0,1000):
		t = h * i
		Czas.append(t)
		wykladnik = np.asarray(Heff) * t
		NonUnitary = SLA.expm(wykladnik)
		NewState = mulvec(NonUnitary,InitTaon)
		Density = F0 * NewState[0] + F1 * NewState[1] + F2 * NewState[2] + F3 * NewState[3] + F4 * NewState[4] +\
		F5 * NewState[5] + F6 * NewState[6] + F7 * NewState[7] + F8 * NewState[8]
		ExpW1 = np.trace(mulmul3(Density,A1,A2))
		ExpW2 = np.trace(mulmul3(Density,A2,A3))
		ExpW3 = np.trace(mulmul3(Density,A3,A4))
		ExpW4 = np.trace(mulmul3(Density,A4,A5))
		ExpW5 = np.trace(mulmul3(Density,A5,A1))
		suma = ExpW1 + ExpW2 + ExpW3 + ExpW4 + ExpW5
		Evolution1.append(suma)
	Evolution.append(Evolution1)
 
stop = time.time()
czas = stop-start
print("czas = {}".format(czas))
    def _decompose_(self, qubits):
        """The goal is to effect a rotation around an axis in the XY plane in
        each of three orthogonal 2-dimensional subspaces.

        First, the following basis change is performed:
            0000 ↦ 0001        0001 ↦ 1111
            1111 ↦ 0010        1110 ↦ 1100
                               0010 ↦ 0000
            0110 ↦ 0101        1101 ↦ 0011
            1001 ↦ 0110        0100 ↦ 0100
            1010 ↦ 1001        1011 ↦ 0111
            0101 ↦ 1010        1000 ↦ 1000
            1100 ↦ 1101        0111 ↦ 1011
            0011 ↦ 1110

        Note that for each 2-dimensional subspace of interest, the first two
        qubits are the same and the right two qubits are different. The desired
        rotations thus can be effected by a complex-version of a partial SWAP
        gate on the latter two qubits, controlled on the first two qubits. This
        partial SWAP-like gate can  be decomposed such that it is parameterized
        solely by a rotation in the ZY plane on the third qubit. These are the
        `individual_rotations`; call them U0, U1, U2.

        To decompose the double controlled rotations, we use four other
        rotations V0, V1, V2, V3 (the `combined_rotations`) such that
            U0 = V3 · V1 · V0
            U1 = V3 · V2 · V1
            U2 = V2 · V0
        """

        if self._is_parameterized_():
            return NotImplemented

        individual_rotations = [
            la.expm(0.5j * self.exponent * np.array([
                [np.real(w), 1j * s * np.imag(w)],
                [-1j * s * np.imag(w), -np.real(w)]]))
            for s, w in zip([1, -1, -1], self.weights)]

        combined_rotations = {}
        combined_rotations[0] = la.sqrtm(np.linalg.multi_dot([
                la.inv(individual_rotations[1]),
                individual_rotations[0],
                individual_rotations[2]]))
        combined_rotations[1] = la.inv(combined_rotations[0])
        combined_rotations[2] = np.linalg.multi_dot([
                la.inv(individual_rotations[0]),
                individual_rotations[1],
                combined_rotations[0]])
        combined_rotations[3] = individual_rotations[0]

        controlled_rotations = {i: cirq.ControlledGate(
            cirq.MatrixGate(combined_rotations[i], qid_shape=(2,)))
            for i in range(4)}

        a, b, c, d = qubits

        basis_change = list(cirq.flatten_op_tree([
            cirq.CNOT(b, a),
            cirq.CNOT(c, b),
            cirq.CNOT(d, c),
            cirq.CNOT(c, b),
            cirq.CNOT(b, a),
            cirq.CNOT(a, b),
            cirq.CNOT(b, c),
            cirq.CNOT(a, b),
            [cirq.X(c), cirq.X(d)],
            [cirq.CNOT(c, d), cirq.CNOT(d, c)],
            [cirq.X(c), cirq.X(d)],
            ]))

        controlled_rotations = list(cirq.flatten_op_tree([
            controlled_rotations[0](b, c),
            cirq.CNOT(a, b),
            controlled_rotations[1](b, c),
            cirq.CNOT(b, a),
            cirq.CNOT(a, b),
            controlled_rotations[2](b, c),
            cirq.CNOT(a, b),
            controlled_rotations[3](b, c)
            ]))

        controlled_swaps = [
            [cirq.CNOT(c, d), cirq.H(c)],
            cirq.CNOT(d, c),
            controlled_rotations,
            cirq.CNOT(d, c),
            [cirq.inverse(op) for op in reversed(controlled_rotations)],
            [cirq.H(c), cirq.CNOT(c, d)],
            ]

        return [basis_change, controlled_swaps, basis_change[::-1]]
示例#45
0
 def lrsp(p):
     fbetaA=tauxcontacper(betaA,p,cbeta,T)
     fbetaS=tauxcontacper(betaS,p,cbeta,T)
     a=matcroissance(fbetaA,fbetaS,piS,gammaS,gammaA)
     phiT=np.dot(expm(a(0.99*T)*(1-p)*T),expm(a(0.01*T)*p*T))
     return((np.log(spectralrad(phiT)))/T)
示例#46
0
    def _grad_theta(self, dis, real_state):

        G_list = self.getGen()

        Q = real_state

        phi = dis.getPhi()
        psi = dis.getPsi()

        grad = list()

        zero_state = get_zero_state(self.size)

        try:
            A = expm((-1 / lamb) * phi)
        except Exception:
            print('grad_gen -1/lamb:\n', (-1 / lamb))
            print('size of phi:\n', phi.shape)

        try:
            B = expm((1 / lamb) * psi)
        except Exception:
            print('grad_gen 1/lamb:\n', (1 / lamb))
            print('size of psi:\n', psi.shape)

        for G, j in zip(G_list, range(len(self.qc_list))):

            fake_state = np.matmul(G, zero_state)

            grad_g_psi = list()
            grad_g_phi = list()
            grad_g_reg = list()

            for i in range(self.qc_list[j].depth):

                grad_i = self.qc_list[j].get_grad_mat_rep(i)

                # for psi term
                grad_g_psi.append(0)

                # for phi term
                fake_grad = np.matmul(grad_i, zero_state)
                g_Gi = self.prob_gen[j] * (
                    np.matmul(fake_grad, fake_state.getH()) +
                    np.matmul(fake_state, fake_grad.getH()))
                grad_g_phi.append(np.trace(np.matmul(g_Gi, phi)))

                # for reg term
                term1 = np.trace(np.matmul(A, g_Gi)) * np.trace(np.matmul(
                    B, Q))
                term2 = np.trace(np.matmul(A, np.matmul(g_Gi, np.matmul(B,
                                                                        Q))))
                term3 = np.trace(np.matmul(g_Gi, np.matmul(A, np.matmul(Q,
                                                                        B))))
                term4 = np.trace(np.matmul(B, g_Gi)) * np.trace(np.matmul(
                    A, Q))

                tmp_reg_grad = lamb / np.e * (cst1 * term1 - cst2 * term2 -
                                              cst2 * term3 + cst3 * term4)
                grad_g_reg.append(tmp_reg_grad)

            g_psi = np.asarray(grad_g_psi)
            g_phi = np.asarray(grad_g_phi)
            g_reg = np.asarray(grad_g_reg)

            grad.append(np.real(g_psi - g_phi - g_reg))

        # print("grad:\n",grad)
        return grad
 def heat_kernel(s):
     h_of_t = linalg.expm(-1 * (t - s) * scriptLaplacian)[
         subgraph.vertices.index(x)][subgraph.vertices.index(y)]
     return h_of_t
示例#48
0
 def u_true(self, x, t):
     return -self.sigma(x).cpu().numpy().T.dot(
         expm(self.A.cpu().numpy().T *
              (self.T - t)).dot(self.alpha.cpu().numpy()) *
         np.ones(x.shape).T)
示例#49
0
 def test_multiexp_singlemat(self):
     # A is a positive definite matrix
     A = rnd.randn(self.m, self.m)
     A = A + A.T
     np_testing.assert_allclose(multiexp(A, sym=True), expm(A))
示例#50
0
def test_expm(rng):
    pytest.importorskip('scipy')
    import scipy.linalg as linalg
    for a in [np.eye(3), rng.randn(10, 10)]:
        assert np.allclose(linalg.expm(a), expm(a))
    dict(name="sigx0_w", value=1.0),
    dict(name="sigx0_i", value=1.0)
]

reg = Regressor(TwTi_RoRi(parameters))
reg.ss.jacobian = False
reg.ss.update()

dt = 600
hold = 'foh'
Ad, B0d, B1d, Qd = reg.ss.discretization(dt, hold)

AA = np.zeros((reg.ss.Nx + reg.ss.Nu, reg.ss.Nx + reg.ss.Nu))
AA[:reg.ss.Nx, :reg.ss.Nx] = reg.ss.A
AA[:reg.ss.Nx, reg.ss.Nx:] = reg.ss.B
AAd = expm(AA * dt)
Ad2 = AAd[:reg.ss.Nx, :reg.ss.Nx]
B0d2 = AAd[:reg.ss.Nx, reg.ss.Nx:]

assert np.allclose(Ad, Ad2)
assert np.allclose(B0d, B0d2)
print('\nTest zero order hold: OK')

AA = np.zeros((reg.ss.Nx + 2 * reg.ss.Nu, reg.ss.Nx + 2 * reg.ss.Nu))
AA[:reg.ss.Nx, :reg.ss.Nx] = reg.ss.A
AA[:reg.ss.Nx, reg.ss.Nx:reg.ss.Nx + reg.ss.Nu] = reg.ss.B
AA[:reg.ss.Nx, -reg.ss.Nu:] = reg.ss.B
AA[reg.ss.Nx:reg.ss.Nx + reg.ss.Nu, -reg.ss.Nu:] = np.eye(reg.ss.Nu)
# AA[-reg.ss.Nu:, -2 * reg.ss.Nu:-reg.ss.Nu] = -np.eye(reg.ss.Nu)
AA[-reg.ss.Nu:, -reg.ss.Nu:] = np.eye(reg.ss.Nu)
示例#52
0
def exchange_and_transition_matrices(n, exch_mat_opt, exch_range, f_vec=None):
    """
    Compute the exchange matrix and the Markov chain transition matrix from given number of objects

    :param n: the number of objects
    :type n: int
    :param exch_mat_opt: option for the exchange matrix, "s" = standard, "u" = uniform, "d" = diffusive, "r" = ring
    :type exch_mat_opt: str
    :param exch_range: range of the exchange matrix
    :type exch_range: int
    :param f_vec: an optional vector of relative weight
    :type f_vec: list[int]
    :return: the (n x n) exchange matrix and the (n x n) markov transition matrix
    :rtype: (numpy.ndarray, numpy.ndarray)
    """

    # To manage other options
    if exch_mat_opt not in ["s", "u", "d", "r"]:
        warnings.warn(
            "Exchange matrix option ('exch_mat_opt') not recognized, setting it to 's'"
        )
        exch_mat_opt = "s"

    # Weights if None
    if f_vec is None:
        f_vec = np.ones(n) / n
    # Computation regarding options
    if exch_mat_opt == "s":
        exch_mat = np.abs(np.add.outer(np.arange(n),
                                       -np.arange(n))) <= exch_range
        np.fill_diagonal(exch_mat, 0)
        exch_mat = exch_mat / np.sum(exch_mat)
    elif exch_mat_opt == "u":
        adj_mat = np.abs(np.add.outer(np.arange(n),
                                      -np.arange(n))) <= exch_range
        np.fill_diagonal(adj_mat, 0)
        g_vec = np.sum(adj_mat, axis=1) / np.sum(adj_mat)
        k_vec = f_vec / g_vec
        b_mat = np.array([[min(v1, v2) for v2 in k_vec]
                          for v1 in k_vec]) * adj_mat / np.sum(adj_mat)
        exch_mat = np.diag(f_vec) - np.diag(np.sum(b_mat, axis=1)) + b_mat
    elif exch_mat_opt == "d":
        adj_mat = np.abs(np.add.outer(np.arange(n), -np.arange(n))) <= 1
        np.fill_diagonal(adj_mat, 0)
        l_adj_mat = np.diag(np.sum(adj_mat, axis=1)) - adj_mat
        pi_outer_mat = np.outer(np.sqrt(f_vec), np.sqrt(f_vec))
        phi_mat = (l_adj_mat / pi_outer_mat) / np.trace(l_adj_mat)
        exch_mat = expm(-exch_range * phi_mat) * pi_outer_mat
    else:
        exch_mat = np.abs(np.add.outer(np.arange(n),
                                       -np.arange(n))) <= exch_range
        if exch_range == 1:
            np.fill_diagonal(exch_mat, 0)
        else:
            to_remove = np.abs(np.add.outer(np.arange(n),
                                            -np.arange(n))) <= (exch_range - 1)
            exch_mat = exch_mat ^ to_remove
        exch_mat = exch_mat / np.sum(exch_mat)

    w_mat = (exch_mat / np.sum(exch_mat, axis=1)).T

    # Return the transition matrix
    return exch_mat, w_mat
示例#53
0
    def integrate(self, t_final, atol=1e-18, rtol=1e-10):
        """
        Adaptively integrate the system of equations assuming self.t and self.y set the initial value.
        :param t_final: (scalar) the final time to be reached.
        :param atol: the absolute tolerance parameter
        :param rtol: the relative tolerance parameter
        :return: current value of y
        """
        if not np.isscalar(t_final):
            raise ValueError(
                "t_final must be a scalar. If t_final is iterable consider using "
                "the list comprehension [integrate(t) for t in times].")

        sign_dt = np.sign(t_final - self.t)

        # Loop util the final time moment is reached
        while sign_dt * (t_final - self.t) > 0:
            #######################################################################################
            #
            #           Description of numerical methods
            #
            #   A formal solution of the system of linear ode y'(t) = M(t) y(t) reads as
            #
            #       y(t) = T exp[ \int_{t_init}^{t_fin} M(\tau) d\tau ] y(t_init)
            #
            #   where T exp is a Dyson time-ordered exponent. Hence,
            #
            #       y(t + dt) = T exp[ \int_{t}^{t+dt} M(\tau) d\tau ] y(t).
            #
            #   Dropping the time ordering operation leads to the cubic error
            #
            #       y(t + dt) = exp[ \int_{t}^{t+dt} M(\tau) d\tau ] y(t) + O( dt^3 ).
            #
            #   Employing the mid-point rule for the integration also leads to the cubic error
            #
            #       y(t + dt) = exp[  M(t + dt / 2) dt ] y(t) + O( dt^3 ).
            #
            #   Therefore, we finally get the linear equation w.r.t. unknown y(t + dt) [note y(t) is known]
            #
            #       exp[  -M(t + dt / 2) dt ] y(t + dt) = y(t) + O( dt^3 ),
            #
            #   which can be solved by scipy.optimize.nnls ensuring the non-negativity constrain for y(t + dt).
            #
            #######################################################################################

            # Initial guess for the time-step
            dt = 0.25 / norm(self.M(self.t, *self.M_args))

            # time step must not take as above t_final
            dt = sign_dt * min(dt, abs(t_final - self.t))

            # Loop until optimal value of dt is not found (adaptive step size integrator)
            while True:
                M = self.M(self.t + 0.5 * dt, *self.M_args)
                M = np.array(M, copy=False)
                M *= -dt

                new_y, residual = nnls(expm(M), self.y)

                # Adaptive step termination criterion
                if np.allclose(residual, 0., rtol, atol):
                    # residual is small it seems we got the solution

                    # Additional check: If M is a transition rate matrix,
                    # then the sum of y must be preserved
                    if np.allclose(M.sum(axis=0), 0., rtol, atol):

                        # exit only if sum( y(t+dt) ) = sum( y(t) )
                        if np.allclose(sum(self.y), sum(new_y), rtol, atol):
                            break
                    else:
                        # M is not a transition rate matrix, thus exist
                        break

                if np.allclose(dt, 0., rtol, atol):
                    # print waring if dt is very small
                    print(
                        "Warning in nnl_ode: adaptive time-step became very small." \
                        "The numerical result may not be trustworthy."
                    )
                    break
                else:
                    # half the time-step
                    dt *= 0.5

            # the dt propagation is successfully completed
            self.t += dt
            self.y = new_y

        return self.y
示例#54
0
    def _grad_beta(self, gen, real_state):

        psi = self.getPsi()
        phi = self.getPhi()

        zero_state = get_zero_state(gen.size)

        G_list = gen.getGen()
        P = np.zeros_like(G_list[0])
        for p, g in zip(gen.prob_gen, G_list):
            state_i = np.matmul(g, zero_state)
            P += p * (np.matmul(state_i, state_i.getH()))

        Q = real_state

        try:
            A = expm((-1 / lamb) * phi)
        except Exception:
            print('grad_beta -1/lamb:\n', (-1 / lamb))
            print('size of phi:\n', phi.shape)

        try:
            B = expm((1 / lamb) * psi)
        except Exception:
            print('grad_beta 1/lamb:\n', (1 / lamb))
            print('size of psi:\n', psi.shape)

        grad_psi_term = np.zeros_like(self.beta, dtype=complex)
        grad_phi_term = np.zeros_like(self.beta, dtype=complex)
        grad_reg_term = np.zeros_like(self.beta, dtype=complex)

        for type in range(len(self.herm)):
            gradphi = self._grad_phi(type)

            gradpsi_list = list()
            gradphi_list = list()
            gradreg_list = list()

            for grad_phi in gradphi:
                gradpsi_list.append(0)

                gradphi_list.append(np.trace(np.matmul(P, grad_phi)))

                tmp_grad_phi = -1 / lamb * np.matmul(grad_phi, A)

                term1 = np.trace(np.matmul(tmp_grad_phi, P)) * np.trace(
                    np.matmul(B, Q))
                term2 = np.trace(
                    np.matmul(tmp_grad_phi, np.matmul(P, np.matmul(B, Q))))
                term3 = np.trace(
                    np.matmul(P, np.matmul(tmp_grad_phi, np.matmul(Q, B))))
                term4 = np.trace(np.matmul(B, P)) * np.trace(
                    np.matmul(tmp_grad_phi, Q))

                gradreg_list.append(
                    lamb / np.e * (cst1 * term1 - cst2 * term2 - cst2 * term3 +
                                   cst3 * term4))

            # calculate grad of psi term
            grad_psi_term[:, type] += np.asarray(gradpsi_list)

            # calculate grad of phi term
            grad_phi_term[:, type] += np.asarray(gradphi_list)

            # calculate grad of reg term
            grad_reg_term[:, type] += np.asarray(gradreg_list)

        # print("grad_beta:\n",np.real(grad_psi_term - grad_phi_term - grad_reg_term))
        return np.real(grad_psi_term - grad_phi_term - grad_reg_term)
示例#55
0
def exact_update_method(J,rhov,dt = 1e-4):
    rhov = np.dot(spla.expm(J*dt),rhov)
    assert_probability_mass_conserved(rhov)
    return rhov
示例#56
0
NUM_POINTS = 100

X0s = []
Xs = []
for ii in range(NUM_POINTS):
    # X0 = np.random.uniform(low=-1, high=1, size=(2))
    X0 = np.dot(vec, np.random.uniform(low=-1, high=1, size=(2)))
    X0s.append(X0)
    Xs.append([])

for step in range(steps):
    t = Ts[step]

    # eat = np.dot(vec, np.dot(la.expm(val * t), invvec))
    eat = la.expm(A * t)

    for ii in range(NUM_POINTS):
        X = np.dot(eat, X0s[ii])
        Xs[ii].append(X)

##########################################

points = np.linspace(-100, 100, 100)

print("basis 0: ", vec[0][0], vec[1][0])
basis0_x = points * vec[0][0]
basis0_y = points * vec[1][0]

print("basis 1: ", vec[0][1], vec[1][1])
basis1_x = points * vec[0][1]
示例#57
0
def get_random_transformation(dim):
    herm = get_random_hermitian(dim)
    T = expm(1.0j * herm)
    return T
示例#58
0
 def test_logm_nearly_singular(self):
     M = np.array([[1e-100]])
     expected_warning = _matfuncs_inv_ssq.LogmNearlySingularWarning
     L, info = _assert_warns(expected_warning, logm, M, disp=False)
     E = expm(L)
     assert_allclose(E, M, atol=1e-14)
示例#59
0
 def lrsp(p):
     betaa=tauxcontacper(betaamax,p,cbeta,T)
     betai=tauxcontacper(betaimax,p,cbeta,T)
     a=matcroissance(betaa,betai,pii,gammai,gammaa)
     phiT=np.dot(expm(a(0.01*T)*p*T),expm(a(0.99*T)*(1-p)*T))
     return((np.log(spectralrad(phiT)))/T)
示例#60
0
    def _grad_prob(self, dis, real_state):

        G_list = self.getGen()

        psi = dis.getPsi()
        phi = dis.getPhi()

        Q = real_state

        zero_state = get_zero_state(self.size)

        try:
            A = expm((-1 / lamb) * phi)
        except Exception:
            print('grad_gen -1/lamb:\n', (-1 / lamb))
            print('size of phi:\n', phi.shape)

        try:
            B = expm((1 / lamb) * psi)
        except Exception:
            print('grad_gen 1/lamb:\n', (1 / lamb))
            print('size of psi:\n', psi.shape)

        grad_psi_term = np.zeros_like(self.W_classical, dtype=complex)
        grad_phi_term = np.zeros_like(self.W_classical, dtype=complex)
        grad_reg_term = np.zeros_like(self.W_classical, dtype=complex)

        # (#mix,(#output,#input))
        grad = np.zeros((self.num_to_mix, self.num_output, self.num_input))

        for k in range(self.num_output):
            for l in range(self.num_input):
                for i in range(self.num_to_mix):
                    tmp = 0
                    for j in range(self.num_output):

                        # to calculate {\partial prob_gen[i]}{\partial W_classical[b][a]}
                        # \[\frac{{\partial {g_i}}}{{\partial {z_j}}} \cdot \frac{{\partial {z_j}}}{{\partial {w_{ba}}}}\]
                        # because j can be different so we fix i,k,l
                        if j == i:
                            if j == k:
                                tmp_equal = (
                                    self.prob_gen[i] -
                                    self.prob_gen[i]**2) * self.input[l]
                                tmp += tmp_equal
                            else:
                                tmp_equal = 0
                                tmp += tmp_equal
                        else:
                            if j == k:
                                tmp_notequal = -self.prob_gen[
                                    i] * self.prob_gen[j] * self.input[l]
                                tmp += tmp_notequal
                            else:
                                tmp_notequal = 0
                                tmp += tmp_notequal
                    grad[i][k][l] = tmp

        for b in range(self.num_to_mix):
            for a in range(self.num_input):

                gW = np.zeros(G_list[0].shape, dtype=complex)

                for i in range(self.num_to_mix):
                    state_i = np.matmul(G_list[i], zero_state)
                    gW += grad[i][b][a] * (np.matmul(state_i, state_i.getH()))

                # calculate grad of psi term
                grad_psi_term[b][a] = 0

                # calculate grad of phi term
                grad_phi_term[b][a] = np.trace(np.matmul(gW, phi))

                # calculate grad of reg term
                term1 = np.trace(np.matmul(A, gW)) * np.trace(np.matmul(B, Q))
                term2 = np.trace(np.matmul(A, np.matmul(gW, np.matmul(B, Q))))
                term3 = np.trace(np.matmul(gW, np.matmul(A, np.matmul(Q, B))))
                term4 = np.trace(np.matmul(B, gW)) * np.trace(np.matmul(A, Q))

                grad_reg_term[b][a] = lamb / np.e * (
                    cst1 * term1 - cst2 * term2 - cst2 * term3 + cst3 * term4)

        grad_w = np.real(grad_psi_term - grad_phi_term - grad_reg_term)

        return grad_w