def sparseMatrix2coo(A): """Convert SparseMatrix to scipy.coo_matrix. Parameters ---------- A: pg.SparseMapMatrix | pg.SparseMatrix Matrix to convert from. Returns ------- mat: scipy.coo_matrix Matrix to convert into. """ from scipy.sparse import coo_matrix vals = pg.RVector() rows = pg.IndexArray([0]) cols = pg.IndexArray([0]) if isinstance(A, pg.SparseMatrix): C = pg.RSparseMapMatrix(A) C.fillArrays(vals=vals, rows=rows, cols=cols) return coo_matrix(vals, (rows, cols)) elif isinstance(A, pg.SparseMapMatrix): A.fillArrays(vals, rows, cols) return coo_matrix(vals, (rows, cols)) return coo_matrix(A)
def test_DataContainerFilter(self): """ """ data = pg.DataContainer() data.resize(101) data.markInvalid([0, 100]) x = np.array([0, 100], dtype="int") a = pg.IndexArray(x) data.markInvalid(a) data.markInvalid(pg.IndexArray(np.array([0, 100], dtype="int")))
def test_ListToIndexArray(self): """ implemented in custom_rvalue.cpp""" idx = [0, 1, 1, 0] I = pg.IndexArray(idx) self.assertEqual(pg.sum(I), sum(idx)) bn = (np.array(idx) > 0) # numpy bool idx = np.nonzero(bn)[0] # numpy int64 # numyp int64 -> IndexArray I = pg.IndexArray(idx) self.assertEqual(I.size(), 2) self.assertEqual(pg.sum(I), sum(idx))
def test_DataContainerFilter(self): """ """ data = pg.DataContainer() data.resize(5) data.markValid([0, 4]) self.assertEqual(data('valid'), [1.0, 0.0, 0.0, 0.0, 1.0]) data.markInvalid(pg.IndexArray(np.arange(5, dtype="long"))) self.assertEqual(data('valid'), [0.0, 0.0, 0.0, 0.0, 0.0]) data.markValid(np.arange(5, dtype="long")) self.assertEqual(data('valid'), [1.0, 1.0, 1.0, 1.0, 1.0]) data.markInvalid(range(5)) self.assertEqual(data('valid'), [0.0, 0.0, 0.0, 0.0, 0.0]) x = np.arange(5, dtype='float') data.markValid(pg.Vector(x) > 2.0) self.assertEqual(data('valid'), [0.0, 0.0, 0.0, 1.0, 1.0]) data.markValid(pg.BVector(x < 2.0)) self.assertEqual(data('valid'), [1.0, 1.0, 0.0, 1.0, 1.0]) data.markInvalid(pg.find(x > 3.0)) self.assertEqual(data('valid'), [1.0, 1.0, 0.0, 1.0, 0.0]) data.markInvalid(x < 1.0) self.assertEqual(data('valid'), [0.0, 1.0, 0.0, 1.0, 0.0])
def convertDolfinMesh(mesh): """ Convert :term:`Dolfin` mesh instance into a gimliapi:`GIMLI::Mesh` The resulting mesh does not separate between different boundary domains. Instead each outer boundary have the marker 1. TODO * 1D Mesh * 3D Mesh Parameters ---------- mesh: Dolfin::Mesh Returns ------- out: gimliapi:`GIMLI::Mesh` """ out = pg.Mesh(2) for v in mesh.coordinates(): out.createNode(v) for c in mesh.cells(): out.createCell(pg.IndexArray(c)) out.createNeighbourInfos() for b in out.boundaries(): if b.leftCell() is None or b.rightCell() is None: b.setMarker(1) return out
def convertHDF5Mesh(h5Mesh, group='mesh', indices='cell_indices', pos='coordinates', cells='topology', marker='values', marker_default=0, dimension=3, verbose=True, useFenicsIndices=False): """ Converts instance of a hdf5 mesh to a :gimliapi:`GIMLI::Mesh`. For full documentation please see :py:mod:`pygimli:meshtools:readHDF5Mesh`. """ # open mesh containing group inside hdf file inmesh = h5Mesh.get(group) # get node positions mesh_pos = inmesh[pos][:] # get cells if useFenicsIndices: # case 1/2: using fenics specific indices # TODO why extra indices? cause this is really slow # figure out the nature and purpose of the extra fenics indices mesh_indices = inmesh[indices] try: mesh_cells = inmesh[cells][mesh_indices] except IndexError as IE: print('Fenics Indices arren\'t just in arbitrary order in range\ (0, cellCount) as expected. Need Fix.') raise IE else: # case 2/2: indices implicit: [0, ... cellCount) mesh_cells = inmesh[cells][:] # get marker try: # case 1/3: marker found in hdf file mesh_marker = inmesh[marker][:] except KeyError: if isinstance(marker_default, int): # case 2/3: marker not found, given as int mesh_marker = np.ones(len(mesh_cells), dtype=int) * marker_default else: # case 3/3: marker not found, given as array_like mesh_marker = marker_default # start building pygimli mesh mesh = pg.Mesh(dimension) for node in mesh_pos: mesh.createNode(node) for i, cell in enumerate(mesh_cells): mesh.createCell(pg.IndexArray(cell), marker=int(mesh_marker[i])) mesh.createNeighbourInfos() if verbose: print('converted mesh:', mesh) return mesh
def test_NumpyToIndexArray(self): """Implemented in custom_rvalue.cpp.""" x = np.array(range(10)) a = pg.IndexArray(x) self.assertEqual(a.size(), len(x)) self.assertEqual(pg.sum(a), sum(x)) x = np.arange(0, 10, dtype=np.int64) a = pg.IndexArray(x) self.assertEqual(a.size(), len(x)) self.assertEqual(pg.sum(a), sum(x)) x = np.arange(0, 10, dtype="int") a = pg.IndexArray(x) self.assertEqual(a.size(), len(x)) self.assertEqual(pg.sum(a), sum(x)) x = np.array([0, 100], dtype="int") a = pg.IndexArray(x) self.assertEqual(a.size(), len(x)) self.assertEqual(pg.sum(a), sum(x))
def test_IndexArrayToNumpy(self): """Implemented through hand_made_wrapper.py""" # check if array is really taken # not yet taken: .. see __init__.py:__BVectorArrayCall__ v = pg.IndexArray(10, 2) self.assertEqual(type(v), pg.IndexArray) # print(type(v[0])) # print(pg.showSizes()) a = np.asarray(v) self.assertEqual(type(a), np.ndarray) # self.assertEqual(a.dtype, 'int64') self.assertEqual(len(a), 10) self.assertEqual(sum(a), 20) a = np.array(v) self.assertEqual(type(a), np.ndarray) self.assertEqual(len(a), 10) self.assertEqual(sum(a), 20)
def init(self, mesh, tMax, satSteps, ertSteps): """Initialize some settings.""" if mesh is not None: self.parMesh = pg.Mesh(mesh) self.setMesh(mesh) self.createRefinedForwardMesh(refine=False, pRefine=False) self.tMax = tMax self.satSteps = satSteps self.ertSteps = ertSteps self.timesAdvection = np.linspace(1, tMax, satSteps) self.timesERT = pg.IndexArray( np.floor( np.linspace(0, len(self.timesAdvection) - 1, self.ertSteps))) self._J = pg.Matrix() self.setJacobian(self._J) self.ws = WorkSpace()
def test_IndexAccess(self): I = pg.IndexArray([0, 1, 1, 0]) np.testing.assert_array_equal(pg.sum(I), 2) np.testing.assert_array_equal(sum(I), 2) np.testing.assert_array_equal(np.sum(I), 2)
#ax, _ = pg.show(mesh, data=c[400]*0.001, label='Concentration $c$ in g$/$l', #cMin=0, cMax=2.5) print('Solve ERT modelling ...') # Create survey measurement scheme ertScheme = pg.physics.ert.createERTData(pg.utils.grange(-20, 20, dx=1.0), schemeName='dd') # Create suitable mesh for ert forward calculation meshERT = mt.createParaMesh(ertScheme, quality=33, paraMaxCellSize=0.2, boundaryMaxCellSize=50, smooth=[1, 2]) # Select 10 time frame to simulate ERT data timesERT = pg.IndexArray(np.floor(np.linspace(0, len(c) - 1, 10))) # Create conductivity of fluid for salt concentration $c$ sigmaFluid = c[timesERT] * 0.1 + 0.01 # Calculate bulk resistivity based on Archie's Law resBulk = pg.physics.petro.resistivityArchie(rFluid=1. / sigmaFluid, porosity=0.3, m=1.3, mesh=mesh, meshI=meshERT, fill=1) # apply background resistivity model rho0 = np.zeros(meshERT.cellCount()) + 1000. for c in meshERT.cells(): if c.center()[1] < -8: rho0[c.id()] = 150. elif c.center()[1] < -2: