def __iadd__(self, other): if other != 0: if not other._getMatrix().Filled(): other._getMatrix().FillComplete() # Depending on which one is more filled, pick the order of operations if self._getMatrix().Filled() and other._getMatrix().NumGlobalNonzeros() \ > self._getMatrix().NumGlobalNonzeros(): tempBandwidth = other._getMatrix().NumGlobalNonzeros() \ /self._getMatrix().NumGlobalRows()+1 tempMatrix = Epetra.CrsMatrix(Epetra.Copy, self.nonOverlappingMap, tempBandwidth) if EpetraExt.Add(other._getMatrix(), False, 1, tempMatrix, 1) != 0: import warnings warnings.warn("EpetraExt.Add returned error code in __iadd__, 1", UserWarning, stacklevel=2) if EpetraExt.Add(self._getMatrix(), False, 1, tempMatrix, 1) != 0: import warnings warnings.warn("EpetraExt.Add returned error code in __iadd__, 2", UserWarning, stacklevel=2) self.matrix = tempMatrix else: if EpetraExt.Add(other._getMatrix(), False,1,self._getMatrix(),1) != 0: import warnings warnings.warn("EpetraExt.Add returned error code in __iadd__", UserWarning, stacklevel=2) return self
def matmat(self, other): from PyTrilinos import Epetra from block.block_util import isscalar try: if isscalar(other): C = type(self.M)(self.M) if other != 1: C.Scale(other) return matrix_op(C, self.transposed) other = other.down_cast() if hasattr(other, 'mat'): from PyTrilinos import EpetraExt # Create result matrix C. This is done in a contorted way, to # ensure all diagonals are present. A = type(self.M)(self.M) A.PutScalar(1.0) B = type(other.mat())(other.mat()) B.PutScalar(1.0) C = Epetra.FECrsMatrix(Epetra.Copy, self.rowmap(), 100) EpetraExt.Multiply(A, self.transposed, B, other.transposed, C) C.OptimizeStorage() # C is now finalised, we can use it to store the real mat-mat product. assert (0 == EpetraExt.Multiply(self.M, self.transposed, other.mat(), other.transposed, C)) result = matrix_op(C) # Sanity check. Cannot trust EpetraExt.Multiply always, it seems. from block import block_vec v = result.create_vec() block_vec([v]).randomize() xv = self * other * v err = (xv - result * v).norm('l2') / (xv).norm('l2') if (err > 1e-3): print('++ a :', self * other) print('++ a\':', result) print( '++ EpetraExt.Multiply computed wrong result; ||(a-a\')x||/||ax|| = %g' % err) return result else: C = type(self.M)(self.M) if self.transposed: C.LeftScale(other.vec()) else: C.RightScale(other.vec()) return matrix_op(C, self.transposed) except AttributeError: raise TypeError("can't extract matrix data from type '%s'" % str(type(other)))
def exportMmf(self, filename): """ Exports the matrix to a Matrix Market file of the given `filename`. """ self.fillComplete() EpetraExt.RowMatrixToMatrixMarketFile(text_to_native_str(filename), self.matrix)
def exportMmf(self, filename): """ Exports the matrix to a Matrix Market file of the given filename. """ if not self.matrix.Filled(): self.matrix.FillComplete() EpetraExt.RowMatrixToMatrixMarketFile(filename, self.matrix)
def get_negative_matrix(self, matrix, n): std_map = Epetra.Map(n, 0, self.comm) if matrix.Filled() == False: matrix.FillComplete() A = Epetra.CrsMatrix(Epetra.Copy, std_map, 3) EpetraExt.Add(matrix, False, -1.0, A, 1.0) return A
def add(self, other, lscale=1.0, rscale=1.0): try: other = other.down_cast() except AttributeError: #raise TypeError("can't extract matrix data from type '%s'"%str(type(other))) pass if hasattr(other, 'mat'): from PyTrilinos import Epetra, EpetraExt C = Epetra.FECrsMatrix(Epetra.Copy, self.rowmap(), 100) assert (0 == EpetraExt.Add(self.M, self.transposed, lscale, C, 0.0)) assert (0 == EpetraExt.Add(other.mat(), other.transposed, rscale, C, 1.0)) C.FillComplete() C.OptimizeStorage() return matrix_op(C) else: lhs = self.matmat(lscale) D = Diag(lhs).add(other, rscale=rscale) lhs.M.ReplaceDiagonalValues(D.vec()) return lhs
def SaveEpertaMatrix(A, name): from PyTrilinos import EpetraExt from numpy import array, loadtxt import scipy.sparse as sps import scipy.io test = "".join([name, ".txt"]) EpetraExt.RowMatrixToMatlabFile(test, A) data = loadtxt(test) col, row, values = data[:, 0] - 1, data[:, 1] - 1, data[:, 2] Asparse = sps.csr_matrix((values, (row, col))) testmat = "".join([name, ".mat"]) scipy.io.savemat(testmat, {name: Asparse}, oned_as='row')
def SaveEpertaMatrix(A, name, xdim, ydim): from PyTrilinos import EpetraExt from numpy import array, loadtxt import scipy.sparse as sps import scipy.io test = "".join([name, ".txt"]) EpetraExt.RowMatrixToMatlabFile(test, A) data = loadtxt(test) col, row, values = data[:, 0] - 1, data[:, 1] - 1, data[:, 2] Asparse = sps.csr_matrix((values, (row, col))) As = Asparse[0:xdim, 0:ydim] comm = Epetra.PyComm() Ap = scipy_csr_matrix2CrsMatrix(Aublas1, comm) return Ap
def NullSpace(A, name): from PyTrilinos import EpetraExt, Epetra from numpy import array, loadtxt import scipy.sparse as sps import scipy.io import matplotlib.pylab as plt test = "".join([name, ".txt"]) EpetraExt.RowMatrixToMatlabFile(test, A) data = loadtxt(test) col, row, values = data[:, 0] - 1, data[:, 1] - 1, data[:, 2] Asparse = sps.csr_matrix((values, (row, col))) (Nb, Mb) = Asparse.shape Aublas1 = Asparse[0:Nb - 1, 0:Mb - 1] comm = Epetra.PyComm() Ap = scipy_csr_matrix2CrsMatrix(Aublas1, comm) return Ap
def transpose_matrix(A): """ Transposes a matrix Parameters ---------- A: Epetra Matrix Returns ------- C: transpose of matrix A """ V = Epetra.Vector(A.RangeMap()) V.PutScalar(1.0) I = diagonal_matrix_from_vector(V, A.RangeMap()) C = Epetra.CrsMatrix(Epetra.Copy, A.DomainMap(), 10) EpetraExt.Multiply(A, True, I, False, C) C.FillComplete() return C
def get_i_Jac(self, xVec): """ Calculate total current and Jacobian Returns (iVec, Jac):: iVec = G xVec + i(xVec) Jac = G + (di/dx)(xVec) xVec: input vector of nodal voltages. iVec: output vector of currents Jac: system Jacobian """ # Copy xVec to pytrilinos vector self.xVec[:] = xVec # Erase arrays self.iVec.fill(0.) # Erase M and add linear contribution to iVec and M self.G.Multiply(False, self.xVec, self.iVec) # For now just re-create. Later this could somehow be # optimized self.Jacnz = [([], []) for i in xrange(self.ckt.nD_dimension)] # Erase Jac and add G in one step EpetraExt.Add(self.G, False, 1., self.Jac, 0.) # Nonlinear contribution for elem in self.ckt.nD_nlinElem: # first have to retrieve port voltages from xVec xin = np.zeros(len(elem.controlPorts)) set_xin(xin, elem.nD_vpos, elem.nD_vneg, xVec) (outV, outJac) = elem.eval_and_deriv(xin) # Update iVec and Jacobian now. outV may have extra charge # elements but they are not used in the following set_i(self.iVec, elem.nD_cpos, elem.nD_cneg, outV) set_Jac(self.Jacnz, elem.nD_cpos, elem.nD_cneg, elem.nD_vpos, elem.nD_vneg, outJac) # Insert actual elements in M for row, data in enumerate(self.Jacnz): self.Jac.SumIntoGlobalValues(row, *data) return (self.iVec, self.Jac)
def mat_multiply(A, B, transpose_1=False, transpose_2=False, fill=30): """ Matrix product of two matrices Parameters ---------- A: Epetra Matrix B: Epetra Matrix transpose_1: bool, optional If true, then A is transposed before multiplication transpose_2: bool, optional If true, then B is transposed before multiplication fill: int, optional estimate of how many nonzeros per row Returns ------- C: Epetra Matrix C = A*B """ if transpose_1: C = Epetra.CrsMatrix(Epetra.Copy, A.DomainMap(), fill) else: C = Epetra.CrsMatrix(Epetra.Copy, A.RangeMap(), fill) ierr = EpetraExt.Multiply(A, transpose_1, B, transpose_2, C) assert ierr == 0 if transpose_1: C.FillComplete(B.DomainMap(), A.DomainMap()) else: C.FillComplete() if not (transpose_1 or transpose_2): assert (C.NumGlobalRows(), C.NumGlobalCols()) == (A.NumGlobalRows(), B.NumGlobalCols()) if transpose_1 and not transpose_2: assert (C.NumGlobalRows(), C.NumGlobalCols()) == (A.NumGlobalCols(), B.NumGlobalCols()) if not transpose_1 and transpose_2: assert (C.NumGlobalRows(), C.NumGlobalCols()) == (A.NumGlobalRows(), B.NumGlobalRows()) return C
def pymultimat(self, A, B, nf, transpose_A=False, transpose_B=False): """ Multiplica a matriz A pela matriz B ambas de mesma ordem e quadradas nf: ordem da matriz """ if A.Filled() == False: A.FillComplete() if B.Filled() == False: B.FillComplete() nf_map = Epetra.Map(nf, 0, self.comm) C = Epetra.CrsMatrix(Epetra.Copy, nf_map, 3) EpetraExt.Multiply(A, transpose_A, B, transpose_B, C) # C.FillComplete() return C
def pymultimat(comm, A, B, transpose_A=False, transpose_B=False): """ Multiplica a matriz A pela matriz B ambas de mesma ordem e quadradas nf: ordem da matriz """ assert A.NumMyCols() == A.NumMyRows() assert B.NumMyCols() == B.NumMyRows() assert A.NumMyRows() == B.NumMyRows() n = A.NumMyCols() if A.Filled() == False: A.FillComplete() if B.Filled() == False: B.FillComplete() nf_map = Epetra.Map(n, 0, comm) C = Epetra.CrsMatrix(Epetra.Copy, nf_map, 3) EpetraExt.Multiply(A, transpose_A, B, transpose_B, C) return C
def generator(problemID, comm, List): GaleriList = {} if problemID[0:3] == "HB_": print "<p><p><div class=\"outputBox\"><pre>"; FileName = HB_REPOSITORY + problemID[3:]; Map, Matrix, LHS, RHS, ExactSolution = Galeri.ReadHB(FileName, comm); NullSpace = "not-set" print "</div>" elif problemID[0:3] == "MM_": # read matrix first, then use its map for the vectors # FIXME: to check for vectors here FileName = MM_REPOSITORY + problemID[3:] + "/A.mm"; (ierr, Matrix) = EpetraExt.MatrixMarketFileToCrsMatrix(FileName, comm) Map = Matrix.RowMatrixRowMap() FileName = MM_REPOSITORY + problemID[3:] + "/ExactSolution.mm"; if os.path.isfile(FileName): (ierr, ExactSolution) = EpetraExt.MatrixMarketFileToMultiVector(FileName, Map) else: ExactSolution = Epetra.Vector(Map) ExactSolution.PutScalar(0.0) FileName = MM_REPOSITORY + problemID[3:] + "/RHS.mm"; if os.path.isfile(FileName): (ierr, RHS) = EpetraExt.MatrixMarketFileToMultiVector(FileName, Map) else: RHS = Epetra.MultiVector(Map, ExactSolution.NumVectors()) RHS.PutScalar(0.0) FileName = MM_REPOSITORY + problemID[3:] + "/LHS.mm"; if os.path.isfile(FileName): (ierr, LHS) = EpetraExt.MatrixMarketFileToMultiVector(FileName, Map) else: LHS = Epetra.MultiVector(Map, RHS.NumVectors()) LHS.PutScalar(0.0) NullSpace = "not-set" print "</div>" elif problemID[0:4] == "XML_": FileName = XML_REPOSITORY + problemID[4:]; XMLReader = EpetraExt.XMLReader(comm, FileName) Map = XMLReader.ReadMap("map") LHS = XMLReader.ReadMultiVector("LHS") RHS = XMLReader.ReadMultiVector("RHS") ExactSolution = XMLReader.ReadMultiVector("ExactSolution") Matrix = XMLReader.ReadCrsMatrix("A") NullSpace = "not-set" print "</div>" else: parts = string.split(problemID, '_'); ProblemType = parts[0]; for i in range(1, len(parts)): p2 = string.split(parts[i], '!') type = p2[0][0]; name = p2[0][1:] value = p2[1]; if (type == "i"): GaleriList[name] = int(value); elif type == "d": GaleriList[name] = float(value); elif type == "s": GaleriList[name] = value; if string.find(ProblemType, '2D') != -1: MapType = "Cartesian2D"; mx = math.sqrt(NumProcs) if mx * mx == NumProcs: GaleriList['mx'] = int(mx) GaleriList['my'] = int(mx) else: GaleriList['mx'] = int(NumProcs) GaleriList['my'] = 1 elif string.find(ProblemType, '3D') != -1: MapType = "Cartesian3D" mx = math.pow(NumProcs, 0.33334) if mx * mx * mx == NumProcs: GaleriList['mx'] = int(mx) GaleriList['my'] = int(mx) GaleriList['mz'] = int(mx) else: GaleriList['mx'] = int(NumProcs) GaleriList['my'] = 1 GaleriList['mz'] = 1 Map = Galeri.CreateMap(MapType, comm, GaleriList); Matrix = Galeri.CreateCrsMatrix(ProblemType, Map, GaleriList); LHS = Epetra.Vector(Map) RHS = Epetra.Vector(Map) ExactSolution = Epetra.Vector(Map) NullSpace = "not-set" # checks that the matrix is not too big if Map.NumGlobalElements() > MAX_MATRIX_ROWS: print "<b><font color=red>Sorry, the maximum matrix size is 20.000</font></b>" raise("PARAMETER_ERROR"); if Matrix.NumGlobalNonzeros() > MAX_MATRIX_NONZEROS: print "<b><font color=red>Sorry, the maximum number of nonzeros is 250.000</font></b>" raise("PARAMETER_ERROR"); # FIXME??? if List.has_key('solution') == True: if List['solution'] == "zero": ExactSolution.PutScalar(0.0) elif List['solution'] == "random": ExactSolution.Random() elif List['solution'] == "constant": ExactSolution.PutScalar(1.0) elif List['solution'] == "from_file": # do nothing ciao = 2.0 else: raise("PARAMETER_ERROR"); if List.has_key('starting_solution') == True: if List['starting_solution'] == "zero": LHS.PutScalar(0.0) elif List['starting_solution'] == "random": LHS.Random() elif List['starting_solution'] == "constant": LHS.PutScalar(1.0) elif List['starting_solution'] == "from_file": # do nothing ciao = 2.0 else: raise("PARAMETER_ERROR"); if List.has_key('rhs') == True: if List['rhs'] == "zero": RHS.PutScalar(0.0) elif List['rhs'] == "random": RHS.Random() elif List['rhs'] == "constant": RHS.PutScalar(1.0) elif List['rhs'] == "matvec": Matrix.Apply(ExactSolution, RHS); elif List['rhs'] == "from_file": # do nothing ciao = 2.0 else: raise("PARAMETER_ERROR"); else: ExactSolution.Random() Matrix.Apply(ExactSolution, RHS) LHS.PutScalar(0.0) return(Map, Matrix, LHS, RHS, ExactSolution, NullSpace);
def create_matrix(unique_map, edge_attributes, subnetworks=None, inter_processor_edges=None, inter_subgraph_edges=None, matformat="trilinos"): A = Epetra.CrsMatrix(Epetra.Copy, unique_map, 50) my_global_elements_set = set(unique_map.MyGlobalElements()) row_lists = [] col_lists = [] val_lists = [] if inter_processor_edges is not None: vertices_1 = inter_processor_edges['edgelist'][0] vertices_2 = inter_processor_edges['edgelist'][1] if len(vertices_1) > 0: assert set(vertices_1) <= my_global_elements_set, inter_processor_edges assert not set(vertices_2) <= my_global_elements_set, inter_processor_edges for attr in edge_attributes: row_lists.append(vertices_1) col_lists.append(vertices_2) val_lists.append(inter_processor_edges[attr]) if inter_subgraph_edges is not None: vertices_1 = inter_subgraph_edges['edgelist'][0] vertices_2 = inter_subgraph_edges['edgelist'][1] assert set(vertices_1) <= my_global_elements_set, inter_subgraph_edges assert set(vertices_2) <= my_global_elements_set, inter_subgraph_edges for attr in edge_attributes: row_lists.append(vertices_1) col_lists.append(vertices_2) val_lists.append(inter_subgraph_edges[attr]) row_lists.append(vertices_2) col_lists.append(vertices_1) val_lists.append(inter_subgraph_edges[attr]) if subnetworks is not None: for i in subnetworks: vertices_1_local = subnetworks[i].edgelist[:, 0] vertices_2_local = subnetworks[i].edgelist[:, 1] vertices_1_global = subnetworks[i].pi_local_to_global[vertices_1_local] vertices_2_global = subnetworks[i].pi_local_to_global[vertices_2_local] assert set(vertices_1_global) <= my_global_elements_set assert set(vertices_2_global) <= my_global_elements_set cond = np.zeros(subnetworks[i].tubes.nr) for attr in edge_attributes: cond += getattr(subnetworks[i].tubes, attr) row_lists.append(vertices_1_global) col_lists.append(vertices_2_global) val_lists.append(cond) row_lists.append(vertices_2_global) col_lists.append(vertices_1_global) val_lists.append(cond) if matformat == "trilinos": for row, col, val in izip(row_lists, col_lists, val_lists): ierr = A.InsertGlobalValues(row, col, val) assert ierr == 0, ierr A.FillComplete() ones = Epetra.Vector(unique_map) ones[:] = 1.0 x = Epetra.Vector(unique_map) A.Multiply(False, ones, x) D = Epetra.CrsMatrix(Epetra.Copy, unique_map, 50, True) row_inds = D.Map().MyGlobalElements() ierr = D.InsertGlobalValues(row_inds, row_inds, x) assert ierr == 0, ierr ierr = EpetraExt.Add(A, False, -1.0, D, 1.0) assert ierr == 0, ierr D.FillComplete() check = sum_of_columns(D) if check: error = np.max(np.abs(check[:])) assert error < 1.e-14, error return D if matformat == "scipy": N = unique_map.NumGlobalElements() row = np.concatenate(row_lists) col = np.concatenate(col_lists) val = np.concatenate(val_lists) A = coo_matrix((val, (row, col)), shape=(N, N)) ones = np.ones(N) x = A*ones D = diags(x) A = D-A error = np.max(np.abs(A*ones)) assert error < 1.e-14, error return A
def create_matrix_from_graph(unique_map, edge_attributes, graph, subnetworks=None, inter_processor_edges=None, inter_subgraph_edges=None): A = Epetra.CrsMatrix(Epetra.Copy, graph) A.PutScalar(0.0) my_global_elements_set = set(unique_map.MyGlobalElements()) row_lists = [] col_lists = [] val_lists = [] if inter_processor_edges is not None: vertices_1 = inter_processor_edges['edgelist'][0] vertices_2 = inter_processor_edges['edgelist'][1] if len(vertices_1) > 0: assert set(vertices_1) <= my_global_elements_set, inter_processor_edges assert not set(vertices_2) <= my_global_elements_set, inter_processor_edges for attr in edge_attributes: row_lists.append(vertices_1) col_lists.append(vertices_2) val_lists.append(inter_processor_edges[attr]) if inter_subgraph_edges is not None: vertices_1 = inter_subgraph_edges['edgelist'][0] vertices_2 = inter_subgraph_edges['edgelist'][1] assert set(vertices_1) <= my_global_elements_set, inter_subgraph_edges assert set(vertices_2) <= my_global_elements_set, inter_subgraph_edges for attr in edge_attributes: row_lists.append(vertices_1) col_lists.append(vertices_2) val_lists.append(inter_subgraph_edges[attr]) row_lists.append(vertices_2) col_lists.append(vertices_1) val_lists.append(inter_subgraph_edges[attr]) if subnetworks is not None: for i in subnetworks: vertices_1_local = subnetworks[i].edgelist[:, 0] vertices_2_local = subnetworks[i].edgelist[:, 1] vertices_1_global = subnetworks[i].pi_local_to_global[vertices_1_local] vertices_2_global = subnetworks[i].pi_local_to_global[vertices_2_local] assert set(vertices_1_global) <= my_global_elements_set assert set(vertices_2_global) <= my_global_elements_set cond = np.zeros(subnetworks[i].tubes.nr) for attr in edge_attributes: cond += getattr(subnetworks[i].tubes, attr) row_lists.append(vertices_1_global) col_lists.append(vertices_2_global) val_lists.append(cond) row_lists.append(vertices_2_global) col_lists.append(vertices_1_global) val_lists.append(cond) row_lists = np.concatenate(row_lists).astype(np.int32) col_lists = np.concatenate(col_lists).astype(np.int32) val_lists = np.concatenate(val_lists) ierr = A.SumIntoGlobalValues(row_lists, col_lists, val_lists) assert ierr == 0, ierr A.FillComplete() ones = Epetra.Vector(unique_map) ones[:] = 1.0 x = Epetra.Vector(unique_map) A.Multiply(False, ones, x) D = Epetra.CrsMatrix(Epetra.Copy, graph) D.PutScalar(0.0) row_inds = D.Map().MyGlobalElements() ierr = D.SumIntoGlobalValues(row_inds, row_inds, x) assert ierr == 0, ierr ierr = EpetraExt.Add(A, False, -1.0, D, 1.0) assert ierr == 0, ierr D.FillComplete() check = sum_of_columns(D) if check: error = np.max(np.abs(check[:])) assert error < 1.e-14, error return D
from PyTrilinos import Epetra, EpetraExt, AztecOO, ML from Numeric import sin # builds the linear system matrix and sets up starting solution and # right-hand side Comm = Epetra.PyComm() # I got similar results for _1 and _4 MapName = "/Users/marzio/matrices/PREMO/Falcon-step2/Falcon_ss_1_map" MatrixName = "/Users/marzio/matrices/PREMO/Falcon-step2/Falcon_ss_4_matrix" LHSName = "/Users/marzio/matrices/PREMO/Falcon-step2/Falcon_ss_1_guess" RHSName = "/Users/marzio/matrices/PREMO/Falcon-step2/Falcon_ss_1_guess" (ierr, Map) = EpetraExt.MatrixMarketFileToBlockMap(MapName, Comm) (ierr, LHS) = EpetraExt.MatrixMarketFileToMultiVector(LHSName, Map) (ierr, RHS) = EpetraExt.MatrixMarketFileToMultiVector(RHSName, Map) (ierr, Matrix) = EpetraExt.MatrixMarketFileToCrsMatrix(MatrixName, Map) LHSView = LHS.ExtractView() n = LHS.MyLength() for i in xrange(0, n): LHSView[0][i] = sin(i * 3.1415 / n) * sin(i * 3.1415 / n) Matrix.Multiply(False, LHS, RHS) LHS.PutScalar(0.0) # sets up the parameters for ML using a python dictionary MLList = { "max levels" : 10,
def smooth_prolongation_operator(self, A, max_iter=1000, tol=1.e-2, verbose=False): """ Parameters ---------- A: Epetra matrix max_iter: integer Number of smoothing steps verbose: bool Flag to output convergence information Notes ----- See Algorithm 2 in Mandel et al 1999. However Jacobi iteration is used for smoothing as opposed to gradient descent. """ support_matrix_copy = Epetra.CrsMatrix(self.N) tau = Epetra.Vector(A.RangeMap()) J = DinvA(A) ierr = 0 delta_P_temp = Epetra.CrsMatrix(Epetra.Copy, A.RangeMap(), 40) for iter_n in xrange(max_iter): sum_cols_P = sum_of_columns(self.P) assert np.allclose(sum_cols_P[:], 1.0) ierr += EpetraExt.Multiply(J, False, self.P, False, delta_P_temp) # Drop entries of delta_P_temp not matching the structure of delta_P self.delta_P.PutScalar(0.0) ierr += EpetraExt.Add(delta_P_temp, False, 1.0, self.delta_P, 1.0) # delta_P = N*(D^-1 AP) sum_cols_delta_P = sum_of_columns(self.delta_P) assert np.all(self.num_overlaps[:] >= 1) tau[:] = sum_cols_delta_P[:] / self.num_overlaps[:] support_matrix_copy.PutScalar(1.0) support_matrix_copy.LeftScale(tau) # last term in Equation (19) ierr += EpetraExt.Add(support_matrix_copy, False, -1.0, self.delta_P, 1.0) # delta_P = Z(N*D^-1AP) sum_cols_delta_P = sum_of_columns(self.delta_P) assert np.allclose(sum_cols_delta_P[:], 0.0) ierr += EpetraExt.Add(self.delta_P, False, -0.5, self.P, 1.0) error = self.delta_P.NormInf() if error < tol: break logger.debug( "Basis function error: %g. Number of iterations required: %d", error, iter_n) if verbose: print "Basis function error: %g. Number of iterations required: %d" % ( error, iter_n) sum_cols_P = sum_of_columns(self.P) assert np.allclose(sum_cols_P[:], 1.0, atol=1.e-1000, rtol=1e-12) # Important numerical step to ensure that mass is exactly conserved to machine zero """ tau[:] = 1./sum_cols_P[:] self.P.LeftScale(tau) sum_cols_P = sum_of_columns(self.P) assert np.allclose(sum_cols_P[:], 1.0, atol=1.e-1000, rtol=1.e-15) """ assert ierr == 0
def __mul__(self, other): """ Multiply a sparse matrix by another sparse matrix. >>> L1 = _TrilinosMatrixFromShape(rows=3, cols=3) >>> L1.addAt((3, 10, numerix.pi, 2.5), (0, 0, 1, 2), (2, 1, 1, 0)) >>> L2 = _TrilinosIdentityMatrix(size=3) >>> L2.addAt((4.38, 12357.2, 1.1), (2, 1, 0), (1, 0, 2)) >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00), ... (3.88212887e+04, 3.14159265e+00, 0.00000000e+00), ... (2.50000000e+00, 0.00000000e+00, 2.75000000e+00))) >>> L = (L1 * L2).numpyArray >>> print(numerix.allclose(tmp, L)) # doctest: +SERIAL True or a sparse matrix by a vector >>> tmp = numerix.array((29., 6.28318531, 2.5)) >>> print(numerix.allclose(L1 * numerix.array((1, 2, 3), 'd'), tmp)) # doctest: +SERIAL True or a vector by a sparse matrix >>> tmp = numerix.array((7.5, 16.28318531, 3.)) >>> print(numerix.allclose(numerix.array((1, 2, 3), 'd') * L1, tmp)) # doctest: +SERIAL True """ N = self.matrix.NumMyCols() if isinstance(other, _TrilinosMatrix): if isinstance(other.matrix, Epetra.RowMatrix): self.fillComplete() other.fillComplete() result = Epetra.CrsMatrix(Epetra.Copy, self.rowMap, 0) EpetraExt.Multiply(self.matrix, False, other.matrix, False, result) copy = self.copy() copy.matrix = result return copy else: raise TypeError else: shape = numerix.shape(other) if shape == (): result = self.copy() result.matrix.Scale(other) return result elif shape == (N, ): self.fillComplete() y = Epetra.Vector(self.domainMap, other) result = Epetra.Vector(self.rangeMap) self.matrix.Multiply(False, y, result) return numerix.array(result) else: raise TypeError
from PyTrilinos import Epetra, ML, EpetraExt, IFPACK, AztecOO from math import sin comm = Epetra.PyComm() (ierr, Matrix) = EpetraExt.MatrixMarketFileToCrsMatrix("/tmp/MPSalsa_Diamond_med.mm", comm) Map = Matrix.RowMatrixRowMap() # -------------------------------------- # # building solutions and right-hand side # # -------------------------------------- # LHS = Epetra.Vector(Map) RHS = Epetra.Vector(Map) LHSView = LHS.ExtractView() n = LHS.MyLength() for i in xrange(0, n): LHSView[i] = sin(i * 3.1415 / n) * sin(i * 3.1415 / n) Matrix.Multiply(False, LHS, RHS) # ------------------------------------------------- # # Parameters to run ML. Remember the RCM reordering # # for Charon matrices! # # ------------------------------------------------- # MLList = { "max levels": 10, "output": 10, "smoother: type": "IFPACK",
def __mul__(self, other): """ Multiply a sparse matrix by another sparse matrix. >>> L1 = _TrilinosMatrix(size=3) >>> L1.addAt((3,10,numerix.pi,2.5), (0,0,1,2), (2,1,1,0)) >>> L2 = _TrilinosIdentityMatrix(size=3) >>> L2.addAt((4.38,12357.2,1.1), (2,1,0), (1,0,2)) >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00), ... (3.88212887e+04, 3.14159265e+00, 0.00000000e+00), ... (2.50000000e+00, 0.00000000e+00, 2.75000000e+00))) >>> for i in range(0,3): ... for j in range(0,3): ... numerix.allclose(((L1*L2)[i,j],), tmp[i,j]) True True True True True True True True True or a sparse matrix by a vector >>> tmp = numerix.array((29., 6.28318531, 2.5)) >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp) 1 or a vector by a sparse matrix >>> tmp = numerix.array((7.5, 16.28318531, 3.)) >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp) 1 """ N = self._getMatrix().NumMyCols() if isinstance(other, _TrilinosMatrixBase): if isinstance(other._getMatrix(), Epetra.RowMatrix): if not self._getMatrix().Filled(): self._getMatrix().FillComplete() if not other._getMatrix().Filled(): other._getMatrix().FillComplete() result = Epetra.CrsMatrix(Epetra.Copy, self.nonOverlappingMap, 0) EpetraExt.Multiply(self._getMatrix(), False, other._getMatrix(), False, result) copy = self.copy() copy.matrix = result return copy else: raise TypeError else: shape = numerix.shape(other) if shape == (): result = self.copy() result._getMatrix().Scale(other) return result elif shape == (N,): if not self._getMatrix().Filled(): self._getMatrix().FillComplete() y = _numpyToTrilinosVector(other, self.nonOverlappingMap) result = Epetra.Vector(self.nonOverlappingMap) self._getMatrix().Multiply(False, y, result) return _trilinosToNumpyVector(result) else: raise TypeError