Example #1
0
def _init_svd_solver(nsv=6, SVDType='cross', tol=None, maxiter=None,
                     ncv=None, comm=None):
    SLEPc, comm = get_slepc(comm=comm)
    svd_solver = SLEPc.SVD().create(comm=comm)
    svd_solver.setType(SVDType)
    svd_solver.setTolerances(tol=tol, max_it=maxiter)
    svd_solver.setDimensions(nsv=nsv, ncv=ncv)
    svd_solver.setFromOptions()
    return svd_solver
Example #2
0
def calculate_condition_number(A,
                               num_of_factors,
                               backend: str = "scipy",
                               use_sparse: bool = False,
                               zero_tol: float = 1e-5):
    backend = backend.lower()

    if backend == "scipy":
        size = A.getSize()
        Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size)
        Mnp.eliminate_zeros()

        if use_sparse:
            singular_values = svds(A=Mnp,
                                   k=num_of_factors,
                                   which="LM",
                                   maxiter=5000,
                                   return_singular_vectors=False,
                                   solver="lobpcg")
        else:
            M = Mnp.toarray()
            singular_values = svd(M, compute_uv=False, check_finite=False)

        singular_values = singular_values[singular_values > zero_tol]

        condition_number = singular_values.max() / singular_values.min()
    elif backend == "slepc":
        S = SLEPc.SVD()
        S.create()
        S.setOperator(A)
        S.setType(SLEPc.SVD.Type.LAPACK)
        S.setDimensions(nsv=num_of_factors)
        S.setTolerances(max_it=5000)
        S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST)
        S.solve()

        num_converged_values = S.getConverged()
        singular_values_list = list()
        if num_converged_values > 0:
            for i in range(num_converged_values):
                singular_value = S.getValue(i)
                singular_values_list.append(singular_value)
        else:
            raise RuntimeError("SLEPc SVD has not converged.")

        singular_values = np.array(singular_values_list)

        singular_values = singular_values[singular_values > zero_tol]
        condition_number = singular_values.max() / singular_values.min()
    else:
        raise NotImplementedError(
            "The required method for condition number estimation is currently unavailable."
        )

    return condition_number
Example #3
0
def svd_slepc(A, k, tol, max_iter):

    ### Setup matrix operator
    n = A.shape[0]
    mat = MatrixOperator(A, allow_tranpose_mult=True)
    A_operator = PETSc.Mat().createPython([n, n], mat)
    A_operator.setUp()

    ### Solve eigenproblem
    S = SLEPc.SVD()
    S.create()
    S.setOperator(A_operator)
    S.setDimensions(k)
    S.setTolerances(tol, max_iter)
    S.solve()
    print("Number of calls to Ax: %d" % mat.n_calls)

    ### Collect results
    print("")
    its = S.getIterationNumber()
    print("Number of iterations of the method: %i" % its)
    sol_type = S.getType()
    print("Solution method: %s" % sol_type)
    nev, ncv, mpd = S.getDimensions()
    print("NEV %d NCV %d MPD %d" % (nev, ncv, mpd))
    tol, maxit = S.getTolerances()
    print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit))
    nconv = S.getConverged()
    print("Number of converged eigenpairs: %d" % nconv)
    nconv = min(nconv, k)

    if nconv < k:
        raise ZeroDivisionError("Failed to converge for requested number of k with maxiter=%d" % max_iter)

    vecs = np.zeros([n, nconv])
    vecs2 = np.zeros([n, nconv])
    vals = np.zeros(nconv)

    v, u = A_operator.getVecs()

    if nconv > 0:
        for i in range(nconv):
            sigma = S.getSingularTriplet(i, v, u)
            vals[i] = sigma
            vecs[:, i] = v
            vecs2[:, i] = u

    return vals, vecs, vecs2
Example #4
0
def svd(X, method='lanczos'):
    r""" Compute SVD using SLEPc.

    Parameters
    ----------
    X : (n, m) ndarray
        input matrix
    method : str, optional, default='lanczos'
        SVD solver to use, can be one of `'lanczos'`, `'cyclic'`, `'lapack'`, `'trlanczos'`, `'cross'`.

    Returns
    -------
    u, s, vh
    """
    _handle_import_error()
    assert method in svd._mapping.keys(
    ), f'Illegal method, must be one of {list(svd._mapping.keys())}.'

    mat = _to_petsc_matrix(X)
    S = SLEPc.SVD()
    S.create()
    S.setOperator(mat)
    S.setFromOptions()
    S.setType(svd._mapping[method])
    S.setDimensions(nsv=min(X.shape))
    S.solve()

    nconv = S.getConverged()
    s = np.empty((nconv, ), dtype=PETSc.ScalarType)
    U = np.empty((nconv, X.shape[0]), dtype=PETSc.ScalarType)
    Vh = np.empty((nconv, X.shape[1]), dtype=PETSc.ScalarType)

    if nconv > 0:
        for i in range(nconv):
            U_ = PETSc.Vec().createWithArray(U[i])
            V_ = PETSc.Vec().createWithArray(Vh[i])

            s[i] = S.getValue(i)
            S.getVectors(i, U_, V_)
    return U, s, Vh
Example #5
0
    else:
        Print("n-periodic case")
        iR, B = load_gep_n(folder + '/A1.dat', folder + '/A2.dat',
                           folder + '/A3.dat', folder + '/B1.dat',
                           folder + '/B2.dat', folder + '/B3.dat', j, n)
    iR.axpy(-np.exp(1j * omega * dt), B)
    iR.scale(-1)

if np.abs(omega * dt) >= 1e-4:
    iR.scale((np.exp(1j * omega * dt) - 1) / (1j * omega * dt))
else:
    iR.scale(1 + 0.5 * (1j * omega * dt))

ctx = ResolventOperator(iR, I, Mh12, Mh12 / Rh12)

S = SLEPc.SVD()
S.create()

MhRsize = (I.getSize()[0], I.getSize()[0])
MhR = PETSc.Mat().createPython((MhRsize, MhRsize), ctx)
MhR.setUp()

S.setOperator(MhR)
S.setFromOptions()

S.solve()

Print = PETSc.Sys.Print

Print("******************************")
Print("*** SLEPc Solution Results ***")
Example #6
0
def condition_number(A, method='simplified'):
    """
    Estimate the condition number of the matrix A
    """
    if method == 'simplified':
        # Calculate max(abs(A))/min(abs(A))
        amin, amax = 1e10, -1e10
        for irow in range(A.size(0)):
            _indices, values = A.getrow(irow)
            aa = abs(values)
            amax = max(amax, aa.max())
            aa[aa == 0] = amax
            amin = min(amin, aa.min())
        amin = dolfin.MPI.min(dolfin.MPI.comm_world, float(amin))
        amax = dolfin.MPI.max(dolfin.MPI.comm_world, float(amax))
        return amax / amin

    elif method == 'numpy':
        from numpy.linalg import cond

        A = mat_to_scipy_csr(A).todense()
        return cond(A)

    elif method == 'SLEPc':
        from petsc4py import PETSc
        from slepc4py import SLEPc

        # Get the petc4py matrix
        PA = dolfin.as_backend_type(A).mat()

        # Calculate the largest and smallest singular value
        opts = {
            'svd_type': 'cross',
            'svd_eps_type': 'gd',
            # 'help': 'svd_type'
        }
        with petsc_options(opts):
            S = SLEPc.SVD()
            S.create()
            S.setOperator(PA)
            S.setFromOptions()
            S.setDimensions(1, PETSc.DEFAULT, PETSc.DEFAULT)
            S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST)
            S.solve()
            if S.getConverged() == 1:
                sigma_1 = S.getSingularTriplet(0)
            else:
                raise ValueError(
                    'Could not find the highest singular value (%d)' %
                    S.getConvergedReason())
            print('Highest singular value:', sigma_1)

            S.setWhichSingularTriplets(SLEPc.SVD.Which.SMALLEST)
            S.solve()
            if S.getConverged() == 1:
                sigma_n = S.getSingularTriplet(0)
            else:
                raise ValueError(
                    'Could not find the lowest singular value (%d)' %
                    S.getConvergedReason())
            print('Lowest singular value:', sigma_n)
            print(PETSc.Options().getAll())
        print(PETSc.Options().getAll())

        return sigma_1 / sigma_n
Example #7
0
def help(args=None):
    import sys
    # program name
    try:
        prog = sys.argv[0]
    except Exception:
        prog = getattr(sys, 'executable', 'python')
    # arguments
    if args is None:
        args = sys.argv[1:]
    elif isinstance(args, str):
        args = args.split()
    else:
        args = [str(a) for a in args]
    # initialization
    import slepc4py
    slepc4py.init([prog, '-help'] + args)
    from slepc4py import SLEPc
    # and finally ...
    COMM = SLEPc.COMM_SELF
    if 'eps' in args:
        eps = SLEPc.EPS().create(comm=COMM)
        eps.setFromOptions()
        eps.destroy()
        del eps
    if 'svd' in args:
        svd = SLEPc.SVD().create(comm=COMM)
        svd.setFromOptions()
        svd.destroy()
        del svd
    if 'pep' in args:
        pep = SLEPc.PEP().create(comm=COMM)
        pep.setFromOptions()
        pep.destroy()
        del pep
    if 'nep' in args:
        nep = SLEPc.NEP().create(comm=COMM)
        nep.setFromOptions()
        nep.destroy()
        del nep
    if 'mfn' in args:
        mfn = SLEPc.MFN().create(comm=COMM)
        mfn.setFromOptions()
        mfn.destroy()
        del mfn
    if 'st' in args:
        st = SLEPc.ST().create(comm=COMM)
        st.setFromOptions()
        st.destroy()
        del st
    if 'bv' in args:
        bv = SLEPc.BV().create(comm=COMM)
        bv.setFromOptions()
        bv.destroy()
        del bv
    if 'rg' in args:
        rg = SLEPc.RG().create(comm=COMM)
        rg.setFromOptions()
        rg.destroy()
        del rg
    if 'fn' in args:
        fn = SLEPc.FN().create(comm=COMM)
        fn.setFromOptions()
        fn.destroy()
        del fn
    if 'ds' in args:
        ds = SLEPc.DS().create(comm=COMM)
        ds.setFromOptions()
        ds.destroy()
        del ds
Example #8
0
for row in df.itertuples():
    _, i, j, wcCount = row
    wCount = counts[i]
    cCount = counts[j]
    ppmi = PPMI(wcCount, total, wCount, cCount, alpha=alpha)
    data.append(ppmi)
    rowIndex.append(i)
    columnIndex.append(j)

csr = csr_matrix((data, (rowIndex, columnIndex)), shape=(n, n))
print("Doing SVD")
print("PPMI[99,2]=", csr[99, 2])
A = PETSc.Mat().createAIJ(size=(n, n), csr=(csr.indptr, csr.indices, csr.data))
A.assemble()

svd = SLEPc.SVD()
svd.create()

svd.setOperator(A)
svd.setType(svd.Type.TRLANCZOS)
svd.setDimensions(nsv=50, ncv=100)
svd.setFromOptions()
svd.solve()

iterations = svd.getIterationNumber()
nsv, ncv, mpd = svd.getDimensions()
nconv = svd.getConverged()
v, u = A.createVecs()

U = []
V = []