예제 #1
0
    def _getGhostedValues(self, var):
        """Obtain current ghost values from across processes

        Returns
        -------
        ndarray
            Ghosted values
        """
        mesh = var.mesh
        localNonOverlappingCellIDs = mesh._localNonOverlappingCellIDs

        ## The following conditional is required because empty indexing is
        ## not altogether functional.  This numpy.empty((0,))[[]] and this
        ## numpy.empty((0,))[...,[]] both work, but this numpy.empty((3,
        ## 0))[...,[]] is broken.
        if var.shape[-1] != 0:
            s = (Ellipsis, localNonOverlappingCellIDs)
        else:
            s = (localNonOverlappingCellIDs, )

        nonOverlappingVector = Epetra.Vector(self.domainMap, var[s].ravel())

        overlappingVector = Epetra.Vector(self.colMap)
        overlappingVector.Import(nonOverlappingVector,
                                 Epetra.Import(self.colMap, self.domainMap),
                                 Epetra.Insert)

        return numerix.reshape(numerix.asarray(overlappingVector), var.shape)
예제 #2
0
 def solve_linear_problem(self, A, b, x=None, its=1000, tolerance=1e-10):
     '''
     resolve o problema Ax = b
     input:
         A: matriz quadrada esparsa do scipy
         b = termo fonte
         x: chute inicial
         its: numero maximo de iteracoes
         tolerance: tolerancia para o residuo
     output:
         res: informa se o residuo foi menor que a tolerancia
         x2: vetor resposta
     '''
     comm = self._comm
     n = len(b)
     std_map = Epetra.Map(n, 0, comm)
     x2 = Epetra.Vector(std_map)
     if x:
         x2[:] = x[:]
     b2 = Epetra.Vector(std_map)
     b2[:] = b[:]
     A2 = Epetra.CrsMatrix(Epetra.Copy, std_map, 7)
     indices = sp.find(A)
     A2.InsertGlobalValues(indices[0], indices[1], indices[2])
     irr = A2.FillComplete()
     linearProblem = Epetra.LinearProblem(A2, x2, b2)
     solver = AztecOO.AztecOO(linearProblem)
     solver.SetAztecOption(AztecOO.AZ_output, AztecOO.AZ_warnings)
     # solver.SetParameters(self._params)
     solver.Iterate(its, tolerance)
     x2 = np.array(x2)
     res = solver.ScaledResidual() < tolerance
     return x2
예제 #3
0
파일: trilinos_utils.py 프로젝트: jpra2/MAD
    def get_inverse_by_inds(comm, inds):
        """
        retorna inds da matriz inversa a partir das informacoes (inds) da matriz de entrada
        """

        assert inds[3][0] == inds[3][1]
        cols = inds[3][1]
        sz = [cols, cols]
        A = TrilinosUtils.get_CrsMatrix_by_inds(comm, inds)

        lines2 = np.array([])
        cols2 = np.array([])
        values2 = np.array([], dtype=np.float64)
        map1 = Epetra.Map(cols, 0, comm)

        for i in range(cols):
            b = Epetra.Vector(map1)
            b[i] = 1.0

            x = TrilinosUtils.solve_linear_problem(A, b)

            lines = np.nonzero(x[:])[0]
            col = np.repeat(i, len(lines))
            vals = x[lines]

            lines2 = np.append(lines2, lines)
            cols2 = np.append(cols2, col)
            values2 = np.append(values2, vals)

        lines2 = lines2.astype(np.int32)
        cols2 = cols2.astype(np.int32)

        inds2 = np.array([lines2, cols2, values2, sz, False, False])

        return inds2
예제 #4
0
def scipy_csr_matrix2CrsMatrix(sp, comm):
    Ap = sp.indptr
    Aj = sp.indices
    Ax = sp.data
    m = Ap.shape[0]-1
    aMap = Epetra.Map(m, 0, comm)
    # range Map
    arMap=Epetra.Map(sp.shape[0], 0, comm)
    # domain Map
    adMap=Epetra.Map(sp.shape[1], 0, comm)
    aGraph = Epetra.CrsGraph( Epetra.Copy, aMap, 0)
    for ii in range(aMap.NumGlobalElements()):
          i = aMap.GID(ii)
          indy = range(Ap[i],Ap[i+1])
          if (indy != []): 
              aGraph.InsertGlobalIndices(i, Aj[indy])
    aGraph.FillComplete(adMap, arMap)
    A = Epetra.CrsMatrix(Epetra.Copy, aGraph)
    for ii in range(aMap.NumGlobalElements()):
          i = aMap.GID(ii)
          indy = range(Ap[i],Ap[i+1])
	  if (indy != []): 
	      A.SumIntoGlobalValues(i, Ax[indy], Aj[indy])
    A.FillComplete(adMap, arMap)
    return A	      
예제 #5
0
    def _prolongation_operator_init(row_map, my_restriction_supports,
                                    my_basis_supports):
        """
        Creates N x M matrix where N is the number of vertices in the graph and M is the number of basis functions
        """
        range_map = row_map
        comm = range_map.Comm()
        domain_map = Epetra.Map(-1, my_basis_supports.keys(), 0, comm)
        P = Epetra.CrsMatrix(Epetra.Copy, range_map, 30)

        for basis_id in my_basis_supports:
            my_fine_cell_ids = my_basis_supports[basis_id]
            size = len(my_fine_cell_ids)
            assert size > 0
            P.InsertGlobalValues(my_fine_cell_ids, [int(basis_id)] * size,
                                 [0.] * size)

        for basis_id in my_restriction_supports:
            my_fine_cell_ids = my_restriction_supports[basis_id]
            size = len(my_fine_cell_ids)
            assert size > 0
            ierr = P.InsertGlobalValues(my_fine_cell_ids,
                                        [int(basis_id)] * size, [1.] * size)
            assert ierr == 0

        P.FillComplete(domain_map, range_map)

        a = sum_of_columns(P)
        assert np.all(a[:] == 1.0)
        return P
예제 #6
0
    def create_maps(graph, comm):
        """
        Parameters
        ----------
        graph: igraph
            igraph representing the network.
        comm: Epetra communicator

        Returns
        -------
        unique_map: Epetra Map
            Map representing the vertices belonging to each processor
        nonunique_map: Epetra Map
            Map representing the vertices belonging to each processor as well one ghost vertex neighborhood
        subgraph_ids_vec: Epetra Vector
            Epetra vector recording the subgraph id of each vertex
        """
        my_id = comm.MyPID()
        my_local_elements = graph.vs(proc_id_eq=my_id).indices
        my_global_elements = graph.vs[my_local_elements]['global_id']
        my_ghost_elements = set().union(*graph.neighborhood(my_local_elements))
        my_ghost_elements = set(graph.vs(my_ghost_elements)['global_id']) - set(my_global_elements)
        my_ghost_elements = sorted(list(my_ghost_elements))
        assert not set(my_global_elements).intersection(my_ghost_elements)

        unique_map = Epetra.Map(-1, my_global_elements, 0, comm)
        nonunique_map = Epetra.Map(-1, my_global_elements + my_ghost_elements, 0, comm)

        subgraph_ids_vec = Epetra.Vector(unique_map)
        subgraph_ids_vec[:] = np.asarray(graph.vs[my_local_elements]['subgraph_id'], dtype=np.int32)

        return unique_map, nonunique_map, subgraph_ids_vec
예제 #7
0
    def _create_structure_matrix(row_map, my_supports, val=1.0):
        """
        Creates N x M matrix where N is the number of vertices in the graph and M is the number of basis functions.
        This matrix encodes which basis function supports (which is identified by their column ids)
        a given vertex (which is identified by row id) belongs to.
        Note: one vertex may belong to multiple supports.
        """
        range_map = row_map
        comm = range_map.Comm()
        domain_map = Epetra.Map(-1, my_supports.keys(), 0, comm)
        A = Epetra.CrsMatrix(Epetra.Copy, range_map, 30)

        for basis_id in my_supports:
            my_fine_cell_ids = my_supports[basis_id]
            size = len(my_fine_cell_ids)
            assert size > 0
            ierr = A.InsertGlobalValues(my_fine_cell_ids,
                                        [int(basis_id)] * size, [val] * size)
            assert ierr == 0

        A.FillComplete(domain_map, range_map)

        a = sum_of_columns(A)
        assert np.all(a[:] >= 1.0)

        return A
예제 #8
0
 def colMap(self):
     comm = Epetra.SerialComm()
     # Matrix building gets done on all processors
     # Epetra.Map(numGlobalElements, numMyElements, indexBase, comm)
     # If NumGlobalElements = NumMyElements (and not equal to zero) the map is
     # defined to be a local replicated map
     return Epetra.Map(self.cols, self.cols, 0, comm)
    def _solve_(self, L, x, b):
         
        for iteration in range(self.iterations):
             # errorVector = L*x - b
             errorVector = Epetra.Vector(L.RangeMap())
             L.Multiply(False, x, errorVector)
             # If A is an Epetra.Vector with map M
             # and B is an Epetra.Vector with map M
             # and C = A - B
             # then C is an Epetra.Vector with *no map* !!!?!?!
             errorVector -= b

             tol = errorVector.Norm1()

             if iteration == 0:
                 tol0 = tol
                 
             if (tol / tol0) <= self.tolerance: 
                 break

             xError = Epetra.Vector(L.RowMap())
             
             Problem = Epetra.LinearProblem(L, xError, errorVector)
             Solver = self.Factory.Create("Klu", Problem)
             Solver.Solve()

             x[:] = x - xError
             
        if 'FIPY_VERBOSE_SOLVER' in os.environ:
            from fipy.tools.debug import PRINT        
            PRINT('iterations: %d / %d' % (iteration + 1, self.iterations))
            PRINT('residual:', errorVector.Norm2())
예제 #10
0
            def __init__(self):
                self.matrices = {
                    'A': Epetra.CrsMatrix(Epetra.Copy, std_map, 5),
                    'b': Epetra.Vector(std_map)
                }

                self.std_map = {1: std_map}
예제 #11
0
파일: trilinos_utils.py 프로젝트: jpra2/MAD
    def solve_linear_problem(comm, A, b):
        """
        retorna a solucao do sistema linear Ax = b
        input:
            A: matriz do sistema
            b: termo fonte
        output:
            x:solucao
        """

        n = len(b)
        assert A.NumMyCols() == A.NumMyRows()
        assert A.NumMyCols() == n

        if A.Filled():
            pass
        else:
            A.FillComplete()

        std_map = Epetra.Map(n, 0, comm)

        x = Epetra.Vector(std_map)

        linearProblem = Epetra.LinearProblem(A, x, b)
        solver = AztecOO.AztecOO(linearProblem)
        solver.SetAztecOption(AztecOO.AZ_output, AztecOO.AZ_warnings)
        solver.Iterate(10000, 1e-14)

        return x
예제 #12
0
def matrix_scipy_to_epetra(A_scipy, A_epetra=None):
    """
    Converts scipy matrix to a local (non-distributed) epetra matrix.
    Parameters
    ----------
    A_scipy: Scipy Matrix
    A_epetra: Epetra Matrix, optional
        An existing epetra matrix which has the same structure as the scipy matrix

    Returns
    -------
    A_epetra: Epetra Matrix
        If an existing Epetra matrix is passed, the values are replaced

    """
    comm = Epetra.MpiComm(MPI.COMM_SELF)
    map = Epetra.Map(A_scipy.shape[0], 0, comm)
    B = A_scipy.tocoo()

    if A_epetra is None:
        A_epetra = Epetra.CrsMatrix(Epetra.Copy, map, A_scipy.getnnz(axis=1).astype(np.int32), True)
        A_epetra.InsertGlobalValues(B.row, B.col, B.data)
        ierr = A_epetra.FillComplete()
    else:
        ierr = A_epetra.ReplaceMyValues(B.row, B.col, B.data)

    assert ierr == 0
    return A_epetra
예제 #13
0
    def setup(self):
        comm = Epetra.PyComm()
        std_map = Epetra.Map(10, 0, comm)

        class DummyMatrixManager:
            def __init__(self):
                self.matrices = {
                    'A': Epetra.CrsMatrix(Epetra.Copy, std_map, 5),
                    'b': Epetra.Vector(std_map)
                }

                self.std_map = {1: std_map}

            def get_matrix(self, name):
                return self.matrices[name]

            get_vector = get_matrix

        class DummyMesh:
            def __init__(self):
                self.matrix_manager = DummyMatrixManager()

        mesh = DummyMesh()

        self.problem = LinearProblem(mesh, None, 1)
예제 #14
0
    def __init__(self, operator, pid=0, label=""):
        Epetra.Operator.__init__(self)

        from tools import RealOperator

        self.__comm = Epetra.PyComm()
        self.__label = label
        self.__pid = pid

        if self.__comm.MyPID() == pid:
            if operator.dtype == 'complex128' or operator.dtype == 'complex64':
                self.__operator = RealOperator(operator)
            else:
                self.__operator = operator
        else:
            self.__operator = None

        if self.__comm.MyPID() == pid:
            num_my_elems_domain = self.__operator.shape[1]
            num_my_elems_range = self.__operator.shape[0]
        else:
            num_my_elems_domain = 0
            num_my_elems_range = 0

        self.__rangeMap = Epetra.Map(-1, num_my_elems_range, 0, self.__comm)
        self.__domainMap = Epetra.Map(-1, num_my_elems_domain, 0, self.__comm)
예제 #15
0
def test_Complex_Epetra():
    try:
        from PyTrilinos import Epetra
        from jadapy import ComplexEpetraInterface
    except ImportError:
        pytest.skip("Trilinos not found")

    dtype = numpy.float64
    numpy.random.seed(1234)
    tol = numpy.finfo(dtype).eps * 1e3
    atol = tol * 10
    n = 20
    k = 5

    comm = Epetra.PyComm()
    map = Epetra.Map(n, 0, comm)
    a1, a2 = generate_Complex_Epetra_test_matrix(map, [n, n], dtype)
    b1, b2 = generate_Complex_Epetra_test_matrix(map, [n, n], dtype)

    interface = ComplexEpetraInterface.ComplexEpetraInterface(map)

    alpha, beta = jdqz.jdqz(a2, b2, k, tol=tol, interface=interface)
    jdqz_eigs = numpy.array(sorted(alpha / beta, key=lambda x: abs(x)))

    eigs = scipy.linalg.eigvals(a1, b1)
    eigs = numpy.array(sorted(eigs, key=lambda x: abs(x)))
    eigs = eigs[:k]

    assert_allclose(jdqz_eigs.real, eigs.real, rtol=0, atol=atol)
    assert_allclose(abs(jdqz_eigs.imag), abs(eigs.imag), rtol=0, atol=atol)
예제 #16
0
    def _globalMatrixAndVectors(self):
        if not hasattr(self, 'globalVectors'):
            globalMatrix = self.matrix.asTrilinosMeshMatrix()

            mesh = self.var.mesh
            localNonOverlappingCellIDs = mesh._localNonOverlappingCellIDs
            
            ## The following conditional is required because empty indexing is not altogether functional.
            ## This numpy.empty((0,))[[]] and this numpy.empty((0,))[...,[]] both work, but this
            ## numpy.empty((3, 0))[...,[]] is broken.
            if self.var.shape[-1] != 0:
                s = (Ellipsis, localNonOverlappingCellIDs)
            else:
                s = (localNonOverlappingCellIDs,)
                
            nonOverlappingVector = Epetra.Vector(globalMatrix.domainMap,
                                                 self.var[s].ravel())
            from fipy.variables.coupledCellVariable import _CoupledCellVariable

            if isinstance(self.RHSvector, _CoupledCellVariable):
                RHSvector = self.RHSvector[localNonOverlappingCellIDs]
            else:
                RHSvector = numerix.reshape(numerix.array(self.RHSvector), self.var.shape)[s].ravel()
                
                    
            nonOverlappingRHSvector = Epetra.Vector(globalMatrix.rangeMap,
                                                    RHSvector)

            del RHSvector

            overlappingVector = Epetra.Vector(globalMatrix.colMap, self.var)

            self.globalVectors = (globalMatrix, nonOverlappingVector, nonOverlappingRHSvector, overlappingVector)

        return self.globalVectors
예제 #17
0
    def __solve_one_step(self, rhs, RAP, R):
        # returns P*(RAP)^-1* R*rhs

        rhs_coarse = Epetra.Vector(R.DomainMap())

        R.Multiply(True, rhs, rhs_coarse)

        if not np.max(np.abs(sum_of_columns(RAP))) < RAP.NormInf() * 1e-10:
            warnings.warn("sum of matrix columns does not equal to zero")

        # Set dirichlet boundary condition at a point
        if np.max(np.abs(sum_of_columns(RAP))) < RAP.NormInf() * 1e-10:
            row = 0
            RAP = Epetra.CrsMatrix(RAP)
            RAP = epetra_set_matrow_to_zero(RAP, row=0)
            rhs_coarse = epetra_set_vecrow_to_zero(rhs_coarse, row=0)
            if row in RAP.Map().MyGlobalElements():
                ierr = RAP.ReplaceGlobalValues([row], [row], 1.0)
                assert ierr == 0

        sol_coarse = solve_direct(RAP, rhs_coarse)

        sol_fine = Epetra.Vector(self.P.RangeMap())
        self.P.Multiply(False, sol_coarse, sol_fine)
        return sol_fine
예제 #18
0
파일: test_jdqr.py 프로젝트: BIMAU/jadapy
def test_Epetra_lowdim():
    try:
        from PyTrilinos import Epetra
        from jadapy import EpetraInterface
    except ImportError:
        pytest.skip("Trilinos not found")

    dtype = numpy.float64
    numpy.random.seed(1234)
    tol = numpy.finfo(dtype).eps * 1e3
    atol = tol * 10
    n = 20
    k = 2

    comm = Epetra.PyComm()
    map = Epetra.Map(n, 0, comm)
    a1, a2 = generate_Epetra_test_matrix(map, [n, n], dtype)

    interface = EpetraInterface.EpetraInterface(map)

    alpha = jdqr.jdqr(a2, k, Target.LargestMagnitude, tol=tol, subspace_dimensions=[10, 18], interface=interface)
    jdqr_eigs = numpy.array(sorted(alpha, key=lambda x: -abs(x)))

    eigs = scipy.linalg.eigvals(a1)
    eigs = numpy.array(sorted(eigs, key=lambda x: -abs(x)))
    eigs = eigs[:k]

    assert_allclose(jdqr_eigs.real, eigs.real, rtol=0, atol=atol)
    assert_allclose(abs(jdqr_eigs.imag), abs(eigs.imag), rtol=0, atol=atol)
예제 #19
0
def iterative_solver(List, Matrix, InputLHS, RHS, Prec):

  LHS = Epetra.MultiVector(InputLHS)
  
  Time = Epetra.Time(Matrix.Comm())

  hasConditionNumber = False;

  Solver = AztecOO.AztecOO(Matrix, LHS, RHS)
  Solver.SetPrecOperator(Prec)
  if (List['az_solver'] == "AZ_gmres"):
    Solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_gmres);
  elif List['az_solver'] == "AZ_cg":
    Solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_cg);
  elif List['az_solver'] == "AZ_cg_condnum":
    Solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_cg_condnum);
    hasConditionNumber = True
  elif List['az_solver'] == "AZ_gmres_condnum":
    Solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_gmres_condnum);
    hasConditionNumber = True
  elif List['az_solver'] == "AZ_bicgstab":
    Solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_bicgstab);
  elif List['az_solver'] == "AZ_tfqmr":
    Solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_tfqmr);
  elif List['az_solver'] == "AZ_cgs":
    Solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_cgs);
  else:
    print "Solver type not correct, ", List['az_solver']

  Solver.SetAztecOption(AztecOO.AZ_output, 16);
  if List['iters'] < 0 | List['iters'] > MAX_ITERATIONS:
    print "Maximum number of iterations either negative of > ", MAX_ITERATIONS;
    raise("PARAMETER_ERROR");
  if List['tol'] < 1e-12:
    print "Tolerance is too small"
    raise("PARAMETER_ERROR");

  if List['az_kspace'] > 0 & List['az_kspace'] <= MAX_KSPACE:
    Solver.SetAztecOption(AztecOO.AZ_kspace, List['az_kspace']);
  else:
    print "Krylov space dimension either negative of >", MAX_KSPACE
    print "You have", List['az_kspace']
    raise("PARAMETER_ERROR");

  if List['az_output'] == "16":
    Solver.SetAztecOption(AztecOO.AZ_output, 16)
  elif List['az_output'] == "32":
    Solver.SetAztecOption(AztecOO.AZ_output, 32)
  elif List['az_output'] == "AZ_last":
    Solver.SetAztecOption(AztecOO.AZ_output, AztecOO.AZ_last)
  elif List['az_output'] == "AZ_none":
    Solver.SetAztecOption(AztecOO.AZ_output, AztecOO.AZ_none)
    
  err = Solver.Iterate(List['iters'], List['tol']) 

  if hasConditionNumber:
    ConditionNumber = Solver.GetStatus(AztecOO.AZ_condnum)
  else:
    ConditionNumber = 0.0;
  return (err, Solver.NumIters(), Time.ElapsedTime(), ConditionNumber)
예제 #20
0
    def __init__(self, comm, number_of_elements=10):

        self.comm = comm
        self.rank = comm.MyPID()
        self.size = comm.NumProc()

        if self.rank == 0:
            number_of_rows = number_of_elements
        else:
            number_of_rows = 0

        unbalanced_map = Epetra.Map(-1, number_of_rows, 0, self.comm)

        self.A = Epetra.CrsMatrix(Epetra.Copy, unbalanced_map, 3)
        self.x = Epetra.Vector(unbalanced_map)
        self.b = Epetra.Vector(unbalanced_map)

        for gid in unbalanced_map.MyGlobalElements():
            if gid == 0:
                self.A.InsertGlobalValues(gid, [1], [gid])
                self.b[0] = -1
            elif gid == (number_of_elements - 1):
                self.A.InsertGlobalValues(gid, [1], [gid])
                self.b[-1] = 1
            else:
                self.A.InsertGlobalValues(gid, [-1, 2, -1],
                                          [gid - 1, gid, gid + 1])

        #optimizes storage
        self.A.FillComplete()
예제 #21
0
    def get_inverse_tril(self, A, rows):
        """
        Obter a matriz inversa de A
        obs: A deve ser quadrada
        input:
            A: CrsMatrix
            rows: numero de linhas

        output:
            INV: CrsMatrix inversa de A
        """
        num_cols = A.NumMyCols()
        num_rows = A.NumMyRows()
        assert num_cols == num_rows
        map1 = Epetra.Map(rows, 0, self.comm)

        Inv = Epetra.CrsMatrix(Epetra.Copy, map1, 3)

        for i in range(rows):
            b = Epetra.Vector(map1)
            b[i] = 1.0

            x = self.solve_linear_problem(A, b, rows)
            lines = np.nonzero(x[:])[0].astype(np.int32)
            col = np.repeat(i, len(lines)).astype(np.int32)
            Inv.InsertGlobalValues(lines, col, x[lines])

        return Inv
예제 #22
0
    def __init__(self, size, bandwidth=0, sizeHint=None, nonOverlappingMap=None, overlappingMap=None):
        """Creates a `_TrilinosMatrix`.

        :Parameters:
          - `size`: The size N for an N by N matrix.
          - `bandwidth`: The proposed band width of the matrix.
          - `sizeHint`: ???
          - `map`: The Epetra `Map` for the rows that this processor holds
        """
        if sizeHint is not None and bandwidth == 0:
            bandwidth = (sizeHint + size - 1) / (size or 1)
        else:
            bandwidth = bandwidth

        if nonOverlappingMap is None:
            comm = Epetra.PyComm()
            # Matrix building gets done on one processor - it gets the map for
            # all the rows
            if comm.MyPID() == 0:
                nonOverlappingMap = Epetra.Map(size, range(0, size), 0, comm)
            else:
                nonOverlappingMap = Epetra.Map(size, [], 0, comm)

        matrix = Epetra.CrsMatrix(Epetra.Copy, nonOverlappingMap, bandwidth*3/2)

        # Leave extra bandwidth, to handle multiple insertions into the
        # same spot. It's memory-inefficient, but it'll get cleaned up when
        # FillComplete is called, and according to the Trilinos devs the
        # performance boost will be worth it.

        _TrilinosMatrixBase.__init__(self,
                                     matrix=matrix,
                                     nonOverlappingMap=nonOverlappingMap,
                                     overlappingMap=overlappingMap,
                                     bandwidth=bandwidth)
예제 #23
0
    def __matmul__(self, x):
        if isinstance(x, numpy.ndarray):
            local_map = Epetra.LocalMap(x.shape[0], 0, self.Comm())
            x = Epetra.MultiVector(local_map, x.T)

        tmp = Vector(self.Map(), x.NumVectors())
        tmp.Multiply('N', 'N', 1.0, self, x, 0.0)
        return tmp
예제 #24
0
 def __rmul__(self, other):
     if type(numerix.ones(1)) == type(other):
         y = Epetra.Vector(other)
         result = Epetra.Vector(self.nonOverlappingMap)
         self._getMatrix().Multiply(True, y, result)
         return _trilinosToNumpyVector(result)
     else:
         return self * other
 def __init__(self, layers):
     self.__comm = Epetra.PyComm()
     self.__layers = layers
     self.__single_proc_map, self.__multiple_proc_map = self.generate_maps()
     self.__importer = Epetra.Import(self.__multiple_proc_map,
                                     self.__single_proc_map)
     self.__exporter = Epetra.Export(self.__multiple_proc_map,
                                     self.__single_proc_map)
예제 #26
0
    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
예제 #27
0
    def dot(self, x):
        local_map = Epetra.LocalMap(self.shape[1], 0, self.Comm())
        tmp = Epetra.MultiVector(local_map, x.shape[1])
        tmp.Multiply('T', 'N', 1.0, self, x, 0.0)

        if self.shape[1] == 1 or x.shape[1] == 1:
            # Numpy expects a 1D array in this case
            return tmp.array.copy().flatten()
        return tmp.array.copy().T
예제 #28
0
    def takeDiagonal(self):
        nonoverlapping_result = _TrilinosMatrixFromShape.takeDiagonal(self)

        overlapping_result = Epetra.Vector(self.colMap)
        overlapping_result.Import(nonoverlapping_result,
                                  Epetra.Import(self.colMap, self.domainMap),
                                  Epetra.Insert)

        return overlapping_result
예제 #29
0
 def __init__(self, mesh, interpolation_method=None, x=None):
     self.comm = Epetra.PyComm()
     std_map = Epetra.Map(len(mesh.all_volumes), 0, self.comm)
     self.T = Epetra.CrsMatrix(Epetra.Copy, std_map, 0)
     self.Q = Epetra.Vector(std_map)
     if x is None:
         self.x = Epetra.Vector(std_map)
     else:
         self.x = x
예제 #30
0
    def __init_field_graph(self):

        # Assign velocity_x (ux) and velocity_y (uy) indices for each node
        ##Rambod change removed *2 ( added it back)
        self.number_of_field_variables = 2 * self.__global_number_of_nodes
        global_indices = self.balanced_map.MyGlobalElements()
        Global_Indices = global_indices  #self.balanced_map.MyGlobalElements()

        XY_Global_Indices = np.zeros(2 * len(Global_Indices), dtype=np.int32)

        for index in range(len(Global_Indices)):
            XY_Global_Indices[2 * index] = 2 * Global_Indices[index]
            XY_Global_Indices[2 * index + 1] = 2 * Global_Indices[index] + 1

        XY_list = XY_Global_Indices.tolist()

        field_global_indices = np.empty(2 * global_indices.shape[0],
                                        dtype=np.int32)

        field_global_indices[0:-1:2] = 2 * global_indices
        field_global_indices[1::2] = 2 * global_indices + 1

        ### removed multiply by two here rambod Rambod
        Number_of_Global_Variables = 2 * self.__global_number_of_nodes

        # create Epetra Map based on node degrees of Freedom
        #self.field_balanced_map = Epetra.Map(self.number_of_field_variables,field_global_indices.tolist(),0, self.comm)
        self.field_balanced_map = Epetra.Map(Number_of_Global_Variables,
                                             XY_list, 0, self.comm)

        # Instantiate the corresponding graph
        self.balanced_field_graph = Epetra.CrsGraph(Epetra.Copy,
                                                    self.field_balanced_map,
                                                    True)
        # fill the field graph
        for i in global_indices:
            # array of global indices in neighborhood of each node
            global_index_array = (
                self.balanced_neighborhood_graph.ExtractGlobalRowCopy(i))
            # convert global node indices to appropriate field indices
            field_index_array = (np.sort(
                np.r_[2 * global_index_array,
                      2 * global_index_array + 1]).astype(np.int32))

            # insert rows into balanced graph per appropriate rows
            self.balanced_field_graph.InsertGlobalIndices(
                2 * i, field_index_array)
            self.balanced_field_graph.InsertGlobalIndices(
                2 * i + 1, field_index_array)

        # complete fill of balanced graph
        self.balanced_field_graph.FillComplete()
        # create balanced field map from balanced field neighborhood graph
        self.balanced_field_map = self.balanced_field_graph.Map()

        return