Exemplo n.º 1
0
def is_psd(M: np.ndarray, strict=False, tol=1e-8) -> bool:
    """
    Tests if matrix is positive semi-definite

    Parameters
    ----------
    M: (N, N) ndarray
        Matrix to be tested for positive semi-definiteness

    strict: bool
        If True, tests for posotive definiteness

    tol: float
        Numeric tolerance to check for equality

    Returns
    -------
    bool
        True if matrix is positive (semi-)definite, else False
    """
    if isinstance(M, (int, float)):
        return M >= 0

    M = np.asarray(M)
    if not is_symmetric(M, tol):
        return False

    if strict:
        return (la.eigvalsh(M) > 0).all()
    else:
        return (la.eigvalsh(M) >= 0).all()
Exemplo n.º 2
0
def FBFMEB(engine,app):
    '''
    This method calculates the energy spectrums of the spin excitations.
    '''
    path,ne=app.path,min(app.ne or engine.nmatrix,engine.nmatrix)
    if path is not None:
        bz,reciprocals=engine.basis.BZ,engine.lattice.reciprocals
        if not isinstance(path,HP.BaseSpace): path=bz.path(HP.KMap(reciprocals,path) if isinstance(path,str) else path,mode='Q')
        result=np.zeros((path.rank(0),ne+1))
        result[:,0]=path.mesh(0) if path.mesh(0).ndim==1 else np.array(range(path.rank(0)))
        engine.log<<'%s: '%path.rank(0)
        for i,paras in enumerate(path('+')):
            engine.log<<'%s%s'%(i,'..' if i<path.rank(0)-1 else '')
            m=engine.matrix(scalefree=app.scalefree,scaleint=app.scaleint,**paras)
            result[i,1:]=nl.eigvalsh(m)[:ne] if app.method=='eigvalsh' else HM.eigsh(m,k=ne,evon=False)
        engine.log<<'\n'
    else:
        result=np.zeros((2,ne+1))
        result[:,0]=np.array(range(2))
        m=engine.matrix(scalefree=app.scalefree,scaleint=app.scaleint)
        result[0,1:]=nl.eigvalsh(m)[:ne] if app.method=='eigvalsh' else HM.eigsh(m,k=ne,evon=False)
        result[1,1:]=result[0,1:]
    name='%s_%s%s'%(engine.tostr(mask=path.tags),app.name,app.suffix)
    if app.savedata: np.savetxt('%s/%s.dat'%(engine.dout,name),result)
    if app.plot: app.figure('L',result,'%s/%s'%(engine.dout,name))
    if app.returndata: return result
Exemplo n.º 3
0
def Eigenvalues(Hgesamt):
	eigenwerte=[]
	eigenwerte2=[]
	for l in range(N/2):
		block=Hgesamt[l*8:8+l*8:,l*8:8+l*8:]
		eigenwerte.append(LA.eigvalsh(block))
		eigenwerte2.extend(LA.eigvalsh(block))
	#print(eigenwerte2)
	return(eigenwerte)
Exemplo n.º 4
0
def linear_algebra():
    """ Use the `numpy.linalg` library to do Linear Algebra 
        For a reference on math, see 'Linear Algebra explained in four pages'
        http://minireference.com/static/tutorials/linear_algebra_in_4_pages.pdf
    """

    ### Setup two vectors
    x = np.array([1, 2, 3, 4])
    y = np.array([5, 6, 7, 8])

    ### Vector Operations include addition, subtraction, scaling, norm (length),
    # dot product, and cross product
    print np.vdot(x, y)  # Dot product of two vectors


    ### Setup two arrays / matrices
    a = np.array([[1, 2],
                  [3, 9]])
    b = np.array([[2, 4],
                  [5, 6]])


    ### Dot Product of two arrays
    print np.dot(a, b)


    ### Solving system of equations (i.e. 2 different equations with x and y)
    print LA.solve(a, b)


    ### Inverse of a matrix undoes the effects of the Matrix
    # The matrix multipled by the inverse matrix returns the 
    # 'identity matrix' (ones on the diagonal and zeroes everywhere else); 
    # identity matrix is useful for getting rid of the matrix in some equation
    print LA.inv(a)  # return inverse of the matrix
    print "\n"


    ### Determinant of a matrix is a special way to combine the entries of a
    # matrix that serves to check if matrix is invertible (!=0) or not (=0)
    print LA.det(a)  # returns the determinant of the array
    print "\n"  # e.g. 3, means that it is invertible


    ### Eigenvectors is a special set of input vectors for which the action of
    # the matrix is described as simple 'scaling'.  When a matrix is multiplied
    # by one of its eigenvectors, the output is the same eigenvector multipled
    # by a constant (that constant is the 'eigenvalue' of the matrix)
    print LA.eigvals(a)  # comput the eigenvalues of a general matrix
    print "\n"
    print LA.eigvalsh(a)  # Comput the eigenvalues of a Hermitian or real symmetric matrix
    print "\n"
    print LA.eig(a)  # return the eigenvalues for a square matrix
    print "\n"
    print LA.eigh(a)  # return the eigenvalues or eigenvectors of a Hermitian or symmetric matrix
    print "\n"
Exemplo n.º 5
0
    def do(self, a, b):
        # note that eigenvalue arrays returned by eig must be sorted since
        # their order isn't guaranteed.
        ev = linalg.eigvalsh(a, 'L')
        evalues, evectors = linalg.eig(a)
        evalues.sort(axis=-1)
        assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype))

        ev2 = linalg.eigvalsh(a, 'U')
        assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype))
Exemplo n.º 6
0
def info_rate(G_PRE,H,Sigma_Z): 
    #G_PRE is a list for precoding matrices for all users
    #H is a list for channel matrices
    G1, G2 = G_PRE
    
    R_users = list()
    for u in [0,1]: # 2 users
        m, n = H[u].shape
        R_total = array(0)
        for i in range(n):
            #G = G_RX[u]
            
            #R_v1 = identity(n)
            #R_v2 = identity(n)
            R_v1 = zeros((n,n))
            R_v1[0,0] = 1
            R_v2 = zeros((n,n))
            R_v2[1,1] = 1

            Sigma_X = \
            G1.dot(R_v1).dot(G1.conj().transpose()) + \
            G2.dot(R_v2).dot(G2.conj().transpose())
            
            Sigma_Y = ( 
            H[u].dot(Sigma_X).dot(H[u].conj().transpose()) + 
            Sigma_Z 
            )
            
            if   u==0: # if user 1
                R_v1[i,i] = 0
            elif u==1: # if user 2
                R_v2[i,i] = 0

            Sigma_X_V = \
            G1.dot(R_v1).dot(G1.conj().transpose()) + \
            G2.dot(R_v2).dot(G2.conj().transpose())
            
            Sigma_Y_V = ( 
            H[u].dot(Sigma_X_V).dot(H[u].conj().transpose()) + 
            Sigma_Z 
            )
            
            H_Y = sum(log(eigvalsh(Sigma_Y)))
            H_Y_V = sum(log(eigvalsh(Sigma_Y_V)))
            R = H_Y - H_Y_V    
    
            R_total = R_total + R
            
        R_users.append(R_total)          
    return R_users
Exemplo n.º 7
0
def info_rate_ild_fast( H_TX, H_CH, H_RX, P_vec, SCHEME, SIM ):
    N0 = SIM['N0'];
    dt = SIM['dt'];
    REAL_DIM_PER_SYM = SIM['REAL_DIM_PER_SYM'];
    T_TRANSMISSION = SIM['T_TRANSMISSION'];
    
    # Power allocation (uniform)
    Sigma_X_NORMALIZED, layer = power_alloc(H_TX, SCHEME, SIM);
    K_prime = len(layer); #K_prime = SHCEME['K_prime']
    
    # Compute mutual informal layer by layer
    R_vec_per_layer = zeros((K_prime,len(P_vec)));
    for k in range(K_prime):
        sigma2_N = N0/2 * REAL_DIM_PER_SYM * (1/dt);  # DEPENDS ON WHETHER NOISE IS REAL (PASSBAND) OR COMPLEX (BASEBAND)
        #Sigma_N = sigma2_N * eye(length(layer{k}));
        
        H_RX_k = H_RX[:,layer[k]];
        H_RX_k, s, V = svd(H_RX_k); # ensure that H_RX_k is orthonormal
        H_RXCHTX = H_RX_k.transpose().dot(H_CH).dot(H_TX);
        
        
        Sigma_X = Sigma_X_NORMALIZED;     #XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        
        Sigma_S = H_RXCHTX.dot(Sigma_X).dot(H_RXCHTX.transpose());
        
        #Sigma_Z = H_RX_k.transpose().dot(sigma2_N).dot(H_RX_k);
        
        Sigma_X_bar = Sigma_X;
        Sigma_X_bar[:,layer[k]] = 0;
        Sigma_X_bar[layer[k],:] = 0;
        
        Sigma_S_bar = H_RXCHTX.dot(Sigma_X_bar).dot(H_RXCHTX.transpose());
    
        EIG_S = eigvalsh(Sigma_S);
        EIG_S_bar = eigvalsh(Sigma_S_bar);
        
        I_vec = zeros(len(P_vec));
        loop_index = 0;
        for P in P_vec:
            #I = sum(log(eig( P*Sigma_S+Sigma_Z ))) - sum(log(eig( P*Sigma_S_bar+Sigma_Z )));
            I = sum(log( P * EIG_S + sigma2_N )) - sum(log( P * EIG_S_bar + sigma2_N ));
            I_vec[loop_index] = I;
            loop_index = loop_index + 1;
        
        R_vec_per_layer[k,:] = I_vec / 2 * REAL_DIM_PER_SYM / T_TRANSMISSION;

    
    R_vec = sum(R_vec_per_layer,0); # sum the rows (sum along the columns)
    
    return R_vec
Exemplo n.º 8
0
    def _fa_paf(self, smc = True):
        cor = self.cor.copy()
        if smc:
            np.fill_diagonal(cor, utils.SMC(cor))
        eig_val1 = la.eigvalsh(self.cor)
        eig_val1.sort()
        comm = np.sum(np.diag(cor))
        err = comm
        comm_list = []
        i = 0
        while err > self.lower:
            eig_val, eig_vec = utils.eigenh_sorted(cor)
            if (self.n_factors > 1):
                loadings = eig_vec[:, :self.n_factors].dot(
                    np.diag(np.sqrt(eig_val[:self.n_factors])))
            else:
                loadings = eig_vec[:, 0] * np.sqrt(eig_val[0])

            model = loadings.dot(loadings.T)
            new = np.diag(model)
            comm1 = np.sum(new)
            np.fill_diagonal(cor, new)
            err = np.abs(comm - comm1)
            if np.iscomplex(err):
                print('Imaginary eigenvalue condition'
                      ' occurred!')
                break
            comm = comm1
            comm_list.append(comm1)
            i += 1
            if i > 1000:
                print('maximum iteration exceeded')
                err = 0

        self.loadings = loadings
Exemplo n.º 9
0
Arquivo: bgmm.py Projeto: cindeem/nipy
def normal_eval(mu, P, x, dP=None):
    """
    Probability of x under normal(mu,inv(P))

    Parameters
    ----------
    mu: array of shape (n): the mean parameter
    P: array of shape (n,n): the precision matrix 
    x: array of shape (n): the data to be evaluated

    Returns
    -------
    (float) the density
    """
    p = np.size(mu)
    if dP==None:
        dP = np.prod(eigvalsh(P))
    mu = np.reshape(mu,(1,p))
    w0 = np.log(dP)-p*np.log(2*np.pi)
    w0 /= 2               
    x = np.reshape(x,(1,p))
    q = np.dot(np.dot(mu-x,P),(mu-x).T)
    w = w0 - q/2
    L = np.exp(w)
    return np.squeeze(L)
Exemplo n.º 10
0
def compactness(im):
    from numpy import array, meshgrid, arange, shape, mean, zeros
    from numpy import outer, sum, max, linalg
    from numpy import sqrt
    from math import exp

    (h, w) = shape(im)
    (X, Y) = meshgrid(arange(w), arange(h))
    x = X.flatten()
    y = Y.flatten()
    wgts = im[y, x]
    sw = sum(wgts)
    if sw == 0:
        return 1
    wgts /= sw
    wpts = array([wgts * x, wgts * y])
    wmean = sum(wpts, 1)
    N = len(x)
    s = array([x, y])
    P = zeros((2, 2))
    for i in range(0, N):
        P += wgts[i] * outer(s[:, i], s[:, i])
    P = P - outer(wmean, wmean)

    det = abs(linalg.det(P))
    if det > 0:
        v = linalg.eigvalsh(P)
        v = abs(v)
        r = min(v) / max(v)
        return 100.0 * sqrt(r / det)
    else:
        return 0.0
Exemplo n.º 11
0
  def __call__(self, function, point, state):
    """
    Computes Goldfeld step 
    """
    g = function.gradient(point)
    state['gradient'] = g
    G = function.hessian(point)
    state['hessian'] = G
    c = 1e-8 # is this one best?
    
    d0 = None

    try:
        L = cholesky(G)
        # reach here => isPositiveDefinite = True
        step = n_solve(L.T, n_solve(L, -g))
    except:
        # isPositiveDefinite = False
        G_eigvals = eigvalsh(G)
        minEig = min(G_eigvals)
        if minEig < 0:
            shift = -minEig + c
            
            #avoiding sparse case with big nVars
            for i in xrange(point):  G[i,i] += shift
                
        step = n_solve(G, -g)

    state['direction'] = step
    return step
Exemplo n.º 12
0
def calculate_gyration_tensor_parameters(points):
    """
    Calculates the gyration tensor parameters R_g^2, η, c, κ from a list of
    all points inside a cavity.
     - R_g^2 is the squared gyration radius
     - η is the asphericity
     - c is the acylindricity
     - κ is the anisotropy
    """

    points = np.array(points, dtype=np.float)
    mean = np.mean(points, axis=0)
    points -= mean

    gyration_tensor = np.zeros((3, 3))
    for i in range(3):
        for j in range(i, 3):
            gyration_tensor[i, j] = np.dot(points[:, i], points[:, j])
            gyration_tensor[j, i] = gyration_tensor[i, j]
    # cell volume is constant, cavity volume is proportional to len(points)
    gyration_tensor /= len(points)

    eigvals = list(sorted(la.eigvalsh(gyration_tensor), reverse=True))

    squared_gyration_radius = sum(eigvals)
    if squared_gyration_radius > 0:
        asphericity = (eigvals[0] - 0.5 * (eigvals[1] + eigvals[2])) / squared_gyration_radius
        acylindricity = (eigvals[1] - eigvals[2]) / squared_gyration_radius
        anisotropy = (asphericity ** 2 + 0.75 * acylindricity ** 2) ** 0.5
    else:
        asphericity = 0
        acylindricity = 0
        anisotropy = 0
    return mean, squared_gyration_radius, asphericity, acylindricity, anisotropy
Exemplo n.º 13
0
def array_compactness(im):
        '''
        calculate the compactness of a 2D array. Each element of the 2D array
        should be proportional to the score of that pixel in the overall scoring scheme
        . '''
        from numpy import array,meshgrid,arange,shape,mean,zeros
        from numpy import outer,sum,max,linalg
        from numpy import sqrt
        from math import exp
        (h,w) = shape(im)
        (X,Y) = meshgrid(arange(w),arange(h))
        x = X.flatten()
        y = Y.flatten()
        wgts = im[y,x]
        sw = sum(wgts)
        if sw == 0:
                return 1
        wgts /= sw
        wpts = array([wgts*x, wgts*y])
        wmean = sum(wpts, 1)
        N = len(x)
        s = array([x,y])
        P = zeros((2,2))
        for i in range(0,N):
                P += wgts[i]*outer(s[:,i],s[:,i])
        P = P - outer(wmean,wmean);

        det = abs(linalg.det(P))
        if (det <= 0):
                return 0.0
        v = linalg.eigvalsh(P)
        v = abs(v)
        r = min(v)/max(v)
        return 100.0*sqrt(r/det)
Exemplo n.º 14
0
  def f(k):
    kp = kpgen(k) # get kpoint
    hk = hk_gen(kp) # generate hamiltonian
#    es,ew = lgs.eigsh(csc_matrix(hk),k=4,which="LM",sigma=0.0)
    es = lg.eigvalsh(hk) # get eigenvalues
    g = np.min(es[es>0.]) - np.max(es[es<0.])
    return g  # return gap
Exemplo n.º 15
0
def eigenvalues_hadamard(matrix1, matrix2):
    """Computes the Hadamard product of 2 matrices. See
    https://www.johndcook.com/blog/2018/10/10/hadamard-product/ for details

    :param matrix1: first matrix
    :param matrix2: second matrix
    :return: lower and upper
    """

    matrix1 = array(matrix1)  # as arrays
    matrix2 = array(matrix2)

    eig_a = eigvalsh(matrix1)  # eigenvalues (optimized for Hermitian matrices)
    eig_b = eigvalsh(matrix2)

    return eig_a, eig_b
Exemplo n.º 16
0
    def unweighted_likelihood_(self, x):
        """
        return the likelihood of each data for each component
        the values are not weighted by the component weights

        Parameters
        ----------
        x: array of shape (n_samples,self.dim)
           the data used in the estimation process

        Returns
        -------
        like, array of shape(n_samples,self.k)
          unweighted component-wise likelihood
        """
        n = x.shape[0]
        like = np.zeros((n, self.k))

        for k in range(self.k):
            # compute the data-independent factor first
            w = -np.log(2 * np.pi) * self.dim
            m = np.reshape(self.means[k], (1, self.dim))
            b = self.precisions[k]
            if self.prec_type == "full":
                w += np.log(eigvalsh(b)).sum()
                dx = m - x
                q = np.sum(np.dot(dx, b) * dx, 1)
            else:
                w += np.sum(np.log(b))
                q = np.dot((m - x) ** 2, b)
            w -= q
            w /= 2
            like[:, k] = np.exp(w)
        return like
Exemplo n.º 17
0
def main():

    L = 42
    t = 1
    h_0 = t*np.eye(L, k=1)                                      ##Upper triagonal of hopping in y-direction
    h_0[0,L-1] = np.conjugate(t)                                ##Periodic boundary condition in -y-direction
    h_0 = h_0 + h_0.conj().T                                    ##Full matrix for one slice in y
    h_0 = np.kron(np.eye(L), h_0)                               ##Put all slices together

    diag = np.eye(L, k=1)
    period = np.eye(L, k=L-1)

##Now only the hopping between 1d slices is missing the for loop will add these

#    ps = np.array([1, 2, 6, 8, 12, 14, 16, 21])
    ps = np.linspace(0, 100, 50)                               ##All fluxes
    spectrum = []

    for p in np.nditer(ps):
        t_mag = np.exp(2j*np.pi*np.arange(L)*p/L)               ##Peierls phase for all fluxes
        X = t*np.diag(t_mag)
        X = np.kron(diag, X) + np.kron(period, X.conj().T)
        X = X + X.conj().T                                      ##Construct the hopping matrix in x-direction between 1d slices
        H = h_0 + X                                             ##Add the two hamiltonian parts
        spectrum.append(LA.eigvalsh(H))                         ##Get eigenvalues for each flux

    ax = plt.subplot(111)
    ps = ps/L
    ax.plot(ps, spectrum, marker='.', markersize=0.1, linestyle='None', color='k')

    plt.show()
Exemplo n.º 18
0
def get_vn_entropy(psi, spin, N=None, mode='1spin', base='e'):
    """
    Compute the von Neumann entropy for a given state "psi".
    "psi" must be a column vector. Sparsity is optional.
    Available modes: "1spin" for the entanglement entropy for only the first
    spin, "eqsplit" for the entanglement entropy for an evenly split system.
    Available bases: "e" for natural log, "2" for log2 and "10" for log10.
    """
    if N is None and mode == 'eqsplit':
        raise Exception("N cannot be 'None' for mode='eqsplit'.")

    if mode == '1spin':
        red_rho_A = red_rho_A_1spin(psi, spin)
    elif mode == 'eqsplit':
        red_rho_A = red_rho_eqsplit(psi, spin, N)

    lamb = eigvalsh(red_rho_A.todense())  # Eigenvalues of the reduced matrix.
    S_AB_terms = []
    for i in range(np.shape(red_rho_A)[0]):
        if abs(lamb[i]) < 1e-6:
            # lim a->0 (alog(a)) = 0. It also removes some minuscule negative
            #  lambda values resulting from rounding errors.
            S_AB_terms.append(0)
        else:
            if base == 'e':
                S_AB_terms.append(-lamb[i] * np.log(lamb[i]))
            elif base == '2' or base == 2:
                S_AB_terms.append(-lamb[i] * np.log2(lamb[i]))
            elif base == '10' or base == 10:
                S_AB_terms.append(-lamb[i] * np.log10(lamb[i]))
            else:
                raise Exception('Available bases are "e", "2" and "10"')

    return float(np.sum(S_AB_terms))
Exemplo n.º 19
0
def genMulCov(size, numberOfCov, low, upper, mode, portion = 0.05):
    S_set = []   
    Cov_set = []
    minEVal_set = [] 
#    low = abs(low)
#    upper = abs(upper)
    m = size/3
    mm = m/2
#    print m, mm
    S_init = np.zeros((size,size))
    for k in range(numberOfCov):
        S = np.zeros((size,size))
        if k == 0:
            S = genInvCov(size, low, upper, portion)
            if mode == 5:      
                ind_zero = np.where(spy.sparse.rand(m, size-m, 0.5).todense() == 0)
                value = np.multiply((np.random.randint(2, size = (m, size -m)) - 0.5)*2,(low + (upper - low)*np.random.rand(m,size -m)))
                value[ind_zero] = 0
                hub = value
                S[:m, m:size] = hub
                S[m:size, :m] = hub.T        
                minEVal_set.append(alg.eigvalsh(S)[0])
            S_init = S
        elif mode == 3: #'laplacian'
            ind1 = range(m)
            ind2 = np.random.permutation(m)
            S = np.copy(S_init)
            S[ind1, :] = S[ind2, :]            
            S[:, ind1] = S[:, ind2]
        elif mode  == 5: #'perturbation'
            S = np.copy(S_init)
            ind_zero = np.where(spy.sparse.rand(mm, size-mm, 0.5).todense() == 0)
            pert = np.multiply((np.random.randint(2, size = (mm, size -mm)) - 0.5)*2,(low + (upper - low)*np.random.rand(mm,size -mm)))
            pert[ind_zero] = 0 
            S[:mm, mm:size] = pert
            S[mm:size, :mm] = pert.T
            minEVal_set.append(alg.eigvalsh(S)[0])
        else:
#            print 'Activate normal mode'
            S = genInvCov(size, low, upper, portion)
        S_set.append(S)
    
    for k in range(numberOfCov):
        if mode == 5:
            S_set[k] = S_set[k] + (0.1 - min(minEVal_set))*np.identity(size)
        Cov_set.append(alg.inv(S_set[k]))
    return S_set, Cov_set   
Exemplo n.º 20
0
 def prinvals(self):
     if self.type != SYMTENSOR:
         return None
     if self._prin is None:
         sx, sy, sz, txy, tyz, txz = self._tensor_components()
         s3, s2, s1 = sorted(eigvalsh([[sx,txy,txz],[txy,sy,tyz],[txz,tyz,sz]]))
         self._prin = array([s3, s2, s1])
     return self._prin
Exemplo n.º 21
0
 def do(self, a, b):
     # note that eigenvalue arrays must be sorted since
     # their order isn't guaranteed.
     ev = linalg.eigvalsh(a)
     evalues, evectors = linalg.eig(a)
     ev.sort(axis=-1)
     evalues.sort(axis=-1)
     assert_almost_equal(ev, evalues)
    def do(self, a):
        ev = linalg.eigvalsh(a)
        # flip resulting eigenvalue array, since they are returned in
        # reverse order from the values given by linal.eig
        ev = ev[::-1]

        evalues, evectors = linalg.eig(a)
        assert_almost_equal(ev, evalues)
Exemplo n.º 23
0
def gaussian_latitudes(n):
    """Construct latitudes and latitude bounds for a Gaussian grid.

    Args:

    * n:
        The Gaussian grid number (half the number of latitudes in the
        grid.

    Returns:
        A 2-tuple where the first element is a length `n` array of
        latitudes (in degrees) and the second element is an `(n, 2)`
        array of bounds.

    """
    if abs(int(n)) != n:
        raise ValueError('n must be a non-negative integer')
    nlat = 2 * n
    # Create the coefficients of the Legendre polynomial and construct the
    # companion matrix:
    cs = np.array([0] * nlat + [1], dtype=np.int)
    cm = legcompanion(cs)
    # Compute the eigenvalues of the companion matrix (the roots of the
    # Legendre polynomial) taking advantage of the fact that the matrix is
    # symmetric:
    roots = la.eigvalsh(cm)
    roots.sort()
    # Improve the roots by one application of Newton's method, using the
    # solved root as the initial guess:
    fx = legval(roots, cs)
    fpx = legval(roots, legder(cs))
    roots -= fx / fpx
    # The roots should exhibit symmetry, but with a sign change, so make sure
    # this is the case:
    roots = (roots - roots[::-1]) / 2.
    # Compute the Gaussian weights for each interval:
    fm = legval(roots, cs[1:])
    fm /= np.abs(fm).max()
    fpx /= np.abs(fpx).max()
    weights = 1. / (fm * fpx)
    # Weights should be symmetric and sum to two (unit weighting over the
    # interval [-1, 1]):
    weights = (weights + weights[::-1]) / 2.
    weights *= 2. / weights.sum()
    # Calculate the bounds from the weights, still on the interval [-1, 1]:
    bounds1d = np.empty([nlat + 1])
    bounds1d[0] = -1
    bounds1d[1:-1] = -1 + weights[:-1].cumsum()
    bounds1d[-1] = 1
    # Convert the bounds to degrees of latitude on [-90, 90]:
    bounds1d = np.rad2deg(np.arcsin(bounds1d))
    bounds2d = np.empty([nlat, 2])
    bounds2d[:, 0] = bounds1d[:-1]
    bounds2d[:, 1] = bounds1d[1:]
    # Convert the roots from the interval [-1, 1] to latitude values on the
    # interval [-90, 90] degrees:
    latitudes = np.rad2deg(np.arcsin(roots))
    return latitudes, bounds2d
Exemplo n.º 24
0
def restricted_lovasz_DIMACS(G):
    H=nx.complement(o.Instance(G))
    A=nx.adjacency_matrix(H)
    import numpy as np
    B=np.eye(len(H.nodes()))
    from numpy.linalg import eigvalsh
    L=list(eigvalsh(A+B))
    L.sort(reverse=True)
    return int(np.floor(sum([L[k] for k in range(0,1)])))
Exemplo n.º 25
0
    def __init__(self,initmean,initvar,transgain,transnoise,measgain,measnoise):

        # Check the initial mean.
        try:
            numstate,=numpy.shape(initmean)
        except ValueError:
            raise Exception('Initial mean must be a vector.')

        # Check the initial variance.
        if numpy.shape(initvar)!=(numstate,numstate):
            raise Exception('Initial variance must be a {}-by-{} matrix.'.format(numstate,numstate))
        if not numpy.allclose(numpy.transpose(initvar),initvar):
            raise Exception('Initial variance matrix must be symmetric.')
        try:
            cholfact=linalg.cholesky(initvar)
        except linalg.LinAlgError:
            raise Exception('Initial variance matrix must be positive-definite.')

        # Check the transition gain.
        if numpy.ndim(transgain)!=2 or numpy.shape(transgain)!=(numstate,numstate):
            raise Exception('Transition gain must be a {}-by-{} matrix.'.format(numstate,numstate))

        # Check the transition noise.
        if numpy.ndim(transnoise)!=2 or numpy.shape(transnoise)!=(numstate,numstate):
            raise Exception('Transition noise must be a {}-by-{} matrix.'.format(numstate,numstate))
        if not numpy.allclose(numpy.transpose(transnoise),transnoise):
            raise Exception('Transition noise matrix must be symmetric.')
        if numpy.any(linalg.eigvalsh(transnoise)<0.0):
            raise Exception('Transition noise matrix must be positive-semi-definite.')

        # Check the measurement gain.
        try:
            numobs,numcol=numpy.shape(measgain)
        except ValueError:
            raise Exception('Measurement gain must be a matrix.')
        if numcol!=numstate:
            raise Exception('Measurement gain matrix must have {} columns.'.format(numstate))

        # Check the measurement noise.
        if numpy.ndim(measnoise)!=2 or numpy.shape(measnoise)!=(numobs,numobs):
            raise Exception('Measurement noise must be a {}-by-{} matrix.'.format(numobs,numobs))
        if not numpy.allclose(numpy.transpose(measnoise),measnoise):
            raise Exception('Measurement noise matrix must be symmetric.')
        try:
            cholfact=linalg.cholesky(measnoise)
        except linalg.LinAlgError:
            raise Exception('Measurement noise matrix must be positive-definite.')

        # Set the model.
        self.initmean=numpy.asarray(initmean)
        self.initvar=numpy.asarray(initvar)
        self.transgain=numpy.asarray(transgain)
        self.transnoise=numpy.asarray(transnoise)
        self.measgain=numpy.asarray(measgain)
        self.measnoise=numpy.asarray(measnoise)

        self.__size__=numstate,numobs
Exemplo n.º 26
0
def info_rate_expand( H_TX, H_CH, H_RX, P_vec, SCHEME, SIM ):
    #return R_vec

    #[U, S, V] = svd(H_RX);
    #svalue = diag(S);
    #SELECTED_COLS_IDX = find(svalue > max(svalue) * 1e-4);
    #H_RX_REDUCED = U(:,SELECTED_COLS_IDX);
    
    [U, svalue, V] = svd(H_RX);
    IS_ABOVE_THRESHOLD = svalue > max(svalue) * 1e-4;
    SELECTED_COLS_IDX = [i for i in range(len(IS_ABOVE_THRESHOLD)) if IS_ABOVE_THRESHOLD[i]==True];
    H_RX_REDUCED = U[:,SELECTED_COLS_IDX];
    
    #%-------------------------------------------------------
    N0 = SIM['N0'];
    dt = SIM['dt'];
    REAL_DIM_PER_SYM = SIM['REAL_DIM_PER_SYM'];
    T_TRANSMISSION = SIM['T_TRANSMISSION'];
    
    
    Sigma_X_NORMALIZED, layer = power_alloc(H_TX, SCHEME, SIM);
    
    H_RXCHTX = H_RX_REDUCED.transpose().dot(H_CH).dot(H_TX);
    
    sigma2_N = N0/2 * REAL_DIM_PER_SYM * (1/dt);  # DEPENDS ON WHETHER NOISE IS REAL (PASSBAND) OR COMPLEX (BASEBAND)
    #trace(Sigma_N)*dt
    
    Sigma_Z = H_RX_REDUCED.transpose().dot(sigma2_N).dot(H_RX_REDUCED);
    trace(Sigma_Z)*dt
    HYX = sum(log(eigvalsh(Sigma_Z))) #H(Y|X)
        
    I_vec = zeros(len(P_vec));
    loop_index = 0;
    for P in P_vec:
        Sigma_X = P * Sigma_X_NORMALIZED; #XXXXXXXXXXXXXXXXXXXXXXXXXXXX
        Sigma_S = H_RXCHTX.dot(Sigma_X).dot(H_RXCHTX.transpose()); 
        HY = sum(log(eigvalsh(Sigma_S + Sigma_Z)))
        I = HY - HYX;
        I_vec[loop_index] = I;
        loop_index = loop_index + 1;
    
    R_vec = I_vec / 2 * REAL_DIM_PER_SYM / T_TRANSMISSION;

    return R_vec
Exemplo n.º 27
0
def coth_poles_pade(N, use_scipy=False):
  """ Calculates the simple poles of the [N-1, N] Padé approximant to the
      hyperbolic cotangent function and the corresponding residues.
      The implementation follows
        Hu et al. JCP 134, 244106 (2011).
      Remarks: Pole at x = 0 is NOT included!
        Only poles with non-negative imaginary part are returned. The other
        ones can be obtained by either -poles or conj(poles).
      Arguments:
       'N' -- number of expansion terms (integer)
      Return values:
       '(i·xi, eta)'
           -- tuple containing sorted np.array 'i·xi' of the purely imaginary
              poles and a sorted array 'eta' of the corresponding residues
      The hyperbolic cotangent is then approximated by

        coth(x) ≅ 1/x + sum( eta_j / (x - i xi_j) + eta_j / (x + i xi_j) )
  """
  # set-up the symmetric matrices A (2N,2N) and B (2N-1,2N-1)
  i = 1 + np.arange(2*N - 1)
  d = 1. / np.sqrt((2*i + 1) * (2*i + 3))
  A = np.diag(d, 1) + np.diag(d, -1)
  B = A[1:, 1:]
  # find eigenvalues of matrices A and B
  if not use_scipy:
    AZ = la.eigvalsh(A)
    BZ = la.eigvalsh(B)
  else:
    AZ = sla.eigvalsh(A, overwrite_a=True)  # gives no segfault
    BZ = sla.eigvalsh(B, overwrite_a=True)
  BZ = np.delete(-np.sort(-BZ), N - 1)  # kick out the root at zero
  xi = np.sort(1. / AZ[AZ > 0.]); xi2 = np.square(xi)
  zeta = 1. / BZ[BZ > 0.]; zeta2 = np.square(zeta)
  nx = np.newaxis
  eta = (np.hstack([zeta2[nx, :] - xi2[:, nx], np.ones(N)[:, nx]]) /
         ((xi2[nx, :] - xi2[:, nx]) *
          (1. - np.identity(N)) + np.identity(N))).prod(-1)
  # The 'hstack' with 'ones' in the numerator of the product compensates for
  # smaller size of 'zeta' (N-1) compared to 'xi' (N). The 'identity'
  # construction in the denominator sets the main diagonal to unity, because
  # the product xi2_k - xi2_j is supposed to run over all k that are not equal
  # to j.
  eta *= N * (N + 1.5)
  return 1j * xi, eta  # return poles and residues
Exemplo n.º 28
0
        def ml_function(Psi, S, q):
            sc = np.diag(1 / np.sqrt(Psi))
            Sstar = sc.dot(S).dot(sc)
            eig_val = la.eigvalsh(Sstar)
            eig_val.sort()
            eig_val = eig_val[::-1]
            e = eig_val[-(eig_val.shape[0] - q):]
            e = np.sum(np.log(e) - e) - q + S.shape[0]

            return -e
Exemplo n.º 29
0
Arquivo: mimo.py Projeto: ghozlan/mimo
def info_rate(G_RX,H,Sigma_Z):
    m, n = H.shape
    R_total = array(0)
    for i in range(n):
        G = G_RX[i,:].reshape((1,m))

        R_xx = identity(n)
        Sigma_Y = G.dot( H.dot(R_xx).dot(H.conj().transpose()) + Sigma_Z ).dot( G.conj().transpose() ) 
        
        R_xx_tilde = R_xx
        R_xx_tilde[i,i] = 0
        Sigma_Y_X = G.dot( H.dot(R_xx_tilde).dot(H.conj().transpose()) + Sigma_Z ).dot( G.conj().transpose() ) 

        H_Y = sum(log(eigvalsh(Sigma_Y)))
        H_Y_X = sum(log(eigvalsh(Sigma_Y_X)))
        R = H_Y - H_Y_X    

        R_total = R_total + R
    return real(R_total)
Exemplo n.º 30
0
def genInvCov(size, low = 0 , upper = 0.6, portion = 0.05):
    S = np.zeros((size,size))
    G = GenRndGnm(PUNGraph, size, int((size*(size-1))*portion))
    for EI in G.Edges():
        value = (np.random.randint(2) - 0.5)*2*(low + (upper - low)*np.random.rand(1)[0])  
        S[EI.GetSrcNId(), EI.GetDstNId()] = value
    S = S + S.T
    vals = alg.eigvalsh(S)
    S = S + (0.1 - vals[0])*np.identity(size)
    return np.matrix(S)
Exemplo n.º 31
0
    cov_root = file_root + 'CovMatricesAll/'
    c2 = np.diag(np.loadtxt(cov_root + 'c2_n%d_m%d_11_%s.txt' % (n, m, index)))
    c3 = np.loadtxt(cov_root + 'c3_n%d_m%d_1,11_%s.txt' % (n, m, index))
    c4 = np.loadtxt(cov_root + 'c4_n%d_m%d_11,11_%s.txt' % (n, m, index))

    # Now symmetrize and return matrices
    return c2, 0.5 * (c3 + c3.T), 0.5 * (c4 + c4.T)


# Load in full theoretical matrices
print("Loading best estimate of covariance matrix")
c2, c3, c4 = load_matrices('full')

# Check matrix convergence
from numpy.linalg import eigvalsh
eig_c4 = eigvalsh(c4)
eig_c2 = eigvalsh(c2)
if min(eig_c4) < -1. * min(eig_c2):
    print(
        "4-point covariance matrix has not converged properly via the eigenvalue test. Exiting"
    )
    sys.exit()

# Compute full covariance matrices and precision
full_cov = c4 + c3 * alpha + c2 * alpha**2.
n_bins = len(c4)

# Compute full precision matrix
print("Computing the full precision matrix estimate:")
# Load in partial theoretical matrices
c2s, c3s, c4s = [], [], []
Exemplo n.º 32
0
def get_prinmom(moi):
    prinmom = la.eigvalsh(moi)
    return prinmom
Exemplo n.º 33
0
m = -1.
tx = 0.5
t = 0.5
k0 = np.pi/3.*0.
n=3
mg=0.9
rr=5.
#fig1 = plt.figure(1)
# axes.titlesize: large   # fontsize of the axes title
# axes.labelsize: medium  # fontsize of the x any y labels
for i, val in enumerate(k1):
    h1 = -(m * (2. - np.cos(k3)) + 2 * tx * (np.cos(k1[i]) - np.cos(k0)-mg)) * pm(1) - 2 * t * np.sin(k3) * pm(3)
    h2 = +m * pm(1) / 2 + t * pm(2) / 1j
    h3 = +m * pm(1) / 2 - t * pm(2) / 1j
    b = tridiag(h1, h2, h3, N)  # this creates 2N*2N hamiltonian that describes the system for a GIVEN k_3
    w = LA.eigvalsh(b)  # this calculates the eigen values aka energies of the system for given k_3
    #plt.plot(np.ones((np.size(w))) * k1[i], w, 'ko',
             # markersize=0.1)  # this puts dots for each eigen value for a given k_3

n=np.arange(1,6,1)
fig2 = plt.figure(2)
for pi, val in enumerate(n):
    aa=250+n[pi]
    plt.subplot(aa)
    #super conductivity
    for i, val in enumerate(k1):
        h1=-(m*(2.-np.cos(k3))+2*tx*(np.cos(k1[i])-np.cos(k0)-mg))*pm(1)-2*t*np.sin(k3)*pm(3)
        h2=+m*pm(1)/2+t*pm(2)/1j
        h3=+m*pm(1)/2-t*pm(2)/1j
        H=tridiag(h1,h2,h3,N) #this creates 2N*2N hamiltonian that describes the system for a GIVEN k_3
        hm1=-(m*(2.-np.cos(-k3))+2*tx*(np.cos(-k1[i])-np.cos(k0)-mg))*pm(1)-2*t*np.sin(-k3)*pm(3)
Exemplo n.º 34
0
def myeigvalsh(v):
    return eigvalsh(v.reshape(N, N)).flatten()
Exemplo n.º 35
0
a = np.arange(0.0, 1.01, 0.01)
E1 = []
E2 = []
E3 = []
E4 = []

for i in range(101):
    x = a[i]  # x är a
    y = 1 - x  # y är b
    # print(x)

    H = np.array([[2 * x + y, 0, 0, 0], [0, -y, 2 * y, 0], [0, 2 * y, -y, 0],
                  [0, 0, 0, -2 * x + y]])

    E = LA.eigvalsh(H)  # eigvalsh beräknar egenvärden till hermiteska matriser

    E1.append(E[0])
    E2.append(E[1])
    E3.append(E[2])
    E4.append(E[3])

    # print(x,E[0])

# print(E)

plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k')
plt.plot(a, E1, 'r-', label='E_1')
plt.plot(a, E2, 'g-', label='E_2')
plt.plot(a, E3, 'b-', label='E_3')
plt.plot(a, E4, 'k-', label='E_4')
Exemplo n.º 36
0
    def __init__(self, y, x, w, method='full', epsilon=0.0000001):
        # set up main regression variables and spatial filters
        self.y = y
        self.x = x
        self.n, self.k = self.x.shape
        self.method = method
        self.epsilon = epsilon
        #W = w.full()[0]
        #Wsp = w.sparse
        ylag = ps.lag_spatial(w, y)
        # b0, b1, e0 and e1
        xtx = spdot(self.x.T, self.x)
        xtxi = la.inv(xtx)
        xty = spdot(self.x.T, self.y)
        xtyl = spdot(self.x.T, ylag)
        b0 = np.dot(xtxi, xty)
        b1 = np.dot(xtxi, xtyl)
        e0 = self.y - spdot(x, b0)
        e1 = ylag - spdot(x, b1)
        methodML = method.upper()
        # call minimizer using concentrated log-likelihood to get rho
        if methodML in ['FULL', 'LU', 'ORD']:
            if methodML == 'FULL':
                W = w.full()[0]     # moved here
                res = minimize_scalar(lag_c_loglik, 0.0, bounds=(-1.0, 1.0),
                                      args=(
                                          self.n, e0, e1, W), method='bounded',
                                      tol=epsilon)
            elif methodML == 'LU':
                I = sp.identity(w.n)
                Wsp = w.sparse  # moved here
                res = minimize_scalar(lag_c_loglik_sp, 0.0, bounds=(-1.0,1.0),
                                      args=(self.n, e0, e1, I, Wsp),
                                      method='bounded', tol=epsilon)
            elif methodML == 'ORD':
                # check on symmetry structure
                if w.asymmetry(intrinsic=False) == []:
                    ww = symmetrize(w)
                    WW = ww.todense()
                    evals = la.eigvalsh(WW)
                else:
                    W = w.full()[0]     # moved here
                    evals = la.eigvals(W)
                res = minimize_scalar(lag_c_loglik_ord, 0.0, bounds=(-1.0, 1.0),
                                      args=(
                                          self.n, e0, e1, evals), method='bounded',
                                      tol=epsilon)
        else:
            # program will crash, need to catch
            print("{0} is an unsupported method".format(methodML))
            self = None
            return

        self.rho = res.x[0][0]

        # compute full log-likelihood, including constants
        ln2pi = np.log(2.0 * np.pi)
        llik = -res.fun - self.n / 2.0 * ln2pi - self.n / 2.0
        self.logll = llik[0][0]

        # b, residuals and predicted values

        b = b0 - self.rho * b1
        self.betas = np.vstack((b, self.rho))   # rho added as last coefficient
        self.u = e0 - self.rho * e1
        self.predy = self.y - self.u

        xb = spdot(x, b)

        self.predy_e = inverse_prod(
            w.sparse, xb, self.rho, inv_method="power_exp", threshold=epsilon)
        self.e_pred = self.y - self.predy_e

        # residual variance
        self.sig2 = self.sig2n  # no allowance for division by n-k

        # information matrix
        a = -self.rho * W
        np.fill_diagonal(a, 1.0)
        ai = la.inv(a)
        wai = np.dot(W, ai)
        tr1 = np.trace(wai)

        wai2 = np.dot(wai, wai)
        tr2 = np.trace(wai2)

        waiTwai = np.dot(wai.T, wai)
        tr3 = np.trace(waiTwai)

        wpredy = ps.lag_spatial(w, self.predy_e)
        wpyTwpy = np.dot(wpredy.T, wpredy)
        xTwpy = spdot(x.T, wpredy)

        # order of variables is beta, rho, sigma2

        v1 = np.vstack(
            (xtx / self.sig2, xTwpy.T / self.sig2, np.zeros((1, self.k))))
        v2 = np.vstack(
            (xTwpy / self.sig2, tr2 + tr3 + wpyTwpy / self.sig2, tr1 / self.sig2))
        v3 = np.vstack(
            (np.zeros((self.k, 1)), tr1 / self.sig2, self.n / (2.0 * self.sig2 ** 2)))

        v = np.hstack((v1, v2, v3))

        self.vm1 = la.inv(v)  # vm1 includes variance for sigma2
        self.vm = self.vm1[:-1, :-1]  # vm is for coefficients only
Exemplo n.º 37
0
    def _p_mixed(self, state, sub_sys_A, return_rdm=None):
        """
		This function calculates the eigenvalues of the reduced density matrix.
		It will first calculate the partial trace of the full density matrix and
		then diagonalizes it to get the eigenvalues. It will automatically choose
		the subsystem with the smaller hilbert space to do the diagonalization in order
		to reduce the calculation time but will only return the desired reduced density
		matrix. 
		"""
        N = self.N
        sps = self.sps

        N_A = len(sub_sys_A)
        N_B = N - N_A

        proj = self.get_proj(_dtypes[state.dtype.char])
        state = state.transpose((2, 0, 1))

        Ns_full = proj.shape[0]
        n_states = state.shape[0]

        gen = (proj * s * proj.H for s in state[:])

        proj_state = _np.zeros((n_states, Ns_full, Ns_full),
                               dtype=_dtypes[state.dtype.char])

        for i, s in enumerate(gen):
            proj_state[i, ...] += s[...]

        rdm_A, p_A = None, None
        rdm_B, p_B = None, None

        if return_rdm == 'both':
            rdm_A, rdm_B = _lattice_partial_trace_mixed(proj_state,
                                                        sub_sys_A,
                                                        N,
                                                        sps,
                                                        return_rdm="both")

            p_A = eigvalsh(rdm_A) + _np.finfo(rdm_A.dtype).eps
            p_B = eigvalsh(rdm_B) + _np.finfo(rdm_B.dtype).eps

        elif return_rdm == 'A':
            rdm_A, rdm_B = _lattice_partial_trace_mixed(proj_state,
                                                        sub_sys_A,
                                                        N,
                                                        sps,
                                                        return_rdm="A")
            p_A = eigvalsh(rdm_A) + _np.finfo(rdm_A.dtype).eps

        elif return_rdm == 'B':
            rdm_A, rdm_B = _lattice_partial_trace_mixed(proj_state,
                                                        sub_sys_A,
                                                        N,
                                                        sps,
                                                        return_rdm="B")
            p_B = eigvalsh(rdm_B) + _np.finfo(rdm_B.dtype).eps

        else:
            rdm_A, rdm_B = _lattice_partial_trace_mixed(proj_state,
                                                        sub_sys_A,
                                                        N,
                                                        sps,
                                                        return_rdm="A")
            p_A = eigvalsh(rdm_A) + _np.finfo(rdm_A.dtype).eps

        return p_A, p_B, rdm_A, rdm_B
Exemplo n.º 38
0
    
    if (m + n) % 2 == 0:
        return 0.0
    
    return -8*a*m*n/(pi**2*((m**2-n**2)**2))

# construct the matrix, note that m & n in these expressions are one less than
# in the original formulas because python numbering starts at 0, not 1
Hhat = empty([N, N])

for m in range(N):
    for n in range(N):
        Hhat[m, n] = H(m+1, n+1)
        
# calculate the values and the vectors
value = eigvalsh(Hhat)

# print the results
for n in range(to_print):
    print("E[", n+1, "] = ", value[n]/q, "eV")

if part in ['e']:
    
    clf
    colors = ['r-', 'g-', 'b-']
    wave = linspace(0, L, 100)
    x = linspace(0, L, 100)
    
    for n in range(3):
        # plot each wave function value for each i in x
        for i in range(len(wave)):
Exemplo n.º 39
0
    def band_structure(self, path_kc, modes=False, born=False, verbose=True):
        """Calculate phonon dispersion along a path in the Brillouin zone.

        The dynamical matrix at arbitrary q-vectors is obtained by Fourier
        transforming the real-space force constants. In case of negative
        eigenvalues (squared frequency), the corresponding negative frequency
        is returned.

        Frequencies and modes are in units of eV and Ang/sqrt(amu),
        respectively.

        Parameters:

        path_kc: ndarray
            List of k-point coordinates (in units of the reciprocal lattice
            vectors) specifying the path in the Brillouin zone for which the
            dynamical matrix will be calculated.
        modes: bool
            Returns both frequencies and modes when True.
        born: bool
            Include non-analytic part given by the Born effective charges and
            the static part of the high-frequency dielectric tensor. This
            contribution to the force constant accounts for the splitting
            between the LO and TO branches for q -> 0.
        verbose: bool
            Print warnings when imaginary frequncies are detected.

        """

        assert self.D_N is not None
        if born:
            assert self.Z_avv is not None
            assert self.eps_vv is not None

        # Lattice vectors -- ordered as illustrated in class docstring
        R_cN = self.lattice_vectors()

        # Dynamical matrix in real-space
        D_N = self.D_N

        # Lists for frequencies and modes along path
        omega_kl = []
        u_kl = []

        # Reciprocal basis vectors for use in non-analytic contribution
        reci_vc = 2 * pi * la.inv(self.atoms.cell)
        # Unit cell volume in Bohr^3
        vol = abs(la.det(self.atoms.cell)) / units.Bohr**3

        for q_c in path_kc:

            # Add non-analytic part
            if born:
                # q-vector in cartesian coordinates
                q_v = np.dot(reci_vc, q_c)
                # Non-analytic contribution to force constants in atomic units
                qdotZ_av = np.dot(q_v, self.Z_avv).ravel()
                C_na = (4 * pi * np.outer(qdotZ_av, qdotZ_av) /
                        np.dot(q_v, np.dot(self.eps_vv, q_v)) / vol)
                self.C_na = C_na / units.Bohr**2 * units.Hartree
                # Add mass prefactor and convert to eV / (Ang^2 * amu)
                M_inv = np.outer(self.m_inv_x, self.m_inv_x)
                D_na = C_na * M_inv / units.Bohr**2 * units.Hartree
                self.D_na = D_na
                D_N = self.D_N + D_na / np.prod(self.N_c)

            # if np.prod(self.N_c) == 1:
            #
            #     q_av = np.tile(q_v, len(self.indices))
            #     q_xx = np.vstack([q_av]*len(self.indices)*3)
            #     D_m += q_xx

            # Evaluate fourier sum
            phase_N = np.exp(-2.j * pi * np.dot(q_c, R_cN))
            D_q = np.sum(phase_N[:, np.newaxis, np.newaxis] * D_N, axis=0)

            if modes:
                omega2_l, u_xl = la.eigh(D_q, UPLO='U')
                # Sort eigenmodes according to eigenvalues (see below) and
                # multiply with mass prefactor
                u_lx = (self.m_inv_x[:, np.newaxis] *
                        u_xl[:, omega2_l.argsort()]).T.copy()
                u_kl.append(u_lx.reshape((-1, len(self.indices), 3)))
            else:
                omega2_l = la.eigvalsh(D_q, UPLO='U')

            # Sort eigenvalues in increasing order
            omega2_l.sort()
            # Use dtype=complex to handle negative eigenvalues
            omega_l = np.sqrt(omega2_l.astype(complex))

            # Take care of imaginary frequencies
            if not np.all(omega2_l >= 0.):
                indices = np.where(omega2_l < 0)[0]

                if verbose:
                    print('WARNING, %i imaginary frequencies at '
                          'q = (% 5.2f, % 5.2f, % 5.2f) ; (omega_q =% 5.3e*i)'
                          % (len(indices), q_c[0], q_c[1], q_c[2],
                             omega_l[indices][0].imag))

                omega_l[indices] = -1 * np.sqrt(np.abs(omega2_l[indices].real))

            omega_kl.append(omega_l.real)

        # Conversion factor: sqrt(eV / Ang^2 / amu) -> eV
        s = units._hbar * 1e10 / sqrt(units._e * units._amu)
        omega_kl = s * np.asarray(omega_kl)

        if modes:
            return omega_kl, np.asarray(u_kl)

        return omega_kl
Exemplo n.º 40
0
    def update_prim_var_by_PALM(self,
                                W_init=None,
                                H_init=None,
                                max_iter=1000,
                                tol=1e-1,
                                verbose=False):
        '''
        This function alternatively updates the primal variables in a Gauss-Seidel fasion.
        Each update is performed using the proximal gradient method
        Input:
            k           ------ the outer iteration number
            W_init      ------ the initialization for W
            H_init      ------ the initialization for H
            max_iter    ------ the max number of iterations for PALM
            tol         ------ the tolerance for stopping PALM
        '''
        if W_init is None or H_init is None:
            raise ValueError(
                'Error: inner iterations by PLAM are lack of initializations!')

        (ha, hb) = H_init.shape
        start_time = time.time()
        #H_j_pre, W_j_pre, H_j_cur, W_j_cur = np.asmatrix(np.copy(H_init)), np.asmatrix(np.copy(W_init)), np.asmatrix(np.copy(H_init)), np.asmatrix(np.copy(W_init))
        H_j_pre, W_j_pre = H_init, W_init
        tmp = self.rho * self.all_1_mat + (self.nu - self.rho) * self.I_ha
        end_time = time.time()
        self.time_used += end_time - start_time

        for j in range(max_iter):
            # update H and W by proximal gradient method respectively
            start_time = time.time()
            Hessian = 2 * W_j_pre.transpose() * W_j_pre / self.n_factor + tmp
            #egenvals = LA.eigvalsh(Hessian)
            t = 0.51 * LA.eigvalsh(Hessian)[ha - 1]
            #t = 0.51 * LA.norm(Hessian, 'fro')
            grad_H_pre = Hessian * H_j_pre - 2 * W_j_pre.transpose(
            ) * self.data_mat / self.n_factor
            #H_j_cur = np.maximum(0, H_j_pre - grad_H_pre / t)
            H_j_cur = np.maximum(0, H_j_pre - grad_H_pre / t)

            Hessian = H_j_cur * H_j_cur.transpose()
            #c = 0.5 * LA.norm(Hessian, 'fro')
            c = 0.51 * LA.eigvalsh(Hessian)[ha - 1]
            grad_W_pre = W_j_pre * Hessian - self.data_mat * H_j_cur.transpose(
            )
            #W_j_cur = np.maximum(0, W_j_pre - grad_W_pre / c)
            if self.W_bound:
                W_j_cur = np.minimum(self.max_val,
                                     np.maximum(0, W_j_pre - grad_W_pre / c))
            else:
                W_j_cur = np.maximum(0, W_j_pre - grad_W_pre / c)

            end_time = time.time()
            self.time_used += end_time - start_time

            # check the convergence
            H_j_change = LA.norm(H_j_cur - H_j_pre, 'fro') / LA.norm(
                H_j_pre, 'fro')
            W_j_change = LA.norm(W_j_cur - W_j_pre, 'fro') / LA.norm(
                W_j_pre, 'fro')

            # update the pres
            H_j_pre = np.asmatrix(np.copy(H_j_cur))
            W_j_pre = np.asmatrix(np.copy(W_j_cur))

            if W_j_change + H_j_change < tol:
                break

        return (W_j_cur, H_j_cur, j + 1)
Exemplo n.º 41
0
def Heigenvalues(a, UPLO='L'):
    return linalg.eigvalsh(a, UPLO)
Exemplo n.º 42
0
 def count(self):
   evs = eigvalsh( self.matrix() )
   non_zero_evs = [ v for v in evs if v > EPSILON ]
   return int(round(
     reduce(lambda x,y: x*y, non_zero_evs, 1) / (1 + len(non_zero_evs))
   ))
        #### compute the laplacian matrix
        lm = [[0 for row in range(N)] for col in range(N)]
        for j in range(N):
            for k in range(N):
                if j == k:
                    lm[j][k] = 1
                    ######### for isolated nodes
                    if degrees[j] == 0:
                        lm[j][k] = 0
                else:
                    if inter_matrix[j][k] > 0:
                        lm[j][k] = -1 * inter_matrix[j][k] * 1.0 / math.sqrt(
                            degrees[j] * degrees[k])

        tmp_eig = LA.eigvalsh(lm)
        tmp_eig.sort()
        eigenvalues.append(tmp_eig)

        #### get the connectivity
        j = 0
        while tmp_eig[j] < 0.001:
            j += 1
        connectivity = tmp_eig[j]

        #### compute isolated nodes
        isolated_count = 0
        for j in range(N):
            if degrees[j] == 0:
                isolated_count += 1
Exemplo n.º 44
0
left_on = 0
right_on = 1
center_on = 0
initialize_on = 1

# define hamiltonian and do 2-to-1 blocking
chi_b = 4
sX = np.array([[0, 1], [1, 0]])
sY = np.array([[0, -1j], [1j, 0]])
sZ = np.array([[1, 0], [0, -1]])
ham_s = np.real(np.kron(sX, sX) + np.kron(sY, sY))
ham_init = (0.5 * np.kron(np.eye(8), np.kron(ham_s, np.eye(2))) +
            np.kron(np.eye(4), np.kron(ham_s, np.eye(4))) +
            0.5 * np.kron(np.eye(2), np.kron(ham_s, np.eye(8))))
bias_shift = max(LA.eigvalsh(ham_init)) - min(LA.eigvalsh(ham_init))

if initialize_on:
  # initialize tensors
  u = [0] * n_levels
  w = [0] * n_levels
  u[0] = np.eye(chi_b**2, chi_b**2).reshape(chi_b, chi_b, chi_b, chi_b)
  w[0] = orthog(np.random.rand(chi_b, chi_b, chi), pivot=2)
  for k in range(n_levels - 1):
    u[k + 1] = (np.eye(chi**2, chi_p**2)).reshape(chi, chi, chi_p, chi_p)
    w[k + 1] = orthog(np.random.rand(chi_p, chi_p, chi), pivot=2)

  v = np.random.rand(chi, chi, chi, 1)
  v = v / LA.norm(v)

else:
Exemplo n.º 45
0
    def _p_pure_sparse(self,
                       state,
                       sub_sys_A,
                       return_rdm=None,
                       sparse_diag=True,
                       maxiter=None):

        partial_trace_args = dict(sub_sys_A=sub_sys_A,
                                  sparse=True,
                                  enforce_pure=True)

        N_A = len(sub_sys_A)
        N_B = self.N - N_A

        rdm_A = None
        rdm_B = None

        if return_rdm is None:
            if N_A <= N_B:
                partial_trace_args["return_rdm"] = "A"
                rdm = self._partial_trace(state, **partial_trace_args)
            else:
                partial_trace_args["return_rdm"] = "B"
                rdm = self._partial_trace(state, **partial_trace_args)

        elif return_rdm == 'A' and N_A <= N_B:
            partial_trace_args["return_rdm"] = "A"
            rdm_A = self._partial_trace(state, **partial_trace_args)
            rdm = rdm_A

        elif return_rdm == 'B' and N_B <= N_A:
            partial_trace_args["return_rdm"] = "B"
            rdm_B = self._partial_trace(state, **partial_trace_args)
            rdm = rdm_B

        else:
            partial_trace_args["return_rdm"] = "both"
            rdm_A, rdm_B = self._partial_trace(state, **partial_trace_args)

            if N_A < N_B:
                rdm = rdm_A
            else:
                rdm = rdm_B

        if sparse_diag and rdm.shape[0] > 16:

            def get_p_patchy(rdm):
                n = rdm.shape[0]
                p_LM = eigsh(rdm,
                             k=n // 2 + n % 2,
                             which="LM",
                             maxiter=maxiter,
                             return_eigenvectors=False)  # get upper half
                p_SM = eigsh(rdm,
                             k=n // 2,
                             which="SM",
                             maxiter=maxiter,
                             return_eigenvectors=False)  # get lower half
                p = _np.concatenate(
                    (p_LM[::-1], p_SM)) + _np.finfo(p_LM.dtype).eps
                return p

            if _sp.issparse(rdm):
                p = get_p_patchy(rdm)
                p = p.reshape((1, -1))
            else:
                p_gen = [get_p_patchy(dm) for dm in rdm[:]]
                p = _np.stack(p_gen)

        else:
            if _sp.issparse(rdm):
                p = eigvalsh(rdm.todense())[::-1] + _np.finfo(rdm.dtype).eps
                p = p.reshape((1, -1))
            else:
                p_gen = [
                    eigvalsh(dm.todense())[::-1] + _np.finfo(dm.dtype).eps
                    for dm in rdm[:]
                ]
                p = _np.stack(p_gen)

        return p, rdm_A, rdm_B
Exemplo n.º 46
0
    def Berry_path_plot(self, angle, N, typ, ax=None):
        """
        Plot Berry curvature as colormap of bands
        :param angle: field shift angle for K-path
        :param N: number of evaluation points
        :param typ: which bands to color, choose from: 'middle','all' & 'occ/unocc'
        :param ax: axis object if applicable, otherwise function will create one
        :return: Plot of Berry curvature
        """

        if self.Hamiltonian.angle == 0:

            kx, ky = path_theta_0(N)

        elif self.Hamiltonian.angle == np.pi / 6:
            kx, ky = path_theta_pi_6(N)

        else:

            kx, ky = path(N)
        ev = []
        bc = []
        bc_o = np.zeros(len(kx))
        bc_u = np.zeros(len(kx))

        for i in range(len(kx)):
            ev.append(eigvalsh(H.get_Hamiltonian(kx[i], ky[i])))
            if typ == 'middle':
                bc.append(
                    inv.berry_curvature_middle_states(np.array([kx[i], ky[i]]),
                                                      0.05))
            elif typ == 'all':
                bc.append(
                    inv.berry_curvature_per_band(np.array([kx[i], ky[i]]),
                                                 0.05))
            else:
                bc_o[i] = inv.berry_curvature(np.array([kx[i], ky[i]]), 0.05)
                bc_u[i] = inv.berry_curvature_unoccupied(
                    np.array([kx[i], ky[i]]), 0.05)

        bc = np.array(bc)

        ev = np.array(ev)
        ev = ev.reshape((3 * N, len(H.lattice.orb)))

        axis = np.arange(0, 3 * N, 1)

        CMAP = plt.get_cmap('coolwarm')
        s = len(axis)

        def myCMAP(x):
            return CMAP((s * x + 1) / 2)

        if not ax:
            fig = plt.figure(figsize=(16, 8))
            ax0 = fig.add_subplot(1, 1, 1)
        else:
            ax0 = ax

        if typ == 'middle':
            colors = [myCMAP(v) for v in bc]
            # if i == 1 or i == 2:
            #    colors = 'lightgrey'
            ax0.scatter(axis, ev[:, 1], c=colors, s=4.0, rasterized=True)
            ax0.scatter(axis, ev[:, 2], c=colors, s=4.0, rasterized=True)

        elif typ == 'all':
            for i in range(len(bc[0, :])):
                colors = [myCMAP(v) for v in bc[:, i]]
                # if i == 1 or i == 2:
                #    colors = 'lightgrey'
                ax0.scatter(axis, ev[:, i], c=colors, s=4.0, rasterized=True)

        else:

            colors_o = [myCMAP(v) for v in bc_o]
            colors_u = [myCMAP(v) for v in bc_u]
            ax0.scatter(axis, ev[:, 1], c=colors_o, s=4.0, rasterized=True)
            ax0.scatter(axis, ev[:, 2], c=colors_u, s=4.0, rasterized=True)

        ax0.set_title('Plot along path in k-space', fontsize=10)
        ax0.set_xticks([0, N, 2 * N, 3 * N])
        ax0.set_xticklabels(["$\Gamma$", "$K$", "$K'$", "$\Gamma$"])

        ax0.set_ylabel("$\epsilon_{k}$")
        ax0.set_yticks([-5, 0, 5])
        txt = 'B = {}'.format(B)
        ax0.text(1.5 * N,
                 5.5,
                 txt,
                 ha="center",
                 va="center",
                 bbox=dict(boxstyle="square", ec='black', fc='white'))

        if not ax:
            ax0.show()
Exemplo n.º 47
0
    En2, A, sWeight, B = dmrg_two_sites(A,
                                        WL,
                                        M,
                                        WR,
                                        chi,
                                        numsweeps=OPTS_numsweeps,
                                        dispon=OPTS_dispon,
                                        updateon=OPTS_updateon,
                                        maxit=OPTS_maxit,
                                        krydim=OPTS_krydim)

    #### Compare with exact results (computed from free fermions)
    from numpy import linalg as LA
    import matplotlib.pyplot as plt
    H = np.diag(np.ones(Nsites - 1), k=1) + np.diag(np.ones(Nsites - 1), k=-1)
    D = LA.eigvalsh(H)
    EnExact = 2 * sum(D[D < 0])

    ##### Plot results
    plt.figure(1)
    plt.yscale('log')
    plt.plot(range(len(En1)), En1 - EnExact, 'b', label="chi = 16")
    plt.plot(range(len(En2)), En2 - EnExact, 'r', label="chi = 32")
    plt.legend()
    plt.title('DMRG for XX model')
    plt.xlabel('Update Step')
    plt.ylabel('Ground Energy Error')
    plt.show()
'''
def gs_Arnoldi(psivec, A_funct, functArgs, maxit=2, krydim=4):
    col_vec = cytnx.zeros([len(psivec), krydim +1]).astype(cytnx.Type.ComplexDouble)
Exemplo n.º 48
0
    iz, ip, im = get_spin_ops(imult)

    Hhfi = np.kron(iz, sz) + 0.5 * (np.kron(ip, sm) + np.kron(im, sp))
    Hhfi *= A
    H = ge * muB * B * np.kron(np.identity(
        imult), sz) - gn * muN * B * np.kron(iz, np.identity(2)) + Hhfi
    return H


gausstoau = 1. / 2.35e+9
bfield = np.linspace(0, 2000, num=150, dtype=float)
evalsLi = np.empty((len(bfield), ILimult * 2), dtype=float)
evalsRb = np.empty((len(bfield), IRbmult * 2), dtype=float)

for i in range(len(bfield)):
    print(i)
    evalsLi[i, :] = npl.eigvalsh(
        get_H(ALi, gnLi, ILimult, bfield[i] * gausstoau)) / mhztoau
    evalsRb[i, :] = npl.eigvalsh(
        get_H(ARb, gnRb, IRbmult, bfield[i] * gausstoau)) / mhztoau

plt.clf()
for i in range(ILimult * 2):
    plt.plot(bfield, evalsLi[:, i])
plt.savefig("li.png")

plt.clf()
for i in range(IRbmult * 2):
    plt.plot(bfield, evalsRb[:, i])
plt.savefig("rb.png")
Exemplo n.º 49
0
def laggauss(deg):
    """
    Gauss-Laguerre quadrature.

    Computes the sample points and weights for Gauss-Laguerre quadrature.
    These sample points and weights will correctly integrate polynomials of
    degree :math:`2*deg - 1` or less over the interval :math:`[0, \\inf]`
    with the weight function :math:`f(x) = \\exp(-x)`.

    Parameters
    ----------
    deg : int
        Number of sample points and weights. It must be >= 1.

    Returns
    -------
    x : ndarray
        1-D ndarray containing the sample points.
    y : ndarray
        1-D ndarray containing the weights.

    Notes
    -----

    .. versionadded:: 1.7.0

    The results have only been tested up to degree 100 higher degrees may
    be problematic. The weights are determined by using the fact that

    .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))

    where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
    is the k'th root of :math:`L_n`, and then scaling the results to get
    the right value when integrating 1.

    """
    ideg = pu._deprecate_as_int(deg, "deg")
    if ideg <= 0:
        raise ValueError("deg must be a positive integer")

    # first approximation of roots. We use the fact that the companion
    # matrix is symmetric in this case in order to obtain better zeros.
    c = np.array([0]*deg + [1])
    m = lagcompanion(c)
    x = la.eigvalsh(m)

    # improve roots by one application of Newton
    dy = lagval(x, c)
    df = lagval(x, lagder(c))
    x -= dy/df

    # compute the weights. We scale the factor to avoid possible numerical
    # overflow.
    fm = lagval(x, c[1:])
    fm /= np.abs(fm).max()
    df /= np.abs(df).max()
    w = 1/(fm * df)

    # scale w to get the right value, 1 in this case
    w /= w.sum()

    return x, w
Exemplo n.º 50
0
 def fg(k): # minimize the gap
   es = lg.eigvalsh(hkgen(k)) # eigenvalues
   return np.min(es[es>0.])-np.max(es[es<0.]) # return gap
Exemplo n.º 51
0
bfield = np.linspace(0, 2000, num=150, dtype=float)
stotvals = np.arange(-4.5, 4.51, step=0.5)
scount = np.zeros(len(stotvals), dtype=int)
evals = np.empty((len(stotvals)), dtype=object)

SzLi = np.kron(get_spin_ops(ILimult)[0], np.identity(2)) + np.kron(np.identity(ILimult), get_spin_ops(2)[0])
SzRb = np.kron(get_spin_ops(IRbmult)[0], np.identity(2)) + np.kron(np.identity(IRbmult), get_spin_ops(2)[0])
Sztot = np.kron(SzLi, np.identity(IRbmult*2)) + np.kron(np.identity(ILimult*2), SzRb)
Sdiag = np.diagonal(Sztot)

for i in range(1, len(bfield)):
    print(i)
    H = np.kron(get_H(ALi, gnLi, ILimult, bfield[i] * gausstoau), np.identity(IRbmult*2))
    H += np.kron(np.identity(ILimult*2), get_H(ARb, gnRb, IRbmult, bfield[i] * gausstoau))
    for s in range(len(stotvals)):
        egvs, vecs = npl.eigvalsh(hblock) 
        egvs /= mhztoau
        spins = np.diagonal(vecs.transpose() @ Sztot @ vecs) 
            if i == 0:
                evals[s] = np.zeros((len(bfield), len(egvs)), dtype=float)
                scount[s] = len(egvs)
            evals[s][i, :] = egvs
        else:
            if i == 0:
                evals[s] = np.zeros((len(bfield), 0), dtype=float)
                scount[s] = 0

print(scount)
for s in range(len(stotvals)):
    plt.clf()
Exemplo n.º 52
0
def norm(matrix):
    e = linalg.eigvalsh(matrix)
    size = len(e)
    e = NP.sort(e)
    norm = e[size - 1]
    return norm
Exemplo n.º 53
0
 def fg(k): # minimize the gap
   es1 = lg.eigvalsh(hkgen(k)) # eigenvalues
   es2 = lg.eigvalsh(hkgen(k)) # eigenvalues
   return np.min(es1[es1>0.])-np.max(es2[es2<0.]) # return gap
Exemplo n.º 54
0
    avgVariable_26 *= 1.0/numRows
    avgVariable_27 *= 1.0/numRows

    # Reynolds stresses stuff

    # Calculate Reynolds stress tensor
    reynolds_stress_tensor = matrix( [[ avgVariable_8 , avgVariable_9 , avgVariable_10 ],[ avgVariable_9 , avgVariable_11 , avgVariable_12 ],[ avgVariable_10 , avgVariable_12 , avgVariable_13 ]])

    # Calculate trace
    trace = avgVariable_8 + avgVariable_11 + avgVariable_13 + 1.0e-20

    # Calculate anisotropy tensor
    anisotropy_tensor = (1.0/trace)*reynolds_stress_tensor - (1.0/3.0)*matrix( [[ 1.0 , 0.0 , 0.0 ],[ 0.0 , 1.0 , 0.0 ],[ 0.0 , 0.0 , 1.0 ]])

    # Calculate tensor eigenvalues
    eigenvalues_anisotropy_tensor = linalg.eigvalsh(anisotropy_tensor)
    sorted_eigenvalues_anisotropy_tensor = sorted(eigenvalues_anisotropy_tensor, reverse=True)

    # Calculate barycentric map points
    x = x1c*( sorted_eigenvalues_anisotropy_tensor[0] - sorted_eigenvalues_anisotropy_tensor[1] ) + x2c*( 2.0*sorted_eigenvalues_anisotropy_tensor[1] - 2.0*sorted_eigenvalues_anisotropy_tensor[2] ) + x3c*( 3.0*sorted_eigenvalues_anisotropy_tensor[2] + 1 )

    # Create string
    string = '%f  %f  %f  %f  %f' %(avgVariable_25, avgVariable_26, avgVariable_27, x.item(0), x.item(1))
    print(string)

    outputFile.write(string)
    outputFile.write('\n')


    # Close input file for processing
    inputFile.close()
Exemplo n.º 55
0
# 1) Compute the arithmetic center of the atomic coordinates.
center = mol.coordinates.mean(axis=0)
# Without the axis=0 argument, the average over all X, Y and Z components would
# be computed. Now it just computes the averages for each column. axis=1 would
# refer to averaging over rows.

# 2) Move the arithmetic center of the coordinates to the origin. The same
# comments from the b_com.py apply.
centered = mol.coordinates - mol.coordinates.mean(axis=0)

# 3) Compute the covariance matrix of the centered coordinates.
covar = dot(centered.transpose(), centered) / mol.size

# 4) Compute the eigenvalues of the symmetric covariance matrix.
evals = eigvalsh(covar)

# 5) The spread along the three eigenvectors is computed as the standard deviation
# of the atomic coordinates along that direction:
c, b, a = sqrt(evals)
print("Spread along the long axis [A]:", a / angstrom)
print("Spread along the intermediate axis [A]:", b / angstrom)
print("Spread along the short axis [A]:", c / angstrom)

# 6) Test in which category this shape belongs. The factor R is set to 1.5.
R = 1.5
if b < R * c:
    if a < R * b:
        shape = 'equant'  # sphere-like
    else:
        shape = 'prolate'  # sigar-like
Exemplo n.º 56
0
#		for i in range(N):
#			newline = nodeids[i] + ': '
#			for j in range(N):
#				if i == j:
#					lm[i][j] = degrees[i]
#				else:
#					if am[i][j] > 0:
#						lm[i][j] = -1*am[i][j]
#				
#				newline += str(lm[i][j]) + ' ' 
#			newline += '\n'
#			outf.writelines(newline)
#		outf.writelines('\n')
		
		### Now we can compute the eigen values of the laplacian matrix
		eigenvals = LA.eigvalsh(lm)
		eigenvals.sort()
		newline = ''
		for i in range(N):
			newline += str(eigenvals[i]) + ' '
		newline += '\n\n'
		outf_eig.writelines(newline)
		
		########################################################################
		
		### add a label about the PRR, isolated nodes, avg prnt size, number of 
		### shortcuts, and smallest non-zero eigenvalue for each cycle 
#		connectivity = 0
#		i = 0
#		while eigenvals[i] < 0.001:
#			i += 1
Exemplo n.º 57
0
 ax12.plot(dmm2.E, prop_dmm2, '*-', label='DMM2 prop')
 ax12.legend(numpoints = 1)
 '''
 exact_dmm = np.empty(numobjects, dtype=object)
 prop_dmm = np.empty(numobjects, dtype=object)
 
 fig1 = plt.figure(1)
 fig1.clf()
 ax1 = fig1.add_subplot(111)
 ax1.set_xlabel('Population')
 ax1.set_ylabel('Energy')
 ax1.set_ylim([-0.2, 1.2])
 
 for i in range(numobjects):
     dmm_list[i].propagate_beta1(numsteps)
     prop_dmm[i] = linalg.eigvalsh(dmm_list[i].rhocopy)[::-1]
     exact_dmm[i] = dmm_list[i].get_exact_pop()
     ax1.plot(dmm_list[i].E, exact_dmm[i], '*-', label='Exact')
     ax1.plot(dmm_list[i].E, prop_dmm[i], '*-', label='Prop')
 ax1.set_title("Population of DMM at $\\beta = %.2f$, $\mu = %.2f$" % (dmm_list[0].beta, dmm_list[0].mu))
 ax1.legend(numpoints = 1)
 
 
 ###########################################################################
 #
 #   Compare RK4 methods
 #
 ###########################################################################
 '''
 dmm1.beta = 0.0
 dmm1.rk4(dmm1.deriv, numsteps)
Exemplo n.º 58
0
def check_rdm(rdm):
    assert np.trace(rdm)==pytest.approx(1.0)
    assert np.trace(rdm@rdm)<=1.0+1e-15
    assert rdm==pytest.approx(rdm.T.conj())
    assert (la.eigvalsh(rdm)>-1e-15).all()
Exemplo n.º 59
0
def blubb(t, t1, t2):
    N = 256

    #construct unit cell from intra and inter h
    hintra1 = np.array([[0, t], [t, 0]])
    hintra2 = np.array([[0, t2], [t2, 0]])
    hinter1 = np.array([[t, 0], [0, t1]])
    hinter2 = hinter1.T
    #stack little hs to get unit cell intras
    M1 = np.hstack((hintra1, hinter1))
    M2 = np.hstack((hinter2, hintra2))
    M = np.vstack((M1, M2))
    heinheitintra = np.kron(np.eye(2), M)
    #build stack for inters for 8x8 unit cell
    hinter3 = np.array([[t1, 0], [0, t]])
    Z = np.zeros((2, 2))
    K1 = np.hstack((Z, Z))
    K2 = np.hstack((hinter3, Z))
    K = np.vstack((K1, K2))
    K_T = K.T
    heinheitinter1 = np.kron(np.eye(2, k=+1), K)
    heinheitinter2 = np.kron(np.eye(2, k=-1), K_T)
    #put together to get h einheit
    heinheit = heinheitintra + heinheitinter1 + heinheitinter2
    #    print(heinheit)
    #construct inter for chi the big hamiltonian ribbon
    c1 = np.array([[0, 0], [t2, 0]])
    c2 = np.array([[0, 0], [t, 0]])
    chi1 = np.hstack((c1, Z))
    chi2 = np.hstack((Z, c2))
    chi = np.vstack((chi1, chi2))
    Z2 = np.zeros((4, 4))
    heinheitinter = np.vstack((np.hstack((chi, Z2)), np.hstack((Z2, chi))))
    #    print(heinheitinter)
    #now put it all together + boundary conditions
    H = np.kron(np.eye(N), heinheit)
    H += np.kron(np.eye(N, k=1), heinheitinter.T)
    H += np.kron(np.eye(N, k=-1), heinheitinter)
    H += np.kron(np.eye(N, k=N - 1), heinheitinter.T)
    H += np.kron(np.eye(N, k=-N + 1), heinheitinter)
    #    print(H)

    hmfft = (1 / N) * fftshift(mfft(mfft(H.conj().T, 8).conj().T, 8))
    #    print(hmfft)

    eigenwerte = []
    for l in range(N):
        block = hmfft[l * 8:8 + l * 8:, l * 8:8 + l * 8:]
        eigenwerte.append(LA.eigvalsh(block))


#    print(eigenwerte)
    k = np.linspace(-np.pi, np.pi, N)
    y = np.array(eigenwerte)

    #   define dos
    k2 = np.linspace(-np.pi, np.pi, N)
    e = np.linspace(-5, 5, N)
    eta = 0.1
    ew = y.flatten()

    def delta_1(ew, e):
        return (1 / N) * np.sum((1 / math.pi) * (eta / (eta**2 + (e - ew)**2)))

    def delta_2(ew, e):
        return (1 / N) * np.sum((1 / (eta * math.sqrt(math.pi))) * np.exp(
            (-(e - ew)**2) / (eta**2)))

    lorenz_liste = []
    gauss_liste = []
    for i in e:
        lorenz_liste.append(delta_1(ew, i))
    for l in e:
        gauss_liste.append(delta_2(ew, l))

    plt.subplot(1, 2, 1)
    plt.plot(k, y)
    plt.xlabel('k')
    plt.ylabel('E')
    plt.subplot(1, 2, 2)
    plt.xlabel('dos')
    plt.ylabel('E')
    plt.plot(lorenz_liste, e)
    plt.plot(gauss_liste, e)
    plt.show()
Exemplo n.º 60
0
# -----------------

# define hamiltonian and do 2-to-1 blocking
chi_b = 4
sX = np.array([[0, 1], [1, 0]])
sY = np.array([[0, -1j], [1j, 0]])
sZ = np.array([[1, 0], [0, -1]])
ham_s = np.real(np.kron(sX, sX) + np.kron(sY, sY))
# ham_s = (-np.kron(sX, sX) + 0.5 * np.kron(np.eye(2), sZ) +
#          0.5 * np.kron(np.eye(2), sZ))
ham_temp = (0.5 * np.kron(np.eye(8), np.kron(ham_s, np.eye(2))) +
            np.kron(np.eye(4), np.kron(ham_s, np.eye(4))) +
            0.5 * np.kron(np.eye(2), np.kron(ham_s, np.eye(8))))
ham_init = BT.fromdense([ind_chib1] * 3 + [ind_chib0] * 3,
                        ham_temp.reshape([chi_b] * 6))
bias_shift = max(LA.eigvalsh(ham_temp)) - min(LA.eigvalsh(ham_temp))
ham = [0] * (n_levels + 1)
ham[0] = ham_init.copy()

if initialize_on:
    # initialize tensors
    u = [0] * n_levels
    w = [0] * n_levels
    utemp = np.eye(chi_b**2, chi_b**2).reshape(chi_b, chi_b, chi_b, chi_b)
    u[0] = BT.fromdense([ind_chib1] * 2 + [ind_chib0] * 2, utemp)
    w[0] = BT.randn([ind_chib1] * 2 + [ind_chib0], dtype='float64')
    for k in range(n_levels - 1):
        utemp = (np.eye(chi**2, chi_p**2)).reshape(chi, chi, chi_p, chi_p)
        u[k + 1] = BT.fromdense([ind_chi1] * 2 + [ind_chip0] * 2, utemp)
        w[k + 1] = BT.randn([ind_chip1] * 2 + [ind_chi0], dtype='float64')