def test_centering(self): M1d = TensorMesh([10], 'C') M2d = TensorMesh([10, 10], 'CC') M3d = TensorMesh([10, 10, 10], 'CCC') self.assertLess(np.abs(M1d.x0 + 0.5).sum(), TOL) self.assertLess(np.abs(M2d.x0 + 0.5).sum(), TOL) self.assertLess(np.abs(M3d.x0 + 0.5).sum(), TOL)
def dotest(MYSOLVER, multi=False, A=None, **solverOpts): if A is None: h1 = np.ones(10) * 100. h2 = np.ones(10) * 100. h3 = np.ones(10) * 100. h = [h1, h2, h3] M = TensorMesh(h) D = M.faceDiv G = -M.faceDiv.T Msig = M.getFaceInnerProduct() A = D * Msig * G A[-1, -1] *= 1 / M.vol[ -1] # remove the constant null space from the matrix else: M = Mesh.TensorMesh([A.shape[0]]) Ainv = MYSOLVER(A, **solverOpts) if multi: e = np.ones(M.nC) else: e = np.ones((M.nC, numRHS)) rhs = A * e x = Ainv * rhs Ainv.clean() return np.linalg.norm(e - x, np.inf)
def dotest(MYSOLVER, multi=False, A=None, **solverOpts): if A is None: h1 = np.ones(10)*100. h2 = np.ones(10)*100. h3 = np.ones(10)*100. h = [h1,h2,h3] M = TensorMesh(h) D = M.faceDiv G = -M.faceDiv.T Msig = M.getFaceInnerProduct() A = D*Msig*G A[-1,-1] *= 1/M.vol[-1] # remove the constant null space from the matrix else: M = Mesh.TensorMesh([A.shape[0]]) Ainv = MYSOLVER(A, **solverOpts) if multi: e = np.ones(M.nC) else: e = np.ones((M.nC, numRHS)) rhs = A * e x = Ainv * rhs Ainv.clean() return np.linalg.norm(e-x,np.inf)
class SimpleOctreeOperatorTests(unittest.TestCase): def setUp(self): h1 = np.random.rand(5) h2 = np.random.rand(7) h3 = np.random.rand(3) self.tM = TensorMesh([h1,h2,h3]) self.oM = TreeMesh([h1,h2,h3]) self.tM2 = TensorMesh([h1,h2]) self.oM2 = TreeMesh([h1,h2]) def test_faceDiv(self): self.assertAlmostEqual((self.tM.faceDiv - self.oM.faceDiv).toarray().sum(), 0) self.assertAlmostEqual((self.tM2.faceDiv - self.oM2.faceDiv).toarray().sum(), 0) def test_nodalGrad(self): self.assertAlmostEqual((self.tM.nodalGrad - self.oM.nodalGrad).toarray().sum(), 0) self.assertAlmostEqual((self.tM2.nodalGrad - self.oM2.nodalGrad).toarray().sum(), 0) def test_edgeCurl(self): self.assertAlmostEqual((self.tM.edgeCurl - self.oM.edgeCurl).toarray().sum(), 0) # self.assertAlmostEqual((self.tM2.edgeCurl - self.oM2.edgeCurl).toarray().sum(), 0) def test_InnerProducts(self): self.assertAlmostEqual((self.tM.getFaceInnerProduct() - self.oM.getFaceInnerProduct()).toarray().sum(), 0) self.assertAlmostEqual((self.tM2.getFaceInnerProduct() - self.oM2.getFaceInnerProduct()).toarray().sum(), 0) self.assertAlmostEqual((self.tM2.getEdgeInnerProduct() - self.oM2.getEdgeInnerProduct()).toarray().sum(), 0) self.assertAlmostEqual((self.tM.getEdgeInnerProduct() - self.oM.getEdgeInnerProduct()).toarray().sum(), 0)
def setUp(self): h1 = np.random.rand(5) h2 = np.random.rand(7) h3 = np.random.rand(3) self.tM = TensorMesh([h1,h2,h3]) self.oM = TreeMesh([h1,h2,h3]) self.tM2 = TensorMesh([h1,h2]) self.oM2 = TreeMesh([h1,h2])
def test_negative(self): M1d = TensorMesh([10], 'N') self.assertRaises(Exception, TensorMesh, [10], 'F') M2d = TensorMesh([10, 10], 'NN') M3d = TensorMesh([10, 10, 10], 'NNN') self.assertLess(np.abs(M1d.x0 + 1.0).sum(), TOL) self.assertLess(np.abs(M2d.x0 + 1.0).sum(), TOL) self.assertLess(np.abs(M3d.x0 + 1.0).sum(), TOL)
def setUp(self): a = np.array([1, 1, 1]) b = np.array([1, 2]) c = np.array([1, 4]) gridIt = lambda h: [np.cumsum(np.r_[0, x]) for x in h] X, Y = ndgrid(gridIt([a, b]), vector=False) self.TM2 = TensorMesh([a, b]) self.Curv2 = CurvilinearMesh([X, Y]) X, Y, Z = ndgrid(gridIt([a, b, c]), vector=False) self.TM3 = TensorMesh([a, b, c]) self.Curv3 = CurvilinearMesh([X, Y, Z])
def _plotCylTensorMesh(self, plotType, *args, **kwargs): if not self.isSymmetric: raise Exception('We have not yet implemented this type of view.') assert plotType in ['plotImage', 'plotGrid'] # Hackity Hack: # Just create a TM and use its view. from SimPEG.Mesh import TensorMesh M = TensorMesh([self.hx, self.hz], x0=[self.x0[0], self.x0[2]]) ax = kwargs.get('ax', None) if ax is None: fig = plt.figure() ax = plt.subplot(111) kwargs['ax'] = ax else: assert isinstance( ax, matplotlib.axes.Axes), "ax must be an matplotlib.axes.Axes" fig = ax.figure # Don't show things in the TM.plotImage showIt = kwargs.get('showIt', False) kwargs['showIt'] = False out = getattr(M, plotType)(*args, **kwargs) ax.set_xlabel('x') ax.set_ylabel('z') if showIt: plt.show() return out
def test_UBCfiles(self): mesh = self.mesh # Make a vector vec = np.arange(mesh.nC) # Write and read mesh.writeUBC('temp.msh', {'arange.txt': vec}) meshUBC = TensorMesh.readUBC('temp.msh') vecUBC = meshUBC.readModelUBC('arange.txt') # The mesh assert mesh.__str__() == meshUBC.__str__() assert np.sum(mesh.gridCC - meshUBC.gridCC) == 0 assert np.sum(vec - vecUBC) == 0 assert np.all(np.array(mesh.h) - np.array(meshUBC.h) == 0) vecUBC = mesh.readModelUBC('arange.txt') assert np.sum(vec - vecUBC) == 0 mesh.writeModelUBC('arange2.txt', vec + 1) vec2UBC = mesh.readModelUBC('arange2.txt') assert np.sum(vec + 1 - vec2UBC) == 0 print 'IO of UBC tensor mesh files is working' os.remove('temp.msh') os.remove('arange.txt') os.remove('arange2.txt')
def test_UBCfiles(self): mesh = self.mesh # Make a vector vec = np.arange(mesh.nC) # Write and read mesh.writeUBC('temp.msh', {'arange.txt':vec}) meshUBC = TensorMesh.readUBC('temp.msh') vecUBC = meshUBC.readModelUBC('arange.txt') # The mesh assert mesh.__str__() == meshUBC.__str__() assert np.sum(mesh.gridCC - meshUBC.gridCC) == 0 assert np.sum(vec - vecUBC) == 0 assert np.all(np.array(mesh.h) - np.array(meshUBC.h) == 0) vecUBC = mesh.readModelUBC('arange.txt') assert np.sum(vec - vecUBC) == 0 mesh.writeModelUBC('arange2.txt', vec + 1) vec2UBC = mesh.readModelUBC('arange2.txt') assert np.sum(vec + 1 - vec2UBC) == 0 print 'IO of UBC tensor mesh files is working' os.remove('temp.msh') os.remove('arange.txt') os.remove('arange2.txt')
def test_VTKfiles(self): mesh = self.mesh vec = np.arange(mesh.nC) mesh.writeVTK('temp.vtr', {'arange.txt': vec}) meshVTR, models = TensorMesh.readVTK('temp.vtr') assert mesh.__str__() == meshVTR.__str__() assert np.all(np.array(mesh.h) - np.array(meshVTR.h) == 0) assert 'arange.txt' in models vecVTK = models['arange.txt'] assert np.sum(vec - vecVTK) == 0 print 'IO of VTR tensor mesh files is working' os.remove('temp.vtr')
def test_VTKfiles(self): mesh = self.mesh vec = np.arange(mesh.nC) mesh.writeVTK('temp.vtr', {'arange.txt':vec}) meshVTR, models = TensorMesh.readVTK('temp.vtr') assert mesh.__str__() == meshVTR.__str__() assert np.all(np.array(mesh.h) - np.array(meshVTR.h) == 0) assert 'arange.txt' in models vecVTK = models['arange.txt'] assert np.sum(vec - vecVTK) == 0 print 'IO of VTR tensor mesh files is working' os.remove('temp.vtr')
def _plotCylTensorMesh(self, plotType, *args, **kwargs): if not self.isSymmetric: raise Exception('We have not yet implemented this type of view.') assert plotType in ['plotImage', 'plotGrid'] # Hackity Hack: # Just create a TM and use its view. from SimPEG.Mesh import TensorMesh vType = kwargs.pop('vType', None) if vType is not None: if vType.upper() != 'CCV': if vType.upper() == 'F': val = mkvc(self.aveF2CCV * args[0]) kwargs['vType'] = 'CCv' # now the vector is cell centered if vType.upper() == 'E': val = mkvc(self.aveE2CCV * args[0]) args = (val,) + args[1:] mirror = kwargs.pop('mirror', None) if mirror is True: # create a mirrored mesh hx = np.hstack([np.flipud(self.hx), self.hx]) x00 = self.x0[0] - self.hx.sum() M = TensorMesh([hx, self.hz], x0=[x00, self.x0[2]]) # mirror the data if len(args) > 0: val = args[0] if len(val) == self.nC: # only a single value at cell centers val = val.reshape(self.vnC[0], self.vnC[2], order='F') val = mkvc(np.vstack([np.flipud(val), val])) elif len(val) == 2*self.nC: val_x = val[:self.nC] val_z = val[self.nC:] val_x = val_x.reshape(self.vnC[0], self.vnC[2], order='F') val_x = mkvc(np.vstack([-1.*np.flipud(val_x), val_x])) # by symmetry val_z = val_z.reshape(self.vnC[0], self.vnC[2], order='F') val_z = mkvc(np.vstack([np.flipud(val_z), val_z])) val = np.hstack([val_x, val_z]) args = (val,) + args[1:] else: M = TensorMesh([self.hx, self.hz], x0=[self.x0[0], self.x0[2]]) ax = kwargs.get('ax', None) if ax is None: fig = plt.figure() ax = plt.subplot(111) kwargs['ax'] = ax else: assert isinstance(ax, matplotlib.axes.Axes), "ax must be an matplotlib.axes.Axes" fig = ax.figure # Don't show things in the TM.plotImage showIt = kwargs.get('showIt', False) kwargs['showIt'] = False out = getattr(M, plotType)(*args, **kwargs) ax.set_xlabel('x') ax.set_ylabel('z') if showIt: plt.show() return out
def test_tensor(self): M = TensorMesh([[(10., 2)]]) self.assertLess(np.abs(M.hx - np.r_[10., 10.]).sum(), TOL)
def test_cent_neg(self): M3d = TensorMesh([10, 10, 10], 'C0N') self.assertLess(np.abs(M3d.x0 + np.r_[0.5, 0, 1.0]).sum(), TOL)
def setupMesh(self, nc): """ For a given number of cells nc, generate a TensorMesh with uniform cells with edge length h=1/nc. """ if 'TensorMesh' in self._meshType: if 'uniform' in self._meshType: h = [nc, nc, nc] elif 'random' in self._meshType: h1 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h2 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h3 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h = [hi / np.sum(hi) for hi in [h1, h2, h3]] # normalize else: raise Exception('Unexpected meshType') self.M = TensorMesh(h[:self.meshDimension]) max_h = max([np.max(hi) for hi in self.M.h]) return max_h elif 'CylMesh' in self._meshType: if 'uniform' in self._meshType: h = [nc, nc, nc] else: raise Exception('Unexpected meshType') if self.meshDimension == 2: self.M = CylMesh([h[0], 1, h[2]]) max_h = max([np.max(hi) for hi in [self.M.hx, self.M.hz]]) elif self.meshDimension == 3: self.M = CylMesh(h) max_h = max([np.max(hi) for hi in self.M.h]) return max_h elif 'Curv' in self._meshType: if 'uniform' in self._meshType: kwrd = 'rect' elif 'rotate' in self._meshType: kwrd = 'rotate' else: raise Exception('Unexpected meshType') if self.meshDimension == 1: raise Exception('Lom not supported for 1D') elif self.meshDimension == 2: X, Y = Utils.exampleLrmGrid([nc, nc], kwrd) self.M = CurvilinearMesh([X, Y]) elif self.meshDimension == 3: X, Y, Z = Utils.exampleLrmGrid([nc, nc, nc], kwrd) self.M = CurvilinearMesh([X, Y, Z]) return 1. / nc elif 'Tree' in self._meshType: nc *= 2 if 'uniform' in self._meshType or 'notatree' in self._meshType: h = [nc, nc, nc] elif 'random' in self._meshType: h1 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h2 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h3 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h = [hi / np.sum(hi) for hi in [h1, h2, h3]] # normalize else: raise Exception('Unexpected meshType') levels = int(np.log(nc) / np.log(2)) self.M = Tree(h[:self.meshDimension], levels=levels) def function(cell): if 'notatree' in self._meshType: return levels - 1 r = cell.center - np.array([0.5] * len(cell.center)) dist = np.sqrt(r.dot(r)) if dist < 0.2: return levels return levels - 1 self.M.refine(function, balance=False) self.M.number(balance=False) # self.M.plotGrid(showIt=True) max_h = max([np.max(hi) for hi in self.M.h]) return max_h
X = np.empty_like(b) for i in range(b.shape[1]): X[:,i] = b[:,i]/diagA return X if __name__ == '__main__': from SimPEG.Mesh import TensorMesh from time import time h1 = np.ones(20)*100. h2 = np.ones(20)*100. h3 = np.ones(20)*100. h = [h1,h2,h3] M = TensorMesh(h) D = M.faceDiv G = M.cellGrad Msig = M.getFaceInnerProduct() A = D*Msig*G A[0,0] *= 10 # remove the constant null space from the matrix e = np.ones(M.nC) rhs = A.dot(e) tic = time() solve = Solver(A, options={'factorize':True}) x = solve.solve(rhs) print 'Factorized', time() - tic print np.linalg.norm(e-x,np.inf)
def test_printing(self): print(TensorMesh([10])) print(TensorMesh([10, 10])) print(TensorMesh([10, 10, 10]))
def test_oneCell(self): hx = np.array([1e-5]) M = TensorMesh([hx]) self.assertTrue(M.nC == 1)
def setUp(self): a = np.array([1, 1, 1]) b = np.array([1, 2]) c = np.array([1, 4]) self.mesh2 = TensorMesh([a, b], [3, 5]) self.mesh3 = TensorMesh([a, b, c])
h1[0] = 0.5 h1[-1] = 0.6 h2 = .5 * np.ones(4) h3 = .4 * np.ones(6) x0 = np.zeros(3) if testDim == 1: h = [h1] x0 = x0[0] elif testDim == 2: h = [h1, h2] x0 = x0[0:2] else: h = [h1, h2, h3] M = TensorMesh(h, x0) ccMesh = M.gridCC # ------------------- Test conductivities! -------------------------- print('Testing 1 block conductivity') p0 = np.array([0.5, 0.5, 0.5])[:testDim] p1 = np.array([1.0, 1.0, 1.0])[:testDim] vals = np.array([100, 1e-6]) sigma = defineBlockConductivity(ccMesh, p0, p1, vals) # Plot sigma model print(sigma.shape) M.plotImage(sigma)
def setUp(self): h = np.ones(16) mesh = TensorMesh([h, 2 * h, 3 * h]) self.mesh = mesh
X = np.empty_like(b) for i in range(b.shape[1]): X[:, i] = b[:, i] / diagA return X if __name__ == '__main__': from SimPEG.Mesh import TensorMesh from time import time h1 = np.ones(20) * 100. h2 = np.ones(20) * 100. h3 = np.ones(20) * 100. h = [h1, h2, h3] M = TensorMesh(h) D = M.faceDiv G = M.cellGrad Msig = M.getFaceInnerProduct() A = D * Msig * G A[0, 0] *= 10 # remove the constant null space from the matrix e = np.ones(M.nC) rhs = A.dot(e) tic = time() solve = Solver(A, options={'factorize': True}) x = solve.solve(rhs) print 'Factorized', time() - tic print np.linalg.norm(e - x, np.inf)
h1[0] = 0.5 h1[-1] = 0.6 h2 = .5 * np.ones(4) h3 = .4 * np.ones(6) x0 = np.zeros(3) if testDim == 1: h = [h1] x0 = x0[0] elif testDim == 2: h = [h1, h2] x0 = x0[0:2] else: h = [h1, h2, h3] M = TensorMesh(h, x0) ccMesh = M.gridCC # ------------------- Test conductivities! -------------------------- print('Testing 1 block conductivity') p0 = np.array([0.5,0.5,0.5])[:testDim] p1 = np.array([1.0,1.0,1.0])[:testDim] vals = np.array([100,1e-6]) sigma = defineBlockConductivity(ccMesh,p0,p1,vals) # Plot sigma model print sigma.shape M.plotImage(sigma)