def Eigen_Value_Solver(Hamiltonian, input_par, l, energy, Viewer): number_of_eigenvalues = 1 k = np.sqrt(2 * energy) EV_Solver = SLEPc.EPS().create(comm=PETSc.COMM_WORLD) EV_Solver.setOperators(Hamiltonian) ##pass the hamiltonian to the # EV_Solver.setType(SLEPc.EPS.Type.JD) EV_Solver.setProblemType(SLEPc.EPS.ProblemType.NHEP) EV_Solver.setTolerances(input_par["tolerance"], PETSc.DECIDE) EV_Solver.setWhichEigenpairs(EV_Solver.Which.TARGET_REAL) EV_Solver.setTarget(energy) size_of_matrix = PETSc.Mat.getSize(Hamiltonian) dimension_size = int(size_of_matrix[0]) * 0.1 EV_Solver.setDimensions(number_of_eigenvalues, PETSc.DECIDE, dimension_size) EV_Solver.solve() ##solve the eigenvalue problem eigen_states = [[], []] for i in range(number_of_eigenvalues): eigen_vector = Hamiltonian.getVecLeft() eigen_state = EV_Solver.getEigenpair(i, eigen_vector) eigen_vector.setName("Psi_" + str(l) + "_" + str(i)) Viewer.view(eigen_vector) energy = PETSc.Vec().createMPI(1, comm=PETSc.COMM_WORLD) energy.setValue(0, eigen_state) energy.setName("Energy_" + str(l) + "_" + str(i)) energy.assemblyBegin() energy.assemblyEnd() Viewer.view(energy)
def compute_inf_sup_constant(spaces, b, inner_products): V, Q = spaces m, n = inner_products Z = V * Q u, p = firedrake.TrialFunctions(Z) v, q = firedrake.TestFunctions(Z) A = assemble(-(m(u, v) + b(v, p) + b(u, q)), mat_type='aij').M.handle M = assemble(n(p, q), mat_type='aij').M.handle opts = PETSc.Options() opts.setValue('eps_gen_hermitian', None) opts.setValue('eps_target_real', None) opts.setValue('eps_smallest_magnitude', None) opts.setValue('st_type', 'sinvert') opts.setValue('st_ksp_type', 'preonly') opts.setValue('st_pc_type', 'lu') opts.setValue('st_pc_factor_mat_solver_type', 'mumps') opts.setValue('eps_tol', 1e-8) num_values = 1 eigensolver = SLEPc.EPS().create(comm=firedrake.COMM_WORLD) eigensolver.setDimensions(num_values) eigensolver.setOperators(A, M) eigensolver.setFromOptions() eigensolver.solve() Vr, Vi = A.getVecs() λ = eigensolver.getEigenpair(0, Vr, Vi) return λ
def slepc_eigh(A, B, Z=None, is_hermitian=True): '''GEVP by SLEPc via lapack''' A, B = as_backend_type(A).mat(), as_backend_type(B).mat() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(A, B) E.setProblemType(SLEPc.EPS.ProblemType.GHEP) E.setType('lapack') print 'Z is', Z if Z is not None: print 'Set' Z = [as_backend_type(z).vec() for z in Z] E.setDeflationSpace(Z) # type is -eps_type E.solve() eigw = [] for i in range(E.getConverged()): eigw.append(E.getEigenvalue(i).real) eigw = np.array(eigw) idx = np.argsort(eigw) eigw = eigw[idx] v = A.createVecRight() eigv = [] for i in idx: E.getEigenvector(i, v) eigv.append(v.array.real.tolist()) print v.dot(Z[0]) eigv = np.array(eigv) return eigw, eigv.T
def main(): opts = PETSc.Options() n = opts.getInt('n', 32) m = opts.getInt('m', 32) Print("2-D Laplacian Eigenproblem solved with contour integral, " "N=%d (%dx%d grid)\n" % (m * n, m, n)) A = construct_operator(m, n) # Solver object E = SLEPc.EPS().create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setType(SLEPc.EPS.Type.CISS) # Define region of interest R = E.getRG() R.setType(SLEPc.RG.Type.ELLIPSE) R.setEllipseParameters(0.0, 0.2, 0.1) E.setFromOptions() # Compute solution E.solve() # Print solution vw = PETSc.Viewer.STDOUT() vw.pushFormat(PETSc.Viewer.Format.ASCII_INFO_DETAIL) E.errorView(viewer=vw) vw.popFormat()
def slep_powerit(Ptp, n): Ptp.transpose() E = SLEPc.EPS() E.create() E.setOperators(Ptp) E.setProblemType(SLEPc.EPS.ProblemType.NHEP) E.setTolerances(tol=1e-12) E.setFromOptions() E.solve() Print = PETSc.Sys.Print its = E.getIterationNumber() Print("Number of iterations of the method: %d" % its) eps_type = E.getType() Print("Solution method: %s" % eps_type) nconv = E.getConverged() Print("Number of converged eigenpairs %d" % nconv) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) if nconv > 0: vpost, wpost = Ptp.getVecs() vposti, wposti = Ptp.getVecs() k = E.getEigenpair(0, vpost, vposti) Print("Valeur propre" + str(k)) return abs(vpost)
def _create_eigenproblem_solver(self, A, M, num, problem_type, method_type, which, tol, maxit, shift_invert): """ Create a SLEPc eigenproblem solver with the operator """ # XXX TODO: This import should actually happen at the top, but on some # systems it seems to be slightly non-trivial to install # slepc4py, and since we don't use it for the default eigen- # value methods, it's better to avoid raising an ImportError # which forces users to try and install it. -- Max, 20.3.2014 from slepc4py import SLEPc E = SLEPc.EPS() E.create() E.setOperators(A, M) E.setProblemType(getattr(SLEPc.EPS.ProblemType, problem_type)) E.setType(getattr(SLEPc.EPS.Type, method_type)) E.setWhichEigenpairs(getattr(SLEPc.EPS.Which, which)) E.setDimensions(nev=num) E.setTolerances(tol, maxit) if shift_invert == True: st = E.getST() st.setType(SLEPc.ST.Type.SINVERT) st.setShift(0.0) return E
def eigensolver_setup(self, prefix=None): E = SLEPc.EPS() E.create() E.setType(SLEPc.EPS.Type.KRYLOVSCHUR) if hasattr(self, 'M'): E.setProblemType(SLEPc.EPS.ProblemType.GHEP) else: E.setProblemType(SLEPc.EPS.ProblemType.HEP) # if self.initial_guess: # E.setInitialSpace(self.initial_guess) E.setWhichEigenpairs(E.Which.TARGET_REAL) E.setTarget(-.1) st = E.getST() st.setType('sinvert') st.setShift(-1.e-3) if prefix: E.setOptionsPrefix(prefix) self.set_options(self.slepc_options) E.setFromOptions() return E
def main(): args = docopt(""" Usage: learn_spectral_embeddings.py [options] <adjacency_matrix_path> <type_of_laplacian> <output_path> Options: --pow NUM Every non-zero value in adjacency matrix will be scaled^{pow} [default: 1.0] --max_iter NUM Maximum number of iterations of LOBPCG algorithm [default: 100] --dim NUM Number of eigen-pairs to return [default: 500] --verbosity NUM Verbosity level of LOBPCG solver [default: 0] --pmi Turn adjacency matrix into PMI-based adjacency matrix --neg NUM Negative sampling for PMI-based adjacency matrix [default: 1] --scale_weights Scale weights of the adjacency matrix between 0 and 1 --tune_rhoB Solve quadratic eigenproblem to find better rhoB estimation """) start = time.time() adjacency_matrix_path = args["<adjacency_matrix_path>"] adjacency_matrix = load_npz(adjacency_matrix_path + ".adjacency.npz") _, iw = load_vocabulary(adjacency_matrix_path + ".words.vocab") ### Build laplacian n = adjacency_matrix.shape[0] degrees = np.asarray(adjacency_matrix.sum(axis=1)).flatten() D = scipy.sparse.spdiags(degrees, [0], n, n, format='csr') L = D - adjacency_matrix degrees_sqrt = np.sqrt(degrees) DH = scipy.sparse.spdiags(1.0 / degrees_sqrt, [0], n, n, format='csr') L = DH.dot(L.dot(DH)) ### Build PETSc sparse matrix A = PETSc.Mat().create() A.setSizes([n, n]) A.setFromOptions() A.setUp() inds = L.nonzero() for row_ind, col_ind in np.stack(inds, axis=1): value = L[row_ind, col_ind] assert value != 0 A[row_ind, col_ind] = value A.assemble() ### Solve eigenvalue problem E = SLEPc.EPS() E.create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setFromOptions() E.setWhichEigenpairs(SLEPc.EPS.Which.SMALLEST_MAGNITUDE) print("Time elapsed %f" % (time.time() - start))
def get_extreme_eigw(A, B, Z, params, which): '''Use SLEPC for fish for extremal eigenvalues of GEVP(A, B)''' is_symmetric = is_hermitian(A, tol=1E-8 * A.size(0)) assert is_symmetric # From monolithic matrices to petsc A, B = (as_backend_type(x).mat() for x in (A, B)) # Wrap opts = PETSc.Options() for key, value in params.items(): opts.setValue(key, None if value == 'none' else value) # Setup the eigensolver E = SLEPc.EPS().create() if Z is not None: Z = [as_backend_type(z).vec() for z in Z] E.setDeflationSpace(Z) E.setOperators(A, B) # type is -eps_type if is_symmetric: E.setProblemType(SLEPc.EPS.ProblemType.GHEP) else: assert False E.setProblemType(SLEPc.EPS.ProblemType.GNHEP) # Whch E.setWhichEigenpairs(which) # For 'small' system the shifted problems will use direct solver flag = 'slepc_direct' # Otherwise using shift and invert spectral transformation with zero shift # itertively # NOTE: these can ge configured from commandiline if A.size[0] > 2E6: flag = 'slepc_iter' ST = E.getST() ST.setType('sinvert') KSP = ST.getKSP() KSP.setType('cg') # How to invert the B matrix PC = KSP.getPC() # NOTE: with these setting the cost is as high as direct PC.setType('lu') PC.setFactorSolverPackage('mumps') KSP.setFromOptions() E.setFromOptions() E.solve() its = E.getIterationNumber() nconv = E.getConverged() eigw = [E.getEigenvalue(i).real for i in range(nconv)] return eigw, flag
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
def test_laplace_physical_ev(parallel=False): try: from slepc4py import SLEPc except ImportError: pytest.skip(msg="SLEPc unavailable, skipping eigenvalue test") mesh = UnitSquareMesh(64, 64) V = FunctionSpace(mesh, 'CG', 1) u = TrialFunction(V) v = TestFunction(V) bc = DirichletBC(V, Constant(0.0), (1, 2, 3, 4)) # We just need the Stiffness and Mass matrix a = inner(grad(u), grad(v)) * dx m = inner(u, v) * dx A = topetsc(assemble(a, bcs=[bc])) M = topetsc(assemble(m, bcs=[bc])) # This shifts the "1.0" Eigenvalues out of the spectrum # of interest (which is around 0.0 in this case). vals = np.repeat(1E8, len(bc.nodes)) A.setValuesLocalRCV(bc.nodes.reshape(-1, 1), bc.nodes.reshape(-1, 1), vals.reshape(-1, 1)) A.assemble() E = SLEPc.EPS() E.create() E.setOperators(A, M) st = E.getST() st.setType('sinvert') kspE = st.getKSP() kspE.setType('fgmres') E.setDimensions(5, PETSc.DECIDE) E.solve() nconv = E.getConverged() assert (nconv > 0) # Create the results vectors vr, wr = A.getVecs() vi, wi = A.getVecs() ev = [] for i in range(nconv): k = E.getEigenpair(i, vr, vi) ev.append(k.real) # Exact eigenvalues are ev_exact = np.array([ 1**2 * np.pi**2 + 1**2 * np.pi**2, 2**2 * np.pi**2 + 1**2 * np.pi**2, 1**2 * np.pi**2 + 2**2 * np.pi**2 ]) assert np.allclose(ev_exact, np.array(ev)[:3], atol=1e-1)
def __init__(self, A, B): self.eps = SLEPc.EPS().create(wrapping.get_mpi_comm(A)) if B is not None: self.A = wrapping.to_petsc4py(A) self.B = wrapping.to_petsc4py(B) self.eps.setOperators(self.A, self.B) else: self.A = wrapping.to_petsc4py(A) self.B = None self.eps.setOperators(self.A)
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]
def eigsh_slepc(A, k, tol, max_iter): ### Setup matrix operator n = A.shape[0] mat = MatrixOperator(A) A_operator = PETSc.Mat().createPython([n, n], mat) A_operator.setUp() ### Solve eigenproblem E = SLEPc.EPS() E.create() E.setOperators(A_operator) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setDimensions(k) E.setTolerances(tol, max_iter) E.setWhichEigenpairs(SLEPc.EPS.Which.SMALLEST_REAL) def monitor_fun(eps, iters, nconv, eigs, errors): print("Current iteration: %d, number of converged eigenvalues: %d" % (iters, nconv)) E.setMonitor(monitor_fun) E.solve() print("Number of calls to Ax: %d" % mat.n_calls) ### Collect results print("") its = E.getIterationNumber() print("Number of iterations of the method: %i" % its) sol_type = E.getType() print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() print("NEV %d NCV %d MPD %d" % (nev, ncv, mpd)) tol, maxit = E.getTolerances() print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.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]) vals = np.zeros(nconv) xr, tmp = A_operator.getVecs() xi, tmp = A_operator.getVecs() if nconv > 0: for i in range(nconv): k = E.getEigenpair(i, xr, xi) vals[i] = k.real vecs[:, i] = xr return vals, vecs
def __init__(self, Mat, n_eigvals=1, n_initial=1): self.eps = SLEPc.EPS() self.Mat = Mat self.eps.create(self.Mat.getComm()) self.eps.setOperators(self.Mat) self.n_eigvals = n_eigvals self.eps.setDimensions(nev=self.n_eigvals, ncv=PETSc.DECIDE, mpd=PETSc.DECIDE) self.eps.setProblemType(SLEPc.EPS.ProblemType.HEP) self.eps.setType(SLEPc.EPS.Type.JD) self.eps.setWhichEigenpairs(SLEPc.EPS.Which.SMALLEST_REAL) self.eps.max_it = 99
def __init__(self, PType, SType): self.E = spc.EPS().create() if PType == "GHEP": self.E.setProblemType(spc.EPS.ProblemType.GHEP) elif PType == "HEP": self.E.setProblemType(spc.EPS.ProblemType.HEP) elif PType == "NHEP": self.E.setProblemType(spc.EPS.ProblemType.NHEP) elif PType == "GNHEP": self.E.setProblemType(spc.EPS.ProblemType.GNHEP) self.E.setType(SType)
def solve_eigensystem(A, B, problem_type=SLEPc.EPS.ProblemType.GHEP): # Create the results vectors xr, tmp = A.getVecs() xi, tmp = A.getVecs() pc = PETSc.PC().create() # pc.setType(pc.Type.HYPRE) pc.setType(pc.Type.BJACOBI) ksp = PETSc.KSP().create() ksp.setType(ksp.Type.PREONLY) ksp.setPC(pc) F = SLEPc.ST().create() F.setType(F.Type.PRECOND) F.setKSP(ksp) F.setShift(0) # Setup the eigensolver E = SLEPc.EPS().create() E.setST(F) E.setOperators(A, B) E.setType(E.Type.LOBPCG) E.setDimensions(10, PETSc.DECIDE) E.setWhichEigenpairs(E.Which.SMALLEST_REAL) E.setProblemType(problem_type) E.setFromOptions() # Solve the eigensystem E.solve() Print("") its = E.getIterationNumber() Print("Number of iterations of the method: %i" % its) sol_type = E.getType() Print("Solution method: %s" % sol_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %i" % nev) tol, maxit = E.getTolerances() Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() Print("Number of converged eigenpairs: %d" % nconv) if nconv > 0: Print("") Print(" k ||Ax-kx||/||kx|| ") Print("----------------- ------------------") for i in range(nconv): k = E.getEigenpair(i, xr, xi) error = E.computeError(i) if k.imag != 0.0: Print(" %9f%+9f j %12g" % (k.real, k.imag, error)) else: Print(" %12f %12g" % (k.real, error)) Print("")
def eigensolver_setup(self): E = SLEPc.EPS() E.create() E.setType(SLEPc.EPS.Type.KRYLOVSCHUR) E.setProblemType(SLEPc.EPS.ProblemType.GHEP) #E.setWhichEigenpairs(E.Which.SMALLEST_MAGNITUDE) E.setWhichEigenpairs(E.Which.TARGET_MAGNITUDE) E.setTarget(0) st = E.getST() st.setType('sinvert') return E
def eigensolver_setup(self): E = SLEPc.EPS() E.create() E.setType(SLEPc.EPS.Type.KRYLOVSCHUR) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setWhichEigenpairs(E.Which.TARGET_REAL) E.setTarget(-.1) st = E.getST() st.setType('sinvert') st.setShift(-1.e-3) return E
def OptimalForcingsSLEPc(FR, shell, nev): comm = MPI.COMM_WORLD rank = comm.Get_rank() f = FR.getVecRight() q = shell.L.getVecRight() tmp = shell.L.getVecRight() ndof_f = f.getSize() ndof_q = q.getSize() # Setup EPS Print(' - Setting the EPS') S = SLEPc.EPS() S.create(comm) S.setOperators(FR) S.setDimensions(nev=nev, ncv=10) S.setTolerances(tol=1e-6, max_it=100) S.setFromOptions() # Solve the EVP Print(" - Solving the EPS") S.solve() its = S.getIterationNumber() nconv = S.getConverged() if rank == 0: eigvals = zeros(nconv, 'complex') fs = zeros([ndof_f, nconv], 'complex') qs = zeros([ndof_q, nconv], 'complex') else: eigvals = None fs = None qs = None for i in range(nconv): eigval = S.getEigenpair(i, f) shell.Pu.mult(f, q) shell.B2.mult(q, tmp) shell.ksp.solve(tmp, q) q.scale(-1.0) vf = Vec2DOF(f) vq = Vec2DOF(q) if rank == 0: eigvals[i] = eigval fs[:, i] = vf qs[:, i] = vq return eigvals, fs, qs
def eigensolver_setup(self): E = SLEPc.EPS() E.create() E.setType(SLEPc.EPS.Type.KRYLOVSCHUR) #E.setType(SLEPc.EPS.Type.LANCZOS) E.setProblemType(SLEPc.EPS.ProblemType.GHIEP) #E.setWhichEigenpairs(E.Which.LARGEST_MAGNITUDE) E.setWhichEigenpairs(E.Which.TARGET_MAGNITUDE) E.setTarget(0.) st = E.getST() st.setType('sinvert') st.setShift(1.e-3) return E
def solve_fancy(P, beta_trial, E_trial=None, neigs=1): """ Solves eigenproblem with fancier tools """ from petsc4py import PETSc from slepc4py import SLEPc t = time.time() # convert eigenproblem into a form that petsc can understand fancy_P = PETSc.Mat().createAIJ(size=P.shape, csr=(P.indptr, P.indices, P.data)) # initalise solver object E = SLEPc.EPS() E.create() # lets set the solver options E.setOperators(fancy_P) E.setProblemType(SLEPc.EPS.ProblemType.NHEP) E.setDimensions(nev=neigs) if E_trial != None: E.setInitialSpace(E_trial) # now we set up the spectral region to look in E.setTarget(beta_trial**2) E.setWhichEigenpairs(7) #look for closest in absoult value #beta_trial**2) print('Solving eigenmodes using fancy solver') E.solve() #now we can start unpacking nconv = E.getConverged() beta = [] Ex = [] Ey = [] vr, wr = fancy_P.getVecs() vi, wi = fancy_P.getVecs() for i in range(nconv): beta.append(E.getEigenpair(i, vr, vi)**0.5) #beta.append(E.getEigenvalue(i)**0.5) Exr, Eyr = np.split(np.array(vr), 2) Exi, Eyi = np.split(np.array(vi), 2) Ex.append(Exr + 1j * Exi) Ey.append(Eyr + 1j * Eyi) E.destroy() fancy_P.destroy() return beta, Ex, Ey
def projectCovToMesh(self, num_kl, cov_expr): """TODO: Docstring for projectCovToMesh. Solves CX = BX where C is the covariance matrix :num_kl : number of kl exapansion terms needed :returns: TODO """ # turn the flag to true self.flag = True # get C,B matrices C = self.getCovMat(cov_expr) B = self._getBMat() # Solve the generalized eigenvalue problem eigensolver = SLEPc.EPS() eigensolver.create() eigensolver.setOperators(C, B) eigensolver.setDimensions(num_kl) eigensolver.setProblemType(SLEPc.EPS.ProblemType.GHEP) eigensolver.setFromOptions() eigensolver.solve() # Get the number of eigen values that converged. #nconv = eigensolver.get_number_converged() # Get N eigenpairs where N is the number of KL expansion and check if N < nconv otherwise you had # really bad matrix # create numpy array of vectors and eigenvalues self.eigen_funcs = np.empty((num_kl), dtype=object) self.eigen_vals = np.empty((num_kl), dtype=float) # store the eigenvalues and eigen functions V = FunctionSpace(self._mesh, "CG", 1) x_real = PETSc.Vec().create() x_real.setSizes(self.domain.getNodes()) x_real.setUp() x_real.setValues(np.arange(0, self.domain.getNodes()), np.zeros(self.domain.getNodes())) # for i in range(0, self.domain.getNodes()): # x_real.setValue(i, 0, 0.) for eigen_pairs in range(0, num_kl): lam = eigensolver.getEigenpair(eigen_pairs, x_real) self.eigen_funcs[eigen_pairs] = Function(V) # use dof_to_vertex map to map values to the function space self.eigen_funcs[eigen_pairs].vector()[:] = x_real.getValues( dof_to_vertex_map(V).astype('int32')) # divide by norm to make the unit norm again self.eigen_funcs[eigen_pairs].vector()[:] = self.eigen_funcs[eigen_pairs].vector()[:] / \ norm(self.eigen_funcs[eigen_pairs]) self.eigen_vals[eigen_pairs] = lam.real
def Eigen_Value_Solver(Hamiltonian, number_of_eigenvalues, input_par, l, Viewer): EV_Solver = SLEPc.EPS().create(comm=PETSc.COMM_WORLD) EV_Solver.setOperators(Hamiltonian) # EV_Solver.setType(SLEPc.EPS.Type.JD) EV_Solver.setProblemType(SLEPc.EPS.ProblemType.NHEP) EV_Solver.setTolerances(input_par["tolerance"], PETSc.DECIDE) EV_Solver.setWhichEigenpairs(EV_Solver.Which.SMALLEST_REAL) size_of_matrix = PETSc.Mat.getSize(Hamiltonian) dimension_size = int(size_of_matrix[0]) * 0.1 EV_Solver.setDimensions(number_of_eigenvalues, PETSc.DECIDE, dimension_size) EV_Solver.solve() num_of_cont = 0 if rank == 0: print("Number of eigenvalues requested and converged") print(number_of_eigenvalues, EV_Solver.getConverged(), "\n") converged = EV_Solver.getConverged() for i in range(converged): eigen_vector = Hamiltonian.getVecLeft() eigen_state = EV_Solver.getEigenpair(i, eigen_vector) if eigen_state.real < 0: eigen_vector.setName("BS_Psi_" + str(l) + "_" + str(i + l + 1)) Viewer.view(eigen_vector) energy = PETSc.Vec().createMPI(1, comm=PETSc.COMM_WORLD) energy.setValue(0,eigen_state) energy.setName("BS_Energy_" + str(l) + "_" + str(i + l + 1)) energy.assemblyBegin() energy.assemblyEnd() Viewer.view(energy) else: eigen_vector.setName("CS_Psi_" + str(l) + "_" + str(num_of_cont)) Viewer.view(eigen_vector) energy = PETSc.Vec().createMPI(1, comm=PETSc.COMM_WORLD) energy.setValue(0,eigen_state) energy.setName("CS_Energy_" + str(l) + "_" + str(num_of_cont)) energy.assemblyBegin() energy.assemblyEnd() Viewer.view(energy) num_of_cont += 1 return num_of_cont
def compute_spectrum(mat, filename): from slepc4py import SLEPc eps = SLEPc.EPS().create() eps.setDimensions(10) eps.setOperators(mat) # Compute 10 eigenvalues with smallest magnitude eps.setWhichEigenpairs(eps.Which.SMALLEST_MAGNITUDE) eps.solve() smallest = np.array([eps.getEigenvalue(i) for i in range(eps.getConverged())]) np.save(filename + '_smallest.npy', smallest) # Compute 10 eigenvalues with largest magnitude eps.setWhichEigenpairs(eps.Which.LARGEST_MAGNITUDE) eps.solve() largest = np.array([eps.getEigenvalue(i) for i in range(eps.getConverged())]) np.save(filename + '_largest.npy', largest)
def find_eigval(H): print("Importing Stuff") import sys, slepc4py from petsc4py import PETSc from slepc4py import SLEPc import numpy A = PETSc.Mat().create() print(H.shape) A.setSizes(H.shape) A.setFromOptions() A.setUp() A[:, :] = np.array(H, dtype=np.complex64)[:, :] A.assemble() E = SLEPc.EPS() E.create() E.setOperators(A) E.setProblemType(SLEPc.EPS.ProblemType.HEP) E.setDimensions(nev=H.shape[0]) E.setTolerances(1e-8, 1000) E.setFromOptions() E.solve() Print = PETSc.Sys.Print Print() Print("******************************") Print("*** SLEPc Solution Results ***") Print("******************************") Print() its = E.getIterationNumber() Print("Number of iterations of the method: %d" % its) eps_type = E.getType() Print("Solution method: %s" % eps_type) nev, ncv, mpd = E.getDimensions() Print("Number of requested eigenvalues: %d" % nev) Print( " the maximum dimension of the subspace to be used by the solver: %d " % ncv) Print(" the maximum dimension allowed for the projected problem: %d" % mpd) #tol, maxit = E.getTolerances() #Print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit)) nconv = E.getConverged() ans = [] for i in range(nconv): ans.append(E.getEigenvalue(i)) return ans
def configure_solver(self): eps = SLEPc.EPS().create() st = eps.getST() st.setType("sinvert") # Set up the linear solver ksp = st.getKSP() ksp.setType("preonly") pc = ksp.getPC() pc.setType("lu") pc.setFactorSolverType("mumps") # Set up number of (default) modes to converge eps.setDimensions(self.nof_modes_to_converge, SLEPc.DECIDE) return eps
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
def krylovschur(A, n, massmatrix=None, onseperation="continue"): if massmatrix is not None: raise NotImplementedError if onseperation != "continue": raise NotImplementedError from petsc4py import PETSc from slepc4py import SLEPc M = petsc_matrix(A) E = SLEPc.EPS().create() E.setOperators(M) E.setDimensions(nev=n) E.setWhichEigenpairs(E.Which.LARGEST_REAL) E.solve() X = np.column_stack([x.array for x in E.getInvariantSubspace()]) return X[:, :n]
def DirectModeSLEPc(ffdisc, shift, nev): from petsc4py import PETSc from slepc4py import SLEPc # Operators print 'Set operators' Lmat = CSR2Mat(ffdisc.L) Bmat = CSR2Mat(ffdisc.B) # Setup EPS print 'Set solver' S = SLEPc.EPS() S.create() S.setTarget(shift) S.setWhichEigenpairs(SLEPc.EPS.Which.TARGET_MAGNITUDE) SI = SLEPc.ST().create() SI.setType(SLEPc.ST.Type.SINVERT) SI.setOperators(Lmat, Bmat) SI.setShift(shift) S.setST(SI) S.setDimensions(nev=nev, ncv=60) S.setTolerances(tol=tol_ev, max_it=100) S.setFromOptions() # Solve the EVP print 'Solving EVP' S.solve() its = S.getIterationNumber() nconv = S.getConverged() omega = zeros(nconv, 'complex') modes = zeros([ffdisc.ndof, nconv], 'complex') ev = Lmat.getVecRight() for i in range(nconv): eigval = S.getEigenpair(i, ev) v = Vec2DOF(ev) omega[i] = eigval / (-1j) modes[:, i] = v return omega, modes