示例#1
0
def plotMatrixSpectrum(model, A, mat_name):
    fig_path = os.path.join(model.fig_dir,
                            "singular_values_{:}.png".format(mat_name))
    try:
        s = svdvals(A)
    except:
        s = -np.sort(-sparse_svds(
            A, return_singular_vectors=False, k=min(100, min(A.shape))))
    plt.plot(s, 'o')
    plt.ylabel(r'$\sigma$')
    plt.title('Singular values of {:}'.format(mat_name))
    plt.savefig(fig_path)
    plt.close()

    if A.shape[0] == A.shape[1]:  #is square
        fig_path = os.path.join(model.fig_dir,
                                "eigenvalues_{:}.png".format(mat_name))
        try:
            eig = eigvals(A)
        except:
            eig = sparse_eigs(A,
                              return_eigenvectors=False,
                              k=min(1000, min(A.shape)))
        plt.plot(eig.real, eig.imag, 'o')
        plt.xlabel(r'Re($\lambda$)')
        plt.ylabel(r'Im($\lambda$)')
        plt.title('Eigenvalues of {:}'.format(mat_name))
        plt.savefig(fig_path)
        plt.close()
示例#2
0
def compute_spectral_radius(X, is_sparse=False):
    """
    Computes the spectral radius of a matrix

    Parameters
    ----------
    X : np.ndarray or scipy.sparse.csr.csr_matrix
        Input matrix
    is_sparse : bool, optional, default=False
        Whether the passed matrix X is a SciPy sparse matrix or not.

    Returns
    -------
    rho : float
        Spectral radius of `X`

    """
    # To compute the eigen-values of a matrix, it must be square
    assert X.shape[0] == X.shape[1], print('Input matrix must be square')

    if is_sparse:
        eigvec = sparse_eigs(X, k=1, which='LM', return_eigenvectors=False)
        maxeig = np.abs(eigvec[0].real)
    else:
        eigvals = np.linalg.eigvals(X)
        maxeig = np.max(np.abs(eigvals))
    return maxeig
示例#3
0
def P_calc(A, AT,      # LinearOperator and its transpose
           tol=1e-6,
           maxiter=10000):
    """Calculate the probabilities that maximize the entropy rate for
    adjacency matrix A.
    """
    from scipy.sparse.linalg import LinearOperator
    from scipy.sparse.linalg import eigs as sparse_eigs
    w,b = sparse_eigs(A,  k=1, tol=tol, maxiter=maxiter)
    print('eigenvalue=%f'%(w[0].real,))
    w,e = sparse_eigs(AT, k=1, tol=tol, maxiter=maxiter)
    e = e[:,-1].real # Left eigenvector
    b = b[:,-1].real # Right eigenvector
    norm = np.dot(e, A*b)
    Ab = A*b # A vector?
    mu = e*Ab/norm # Also a vector ?
    L = e/mu
    R = b/norm
    P = LinearOperator(A.shape,
                       lambda v: L*(A*(R*v)),
                       rmatvec = lambda v: (A.rmatvec(v*L))*R
                       )
    return mu,P
示例#4
0
文件: mps.py 项目: hsumit/for1807-TPS
def correlation_length(B):
    "Constructs the mixed transfermatrix and returns correlation length"
    from scipy.sparse.linalg import eigs as sparse_eigs
    chi = B[0].shape[1]
    L = len(B)

    T = np.tensordot(B[0], np.conj(B[0]), axes=(0, 0))  # a,b,a*,b*
    T = T.transpose(0, 2, 1, 3)  # a,a*,b,b*
    for i in range(1, L):
        T = np.tensordot(T, B[i], axes=(2, 1))  # a,a*,b*,i,b
        T = np.tensordot(T, np.conj(B[i]), axes=([2, 3], [1, 0]))  #a,a*,b,b*
    T = np.reshape(T, (chi**2, chi**2))

    # Obtain the 2nd largest eigenvalue
    eta = sparse_eigs(T, k=2, which='LM', return_eigenvectors=False, ncv=20)
    return -L / np.log(np.min(np.abs(eta)))
示例#5
0
def main(argv=None):
    '''For looking at sensitivity of time and results to u, dy, n_g, n_h.

    '''
    import argparse
    global DEBUG
    if argv is None:  # Usual case
        argv = sys.argv[1:]

    parser = argparse.ArgumentParser(
        description='Plot eigenfunction of the integral equation')
    parser.add_argument('--u',
                        type=float,
                        default=(2.0e-5),
                        help='log fractional deviation')
    parser.add_argument('--dy',
                        type=float,
                        default=3.2e-4,
                        help='y_1-y_0 = log(x_1/x_0)')
    parser.add_argument('--n_g',
                        type=int,
                        default=200,
                        help='number of integration elements in value')
    parser.add_argument(
        '--n_h',
        type=int,
        default=200,
        help=
        'number of integration elements in slope.  Require n_h > 192 u/(dy^2).'
    )
    parser.add_argument('--m_g',
                        type=int,
                        default=50,
                        help='number of points for plot in g direction')
    parser.add_argument('--m_h',
                        type=int,
                        default=50,
                        help='number of points for plot in h direction')
    parser.add_argument('--eigenvalue', action='store_true')
    parser.add_argument('--debug', action='store_true')
    parser.add_argument('--eigenfunction',
                        type=str,
                        default=None,
                        help="Calculate eigenfunction and write to this file")
    parser.add_argument(
        '--Av',
        type=str,
        default=None,
        help="Illustrate A applied to some points and write to this file")
    args = parser.parse_args(argv)
    if args.Av == None and args.eigenfunction == None and not args.eigenvalue:
        print('Nothing to do')
        return 0
    params = {
        'axes.labelsize': 18,  # Plotting parameters for latex
        'text.fontsize': 15,
        'legend.fontsize': 15,
        'text.usetex': True,
        'font.family': 'serif',
        'font.serif': 'Computer Modern Roman',
        'xtick.labelsize': 15,
        'ytick.labelsize': 15
    }
    mpl.rcParams.update(params)
    if args.debug:
        DEBUG = True
        mpl.rcParams['text.usetex'] = False
    else:
        mpl.use('PDF')
    import matplotlib.pyplot as plt  # must be after mpl.use
    from scipy.sparse.linalg import LinearOperator
    from mpl_toolkits.mplot3d import Axes3D  # Mysteriously necessary
    #for "projection='3d'".
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from first_c import LO_step
    #from first import LO_step   # Factor of 9 slower

    g_step = 2 * args.u / (args.n_g - 1)
    h_max = (24 * args.u)**.5
    h_step = 2 * h_max / (args.n_h - 1)
    A = LO_step(args.u, args.dy, g_step, h_step)
    if args.eigenvalue:
        from scipy.sparse.linalg import eigs as sparse_eigs
        from numpy.linalg import norm
        tol = 1e-10
        w, b = sparse_eigs(A, tol=tol, k=10)
        print('Eigenvalues from scipy.sparse.linalg.eigs:')
        for val in w:
            print('norm:%e,  %s' % (norm(val), val))
        A.power(small=tol)
        print('From A.power() %e' % (A.eigenvalue, ))
    if args.eigenfunction != None:
        # Calculate and plot the eigenfunction
        tol = 5e-6
        maxiter = 1000
        A.power(small=tol, n_iter=maxiter, verbose=True)
        floor = 1e-20 * max(A.eigenvector).max()
        fig = plt.figure(figsize=(24, 12))
        ax1 = fig.add_subplot(1, 2, 1, projection='3d', elev=15, azim=135)
        ax2 = fig.add_subplot(1, 2, 2, projection='3d', elev=15, azim=45)
        plot_eig(A, floor, ax1, args)
        plot_eig(A, floor, ax2, args)
        if not DEBUG:
            fig.savefig(open(args.eigenfunction, 'wb'), format='pdf')
    if DEBUG:
        plt.show()
    return 0
示例#6
0
def main(argv=None):
    '''For looking at sensitivity of time and results to u, dy, n_g, n_h.

    '''
    import argparse
    global DEBUG
    if argv is None:                    # Usual case
        argv = sys.argv[1:]

    parser = argparse.ArgumentParser(
        description='Plot eigenfunction of the integral equation')
    parser.add_argument('--u', type=float, default=(2.0e-5),
                       help='log fractional deviation')
    parser.add_argument('--dy', type=float, default=3.2e-4,
                       help='y_1-y_0 = log(x_1/x_0)')
    parser.add_argument('--n_g', type=int, default=200,
                       help='number of integration elements in value')
    parser.add_argument('--n_h', type=int, default=200,
help='number of integration elements in slope.  Require n_h > 192 u/(dy^2).')
    parser.add_argument('--m_g', type=int, default=50,
                       help='number of points for plot in g direction')
    parser.add_argument('--m_h', type=int, default=50,
                       help='number of points for plot in h direction')
    parser.add_argument('--eigenvalue', action='store_true')
    parser.add_argument('--debug', action='store_true')
    parser.add_argument('--eigenfunction', type=str, default=None,
        help="Calculate eigenfunction and write to this file")
    parser.add_argument('--Av', type=str, default=None,
        help="Illustrate A applied to some points and write to this file")
    args = parser.parse_args(argv)
    if args.Av == None and args.eigenfunction == None and not args.eigenvalue:
        print('Nothing to do')
        return 0
    params = {'axes.labelsize': 18,     # Plotting parameters for latex
              'text.fontsize': 15,
              'legend.fontsize': 15,
              'text.usetex': True,
              'font.family':'serif',
              'font.serif':'Computer Modern Roman',
              'xtick.labelsize': 15,
              'ytick.labelsize': 15}
    mpl.rcParams.update(params)
    if args.debug:
        DEBUG = True
        mpl.rcParams['text.usetex'] = False
    else:
        mpl.use('PDF')
    import matplotlib.pyplot as plt  # must be after mpl.use
    from scipy.sparse.linalg import LinearOperator
    from mpl_toolkits.mplot3d import Axes3D  # Mysteriously necessary
                                             #for "projection='3d'".
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from first_c import LO_step
    #from first import LO_step   # Factor of 9 slower

    g_step = 2*args.u/(args.n_g-1)
    h_max = (24*args.u)**.5
    h_step = 2*h_max/(args.n_h-1)
    A = LO_step( args.u, args.dy, g_step, h_step)
    if args.eigenvalue:
        from scipy.sparse.linalg import eigs as sparse_eigs
        from numpy.linalg import norm
        tol = 1e-10
        w,b = sparse_eigs(A,  tol=tol, k=10)
        print('Eigenvalues from scipy.sparse.linalg.eigs:')
        for val in w:
            print('norm:%e,  %s'%(norm(val), val))
        A.power(small=tol)
        print('From A.power() %e'%(A.eigenvalue,))
    if args.eigenfunction != None:
        # Calculate and plot the eigenfunction
        tol = 5e-6
        maxiter = 1000
        A.power(small=tol, n_iter=maxiter, verbose=True)
        floor = 1e-20*max(A.eigenvector).max()
        fig = plt.figure(figsize=(24,12))
        ax1 = fig.add_subplot(1,2,1, projection='3d', elev=15, azim=135)
        ax2 = fig.add_subplot(1,2,2, projection='3d', elev=15, azim=45)
        plot_eig(A, floor, ax1, args)
        plot_eig(A, floor, ax2, args)
        if not DEBUG:
                fig.savefig( open(args.eigenfunction, 'wb'), format='pdf')
    if DEBUG:
        plt.show()
    return 0