def addAt(self, vector, id1, id2): """Add elements of `vector` to the positions in the matrix corresponding to (`id1`,`id2`) Parameters ---------- vector : array_like The values to insert. id1 : array_like The row indices. id2 : array_like The column indices. overlapping : bool Whether to add ghosted values or not (Ignored. Default False). Examples -------- >>> L = _PysparseMatrixFromShape(rows=3, cols=3) >>> L.put([3., 10., numerix.pi, 2.5], [0, 0, 1, 2], [2, 1, 1, 0]) >>> L.addAt([1.73, 2.2, 8.4, 3.9, 1.23], [1, 2, 0, 0, 1], [2, 2, 0, 0, 2]) >>> print(L) 12.300000 10.000000 3.000000 --- 3.141593 2.960000 2.500000 --- 2.200000 """ self.matrix.update_add_at(vector, numerix.asarray(id1, dtype='int32'), numerix.asarray(id2, dtype='int32'))
def addAt(self, vector, id1, id2): """ Add elements of `vector` to the positions in the matrix corresponding to (`id1`,`id2`) >>> L = _PysparseMatrixFromShape(rows=3, cols=3) >>> L.put([3.,10.,numerix.pi,2.5], [0,0,1,2], [2,1,1,0]) >>> L.addAt([1.73,2.2,8.4,3.9,1.23], [1,2,0,0,1], [2,2,0,0,2]) >>> print L 12.300000 10.000000 3.000000 --- 3.141593 2.960000 2.500000 --- 2.200000 """ self.matrix.update_add_at(vector, numerix.asarray(id1, dtype='int32'), numerix.asarray(id2, dtype='int32'))
def addAt(self, vector, id1, id2): """ Add elements of `vector` to the positions in the matrix corresponding to (`id1`,`id2`) >>> L = _PysparseMatrixFromShape(rows=3, cols=3) >>> L.put([3., 10., numerix.pi, 2.5], [0, 0, 1, 2], [2, 1, 1, 0]) >>> L.addAt([1.73, 2.2, 8.4, 3.9, 1.23], [1, 2, 0, 0, 1], [2, 2, 0, 0, 2]) >>> print(L) 12.300000 10.000000 3.000000 --- 3.141593 2.960000 2.500000 --- 2.200000 """ self.matrix.update_add_at(vector, numerix.asarray(id1, dtype='int32'), numerix.asarray(id2, dtype='int32'))
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)
def __rmul__(self, other): if type(numerix.ones(1, 'l')) == type(other): N = self._shape[1] x = PETSc.Vec().createMPI(N, comm=self.matrix.comm) y = x.duplicate() x[:] = other self.matrix.multTranspose(x, y) return numerix.asarray(y) else: return self * other
def _ijv2csr(self, i, j, v): """Convert arrays of matrix indices and values into CSR format see: http://netlib.org/linalg/html_templates/node91.html#SECTION00931100000000000000 .. note:: petsc4py only understands CSR formatted matrices (setValuesCSR and setValuesIJV both inexplicably call the same underlying routine). Parameters ---------- i : array_like column indices j : array_like row indices v : array_like non-zero values Returns ------- ptrs : array_like locations in the val vector that start a row, terminated with len(val) + 1 cols : array_like column indices data : array_like non-zero values """ i = numerix.asarray(i) j = numerix.asarray(j) v = numerix.asarray(v) start_row, end_row = self.matrix.getOwnershipRange() ix = numerix.lexsort([i, j]) ix = ix[(j[ix] >= start_row) & (j[ix] < end_row)] cols = i[ix] row_ptr = numerix.searchsorted(j[ix], numerix.arange(start_row, end_row + 1)) vals = v[ix] # note: PETSc (at least via pip) only seems to handle 32 bit addressing return row_ptr.astype('int32'), cols.astype('int32'), vals
def _fipy2petscGhost(self, var): """Convert a FiPy Variable to a PETSc `GhostVec` Moves the ghosts to the end, as necessary. `var` may be coupled/vector and so moving the ghosts is a bit subtle. Given a (2x4) vector variable `vij` ``` v00 v01 (v02) processor 0 v10 v11 (v12) (v01) v02 v03 processor 1 (v11) v12 v13 ``` where i is the vector index and j is the global index. Elements in () are ghosted We end up with the `GhostVec` ``` v00 v01 v10 v11 (v02) (v12) [4, 6] processor 0 v02 v03 v12 v13 (v01) (v11) [1, 3] processor 1 ``` where the [a, b] are the global ghost indices """ corporeal = numerix.asarray(var[..., self._bodies]).ravel() incorporeal = numerix.asarray(var[..., ~self._bodies]).ravel() array = numerix.concatenate([corporeal, incorporeal]) comm = self.mesh.communicator.petsc4py_comm vec = PETSc.Vec().createGhostWithArray( ghosts=self._ghosts.astype('int32'), array=array, comm=comm) return vec
def _getStencil_(self, id1, id2, globalOverlappihgIDs, globalNonOverlappihgIDs, overlapping=False): id1 = globalOverlappihgIDs[id1] if overlapping: mask = numerix.ones(id1.shape, dtype=bool) else: mask = numerix.in1d(id1, globalNonOverlappihgIDs) id1 = self.matrix()._mesh2matrix(id1[mask]) id2 = numerix.asarray(id2)[mask] return id1, id2, mask
def _globalMatrixAndVectors(self): if not hasattr(self, 'globalVectors'): globalMatrix = self.matrix overlappingVector = self.matrix._fipy2petscGhost(var=self.var) from fipy.variables.coupledCellVariable import _CoupledCellVariable if isinstance(self.RHSvector, _CoupledCellVariable): RHSvector = self.RHSvector else: RHSvector = numerix.reshape(numerix.asarray(self.RHSvector), self.var.shape) overlappingRHSvector = self.matrix._fipy2petscGhost(var=RHSvector) self.globalVectors = (globalMatrix, overlappingVector, overlappingRHSvector) return self.globalVectors
def _petsc2fipyGhost(self, vec): """Convert a PETSc `GhostVec` to a FiPy Variable (form) Moves the ghosts from the end, as necessary. The return Variable may be coupled/vector and so moving the ghosts is a bit subtle. Given an 8-element `GhostVec` `vj` ``` v0 v1 v2 v3 (v4) (v6) [4, 6] processor 0 v4 v5 v6 v7 (v1) (v3) [1, 3] processor 1 ``` where j is the global index and the `[a, b]` are the global ghost indices. Elements in () are ghosted We end up with the (2x4) FiPy Variable ``` v0 v1 (v4) processor 0 v2 v3 (v6) (v1) v4 v4 processor 1 (v3) v6 v7 ``` """ N = len(self.mesh._globalOverlappingCellIDs) M = self._m2m.numberOfEquations var = numerix.empty((M, N), dtype=vec.array.dtype) bodies = numerix.asarray(vec) if M > 1: bodies = numerix.reshape(bodies, (M, -1)) var[..., self._m2m.bodies] = bodies vec.ghostUpdate() with vec.localForm() as lf: if len(self._m2m.ghosts) > 0: ids = numerix.arange(-len(self._m2m.ghosts), 0) ghosts = numerix.reshape(numerix.array(lf)[ids], (M, -1)) var[..., ~self._m2m.bodies] = ghosts return var.flatten()
def _ijv2csr(self, i, j, v): """Convert arrays of matrix indices and values into CSR format see: http://netlib.org/linalg/html_templates/node91.html#SECTION00931100000000000000 .. note:: petsc4py only understands CSR formatted matrices (setValuesCSR and setValuesIJV both inexplicably call the same underlying routine). Parameters ---------- i : array_like column indices j : array_like row indices v : array_like non-zero values Returns ------- row_ptr : array_like locations in the val vector that start a row, terminated with len(val) + 1 cols : array_like column indices val : array_like non-zero values """ # from fipy.tools.debug import PRINT # PRINT("i:", i) # PRINT("j:", j) # PRINT("v:", v) i = numerix.asarray(i) j = numerix.asarray(j) v = numerix.asarray(v) start_row, end_row = self.matrix.getOwnershipRange() # PRINT("start_row:", start_row) # PRINT("end_row:", end_row) ix = numerix.lexsort([i, j]) ix = ix[(j[ix] >= start_row) & (j[ix] < end_row)] cols = i[ix] row_ptr = numerix.searchsorted( j[ix], # numerix.arange(0, self._shape[1]+1)) numerix.arange(start_row, end_row + 1)) vals = v[ix] # PRINT("i[ix]:", i[ix]) # PRINT("j[ix]:", j[ix]) # PRINT("v[ix]:", v[ix]) # PRINT("size:", self._shape) # PRINT("shape:", self._shape[0]) # # PRINT("row_ptr:", row_ptr) # PRINT("cols:", cols) # PRINT("vals:", vals) # # PRINT("size:", self.matrix.sizes) # PRINT("owns-rows:", self.matrix.getOwnershipRange()) # PRINT("owns-cols:", self.matrix.getOwnershipRangesColumn()) # note: PETSc (at least via pip) only seems to handle 32 bit addressing return row_ptr.astype('int32'), cols.astype('int32'), vals
def _applyUnderRelaxation(self, underRelaxation=None): if underRelaxation is not None: self.matrix.putDiagonal(numerix.asarray(self.matrix.takeDiagonal()) / underRelaxation) self.RHSvector += (1 - underRelaxation) * self.matrix.takeDiagonal() * numerix.array(self.var).flatten()
def __higherOrderbuildMatrix(self, var, SparseMatrix, boundaryConditions=(), dt=None, transientGeomCoeff=None, diffusionGeomCoeff=None): mesh = var.mesh N = mesh.numberOfCells M = mesh._maxFacesPerCell if self.order > 2: higherOrderBCs, lowerOrderBCs = self.__getBoundaryConditions( boundaryConditions) var, lowerOrderL, lowerOrderb = self.lowerOrderDiffusionTerm._buildMatrix( var=var, SparseMatrix=SparseMatrix, boundaryConditions=lowerOrderBCs, dt=dt, transientGeomCoeff=transientGeomCoeff, diffusionGeomCoeff=diffusionGeomCoeff) del lowerOrderBCs lowerOrderb = lowerOrderb / mesh.cellVolumes volMatrix = SparseMatrix(mesh=var.mesh, bandwidth=1) volMatrix.addAtDiagonal(1. / mesh.cellVolumes) lowerOrderL = volMatrix * lowerOrderL del volMatrix if not hasattr(self, 'coeffDict'): coeff = self._getGeomCoeff(var)[0] minusCoeff = -coeff coeff.dontCacheMe() minusCoeff.dontCacheMe() self.coeffDict = { 'cell 1 diag': minusCoeff, 'cell 1 offdiag': coeff } del coeff del minusCoeff self.coeffDict['cell 2 offdiag'] = self.coeffDict[ 'cell 1 offdiag'] self.coeffDict['cell 2 diag'] = self.coeffDict['cell 1 diag'] mm = self.__getCoefficientMatrix(SparseMatrix, var, self.coeffDict['cell 1 diag']) L, b = self.__doBCs(SparseMatrix, higherOrderBCs, N, M, self.coeffDict, mm, numerix.zeros(len(var.ravel()), 'd')) del higherOrderBCs del mm b = numerix.asarray(L * lowerOrderb) + b del lowerOrderb L = L * lowerOrderL del lowerOrderL elif self.order == 2: if not hasattr(self, 'coeffDict'): coeff = self._getGeomCoeff(var) minusCoeff = -coeff[0] coeff[0].dontCacheMe() minusCoeff.dontCacheMe() self.coeffDict = { 'cell 1 diag': minusCoeff, 'cell 1 offdiag': coeff[0] } self.coeffDict['cell 2 offdiag'] = self.coeffDict[ 'cell 1 offdiag'] self.coeffDict['cell 2 diag'] = self.coeffDict['cell 1 diag'] self.__calcAnisotropySource(coeff, mesh, var) del coeff del minusCoeff higherOrderBCs, lowerOrderBCs = self.__getBoundaryConditions( boundaryConditions) del lowerOrderBCs L, b = self.__doBCs( SparseMatrix, higherOrderBCs, N, M, self.coeffDict, self.__getCoefficientMatrix(SparseMatrix, var, self.coeffDict['cell 1 diag']), numerix.zeros(len(var.ravel()), 'd')) if hasattr(self, 'anisotropySource'): b -= self.anisotropySource del higherOrderBCs else: L = SparseMatrix(mesh=mesh) L.addAtDiagonal(mesh.cellVolumes) b = numerix.zeros(len(var.ravel()), 'd') return (var, L, b)
############# To convert into numpy array, save it in numpy file and again store it in a variable np.save('rho_value.npy', rho) rho_value = [] rho_value = np.load('rho_value.npy') # ### Convert m values into numpy array by saving and loading into a file numerix.save('mValue_info.npy', mAllCell) # load the state space coordinate array values mValue = numerix.load('mValue_info.npy') np.shape(mValue) # ### Convert m values from cartesian to spherical polar mvalue_sph_pol = numerix.asarray(cart2pol(mValue)) Phi_deg = mvalue_sph_pol[2, :] * (180.0 / np.pi) print('Phi_max_degree = ' + str(max(Phi_deg))) print('Phi_min_degree = ' + str(min(Phi_deg))) phi_angle_all = mvalue_sph_pol[2, :] phi_value = 0.0 * numerix.pi # initial phi value phi_step = 1.0 * 360.0 # Phi value range(0,2pi) will be divided by phi_step delta = (2 * numerix.pi) / phi_step # delta by which phi value will be increased phi_save = [ ] # this will save the values of Phi, which will be required to do the integration total_size = 0 # this will keep track the total number of cells being covered during calculation
def _calcValue(self): returnMask = numerix.zeros(self.shape, dtype=bool) for constraint in self.var.constraints: returnMask = returnMask | numerix.asarray(constraint.where) return returnMask
def Norm2(self, vec): return numerix.L2norm(numerix.asarray(vec))
def _applyUnderRelaxation(self, underRelaxation=None): if underRelaxation is not None: self.matrix.putDiagonal( numerix.asarray(self.matrix.takeDiagonal()) / underRelaxation) self.RHSvector += (1 - underRelaxation) * self.matrix.takeDiagonal( ) * numerix.array(self.var).flatten()
def Norm2(self, vec): from fipy.tools import numerix return numerix.L2norm(numerix.asarray(vec))
def _save_nested_dict(D, root, **kwargs): """ Recursively traverse the nested dictionary and save data and metadata into a mirrored hierarchy Args: D (dict): A possibly nested dictionary with special keys root (:class:`h5py:Group`): Reference to a node within the state hierarchy """ logger = logging.getLogger(__name__) logger.debug('Saving to root: {}'.format(root)) path = root.name if not isinstance(D, Mapping): raise TypeError('Expected (nested) dict, but got {}'.format(type(D))) D = D.copy() meta = D.pop('metadata', None) if meta: if not isinstance(meta, Mapping): raise ValueError( '"metadata" should be mapping, not {}. In path: {}'.format(type(meta), path)) logger.debug('Saving {}:metadata'.format(path)) for metak, metav in meta.items(): if (metav is not None) and (metak not in root.attrs): root.attrs[metak] = metav else: logger.debug('Skipping metadata {}.{} = {}'.format(path, metak, metav)) data = D.pop('data', None) if data: try: dsdata, dsmeta = data dsdata = np.asarray(dsdata) except: logger.error('Improper {}.data: {}'.format(path, data)) raise ValueError( '"data" should be a (array, meta_dict) sequence. In path: {}'.format(path)) logger.debug('data at {}'.format(path)) # logger.debug('data shape={} dtype={}'.format(dsdata.shape, dsdata.dtype)) # logger.debug('data:metadata: {}'.format(dsmeta)) try: _save_data(root, dsdata, dsmeta, name='data', **kwargs) except IOError: logger.error('Error saving {} data {}: {}'.format(root, root['data'], dsdata.shape)) raise stdata = D.pop('data_static', None) if stdata: try: dsstdata, dsstmeta = stdata except: logger.error('Improper {}.data_static: {}'.format(path, stdata)) raise ValueError( '"data_static" should be a (array, meta_dict) sequence. In path: {}'.format(path)) logger.debug('data_static at {}'.format(path)) logger.debug('data_static shape={} dtype={}'.format(dsstdata.shape, dsstdata.dtype)) if 'data' not in root: ds = root.create_dataset('data', data=dsstdata, **kwargs ) if dsstmeta: ds.attrs.update(dsstmeta) # now traverse the rest of the keys which are not popped for k in D: grp = root.require_group(k) _save_nested_dict(D[k], grp, **kwargs)