def test_tree_to_tree_same_base(self): h1 = np.random.rand(16) h1 /= h1.sum() h1s = [h1] insert_1 = [0.25] insert_2 = [0.75] for i in range(1, 3): print(f"Tree to Tree {i+1}D: same base", end="") h1s.append(h1) insert_1.append(0.25) insert_2.append(0.75) mesh1 = discretize.TreeMesh(h1s) mesh1.insert_cells([insert_1], [4]) mesh2 = discretize.TreeMesh(h1s) mesh2.insert_cells([insert_2], [4]) in_put = np.random.rand(mesh1.nC) out_put = np.empty(mesh2.nC) # test the three ways of calling... out1 = volume_average(mesh1, mesh2, in_put, out_put) assert_array_equal(out1, out_put) out2 = volume_average(mesh1, mesh2, in_put) assert_allclose(out1, out2) Av = volume_average(mesh1, mesh2) out3 = Av @ in_put assert_allclose(out1, out3) vol1 = np.sum(mesh1.vol * in_put) vol2 = np.sum(mesh2.vol * out3) print(vol1, vol2) self.assertAlmostEqual(vol1, vol2)
def test_refine_func(self): mesh1 = discretize.TreeMesh((16, 16, 16)) mesh2 = discretize.TreeMesh((16, 16, 16)) mesh1.refine(-1) mesh2.refine(mesh2.max_level) self.assertEqual(mesh1.nC, mesh2.nC)
def test_insert_point(self): mesh1 = discretize.TreeMesh((16, 16, 16)) mesh2 = discretize.TreeMesh((16, 16, 16)) mesh1.insert_cells([[8, 8, 8]], [-1]) mesh2.insert_cells([[8, 8, 8]], [mesh2.max_level]) self.assertEqual(mesh1.nC, mesh2.nC)
def test_refine_ball(self): mesh1 = discretize.TreeMesh((16, 16, 16)) mesh2 = discretize.TreeMesh((16, 16, 16)) centers = [[8, 8, 8]] r_s = [3] mesh1.refine_ball(centers, r_s, [-1]) mesh2.refine_ball(centers, r_s, [mesh2.max_level]) self.assertEqual(mesh1.nC, mesh2.nC)
def test_refine_box(self): mesh1 = discretize.TreeMesh((16, 16, 16)) mesh2 = discretize.TreeMesh((16, 16, 16)) x0s = [[4, 4, 4]] x1s = [[8, 8, 8]] mesh1.refine_box(x0s, x1s, [-1]) mesh2.refine_box(x0s, x1s, [mesh2.max_level]) self.assertEqual(mesh1.nC, mesh2.nC)
def test_errors(self): h1 = np.random.rand(16) h1 /= h1.sum() h2 = np.random.rand(16) h2 /= h2.sum() mesh1D = discretize.TensorMesh([h1]) mesh2D = discretize.TensorMesh([h1, h1]) mesh3D = discretize.TensorMesh([h1, h1, h1]) hr = np.r_[1, 1, 0.5] hz = np.r_[2, 1] meshCyl = discretize.CylMesh([hr, 1, hz], np.r_[0.0, 0.0, 0.0]) mesh2 = discretize.TreeMesh([h2, h2]) mesh2.insert_cells([0.75, 0.75], [4]) with self.assertRaises(TypeError): # Gives a wrong typed object to the function volume_average(mesh1D, h1) with self.assertRaises(NotImplementedError): # Gives a wrong typed mesh volume_average(meshCyl, mesh2) with self.assertRaises(ValueError): # Gives mismatching mesh dimensions volume_average(mesh2D, mesh3D) model1 = np.random.randn(mesh2D.nC) bad_model1 = np.random.randn(3) bad_model2 = np.random.rand(1) # gives input values with incorrect lengths with self.assertRaises(ValueError): volume_average(mesh2D, mesh2, bad_model1) with self.assertRaises(ValueError): volume_average(mesh2D, mesh2, model1, bad_model2)
def doTestFace(self, h, rep, fast, meshType, invProp=False, invMat=False): if meshType == "Curv": hRect = discretize.utils.exampleLrmGrid(h, "rotate") mesh = discretize.CurvilinearMesh(hRect) elif meshType == "Tree": mesh = discretize.TreeMesh(h, levels=3) mesh.refine(lambda xc: 3) mesh.number(balance=False) elif meshType == "Tensor": mesh = discretize.TensorMesh(h) v = np.random.rand(mesh.nF) sig = np.random.rand(1) if rep is 0 else np.random.rand(mesh.nC * rep) def fun(sig): M = mesh.getFaceInnerProduct(sig, invProp=invProp, invMat=invMat) Md = mesh.getFaceInnerProductDeriv(sig, invProp=invProp, invMat=invMat, doFast=fast) return M * v, Md(v) print( meshType, "Face", h, rep, fast, ("harmonic" if invProp and invMat else "standard"), ) return discretize.tests.checkDerivative(fun, sig, num=5, plotIt=False)
def setUp(self): h = np.ones(16) mesh = discretize.TreeMesh([h, 2 * h, 3 * h]) cell_points = np.array([[0.5, 0.5, 0.5], [0.5, 2.5, 0.5]]) cell_levels = np.array([4, 4]) mesh.insert_cells(cell_points, cell_levels) self.mesh = mesh
def run(plotIt=True, n=60): M = discretize.TreeMesh([[(1, 16)], [(1, 16)]], levels=4) M.insert_cells(np.array([5.0, 5.0]), np.array([3])) M.number() if plotIt: fig, axes = plt.subplots(2, 1, figsize=(10, 10)) M.plotGrid(centers=True, nodes=False, ax=axes[0]) axes[0].axis("off") axes[0].set_title("Simple QuadTree Mesh") axes[0].set_xlim([-1, 17]) axes[0].set_ylim([-1, 17]) for ii, loc in zip(range(M.nC), M.gridCC): axes[0].text(loc[0] + 0.2, loc[1], "{0:d}".format(ii), color="r") axes[0].plot(M.gridFx[:, 0], M.gridFx[:, 1], "g>") for ii, loc in zip(range(M.nFx), M.gridFx): axes[0].text(loc[0] + 0.2, loc[1], "{0:d}".format(ii), color="g") axes[0].plot(M.gridFy[:, 0], M.gridFy[:, 1], "m^") for ii, loc in zip(range(M.nFy), M.gridFy): axes[0].text(loc[0] + 0.2, loc[1] + 0.2, "{0:d}".format((ii + M.nFx)), color="m") axes[1].spy(M.faceDiv) axes[1].set_title("Face Divergence") axes[1].set_ylabel("Cell Number") axes[1].set_xlabel("Face Number")
def test_h_gridded_3D(self): hx, hy, hz = np.ones(4), np.r_[1.0, 2.0, 3.0, 4.0], 2 * np.ones(4) M = discretize.TreeMesh([hx, hy, hz]) def refinefcn(cell): xyz = cell.center d = (xyz**2).sum()**0.5 if d < 3: return 2 return 1 M.refine(refinefcn) H = M.h_gridded test_hx = np.all(H[:, 0] == np.r_[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, ]) test_hy = np.all(H[:, 1] == np.r_[1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 2.0, 2.0, 3.0, 7.0, 7.0, 3.0, 3.0, 7.0, 7.0, ]) test_hz = np.all(H[:, 2] == np.r_[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, ]) self.assertTrue(test_hx and test_hy and test_hz)
def setUp(self): def topo(x): return np.sin(x * (2. * np.pi)) * 0.3 + 0.5 def function(cell): r = cell.center - np.array([0.5] * len(cell.center)) dist1 = np.sqrt(r.dot(r)) - 0.08 dist2 = np.abs(cell.center[-1] - topo(cell.center[0])) dist = min([dist1, dist2]) # if dist < 0.05: # return 5 if dist < 0.05: return 6 if dist < 0.2: return 5 if dist < 0.3: return 4 if dist < 1.0: return 3 else: return 0 M = discretize.TreeMesh([64, 64], levels=6) M.refine(function) self.M = M
def test_faceDiv(self): hx, hy = np.r_[1., 2, 3, 4], np.r_[5., 6, 7, 8] T = discretize.TreeMesh([hx, hy], levels=2) T.refine(lambda xc: 2) # T.plotGrid(showIt=True) M = discretize.TensorMesh([hx, hy]) self.assertEqual(M.nC, T.nC) self.assertEqual(M.nF, T.nF) self.assertEqual(M.nFx, T.nFx) self.assertEqual(M.nFy, T.nFy) self.assertEqual(M.nE, T.nE) self.assertEqual(M.nEx, T.nEx) self.assertEqual(M.nEy, T.nEy) self.assertTrue(np.allclose(M.area, T.permuteF * T.area)) self.assertTrue(np.allclose(M.edge, T.permuteE * T.edge)) self.assertTrue(np.allclose(M.vol, T.permuteCC * T.vol)) # plt.subplot(211).spy(M.faceDiv) # plt.subplot(212).spy(T.permuteCC*T.faceDiv*T.permuteF.T) # plt.show() self.assertEqual( (M.faceDiv - T.permuteCC * T.faceDiv * T.permuteF.T).nnz, 0)
def run(plotIt=True, n=60): M = discretize.TreeMesh([[(1, 16)], [(1, 16)]], levels=4) M.insert_cells(np.array([5., 5.]), np.array([3])) M.number() if plotIt: fig, axes = plt.subplots(2, 1, figsize=(10, 10)) M.plotGrid(centers=True, nodes=False, ax=axes[0]) axes[0].axis('off') axes[0].set_title('Simple QuadTree Mesh') axes[0].set_xlim([-1, 17]) axes[0].set_ylim([-1, 17]) for ii, loc in zip(range(M.nC), M.gridCC): axes[0].text(loc[0]+0.2, loc[1], '{0:d}'.format(ii), color='r') axes[0].plot(M.gridFx[:, 0], M.gridFx[:, 1], 'g>') for ii, loc in zip(range(M.nFx), M.gridFx): axes[0].text(loc[0]+0.2, loc[1], '{0:d}'.format(ii), color='g') axes[0].plot(M.gridFy[:, 0], M.gridFy[:, 1], 'm^') for ii, loc in zip(range(M.nFy), M.gridFy): axes[0].text( loc[0]+0.2, loc[1]+0.2, '{0:d}'.format( (ii+M.nFx) ), color='m' ) axes[1].spy(M.faceDiv) axes[1].set_title('Face Divergence') axes[1].set_ylabel('Cell Number') axes[1].set_xlabel('Face Number')
def test_VectorIdenties(self): hx, hy, hz = [[(1, 4)], [(1, 4)], [(1, 4)]] M = discretize.TreeMesh([hx, hy, hz], levels=2) Mr = discretize.TensorMesh([hx, hy, hz]) M.refine(2) #Why wasn't this here before? self.assertTrue(np.allclose((M.faceDiv * M.edgeCurl).data, 0)) hx, hy, hz = np.r_[1., 2, 3, 4], np.r_[5., 6, 7, 8], np.r_[9., 10, 11, 12] M = discretize.TreeMesh([hx, hy, hz], levels=2) Mr = discretize.TensorMesh([hx, hy, hz]) M.refine(2) A1 = M.faceDiv * M.edgeCurl A2 = Mr.faceDiv * Mr.edgeCurl self.assertTrue(len(A1.data) == 0 or np.allclose(A1.data, 0)) self.assertTrue(len(A2.data) == 0 or np.allclose(A2.data, 0))
def test_tree_to_tree_sub(self): h1 = np.ones(32) h2 = np.ones(16) h1s = [h1] h2s = [h2] insert_1 = [12] insert_2 = [4] for i in range(1, 3): print(f"Tree to smaller Tree {i+1}D: ", end="") h1s.append(h1) h2s.append(h2) insert_1.append(12) insert_2.append(4) mesh1 = discretize.TreeMesh(h1s) mesh1.insert_cells([insert_1], [4]) mesh2 = discretize.TreeMesh(h2s) mesh2.insert_cells([insert_2], [4]) in_put = np.random.rand(mesh1.nC) out_put = np.empty(mesh2.nC) # test the three ways of calling... out1 = volume_average(mesh1, mesh2, in_put, out_put) assert_array_equal(out1, out_put) out2 = volume_average(mesh1, mesh2, in_put) assert_allclose(out1, out2) Av = volume_average(mesh1, mesh2) out3 = Av @ in_put assert_allclose(out1, out3) # get cells in extent of smaller mesh cells = mesh1.gridCC < [16] * (i + 1) if i > 0: cells = np.all(cells, axis=1) vol1 = np.sum(mesh1.vol[cells] * in_put[cells]) vol2 = np.sum(mesh2.vol * out3) print(vol1, vol2) self.assertAlmostEqual(vol1, vol2)
def test_edgeCurl(self): hx, hy, hz = np.r_[1., 2, 3, 4], np.r_[5., 6, 7, 8], np.r_[9., 10, 11, 12] M = discretize.TreeMesh([hx, hy, hz], levels=2) M.refine(lambda xc: 2) Mr = discretize.TensorMesh([hx, hy, hz]) A = Mr.edgeCurl - M.permuteF * M.edgeCurl * M.permuteE.T self.assertTrue(len(A.data) == 0 or np.allclose(A.data, 0))
def test_serialization(self): hx, hy = np.r_[1.0, 2, 3, 4], np.r_[5.0, 6, 7, 8] mesh1 = discretize.TreeMesh([hx, hy], levels=2, x0=np.r_[-1, -1]) mesh1.refine(2) mesh2 = discretize.TreeMesh.deserialize(mesh1.serialize()) self.assertTrue(np.all(mesh1.x0 == mesh2.x0)) self.assertTrue(np.all(mesh1.shape_cells == mesh2.shape_cells)) self.assertTrue(np.all(mesh1.gridCC == mesh2.gridCC)) mesh1.x0 = np.r_[-2.0, 2] mesh2 = discretize.TreeMesh.deserialize(mesh1.serialize()) self.assertTrue(np.all(mesh1.x0 == mesh2.x0))
def run(plotIt=True): M = discretize.TreeMesh([32, 32]) M.refine(3) def refine(cell): xyz = cell.center for i in range(3): if np.abs(np.sin(xyz[0] * np.pi * 2) * 0.5 + 0.5 - xyz[1]) < 0.2 * i: return 6 - i return 0 M.refine(refine) if plotIt: M.plotGrid()
def run(plotIt=True): M = discretize.TreeMesh([8, 8]) def refine(cell): xyz = cell.center dist = ((xyz - [0.25, 0.25])**2).sum()**0.5 if dist < 0.25: return 3 return 2 M.refine(refine) if plotIt: M.plotGrid(nodes=True, cells=True, facesX=True) plt.legend(('Grid', 'Cell Centers', 'Nodes', 'Hanging Nodes', 'X faces', 'Hanging X faces'))
def test_counts(self): nc = 8 h1 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h2 = np.random.rand(nc) * nc * 0.5 + nc * 0.5 h = [hi / np.sum(hi) for hi in [h1, h2]] # normalize M = discretize.TreeMesh(h) points = np.array([[0.1, 0.1, 0.3]]) level = np.array([3]) M.insert_cells(points, level) M.number() self.assertEqual(M.nhFx, 4) self.assertEqual(M.nFx, 12) self.assertTrue(np.allclose(M.vol.sum(), 1.0))
def setUp(self): def function(cell): r = cell.center - np.array([0.5] * len(cell.center)) dist = np.sqrt(r.dot(r)) if dist < 0.2: return 4 if dist < 0.3: return 3 if dist < 1.0: return 2 else: return 0 M = discretize.TreeMesh([16, 16, 16], levels=4) M.refine(function) # M.plotGrid(showIt=True) self.M = M
def test_counts(self): nc = 8 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 M = discretize.TreeMesh(h, levels=3) points = np.array([[0.2, 0.1, 0.7], [0.8, 0.4, 0.2]]) levels = np.array([1, 2]) M.insert_cells(points, levels) M.number() # M.plotGrid(showIt=True) self.assertEqual(M.nhFx, 4) self.assertTrue(M.nFx, 19) self.assertTrue(M.nC, 15) self.assertTrue(np.allclose(M.vol.sum(), 1.0))
def doTestEdge(h, rep, fast, meshType, invProp=False, invMat=False): if meshType == 'Curv': hRect = discretize.utils.exampleLrmGrid(h,'rotate') mesh = discretize.CurvilinearMesh(hRect) elif meshType == 'Tree': mesh = discretize.TreeMesh(h, levels=3) mesh.refine(lambda xc: 3) elif meshType == 'Tensor': mesh = discretize.TensorMesh(h) v = np.random.rand(mesh.nE) sig = np.random.rand(1) if rep is 0 else np.random.rand(mesh.nC*rep) def fun(sig): M = mesh.getEdgeInnerProduct(sig, invProp=invProp, invMat=invMat) Md = mesh.getEdgeInnerProductDeriv(sig, invProp=invProp, invMat=invMat, doFast=fast) return M*v, Md(v) print(meshType, 'Edge', h, rep, fast, ('harmonic' if invProp and invMat else 'standard')) return discretize.Tests.checkDerivative(fun, sig, num=5, plotIt=False)
def run(plotIt=True): M = discretize.TensorMesh([32, 32]) v = discretize.utils.random_model(M.vnC, seed=789) v = discretize.utils.mkvc(v) O = discretize.TreeMesh([32, 32]) def function(cell): if ( cell.center[0] < 0.75 and cell.center[0] > 0.25 and cell.center[1] < 0.75 and cell.center[1] > 0.25 ): return 5 if ( cell.center[0] < 0.9 and cell.center[0] > 0.1 and cell.center[1] < 0.9 and cell.center[1] > 0.1 ): return 4 return 3 O.refine(function) P = M.getInterpolationMat(O.gridCC, "CC") ov = P * v if not plotIt: return fig, axes = plt.subplots(1, 2, figsize=(10, 5)) out = M.plotImage(v, grid=True, ax=axes[0]) cb = plt.colorbar(out[0], ax=axes[0]) cb.set_label("Random Field") axes[0].set_title("TensorMesh") out = O.plotImage(ov, grid=True, ax=axes[1], clim=[0, 1]) cb = plt.colorbar(out[0], ax=axes[1]) cb.set_label("Random Field") axes[1].set_title("TreeMesh")
def test_h_gridded_2D(self): hx, hy = np.ones(4), np.r_[1., 2., 3., 4.] M = discretize.TreeMesh([hx, hy]) def refinefcn(cell): xyz = cell.center d = (xyz**2).sum()**0.5 if d < 3: return 2 return 1 M.refine(refinefcn) H = M.h_gridded test_hx = np.all(H[:, 0] == np.r_[1., 1., 1., 1., 2., 2., 2.]) test_hy = np.all(H[:, 1] == np.r_[1., 1., 2., 2., 3., 7., 7.]) self.assertTrue(test_hx and test_hy)
def test_faceInnerProduct(self): hx, hy, hz = np.r_[1., 2, 3, 4], np.r_[5., 6, 7, 8], np.r_[9., 10, 11, 12] # hx, hy, hz = [[(1, 4)], [(1, 4)], [(1, 4)]] M = discretize.TreeMesh([hx, hy, hz], levels=2) M.refine(lambda xc: 2) # M.plotGrid(showIt=True) Mr = discretize.TensorMesh([hx, hy, hz]) # print(M.nC, M.nF, M.getFaceInnerProduct().shape, M.permuteF.shape) A_face = Mr.getFaceInnerProduct( ) - M.permuteF * M.getFaceInnerProduct() * M.permuteF.T A_edge = Mr.getEdgeInnerProduct( ) - M.permuteE * M.getEdgeInnerProduct() * M.permuteE.T self.assertTrue(len(A_face.data) == 0 or np.allclose(A_face.data, 0)) self.assertTrue(len(A_edge.data) == 0 or np.allclose(A_edge.data, 0))
def test_pickle2D(self): mesh0 = discretize.TreeMesh([8, 8]) def refine(cell): xyz = cell.center dist = ((xyz - 0.25)**2).sum()**0.5 if dist < 0.25: return 3 return 2 mesh0.refine(refine) byte_string = pickle.dumps(mesh0) mesh1 = pickle.loads(byte_string) self.assertEqual(mesh0.nC, mesh1.nC) self.assertEqual(mesh0.__str__(), mesh1.__str__()) self.assertTrue(np.allclose(mesh0.gridCC, mesh1.gridCC)) self.assertTrue(np.allclose(np.array(mesh0.h), np.array(mesh1.h))) print("Pickling of 2D TreeMesh is working")
def test_dic_serialize3D(self): mesh0 = discretize.TreeMesh([8, 8, 8]) def refine(cell): xyz = cell.center dist = ((xyz - 0.25)**2).sum()**0.5 if dist < 0.25: return 3 return 2 mesh0.refine(refine) mesh_dict = mesh0.serialize() mesh1 = discretize.TreeMesh.deserialize(mesh_dict) self.assertEqual(mesh0.nC, mesh1.nC) self.assertEqual(mesh0.__str__(), mesh1.__str__()) self.assertTrue(np.allclose(mesh0.gridCC, mesh1.gridCC)) self.assertTrue(np.allclose(np.array(mesh0.h), np.array(mesh1.h))) print("dic serialize 3D is working")
def run(plotIt=True): M = discretize.TreeMesh([8, 8]) def refine(cell): xyz = cell.center dist = ((xyz - [0.25, 0.25])**2).sum()**0.5 if dist < 0.25: return 3 return 2 M.refine(refine) if plotIt: M.plotGrid(nodes=True, centers=True, faces_x=True) plt.legend(( "Nodes", "Hanging Nodes", "Cell Centers", "X faces", "Hanging X faces", "Grid", ))
def test_faceDiv(self): hx, hy, hz = np.r_[1., 2, 3, 4], np.r_[5., 6, 7, 8], np.r_[9., 10, 11, 12] M = discretize.TreeMesh([hx, hy, hz], levels=2) M.refine(lambda xc: 2) # M.plotGrid(showIt=True) Mr = discretize.TensorMesh([hx, hy, hz]) self.assertEqual(M.nC, Mr.nC) self.assertEqual(M.nF, Mr.nF) self.assertEqual(M.nFx, Mr.nFx) self.assertEqual(M.nFy, Mr.nFy) self.assertEqual(M.nE, Mr.nE) self.assertEqual(M.nEx, Mr.nEx) self.assertEqual(M.nEy, Mr.nEy) self.assertTrue(np.allclose(Mr.area, M.permuteF * M.area)) self.assertTrue(np.allclose(Mr.edge, M.permuteE * M.edge)) self.assertTrue(np.allclose(Mr.vol, M.permuteCC * M.vol)) A = Mr.faceDiv - M.permuteCC * M.faceDiv * M.permuteF.T self.assertTrue(np.allclose(A.data, 0))