def test_summary_validate(self): PM = ComplicatedInversion() PM.summary() PM.validate() with self.assertRaises(ValueError): PM.model = np.ones(2) PM.summary() PM.validate() PM.AMap = Maps.ExpMap(nP=3) with self.assertRaises(ValueError): PM.model = np.ones(2) PM.summary() PM.validate() PM.gammaMap = Maps.ExpMap(nP=2) with self.assertRaises(ValueError): # maps are mismatching sizes PM.model = np.ones(2) PM.summary() PM.validate() PM.AMap = Maps.ExpMap(nP=2) PM.model = np.ones(2) PM.summary() PM.validate() assert PM.KsDeriv == 0
def spectral_ip_mappings(mesh, indActive=None, inactive_eta=1e-4, inactive_tau=1e-4, inactive_c=1e-4, is_log_eta=True, is_log_tau=True, is_log_c=True): """ Generates Mappings for Spectral Induced Polarization Problem. Three parameters are required to be input: Chargeability (eta), Time constant (tau), and Frequency dependency (c). If there is no topography (indActive is None), model (m) can be either set to m = np.r_[log(eta), log(tau), log(c)] or m = np.r_[eta, tau, c] When indActive is not None, m is m = np.r_[log(eta[indAcitve]), log(tau[indAcitve]), log(c[indAcitve])] or m = np.r_[eta[indAcitve], tau[indAcitve], c[indAcitve]] or TODO: Illustrate input and output variables """ if indActive is None: indActive = np.ones(mesh.nC, dtype=bool) actmap_eta = Maps.InjectActiveCells(mesh, indActive=indActive, valInactive=inactive_eta) actmap_tau = Maps.InjectActiveCells(mesh, indActive=indActive, valInactive=inactive_tau) actmap_c = Maps.InjectActiveCells(mesh, indActive=indActive, valInactive=inactive_c) wires = Maps.Wires(('eta', indActive.sum()), ('tau', indActive.sum()), ('c', indActive.sum())) if is_log_eta: eta_map = actmap_eta * Maps.ExpMap(nP=actmap_eta.nP) * wires.eta else: eta_map = actmap_eta * wires.eta if is_log_tau: tau_map = actmap_tau * Maps.ExpMap(nP=actmap_tau.nP) * wires.tau else: tau_map = actmap_tau * wires.tau if is_log_c: c_map = actmap_c * Maps.ExpMap(nP=actmap_c.nP) * wires.c else: c_map = actmap_c * wires.c return eta_map, tau_map, c_map, wires
def setup_maps(self, mesh, k_fun, theta_fun): wires = Maps.Wires( ('Ks', mesh.nC), ('A', mesh.nC), ('theta_s', mesh.nC) ) k_fun.KsMap = Maps.ExpMap(nP=mesh.nC) * wires.Ks k_fun.AMap = wires.A theta_fun.theta_sMap = wires.theta_s
def getSensitivity(survey, A, B, M, N, model): if survey == "Dipole-Dipole": rx = DC.Rx.Dipole(np.r_[M, 0.0], np.r_[N, 0.0]) src = DC.Src.Dipole([rx], np.r_[A, 0.0], np.r_[B, 0.0]) elif survey == "Pole-Dipole": rx = DC.Rx.Dipole(np.r_[M, 0.0], np.r_[N, 0.0]) src = DC.Src.Pole([rx], np.r_[A, 0.0]) elif survey == "Dipole-Pole": rx = DC.Rx.Pole(np.r_[M, 0.0]) src = DC.Src.Dipole([rx], np.r_[A, 0.0], np.r_[B, 0.0]) elif survey == "Pole-Pole": rx = DC.Rx.Pole(np.r_[M, 0.0]) src = DC.Src.Pole([rx], np.r_[A, 0.0]) # Model mappings expmap = Maps.ExpMap(mesh) mapping = expmap survey = DC.Survey([src]) problem = DC.Problem3D_CC(mesh, sigmaMap=mapping) problem.Solver = SolverLU problem.pair(survey) fieldObj = problem.fields(model) J = problem.Jtvec(model, np.array([1.0]), f=fieldObj) return J
def setUp(self): cs = 5. ncx = 20 ncy = 6 npad = 20 hx = [(cs, ncx), (cs, npad, 1.3)] hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)] mesh = Mesh.CylMesh([hx, 1, hy], '00C') active = mesh.vectorCCz < 0. activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz) mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap rxOffset = 40. rx = EM.TDEM.RxTDEM(np.array([[rxOffset, 0., 0.]]), np.logspace(-4, -3, 20), 'bz') src = EM.TDEM.SrcTDEM_VMD_MVP([rx], loc=np.array([0., 0., 0.])) survey = EM.TDEM.SurveyTDEM([src]) self.prb = EM.TDEM.ProblemTDEM_b(mesh, mapping=mapping) # self.prb.timeSteps = [1e-5] self.prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)] # self.prb.timeSteps = [(1e-05, 100)] try: from pymatsolver import MumpsSolver self.prb.Solver = MumpsSolver except ImportError, e: self.prb.Solver = SolverLU
def test_sum(self): M2 = Mesh.TensorMesh([np.ones(10), np.ones(20)], "CC") block = ( Maps.ParametricEllipsoid(M2) * Maps.Projection(7, np.r_[1, 2, 3, 4, 5, 6]) ) background = ( Maps.ExpMap(M2) * Maps.SurjectFull(M2) * Maps.Projection(7, np.r_[0]) ) summap0 = Maps.SumMap([block, background]) summap1 = block + background m0 = np.hstack([ np.random.rand(3), np.r_[M2.x0[0], 2*M2.hx.min()], np.r_[M2.x0[1], 4*M2.hy.min()] ]) self.assertTrue( np.all(summap0 * m0 == summap1 * m0) ) self.assertTrue(summap0.test(m0)) self.assertTrue(summap1.test(m0))
def test_basic(self): expMap = Maps.ExpMap(Mesh.TensorMesh((3, ))) assert expMap.nP == 3 for Example in [SimpleExample, ShortcutExample]: PM = Example(sigmaMap=expMap) assert PM.sigmaMap is not None assert PM.sigmaMap is expMap # There is currently no model, so sigma, which is mapped, fails self.assertRaises(AttributeError, getattr, PM, 'sigma') PM.model = np.r_[1., 2., 3.] assert np.all(PM.sigma == np.exp(np.r_[1., 2., 3.])) PM = pickle.loads(pickle.dumps(PM)) assert np.all(PM.sigmaDeriv.todense() == Utils.sdiag( np.exp(np.r_[1., 2., 3.])).todense()) # If we set sigma, we should delete the mapping PM.sigma = np.r_[1., 2., 3.] assert np.all(PM.sigma == np.r_[1., 2., 3.]) PM = pickle.loads(pickle.dumps(PM)) assert PM.sigmaMap is None assert PM.sigmaDeriv == 0 del PM.model # sigma is not changed assert np.all(PM.sigma == np.r_[1., 2., 3.])
def run(plotIt=True): M = Mesh.TensorMesh([7, 5]) v1dMap = Maps.SurjectVertical1D(M) expMap = Maps.ExpMap(M) myMap = expMap * v1dMap m = np.r_[0.2, 1, 0.1, 2, 2.9] # only 5 model parameters! sig = myMap * m if not plotIt: return figs, axs = plt.subplots(1, 2) axs[0].plot(m, M.vectorCCy, 'b-o') axs[0].set_title('Model') axs[0].set_ylabel('Depth, y') axs[0].set_xlabel('Value, $m_i$') axs[0].set_xlim(0, 3) axs[0].set_ylim(0, 1) clbar = plt.colorbar( M.plotImage(sig, ax=axs[1], grid=True, gridOpts=dict(color='grey'))[0]) axs[1].set_title('Physical Property') axs[1].set_ylabel('Depth, y') clbar.set_label('$\sigma = \exp(\mathbf{P}m)$') plt.tight_layout()
def setUp(self): mesh = Mesh.TensorMesh([30, 30], x0=[-0.5, -1.]) sigma = np.ones(mesh.nC) model = np.log(sigma) prob = DC.Problem3D_CC(mesh, rhoMap=Maps.ExpMap(mesh)) rx = DC.Rx.Pole( Utils.ndgrid([mesh.vectorCCx, np.r_[mesh.vectorCCy.max()]]) ) src = DC.Src.Dipole( [rx], np.r_[-0.25, mesh.vectorCCy.max()], np.r_[0.25, mesh.vectorCCy.max()] ) survey = DC.Survey([src]) prob.pair(survey) self.std = 0.01 survey.std = self.std dobs = survey.makeSyntheticData(model) self.eps = 1e-8 * np.min(np.abs(dobs)) survey.eps = self.eps dmis = DataMisfit.l2_DataMisfit(survey) self.model = model self.mesh = mesh self.survey = survey self.prob = prob self.dobs = dobs self.dmis = dmis
def test_Links(self): m = Mesh.TensorMesh((3, )) expMap = Maps.ExpMap(m) iMap = Maps.IdentityMap(m) PM = MyReciprocalPropMap([('sigma', iMap)]) pm = PM(np.r_[1, 2., 3]) # print pm.sigma # print pm.sigmaMap assert np.all(pm.sigma == [1, 2, 3]) assert np.all(pm.rho == 1. / np.r_[1, 2, 3]) assert pm.sigmaMap is iMap assert pm.rhoMap is None assert pm.sigmaDeriv is not None assert pm.rhoDeriv is not None assert 'sigma' in PM assert 'rho' not in PM assert 'mu' not in PM assert 'mui' not in PM assert 'sigma' in pm assert 'rho' not in pm assert 'mu' not in pm assert 'mui' not in pm assert pm.mu == mu_0 assert pm.mui == 1.0 / mu_0 assert pm.muMap is None assert pm.muDeriv is None assert pm.muiMap is None assert pm.muiDeriv is None PM = MyReciprocalPropMap([('rho', iMap)]) pm = PM(np.r_[1, 2., 3]) # print pm.sigma # print pm.sigmaMap assert np.all(pm.sigma == 1. / np.r_[1, 2, 3]) assert np.all(pm.rho == [1, 2, 3]) assert pm.sigmaMap is None assert pm.rhoMap is iMap assert pm.sigmaDeriv is not None assert pm.rhoDeriv is not None assert 'sigma' not in PM assert 'rho' in PM assert 'mu' not in PM assert 'mui' not in PM assert 'sigma' not in pm assert 'rho' in pm assert 'mu' not in pm assert 'mui' not in pm self.assertRaises(AssertionError, MyReciprocalPropMap, [('rho', iMap), ('sigma', iMap)]) self.assertRaises(AssertionError, MyReciprocalPropMap, [('sigma', iMap), ('rho', iMap)]) MyReciprocalPropMap([('sigma', iMap), ('mu', iMap)]) # This should be fine
def setup(self): self.setup_geometry() self.setup_measurement() # Setup Problem with exponential mapping and Active cells only in the core mesh expmap = Maps.ExpMap(self.mesh) mapactive = Maps.InjectActiveCells(mesh=self.mesh, indActive=self.actind, valInactive=-5.) self.mapping = expmap * mapactive problem = DC.Problem3D_CC(self.mesh, sigmaMap=self.mapping) problem.pair(self.survey.simpeg_survey) problem.Solver = Solver # Compute prediction using the forward model and true conductivity data. # survey.dpred(mtrue[actind]) # Make synthetic data adding a noise to the prediction. # In fact prediction is computed again. self.set_syntetic_conductivity() #self.survey.simpeg_survey.makeSyntheticData(self.mtrue[self.actind], std=0.05, force=True) m = self.mtrue[self.actind] std = 0.05 dtrue = self.survey.simpeg_survey.dpred(m, f=None) noise = std*abs(dtrue)*np.random.randn(*dtrue.shape) self.survey.simpeg_survey.dobs = dtrue+noise self.survey.simpeg_survey.std = dtrue*0 + std
def test_reciprocal(self): expMap = Maps.ExpMap(Mesh.TensorMesh((3, ))) PM = ReciprocalMappingExample() self.assertRaises(AttributeError, getattr, PM, 'sigma') PM.sigmaMap = expMap PM.model = np.r_[1., 2., 3.] assert np.all(PM.sigma == np.exp(np.r_[1., 2., 3.])) assert np.all(PM.rho == 1.0 / np.exp(np.r_[1., 2., 3.])) PM.rho = np.r_[1., 2., 3.] assert PM.rhoMap is None assert PM.sigmaMap is None assert PM.rhoDeriv == 0 assert PM.sigmaDeriv == 0 assert np.all(PM.sigma == 1.0 / np.r_[1., 2., 3.]) PM.sigmaMap = expMap # change your mind? PM = pickle.loads(pickle.dumps(PM)) PM.rhoMap = expMap assert PM._get('sigmaMap') is None assert len(PM.rhoMap) == 1 assert len(PM.sigmaMap) == 2 PM = pickle.loads(pickle.dumps(PM)) assert np.all(PM.rho == np.exp(np.r_[1., 2., 3.])) assert np.all(PM.sigma == 1.0 / np.exp(np.r_[1., 2., 3.])) PM = pickle.loads(pickle.dumps(PM)) assert isinstance(PM.sigmaDeriv.todense(), np.ndarray)
def test_multiMapCompressed(self): m = Mesh.TensorMesh((3, )) expMap = Maps.ExpMap(m) iMap = Maps.IdentityMap(m) PM = MyPropMap({ 'maps': [('sigma', expMap), ('mu', iMap)], 'slices': { 'mu': [0, 1, 2] } }) pm = PM(np.r_[1, 2., 3]) assert pm.nP == 3 assert 'sigma' in PM assert 'mu' in PM assert 'mui' not in PM assert 'sigma' in pm assert 'mu' in pm assert 'mui' not in pm assert np.all(pm.sigmaModel == [1, 2, 3]) assert np.all(pm.sigma == np.exp([1, 2, 3])) assert np.all(pm.muModel == [1, 2, 3]) assert np.all(pm.mu == [1, 2, 3])
def test_nC_residual(self): # x-direction cs, ncx, ncz, npad = 1., 10., 10., 20 hx = [(cs, ncx), (cs, npad, 1.3)] # z direction npad = 12 temp = np.logspace(np.log10(1.), np.log10(12.), 19) temp_pad = temp[-1] * 1.3**np.arange(npad) hz = np.r_[temp_pad[::-1], temp[::-1], temp, temp_pad] mesh = Mesh.CylMesh([hx, 1, hz], '00C') active = mesh.vectorCCz < 0. active = mesh.vectorCCz < 0. actMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz) mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * actMap regMesh = Mesh.TensorMesh([mesh.hz[mapping.maps[-1].indActive]]) reg = Regularization.Simple(regMesh) self.assertTrue(reg._nC_residual == regMesh.nC) self.assertTrue( all([fct._nC_residual == regMesh.nC for fct in reg.objfcts]))
def setUp(self): cs = 10 nc = 20 npad = 10 mesh = Mesh.CylMesh([[(cs, nc), (cs, npad, 1.3)], np.r_[2 * np.pi], [(cs, npad, -1.3), (cs, nc), (cs, npad, 1.3)]]) mesh.x0 = np.r_[0., 0., -mesh.hz[:npad + nc].sum()] # receivers rx_x = np.linspace(10, 200, 20) rx_z = np.r_[-5] rx_locs = Utils.ndgrid([rx_x, np.r_[0], rx_z]) rx_list = [DC.Rx.BaseRx(rx_locs, 'ex')] # sources src_a = np.r_[0., 0., -5.] src_b = np.r_[55., 0., -5.] src_list = [DC.Src.Dipole(rx_list, locA=src_a, locB=src_b)] self.mesh = mesh self.sigma_map = Maps.ExpMap(mesh) * Maps.InjectActiveCells( mesh, mesh.gridCC[:, 2] <= 0, np.log(1e-8)) self.prob = DC.Problem3D_CC(mesh, sigmaMap=self.sigma_map, Solver=Pardiso, bc_type="Dirichlet") self.survey = DC.Survey(src_list) self.prob.pair(self.survey)
def get_analytic(self, sigma, eta, tau, c, src_z, time): from simpegEM1D import (EM1D, EM1DSurveyTD) mesh1D = Mesh.TensorMesh([1]) TDsurvey = EM1DSurveyTD(rx_location=np.array([0., 0., src_z]), src_location=np.array([0., 0., src_z]), topo=np.r_[0., 0., 0.], depth=np.r_[0.], rx_type='dBzdt', wave_type='stepoff', src_type='CircularLoop', a=13., I=1., time=time, half_switch=True) # Convert to Pelton's model tau_p = tau / (1 - eta)**(1. / c) expmap = Maps.ExpMap(mesh1D) prob = EM1D(mesh1D, sigma=np.r_[sigma], eta=np.r_[eta], tau=np.r_[tau_p], c=np.r_[c]) if prob.ispaired: prob.unpair() if TDsurvey.ispaired: TDsurvey.unpair() prob.pair(TDsurvey) prob.chi = np.zeros(TDsurvey.n_layer) dhzdt = TDsurvey.dpred([]) return dhzdt
def setup(self): self.setup_geometry() self.set_syntetic_conductivity() self.setup_measurement() # Setup Problem with exponential mapping and Active cells only in the core mesh expmap = Maps.ExpMap(self.mesh) extrude = Maps.Surject2Dto3D(self.mesh_core, normal='Y') mapactive = Maps.InjectActiveCells(mesh=self.mesh, indActive=self.actind, valInactive=-5.) self.mapping = expmap * mapactive * extrude assert self.mapping.nP == self.mesh_core.nCx * self.mesh_core.nCz problem = DC.Problem3D_CC(self.mesh, sigmaMap=self.mapping) problem.pair(self.survey.simpeg_survey) problem.Solver = SolverLU #problem.Solver = SolverBiCG # Compute prediction using the forward model and true conductivity data. # survey.dpred(mtrue[actind]) # Make synthetic data adding a noise to the prediction. # In fact prediction is computed again. self.survey.simpeg_survey.makeSyntheticData(self.mtrue, std=0.05, force=True)
def test_tripleMultiply(self): M = Mesh.TensorMesh([2, 4], '0C') expMap = Maps.ExpMap(M) vertMap = Maps.SurjectVertical1D(M) actMap = Maps.InjectActiveCells(M, M.vectorCCy <= 0, 10, nC=M.nCy) m = np.r_[1., 2.] t_true = np.exp(np.r_[1, 1, 2, 2, 10, 10, 10, 10.]) self.assertLess( np.linalg.norm((expMap * vertMap * actMap * m) - t_true, np.inf), TOL) self.assertLess( np.linalg.norm(((expMap * vertMap * actMap) * m) - t_true, np.inf), TOL) self.assertLess( np.linalg.norm((expMap * vertMap * (actMap * m)) - t_true, np.inf), TOL) self.assertLess( np.linalg.norm((expMap * (vertMap * actMap) * m) - t_true, np.inf), TOL) self.assertLess( np.linalg.norm(((expMap * vertMap) * actMap * m) - t_true, np.inf), TOL) self.assertRaises(ValueError, lambda: expMap * actMap * vertMap) self.assertRaises(ValueError, lambda: actMap * vertMap * expMap)
def test_mapMultiplication(self): M = Mesh.TensorMesh([2, 3]) expMap = Maps.ExpMap(M) vertMap = Maps.SurjectVertical1D(M) combo = expMap * vertMap m = np.arange(3.0) t_true = np.exp(np.r_[0, 0, 1, 1, 2, 2.]) self.assertLess(np.linalg.norm((combo * m) - t_true, np.inf), TOL) self.assertLess( np.linalg.norm((expMap * vertMap * m) - t_true, np.inf), TOL) self.assertLess( np.linalg.norm(expMap * (vertMap * m) - t_true, np.inf), TOL) self.assertLess( np.linalg.norm((expMap * vertMap) * m - t_true, np.inf), TOL) # Try making a model mod = Models.Model(m, mapping=combo) # print mod.transform # import matplotlib.pyplot as plt # plt.colorbar(M.plotImage(mod.transform)[0]) # plt.show() self.assertLess(np.linalg.norm(mod.transform - t_true, np.inf), TOL) self.assertRaises(Exception, Models.Model, np.r_[1.0], mapping=combo) self.assertRaises(ValueError, lambda: combo * (vertMap * expMap)) self.assertRaises(ValueError, lambda: (combo * vertMap) * expMap) self.assertRaises(ValueError, lambda: vertMap * expMap) self.assertRaises(ValueError, lambda: expMap * np.ones(100)) self.assertRaises(ValueError, lambda: expMap * np.ones((100, 1))) self.assertRaises(ValueError, lambda: expMap * np.ones((100, 5))) self.assertRaises(ValueError, lambda: combo * np.ones(100)) self.assertRaises(ValueError, lambda: combo * np.ones((100, 1))) self.assertRaises(ValueError, lambda: combo * np.ones((100, 5)))
def setUp(self, parallel=True): frequency = np.array([900, 7200, 56000], dtype=float) hz = get_vertical_discretization_frequency( frequency, sigma_background=1./10. ) n_sounding = 10 dx = 20. hx = np.ones(n_sounding) * dx mesh = Mesh.TensorMesh([hx, hz], x0='00') inds = mesh.gridCC[:, 1] < 25 inds_1 = mesh.gridCC[:, 1] < 50 sigma = np.ones(mesh.nC) * 1./100. sigma[inds_1] = 1./10. sigma[inds] = 1./50. sigma_em1d = sigma.reshape(mesh.vnC, order='F').flatten() mSynth = np.log(sigma_em1d) x = mesh.vectorCCx y = np.zeros_like(x) z = np.ones_like(x) * 30. rx_locations = np.c_[x, y, z] src_locations = np.c_[x, y, z] topo = np.c_[x, y, z-30.].astype(float) mapping = Maps.ExpMap(mesh) survey = GlobalEM1DSurveyFD( rx_locations=rx_locations, src_locations=src_locations, frequency=frequency, offset=np.ones_like(frequency) * 8., src_type="VMD", rx_type="Hz", field_type='secondary', topo=topo ) problem = GlobalEM1DProblemFD( [], sigmaMap=mapping, hz=hz, parallel=parallel, n_cpu=5 ) problem.pair(survey) survey.makeSyntheticData(mSynth) # Now set up the problem to do some minimization dmis = DataMisfit.l2_DataMisfit(survey) reg = Regularization.Tikhonov(mesh) opt = Optimization.InexactGaussNewton( maxIterLS=20, maxIter=10, tolF=1e-6, tolX=1e-6, tolG=1e-6, maxIterCG=6 ) invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=0.) 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, parallel=False): frequency = np.array([900, 7200, 56000], dtype=float) hz = np.r_[1.] n_sounding = 10 dx = 20. hx = np.ones(n_sounding) * dx e = np.ones(n_sounding) mSynth = np.r_[e * np.log(1. / 100.), e * 20] x = np.arange(n_sounding) y = np.zeros_like(x) z = np.ones_like(x) * 30. rx_locations = np.c_[x, y, z] src_locations = np.c_[x, y, z] topo = np.c_[x, y, z - 30.].astype(float) wires = Maps.Wires(('sigma', n_sounding), ('h', n_sounding)) expmap = Maps.ExpMap(nP=n_sounding) sigmaMap = expmap * wires.sigma survey = GlobalEM1DSurveyFD(rx_locations=rx_locations, src_locations=src_locations, frequency=frequency, offset=np.ones_like(frequency) * 8., src_type="VMD", rx_type="ppm", field_type='secondary', topo=topo, half_switch=True) problem = GlobalEM1DProblemFD([], sigmaMap=sigmaMap, hMap=wires.h, hz=hz, parallel=parallel, n_cpu=2) problem.pair(survey) survey.makeSyntheticData(mSynth) # Now set up the problem to do some minimization mesh = Mesh.TensorMesh([int(n_sounding * 2)]) dmis = DataMisfit.l2_DataMisfit(survey) reg = Regularization.Tikhonov(mesh) opt = Optimization.InexactGaussNewton(maxIterLS=20, maxIter=10, tolF=1e-6, tolX=1e-6, tolG=1e-6, maxIterCG=6) invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=0.) inv = Inversion.BaseInversion(invProb) self.inv = inv self.reg = reg self.p = problem self.mesh = mesh self.m0 = mSynth * 1.2 self.survey = survey self.dmis = dmis
def run(plotIt=True): """ EM: FDEM: 1D: Inversion ======================= Here we will create and run a FDEM 1D inversion. """ cs, ncx, ncz, npad = 5., 25, 15, 15 hx = [(cs, ncx), (cs, npad, 1.3)] hz = [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)] mesh = Mesh.CylMesh([hx, 1, hz], '00C') layerz = -100. active = mesh.vectorCCz < 0. layer = (mesh.vectorCCz < 0.) & (mesh.vectorCCz >= layerz) actMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz) mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * actMap sig_half = 2e-2 sig_air = 1e-8 sig_layer = 1e-2 sigma = np.ones(mesh.nCz) * sig_air sigma[active] = sig_half sigma[layer] = sig_layer mtrue = np.log(sigma[active]) if plotIt: import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(3, 6)) plt.semilogx(sigma[active], mesh.vectorCCz[active]) ax.set_ylim(-500, 0) ax.set_xlim(1e-3, 1e-1) ax.set_xlabel('Conductivity (S/m)', fontsize=14) ax.set_ylabel('Depth (m)', fontsize=14) ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5) rxOffset = 10. bzi = EM.FDEM.Rx.Point_b(np.array([[rxOffset, 0., 1e-3]]), orientation='z', component='imag') freqs = np.logspace(1, 3, 10) srcLoc = np.array([0., 0., 10.]) srcList = [ EM.FDEM.Src.MagDipole([bzi], freq, srcLoc, orientation='Z') for freq in freqs ] survey = EM.FDEM.Survey(srcList) prb = EM.FDEM.Problem3D_b(mesh, mapping=mapping) try: from pymatsolver import MumpsSolver prb.Solver = MumpsSolver except ImportError, e: prb.Solver = SolverLU
def setUp_TDEM(prbtype='b', rxcomp='bz', waveform='stepoff'): cs = 5. ncx = 8 ncy = 8 ncz = 8 npad = 4 # hx = [(cs, ncx), (cs, npad, 1.3)] # hz = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)] mesh = Mesh.TensorMesh( [ [(cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)], [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)], [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)] ], 'CCC' ) active = mesh.vectorCCz < 0. activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz) mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap prb = getattr(EM.TDEM, 'Problem3D_{}'.format(prbtype))(mesh, sigmaMap=mapping) rxtimes = np.logspace(-4, -3, 20) if waveform.upper() == 'RAW': out = EM.Utils.VTEMFun(prb.times, 0.00595, 0.006, 100) wavefun = interp1d(prb.times, out) t0 = 0.006 waveform = EM.TDEM.Src.RawWaveform(offTime=t0, waveFct=wavefun) prb.timeSteps = [(1e-3, 5), (1e-4, 5), (5e-5, 10), (5e-5, 10), (1e-4, 10)] rxtimes = t0+rxtimes else: waveform = EM.TDEM.Src.StepOffWaveform() prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)] rxOffset = 10. rx = getattr(EM.TDEM.Rx, 'Point_{}'.format(rxcomp[:-1]))( np.array([[rxOffset, 0., -1e-2]]), rxtimes, rxcomp[-1] ) src = EM.TDEM.Src.MagDipole( [rx], loc=np.array([0., 0., 0.]), waveform=waveform ) survey = EM.TDEM.Survey([src]) prb.Solver = Solver m = (np.log(1e-1)*np.ones(prb.sigmaMap.nP) + 1e-2*np.random.rand(prb.sigmaMap.nP)) prb.pair(survey) mesh = mesh return prb, m, mesh
def test_deriv2(self): nP = 100 mapping = Maps.ExpMap(nP=nP) m = np.random.rand(nP) v = np.random.rand(nP) objfct = ObjectiveFunction.L2ObjectiveFunction(nP=nP, mapping=mapping) self.assertTrue( np.allclose(objfct.deriv2(m=m, v=v), objfct.deriv2(m=m) * v))
def fit_colecole_with_se(self, eta_cc=0.8, tau_cc=0.003, c_cc=0.6): def ColeColeSeigel(f, sigmaInf, eta, tau, c): w = 2 * np.pi * f return sigmaInf * (1 - eta / (1 + (1j * w * tau)**c)) # Step1: Fit Cole-Cole with Stretched Exponential function time = np.logspace(-6, np.log10(0.01), 41) wt, tbase, omega_int = DigFilter.setFrequency(time) frequency = omega_int / (2 * np.pi) # Cole-Cole parameters siginf = 1. self.eta_cc = eta_cc self.tau_cc = tau_cc self.c_cc = c_cc sigma = ColeColeSeigel(frequency, siginf, eta_cc, tau_cc, c_cc) sigTCole = DigFilter.transFiltImpulse(sigma, wt, tbase, omega_int, time, tol=1e-12) wires = Maps.Wires(('eta', 1), ('tau', 1), ('c', 1)) taumap = Maps.ExpMap(nP=1) * wires.tau survey = SESurvey() dtrue = -sigTCole survey.dobs = dtrue m1D = Mesh.TensorMesh([np.ones(3)]) prob = SEInvImpulseProblem(m1D, etaMap=wires.eta, tauMap=taumap, cMap=wires.c) update_sens = Directives.UpdateSensitivityWeights() prob.time = time prob.pair(survey) m0 = np.r_[eta_cc, np.log(tau_cc), c_cc] perc = 0.05 dmisfitpeta = DataMisfit.l2_DataMisfit(survey) dmisfitpeta.W = 1 / (abs(survey.dobs) * perc) reg = regularization.Simple(m1D) opt = Optimization.ProjectedGNCG(maxIter=10) invProb = InvProblem.BaseInvProblem(dmisfitpeta, reg, opt) # Create an inversion object target = Directives.TargetMisfit() invProb.beta = 0. inv = Inversion.BaseInversion(invProb, directiveList=[target]) reg.mref = 0. * m0 prob.counter = opt.counter = Utils.Counter() opt.LSshorten = 0.5 opt.remember('xc') opt.tolX = 1e-20 opt.tolF = 1e-20 opt.tolG = 1e-20 opt.eps = 1e-20 mopt = inv.run(m0) return mopt
def setUp(self): time = np.logspace(-3, 0, 21) n_loc = 10 wires = Maps.Wires(('eta', n_loc), ('tau', n_loc), ('c', n_loc)) taumap = Maps.ExpMap(nP=n_loc) * wires.tau etamap = Maps.ExpMap(nP=n_loc) * wires.eta cmap = Maps.ExpMap(nP=n_loc) * wires.c eta0, tau0, c0 = 0.1, 10., 0.5 m0 = np.log(np.r_[eta0 * np.ones(n_loc), tau0 * np.ones(n_loc), c0 * np.ones(n_loc)]) survey = SEMultiSurvey(time=time, locs=np.zeros((n_loc, 3))) m1D = Mesh.TensorMesh([np.ones(int(n_loc * 3))]) prob = SEMultiInvProblem(m1D, etaMap=etamap, tauMap=taumap, cMap=cmap) prob.pair(survey) self.survey = survey self.m0 = m0 self.time = time
def run(plotIt=True): """ Maps: ComboMaps =============== We will use an example where we want a 1D layered earth as our model, but we want to map this to a 2D discretization to do our forward modeling. We will also assume that we are working in log conductivity still, so after the transformation we map to conductivity space. To do this we will introduce the vertical 1D map (:class:`SimPEG.Maps.SurjectVertical1D`), which does the first part of what we just described. The second part will be done by the :class:`SimPEG.Maps.ExpMap` described above. .. code-block:: python :linenos: M = Mesh.TensorMesh([7,5]) v1dMap = Maps.SurjectVertical1D(M) expMap = Maps.ExpMap(M) myMap = expMap * v1dMap m = np.r_[0.2,1,0.1,2,2.9] # only 5 model parameters! sig = myMap * m If you noticed, it was pretty easy to combine maps. What is even cooler is that the derivatives also are made for you (if everything goes right). Just to be sure that the derivative is correct, you should always run the test on the mapping that you create. """ M = Mesh.TensorMesh([7, 5]) v1dMap = Maps.SurjectVertical1D(M) expMap = Maps.ExpMap(M) myMap = expMap * v1dMap m = np.r_[0.2, 1, 0.1, 2, 2.9] # only 5 model parameters! sig = myMap * m if not plotIt: return figs, axs = plt.subplots(1, 2) axs[0].plot(m, M.vectorCCy, 'b-o') axs[0].set_title('Model') axs[0].set_ylabel('Depth, y') axs[0].set_xlabel('Value, $m_i$') axs[0].set_xlim(0, 3) axs[0].set_ylim(0, 1) clbar = plt.colorbar( M.plotImage(sig, ax=axs[1], grid=True, gridOpts=dict(color='grey'))[0]) axs[1].set_title('Physical Property') axs[1].set_ylabel('Depth, y') clbar.set_label('$\sigma = \exp(\mathbf{P}m)$') plt.tight_layout()
def _setupDCProblem(self): expMap = Maps.ExpMap(self.mesh) inactiveCellIndices = numpy.logical_not(self.activeCellIndices) inactiveCellData = self.givenModelCond[inactiveCellIndices] mapActive = Maps.InjectActiveCells(mesh=self.mesh, indActive=self.activeCellIndices, valInactive=inactiveCellData) self.mapping = expMap * mapActive self.DCproblem = DC.Problem3D_CC(self.mesh, sigmaMap=self.mapping) self.DCproblem.pair(self.survey) self.DCproblem.Solver = Solver pass
def setUp(self): print('\nTesting Transect for analytic') cs = 10. ncx, ncy, ncz = 10, 10, 10 npad = 5 freq = 1e2 hx = [(cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)] hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)] hz = [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)] mesh = Mesh.TensorMesh([hx, hy, hz], 'CCC') mapping = Maps.ExpMap(mesh) x = np.linspace(-10, 10, 5) XYZ = Utils.ndgrid(x, np.r_[0], np.r_[0]) rxList = EM.FDEM.Rx.Point_e(XYZ, orientation='x', component='imag') SrcList = [ EM.FDEM.Src.MagDipole([rxList], loc=np.r_[0., 0., 0.], freq=freq), EM.FDEM.Src.CircularLoop([rxList], loc=np.r_[0., 0., 0.], freq=freq, radius=np.sqrt(1. / np.pi)), # EM.FDEM.Src.MagDipole_Bfield([rxList], loc=np.r_[0., 0., 0.], # freq=freq), # less accurate ] survey = EM.FDEM.Survey(SrcList) prb = EM.FDEM.Problem3D_b(mesh, mapping=mapping) prb.pair(survey) try: from pymatsolver import PardisoSolver prb.Solver = PardisoSolver except ImportError: prb.Solver = SolverLU sig = 1e-1 sigma = np.ones(mesh.nC) * sig sigma[mesh.gridCC[:, 2] > 0] = 1e-8 m = np.log(sigma) self.prb = prb self.mesh = mesh self.m = m self.sig = sig print(' starting solve ...') u = self.prb.fields(self.m) print(' ... done') self.u = u
def test_slices(self): expMap = Maps.ExpMap(Mesh.TensorMesh((3, ))) PM = MyPropMap({ 'maps': [('sigma', expMap)], 'slices': { 'sigma': [2, 1, 0] } }) assert PM.sigmaIndex == [2, 1, 0] m = PM(np.r_[1., 2, 3]) assert np.all(m.sigmaModel == np.r_[3, 2, 1]) assert np.all(m.sigma == np.exp(np.r_[3, 2, 1]))