Exemple #1
0
    def initialize(self,slepc_args=None):
        """
        Initialize PETSc/SLEPc with various arguments (which would be
        passed on the command line for a C program).

        Only the first call to this function has any effect, and this
        function is automatically called with no arguments when any
        dynamite submodule is imported. Thus, one must call it before
        importing any submodules.

        Parameters
        ==========

        slepc_args : list of str
            The arguments to SLEPc initialization.
        """
        if slepc_args is None:
            slepc_args = []

        if not self.initialized:
            slepc4py.init(slepc_args)
            self.initialized = True
        else:
            if slepc_args:
                raise RuntimeError('initialize has already been called. Perhaps '
                                   'you already imported a dynamite submodule?')
Exemple #2
0
def getDeterminant(K):
    import sys, slepc4py
    slepc4py.init(sys.argv)

    from petsc4py import PETSc
    from slepc4py import SLEPc

    N = len(K[0,:])

    opts = PETSc.Options()

    A = PETSc.Mat(); A.createDense((N,N))
    #A.setFromOptions()

    # copy matrices to petsc, is there are more direct way ?
    for i in range(N):
        for j in range(N):
            A[i,j] = K[i,j]


    A.assemble()
    
    
    A.LU()

    print A
    return mul(A.getDiagonal())
Exemple #3
0
    def eigenfunctions(self, matrix, number_modes):
        import sys, slepc4py

        slepc4py.init(sys.argv)

        from petsc4py import PETSc
        from slepc4py import SLEPc

        E = SLEPc.EPS()
        E.create()

        E.setOperators(matrix.petScMatrix())
        E.setProblemType(SLEPc.EPS.ProblemType.HEP)
        #E.setType(SLEPc.EPS.Type.ARNOLDI)
        E.setFromOptions()
        E.setTolerances(tol=1e-9, max_it=200)
        E.setDimensions(nev=number_modes)
        E.solve()

        Print = PETSc.Sys.Print

        iterations = E.getIterationNumber()
        self.log("Number of iterations of the method: %d" % iterations)

        eps_type = E.getType()
        self.log("Solution method: %s" % eps_type)

        nev, ncv, mpd = E.getDimensions()
        self.log("Number of requested eigenvalues: %d" % nev)

        tol, maxit = E.getTolerances()
        self.log("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit))

        nconv = E.getConverged()
        self.log("Number of converged eigenpairs %d" % nconv)

        eigenvalues = np.zeros(nconv, dtype=np.complex128)
        result_vector = ParallelVector(matrix.distributionPlan())
        plan = DistributionPlan(mpi.COMM_WORLD,
                                n_columns=matrix.totalShape()[1],
                                n_rows=nconv)
        eigenvectors_parallel = ParallelMatrix(plan)

        # Create the results vectors
        vr, wr = matrix.petScMatrix().getVecs()
        vi, wi = matrix.petScMatrix().getVecs()
        #
        for i in range(nconv):
            k = E.getEigenpair(i, vr, vi)

            result_vector.setCollective(vr.getArray())
            eigenvalues[i] = k

            if i in eigenvectors_parallel.localRows():
                eigenvectors_parallel.setRow(i, result_vector.fullData())

        return eigenvalues, eigenvectors_parallel
Exemple #4
0
def init_slepc_args():
    try:
        import sys, slepc4py

    except ImportError:
        return

    argv = [arg for arg in sys.argv if arg not in ['-h', '--help']]
    slepc4py.init(argv)
    def eigenfunctions(self, matrix, number_modes):
        import sys, slepc4py

        slepc4py.init(sys.argv)

        from petsc4py import PETSc
        from slepc4py import SLEPc

        E = SLEPc.EPS()
        E.create()

        E.setOperators(matrix.petScMatrix())
        E.setProblemType(SLEPc.EPS.ProblemType.HEP)
        #E.setType(SLEPc.EPS.Type.ARNOLDI)
        E.setFromOptions()
        E.setTolerances(tol=1e-9, max_it=200)
        E.setDimensions(nev=number_modes)
        E.solve()

        Print = PETSc.Sys.Print

        iterations = E.getIterationNumber()
        self.log("Number of iterations of the method: %d" % iterations)

        eps_type = E.getType()
        self.log("Solution method: %s" % eps_type)

        nev, ncv, mpd = E.getDimensions()
        self.log("Number of requested eigenvalues: %d" % nev)

        tol, maxit = E.getTolerances()
        self.log("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit))

        nconv = E.getConverged()
        self.log("Number of converged eigenpairs %d" % nconv)

        eigenvalues = np.zeros(nconv, dtype=np.complex128)
        result_vector = ParallelVector(matrix.distributionPlan())
        plan = DistributionPlan(mpi.COMM_WORLD, n_columns=matrix.totalShape()[1], n_rows=nconv)
        eigenvectors_parallel = ParallelMatrix(plan)

        # Create the results vectors
        vr, wr = matrix.petScMatrix().getVecs()
        vi, wi = matrix.petScMatrix().getVecs()
        #
        for i in range(nconv):
            k = E.getEigenpair(i, vr, vi)

            result_vector.setCollective(vr.getArray())
            eigenvalues[i] = k

            if i in eigenvectors_parallel.localRows():
                eigenvectors_parallel.setRow(i, result_vector.fullData())

        return eigenvalues, eigenvectors_parallel
Exemple #6
0
def getMinAbsEigenvalue(K):
    
    import sys, slepc4py
    slepc4py.init(sys.argv)

    from petsc4py import PETSc
    from slepc4py import SLEPc

    N = len(K[0,:])

    opts = PETSc.Options()

    A = PETSc.Mat(); A.createDense((N,N))

    # copy matrices to petsc, is there are more direct way ?
    for i in range(N):
        for j in range(N):
            A[i,j] = K[i,j]


    A.assemble()

    E = SLEPc.EPS(); E.create()

    E.setOperators(A)
    # Non-hermite problem
    E.setProblemType(SLEPc.EPS.ProblemType.NHEP)
    E.setWhichEigenpairs(SLEPc.EPS.Which.SMALLEST_MAGNITUDE)
    E.setTolerances(tol=1.e-11, max_it=1000)
    E.setDimensions(1)
    
    E.solve()

    #nPrint = PETSc.Sys.Print

    eps_type = E.getType()
    #Print( "Solution method: %s" % eps_type )

    nconv = E.getConverged()
    Print( "Number of converged eigenpairs %d" % nconv )

    val = []
    #    # Create the results vectors
    vr, wr = A.getVecs()
    vi, wi = A.getVecs()
    #    #
    for i in range(nconv): val.append(E.getEigenpair(i, vr, vi))
    #        val.append(k)
    #        error = E.computeRelativeError(i)
    #    #E.getEigenvector(0, vr, vi)
    #   #return vr[:]+ vi[:]
    # print "Eigenvalues: ", val
    vals = array(val)
    idx = argmin(abs(vals))
    return vals[idx]
Exemple #7
0
def init_petsc_and_slepc(comm=None):
    """Make sure petsc is initialized with comm before slepc.
    """
    import os
    petsc_arch = os.environ.get("PETSC_ARCH", None)

    import petsc4py
    petsc4py.init(args=['-no_signal_handler'], arch=petsc_arch, comm=comm)
    import slepc4py
    slepc4py.init(args=['-no_signal_handler'], arch=petsc_arch)
    return petsc4py.PETSc, slepc4py.SLEPc
    def init_petsc_slepc(self, comm):
        import os
        petsc_arch = os.environ.get("PETSC_ARCH", None)

        import petsc4py
        petsc4py.init(args=['-no_signal_handler'], arch=petsc_arch, comm=comm)
        import slepc4py
        slepc4py.init(args=['-no_signal_handler'], arch=petsc_arch)

        self._comm = comm
        self._PETSc = petsc4py.PETSc
        self._SLEPc = slepc4py.SLEPc
Exemple #9
0
    def eigenvalues(self):
        import slepc4py
        slepc4py.init()
        from slepc4py import SLEPc
        E = SLEPc.EPS(); E.create()

        E.setOperators(self.A)
        E.setProblemType(SLEPc.EPS.ProblemType.NHEP)
        E.setDimensions(1)
        E.setWhichEigenpairs(SLEPc.EPS.Which.SMALLEST_REAL)
        E.setFromOptions()
        E.solve()
        n = E.getConverged()
        for i in range(0, n):
            print(E.getEigenvalue(0))
        return 
Exemple #10
0
import numpy as np
import scipy.sparse
from numpy import sin, cos, tan
import sys
import petsc4py
petsc4py.init()
import slepc4py
slepc4py.init()
import dill


class Model():
    '''
    Base class for the FVF model, including functions for most common operations except for make_A, and make_B, which
    are implemented in the child class definitions found in individual files.
    '''
    def __init__(self, model_variables, model_parameters, physical_constants):
        self.model_variables = model_variables
        self.model_parameters = model_parameters
        self.physical_constants = physical_constants

        for key in model_parameters:
            exec('self.' + str(key) + ' = model_parameters[\'' + str(key) +
                 '\']')
        for key in physical_constants:
            exec('self.' + str(key) + ' = physical_constants[\'' + str(key) +
                 '\']')

        self.calculate_nondimensional_parameters()
        self.set_up_grid(self.R, self.h)
Exemple #11
0
def solve_for_combo(c):
    import time
    time_start = -time.time()
    import FVF_loglib as flog
    import FVF_plotlib as fplt
    from . import analyze as fana
    from . import utilities as util
    import petsc4py
    petsc4py.init()
    import slepc4py
    slepc4py.init()
    import dill

    print('working on combination {0}/{1}'.format(c['iter_num'], c['total_iter']))

    data_dir = c['data_dir']
    T = c['T_list']

    # Set up directory to store solution data
    try:
        out_dir = futil.get_out_dir(out_dir_base, data_dir, len(cfg.data_dir), T, len(cfg.T_list))
        futil.ensure_dir(out_dir)
    except:
        print('problem setting out directory')
        return

    # Set up logger
    try:
        logger = flog.setup_custom_logger(dir_name=out_dir, filename='run.log', verbose=cfg.verbose)
    except:
        print('problem creating logger')
        return

    try:
        # Store config file for later reference
        logger.info('used config file {0}.py'.format(config_file))
        futil.store_config_file(config_file, out_dir_base)

        logger.info('Main output directory set to {0}'.format(out_dir_base))
        logger.info('Output subdirectory set to {0}'.format(out_dir))

        # Convert Time in years to model frequency
        t_star = (23.9345*3600)/(2*np.pi)
        Target_j = 2*np.pi/(T*365.25*24*3600/t_star)*1j
        Target = Target_j + Target_j*1j/(2*cfg.target_Q)

        # Find which CC matrix to use
        dCyr_list = futil.find_available_skin_depths(data_dir)
        dCyr_use = futil.find_closest_CC(T, dCyr_list)
        logger.info('{0} dCyr used'.format(dCyr_use))
    except:
        problem = "problem storing config file or finding correct magnetic skin depth"
        logger.error(problem, exc_info=1)
        print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))

        return

    # %% Load Matrices and model from files
    #==============================================================================
    try:
        viewer = petsc4py.PETSc.Viewer().createBinary(data_dir+fileA+str(dCyr_use)+'.dat', 'r')
        A = petsc4py.PETSc.Mat().load(viewer)
        viewer = petsc4py.PETSc.Viewer().createBinary(data_dir+fileB+'.dat', 'r')
        B = petsc4py.PETSc.Mat().load(viewer)
        try:
            model = dill.load(open(data_dir+filemodel,'rb'))
        except:
            model = dill.load(open(data_dir+filemodel,'rb'),encoding='latin1')
        logger.info('A'+str(dCyr_use)+' matrix used')
        logger.info('matrices and model loaded into memory from ' + data_dir)
    except:
        problem = "Problem loading matrices from file."
        logger.error(problem, exc_info=1)
        print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))
        return

    # %% Set up SLEPc Solver
    #==============================================================================
    try:
        EPS = slepc4py.SLEPc.EPS().create()
        EPS.setDimensions(num_solutions_to_calculate, petsc4py.PETSc.DECIDE)
        EPS.setOperators(A, B)
        EPS.setType(EPS.Type.KRYLOVSCHUR)
        EPS.setProblemType(slepc4py.SLEPc.EPS.ProblemType.PGNHEP)
        EPS.setTarget(Target)
        EPS.setWhichEigenpairs(EPS.Which.TARGET_MAGNITUDE)
        EPS.setTolerances(tol)
        EPS.setFromOptions()
        ST = EPS.getST()
        ST.setType(slepc4py.SLEPc.ST.Type.SINVERT)
        logger.info('Solver set up, Target Period = {0:.1f}, Number of solutions to calculate = {1}'.format(T, num_solutions_to_calculate))
    except:
        problem = "Problem setting up SLEPc Solver."
        logger.error(problem, exc_info=1)
        print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))
        return

    # %% Solve Problem
    #==============================================================================
    try:
        EPS.solve()
        logger.info('problem solved')
    except:
        problem = "Problem Solving Eigenvalues."
        logger.error(problem, exc_info=1)
        print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))
        return
    try:
        # Save Computed Solutions
        conv = EPS.getConverged()
        logger.info('{0} eigenvalues converged'.format(conv))
        vals = []
        vecs = []
        for ind in range(conv):
            vs, ws = petsc4py.PETSc.Mat.getVecs(A)
            v = EPS.getEigenpair(ind, ws)
            vals.append(v)
            vecs.append(ws.getArray())
        Periods = (2*np.pi/np.array([x.imag for x in vals]))*model.t_star/(24.*3600.*365.25)
        Period_max = Periods.max()
        Period_min = Periods.min()
        logger.info('min Period = {0:.1f}yrs, max Period = {1:.1f}yrs'.format(Period_min, Period_max))
    except:
        problem = "Problem Computing Eigenvalues."
        logger.error(problem, exc_info=1)
        print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))
        return

    #%% Filter Solutions
    #==============================================================================
    try:
        logger.info('Filtering Eigenvalues:')

        # filter results to keep only those that satisfy requirements specified in filter_dict
        fvals, fvecs = fana.filter_results(model, vals, vecs, cfg.filter_dict)

        # Sort by fit to given parameter choices
        svals, svecs = fana.sort_by_total_misfit(model, fvals, fvecs, cfg.sort_dict)

    except:
        try:
            problem = "Problem Saving Eigenvalues."
            logger.error(problem, exc_info=1)
            print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))
            svals = vals
            svecs = vecs
        except:
            svals = []
            svecs = []
            problem = "Problem Saving Eigenvalues."
            logger.error(problem, exc_info=1)
            print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))

    # %% Save Filtered Eigenvectors
    #==============================================================================
    try:
        if savefile:
            dill.dump({'vals': svals, 'vecs': svecs, 'model':model},open(out_dir + savefile, 'wb'))
            logger.info('saved {0:d} vals and vecs saved to '.format(len(svals)) + out_dir + savefile)
    except:
        problem = "Problem Saving Eigenvalues."
        logger.error(problem, exc_info=1)
        print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))
        return
    # %% Plot Filtered Eigenvectors
    #==============================================================================
    try:
        logger.info('Plotting:')

        for ind in range(min(cfg.num_solutions_to_plot,len(svals))):
            val = svals[ind]
            vec = fana.shift_vec_real(model, svecs[ind], var='vth')
            vec = fana.normalize_vec(vec, 10)
            Period = fana.get_period(model, val)
            Q = fana.get_Q(val)
            r_ord = fana.get_order_r(model, vec)
            th_ord = fana.get_order_th(model, vec)
            if abs(Period) < 1.0:
                title = ('{0:03d} k={3}, l={4}, m={5}, T={1:.2f}dys, Q={2:.2f}'.format(ind, Period*365.25, Q, r_ord, th_ord, model.m)
                         + '\nH={:.0f}km, B={:.2f}mT, N={:.2f} pvbc'.format(model.h/1e3, np.mean(model.Br)*model.B_star*1e3, np.mean(model.N)))
            else:
                title = ('{0:03d} k={3}, l={4}, m={5}, T={1:.2f}yrs, Q={2:.2f}'.format(ind, Period, Q, r_ord, th_ord, model.m)
                         + '\nH={:.0f}km, B={:.2f}mT, N={:.2f} pvbc'.format(model.h/1e3, np.mean(model.Br)*model.B_star*1e3, np.mean(model.N)))
            if (model.Nk > 1):
                # fplt.plot_fast_solution(model, vec, title=title, dir_name=out_dir)
                fplt.plot_full_solution(model, val, vec, title=title, dir_name=out_dir, layer_boundary=3380)
            else:
                if('br' in model.model_variables):
                    fplt.plot_1D(model, vec, val, ind, dir_name=out_dir, title=title)
                else:
                    fplt.plot_1D_noB(model, vec, val, ind, dir_name=out_dir, title=title)
            logger.info('\t plotted ind={0}, T={1:.2f}yrs (eig={2:.2e})'.format(ind, Period, val))
        logger.info('run complete')
    except:
        problem = "Problem Plotting Eigenvalues."
        logger.error(problem, exc_info=1)
        print('combination {0}/{1} broke, {2}'.format(c['iter_num'], c['total_iter'], problem))

        return
    dtime = (time_start + time.time())/60.
    print('done with combination {0}/{1} in {2:.2f}min'.format(c['iter_num'], c['total_iter'], dtime))
Exemple #12
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
Exemple #13
0
"""
# TODO: delete solver or keep and extend
# TODO: FEAST / other contour solvers?
# TODO: exponential, sqrt etc.
# TODO: region for eps in middle, both ciss and normal
# TODO: mumps set icntrl(14): catch error infog(1)=-9 and resatrt

import numpy as np
import scipy.sparse as sp
import petsc4py
import slepc4py
from petsc4py import PETSc
from slepc4py import SLEPc

petsc4py.init()
slepc4py.init()


def convert_to_petsc(a, comm=PETSc.COMM_WORLD):
    """ Convert a scipy sparse matrix to the relevant PETSc type, currently
    only supports csr, bsr, vectors and dense matrices formats. """
    if sp.isspmatrix_csr(a):
        a.sort_indices()
        csr = (a.indptr, a.indices, a.data)
        b = PETSc.Mat().createAIJ(size=a.shape, csr=csr, comm=comm)
    elif sp.isspmatrix_bsr(a):
        a.sort_indices()
        csr = (a.indptr, a.indices, a.data)
        b = PETSc.Mat().createBAIJ(size=a.shape, bsize=a.blocksize,
                                   csr=csr, comm=comm)
    elif a.ndim == 1:
Exemple #14
0
def getEigenvalues(func, args, N=64, EigvType="All"):

        import sys, slepc4py
        slepc4py.init(sys.argv)

        from petsc4py import PETSc
        from slepc4py import SLEPc
        import numpy as np

    
        # Equation
        class A(object):
                def __init__(self): pass

                def mult(self, A, x, y):
                  y[...] = func(x[...], args)
            
        
        context = A()
        A = PETSc.Mat().createPython((N,N), context)
        A.setUp()
        """
            def setupBMatrix():
                B = PETSc.Mat(dtype=complex); B.create()
                B.setSizes([N,N])
                B.setFromOptions()
                for n in range(N):
                    for m in range(N):
                        if m == n : B[n,m] =  - eps *  2. * omega[n]
                        else      : B[n,m] = 0.
                B.assemble()
                return B

            B = setupBMatrix() 
        """

        
        S = SLEPc.EPS().create()
        
        S.setOperators(A)
        #S.setOperators(A,B)
        S.setFromOptions()
        A.setFromOptions()
        S.setProblemType(SLEPc.EPS.ProblemType.NHEP)
        S.setBalance()
        S.setDimensions(N)
      
        #F1 = PETSc.Vec().createSeq(Nv)
        #F1.setValues(range(Nv), getInitialF1(ky))
        #S.setInitialSpace(F1)

        S.setTolerances(tol=1.e-15, max_it=500000)
    
        S.solve()
        
        its = S.getIterationNumber()
        sol_type = S.getType()
        nev, ncv, mpd = S.getDimensions()
        tol, maxit = S.getTolerances()
        nconv = S.getConverged()
        
        print("Number of converged eigenpairs: %d" % nconv)
        
        eigval = []
        eigvec = []
        
        if nconv > 0:
                ### (1) Get All eigenvalues ###
                xr, tmp = A.getVecs()
                xi, tmp = A.getVecs()
                for i in range(nconv):
                    k = S.getEigenpair(i, xr, xi)
                    error = S.computeRelativeError(i)
                    #print(" %9f%+9f j  %12g" % (k.real, k.imag, error))
                    eigval.append(k.real + k.imag * 1.j)
                    eigvec.append(xr[...] + 1.j * xi[...])
      
        return np.array(eigval), np.array(eigvec)
import sys, slepc4py
slepc4py.init(sys.argv)
from petsc4py import PETSc
from slepc4py import SLEPc
import numpy as np
import scipy as sc
import scipy.sparse as sp
import matplotlib.pyplot as plt
import scipy.linalg as spalg
from scipy.sparse.linalg import eigs

## Code for using nump/scipy only (with eig or eigs)

opts = PETSc.Options()
nEV = opts.getInt('nev', 5)
np.set_printoptions(threshold=np.nan)

Ly = 350e03
Lj = 20e03
Hm = 500
Ny = opts.getInt('Ny', 400)

f0 = 1.e-4
bet = 0
g0 = 9.81
rho = 1024
dkk = 2e-2

y = np.linspace(0,Ly, Ny+1)
hy = y[1] - y[0]
e = np.ones(Ny+1)
Exemple #16
0
import sys, slepc4py
slepc4py.init(sys.argv)

from petsc4py import PETSc
from slepc4py import SLEPc

Print = PETSc.Sys.Print


def construct_operators(m, n):
    """
    Standard symmetric eigenproblem corresponding to the
    Laplacian operator in 2 dimensions.
    """
    Print("Quadratic Eigenproblem, N=%d (%dx%d grid)" % (m * n, m, n))
    # K is the 2-D Laplacian
    K = PETSc.Mat().create()
    K.setSizes([n * m, n * m])
    K.setFromOptions()
    K.setUp()
    Istart, Iend = K.getOwnershipRange()
    for I in range(Istart, Iend):
        v = -1.0
        i = I // n
        j = I - i * n
        if i > 0:
            J = I - n
            K[I, J] = v
        if i < m - 1:
            J = I + n
            K[I, J] = v
Exemple #17
0
def getEigenvalues(func, args, N=64, EigvType="All"):

    import sys, slepc4py
    slepc4py.init(sys.argv)

    from petsc4py import PETSc
    from slepc4py import SLEPc
    import numpy as np

    # Equation
    class A(object):
        def __init__(self):
            pass

        def mult(self, A, x, y):
            y[...] = func(x[...], args)

    context = A()
    A = PETSc.Mat().createPython((N, N), context)
    A.setUp()
    """
            def setupBMatrix():
                B = PETSc.Mat(dtype=complex); B.create()
                B.setSizes([N,N])
                B.setFromOptions()
                for n in range(N):
                    for m in range(N):
                        if m == n : B[n,m] =  - eps *  2. * omega[n]
                        else      : B[n,m] = 0.
                B.assemble()
                return B

            B = setupBMatrix() 
        """

    S = SLEPc.EPS().create()

    S.setOperators(A)
    #S.setOperators(A,B)
    S.setFromOptions()
    A.setFromOptions()
    S.setProblemType(SLEPc.EPS.ProblemType.NHEP)
    S.setBalance()
    S.setDimensions(N)

    #F1 = PETSc.Vec().createSeq(Nv)
    #F1.setValues(range(Nv), getInitialF1(ky))
    #S.setInitialSpace(F1)

    S.setTolerances(tol=1.e-15, max_it=500000)

    S.solve()

    its = S.getIterationNumber()
    sol_type = S.getType()
    nev, ncv, mpd = S.getDimensions()
    tol, maxit = S.getTolerances()
    nconv = S.getConverged()

    print("Number of converged eigenpairs: %d" % nconv)

    eigval = []
    eigvec = []

    if nconv > 0:
        ### (1) Get All eigenvalues ###
        xr, tmp = A.getVecs()
        xi, tmp = A.getVecs()
        for i in range(nconv):
            k = S.getEigenpair(i, xr, xi)
            error = S.computeRelativeError(i)
            #print(" %9f%+9f j  %12g" % (k.real, k.imag, error))
            eigval.append(k.real + k.imag * 1.j)
            eigvec.append(xr[...] + 1.j * xi[...])

    return np.array(eigval), np.array(eigvec)