def test_Simulation2DNodal(self): problemDC = dc.Simulation2DNodal(self.mesh, survey=self.surveyDC, sigmaMap=maps.IdentityMap(self.mesh)) problemDC.solver = Solver data0 = problemDC.dpred(self.sigma0) datainf = problemDC.dpred(self.sigmaInf) surveyIP = ip.Survey(self.source_lists_ip) problemIP = ip.Simulation2DNodal( self.mesh, survey=surveyIP, sigma=self.sigmaInf, etaMap=maps.IdentityMap(self.mesh), ) problemIP.solver = Solver data_full = data0 - datainf data = problemIP.dpred(self.eta) err = np.linalg.norm( (data - data_full) / data_full)**2 / data_full.size if err < 0.05: passed = True print(">> IP forward test for Simulation2DNodal is passed") print(err) else: passed = False print(">> IP forward test for Simulation2DNodal is failed") self.assertTrue(passed)
def test_Simulation3DCellCentered(self): simulationdc = dc.simulation.Simulation3DCellCentered( self.mesh, sigmaMap=maps.IdentityMap(self.mesh), solver=Solver, survey=self.survey_dc, ) data0 = simulationdc.dpred(self.sigma0) datainf = simulationdc.dpred(self.sigmaInf) data_full = (data0 - datainf) / datainf simulationip = ip.simulation.Simulation3DCellCentered( mesh=self.mesh, survey=self.survey_ip, sigma=self.sigmaInf, etaMap=maps.IdentityMap(self.mesh), Ainv=simulationdc.Ainv, solver=Solver, ) data = simulationip.dpred(self.eta) err = np.linalg.norm( (data - data_full) / data_full)**2 / data_full.size if err > 0.05: import matplotlib.pyplot as plt plt.plot(data_full) plt.plot(data, "k.") plt.show() self.assertLess(err, 0.05)
def test_Simulation3DCellCentered(self): simulationdc = dc.simulation.Simulation3DCellCentered( mesh=self.mesh, survey=self.surveyDC, sigmaMap=maps.IdentityMap(self.mesh)) simulationdc.Solver = Solver data0 = simulationdc.dpred(self.sigma0) finf = simulationdc.fields(self.sigmaInf) datainf = simulationdc.dpred(self.sigmaInf, f=finf) surveyip = ip.survey.Survey([self.src]) simulationip = ip.simulation.Simulation3DCellCentered( mesh=self.mesh, survey=surveyip, rho=1.0 / self.sigmaInf, etaMap=maps.IdentityMap(self.mesh), Ainv=simulationdc.Ainv, _f=finf, ) simulationip.Solver = Solver data_full = data0 - datainf data = simulationip.dpred(self.eta) err = np.linalg.norm( (data - data_full) / data_full)**2 / data_full.size if err < 0.05: passed = True print(">> IP forward test for Simulation3DCellCentered is passed") else: passed = False print(">> IP forward test for Simulation3DCellCentered is failed") self.assertTrue(passed)
def test_Simulation2DCellCentered(self): simDC = dc.Simulation2DCellCentered( self.mesh, sigmaMap=maps.IdentityMap(self.mesh), solver=Solver, survey=self.survey_dc, ) data0 = simDC.dpred(self.sigma0) datainf = simDC.dpred(self.sigmaInf) data_full = (data0 - datainf) / datainf simIP = ip.Simulation2DCellCentered( self.mesh, sigma=self.sigmaInf, etaMap=maps.IdentityMap(self.mesh), solver=Solver, survey=self.survey_ip, ) data = simIP.dpred(self.eta) np.testing.assert_allclose(simIP._scale, simIP._sign / datainf) err = np.linalg.norm( (data - data_full) / data_full)**2 / data_full.size if err > 0.05: import matplotlib.pyplot as plt plt.plot(data_full) plt.plot(data, "k.") plt.show() self.assertLess(err, 0.05)
def setUp(self): IO = dc.IO() ABMN = np.loadtxt(my_dir + "/resources/mixed_survey.loc") A = ABMN[:100, :2] B = ABMN[:100, 2:4] M = ABMN[:100, 4:6] N = ABMN[:100, 6:8] survey = IO.from_ambn_locations_to_survey(A, B, M, N, survey_type="dipole-dipole") # add some other receivers and sources to the mix electrode_locations = np.unique(np.r_[A, B, M, N], axis=0) rx_p = dc.receivers.Pole(electrode_locations[[2, 4, 6]]) rx_d = dc.receivers.Dipole(electrode_locations[[2, 4, 6]], electrode_locations[[3, 5, 9]]) tx_pd = dc.sources.Pole([rx_d], electrode_locations[0]) tx_pp = dc.sources.Pole([rx_p], electrode_locations[1]) tx_dp = dc.sources.Dipole([rx_p], electrode_locations[0], electrode_locations[1]) source_list = survey.source_list source_list.append(tx_pd) source_list.append(tx_pp) source_list.append(tx_dp) survey = dc.Survey(source_list) self.survey = survey # This survey is a mix of d-d, d-p, p-d, and p-p txs and rxs. # This mesh is meant only for testing mesh, inds = IO.set_mesh(dx=10, dz=40) self.sim1 = dc.Simulation2DNodal( survey=survey, mesh=mesh, solver=Pardiso, storeJ=False, sigmaMap=maps.IdentityMap(mesh), miniaturize=False, ) self.sim2 = dc.Simulation2DNodal( survey=survey, mesh=mesh, solver=Pardiso, storeJ=False, sigmaMap=maps.IdentityMap(mesh), miniaturize=True, ) self.model = np.ones(mesh.nC) self.f1 = self.sim1.fields(self.model) self.f2 = self.sim2.fields(self.model)
def test_Simulation3DNodal(self): simulationdc = dc.simulation.Simulation3DNodal( self.mesh, sigmaMap=maps.IdentityMap(self.mesh), solver=Solver, survey=self.survey_dc, ) data0 = simulationdc.dpred(self.sigma0) datainf = simulationdc.dpred(self.sigmaInf) data_full = (data0 - datainf) / datainf simulationip = ip.simulation.Simulation3DNodal( mesh=self.mesh, survey=self.survey_ip, sigma=self.sigmaInf, etaMap=maps.IdentityMap(self.mesh), Ainv=simulationdc.Ainv, solver=Solver, ) data = simulationip.dpred(self.eta) simulationip_stored = ip.simulation.Simulation3DNodal( mesh=self.mesh, survey=self.survey_ip, sigma=self.sigmaInf, etaMap=maps.IdentityMap(self.mesh), Ainv=simulationdc.Ainv, solver=Solver, storeJ=True, ) data2 = simulationip_stored.dpred(self.eta) np.testing.assert_allclose(data, data2) np.testing.assert_allclose(simulationip._scale, simulationip._sign / datainf) err = np.linalg.norm( (data - data_full) / data_full)**2 / data_full.size if err > 0.05: import matplotlib.pyplot as plt plt.plot(data_full) plt.plot(data, "k.") plt.show() self.assertLess(err, 0.05)
def JvecAdjointTest(sigmaHalf, formulation="PrimSec"): forType = "PrimSec" not in formulation survey, sigma, sigBG, m1d = nsem.utils.test_utils.setup1DSurvey( sigmaHalf, tD=forType, structure=False) print("Adjoint test of e formulation for {:s} comp \n".format(formulation)) if "PrimSec" in formulation: problem = nsem.Simulation1DPrimarySecondary( m1d, sigmaPrimary=sigBG, sigmaMap=maps.IdentityMap(m1d)) else: raise NotImplementedError( "Only {} formulations are implemented.".format(formulation)) problem.pair(survey) m = sigma u = problem.fields(m) np.random.seed(1983) v = np.random.rand(survey.nD, ) # print problem.PropMap.PropModel.nP w = np.random.rand(problem.mesh.nC, ) vJw = v.ravel().dot(problem.Jvec(m, w, u)) wJtv = w.ravel().dot(problem.Jtvec(m, v, u)) tol = np.max([TOL * (10**int(np.log10(np.abs(vJw)))), FLR]) print(" vJw wJtv vJw - wJtv tol abs(vJw - wJtv) < tol") print(vJw, wJtv, vJw - wJtv, tol, np.abs(vJw - wJtv) < tol) return np.abs(vJw - wJtv) < tol
def DerivJvecTest(halfspace_value, freq=False, expMap=True): survey, sig, sigBG, mesh = nsem.utils.test_utils.setup1DSurvey( halfspace_value, False, structure=True) simulation = nsem.Simulation1DPrimarySecondary( mesh, sigmaPrimary=sigBG, sigmaMap=maps.IdentityMap(mesh), survey=survey) print("Using {0} solver for the simulation".format(simulation.solver)) print( "Derivative test of Jvec for eForm primary/secondary for 1d comp from {0} to {1} Hz\n" .format(survey.frequencies[0], survey.frequencies[-1])) # simulation.mapping = maps.ExpMap(simulation.mesh) # simulation.sigmaPrimary = np.log(sigBG) x0 = sigBG # cond = sig[0] # x0 = np.log(np.ones(simulation.mesh.nC)*halfspace_value) # simulation.sigmaPrimary = x0 np.random.seed(1983) # if True: # x0 = x0 + np.random.randn(simulation.mesh.nC)*halfspace_value*1e-1 survey = simulation.survey def fun(x): return simulation.dpred(x), lambda x: simulation.Jvec(x0, x) return tests.checkDerivative(fun, x0, num=4, plotIt=False, eps=FLR)
def setupSimpegNSEM_ePrimSec(inputSetup, comp="Imp", singleFreq=False, expMap=True): M, freqs, sig, sigBG, rx_loc = inputSetup # Make a receiver list receiver_list = [] if comp == "All": rx_type_list = ["xx", "xy", "yx", "yy", "zx", "zy"] elif comp == "Imp": rx_type_list = ["xx", "xy", "yx", "yy"] elif comp == "Tip": rx_type_list = ["zx", "zy"] else: rx_type_list = [comp] for rx_type in rx_type_list: if rx_type in ["xx", "xy", "yx", "yy"]: receiver_list.append(Point3DImpedance(rx_loc, rx_type, "real")) receiver_list.append(Point3DImpedance(rx_loc, rx_type, "imag")) if rx_type in ["zx", "zy"]: receiver_list.append(Point3DTipper(rx_loc, rx_type, "real")) receiver_list.append(Point3DTipper(rx_loc, rx_type, "imag")) # Source list source_list = [] if singleFreq: source_list.append(Planewave_xy_1Dprimary(receiver_list, singleFreq)) else: for freq in freqs: source_list.append(Planewave_xy_1Dprimary(receiver_list, freq)) # Survey NSEM survey = Survey(source_list) # Setup the problem object sigma1d = M.r(sigBG, "CC", "CC", "M")[0, 0, :] if expMap: problem = Simulation3DPrimarySecondary(M, survey=survey, sigmaPrimary=np.log(sigma1d)) problem.sigmaMap = maps.ExpMap(problem.mesh) problem.model = np.log(sig) else: problem = Simulation3DPrimarySecondary(M, survey=survey, sigmaPrimary=sigma1d) problem.sigmaMap = maps.IdentityMap(problem.mesh) problem.model = sig problem.verbose = False try: from pymatsolver import Pardiso problem.solver = Pardiso except: pass return (survey, problem)
def test_regularization(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): if mesh.dim < 3 and r.__name__[-1] == "z": continue if mesh.dim < 2 and r.__name__[-1] == "y": continue print("Testing {0:d}D".format(mesh.dim)) mapping = maps.IdentityMap(mesh) reg = r(mesh=mesh, mapping=mapping) print("--- Checking {} --- \n".format( reg.__class__.__name__)) if mapping.nP != "*": m = np.random.rand(mapping.nP) else: m = np.random.rand(mesh.nC) mref = np.ones_like(m) * np.mean(m) reg.mref = mref # test derivs passed = reg.test(m, eps=TOL) self.assertTrue(passed)
def test_vangenuchten_theta_m(self): mesh = discretize.TensorMesh([50]) idnmap = maps.IdentityMap(nP=mesh.nC) seeds = { "theta_r": np.random.rand(mesh.nC), "theta_s": np.random.rand(mesh.nC), "n": np.random.rand(mesh.nC) + 1, "alpha": np.random.rand(mesh.nC), } opts = [ ("theta_r", dict(theta_rMap=idnmap), 1), ("theta_s", dict(theta_sMap=idnmap), 1), ("n", dict(nMap=idnmap), 1), ("alpha", dict(alphaMap=idnmap), 1), ] u = np.random.randn(mesh.nC) for name, opt, nM in opts: van = richards.empirical.Vangenuchten_theta(mesh, **opt) x0 = np.concatenate([seeds[n] for n in name.split("-")]) def fun(m): van.model = m return van(u), van.derivM(u) print("Vangenuchten_theta test m deriv: ", name) passed = checkDerivative(fun, x0, plotIt=False) self.assertTrue(passed, True)
def __init__(self, L, dL, survey, gfunc): """ :param L: lateral extent of square survey area in meters :param dL: list of mesh block sizes in meters :param survey: gravity survey geometry :param gfunc: geology function mapping a np.array of (x,y,z) positions (shape = (N, 3)) to a set of rock properties (density contrast) """ # Set all the initial stuff up self.survey = survey self.L = L self.dL = list(sorted(dL)[::-1]) self.survey = survey self.gfunc = gfunc # Make a TensorMesh and forward model pair for each set of parameters self.meshxfwd = [] for dLi in self.dL: NL = 2 * int(L / dLi) mesh = baseline_tensor_mesh(NL, dLi) model_map = maps.IdentityMap(mesh=mesh, nP=mesh.nC) ind_active = np.array([True for i in range(mesh.nC)]) fwd = gravity.simulation.Simulation3DIntegral( survey=survey, mesh=mesh, rhoMap=model_map, actInd=ind_active, store_sensitivities="ram", ) self.meshxfwd.append((mesh, fwd))
def __init__(self, mesh, survey, gfunc): """ Initialize the problem :param mesh: discretize.mesh instance :param survey: SimPEG.gravity.Gravity.Survey instance :param gfunc: geology function mapping a np.array of (x,y,z) positions (shape = (N, 3)) to a set of rock properties (density contrast) """ # Set all the initial stuff up self.survey = survey self.mesh = mesh self.gfunc = gfunc # Initialize a gravity simulation object to cache sensitivities and # make MCMC that much faster self.model_map = maps.IdentityMap(mesh=mesh, nP=mesh.nC) self.ind_active = np.array([True for i in range(mesh.nC)]) self.fwd = gravity.simulation.Simulation3DIntegral( survey=self.survey, mesh=self.mesh, rhoMap=self.model_map, actInd=self.ind_active, store_sensitivities="ram", ) self.voxmodel = None self.fwd_data = None
def test_pole_dipole_mini(self): sim1 = dc.Simulation2DNodal(mesh=self.mesh, survey=self.p_d_survey, sigmaMap=maps.IdentityMap(self.mesh)) sim2 = dc.Simulation2DNodal( mesh=self.mesh, survey=self.p_d_survey, sigmaMap=maps.IdentityMap(self.mesh), miniaturize=True, ) mSynth = np.ones(self.mesh.nC) d1 = sim1.dpred(mSynth) d2 = sim2.dpred(mSynth) self.assertTrue(np.allclose(d1, d2))
def run_inversion( m0, simulation, data, actind, mesh, maxIter=15, beta0_ratio=1e0, coolingFactor=5, coolingRate=2, upper=np.inf, lower=-np.inf, use_sensitivity_weight=True, alpha_s=1e-4, alpha_x=1.0, alpha_y=1.0, alpha_z=1.0, ): """ Run DC inversion """ dmisfit = data_misfit.L2DataMisfit(simulation=simulation, data=data) # Map for a regularization regmap = maps.IdentityMap(nP=int(actind.sum())) # Related to inversion if use_sensitivity_weight: reg = regularization.Sparse(mesh, indActive=actind, mapping=regmap) reg.alpha_s = alpha_s reg.alpha_x = alpha_x reg.alpha_y = alpha_y reg.alpha_z = alpha_z else: reg = regularization.Tikhonov(mesh, indActive=actind, mapping=regmap) reg.alpha_s = alpha_s reg.alpha_x = alpha_x reg.alpha_y = alpha_y reg.alpha_z = alpha_z opt = optimization.ProjectedGNCG(maxIter=maxIter, upper=upper, lower=lower) invProb = inverse_problem.BaseInvProblem(dmisfit, reg, opt) beta = directives.BetaSchedule(coolingFactor=coolingFactor, coolingRate=coolingRate) betaest = directives.BetaEstimate_ByEig(beta0_ratio=beta0_ratio) target = directives.TargetMisfit() # Need to have basice saving function update_Jacobi = directives.UpdatePreconditioner() if use_sensitivity_weight: updateSensW = directives.UpdateSensitivityWeights() directiveList = [beta, target, updateSensW, update_Jacobi, betaest] else: directiveList = [beta, target, update_Jacobi, betaest] inv = inversion.BaseInversion(invProb, directiveList=directiveList) opt.LSshorten = 0.5 opt.remember("xc") # Run inversion mopt = inv.run(m0) return mopt, invProb.dpred
def model_soundings(h0, h1, rho0, rho1, rho2): hz = np.r_[h0, h1] rho = np.r_[rho0, rho1, rho2] srcList_w = [] srcList_s = [] AB2 = np.arange(4, 89, 3) + 0.5 for i, a in enumerate(AB2): a_loc = -a b_loc = a m_loc_wen = -a + (a * 2) // 3 n_loc_wen = -m_loc_wen m_loc_sch = -1.5 n_loc_sch = 1.5 rx_w = DC.Rx.Dipole(np.r_[m_loc_wen, 0, 0], np.r_[n_loc_wen, 0, 0]) rx_s = DC.Rx.Dipole(np.r_[m_loc_sch, 0, 0], np.r_[n_loc_sch, 0, 0]) locA = np.r_[a_loc, 0, 0] locB = np.r_[b_loc, 0, 0] src = DC.Src.Dipole([rx_w], locA, locB) srcList_w.append(src) src = DC.Src.Dipole([rx_s], locA, locB) srcList_s.append(src) m = np.r_[rho, hz] wires = maps.Wires(('rho', rho.size), ('t', rho.size - 1)) mapping_rho = maps.IdentityMap(nP=rho.size) * wires.rho mapping_t = maps.IdentityMap(nP=hz.size) * wires.t survey = DC.Survey(srcList_w) simulation = DC.Simulation1DLayers(rhoMap=mapping_rho, thicknessesMap=mapping_t, survey=survey, data_type='apparent_resistivity') data_w = simulation.make_synthetic_data(m) survey = DC.Survey(srcList_s) simulation = DC.Simulation1DLayers(rhoMap=mapping_rho, thicknessesMap=mapping_t, survey=survey, data_type='apparent_resistivity') data_s = simulation.make_synthetic_data(m) return data_w, data_s
def get_problem_survey(self): survey_obj = survey.LinearSurvey() simulation_obj = simulation.LinearSimulation( survey=survey_obj, mesh=self.mesh_prop, model_map=maps.IdentityMap(), G=self.G, ) return survey_obj, simulation_obj
def run(plotIt=True): M = discretize.TensorMesh([np.ones(40)]) M.setCellGradBC("dirichlet") params = richards.empirical.HaverkampParams().celia1990 k_fun, theta_fun = richards.empirical.haverkamp(M, **params) k_fun.KsMap = maps.IdentityMap(nP=M.nC) bc = np.array([-61.5, -20.7]) h = np.zeros(M.nC) + bc[0] def getFields(timeStep, method): timeSteps = np.ones(int(360 / timeStep)) * timeStep prob = richards.SimulationNDCellCentered( M, hydraulic_conductivity=k_fun, water_retention=theta_fun, boundary_conditions=bc, initial_conditions=h, do_newton=False, method=method, ) prob.time_steps = timeSteps return prob.fields(params["Ks"] * np.ones(M.nC)) Hs_M010 = getFields(10, "mixed") Hs_M030 = getFields(30, "mixed") Hs_M120 = getFields(120, "mixed") Hs_H010 = getFields(10, "head") Hs_H030 = getFields(30, "head") Hs_H120 = getFields(120, "head") if not plotIt: return plt.figure(figsize=(13, 5)) plt.subplot(121) plt.plot(40 - M.gridCC, Hs_M010[-1], "b-") plt.plot(40 - M.gridCC, Hs_M030[-1], "r-") plt.plot(40 - M.gridCC, Hs_M120[-1], "k-") plt.ylim([-70, -10]) plt.title("Mixed Method") plt.xlabel("Depth, cm") plt.ylabel("Pressure Head, cm") plt.legend(("$\Delta t$ = 10 sec", "$\Delta t$ = 30 sec", "$\Delta t$ = 120 sec")) plt.subplot(122) plt.plot(40 - M.gridCC, Hs_H010[-1], "b-") plt.plot(40 - M.gridCC, Hs_H030[-1], "r-") plt.plot(40 - M.gridCC, Hs_H120[-1], "k-") plt.ylim([-70, -10]) plt.title("Head-Based Method") plt.xlabel("Depth, cm") plt.ylabel("Pressure Head, cm") plt.legend(("$\Delta t$ = 10 sec", "$\Delta t$ = 30 sec", "$\Delta t$ = 120 sec"))
def setUp(self): cs = 12.5 hx = [(cs, 7, -1.3), (cs, 61), (cs, 7, 1.3)] hy = [(cs, 7, -1.3), (cs, 20)] mesh = discretize.TensorMesh([hx, hy], x0="CN") # x = np.linspace(-200, 200., 20) x = np.linspace(-200, 200.0, 2) M = utils.ndgrid(x - 12.5, np.r_[0.0]) N = utils.ndgrid(x + 12.5, np.r_[0.0]) A0loc = np.r_[-150, 0.0] A1loc = np.r_[-130, 0.0] B0loc = np.r_[-130, 0.0] B1loc = np.r_[-110, 0.0] rx = dc.Rx.Dipole(M, N) src0 = dc.Src.Dipole([rx], A0loc, B0loc) src1 = dc.Src.Dipole([rx], A1loc, B1loc) survey = ip.Survey([src0, src1]) sigma = np.ones(mesh.nC) * 1.0 problem = ip.Simulation2DCellCentered( mesh, survey=survey, sigma=sigma, etaMap=maps.IdentityMap(mesh), verbose=False, ) mSynth = np.ones(mesh.nC) * 0.1 dobs = problem.make_synthetic_data(mSynth, add_noise=True) # Now set up the problem to do some minimization dmis = data_misfit.L2DataMisfit(data=dobs, simulation=problem) reg = regularization.Tikhonov(mesh) opt = optimization.InexactGaussNewton(maxIterLS=20, maxIter=10, tolF=1e-6, tolX=1e-6, tolG=1e-6, maxIterCG=6) invProb = inverse_problem.BaseInvProblem(dmis, reg, opt, beta=1e4) inv = inversion.BaseInversion(invProb) self.inv = inv self.reg = reg self.p = problem self.mesh = mesh self.m0 = mSynth self.survey = survey self.dmis = dmis
def setUp(self): mesh = discretize.TensorMesh([100]) self.sim = simulation.ExponentialSinusoidSimulation( mesh=mesh, model_map=maps.IdentityMap(mesh), ) mtrue = np.zeros(mesh.nC) mtrue[mesh.vectorCCx > 0.3] = 1.0 mtrue[mesh.vectorCCx > 0.45] = -0.5 mtrue[mesh.vectorCCx > 0.6] = 0 self.mtrue = mtrue
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 test_haverkamp_k_m(self): mesh = discretize.TensorMesh([5]) expmap = maps.IdentityMap(nP=mesh.nC) wires2 = maps.Wires(("one", mesh.nC), ("two", mesh.nC)) wires3 = maps.Wires(("one", mesh.nC), ("two", mesh.nC), ("three", mesh.nC)) opts = [ ("Ks", dict(KsMap=expmap), 1), ("A", dict(AMap=expmap), 1), ("gamma", dict(gammaMap=expmap), 1), ("Ks-A", dict(KsMap=expmap * wires2.one, AMap=expmap * wires2.two), 2), ( "Ks-gamma", dict(KsMap=expmap * wires2.one, gammaMap=expmap * wires2.two), 2, ), ( "A-gamma", dict(AMap=expmap * wires2.one, gammaMap=expmap * wires2.two), 2, ), ( "Ks-A-gamma", dict( KsMap=expmap * wires3.one, AMap=expmap * wires3.two, gammaMap=expmap * wires3.three, ), 3, ), ] u = np.random.randn(mesh.nC) for name, opt, nM in opts: np.random.seed(2) hav = richards.empirical.Haverkamp_k(mesh, **opt) def fun(m): hav.model = m return hav(u), hav.derivM(u) print("Haverkamp_k test m deriv: ", name) passed = checkDerivative(fun, np.random.randn(mesh.nC * nM), plotIt=False) self.assertTrue(passed, True)
def test_Simulation2DCellCentered(self): problemDC = dc.Simulation2DCellCentered(self.mesh, survey=self.surveyDC, rhoMap=maps.IdentityMap( self.mesh)) problemDC.solver = Solver data0 = problemDC.dpred(1.0 / self.sigma0) finf = problemDC.fields(1.0 / self.sigmaInf) datainf = problemDC.dpred(1.0 / self.sigmaInf, f=finf) surveyIP = ip.Survey(self.source_lists_ip) problemIP = ip.Simulation2DCellCentered( self.mesh, survey=surveyIP, rho=1.0 / self.sigmaInf, etaMap=maps.IdentityMap(self.mesh), ) problemIP.solver = Solver data_full = data0 - datainf data = problemIP.dpred(self.eta) err = np.linalg.norm( (data - data_full) / data_full)**2 / data_full.size if err < 0.05: passed = True print(">> IP forward test for Simulation2DCellCentered is passed") else: import matplotlib.pyplot as plt passed = False print(">> IP forward test for Simulation2DCellCentered is failed") print(err) plt.plot(data_full) plt.plot(data, "k.") plt.show() self.assertTrue(passed)
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_mref_is_zero(self): mesh = discretize.TensorMesh([10, 5, 8]) mref = np.ones(mesh.nC) for regType in ["Tikhonov", "Sparse", "Simple"]: reg = getattr(regularization, regType)(mesh, mref=mref, mapping=maps.IdentityMap(mesh)) print("Check: phi_m (mref) = {0:f}".format(reg(mref))) passed = reg(mref) < TOL self.assertTrue(passed)
def setUp(self): aSpacing = 2.5 nElecs = 10 surveySize = nElecs * aSpacing - aSpacing cs = surveySize / nElecs / 4 mesh = discretize.TensorMesh( [ [(cs, 10, -1.3), (cs, surveySize / cs), (cs, 10, 1.3)], [(cs, 3, -1.3), (cs, 3, 1.3)], # [(cs, 5, -1.3), (cs, 10)] ], "CN", ) source_list = dc.utils.WennerSrcList(nElecs, aSpacing, in2D=True) survey = dc.survey.Survey(source_list) simulation = dc.simulation.Simulation3DNodal( mesh=mesh, survey=survey, rhoMap=maps.IdentityMap(mesh), storeJ=True, bc_type="Robin", ) mSynth = np.ones(mesh.nC) dobs = simulation.make_synthetic_data(mSynth, add_noise=True) # Now set up the problem to do some minimization dmis = data_misfit.L2DataMisfit(simulation=simulation, data=dobs) reg = regularization.Tikhonov(mesh) opt = optimization.InexactGaussNewton(maxIterLS=20, maxIter=10, tolF=1e-6, tolX=1e-6, tolG=1e-6, maxIterCG=6) invProb = inverse_problem.BaseInvProblem(dmis, reg, opt, beta=1e4) inv = inversion.BaseInversion(invProb) self.inv = inv self.reg = reg self.p = simulation self.mesh = mesh self.m0 = mSynth self.survey = survey self.dmis = dmis self.dobs = dobs
def setUp(self): print("\n ---- Testing {} ---- \n".format(self.formulation)) cs = 12.5 hx = [(cs, 2, -1.3), (cs, 61), (cs, 2, 1.3)] hy = [(cs, 2, -1.3), (cs, 20)] mesh = discretize.TensorMesh([hx, hy], x0="CN") x = np.linspace(-135, 250.0, 20) M = utils.ndgrid(x - 12.5, np.r_[0.0]) N = utils.ndgrid(x + 12.5, np.r_[0.0]) A0loc = np.r_[-150, 0.0] A1loc = np.r_[-130, 0.0] # rxloc = [np.c_[M, np.zeros(20)], np.c_[N, np.zeros(20)]] rx1 = dc.receivers.Dipole(M, N) rx2 = dc.receivers.Dipole(M, N, data_type="apparent_resistivity") src0 = dc.sources.Pole([rx1, rx2], A0loc) src1 = dc.sources.Pole([rx1, rx2], A1loc) survey = dc.survey.Survey([src0, src1]) survey.set_geometric_factor() simulation = getattr(dc, self.formulation)( mesh, rhoMap=maps.IdentityMap(mesh), storeJ=self.storeJ, solver=Solver, survey=survey, bc_type=self.bc_type, ) mSynth = np.ones(mesh.nC) * 1.0 data = simulation.make_synthetic_data(mSynth, add_noise=True) # Now set up the problem to do some minimization dmis = data_misfit.L2DataMisfit(simulation=simulation, data=data) reg = regularization.Tikhonov(mesh) opt = optimization.InexactGaussNewton(maxIterLS=20, maxIter=10, tolF=1e-6, tolX=1e-6, tolG=1e-6, maxIterCG=6) invProb = inverse_problem.BaseInvProblem(dmis, reg, opt, beta=1e0) inv = inversion.BaseInversion(invProb) self.inv = inv self.reg = reg self.p = simulation self.mesh = mesh self.m0 = mSynth self.survey = survey self.dmis = dmis self.data = data
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): nC = 20 M = discretize.TensorMesh([nC, nC]) y = np.linspace(0.0, 1.0, nC // 2) rlocs = np.c_[y * 0 + M.vectorCCx[-1], y] rx = tomo.Rx(locations=rlocs) srcList = [ tomo.Src(loc=np.r_[M.vectorCCx[0], yi], rxList=[rx]) for yi in y ] survey = tomo.Survey(srcList) problem = tomo.Simulation(M, slownessMap=maps.IdentityMap(M)) problem.pair(survey) self.M = M self.problem = problem self.survey = survey
def get_problem_survey(self, nx=20, ny=20, dx=10, dy=20): hx = np.ones(nx) * dx hy = np.ones(ny) * dy self._mesh_prop = TensorMesh([hx, hy]) y = np.linspace(0, 400, 10) self._source_locations_prop = np.c_[y * 0 + self._mesh_prop.vectorCCx[0], y] self._receiver_locations_prop = np.c_[y * 0 + self._mesh_prop.vectorCCx[-1], y] rx = survey.BaseRx(self._receiver_locations_prop) srcList = [ survey.BaseSrc(location=self._source_locations_prop[i, :], receiver_list=[rx]) for i in range(y.size) ] self._survey_prop = seismic.survey.StraightRaySurvey(srcList) self._simulation_prop = seismic.simulation.Simulation2DIntegral( survey=self._survey_prop, mesh=self._mesh_prop, slownessMap=maps.IdentityMap(self._mesh_prop)) self._data_prop = data.Data(self._survey_prop)