def scipy_to_petsc(A): """Converts SciPy CSR matrix to PETSc serial matrix.""" nrows = A.shape[0] ncols = A.shape[1] ai, aj, av = A.indptr, A.indices, A.data mat = PETSc.Mat() mat.createAIJ(size=(nrows, ncols)) mat.setUp() mat.setValuesCSR(ai, aj, av) mat.assemble() return mat
def _as_petscmat(self): if df.has_petsc4py(): from petsc4py import PETSc # mat = PETSc.Mat().createPython(df.as_backend_type(self.prior.M).mat().getSizes(), comm = self.prior.mpi_comm) mat = PETSc.Mat().createPython(self.prior.dim, comm=self.prior.mpi_comm) mat.setPythonContext(self) return df.PETScMatrix(mat) else: df.warning( 'Petsc4py not installed: cannot generate PETScMatrix with specified size!' ) pass
def _init_nest(self): mat = PETSc.Mat() self._blocks = [] rows, cols = self.sparsity.shape for i in range(rows): row = [] for j in range(cols): row.append(Mat(self.sparsity[i, j], self.dtype, '_'.join([self.name, str(i), str(j)]))) self._blocks.append(row) # PETSc Mat.createNest wants a flattened list of Mats mat.createNest([[m.handle for m in row_] for row_ in self._blocks]) self._handle = mat
def __init__(self, n): from petsc4py import PETSc A = PETSc.Mat().create() A.setSizes(n) A.setType('aij') A.setUp() A.assemblyBegin() for i in range(n): A[i, i] = 1 if i + 1 < n: A[i, i + 1] = i A.assemblyEnd() self.A = A
def CSR2Mat(L): from petsc4py import PETSc if L.format == 'csr': L2 = L else: L2 = L.tocsr() B = PETSc.Mat() B.createAIJ(L2.shape, csr=(L2.indptr, L2.indices, L2.data)) return B
def _block_mat_mult(a, b, comm=MPI.COMM_WORLD): a_global_rows, a_global_cols = a.globalshape a_local_rows, a_local_cols = a.shape b_global_rows, b_global_cols = b.globalshape b_local_rows, b_local_cols = b.shape A = PETSc.Mat().create(comm=comm) A.setSizes((a_global_rows, a_global_cols)) A.setFromOptions() A.setPreallocationNNZ((a_global_rows, a_global_cols)) A_row_start, A_row_end = A.getOwnershipRange() A.setValues(range(A_row_start, A_row_end), range(a_global_cols), a) A.assemblyBegin() A.assemblyEnd() B = PETSc.Mat().create(comm=comm) B.setSizes((b_global_rows, b_global_cols)) B.setFromOptions() B.setPreallocationNNZ((b_global_rows, b_global_cols)) B_row_start, B_row_end = B.getOwnershipRange() B.setValues(range(B_row_start, B_row_end), range(b_global_cols), b) B.assemblyBegin() B.assemblyEnd() C = A.matMult(B) size = comm.Get_size() rank = comm.Get_rank() comm_dims = get_comm_dims(size, 'b') comm_coord = get_cart_coords(comm_dims, size, rank) return Distribution_Dict['b'](C.getValues(range(A_row_start, A_row_end), range(b_global_cols)), comm=comm, comm_dims=comm_dims, comm_coord=comm_coord)
def CreatePETScMatrix(ngs_mat): pardofs = ngs_mat.row_pardofs # comm = MPI.COMM_WORLD comm = pardofs.comm.mpi4py globnums, nglob = pardofs.EnumerateGlobally() iset = psc.IS().createGeneral(indices=globnums, comm=comm) lgmap = psc.LGMap().createIS(iset) locmat = ngs_mat.local_mat val, col, ind = locmat.CSR() ind = np.array(ind, dtype='int32') apsc_loc = psc.Mat().createAIJ(size=(locmat.height, locmat.width), csr=(ind, col, val), comm=MPI.COMM_SELF) mat = psc.Mat().createPython(size=nglob, comm=comm) mat.setType(psc.Mat.Type.IS) mat.setLGMap(lgmap) mat.setISLocalMat(apsc_loc) mat.assemble() mat.convert("mpiaij") return mat
def testCreateInterpolation(self): mat = PETSc.Mat().create() mat.setSizes(((10, None), (10, None))) mat.setUp() vec = PETSc.Vec().create() vec.setSizes((10, None)) vec.setUp() def create_interp(dm, dmf): return mat, vec self.dm.setCreateInterpolation(create_interp) m, v = self.dm.createInterpolation(self.dm) self.assertEqual(m, mat) self.assertEqual(v, vec)
def minres(A, b, uh): PA = PETSc.Mat().createAIJ(size=A.shape, csr=(A.indptr, A.indices, A.data)) Pb = PETSc.Vec().createWithArray(b) x = PETSc.Vec().createWithArray(uh) ksp = PETSc.KSP().create() #ksp.setType('minres') pc = ksp.getPC() pc.setType('none') ksp.setOperators(PA) ksp.setFromOptions() ksp.solve(Pb, x)
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 solve_nonlinear(self, inputs, outputs): self.K = self.assemble_CSC_K(inputs) #from scipy.io import savemat #savemat('K', {'K': self.K}) rank = MPI.COMM_WORLD.rank if rank == 0: print("solving linear system") rank = PETSc.COMM_WORLD.rank num_elements = self.options['num_elements'] num_nodes = num_elements + 1 size = 2 * num_nodes + 2 A = PETSc.Mat() A.create(comm=MPI.COMM_WORLD) A.setSizes([size, size]) A.setType("aij") A.setUp() rows, cols, data = self.assemble_struct_K(inputs) #np.save('rows',rows) #np.save('cols',cols) #np.save('data',data) for idx, (row, col) in enumerate(zip(rows, cols)): A.setValue(row, col, data[idx]) A.setValue(size - 2, size - 2, 0) A.setValue(size - 1, size - 1, 0) A.assemble() x, f = A.createVecs() x.set(0) f.set(0) f.setValue(size - 4, -1) f.assemble() ksp = PETSc.KSP() ksp.create(MPI.COMM_WORLD) ksp.setOperators(A) ksp.setFromOptions() ksp.setType('bicg') ksp.getPC().setType('jacobi') ksp.solve(f, x) res = ksp.getResidualNorm() local_x = np.zeros(size) id_start, id_end = A.getOwnershipRange() # print("processors %d"%rank," owns %d,%d"%(id_start,id_end)) local_x[id_start:id_end] = x[...] global_x = np.zeros(size) #print(np.dot(A[:, :], global_x)-f[:]) # print(np.array(x)) MPI.COMM_WORLD.Reduce([local_x, MPI.DOUBLE], [global_x, MPI.DOUBLE], op=MPI.SUM) if rank == 0: outputs['d'] = global_x
def eigfind(mac): n = mac.getSize() Dt = Vec() mac.getDiagonal(Dt) Dt.reciprocal() Dpt = PETSc.Mat().createAIJ([n, n]) Dpt.setUp() Dpt.setDiagonal(Dt) Dpt.assemblyBegin() Dpt.assemblyEnd() tarmat = Dpt * mac def solve_eigensystem(Ac, problem_type=SLEPc.EPS.ProblemType.HEP): # Create the result vectors xr, xi = Ac.createVecs() # Setup the eigensolver E = SLEPc.EPS().create() E.setOperators(Ac, None) E.setDimensions(2, PETSc.DECIDE) 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("") solve_eigensystem(tarmat)
def FluidNonLinearSetup(Pressure, mu, u_k): MO.PrintStr("Preconditioning Fluid linear setup", 3, "=") #parameters['linear_algebra_backend'] = 'uBLAS' p = TrialFunction(Pressure) q = TestFunction(Pressure) mesh = Pressure.mesh() N = FacetNormal(Pressure.mesh()) h = CellSize(Pressure.mesh()) h_avg = avg(h) alpha = 10.0 gamma = 10.0 tic() if Pressure.__str__().find("CG") == -1: Fp = assemble(mu*(jump(q)*jump(p)*dx(mesh)) \ + inner(inner(grad(p),u_k),q)*dx(mesh)- (1/2)*inner(u_k,N)*inner(q,p)*ds(mesh) \ -(1/2)*(inner(u_k('+'),N('+'))+inner(u_k('-'),N('-')))*avg(inner(q,p))*ds(mesh) \ -dot(avg(q),dot(outer(p('+'),N('+'))+outer(p('-'),N('-')),avg(u_k)))*dS(Pressure.mesh())) else: if mesh.topology().dim() == 2: Fp = assemble(mu * inner(grad(q), grad(p)) * dx(mesh) + inner( (u_k[0] * grad(p)[0] + u_k[1] * grad(p)[1]), q) * dx(mesh) + (1 / 2) * div(u_k) * inner(p, q) * dx(mesh) - (1 / 2) * (u_k[0] * N[0] + u_k[1] * N[1]) * inner(p, q) * ds(mesh)) else: Fp = assemble(mu * inner(grad(q), grad(p)) * dx(mesh) + inner((u_k[0] * grad(p)[0] + u_k[1] * grad(p)[1] + u_k[2] * grad(p)[2]), q) * dx(mesh) + (1 / 2) * div(u_k) * inner(p, q) * dx(mesh) - (1 / 2) * (u_k[0] * N[0] + u_k[1] * N[1] + u_k[2] * N[2]) * inner(p, q) * ds(mesh)) Fp = PETSc.Mat().createAIJ(size=Fp.sparray().shape, csr=(Fp.sparray().indptr, Fp.sparray().indices, Fp.sparray().data)) print("{:40}" ).format("DG convection-diffusion assemble, time: "), " ==> ", ( "{:4f}").format( toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) tic() kspFp = NSprecondSetup.PCDKSPnonlinear(Fp) print("{:40}").format("Non-linear fluid precond, time: "), " ==> ", ( "{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) print "\n\n" return kspFp, Fp
def loadMat(filename, filetype, delimiter=None): """ Import a PETSc matrix from a file. Args: filename (str): path to input file. filetype (str): the filetype. * ``'txt'`` - a 2D matrix array in text format. * ``'bin'`` - a PETSc matrix vector. delimiter (str): this is passed to `numpy.genfromtxt\ <http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html>`_ in the case of strange delimiters in an imported ``txt`` file. """ if filetype == 'txt': try: try: if delimiter is None: matArray = _np.genfromtxt(filename, dtype=_PETSc.ScalarType) else: matArray = _np.genfromtxt(filename, dtype=_PETSc.ScalarType, delimiter=delimiter) except: filefix = [] for line in _fl.FileInput(filename, inplace=0): if line[2] != 't': line = line.replace(" i", "j") line = line.replace(" -", "-") line = line.replace("+-", "-") filefix.append(line) matArray = _np.genfromtxt(filefix, dtype=_PETSc.ScalarType) return arrayToMat(matArray) except: print "\nERROR: input state space file " + filename\ + " does not exist or is in an incorrect format" _sys.exit() elif filetype == 'bin': binLoad = _PETSc.Viewer().createBinary(filename, 'r') try: return _PETSc.Mat().load(binLoad) except: print "\nERROR: input state space file " + filename\ + " does not exist or is in an incorrect format" _sys.exit() binLoad.destroy()
def setup(self, system): """ Setup petsc problem just once. Args ---- system : `System` Parent `System` object. """ if not system.is_active(): return # allocate and cache the ksp problem for each voi for voi in system.dumat: sizes = system._local_unknown_sizes[voi] lsize = np.sum(sizes[system.comm.rank, :]) size = np.sum(sizes) if trace: debug("creating petsc matrix of size (%d,%d)" % (lsize, size)) jac_mat = PETSc.Mat().createPython([(lsize, size), (lsize, size)], comm=system.comm) if trace: debug("petsc matrix creation DONE for %s" % voi) jac_mat.setPythonContext(self) jac_mat.setUp() if trace: # pragma: no cover debug("creating KSP object for system", system.pathname) ksp = self.ksp[voi] = PETSc.KSP().create(comm=system.comm) if trace: debug("KSP creation DONE") ksp.setOperators(jac_mat) ksp.setType(self.options['ksp_type']) ksp.setGMRESRestart(1000) ksp.setPCSide(PETSc.PC.Side.RIGHT) ksp.setMonitor(Monitor(self)) if trace: # pragma: no cover debug("ksp.getPC()") debug("rhs_buf, sol_buf size: %d" % lsize) pc_mat = ksp.getPC() pc_mat.setType('python') pc_mat.setPythonContext(self) if trace: # pragma: no cover debug("ksp setup done") if self.preconditioner: self.preconditioner.setup(system)
def __init__(self, n_rows, n_cols, row_val_iterator, mpi_comm=PETSc.COMM_WORLD, *args, **kwargs): self.mpi_comm = mpi_comm self.mat = PETSc.Mat(*args, **kwargs) self.n_rows = n_rows self.n_cols = n_cols self.n_nonzeros = 0 SLEPc self.mat.setSizes([n_rows, n_cols]) self.mat.setFromOptions() self.mat.setUp() self.fill(row_val_iterator) self.row_val_iterator = row_val_iterator
def main(y): # lamb = 1.2 # print y.toarray() lam = np.linspace(0, 2, num_iter) GSV = np.zeros((num_iter)) # print b_matrix().transpose().dot(y).toarray() R, Q = qr() print "end QR" for i in xrange(num_iter): GSV[i] = CV(Q, R, lam[i], y) print GSV[i], i a = np.unravel_index(GSV.argmin(), GSV.shape) lamb = lam[a] print b_matrix().transpose().dot(y).toarray() b = PETSc.Vec().createSeq(m * m) b.setValues(range(m * m), b_matrix().transpose().dot(y).toarray()) D = np.eye(m * m) D[:1, :] = 0 D = sparse.coo_matrix(D).dot(lamb) B = b_matrix().transpose().dot(b_matrix()) B = D + B A = PETSc.Mat() A.create(comm) A.setSizes([m * m, m * m]) A.setType('mpidense') A.setUp() A.setValues(range(m * m), range(m * m), B.toarray()) A.assemblyBegin() A.assemblyEnd() x = PETSc.Vec().createSeq(m * m) ksp = PETSc.KSP().create() ksp.setOperators(A) ksp.setFromOptions() ksp.setType('cg') #ksp.set print 'Solving with:', ksp.getType() ksp.solve(b, x) #SS.setValues(range(m*m), range(m*m),B.toarray()) #S = sparse.kron(S,SX) print 'Converged in', ksp.getIterationNumber(), 'iterations.' # print x.getArray() x = sparse.coo_matrix(x.getArray()) fun = b_matrix().dot(x.transpose()).toarray() # x = np.linspace(0,1,n) # Z = np.reshape(fun,(n,n)) # fig = plt.figure() # ax = fig.add_subplot(111,projection ='3d') # X,Y = np.meshgrid(x,x) # ax.plot_surface(X,Y,Z, rstride =4, cstride =4, color ='b') return fun
def initialize(self): if ((self.A_train == None or self.B_train == None) and self.rank == 0): print( 'initialize: please provide the operator and r.h.s. first...') sys.exit() self.X = PETSc.Mat() self.P = PETSc.Mat() self.X.createDense([self.numOfColsA_train, self.numOfColsB_train]) self.P.createDense([self.numOfRowsA_train, self.numOfColsB_train]) self.X.setUp() self.P.setUp() self.x_0_train, self.b_0_train = self.A_train.createVecs() self.x_0_train_old = self.x_0_train.duplicate() self.x_0_val, self.b_0_val = self.A_val.createVecs() self.x_0_test, self.b_0_test = self.A_test.createVecs() # MPI auxiliary arrays for gathering of results self.r_counts = np.array([0] * PETSc.COMM_WORLD.size, dtype=int) self.r_displs = np.array([0] * PETSc.COMM_WORLD.size, dtype=int)
def makenew(Att, phere, emaxhere): nhere = Att.getSize() Dt = Vec() Att.getDiagonal(Dt) Dt.reciprocal() Dpt = PETSc.Mat().createAIJ([nhere, nhere]) Dpt.setUp() Dpt.setDiagonal(Dt) Dpt.assemblyBegin() Dpt.assemblyEnd() omega = -4.0 / 3.0 / emaxhere second = omega * Dpt * Att * phere tmat = phere + second return tmat
def compute_u(p: np.ndarray) -> np.ndarray: # First, make PETc Hamiltonian # H = -\Delta + p # Note: cannot use dense np.array one n = len(p) A = PETSc.Mat().create() A.setSizes([n, n]) A.setUp() rstart, rend = A.getOwnershipRange() # first row if rstart == 0: A[0, :2] = [2 + p[0], -1] rstart += 1 # last row if rend == n: A[n - 1, -2:] = [-1, 2 + p[n - 1]] rend -= 1 # other rows for i in range(rstart, rend): A[i, i - 1:i + 2] = [-1, 2 + p[i], -1] A.assemble() # Compute u u = PETSc.Vec().createSeq(n) # Initialize ksp solver. ksp = PETSc.KSP().create() ksp.setOperators(A) # Solve! one = PETSc.Vec().createSeq(n) one[:] = np.ones(n) ksp.solve(one, u) # pass to np.array u = u.getArray() # theoretical error correction umin = 1 / np.max(p) u = np.maximum(umin, u) pmin = np.min(p) if pmin > 0: umax = 1 / pmin u = np.minimum(umax, u) return u
def create_covariance_matrix_petsc(n=None): model = Correlation_Model() entry_function = lambda i, j: model.correlation(i, j) shell = Matrix_Shell_Petsc(entry_function) if n is None: n = shell.n logger.debug('Creating covariance matrix in petsc format with size %d.' % n) A = petsc.Mat() A.createPython([n, n], context=shell, comm=petsc.COMM_WORLD) return A
def _DatMat(sparsity, dat=None): """A :class:`PETSc.Mat` with global size nx1 or nx1 implemented as a :class:`.Dat`""" if isinstance(sparsity.dsets[0], GlobalDataSet): sizes = ((None, 1), (sparsity._ncols, None)) elif isinstance(sparsity.dsets[1], GlobalDataSet): sizes = ((sparsity._nrows, None), (None, 1)) else: raise ValueError("Not a DatMat") A = PETSc.Mat().createPython(sizes, comm=sparsity.comm) A.setPythonContext(_DatMatPayload(sparsity, dat)) A.setUp() return A
def solve_petsc(self, solver_data_list, rhs_list, nu, *args, **kwargs): #try catch for the petsc4py use in multiple rhs solve try: import petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc from pysit.util.wrappers.petsc import PetscWrapper except ImportError: raise ImportError( 'petsc4py is not installed, please install it and try again') petsc = kwargs['petsc'] if petsc is not None: if len(solver_data_list) != len(rhs_list): raise ValueError( 'solver and right hand side list must be the same size') else: #Building the Helmholtz operator for petsc H = self._build_helmholtz_operator(nu) ndof = H.shape[1] nshot = len(rhs_list) # creating the B rhs Matrix B = PETSc.Mat().createDense([ndof, nshot]) B.setUp() for i in range(nshot): B.setValues(list(range(0, ndof)), [i], rhs_list[i]) B.assemblyBegin() B.assemblyEnd() # call the wrapper to solve the system wrapper = PetscWrapper() try: linear_solver = wrapper.factorize(H, petsc, PETSc.COMM_WORLD) Uhat = linear_solver(B.getDenseArray()) except: raise SyntaxError( 'petsc = ' + str(petsc) + ' is not a correct solver you can only use \'superlu_dist\', \'mumps\' or \'mkl_pardiso\' ' ) numb = 0 for solver_data in solver_data_list: u = Uhat[:, numb] u.shape = solver_data.k.data.shape solver_data.k.data = u numb += 1
def zero_matrix(nrows, ncols): '''Zero matrix''' mat = csr_matrix( ( np.zeros(nrows, dtype=float), # Data # Rows, cols = so first col in each row is 0 (np.arange(nrows), np.zeros(nrows, dtype=int))), shape=(nrows, ncols)) A = PETSc.Mat().createAIJ(size=[[nrows, nrows], [ncols, ncols]], csr=(mat.indptr, mat.indices, mat.data)) A.assemble() return PETScMatrix(A)
def SchurPCD(Mass, L, F, backend): Mass = Mass.sparray() F = F.sparray() F = F + 1e-10 * sp.identity(Mass.shape[0]) F = PETSc.Mat().createAIJ(size=F.shape, csr=(F.indptr, F.indices, F.data)) Mass.tocsc() Schur = sp.rand(Mass.shape[0], Mass.shape[0], density=0.00, format='csr') ksp = PETSc.KSP().create() pc = ksp.getPC() ksp.setOperators(F, F) ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() OptDB['pc_factor_shift_amount'] = "0.1" # OptDB['pc_factor_shift_type'] = 'POSITIVE_DEFINITE' OptDB['pc_factor_mat_ordering_type'] = 'amd' # OptDB['rtol'] = 1e-8 # ksp.max_it = 5 ksp.setFromOptions() for i in range(0, Mass.shape[0]): Col = Mass.getcol(i) Col = Col.toarray() Col = IO.arrayToVec(Col) u = Col.duplicate() ksp.solve(Col, u) C = u.duplicate() L.mult(u, C) # print C.array Schur[i, :] = C.array if backend == "PETSc": return PETSc.Mat().createAIJ(size=Schur.transpose().shape, csr=(Schur.transpose().indptr, Schur.transpose().indices, Schur.transpose().data)) else: return Schur.transpose()
def buildLineIntegralGaugeOperators(self, lines, linesSegments): """ Build the linear algebra operators needed to compute the line integral gauges. The operators are local to each process, contributions are currently summed in the output functions. """ #create lineIntegralGaugesVec to store contributions to all lines from this process self.lineIntegralGaugesVec = PETSc.Vec().create(comm=PETSc.COMM_SELF) self.lineIntegralGaugesVec.setSizes(len(lines)) self.lineIntegralGaugesVec.setUp() # create lineIntegralGaugeMats to store coefficients mapping contributions from each field # to the line integral gauges self.lineIntegralGaugeMats = [] if not self.isLineIntegralGauge: return # size of lineIntegralGaugeMats depends on number of local points for each field for pointGaugesVec in self.pointGaugeVecs: m = PETSc.Mat().create(comm=PETSc.COMM_SELF) m.setSizes([len(lines), pointGaugesVec.getSize()]) m.setType('aij') m.setUp() self.lineIntegralGaugeMats.append(m) # Assemble contributions from each point in each line segment for lineIndex, (line, segments) in enumerate(zip(self.lines, linesSegments)): field, endpoints = line fieldIndex = self.fields.index(field) # Trapezoid Rule to calculate coefficients here for p1, p2 in segments: segmentLength = np.linalg.norm(np.asarray(p2) - np.asarray(p1)) for point in p1, p2: point_data = self.points[tuple(point)] # only assign coefficients for locally owned points if field in point_data: pointID = point_data[field] self.lineIntegralGaugeMats[fieldIndex].setValue( lineIndex, pointID, old_div(segmentLength, 2), addv=True) for m in self.lineIntegralGaugeMats: m.assemble()
def _BuildMassMatrix2(self): """TODO: Docstring for getBmat. We are solving for CX = BX where C is the covariance matrix and B is just a mass matrix. Here we assemble B. This is a private function. DONT call this unless debuging. :returns: PETScMatrix B """ # B matrix is just a mass matrix, can be easily assembled through fenics # however, the ordering in fenics is not the mesh ordering. so we build a temp matrix # then use the vertex to dof map to get the right ordering interms of our mesh nodes V = FunctionSpace(self.mesh, "CG", 1) # Define basis and bilinear form u = TrialFunction(V) v = TestFunction(V) a = u * v * dx B_temp = assemble(a) B = PETSc.Mat().create() B.setType('aij') B.setSizes(len(self.pts), len(self.pts)) B.setUp() B_ij = B_temp.array() v_to_d_map = vertex_to_dof_map(V) print '---------------------------' print '---------------------------' print ' Building Mass Matrix ' print '---------------------------' print '---------------------------' for node_i in range(0, len(self.pts)): for node_j in range(node_i, len(self.pts)): B_ij_nodes = B_ij[v_to_d_map[node_i], v_to_d_map[node_j]] if B_ij_nodes > 0: B.setValue(node_i, node_j, B_ij_nodes) B.setValue(node_j, node_i, B_ij_nodes) B.assemblyBegin() B.assemblyEnd() print '---------------------------' print '---------------------------' print ' Finished Mass Matrix ' print '---------------------------' print '---------------------------' self.M = B return
def load_qep_n(fM1, fM2, fM3, fC1, fC2, fC3, fK1, fK2, fK3, j, n, adjoint=False): dtheta = 2*np.pi/n rj = np.exp(1j*j*dtheta) M = PETSc.Mat().load(PETSc.Viewer().createBinary(fM1, 'r')) M2 = PETSc.Mat().load(PETSc.Viewer().createBinary(fM2, 'r')) M.axpy(rj, M2) del M2 M3 = PETSc.Mat().load(PETSc.Viewer().createBinary(fM3, 'r')) M.axpy(1/rj, M3) del M3 C = PETSc.Mat().load(PETSc.Viewer().createBinary(fC1, 'r')) C2 = PETSc.Mat().load(PETSc.Viewer().createBinary(fC2, 'r')) C.axpy(rj, C2) del C2 C3 = PETSc.Mat().load(PETSc.Viewer().createBinary(fC3, 'r')) C.axpy(1/rj, C3) del C3 K = PETSc.Mat().load(PETSc.Viewer().createBinary(fK1, 'r')) K2 = PETSc.Mat().load(PETSc.Viewer().createBinary(fK2, 'r')) K.axpy(rj, K2) del K2 K3 = PETSc.Mat().load(PETSc.Viewer().createBinary(fK3, 'r')) K.axpy(1/rj, K3) del K3 if adjoint: M.transpose().conjugate() C.transpose().conjugate() K.transpose().conjugate() return M, C, K
def solve(self, A, F, uh): PA = PETSc.Mat().createAIJ(size=A.shape, csr=(A.indptr, A.indices, A.data)) PF = PETSc.Vec().createWithArray(F) x = PETSc.Vec().createWithArray(uh) ksp = PETSc.KSP() ksp.create(PETSc.COMM_WORLD) # and incomplete Cholesky ksp.setType('cg') # and incomplete Cholesky ksp.getPC().setType('gamg') ksp.setOperators(PA) ksp.setFromOptions() ksp.solve(PF, x) return x
def create_matrix_from_csr(csr): # Prepare parameters i, j = csr m = n = i.size - 1 bs = 1 # Allocate matrix A = PETSc.Mat().createAIJ((m, n), bs) A.setPreallocationCSR((i, j)) # Forbid further nonzero insertions A.setOption(PETSc.Mat.Option.NEW_NONZERO_LOCATION_ERR, True) return A