def extractFields(self, bvec): nD = int(bvec.shape[0] / 3) bvec = np.reshape(bvec, (3, nD)) R = MagUtils.rotationMatrix(self.prism.pinc, self.prism.pdec) bvec = R.dot(bvec) if self.uType == "bx": u = utils.mkvc(bvec[0, :]) if self.uType == "by": u = utils.mkvc(bvec[1, :]) if self.uType == "bz": u = utils.mkvc(bvec[2, :]) if self.uType == "tf": # Projection matrix Ptmi = MagUtils.dipazm_2_xyz( self.survey.source_field.parameters[1], self.survey.source_field.parameters[2]) u = utils.mkvc(Ptmi.dot(bvec)) return u
def test_regularizationMesh(self): for i, mesh in enumerate(self.meshlist): print("Testing {0:d}D".format(mesh.dim)) # mapping = r.mapPair(mesh) # reg = r(mesh, mapping=mapping) # m = np.random.rand(mapping.nP) if mesh.dim == 1: indAct = utils.mkvc(mesh.gridCC <= 0.8) elif mesh.dim == 2: indAct = utils.mkvc( mesh.gridCC[:, -1] <= 2 * np.sin(2 * np.pi * mesh.gridCC[:, 0]) + 0.5) elif mesh.dim == 3: indAct = utils.mkvc( mesh.gridCC[:, -1] <= 2 * np.sin(2 * np.pi * mesh.gridCC[:, 0]) + 0.5 * 2 * np.sin(2 * np.pi * mesh.gridCC[:, 1]) + 0.5) regmesh = regularization.RegularizationMesh(mesh, indActive=indAct) assert (regmesh.vol == mesh.vol[indAct]).all()
def test_Simulation3DCellCentered_Neumann(self, tolerance=0.1): simulation = dc.Simulation3DCellCentered(self.mesh, survey=self.survey, sigma=self.sigma, bc_type="Neumann") simulation.solver = Solver f = simulation.fields(self.sigma) eNumeric = utils.mkvc(f[self.survey.source_list, "e"]) jNumeric = utils.mkvc(f[self.survey.source_list, "j"]) errE = np.linalg.norm(jNumeric[self.ROIfaceInds] - self.J_analytic[ self.ROIfaceInds]) / np.linalg.norm( self.J_analytic[self.ROIfaceInds]) errJ = np.linalg.norm(eNumeric[self.ROIfaceInds] - self.E_analytic[ self.ROIfaceInds]) / np.linalg.norm( self.E_analytic[self.ROIfaceInds]) if errE < tolerance and errJ < tolerance: print("\n") print("E field error =", errE) print("J field error =", errJ) passed = True print( ">> DC analytic test for Simulation3DCellCentered_Neumann passed" ) else: print("\n") print("E field error =", errE) print("J field error =", errJ) passed = False print( ">> DC analytic test for Simulation3DCellCentered_Neumann failed" ) self.assertTrue(passed)
def test_Simulation3DNodal(self, tolerance=0.1): simulation = dc.simulation.Simulation3DNodal(self.mesh, survey=self.survey, sigma=self.sigma) simulation.solver = Solver f = simulation.fields(self.sigma) eNumeric = utils.mkvc(f[self.survey.source_list, "e"]) jNumeric = utils.mkvc(f[self.survey.source_list, "j"]) # also test if we can get charge and charge_density f[:, "charge"] f[:, "charge_density"] errE = np.linalg.norm(jNumeric[self.ROIedgeInds] - self.J_analytic[ self.ROIedgeInds]) / np.linalg.norm( self.J_analytic[self.ROIedgeInds]) errJ = np.linalg.norm(eNumeric[self.ROIedgeInds] - self.E_analytic[ self.ROIedgeInds]) / np.linalg.norm( self.E_analytic[self.ROIedgeInds]) if errE < tolerance and errJ < tolerance: print("\n") print("E field error =", errE) print("J field error =", errJ) passed = True print(">> DC analytic test for Simulation3DNodal passed") else: print("\n") print("E field error =", errE) print("J field error =", errJ) passed = False print(">> DC analytic test for Simulation3DNodal failed") self.assertTrue(passed)
def sumCylinderCharges(xc, zc, r, qSecondary): chargeRegionVerts = getCylinderPoints(xc, zc, r + 0.5) codes = chargeRegionVerts.shape[0] * [Path.LINETO] codes[0] = Path.MOVETO codes[-1] = Path.CLOSEPOLY chargeRegionPath = Path(chargeRegionVerts, codes) CCLocs = mesh.gridCC chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs)) plateChargeLocs = CCLocs[chargeRegionInsideInd] plateCharge = qSecondary[chargeRegionInsideInd] posInd = np.where(plateCharge >= 0) negInd = np.where(plateCharge < 0) qPos = utils.mkvc(plateCharge[posInd]) qNeg = utils.mkvc(plateCharge[negInd]) qPosLoc = plateChargeLocs[posInd, :][0] qNegLoc = plateChargeLocs[negInd, :][0] # qPosData = np.vstack([qPosLoc[:, 0], qPosLoc[:, 1], qPos]).T # qNegData = np.vstack([qNegLoc[:, 0], qNegLoc[:, 1], qNeg]).T if qNeg.shape == (0, ) or qPos.shape == (0, ): qNegAvgLoc = np.r_[-10, -10] qPosAvgLoc = np.r_[+10, -10] else: qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg) qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos) qPosSum = np.sum(qPos) qNegSum = np.sum(qNeg) return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc
def sum_term(rho1, rho2, h, r): m = utils.mkvc(np.arange(1, infinity + 1)) k = (rho2 - rho1) / (rho2 + rho1) return np.sum( ((k ** m.T) * np.ones_like(utils.mkvc(r, 2))) / np.sqrt(1.0 + (2.0 * h * m.T / utils.mkvc(r, 2)) ** 2), 1, )
def MagSphereAnaFunA(x, y, z, R, xc, yc, zc, chi, Bo, flag): """Computing boundary condition using Congrous sphere method. This is designed for secondary field formulation. >> Input mesh: Mesh class Bo: np.array([Box, Boy, Boz]): Primary magnetic flux Chi: susceptibility at cell volume .. math:: \\vec{B}(r) = \\frac{\mu_0}{4\pi}\\frac{m}{\| \\vec{r}-\\vec{r}_0\|^3}[3\hat{m}\cdot\hat{r}-\hat{m}] """ if ~np.size(x) == np.size(y) == np.size(z): print("Specify same size of x, y, z") return dim = x.shape x = utils.mkvc(x) y = utils.mkvc(y) z = utils.mkvc(z) Bot = np.sqrt(sum(Bo ** 2)) mx = Bo[0] / Bot my = Bo[1] / Bot mz = Bo[2] / Bot ind = np.sqrt((x - xc) ** 2 + (y - yc) ** 2 + (z - zc) ** 2) < R Bx = np.zeros(x.size) By = np.zeros(x.size) Bz = np.zeros(x.size) # Inside of the sphere rf2 = 3 / (chi + 3) * (1 + chi) if flag == "total": Bx[ind] = Bo[0] * (rf2) By[ind] = Bo[1] * (rf2) Bz[ind] = Bo[2] * (rf2) elif flag == "secondary": Bx[ind] = Bo[0] * (rf2) - Bo[0] By[ind] = Bo[1] * (rf2) - Bo[1] Bz[ind] = Bo[2] * (rf2) - Bo[2] r = utils.mkvc(np.sqrt((x - xc) ** 2 + (y - yc) ** 2 + (z - zc) ** 2)) V = 4 * np.pi * R ** 3 / 3 mom = Bot / mu_0 * chi / (1 + chi / 3) * V const = mu_0 / (4 * np.pi) * mom mdotr = ( mx * (x[~ind] - xc) / r[~ind] + my * (y[~ind] - yc) / r[~ind] + mz * (z[~ind] - zc) / r[~ind] ) Bx[~ind] = const / (r[~ind] ** 3) * (3 * mdotr * (x[~ind] - xc) / r[~ind] - mx) By[~ind] = const / (r[~ind] ** 3) * (3 * mdotr * (y[~ind] - yc) / r[~ind] - my) Bz[~ind] = const / (r[~ind] ** 3) * (3 * mdotr * (z[~ind] - zc) / r[~ind] - mz) return Bx, By, Bz
def sum_term_deriv(rho1, rho2, h, r): m = utils.mkvc(np.arange(1, infinity + 1)) k = (rho2 - rho1) / (rho2 + rho1) return np.sum( ((k ** m.T) * np.ones_like(utils.mkvc(r, 2))) / (1.0 + (2.0 * h * m.T / utils.mkvc(r, 2)) ** 2) ** (3.0 / 2.0) * ((2.0 * h * m.T) ** 2 / utils.mkvc(r, 2) ** 3), 1, )
def test_SetGet(self): F = self.F nSrc = F.survey.nSrc nT = F.simulation.nT + 1 e = np.random.rand(F.mesh.nE, nSrc, nT) F[:, "e"] = e b = np.random.rand(F.mesh.nF, nSrc, nT) F[:, "b"] = b self.assertTrue(np.all(F[:, "e"] == e)) self.assertTrue(np.all(F[:, "b"] == b)) F[:] = {"b": b, "e": e} self.assertTrue(np.all(F[:, "e"] == e)) self.assertTrue(np.all(F[:, "b"] == b)) for s in zero_types: F[:, "b"] = s self.assertTrue(np.all(F[:, "b"] == b * 0)) b = np.random.rand(F.mesh.nF, 1, nT) F[self.Src0, "b"] = b self.assertTrue(np.all(F[self.Src0, "b"] == b[:, 0, :])) b = np.random.rand(F.mesh.nF, 1, nT) F[self.Src0, "b", 0] = b[:, :, 0] self.assertTrue( np.all(F[self.Src0, "b", 0] == utils.mkvc(b[:, 0, 0], 2))) phi = np.random.rand(F.mesh.nC, 2, nT) F[[self.Src0, self.Src1], "phi"] = phi self.assertTrue(np.all(F[[self.Src0, self.Src1], "phi"] == phi)) fdict = F[:] self.assertTrue(type(fdict) is dict) self.assertTrue(sorted([k for k in fdict]) == ["b", "e", "phi"]) b = np.random.rand(F.mesh.nF, 2, nT) F[[self.Src0, self.Src1], "b"] = b self.assertTrue(F[self.Src0]["b"].shape == (F.mesh.nF, nT)) self.assertTrue(F[self.Src0, "b"].shape == (F.mesh.nF, nT)) self.assertTrue(np.all(F[self.Src0, "b"] == b[:, 0, :])) self.assertTrue(np.all(F[self.Src1, "b"] == b[:, 1, :])) self.assertTrue( np.all(F[self.Src0, "b", 1] == utils.mkvc(b[:, 0, 1], 2))) self.assertTrue( np.all(F[self.Src1, "b", 1] == utils.mkvc(b[:, 1, 1], 2))) self.assertTrue( np.all(F[self.Src0, "b", 4] == utils.mkvc(b[:, 0, 4], 2))) self.assertTrue( np.all(F[self.Src1, "b", 4] == utils.mkvc(b[:, 1, 4], 2))) b = np.random.rand(F.mesh.nF, 2, nT) F[[self.Src0, self.Src1], "b", 0] = b[:, :, 0]
def refine_box(mesh): # Refine for sphere xp, yp, zp = np.meshgrid([-55.0, 50.0], [-50.0, 50.0], [-40.0, 20.0]) xyz = np.c_[mkvc(xp), mkvc(yp), mkvc(zp)] mesh = refine_tree_xyz(mesh, xyz, octree_levels=[2], method="box", finalize=False) return mesh
def test_regularization_ActiveCells(self): for R in dir(regularization): r = getattr(regularization, R) if not inspect.isclass(r): continue if not issubclass(r, objective_function.BaseObjectiveFunction): continue if r.__name__ in IGNORE_ME: continue for i, mesh in enumerate(self.meshlist[:1]): print("Testing Active Cells {0:d}D".format((mesh.dim))) if mesh.dim == 1: indActive = utils.mkvc(mesh.gridCC <= 0.8) elif mesh.dim == 2: indActive = utils.mkvc(mesh.gridCC[:, -1] <= ( 2 * np.sin(2 * np.pi * mesh.gridCC[:, 0]) + 0.5)) elif mesh.dim == 3: indActive = utils.mkvc(mesh.gridCC[:, -1] <= ( 2 * np.sin(2 * np.pi * mesh.gridCC[:, 0]) + 0.5 * 2 * np.sin(2 * np.pi * mesh.gridCC[:, 1]) + 0.5)) if mesh.dim < 3 and r.__name__[-1] == "z": continue if mesh.dim < 2 and r.__name__[-1] == "y": continue for indAct in [ indActive, indActive.nonzero()[0], ]: # test both bool and integers if indAct.dtype != bool: nP = indAct.size else: nP = int(indAct.sum()) reg = r(mesh, indActive=indAct, mapping=maps.IdentityMap(nP=nP)) m = np.random.rand(mesh.nC)[indAct] mref = np.ones_like(m) * np.mean(m) reg.mref = mref print("--- Checking {} ---\n".format( reg.__class__.__name__)) passed = reg.test(m, eps=TOL) self.assertTrue(passed)
def refine_topography(mesh): # Define topography and refine [xx, yy] = np.meshgrid(mesh.vectorNx, mesh.vectorNy) zz = -3 * np.exp((xx**2 + yy**2) / 60**2) + 45.0 topo = np.c_[mkvc(xx), mkvc(yy), mkvc(zz)] mesh = refine_tree_xyz(mesh, topo, octree_levels=[3, 2], method="surface", finalize=False) return mesh
def setUp(self): # Define inducing field and sphere parameters H0 = (50000.0, 60.0, 250.0) # H0 = (50000., 90., 0.) self.b0 = mag.analytics.IDTtoxyz(-H0[1], H0[2], H0[0]) self.rad = 2.0 self.chi = 0.01 # Define a mesh cs = 0.2 hxind = [(cs, 21)] hyind = [(cs, 21)] hzind = [(cs, 21)] mesh = discretize.TensorMesh([hxind, hyind, hzind], "CCC") # Get cells inside the sphere sph_ind = getIndicesSphere([0.0, 0.0, 0.0], self.rad, mesh.gridCC) # Adjust susceptibility for volume difference Vratio = (4.0 / 3.0 * np.pi * self.rad**3.0) / (np.sum(sph_ind) * cs**3.0) model = np.ones(mesh.nC) * self.chi * Vratio self.model = model[sph_ind] # Creat reduced identity map for Linear Pproblem idenMap = maps.IdentityMap(nP=int(sum(sph_ind))) # Create plane of observations xr = np.linspace(-20, 20, nx) yr = np.linspace(-20, 20, ny) self.xr = xr self.yr = yr X, Y = np.meshgrid(xr, yr) components = ["bx", "by", "bz", "tmi"] # Move obs plane 2 radius away from sphere Z = np.ones((xr.size, yr.size)) * 2.0 * self.rad self.locXyz = np.c_[utils.mkvc(X), utils.mkvc(Y), utils.mkvc(Z)] rxLoc = mag.Point(self.locXyz, components=components) srcField = mag.SourceField([rxLoc], parameters=H0) self.survey = mag.Survey(srcField) self.sim = mag.Simulation3DIntegral( mesh, survey=self.survey, chiMap=idenMap, actInd=sph_ind, store_sensitivities="forward_only", )
def test_rotationMatrixFromNormals(self): np.random.seed(0) v0 = np.random.rand(3) v0 *= 1.0 / np.linalg.norm(v0) np.random.seed(5) v1 = np.random.rand(3) v1 *= 1.0 / np.linalg.norm(v1) Rf = utils.coord_utils.rotationMatrixFromNormals(v0, v1) Ri = utils.coord_utils.rotationMatrixFromNormals(v1, v0) self.assertTrue(np.linalg.norm(utils.mkvc(Rf.dot(v0) - v1)) < tol) self.assertTrue(np.linalg.norm(utils.mkvc(Ri.dot(v1) - v0)) < tol)
def test_rotatePointsFromNormals(self): np.random.seed(10) v0 = np.random.rand(3) v0 *= 1.0 / np.linalg.norm(v0) np.random.seed(15) v1 = np.random.rand(3) v1 *= 1.0 / np.linalg.norm(v1) v2 = utils.mkvc( utils.coord_utils.rotatePointsFromNormals( utils.mkvc(v0, 2).T, v0, v1)) self.assertTrue(np.linalg.norm(v2 - v1) < tol)
def sumCylinderCharges(xc, zc, r, qSecondary): chargeRegionVerts = getCylinderPoints(xc, zc, r + 0.5) codes = chargeRegionVerts.shape[0] * [Path.LINETO] codes[0] = Path.MOVETO codes[-1] = Path.CLOSEPOLY chargeRegionPath = Path(chargeRegionVerts, codes) CCLocs = mesh.gridCC chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs)) plateChargeLocs = CCLocs[chargeRegionInsideInd] plateCharge = qSecondary[chargeRegionInsideInd] posInd = np.where(plateCharge >= 0) negInd = np.where(plateCharge < 0) qPos = utils.mkvc(plateCharge[posInd]) qNeg = utils.mkvc(plateCharge[negInd]) qPosLoc = plateChargeLocs[posInd, :][0] qNegLoc = plateChargeLocs[negInd, :][0] # qPosData = np.vstack([qPosLoc[:, 0], qPosLoc[:, 1], qPos]).T # qNegData = np.vstack([qNegLoc[:, 0], qNegLoc[:, 1], qNeg]).T if qNeg.shape == (0,) or qPos.shape == (0,): qNegAvgLoc = np.r_[-10, -10] qPosAvgLoc = np.r_[+10, -10] else: qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg) qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos) qPosSum = np.sum(qPos) qNegSum = np.sum(qNeg) # # Check things by plotting # fig = plt.figure() # ax = fig.add_subplot(111) # platePatch = patches.PathPatch(platePath, facecolor='none', lw=2) # ax.add_patch(platePatch) # chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2) # ax.add_patch(chargeRegionPatch) # plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b') # plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r') # ax.set_xlim(-15,5) # ax.set_ylim(-25,-5) # plt.axes().set_aspect('equal') # plt.show() return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc
def setUp(self): # Define sphere parameters self.rad = 2.0 self.rho = 0.1 # Define a mesh cs = 0.2 hxind = [(cs, 21)] hyind = [(cs, 21)] hzind = [(cs, 21)] mesh = discretize.TensorMesh([hxind, hyind, hzind], "CCC") # Get cells inside the sphere sph_ind = getIndicesSphere([0.0, 0.0, 0.0], self.rad, mesh.gridCC) # Adjust density for volume difference Vratio = (4.0 / 3.0 * np.pi * self.rad**3.0) / (np.sum(sph_ind) * cs**3.0) model = np.ones(mesh.nC) * self.rho * Vratio self.model = model[sph_ind] # Create reduced identity map for Linear Pproblem idenMap = maps.IdentityMap(nP=int(sum(sph_ind))) # Create plane of observations xr = np.linspace(-20, 20, nx) yr = np.linspace(-20, 20, ny) X, Y = np.meshgrid(xr, yr) self.xr = xr self.yr = yr components = ["gx", "gy", "gz"] # Move obs plane 2 radius away from sphere Z = np.ones((xr.size, yr.size)) * 2.0 * self.rad self.locXyz = np.c_[utils.mkvc(X), utils.mkvc(Y), utils.mkvc(Z)] receivers = gravity.Point(self.locXyz, components=components) sources = gravity.SourceField([receivers]) self.survey = gravity.Survey(sources) self.sim = gravity.Simulation3DIntegral( mesh, survey=self.survey, rhoMap=idenMap, actInd=sph_ind, store_sensitivities="disk", )
def setUp(self): np.random.seed(518936) # Create a cloud of random points from a random gaussian mixture self.ndim = 2 self.n_components = 2 sigma = np.random.randn(self.n_components, self.ndim, self.ndim) sigma = np.c_[[sigma[i].dot(sigma[i].T) for i in range(sigma.shape[0])]] sigma[0] += np.eye(self.ndim) sigma[1] += np.eye(self.ndim) - 0.25 * np.eye(self.ndim).transpose((1, 0)) self.sigma = sigma self.means = ( np.abs(np.random.randn(self.ndim, self.ndim)) * np.c_[[100.0, -100.0]] ) self.rv0 = multivariate_normal(self.means[0], self.sigma[0]) self.rv1 = multivariate_normal(self.means[1], self.sigma[1]) self.proportions = np.r_[0.6, 0.4] self.nsample = 1000 self.s0 = self.rv0.rvs(int(self.nsample * self.proportions[0])) self.s1 = self.rv1.rvs(int(self.nsample * self.proportions[1])) self.samples = np.r_[self.s0, self.s1] self.model = mkvc(self.samples) self.mesh = discretize.TensorMesh( [np.maximum(1e-1, np.random.randn(self.nsample) ** 2.0)] ) self.wires = Wires(("s0", self.mesh.nC), ("s1", self.mesh.nC)) self.PlotIt = False
def getJtJdiag(self, m, W=None): """ Return the diagonal of JtJ """ self.model = m if W is None: W = np.ones(self.survey.nD) else: W = W.diagonal() ** 2 if getattr(self, "_gtg_diagonal", None) is None: diag = np.zeros(self.G.shape[1]) if not self.is_amplitude_data: for i in range(len(W)): diag += W[i] * (self.G[i] * self.G[i]) else: fieldDeriv = self.fieldDeriv Gx = self.G[::3] Gy = self.G[1::3] Gz = self.G[2::3] for i in range(len(W)): row = ( fieldDeriv[0, i] * Gx[i] + fieldDeriv[1, i] * Gy[i] + fieldDeriv[2, i] * Gz[i] ) diag += W[i] * (row * row) self._gtg_diagonal = diag else: diag = self._gtg_diagonal return mkvc((sdiag(np.sqrt(diag)) @ self.chiDeriv).power(2).sum(axis=0))
def test_simpleAlias(self): F = self.F nSrc = F.survey.nSrc nT = F.simulation.nT + 1 b = np.random.rand(F.mesh.nF, nSrc, nT) F[:, "b", :] = b self.assertTrue(np.all(F[:, "e", 0] == F.mesh.edgeCurl.T * b[:, :, 0])) e = list(range(nT)) for i in range(nT): e[i] = F.mesh.edgeCurl.T * b[:, :, i] + i e[i] = e[i][:, :, np.newaxis] e = np.concatenate(e, axis=2) self.assertTrue(np.all(F[:, "e", :] == e)) self.assertTrue(np.all(F[self.Src0, "e", :] == e[:, 0, :])) self.assertTrue(np.all(F[self.Src1, "e", :] == e[:, 1, :])) for t in range(nT): self.assertTrue( np.all(F[self.Src1, "e", t] == utils.mkvc(e[:, 1, t], 2))) b = np.random.rand(F.mesh.nF, nT) F[self.Src0, "b", :] = b Cb = F.mesh.edgeCurl.T * b for i in range(Cb.shape[1]): Cb[:, i] += i self.assertTrue(np.all(F[self.Src0, "e", :] == Cb)) def f(): F[self.Src0, "e"] = F[self.Src0, "e"] self.assertRaises(KeyError, f) # can't set a alias attr.
def run(plotIt=True): M = discretize.TensorMesh([100, 100]) h1 = utils.meshTensor([(6, 7, -1.5), (6, 10), (6, 7, 1.5)]) h1 = h1 / h1.sum() M2 = discretize.TensorMesh([h1, h1]) V = utils.model_builder.randomModel(M.vnC, seed=79, its=50) v = utils.mkvc(V) modh = maps.Mesh2Mesh([M, M2]) modH = maps.Mesh2Mesh([M2, M]) H = modH * v h = modh * H if not plotIt: return ax = plt.subplot(131) M.plotImage(v, ax=ax) ax.set_title("Fine Mesh (Original)") ax = plt.subplot(132) M2.plotImage(H, clim=[0, 1], ax=ax) ax.set_title("Course Mesh") ax = plt.subplot(133) M.plotImage(h, clim=[0, 1], ax=ax) ax.set_title("Fine Mesh (Interpolated)")
def test_deriv(self): s = utils.mkvc(utils.model_builder.randomModel(self.M.vnC)) + 1.0 def fun(x): return self.problem.dpred(x), lambda x: self.problem.Jvec(s, x) return tests.checkDerivative(fun, s, num=4, plotIt=False, eps=FLR)
def getFields(self, bType="b", ifreq=0): src = self.srcList[ifreq] Pfx = self.mesh.getInterpolationMat(self.mesh.gridCC[self.activeCC, :], locType="Fx") Pfz = self.mesh.getInterpolationMat(self.mesh.gridCC[self.activeCC, :], locType="Fz") Ey = self.mesh.aveE2CC * self.f[src, "e"] Jy = utils.sdiag(self.sim.sigma) * Ey self.Ey = utils.mkvc(self.mirrorArray(Ey[self.activeCC], direction="y")) self.Jy = utils.mkvc(self.mirrorArray(Jy[self.activeCC], direction="y")) self.Bx = utils.mkvc( self.mirrorArray(Pfx * self.f[src, bType], direction="x")) self.Bz = utils.mkvc( self.mirrorArray(Pfz * self.f[src, bType], direction="z"))
def get_Surface(mtrue, A): active = mtrue > (np.log(1e-8)) nearpoint = findnearest(A) columns = mesh.gridCC[:, 0, None] == nearpoint ind = np.logical_and(columns.T, active).T idm = [] surface = [] for i in range(ind.shape[1]): idm.append( np.where( np.all( mesh.gridCC == np.r_[nearpoint[i], np.max(mesh.gridCC[ind[:, i], 1])], axis=1, ))) surface.append(mesh.gridCC[idm[-1], 1]) return utils.mkvc(np.r_[idm]), utils.mkvc(np.r_[surface])
def setUp(self): Inc = 45.0 Dec = 45.0 Btot = 51000 H0 = (Btot, Inc, Dec) self.b0 = mag.analytics.IDTtoxyz(-Inc, Dec, Btot) cs = 25.0 hxind = [(cs, 5, -1.3), (cs / 2.0, 41), (cs, 5, 1.3)] hyind = [(cs, 5, -1.3), (cs / 2.0, 41), (cs, 5, 1.3)] hzind = [(cs, 5, -1.3), (cs / 2.0, 40), (cs, 5, 1.3)] M = discretize.TensorMesh([hxind, hyind, hzind], "CCC") chibkg = 0.0 self.chiblk = 0.01 chi = np.ones(M.nC) * chibkg self.rad = 100 self.sphere_center = [0.0, 0.0, 0.0] sph_ind = getIndicesSphere(self.sphere_center, self.rad, M.gridCC) chi[sph_ind] = self.chiblk xr = np.linspace(-300, 300, 41) yr = np.linspace(-300, 300, 41) X, Y = np.meshgrid(xr, yr) Z = np.ones((xr.size, yr.size)) * 150 components = ["bx", "by", "bz"] self.xr = xr self.yr = yr self.rxLoc = np.c_[utils.mkvc(X), utils.mkvc(Y), utils.mkvc(Z)] receivers = mag.Point(self.rxLoc, components=components) srcField = mag.SourceField([receivers], parameters=H0) self.survey = mag.Survey(srcField) self.sim = mag.simulation.Simulation3DDifferential( M, survey=self.survey, muMap=maps.ChiMap(M), solver=Pardiso, ) self.M = M self.chi = chi
def test_rotateMatrixFromNormals(self): np.random.seed(20) n0 = np.random.rand(3) n0 *= 1.0 / np.linalg.norm(n0) np.random.seed(25) n1 = np.random.rand(3) n1 *= 1.0 / np.linalg.norm(n1) np.random.seed(30) scale = np.random.rand(100, 1) XYZ0 = scale * n0 XYZ1 = scale * n1 XYZ2 = utils.coord_utils.rotatePointsFromNormals(XYZ0, n0, n1) self.assertTrue( np.linalg.norm(utils.mkvc(XYZ1) - utils.mkvc(XYZ2)) / np.linalg.norm(utils.mkvc(XYZ1)) < tol)
def test_adjoint(self): # Adjoint Test # u = np.random.rand(self.mesh.nC*self.survey.nSrc) v = np.random.rand(self.mesh.nC) w = np.random.rand(mkvc(self.dobs).shape[0]) wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-10 print("Adjoint Test", np.abs(wtJv - vtJtw), passed) self.assertTrue(passed)
def test_SetGet(self): F = self.F nSrc = F.survey.nSrc e = np.random.rand(F.mesh.nE, nSrc) + np.random.rand(F.mesh.nE, nSrc) * 1j F[:, "e"] = e b = np.random.rand(F.mesh.nF, nSrc) + np.random.rand(F.mesh.nF, nSrc) * 1j F[:, "b"] = b self.assertTrue(np.all(F[:, "e"] == e)) self.assertTrue(np.all(F[:, "b"] == b)) F[:] = {"b": b, "e": e} self.assertTrue(np.all(F[:, "e"] == e)) self.assertTrue(np.all(F[:, "b"] == b)) for s in zero_types: F[:, "b"] = s self.assertTrue(np.all(F[:, "b"] == b * 0)) b = np.random.rand(F.mesh.nF, 1) print(type(self.Src0), "here") F[self.Src0, "b"] = b self.assertTrue(np.all(F[self.Src0, "b"] == b)) b = np.random.rand(F.mesh.nF, 1) F[self.Src0, "b"] = b self.assertTrue(np.all(F[self.Src0, "b"] == b)) phi = np.random.rand(F.mesh.nC, 2) F[[self.Src0, self.Src1], "phi"] = phi self.assertTrue(np.all(F[[self.Src0, self.Src1], "phi"] == phi)) fdict = F[:, :] self.assertTrue(type(fdict) is dict) self.assertTrue(sorted([k for k in fdict]) == ["b", "e", "phi"]) b = np.random.rand(F.mesh.nF, 2) F[[self.Src0, self.Src1], "b"] = b self.assertTrue(F[self.Src0]["b"].shape == (F.mesh.nF, 1)) self.assertTrue(F[self.Src0, "b"].shape == (F.mesh.nF, 1)) self.assertTrue(np.all(F[self.Src0, "b"] == utils.mkvc(b[:, 0], 2))) self.assertTrue(np.all(F[self.Src1, "b"] == utils.mkvc(b[:, 1], 2)))
def GravityGradientSphereFreeSpace(x, y, z, R, xc, yc, zc, rho): """ Computing the induced response of magnetic sphere in free-space. >> Input x, y, z: Observation locations R: radius of the sphere xc, yc, zc: Location of the sphere rho: Density of sphere """ if ~np.size(x) == np.size(y) == np.size(z): print("Specify same size of x, y, z") return unit_conv = 1e12 # Unit conversion from SI to (Eotvos) x = mkvc(x) y = mkvc(y) z = mkvc(z) rx = x - xc ry = y - yc rz = z - zc rx2 = rx * rx ry2 = ry * ry rz2 = rz * rz r = np.sqrt(rx2 + ry2 + rz2) bot = r * r * r * r * r M = np.empty_like(x) # create a vector of "Ms" if the point is outide M[r >= R] = R**3 * 4.0 / 3.0 * np.pi * rho # outside points M[r < R] = r[r < R]**3 * 4.0 / 3.0 * np.pi * rho # inside points g = G * (1.0 / bot) * M * unit_conv gxx = g * (2 * rx2 - ry2 - rz2) gyy = g * (2 * ry2 - rx2 - rz2) gzz = -gxx - gyy gxy = g * (3 * rx * ry) gxz = g * (3 * rx * rz) gyz = g * (3 * ry * rz) return gxx, gxy, gxz, gyy, gyz, gzz
def hzAnalyticDipoleF(r, freq, sigma, secondary=True, mu=mu_0): """ The analytical expression is given in Equation 4.56 in Ward and Hohmann, 1988, and the example reproduces their Figure 4.2. .. plot:: import numpy as np import matplotlib.pyplot as plt from SimPEG import electromagnetics as EM freq = np.logspace(-1, 5, 301) test = EM.analytics.hzAnalyticDipoleF( 100, freq, 0.01, secondary=False) plt.loglog(freq, test.real, 'C0-', label='Real') plt.loglog(freq, -test.real, 'C0--') plt.loglog(freq, test.imag, 'C1-', label='Imaginary') plt.loglog(freq, -test.imag, 'C1--') plt.title('Response at $r=100$ m') plt.xlim([1e-1, 1e5]) plt.ylim([1e-12, 1e-6]) plt.xlabel('Frequency (Hz)') plt.ylabel('$H_z$ (A/m)') plt.legend(loc=6) plt.show() **Reference** - Ward, S. H., and G. W. Hohmann, 1988, Electromagnetic theory for geophysical applications, Chapter 4 of Electromagnetic Methods in Applied Geophysics: SEG, Investigations in Geophysics No. 3, 130--311; DOI: `10.1190/1.9781560802631.ch4 <https://doi.org/10.1190/1.9781560802631.ch4>`_. """ r = np.abs(r) k = np.sqrt(-1j * 2.0 * np.pi * freq * mu * sigma) m = 1 front = m / (2.0 * np.pi * (k ** 2) * (r ** 5)) back = 9 - ( 9 + 9j * k * r - 4 * (k ** 2) * (r ** 2) - 1j * (k ** 3) * (r ** 3) ) * np.exp(-1j * k * r) hz = front * back if secondary: hp = -1 / (4 * np.pi * r ** 3) hz = hz - hp if hz.ndim == 1: hz = utils.mkvc(hz, 2) return hz