def test_Problem2D_N(self): problemDC = DC.Problem2D_N(self.mesh, sigmaMap=Maps.IdentityMap(self.mesh)) problemDC.Solver = Solver problemDC.pair(self.surveyDC) data0 = self.surveyDC.dpred(self.sigma0) datainf = self.surveyDC.dpred(self.sigmaInf) problemIP = IP.Problem2D_N( self.mesh, sigma=self.sigmaInf, etaMap=Maps.IdentityMap(self.mesh), ) problemIP.Solver = Solver surveyIP = IP.Survey(self.srcLists_ip) problemIP.pair(surveyIP) data_full = data0 - datainf data = surveyIP.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 Problem2D_N is passed") print(err) else: passed = False print(">> IP forward test for Problem2D_N is failed") self.assertTrue(passed)
def test_Problem3D_CC(self): problemDC = DC.Problem3D_CC( self.mesh, sigmaMap=Maps.IdentityMap(self.mesh) ) problemDC.Solver = Solver problemDC.pair(self.surveyDC) data0 = self.surveyDC.dpred(self.sigma0) finf = problemDC.fields(self.sigmaInf) datainf = self.surveyDC.dpred(self.sigmaInf, f=finf) problemIP = IP.Problem3D_CC( self.mesh, rho=1./self.sigmaInf, etaMap=Maps.IdentityMap(self.mesh), Ainv=problemDC.Ainv, f=finf ) problemIP.Solver = Solver surveyIP = IP.Survey([self.src]) problemIP.pair(surveyIP) data_full = data0 - datainf data = surveyIP.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 Problem3D_CC is passed") else: passed = False print(">> IP forward test for Problem3D_CC is failed") self.assertTrue(passed)
def test_Problem2D_CC(self): problemDC = DC.Problem2D_CC(self.mesh, rhoMap=Maps.IdentityMap(self.mesh)) problemDC.Solver = Solver problemDC.pair(self.surveyDC) data0 = self.surveyDC.dpred(1. / self.sigma0) finf = problemDC.fields(1. / self.sigmaInf) datainf = self.surveyDC.dpred(1. / self.sigmaInf, f=finf) problemIP = IP.Problem2D_CC(self.mesh, rho=1. / self.sigmaInf, etaMap=Maps.IdentityMap(self.mesh)) problemIP.Solver = Solver surveyIP = IP.Survey(self.srcLists_ip) problemIP.pair(surveyIP) data_full = data0 - datainf data = surveyIP.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 Problem2D_CC is passed") else: import matplotlib.pyplot as plt passed = False print(">> IP forward test for Problem2D_CC is failed") print(err) plt.plot(data_full) plt.plot(data, 'k.') plt.show() self.assertTrue(passed)
def setUp(self): cs = 25. hx = [(cs, 0, -1.3), (cs, 21), (cs, 0, 1.3)] hy = [(cs, 0, -1.3), (cs, 21), (cs, 0, 1.3)] hz = [(cs, 0, -1.3), (cs, 20)] mesh = Mesh.TensorMesh([hx, hy, hz], x0="CCN") blkind0 = Utils.ModelBuilder.getIndicesSphere( np.r_[-100., -100., -200.], 75., mesh.gridCC) blkind1 = Utils.ModelBuilder.getIndicesSphere(np.r_[100., 100., -200.], 75., mesh.gridCC) sigma = np.ones(mesh.nC) * 1e-2 eta = np.zeros(mesh.nC) tau = np.ones_like(sigma) * 1. eta[blkind0] = 0.1 eta[blkind1] = 0.1 tau[blkind0] = 0.1 tau[blkind1] = 0.01 x = mesh.vectorCCx[(mesh.vectorCCx > -155.) & (mesh.vectorCCx < 155.)] y = mesh.vectorCCx[(mesh.vectorCCy > -155.) & (mesh.vectorCCy < 155.)] Aloc = np.r_[-200., 0., 0.] Bloc = np.r_[200., 0., 0.] M = Utils.ndgrid(x - 25., y, np.r_[0.]) N = Utils.ndgrid(x + 25., y, np.r_[0.]) times = np.arange(10) * 1e-3 + 1e-3 rx = SIP.Rx.Dipole(M, N, times) src = SIP.Src.Dipole([rx], Aloc, Bloc) survey = SIP.Survey([src]) colemap = [("eta", Maps.IdentityMap(mesh)), ("taui", Maps.IdentityMap(mesh))] problem = SIP.Problem3D_N(mesh, sigma=sigma, mapping=colemap) problem.Solver = Solver problem.pair(survey) mSynth = np.r_[eta, 1. / tau] 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=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 test_vangenuchten_theta_m(self): mesh = Mesh.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 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_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 test_regularization(self): for R in dir(Regularization): r = getattr(Regularization, R) if not inspect.isclass(r): continue if not issubclass(r, ObjectiveFunction.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 __init__(self, mesh, **kwargs): super(Problem_Linear, self).__init__(mesh, **kwargs) nAct = list(self.indActive).count(True) if self.xiMap is None: self.xiMap = Maps.IdentityMap(nP=nAct)
def setupSecondaryProblem(self, mapping=None): print('Setting up Secondary Problem') if mapping is None: mapping = [('sigma', Maps.IdentityMap(self.meshs))] sec_problem = FDEM.Problem3D_e(self.meshs, sigmaMap=mapping) sec_problem.Solver = Solver print('... done setting up secondary problem') return sec_problem
def halfSpaceProblemAnaVMDDiff(showIt=False, waveformType="STEPOFF"): cs, ncx, ncz, npad = 20., 25, 25, 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') sighalf = 1e-2 siginf = np.ones(mesh.nC) * 1e-8 siginf[mesh.gridCC[:, -1] < 0.] = sighalf eta = np.ones(mesh.nC) * 0.2 tau = np.ones(mesh.nC) * 0.005 c = np.ones(mesh.nC) * 0.7 m = np.r_[siginf, eta, tau, c] iMap = Maps.IdentityMap(nP=int(mesh.nC)) maps = [('sigmaInf', iMap), ('eta', iMap), ('tau', iMap), ('c', iMap)] prb = ProblemATEMIP_b(mesh, mapping=maps) if waveformType == "GENERAL": # timeon = np.cumsum(np.r_[np.ones(10)*1e-3, np.ones(10)*5e-4, np.ones(10)*1e-4]) timeon = np.cumsum(np.r_[np.ones(10) * 1e-3, np.ones(10) * 5e-4, np.ones(10) * 1e-4]) timeon -= timeon.max() timeoff = np.cumsum(np.r_[np.ones(20) * 1e-5, np.ones(20) * 1e-4, np.ones(20) * 1e-3]) time = np.r_[timeon, timeoff] current_on = np.ones_like(timeon) current_on[[0, -1]] = 0. current = np.r_[current_on, np.zeros_like(timeoff)] wave = np.c_[time, current] prb.waveformType = "GENERAL" prb.currentwaveform(wave) prb.t0 = time.min() elif waveformType == "STEPOFF": prb.timeSteps = [(1e-5, 20), (1e-4, 20), (1e-3, 10)] offset = 20. tobs = np.logspace(-4, -2, 21) rx = EM.TDEM.RxTDEM(np.array([[offset, 0., 0.]]), tobs, "bz") src = EM.TDEM.SrcTDEM_VMD_MVP([rx], np.array([[0., 0., 0.]]), waveformType=waveformType) survey = EM.TDEM.SurveyTDEM([src]) prb.Solver = MumpsSolver prb.pair(survey) out = survey.dpred(m) bz_ana = mu_0 * hzAnalyticDipoleT_CC( offset, rx.times, sigmaInf=sighalf, eta=eta[0], tau=tau[0], c=c[0]) err = np.linalg.norm(bz_ana - out) / np.linalg.norm(bz_ana) print '>> Relative error = ', err if showIt: plt.loglog(rx.times, abs(bz_ana), 'k') plt.loglog(rx.times, abs(out), 'b.') plt.show() return err
def run(plotIt=True): M = Mesh.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.RichardsProblem(M, hydraulic_conductivity=k_fun, water_retention=theta_fun, boundary_conditions=bc, initial_conditions=h, do_newton=False, method=method) prob.timeSteps = 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): mesh = Mesh.TensorMesh([20, 20, 20], "CCN") sigma = np.ones(mesh.nC) * 1. / 100. actind = mesh.gridCC[:, 2] < -0.2 # actMap = Maps.InjectActiveCells(mesh, actind, 0.) xyzM = Utils.ndgrid( np.ones_like(mesh.vectorCCx[:-1]) * -0.4, np.ones_like(mesh.vectorCCy) * -0.4, np.r_[-0.3]) xyzN = Utils.ndgrid(mesh.vectorCCx[1:], mesh.vectorCCy, np.r_[-0.3]) problem = SP.Problem_CC(mesh, sigma=sigma, qMap=Maps.IdentityMap(mesh), Solver=PardisoSolver) rx = SP.Rx.Dipole(xyzN, xyzM) src = SP.Src.StreamingCurrents([rx], L=np.ones(mesh.nC), mesh=mesh, modelType="CurrentSource") survey = SP.Survey([src]) survey.pair(problem) q = np.zeros(mesh.nC) inda = Utils.closestPoints(mesh, np.r_[-0.5, 0., -0.8]) indb = Utils.closestPoints(mesh, np.r_[0.5, 0., -0.8]) q[inda] = 1. q[indb] = -1. mSynth = q.copy() survey.makeSyntheticData(mSynth) # Now set up the problem to do some minimization dmis = DataMisfit.l2_DataMisfit(survey) reg = Regularization.Simple(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=1e-2) 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 test_Projections(self): m = Mesh.TensorMesh((3, )) iMap = Maps.IdentityMap(m) PM = MyReciprocalPropMap([('sigma', iMap)]) v = np.r_[1, 2., 3] pm = PM(v) assert pm.sigmaProj is not None assert pm.rhoProj is None assert pm.muProj is None assert pm.muiProj is None assert np.all(pm.sigmaProj * v == pm.sigmaModel)
def test_mref_is_zero(self): mesh = Mesh.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 test_regularization_ActiveCells(self): for R in dir(Regularization): r = getattr(Regularization, R) if not inspect.isclass(r): continue if not issubclass(r, ObjectiveFunction.BaseObjectiveFunction): continue if r.__name__ in IGNORE_ME: continue for i, mesh in enumerate(self.meshlist): 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 setUp(self): cs = 12.5 hx = [(cs, 7, -1.3), (cs, 61), (cs, 7, 1.3)] hy = [(cs, 7, -1.3), (cs, 20)] mesh = Mesh.TensorMesh([hx, hy], x0="CN") # x = np.linspace(-200, 200., 20) x = np.linspace(-200, 200., 2) M = Utils.ndgrid(x - 12.5, np.r_[0.]) N = Utils.ndgrid(x + 12.5, np.r_[0.]) A0loc = np.r_[-150, 0.] A1loc = np.r_[-130, 0.] B0loc = np.r_[-130, 0.] B1loc = np.r_[-110, 0.] rx = DC.Rx.Dipole_ky(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. problem = IP.Problem2D_CC(mesh, sigma=sigma, etaMap=Maps.IdentityMap(mesh), verbose=False) problem.pair(survey) mSynth = np.ones(mesh.nC) * 0.1 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=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): # Define sphere parameters self.rad = 2. self.rho = 0.1 # Define a mesh cs = 0.2 hxind = [(cs, 21)] hyind = [(cs, 21)] hzind = [(cs, 21)] mesh = Mesh.TensorMesh([hxind, hyind, hzind], 'CCC') # Get cells inside the sphere sph_ind = PF.MagAnalytics.spheremodel(mesh, 0., 0., 0., self.rad) # Adjust density for volume difference Vratio = (4./3.*np.pi*self.rad**3.) / (np.sum(sph_ind)*cs**3.) 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, 21) yr = np.linspace(-20, 20, 21) X, Y = np.meshgrid(xr, yr) # Move obs plane 2 radius away from sphere Z = np.ones((xr.size, yr.size))*2.*self.rad self.locXyz = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)] rxLoc = PF.BaseGrav.RxObs(self.locXyz) srcField = PF.BaseGrav.SrcField([rxLoc]) self.survey = PF.BaseGrav.LinearSurvey(srcField) self.prob_x = PF.Gravity.GravityIntegral(mesh, rhoMap=idenMap, actInd=sph_ind, forwardOnly=True, rx_type='x') self.prob_y = PF.Gravity.GravityIntegral(mesh, rhoMap=idenMap, actInd=sph_ind, forwardOnly=True, rx_type='y') self.prob_z = PF.Gravity.GravityIntegral(mesh, rhoMap=idenMap, actInd=sph_ind, forwardOnly=True, rx_type='z')
def setUp(self): # Define inducing field and sphere parameters H0 = (50000., 60., 270.) self.b0 = PF.MagAnalytics.IDTtoxyz(-H0[1], H0[2], H0[0]) self.rad = 2. self.chi = 0.01 # Define a mesh cs = 0.2 hxind = [(cs, 21)] hyind = [(cs, 21)] hzind = [(cs, 21)] mesh = Mesh.TensorMesh([hxind, hyind, hzind], 'CCC') # Get cells inside the sphere sph_ind = PF.MagAnalytics.spheremodel(mesh, 0., 0., 0., self.rad) # Adjust susceptibility for volume difference Vratio = (4. / 3. * np.pi * self.rad**3.) / (np.sum(sph_ind) * cs**3.) 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, 21) yr = np.linspace(-20, 20, 21) X, Y = np.meshgrid(xr, yr) # Move obs plane 2 radius away from sphere Z = np.ones((xr.size, yr.size)) * 2. * self.rad self.locXyz = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)] rxLoc = PF.BaseMag.RxObs(self.locXyz) srcField = PF.BaseMag.SrcField([rxLoc], param=H0) self.survey = PF.BaseMag.LinearSurvey(srcField) self.prob_xyz = PF.Magnetics.MagneticIntegral(mesh, mapping=idenMap, actInd=sph_ind, forwardOnly=True, rtype='xyz') self.prob_tmi = PF.Magnetics.MagneticIntegral(mesh, mapping=idenMap, actInd=sph_ind, forwardOnly=True, rtype='tmi')
def test_haverkamp_k_m(self): mesh = Mesh.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 get_problem_survey(self, nx=20, ny=20, dx=10, dy=20): hx = np.ones(nx) * dx hy = np.ones(ny) * dy self._mesh = Mesh.TensorMesh([hx, hy]) y = np.linspace(0, 400, 10) self._src_locations = np.c_[y * 0 + self._mesh.vectorCCx[0], y] self._rx_locations = np.c_[y * 0 + self._mesh.vectorCCx[-1], y] rx = StraightRay.Rx(self._rx_locations, None) srcList = [ StraightRay.Src(loc=self._src_locations[i, :], rxList=[rx]) for i in range(y.size) ] self._survey = StraightRay.Survey(srcList) self._problem = StraightRay.Problem(self._mesh, slownessMap=Maps.IdentityMap( self._mesh)) self._problem.pair(self._survey)
def setUp(self): mesh = Mesh.TensorMesh([4, 4, 4]) # Magnetic inducing field parameter (A,I,D) B = [50000, 90, 0] # Create a MAGsurvey rx = PF.BaseMag.RxObs( np.vstack([[0.25, 0.25, 0.25], [-0.25, -0.25, 0.25]])) srcField = PF.BaseMag.SrcField([rx], param=(B[0], B[1], B[2])) survey = PF.BaseMag.LinearSurvey(srcField) # Create the forward model operator prob = PF.Magnetics.MagneticIntegral(mesh, chiMap=Maps.IdentityMap(mesh)) # Pair the survey and problem survey.pair(prob) # Compute forward model some data m = np.random.rand(mesh.nC) survey.makeSyntheticData(m) reg = Regularization.Sparse(mesh) reg.mref = np.zeros(mesh.nC) wr = np.sum(prob.G**2., axis=0)**0.5 reg.cell_weights = wr reg.norms = [0, 1, 1, 1] reg.eps_p, reg.eps_q = 1e-3, 1e-3 # Data misfit function dmis = DataMisfit.l2_DataMisfit(survey) dmis.W = 1. / survey.std # Add directives to the inversion opt = Optimization.ProjectedGNCG(maxIter=2, lower=-10., upper=10., maxIterCG=2) invProb = InvProblem.BaseInvProblem(dmis, reg, opt) self.mesh = mesh self.invProb = invProb
def setUp(self): aSpacing = 2.5 nElecs = 10 surveySize = nElecs * aSpacing - aSpacing cs = surveySize / nElecs / 4 mesh = Mesh.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') srcList = DC.Utils.WennerSrcList(nElecs, aSpacing, in2D=True) survey = DC.Survey(srcList) problem = DC.Problem3D_N(mesh, rhoMap=Maps.IdentityMap(mesh), storeJ=True) problem.pair(survey) mSynth = np.ones(mesh.nC) 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=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 test_vangenuchten_k_m(self): mesh = Mesh.TensorMesh([50]) expmap = Maps.ExpMap(nP=mesh.nC) idnmap = Maps.IdentityMap(nP=mesh.nC) seeds = { 'Ks': np.random.triangular( np.log(1e-7), np.log(1e-6), np.log(1e-5), mesh.nC ), 'I': np.random.rand(mesh.nC), 'n': np.random.rand(mesh.nC) + 1, 'alpha': np.random.rand(mesh.nC), } opts = [ ('Ks', dict(KsMap=expmap), 1), ('I', dict(IMap=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_k(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_k test m deriv: ', name) passed = checkDerivative( fun, x0, plotIt=False ) self.assertTrue(passed, True)
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 = Mesh.TensorMesh([hx, hy], x0="CN") x = np.linspace(-135, 250., 20) M = Utils.ndgrid(x - 12.5, np.r_[0.]) N = Utils.ndgrid(x + 12.5, np.r_[0.]) A0loc = np.r_[-150, 0.] A1loc = np.r_[-130, 0.] rxloc = [np.c_[M, np.zeros(20)], np.c_[N, np.zeros(20)]] rx = DC.Rx.Dipole_ky(M, N) src0 = DC.Src.Pole([rx], A0loc) src1 = DC.Src.Pole([rx], A1loc) survey = DC.Survey_ky([src0, src1]) problem = DC.Problem2D_N(mesh, mapping=[('rho', Maps.IdentityMap(mesh))]) problem.pair(survey) mSynth = np.ones(mesh.nC) * 1. 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=1e0) 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): nC = 20 M = Mesh.TensorMesh([nC, nC]) y = np.linspace(0., 1., nC / 2) rlocs = np.c_[y * 0 + M.vectorCCx[-1], y] rx = StraightRay.Rx(rlocs, None) srcList = [ StraightRay.Src(loc=np.r_[M.vectorCCx[0], yi], rxList=[rx]) for yi in y ] survey = StraightRay.Survey(srcList) problem = StraightRay.Problem(M, slownessMap=Maps.IdentityMap(M)) problem.pair(survey) self.M = M self.problem = problem self.survey = survey
def test_multiMap(self): m = Mesh.TensorMesh((3, )) expMap = Maps.ExpMap(m) iMap = Maps.IdentityMap(m) PM = MyPropMap([('sigma', expMap), ('mu', iMap)]) pm = PM(np.r_[1., 2, 3, 4, 5, 6]) assert pm.nP == 6 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 == [4., 5, 6]) assert np.all(pm.mu == [4., 5, 6])
def JvecAdjointTest(sigmaHalf, formulation='PrimSec'): forType = 'PrimSec' not in formulation survey, sigma, sigBG, m1d = NSEM.Utils.testUtils.setup1DSurvey(sigmaHalf,tD=forType,structure=False) print('Adjoint test of e formulation for {:s} comp \n'.format(formulation)) if 'PrimSec' in formulation: problem = NSEM.Problem1D_ePrimSec(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
np.r_[-20, -20, -10], np.r_[20, 20, 25], mesh.gridCC, )[0] # Assign magnetization values model[ind, :] = np.kron(np.ones((ind.shape[0], 1)), M_xyz * 0.05) # Remove air cells model = model[actv, :] # Create active map to go from reduce set to full actvMap = Maps.InjectActiveCells(mesh, actv, np.nan) # Creat reduced identity map idenMap = Maps.IdentityMap(nP=nC * 3) # Create the forward model operator prob = PF.Magnetics.MagneticIntegral(mesh, chiMap=idenMap, actInd=actv, modelType='vector') # Pair the survey and problem survey.pair(prob) # Compute some data and add some random noise data = prob.fields(Utils.mkvc(model)) std = 5 # nT data += np.random.randn(len(data)) * std wd = np.ones(len(data)) * std
def run(plotIt=True): """ Mesh: Plotting with defining range ================================== When using a large Mesh with the cylindrical code, it is advantageous to define a :code:`range_x` and :code:`range_y` when plotting with vectors. In this case, only the region inside of the range is interpolated. In particular, you often want to ignore padding cells. """ # ## Model Parameters # # We define a # - resistive halfspace and # - conductive sphere # - radius of 30m # - center is 50m below the surface # electrical conductivities in S/m sig_halfspace = 1e-6 sig_sphere = 1e0 sig_air = 1e-8 # depth to center, radius in m sphere_z = -50. sphere_radius = 30. # ## Survey Parameters # # - Transmitter and receiver 20m above the surface # - Receiver offset from transmitter by 8m horizontally # - 25 frequencies, logaritmically between $10$ Hz and $10^5$ Hz boom_height = 20. rx_offset = 8. freqs = np.r_[1e1, 1e5] # source and receiver location in 3D space src_loc = np.r_[0., 0., boom_height] rx_loc = np.atleast_2d(np.r_[rx_offset, 0., boom_height]) # print the min and max skin depths to make sure mesh is fine enough and # extends far enough def skin_depth(sigma, f): return 500. / np.sqrt(sigma * f) print('Minimum skin depth (in sphere): {:.2e} m '.format( skin_depth(sig_sphere, freqs.max()))) print('Maximum skin depth (in background): {:.2e} m '.format( skin_depth(sig_halfspace, freqs.min()))) # ## Mesh # # Here, we define a cylindrically symmetric tensor mesh. # # ### Mesh Parameters # # For the mesh, we will use a cylindrically symmetric tensor mesh. To # construct a tensor mesh, all that is needed is a vector of cell widths in # the x and z-directions. We will define a core mesh region of uniform cell # widths and a padding region where the cell widths expand "to infinity". # x-direction csx = 2 # core mesh cell width in the x-direction ncx = np.ceil( 1.2 * sphere_radius / csx ) # number of core x-cells (uniform mesh slightly beyond sphere radius) npadx = 50 # number of x padding cells # z-direction csz = 1 # core mesh cell width in the z-direction ncz = np.ceil( 1.2 * (boom_height - (sphere_z - sphere_radius)) / csz ) # number of core z-cells (uniform cells slightly below bottom of sphere) npadz = 52 # number of z padding cells # padding factor (expand cells to infinity) pf = 1.3 # cell spacings in the x and z directions hx = Utils.meshTensor([(csx, ncx), (csx, npadx, pf)]) hz = Utils.meshTensor([(csz, npadz, -pf), (csz, ncz), (csz, npadz, pf)]) # define a SimPEG mesh mesh = Mesh.CylMesh([hx, 1, hz], x0=np.r_[0., 0., -hz.sum() / 2. - boom_height]) # ### Plot the mesh # # Below, we plot the mesh. The cyl mesh is rotated around x=0. Ensure that # each dimension extends beyond the maximum skin depth. # # Zoom in by changing the xlim and zlim. # X and Z limits we want to plot to. Try xlim = np.r_[0., 2.5e6] zlim = np.r_[-2.5e6, 2.5e6] fig, ax = plt.subplots(1, 1) mesh.plotGrid(ax=ax) ax.set_title('Simulation Mesh') ax.set_xlim(xlim) ax.set_ylim(zlim) print('The maximum skin depth is (in background): {:.2e} m. ' 'Does the mesh go sufficiently past that?'.format( skin_depth(sig_halfspace, freqs.min()))) # ## Put Model on Mesh # # Now that the model parameters and mesh are defined, we can define # electrical conductivity on the mesh. # # The electrical conductivity is defined at cell centers when using the # finite volume method. So here, we define a vector that contains an # electrical conductivity value for every cell center. # create a vector that has one entry for every cell center sigma = sig_air * np.ones( mesh.nC) # start by defining the conductivity of the air everwhere sigma[mesh.gridCC[:, 2] < 0.] = sig_halfspace # assign halfspace cells below the earth # indices of the sphere (where (x-x0)**2 + (z-z0)**2 <= R**2) sphere_ind = ((mesh.gridCC[:, 0]**2 + (mesh.gridCC[:, 2] - sphere_z)**2) <= sphere_radius**2) sigma[sphere_ind] = sig_sphere # assign the conductivity of the sphere # Plot a cross section of the conductivity model fig, ax = plt.subplots(1, 1) cb = plt.colorbar(mesh.plotImage(np.log10(sigma), ax=ax, mirror=True)[0]) # plot formatting and titles cb.set_label('$\log_{10}\sigma$', fontsize=13) ax.axis('equal') ax.set_xlim([-120., 120.]) ax.set_ylim([-100., 30.]) ax.set_title('Conductivity Model') # ## Set up the Survey # # Here, we define sources and receivers. For this example, the receivers # are magnetic flux recievers, and are only looking at the secondary field # (eg. if a bucking coil were used to cancel the primary). The source is a # vertical magnetic dipole with unit moment. # Define the receivers, we will sample the real secondary magnetic flux # density as well as the imaginary magnetic flux density bz_r = FDEM.Rx.Point_bSecondary( locs=rx_loc, orientation='z', component='real') # vertical real b-secondary bz_i = FDEM.Rx.Point_b( locs=rx_loc, orientation='z', component='imag') # vertical imag b (same as b-secondary) rxList = [bz_r, bz_i] # list of receivers # Define the list of sources - one source for each frequency. The source is # a point dipole oriented in the z-direction srcList = [ FDEM.Src.MagDipole(rxList, f, src_loc, orientation='z') for f in freqs ] print( 'There are {nsrc} sources (same as the number of frequencies - {nfreq}). ' 'Each source has {nrx} receivers sampling the resulting b-fields'. format(nsrc=len(srcList), nfreq=len(freqs), nrx=len(rxList))) # ## Set up Forward Simulation # # A forward simulation consists of a paired SimPEG problem and Survey. # For this example, we use the E-formulation of Maxwell's equations, # solving the second-order system for the electric field, which is defined # on the cell edges of the mesh. This is the `prob` variable below. The # `survey` takes the source list which is used to construct the RHS for the # problem. The source list also contains the receiver information, so the # `survey` knows how to sample fields and fluxes that are produced by # solving the `prob`. # define a problem - the statement of which discrete pde system we want to # solve prob = FDEM.Problem3D_e(mesh, sigmaMap=Maps.IdentityMap(mesh)) prob.solver = Solver survey = FDEM.Survey(srcList) # tell the problem and survey about each other - so the RHS can be # constructed for the problem and the # resulting fields and fluxes can be sampled by the receiver. prob.pair(survey) # ### Solve the forward simulation # # Here, we solve the problem for the fields everywhere on the mesh. fields = prob.fields(sigma) # ### Plot the fields # # Lets look at the physics! # log-scale the colorbar from matplotlib.colors import LogNorm fig, ax = plt.subplots(1, 2, figsize=(12, 6)) def plotMe(field, ax): plt.colorbar(mesh.plotImage(field, vType='F', view='vec', range_x=[-100., 100.], range_y=[-180., 60.], pcolorOpts={ 'norm': LogNorm(), 'cmap': plt.get_cmap('viridis') }, streamOpts={'color': 'k'}, ax=ax, mirror=True)[0], ax=ax) plotMe(fields[srcList[0], 'bSecondary'].real, ax[0]) ax[0].set_title('Real B-Secondary, {}Hz'.format(freqs[0])) plotMe(fields[srcList[1], 'bSecondary'].real, ax[1]) ax[1].set_title('Real B-Secondary, {}Hz'.format(freqs[1])) plt.tight_layout() if plotIt: plt.show()