• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python linalg.triu函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中scipy.linalg.triu函数的典型用法代码示例。如果您正苦于以下问题:Python triu函数的具体用法?Python triu怎么用?Python triu使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了triu函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_diag

 def test_diag(self):
     a = (100*get_mat(5)).astype('f')
     b = a.copy()
     for k in range(5):
         for l in range(max((k-1,0)),5):
             b[l,k] = 0
     assert_equal(triu(a,k=2),b)
     b = a.copy()
     for k in range(5):
         for l in range(k+3,5):
             b[l,k] = 0
     assert_equal(triu(a,k=-2),b)
开发者ID:AGPeddle,项目名称:scipy,代码行数:12,代码来源:test_special_matrices.py


示例2: make_edges

def make_edges(n):
    A = la.triu(np.random.randint(1,50,(n,n))*(np.random.rand(n,n)>.5))
    S = []
    for index, x in np.ndenumerate(A):
        if x != 0:
            S.append((str(index[0]), str(index[1]), x))
    return S
开发者ID:davidreber,项目名称:Labs,代码行数:7,代码来源:new_mst_solutions.py


示例3: test_basic

 def test_basic(self):
     a = (100*get_mat(5)).astype('l')
     b = a.copy()
     for k in range(5):
         for l in range(k+1,5):
             b[l,k] = 0
     assert_equal(triu(a),b)
开发者ID:AGPeddle,项目名称:scipy,代码行数:7,代码来源:test_special_matrices.py


示例4: Problem1

def Problem1(n):
    """Use linalg.toeplitz() and linalg.triu() to generate matrices of arbitrary size"""

    from scipy.linalg import triu


    ut = triu([[0]*i+[x for x in range(1,(n+1)-i)] for i in range(n)])
    toep = la.toeplitz([1.0/(i+1) for i in range(n)])

    return ut, toep
开发者ID:jasongrout,项目名称:numerical_computing,代码行数:10,代码来源:Matrices_Complexity2.py


示例5: yty2

 def yty2():
     invT = S
     #log("old invT = " + str(invT))
     if j == p_eff - 1:
         invT[:p_eff, :p_eff] = triu(X2[:p_eff, :m].dot(np.conj(X2)[:p_eff, :m].T))
         #log("invT = " + str(invT))
         for jj in range(p_eff):
             invT[jj,jj] = (invT[jj,jj] - 1.)/2.
     #log("invT = {}".format(invT))
     return invT
开发者ID:SeaifanAladdin,项目名称:Scintillometry,代码行数:10,代码来源:ToeplitzFactorizor.py


示例6: spd

def spd(A):
    """
    spd(A) -> True if A is a symmetric positive definite matrix

    constructs an upper triangular matrix from A and then checks that each
    diagonal element is greater than zero (this comes from the test that a
    matrix is SPD iff all principal leading minors are nonzero, and that these
    determinants will carry through to the diagonalization.

    alternative test is testing eigs(A) > 0 but this is much faster as it
    doesn't involve root-finding
    """
    # test symmetric first, as it's easier
    if not symmetric(A):
        return False
    

    t = linalg.triu(A)
    return (np.diag(t) > 0).all()
开发者ID:wukm,项目名称:573,代码行数:19,代码来源:util.py


示例7: kruskal

def kruskal(A):
    size=A.shape
    minSpanTree=sp.zeros(size)
    nodesTree=sp.arange(size[0])
    D=sp.ones(size)*sp.arange(size[0])
    C=la.triu(A)
    Q=sp.concatenate([[C.flatten()],[D.T.flatten()],[D.flatten()]])
    W=Q[:,sp.nonzero(C.flatten())[0]]
    edges=W[:,W[0,:].argsort()]
    i=0
    j=0
    #while np.sum(nodesTree!=nodesTree[0])>0:
    while (j<(size[0]-1)):
        now=edges[:,i]
        i=i+1
        if nodesTree[now[1]]!=nodesTree[now[2]]:
            minSpanTree[now[1],now[2]]=now[0]
            nodesTree[nodesTree==nodesTree[now[2]]]=nodesTree[now[1]]
            j=j+1
    return minSpanTree+minSpanTree.T
开发者ID:jmbejara,项目名称:numerical_computing,代码行数:20,代码来源:MST.py


示例8: GaussSeidel

def GaussSeidel(A, b, tolerance = 1.e-10, MaxSteps = 100):
    """Solve the linear system A x = b using the Gauss-Seidel method, 
    starting from the trivial initial guess."""
    
    x = np.zeros_like(b)
    
    Anorm = A.copy()
    bnorm = b.copy()
    n = len(b)
    
    for i in range(n):
        bnorm[i] /= A[i, i]
        Anorm[i, :] /= A[i, i]
    
    # Compute the split
    D = np.eye(n)
    AL = la.tril(D - Anorm)
    AU = la.triu(D - Anorm)
    N = np.eye(n) - AL
    P = AU
    
    # Compute the convergence matrix and check its spectral radius
    M = np.dot(la.inv(N), P)
    eigenvalues, eigenvectors = la.eig(M)
    rho = np.amax(np.absolute(eigenvalues))
    if (rho > 1):
        print("Gauss-Seidel will not converge as the"\
              " largest eigenvalue of the convergence matrix is {}".format(rho))
    
    for j in range(MaxSteps):
        x_old = x.copy()
        for i in range(n):
            x[i] = bnorm[i] + np.dot(AL[i, :], x) + np.dot(AU[i, :], x_old)
        if (la.norm(x - x_old) < tolerance):
            print("Gauss-Seidel converged in {} iterations.".format(j))
            break
    
    return x
开发者ID:AdrianShe,项目名称:NumericalMethods,代码行数:38,代码来源:Worksheet2_Functions.py


示例9: Jacobi

def Jacobi(A, b, tolerance = 1.e-10, MaxSteps = 100):
    """Solve the linear system A x = b using Jacobi's method, 
    starting from the trivial initial guess."""
    
    x = np.zeros_like(b)
    
    Anorm = A.copy()
    bnorm = b.copy()
    n = len(b)
    
    for i in range(n):
        bnorm[i] /= A[i, i]
        Anorm[i, :] /= A[i, i]
    
    # Compute the split
    N = np.eye(n)
    P = N - Anorm
    AL = la.tril(P)
    AU = la.triu(P)
    
    # Compute the convergence matrix and check its spectral radius
    M = np.dot(la.inv(N), P)
    eigenvalues, eigenvectors = la.eig(M)
    rho = np.amax(np.absolute(eigenvalues))
    if (rho > 1):
        print("Jacobi will not converge as the"\
            " largest eigenvalue of the convergence matrix is {}".format(rho))
    
    for j in range(MaxSteps):
        x_old = x.copy()
        x = bnorm + np.dot(AL + AU, x)
        if (la.norm(x - x_old) < tolerance):
            print "Jacobi converged in ", j, " iterations."
            break
    
    return x
开发者ID:AdrianShe,项目名称:NumericalMethods,代码行数:36,代码来源:Worksheet2_Functions.py


示例10: pseudoSpect

def pseudoSpect(A, npts=200, s=2., gridPointSelect=100, verbose=True,
                lstSqSolve=True):
    """ 
    original code from http://www.cs.ox.ac.uk/projects/pseudospectra/psa.m
    % psa.m - Simple code for 2-norm pseudospectra of given matrix A.
    %         Typically about N/4 times faster than the obvious SVD method.
    %         Comes with no guarantees!   - L. N. Trefethen, March 1999.
    
    parameter: A: the matrix to analyze
               npts: number of points at the grid
               s: axis limits (-s ... +s)
               gridPointSelect: ???
               verbose: prints progress messages
               lstSqSolve: if true, use least squares in algorithm where
                  solve could be used (probably) instead. (replacement for
                  ldivide in MatLab)
    """
    
    from scipy.linalg import schur, triu
    from pylab import (meshgrid, norm, dot, zeros, eye, diag, find,  linspace,                       
                       arange, isreal, inf, ones, lstsq, solve, sqrt, randn,
                       eig, all)

    ldiv = lambda M1,M2 :lstsq(M1,M2)[0] if lstSqSolve else lambda M1,M2: solve(M1,M2)

    def planerot(x):
        '''
        return (G,y)
        with a matrix G such that y = G*x with y[1] = 0    
        '''
        G = zeros((2,2))
        xn = x / norm(x)
        G[0,0] = xn[0]
        G[1,0] = -xn[1]
        G[0,1] = xn[1]
        G[1,1] = xn[0]
        return G, dot(G,x)

    xmin = -s
    xmax = s
    ymin = -s
    ymax = s;  
    x = linspace(xmin,xmax,npts,endpoint=False)
    y = linspace(ymin,ymax,npts,endpoint=False)
    xx,yy = meshgrid(x,y)
    zz = xx + 1j*yy
     
    #% Compute Schur form and plot eigenvalues:
    T,Z = schur(A,output='complex');
        
    T = triu(T)
    eigA = diag(T)
    
    # Reorder Schur decomposition and compress to interesting subspace:
    select = find( eigA.real > -250)           # % <- ALTER SUBSPACE SELECTION
    n = len(select)
    for i in arange(n):
        for k in arange(select[i]-1,i,-1): #:-1:i
            G = planerot([T[k,k+1],T[k,k]-T[k+1,k+1]] )[0].T[::-1,::-1]
            J = slice(k,k+2)
            T[:,J] = dot(T[:,J],G)
            T[J,:] = dot(G.T,T[J,:])
          
    T = triu(T[:n,:n])
    I = eye(n);
    
    # Compute resolvent norms by inverse Lanczos iteration and plot contours:
    sigmin = inf*ones((len(y),len(x)));
    #A = eye(5)
    niter = 0
    for i in arange(len(y)): # 1:length(y)        
        if all(isreal(A)) and (ymax == -ymin) and (i > len(y)/2):
            sigmin[i,:] = sigmin[len(y) - i,:]
        else:
            for jj in arange(len(x)):
                z = zz[i,jj]
                T1 = z * I - T 
                T2 = T1.conj().T
                if z.real < gridPointSelect:    # <- ALTER GRID POINT SELECTION
                    sigold = 0
                    qold = zeros((n,1))
                    beta = 0
                    H = zeros((100,100))                
                    q = randn(n,1) + 1j*randn(n,1)                
                    while norm(q) < 1e-8:
                        q = randn(n,1) + 1j*randn(n,1)                
                    q = q/norm(q)
                    for k in arange(99):
                        v = ldiv(T1,(ldiv(T2,q))) - dot(beta,qold)
                        #stop
                        alpha = dot(q.conj().T, v).real
                        v = v - alpha*q
                        beta = norm(v)
                        qold = q
                        q = v/beta
                        H[k+1,k] = beta
                        H[k,k+1] = beta
                        H[k,k] = alpha
                        if (alpha > 1e100):
                            sig = alpha 
#.........这里部分代码省略.........
开发者ID:MMaus,项目名称:mutils,代码行数:101,代码来源:misc.py


示例11: get_stat_from_dynamics

def get_stat_from_dynamics(singlecdt, tmin=None, tmax=None):
    """Computes stationary autocorrelation vector from autocorr matrix.

    This function uses the autocorrelation matrix, that stores two-point
    autocorrelation functions between the various acquisition time-points,
    to compute the autocorrelation function in case of stationary hypothesis.
    Computation is fast but result is mostly unreliable (depends very much
    on the accuracy of the dynamical autocorrelation estimates, which is
    usually quite low). Use set_stationary_autocorrelation instead.

    Parameters
    ----------
    singlecdt : UnivariateConditioned instance
    tmin : float (default None)
    tmax : float (default None)

    Returns
    -------
    dts, cts, res
    dts : array of floats
        time intervals
    cts : array of ints
        sample counts
    res : array of floats
        autocorrelation values

    Note
    ----
    The estimate of the autocorrelation function using this procedure gives
    very poor accuracy estimates, and should be used only for quick inspection
    when a Univariate has been created and computed.
    For a better autocorrelation function estimate, it is necessary to parse
    samples another time, using only the sample average estimated in
    Univariate conditioned instances.
    """
    times = singlecdt.time
    autocorr = singlecdt.autocorr
    cts = singlecdt.count_two
    # Resize matrices depending on time limits
    indexlow, indexup = 0, None
    if tmin is not None:
        while indexlow < len(times) and times[indexlow] < tmin:
            indexlow += 1
    if tmax is not None:
        indexup = indexlow
        while indexup < len(times) and times[indexup] < tmax:
            indexup += 1
    sl = slice(indexlow, indexup)
    times = times[sl]
    autocorr = autocorr[sl, sl]
    cts = cts[sl, sl]
    # how many time-points
    nframes = len(times)
    all_counts = np.zeros(nframes, dtype=np.int)
    res = np.zeros(nframes, dtype=np.float)
    dts = np.zeros(nframes, dtype=np.float)
    col = np.zeros(nframes, dtype=np.int16)
    col[-1] = 1  # initialisation
    for k in range(nframes):
        col[k] = 1
        col[k-1] -= 1
        forward = triu(toeplitz(col))
        all_counts[k] = np.sum(forward * cts)
        res[k] = np.sum(forward * cts * autocorr)/all_counts[k]
        dts[k] = times[k] - times[0]
    return dts, all_counts, res
开发者ID:bugrevelio,项目名称:tunacell,代码行数:66,代码来源:compute.py


示例12: toepOne

def toepOne(n):
    return la.triu(la.toeplitz(sp.arange(1,n+1,1)))
开发者ID:snowdj,项目名称:byu_macro_boot_camp,代码行数:2,代码来源:Lab2.py



注:本文中的scipy.linalg.triu函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python _testutils.assert_no_overwrite函数代码示例发布时间:2022-05-27
下一篇:
Python linalg.tri函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap