def run(plotIt=True, nFreq=1): """ MT: 3D: Forward =============== Forward model 3D MT data. """ # Make a mesh M = simpeg.Mesh.TensorMesh([[(100,5,-1.5),(100.,10),(100,5,1.5)],[(100,5,-1.5),(100.,10),(100,5,1.5)],[(100,5,1.6),(100.,10),(100,3,2)]], x0=['C','C',-3529.5360]) # Setup the model conds = [1e-2,1] sig = simpeg.Utils.ModelBuilder.defineBlock(M.gridCC,[-1000,-1000,-400],[1000,1000,-200],conds) sig[M.gridCC[:,2]>0] = 1e-8 sig[M.gridCC[:,2]<-600] = 1e-1 sigBG = np.zeros(M.nC) + conds[0] sigBG[M.gridCC[:,2]>0] = 1e-8 ## Setup the the survey object # Receiver locations rx_x, rx_y = np.meshgrid(np.arange(-500,501,50),np.arange(-500,501,50)) rx_loc = np.hstack((simpeg.Utils.mkvc(rx_x,2),simpeg.Utils.mkvc(rx_y,2),np.zeros((np.prod(rx_x.shape),1)))) # Make a receiver list rxList = [] for loc in rx_loc: # NOTE: loc has to be a (1,3) np.ndarray otherwise errors accure for rx_orientation in ['xx','xy','yx','yy']: rxList.append(NSEM.Rx.Point_impedance3D(simpeg.mkvc(loc,2).T,rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_impedance3D(simpeg.mkvc(loc,2).T,rx_orientation, 'imag')) for rx_orientation in ['zx','zy']: rxList.append(NSEM.Rx.Point_tipper3D(simpeg.mkvc(loc,2).T,rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_tipper3D(simpeg.mkvc(loc,2).T,rx_orientation, 'imag')) # Source list srcList =[] for freq in np.logspace(3,-3,nFreq): srcList.append(NSEM.Src.Planewave_xy_1Dprimary(rxList,freq)) # Survey MT survey = NSEM.Survey(srcList) ## Setup the problem object problem = NSEM.Problem3D_ePrimSec(M, sigmaPrimary=sigBG) problem.pair(survey) problem.Solver = Solver # Calculate the data fields = problem.fields(sig) dataVec = survey.eval(fields) # Make the data mtData = NSEM.Data(survey,dataVec) # Add plots if plotIt: pass
def calculateAnalyticSolution(srcList,mesh,model): surveyAna = NSEM.Survey(srcList) data1D = NSEM.Data(surveyAna) for src in surveyAna.srcList: elev = src.rxList[0].locs[0] anaEd, anaEu, anaHd, anaHu = NSEM.Utils.MT1Danalytic.getEHfields(mesh,model,src.freq,elev) anaE = anaEd+anaEu anaH = anaHd+anaHu # Scale the solution # anaE = (anaEtemp/anaEtemp[-1])#.conj() # anaH = (anaHtemp/anaEtemp[-1])#.conj() anaZ = anaE/anaH for rx in src.rxList: data1D[src,rx] = getattr(anaZ, rx.component) return data1D
def DerivJvecTest(halfspace_value, freq=False, expMap=True): survey, sig, sigBG, mesh = NSEM.Utils.testUtils.setup1DSurvey( halfspace_value, False, structure=True) problem = NSEM.Problem1D_ePrimSec(mesh, sigmaPrimary=sigBG, sigmaMap=simpeg.Maps.IdentityMap(mesh)) problem.pair(survey) print('Using {0} solver for the problem'.format(problem.Solver)) print( 'Derivative test of Jvec for eForm primary/secondary for 1d comp from {0} to {1} Hz\n' .format(survey.freqs[0], survey.freqs[-1])) # problem.mapping = simpeg.Maps.ExpMap(problem.mesh) # problem.sigmaPrimary = np.log(sigBG) x0 = sigBG # cond = sig[0] # x0 = np.log(np.ones(problem.mesh.nC)*halfspace_value) # problem.sigmaPrimary = x0 np.random.seed(1983) # if True: # x0 = x0 + np.random.randn(problem.mesh.nC)*halfspace_value*1e-1 survey = problem.survey def fun(x): return survey.dpred(x), lambda x: problem.Jvec(x0, x) return simpeg.Tests.checkDerivative(fun, x0, num=4, plotIt=False, eps=FLR)
def dataMis_AnalyticPrimarySecondary(sigmaHalf): # Make the survey # Primary secondary survey, sig, sigBG, mesh = NSEM.Utils.testUtils.setup1DSurvey(sigmaHalf,False,structure=True) # Analytic data problem = NSEM.Problem1D_ePrimSec(mesh, sigmaPrimary = sig) problem.pair(survey) dataAnaObj = calculateAnalyticSolution(survey.srcList,mesh,sig) data = survey.dpred(sig) dataAna = simpeg.mkvc(dataAnaObj) return np.all((data - dataAna)/dataAna < 2.)
def appRes_psFieldNorm(sigmaHalf): # Make the survey survey, sigma, sigBG, mesh = NSEM.Utils.testUtils.setup1DSurvey(sigmaHalf,False) problem = NSEM.Problem1D_ePrimSec(mesh, sigmaPrimary = sigBG) problem.pair(survey) # Get the fields fields = problem.fields(sigma) # Project the data data = survey.eval(fields) # Calculate the app res and phs app_r = np.array(NSEM.Utils.testUtils.getAppResPhs(data))[:,0] return np.linalg.norm(np.abs(np.log(app_r) - np.log(np.ones(survey.nFreq)/sigmaHalf))*np.log(sigmaHalf))
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) 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 run(plotIt=True): # Setup the forward modeling # Setting up 1D mesh and conductivity models to forward model data. # Frequency nFreq = 26 freqs = np.logspace(2, -3, nFreq) # Set mesh parameters ct = 10 air = simpeg.Utils.meshTensor([(ct, 25, 1.4)]) core = np.concatenate( (np.kron(simpeg.Utils.meshTensor([(ct, 15, -1.2)]), np.ones( (8, ))), simpeg.Utils.meshTensor([(ct, 5)]))) bot = simpeg.Utils.meshTensor([(core[0], 20, -1.4)]) x0 = -np.array([np.sum(np.concatenate((core, bot)))]) # Make the model m1d = simpeg.Mesh.TensorMesh([np.concatenate((bot, core, air))], x0=x0) # Setup model variables active = m1d.vectorCCx < 0. layer1 = (m1d.vectorCCx < -500.) & (m1d.vectorCCx >= -800.) layer2 = (m1d.vectorCCx < -3500.) & (m1d.vectorCCx >= -5000.) # Set the conductivity values sig_half = 1e-2 sig_air = 1e-8 sig_layer1 = .2 sig_layer2 = .2 # Make the true model sigma_true = np.ones(m1d.nCx) * sig_air sigma_true[active] = sig_half sigma_true[layer1] = sig_layer1 sigma_true[layer2] = sig_layer2 # Extract the model m_true = np.log(sigma_true[active]) # Make the background model sigma_0 = np.ones(m1d.nCx) * sig_air sigma_0[active] = sig_half m_0 = np.log(sigma_0[active]) # Set the mapping actMap = simpeg.Maps.InjectActiveCells(m1d, active, np.log(1e-8), nC=m1d.nCx) mappingExpAct = simpeg.Maps.ExpMap(m1d) * actMap # Setup the layout of the survey, set the sources and the connected receivers # Receivers rxList = [] rxList.append( NSEM.Rx.Point_impedance1D(simpeg.mkvc(np.array([-0.5]), 2).T, 'real')) rxList.append( NSEM.Rx.Point_impedance1D(simpeg.mkvc(np.array([-0.5]), 2).T, 'imag')) # Source list srcList = [] for freq in freqs: srcList.append(NSEM.Src.Planewave_xy_1Dprimary(rxList, freq)) # Make the survey survey = NSEM.Survey(srcList) survey.mtrue = m_true # Set the problem problem = NSEM.Problem1D_ePrimSec(m1d, sigmaPrimary=sigma_0, sigmaMap=mappingExpAct) problem.pair(survey) # Forward model data # Project the data survey.dtrue = survey.dpred(m_true) survey.dobs = ( survey.dtrue + 0.01 * abs(survey.dtrue) * np.random.randn(*survey.dtrue.shape)) # Assign uncertainties std = 0.025 # 5% std survey.std = np.abs(survey.dobs * std) # Assign the data weight Wd = 1. / survey.std # Setup the inversion proceedure # Define a counter C = simpeg.Utils.Counter() # Optimization opt = simpeg.Optimization.InexactGaussNewton(maxIter=25) opt.counter = C opt.LSshorten = 0.1 opt.remember('xc') # Data misfit dmis = simpeg.DataMisfit.l2_DataMisfit(survey) dmis.W = Wd # Regularization - with a regularization mesh regMesh = simpeg.Mesh.TensorMesh([m1d.hx[active]], m1d.x0) reg = simpeg.Regularization.Tikhonov(regMesh) reg.mrefInSmooth = True reg.alpha_s = 1e-2 reg.alpha_x = 1. reg.mrefInSmooth = True # Inversion problem invProb = simpeg.InvProblem.BaseInvProblem(dmis, reg, opt) invProb.counter = C # Beta schedule beta = simpeg.Directives.BetaSchedule() beta.coolingRate = 4. beta.coolingFactor = 4. # Initial estimate of beta betaest = simpeg.Directives.BetaEstimate_ByEig(beta0_ratio=10.) # Target misfit stop targmis = simpeg.Directives.TargetMisfit() targmis.target = survey.nD # Create an inversion object directives = [beta, betaest, targmis] inv = simpeg.Inversion.BaseInversion(invProb, directiveList=directives) # Run the inversion mopt = inv.run(m_0) if plotIt: fig = NSEM.Utils.dataUtils.plotMT1DModelData(problem, [mopt]) fig.suptitle('Target - smooth true') fig.axes[0].set_ylim([-10000, 500])
def run(plotIt=True): # nFreq = 13 # freqs = np.logspace(2, -2, nFreq) # # # x and y grid parameters # ctx = 10 #100 # npadx = 22 # incx = 1.3 # nx = [(ctx,npadx,-incx),(ctx,6),(ctx,npadx,incx)] # # # z grid parameters # ct1 = 10 # npad1 = 21 # inc1 = 1.3 # # ct = 10 # npad = 20 # # ct2 = 10 # npad2 = 20 # inc2 = 1.3 nFreq = 13 freqs = np.logspace(2, -2, nFreq) # x and y grid parameters ctx = 10 #100 npadx = 16 incx = 1.5 nx = [(ctx,npadx,-incx),(ctx,6),(ctx,npadx,incx)] # z grid parameters ct1 = 30 npad1 = 15 inc1 = 1.3 ct = 25 npad = 20 ct2 = 1 npad2 = 27 inc2 = 1.3 nz = [(ct1,npad1,-inc1),(ct,npad),(ct2,npad2,inc2)] # Origem do sistema de coordenadas da malha ztop = 0 for i in range(1,npad1+1): ztop += ct1*inc1**(i) ztop += 1.*ct*npad #9*ct # Make a mesh M = simpeg.Mesh.TensorMesh([nx,nx,nz], x0=['C', 'C', -ztop]) #M = simpeg.Mesh.TensorMesh([nx,nx,nz], x0=['C', 'C', 'C']) ccMesh=M.gridCC print(np.size(ccMesh)) #M.setCellGradBC('dirichlet') #print(inspect.signature(M.setCellGradBC)) # visualize input parameters of functions # Setup the model # Profundidade do topo de cada camada (precisa coincidir com a malha!) ztop = M.vectorNz[-1] # zh = np.array([ztop,0.,-200.,-350]) # zh = np.array([ztop,0.,-200.,-300]) # conds = np.array([1e-8,1.,0.01,1.]) #sig = simpeg.Utils.ModelBuilder.layeredModel(ccMesh, zh, conds) conds = [1e-2,1] sig = simpeg.Utils.ModelBuilder.defineBlock( M.gridCC, [-15000, -15000, -350], [15000, 15000, -150], conds) sig[M.gridCC[:, 2] > 0] = 1e-8 #sig[M.gridCC[:, 2] < -1000] = 1 # 1e-1 #sigBG = sig sigBG = np.zeros(M.nC) + conds[1] sigBG[M.gridCC[:, 2] > 0] = 1e-8 if plotIt: fig,axes = plt.subplots(num=1,clear=True) collect_obj, line_obj = M.plotSlice(np.log(sig), grid=True, normal='y',ax=axes) plt.colorbar(collect_obj) plt.show() #%% Setup the layout of the survey, set the sources and the connected receivers # Receiver locations # rx_x, rx_y = np.meshgrid(np.arange(-600, 601, 100), np.arange(-600, 601, 100)) rx_x = np.array([0.]) rx_y = np.array([0.]) #rx_z = np.array([0.]) rx_loc = np.hstack((simpeg.Utils.mkvc(rx_x, 2), simpeg.Utils.mkvc(rx_y, 2), np.zeros((np.prod(rx_x.shape), 1)))) #rx_loc = np.reshape([rx_x,rx_y,rx_z],(1,3)) # Receivers rxList = [] for rx_orientation in ['xx', 'xy', 'yx', 'yy']: rxList.append(NSEM.Rx.Point_impedance3D(rx_loc, rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_impedance3D(rx_loc, rx_orientation, 'imag')) for rx_orientation in ['zx', 'zy']: rxList.append(NSEM.Rx.Point_tipper3D(rx_loc, rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_tipper3D(rx_loc, rx_orientation, 'imag')) # Source list srcList = [] for freq in freqs: srcList.append(NSEM.Src.Planewave_xy_1Dprimary(rxList, freq)) # Make the survey survey = NSEM.Survey(srcList) #survey.mtrue = m_true # Set the problem problem = NSEM.Problem3D_ePrimSec(M, sigma=sig, sigmaPrimary=sigBG) problem.pair(survey) problem.Solver = Solver # Calculate the data fields = problem.fields() dataVec = survey.eval(fields) # # Add uncertainty to the data - 10% standard # # devation and 0 floor # dataVec.standard_deviation.fromvec( # np.ones_like(simpeg.mkvc(dataVec)) * 0.0 # ) # dataVec.floor.fromvec( # np.zeros_like(simpeg.mkvc(dataVec)) # ) if plotIt: #plotting # fig,ax1 = plt.subplots(clear=True) out1 = dataVec.plot_app_res(np.array([0.,0.]),components=['xy','yx'], comp_plot_dict = {'xy':{'marker':'None','ls':'-'}, 'yx':{'marker':'None','ls':'--'} } ) # out1.autoscale(tight=True) # out1.set_yscale('linear') # out1.grid(True) #out1.set_ylim([0.,300.]) mu = 4*math.pi*1E-7; #Magnetic Permeability (H/m) resistivities = np.array([1.,100.,1.]) #[100,10,200] #[300, 2500, 0.8, 3000, 2500]; thicknesses = [150.,200] #[300,300] #[200, 400, 40, 500]; n = len(resistivities); nFreq = 13 frequencies = np.logspace(2, -2, nFreq) #[1,5,10,25,50,100] #data[:,0] ##[0.0001,0.005,0.01,0.05,0.1,0.5,1,5,10,50,100,500,10000]; rhoapp = np.zeros(len(frequencies)) #print('freq\tares\t\t\tphase'); for i,frequency in enumerate(frequencies): w = 2*math.pi*frequency; impedances = list(range(n)); #compute basement impedance impedances[n-1] = cmath.sqrt(w*mu*resistivities[n-1]*1j); for j in range(n-2,-1,-1): resistivity = resistivities[j]; thickness = thicknesses[j]; # 3. Compute apparent resistivity from top layer impedance #Step 2. Iterate from bottom layer to top(not the basement) # Step 2.1 Calculate the intrinsic impedance of current layer dj = cmath.sqrt((w * mu * (1.0/resistivity))*1j); wj = dj * resistivity; # Step 2.2 Calculate Exponential factor from intrinsic impedance ej = cmath.exp(-2*thickness*dj); # Step 2.3 Calculate reflection coeficient using current layer # intrinsic impedance and the below layer impedance belowImpedance = impedances[j + 1]; rj = (wj - belowImpedance)/(wj + belowImpedance); re = rj*ej; Zj = wj * ((1 - re)/(1 + re)); impedances[j] = Zj; # Step 3. Compute apparent resistivity from top layer impedance Z = impedances[0]; absZ = abs(Z); apparentResistivity = (absZ * absZ)/(mu * w); rhoapp[i] = apparentResistivity phase = math.atan2(Z.imag, Z.real) # print(frequency, '\t', apparentResistivity, '\t', phase); #Plot result #fig,ax = plt.subplots(num=1,clear=True) ax = out1 #ax.plot(frequencies,rhoapp,frequencies,data[:,1],'--') ax.plot(frequencies,rhoapp) ax.autoscale(tight=True) ax.legend(('Analytic','Numeric')) ax.set_xlabel('frequency (Hz)') ax.set_ylabel('Apparent Resistivity (Rho.m)') ax.set_xscale('log') ax.set_yscale('linear') ax.invert_xaxis() ax.grid() out1.autoscale(tight=True) out1.set_yscale('linear') out1.grid(True)
# Receivers rxList = [] for rx_orientation in ['xx', 'xy', 'yx', 'yy']: rxList.append(NSEM.Rx.Point_impedance3D(rx_loc, rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_impedance3D(rx_loc, rx_orientation, 'imag')) for rx_orientation in ['zx', 'zy']: rxList.append(NSEM.Rx.Point_tipper3D(rx_loc, rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_tipper3D(rx_loc, rx_orientation, 'imag')) # Source list, srcList = [] for freq in freqs: #srcList.append(NSEM.Src.Planewave_xy_1Dprimary(rxList, freq)) srcList.append(NSEM.Src.Planewave_xy_1Dprimary(rxList, freq, sigBG1d, sigBG)) # Make the survey survey = NSEM.Survey(srcList) #survey.mtrue = m_true # Set the problem problem = NSEM.Problem3D_ePrimSec(M, sigma=sig, sigmaPrimary=sigBG) problem.pair(survey) problem.Solver = Solver # Calculate the data fields = problem.fields() # returns secondary field
def run(plotIt=True): """ MT: 3D: Forward =============== Forward model 3D MT data. """ # Make a mesh M = simpeg.Mesh.TensorMesh([[ (100, 9, -1.5), (100., 13), (100, 9, 1.5) ], [(100, 9, -1.5), (100., 13), (100, 9, 1.5)], [(50, 10, -1.6), (50., 10), (50, 6, 2)]], x0=['C', 'C', -14926.8217]) # Setup the model conds = [1, 1e-2] sig = simpeg.Utils.ModelBuilder.defineBlock(M.gridCC, [-100, -100, -350], [100, 100, -150], conds) sig[M.gridCC[:, 2] > 0] = 1e-8 sig[M.gridCC[:, 2] < -1000] = 1e-1 sigBG = np.zeros(M.nC) + conds[1] sigBG[M.gridCC[:, 2] > 0] = 1e-8 if plotIt: collect_obj, line_obj = M.plotSlice(np.log10(sig), grid=True, normal='X') color_bar = plt.colorbar(collect_obj) # Setup the the survey object # Receiver locations rx_x, rx_y = np.meshgrid(np.arange(-600, 601, 100), np.arange(-600, 601, 100)) rx_loc = np.hstack((simpeg.Utils.mkvc(rx_x, 2), simpeg.Utils.mkvc(rx_y, 2), np.zeros((np.prod(rx_x.shape), 1)))) # Make a receiver list rxList = [] for rx_orientation in ['xx', 'xy', 'yx', 'yy']: rxList.append(NSEM.Rx.Point_impedance3D(rx_loc, rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_impedance3D(rx_loc, rx_orientation, 'imag')) for rx_orientation in ['zx', 'zy']: rxList.append(NSEM.Rx.Point_tipper3D(rx_loc, rx_orientation, 'real')) rxList.append(NSEM.Rx.Point_tipper3D(rx_loc, rx_orientation, 'imag')) # Source list srcList = [ NSEM.Src.Planewave_xy_1Dprimary(rxList, freq) for freq in np.logspace(4, -2, 13) ] # Survey MT survey = NSEM.Survey(srcList) # Setup the problem object problem = NSEM.Problem3D_ePrimSec(M, sigma=sig, sigmaPrimary=sigBG) problem.pair(survey) problem.Solver = Solver # Calculate the data fields = problem.fields() dataVec = survey.eval(fields) # Add uncertainty to the data - 10% standard # devation and 0 floor dataVec.standard_deviation.fromvec( np.ones_like(simpeg.mkvc(dataVec)) * 0.1) dataVec.floor.fromvec(np.zeros_like(simpeg.mkvc(dataVec))) # Add plots if plotIt: # Plot the data # On and off diagonal (on left and right axis, respectively) fig, axes = plt.subplots(2, 1, figsize=(7, 5)) plt.subplots_adjust(right=0.8) [(ax.invert_xaxis(), ax.set_xscale('log')) for ax in axes] ax_r, ax_p = axes ax_r.set_yscale('log') ax_r.set_ylabel('Apparent resistivity [xy-yx]') ax_r_on = ax_r.twinx() ax_r_on.set_yscale('log') ax_r_on.set_ylabel('Apparent resistivity [xx-yy]') ax_p.set_ylabel('Apparent phase') ax_p.set_xlabel('Frequency [Hz]') # Start plotting ax_r = dataVec.plot_app_res(np.array([-200, 0]), components=['xy', 'yx'], ax=ax_r, errorbars=True) ax_r_on = dataVec.plot_app_res(np.array([-200, 0]), components=['xx', 'yy'], ax=ax_r_on, errorbars=True) ax_p = dataVec.plot_app_phs(np.array([-200, 0]), components=['xx', 'xy', 'yx', 'yy'], ax=ax_p, errorbars=True) ax_p.legend(bbox_to_anchor=(1.05, 1), loc=2)