def test_adjoint(self): # Adjoint Test u = np.random.rand(self.mesh.nC*self.survey.nSrc) v = np.random.rand(self.mesh.nC*2) w = np.random.rand(self.survey.dobs.shape[0]) wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-10 print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed)
def test_adjoint(self): # Adjoint Test u = np.random.rand(self.mesh.nC * self.survey.nSrc) v = np.random.rand(self.mesh.nC * 2) w = np.random.rand(self.survey.dobs.shape[0]) wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-10 print 'Adjoint Test', np.abs(wtJv - vtJtw), passed self.assertTrue(passed)
def mycmp(c1,c2): if c1.x0.size == 2: if np.abs(c1.x0[1] - c2.x0[1]) < eps: return c1.x0[0] - c2.x0[0] return c1.x0[1] - c2.x0[1] elif c1.x0.size == 3: if np.abs(c1.x0[2] - c2.x0[2]) < eps: if np.abs(c1.x0[1] - c2.x0[1]) < eps: return c1.x0[0] - c2.x0[0] return c1.x0[1] - c2.x0[1] return c1.x0[2] - c2.x0[2]
def appResNorm(sigmaHalf): nFreq = 26 m1d = Mesh.TensorMesh([[(100,5,1.5),(100.,10),(100,5,1.5)]], x0=['C']) sigma = np.zeros(m1d.nC) + sigmaHalf sigma[m1d.gridCC[:]>200] = 1e-8 # Calculate the analytic fields freqs = np.logspace(4,-4,nFreq) Z = [] for freq in freqs: Ed, Eu, Hd, Hu = NSEM.Utils.getEHfields(m1d,sigma,freq,np.array([200])) Z.append((Ed + Eu)/(Hd + Hu)) Zarr = np.concatenate(Z) app_r, app_p = NSEM.Utils.appResPhs(freqs,Zarr) return np.linalg.norm(np.abs(app_r - np.ones(nFreq)/sigmaHalf)) / np.log10(sigmaHalf)
def testOnes(self): Adiagtest = diagEst(self.A, self.n, self.n) r = np.abs(Adiagtest - self.Adiag) self.assertTrue(r.dot(r) < TOL)
def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None): """ Read list of 2D tx-rx location and plot a speudo-section of apparent resistivity. Assumes flat topo for now... Input: :param d2D, z0 :switch stype -> Either 'pdp' (pole-dipole) | 'dpdp' (dipole-dipole) :switch dtype=-> Either 'appr' (app. res) | 'appc' (app. con) | 'volt' (potential) Output: :figure scatter plot overlayed on image Edited Feb 17th, 2016 @author: dominiquef """ from SimPEG import np from scipy.interpolate import griddata import pylab as plt # Set depth to 0 for now z0 = 0. # Pre-allocate midx = [] midz = [] rho = [] LEG = [] count = 0 # Counter for data for ii in range(DCsurvey.nSrc): Tx = DCsurvey.srcList[ii].loc Rx = DCsurvey.srcList[ii].rxList[0].locs nD = DCsurvey.srcList[ii].rxList[0].nD data = DCsurvey.dobs[count:count + nD] count += nD # Get distances between each poles A-B-M-N if stype == 'pdp': MA = np.abs(Tx[0] - Rx[0][:, 0]) NA = np.abs(Tx[0] - Rx[1][:, 0]) MN = np.abs(Rx[1][:, 0] - Rx[0][:, 0]) # Create mid-point location Cmid = Tx[0] Pmid = (Rx[0][:, 0] + Rx[1][:, 0]) / 2 if DCsurvey.mesh.dim == 2: zsrc = Tx[1] elif DCsurvey.mesh.dim == 3: zsrc = Tx[2] elif stype == 'dpdp': MA = np.abs(Tx[0][0] - Rx[0][:, 0]) MB = np.abs(Tx[1][0] - Rx[0][:, 0]) NA = np.abs(Tx[0][0] - Rx[1][:, 0]) NB = np.abs(Tx[1][0] - Rx[1][:, 0]) # Create mid-point location Cmid = (Tx[0][0] + Tx[1][0]) / 2 Pmid = (Rx[0][:, 0] + Rx[1][:, 0]) / 2 if DCsurvey.mesh.dim == 2: zsrc = (Tx[0][1] + Tx[1][1]) / 2 elif DCsurvey.mesh.dim == 3: zsrc = (Tx[0][2] + Tx[1][2]) / 2 # Change output for dtype if dtype == 'volt': rho = np.hstack([rho, data]) else: # Compute pant leg of apparent rho if stype == 'pdp': leg = data * 2 * np.pi * MA * (MA + MN) / MN elif stype == 'dpdp': leg = data * 2 * np.pi / (1 / MA - 1 / MB + 1 / NB - 1 / NA) LEG.append(1. / (2 * np.pi) * (1 / MA - 1 / MB + 1 / NB - 1 / NA)) else: print """dtype must be 'pdp'(pole-dipole) | 'dpdp' (dipole-dipole) """ break if dtype == 'appc': leg = np.log10(abs(1. / leg)) rho = np.hstack([rho, leg]) elif dtype == 'appr': leg = np.log10(abs(leg)) rho = np.hstack([rho, leg]) else: print """dtype must be 'appr' | 'appc' | 'volt' """ break midx = np.hstack([midx, (Cmid + Pmid) / 2]) if DCsurvey.mesh.dim == 3: midz = np.hstack([midz, -np.abs(Cmid - Pmid) / 2 + zsrc]) elif DCsurvey.mesh.dim == 2: midz = np.hstack([midz, -np.abs(Cmid - Pmid) / 2 + zsrc]) ax = axs # Grid points grid_x, grid_z = np.mgrid[np.min(midx):np.max(midx), np.min(midz):np.max(midz)] grid_rho = griddata(np.c_[midx, midz], rho.T, (grid_x, grid_z), method='linear') if clim == None: vmin, vmax = rho.min(), rho.max() else: vmin, vmax = clim[0], clim[1] grid_rho = np.ma.masked_where(np.isnan(grid_rho), grid_rho) ph = plt.pcolormesh(grid_x[:, 0], grid_z[0, :], grid_rho.T, clim=(vmin, vmax), vmin=vmin, vmax=vmax) cbar = plt.colorbar(format="$10^{%.1f}$", fraction=0.04, orientation="horizontal") cmin, cmax = cbar.get_clim() ticks = np.linspace(cmin, cmax, 3) cbar.set_ticks(ticks) cbar.ax.tick_params(labelsize=10) if dtype == 'appc': cbar.set_label("App.Cond", size=12) elif dtype == 'appr': cbar.set_label("App.Res.", size=12) elif dtype == 'volt': cbar.set_label("Potential (V)", size=12) # Plot apparent resistivity ax.scatter(midx, midz, s=10, c=rho.T, vmin=vmin, vmax=vmax, clim=(vmin, vmax)) #ax.set_xticklabels([]) #ax.set_yticklabels([]) plt.gca().set_aspect('equal', adjustable='box') return ph, LEG
def plot_pseudoSection(Tx,Rx,data,z0, stype): from SimPEG import np, mkvc from scipy.interpolate import griddata from matplotlib.colors import LogNorm import pylab as plt import re """ Read list of 2D tx-rx location and plot a speudo-section of apparent resistivity. Assumes flat topo for now... Input: :param d2D, z0 :switch stype -> Either 'pdp' (pole-dipole) | 'dpdp' (dipole-dipole) Output: :figure scatter plot overlayed on image Created on Mon December 7th, 2015 @author: dominiquef """ #d2D = np.asarray(d2D) midl = [] midz = [] rho = [] for ii in range(len(Tx)): # Get distances between each poles rC1P1 = np.abs(Tx[ii][0] - Rx[ii][:,0]) rC2P1 = np.abs(Tx[ii][1] - Rx[ii][:,0]) rC1P2 = np.abs(Tx[ii][1] - Rx[ii][:,1]) rC2P2 = np.abs(Tx[ii][0] - Rx[ii][:,1]) rP1P2 = np.abs(Rx[ii][:,1] - Rx[ii][:,0]) # Compute apparent resistivity if re.match(stype,'pdp'): rho = np.hstack([rho, data[ii] * 2*np.pi * rC1P1 * ( rC1P1 + rP1P2 ) / rP1P2] ) elif re.match(stype,'dpdp'): rho = np.hstack([rho, data[ii] * 2*np.pi / ( 1/rC1P1 - 1/rC2P1 - 1/rC1P2 + 1/rC2P2 ) ]) Cmid = (Tx[ii][0] + Tx[ii][1])/2 Pmid = (Rx[ii][:,0] + Rx[ii][:,1])/2 midl = np.hstack([midl, ( Cmid + Pmid )/2 ]) midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + z0 ]) # Grid points grid_x, grid_z = np.mgrid[np.min(midl):np.max(midl), np.min(midz):np.max(midz)] grid_rho = griddata(np.c_[midl,midz], np.log10(abs(1/rho.T)), (grid_x, grid_z), method='linear') #plt.subplot(2,1,2) plt.imshow(grid_rho.T, extent = (np.min(midl),np.max(midl),np.min(midz),np.max(midz)), origin='lower', alpha=0.8) cbar = plt.colorbar(format = '%.2f',fraction=0.02) cmin,cmax = cbar.get_clim() ticks = np.linspace(cmin,cmax,3) cbar.set_ticks(ticks) # Plot apparent resistivity plt.scatter(midl,midz,s=50,c=np.log10(abs(1/rho.T)))
def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None): """ Read list of 2D tx-rx location and plot a speudo-section of apparent resistivity. Assumes flat topo for now... Input: :param d2D, z0 :switch stype -> Either 'pdp' (pole-dipole) | 'dpdp' (dipole-dipole) :switch dtype=-> Either 'appr' (app. res) | 'appc' (app. con) | 'volt' (potential) Output: :figure scatter plot overlayed on image Edited Feb 17th, 2016 @author: dominiquef """ from SimPEG import np from scipy.interpolate import griddata import pylab as plt # Set depth to 0 for now z0 = 0. # Pre-allocate midx = [] midz = [] rho = [] LEG = [] count = 0 # Counter for data for ii in range(DCsurvey.nSrc): Tx = DCsurvey.srcList[ii].loc Rx = DCsurvey.srcList[ii].rxList[0].locs nD = DCsurvey.srcList[ii].rxList[0].nD data = DCsurvey.dobs[count:count+nD] count += nD # Get distances between each poles A-B-M-N if stype == 'pdp': MA = np.abs(Tx[0] - Rx[0][:,0]) NA = np.abs(Tx[0] - Rx[1][:,0]) MN = np.abs(Rx[1][:,0] - Rx[0][:,0]) # Create mid-point location Cmid = Tx[0] Pmid = (Rx[0][:,0] + Rx[1][:,0])/2 if DCsurvey.mesh.dim == 2: zsrc = Tx[1] elif DCsurvey.mesh.dim ==3: zsrc = Tx[2] elif stype == 'dpdp': MA = np.abs(Tx[0][0] - Rx[0][:,0]) MB = np.abs(Tx[1][0] - Rx[0][:,0]) NA = np.abs(Tx[0][0] - Rx[1][:,0]) NB = np.abs(Tx[1][0] - Rx[1][:,0]) # Create mid-point location Cmid = (Tx[0][0] + Tx[1][0])/2 Pmid = (Rx[0][:,0] + Rx[1][:,0])/2 if DCsurvey.mesh.dim == 2: zsrc = (Tx[0][1] + Tx[1][1])/2 elif DCsurvey.mesh.dim ==3: zsrc = (Tx[0][2] + Tx[1][2])/2 # Change output for dtype if dtype == 'volt': rho = np.hstack([rho,data]) else: # Compute pant leg of apparent rho if stype == 'pdp': leg = data * 2*np.pi * MA * ( MA + MN ) / MN elif stype == 'dpdp': leg = data * 2*np.pi / ( 1/MA - 1/MB + 1/NB - 1/NA ) LEG.append(1./(2*np.pi) *( 1/MA - 1/MB + 1/NB - 1/NA )) else: print("""dtype must be 'pdp'(pole-dipole) | 'dpdp' (dipole-dipole) """) break if dtype == 'appc': leg = np.log10(abs(1./leg)) rho = np.hstack([rho,leg]) elif dtype == 'appr': leg = np.log10(abs(leg)) rho = np.hstack([rho,leg]) else: print("""dtype must be 'appr' | 'appc' | 'volt' """) break midx = np.hstack([midx, ( Cmid + Pmid )/2 ]) if DCsurvey.mesh.dim==3: midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + zsrc ]) elif DCsurvey.mesh.dim==2: midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + zsrc ]) ax = axs # Grid points grid_x, grid_z = np.mgrid[np.min(midx):np.max(midx), np.min(midz):np.max(midz)] grid_rho = griddata(np.c_[midx,midz], rho.T, (grid_x, grid_z), method='linear') if clim == None: vmin, vmax = rho.min(), rho.max() else: vmin, vmax = clim[0], clim[1] grid_rho = np.ma.masked_where(np.isnan(grid_rho), grid_rho) ph = plt.pcolormesh(grid_x[:,0],grid_z[0,:],grid_rho.T, clim=(vmin, vmax), vmin=vmin, vmax=vmax) cbar = plt.colorbar(format="$10^{%.1f}$",fraction=0.04,orientation="horizontal") cmin,cmax = cbar.get_clim() ticks = np.linspace(cmin,cmax,3) cbar.set_ticks(ticks) cbar.ax.tick_params(labelsize=10) if dtype == 'appc': cbar.set_label("App.Cond",size=12) elif dtype == 'appr': cbar.set_label("App.Res.",size=12) elif dtype == 'volt': cbar.set_label("Potential (V)",size=12) # Plot apparent resistivity ax.scatter(midx,midz,s=10,c=rho.T, vmin =vmin, vmax = vmax, clim=(vmin, vmax)) #ax.set_xticklabels([]) #ax.set_yticklabels([]) plt.gca().set_aspect('equal', adjustable='box') return ph, LEG
def run(plotIt=True): """ MT: 1D: Inversion ================= Forward model 1D MT data. Setup and run a MT 1D inversion. """ ## 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,10,-1.3)]),np.ones((5,))) , simpeg.Utils.meshTensor([(ct,5)]) ) ) bot = simpeg.Utils.meshTensor([(core[0],25,-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 varibles 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,mapping=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) if plotIt: fig = NSEM.Utils.dataUtils.plotMT1DModelData(problem,[]) fig.suptitle('Target - smooth true') # Assign uncertainties std = 0.05 # 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() # Set the optimization opt = simpeg.Optimization.ProjectedGNCG(maxIter = 25) opt.counter = C opt.lower = np.log(1e-4) opt.upper = np.log(5) opt.LSshorten = 0.1 opt.remember('xc') # Data misfit dmis = simpeg.DataMisfit.l2_DataMisfit(survey) dmis.Wd = 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-1 reg.alpha_x = 1. # Inversion problem invProb = simpeg.InvProblem.BaseInvProblem(dmis, reg, opt) invProb.counter = C # Beta cooling beta = simpeg.Directives.BetaSchedule() beta.coolingRate = 4. beta.coolingFactor = 4. betaest = simpeg.Directives.BetaEstimate_ByEig(beta0_ratio=100.) betaest.beta0 = 1. targmis = simpeg.Directives.TargetMisfit() targmis.target = survey.nD # Create an inversion object inv = simpeg.Inversion.BaseInversion(invProb, directiveList=[beta,betaest,targmis]) ## 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]) plt.show()
def animate(ii): #for ii in range(1): removeFrame() # Grab current line and indx = np.where(lineID == ii)[0] srcLeft = [] obs_l = [] obs = [] srcRight = [] obs_r = [] srcList = [] # Split the obs file into left and right # Split the obs file into left and right for jj in range(len(indx)): # Grab corresponding data obs = np.hstack([obs, DCdobs2D.dobs[dataID == indx[jj]]]) #std = dobs2D.std[dataID==indx[jj]] srcList.append(DCdobs2D.srcList[indx[jj]]) Tx = DCdobs2D.srcList[indx[jj]].loc Rx = DCdobs2D.srcList[indx[jj]].rxList[0].locs # Create mid-point location Cmid = (Tx[0][0] + Tx[1][0]) / 2 Pmid = (Rx[0][:, 0] + Rx[1][:, 0]) / 2 ileft = Pmid < Cmid iright = Pmid >= Cmid temp = np.zeros(len(ileft)) temp[ileft] = 1 obs_l = np.hstack([obs_l, temp]) temp = np.zeros(len(iright)) temp[iright] = 1 obs_r = np.hstack([obs_r, temp]) if np.any(ileft): rx = DC.RxDipole(Rx[0][ileft, :], Rx[1][ileft, :]) srcLeft.append(DC.SrcDipole([rx], Tx[0], Tx[1])) #std_l = np.hstack([std_l,std[ileft]]) if np.any(iright): rx = DC.RxDipole(Rx[0][iright, :], Rx[1][iright, :]) srcRight.append(DC.SrcDipole([rx], Tx[0], Tx[1])) #obs_r = np.hstack([obs_r,iright]) #std_r = np.hstack([std_r,std[iright]]) DC2D_full = DC.SurveyDC(srcList) DC2D_full.dobs = np.asarray(obs) DC2D_full.std = DC2D_full.dobs * 0. DC2D_full.std[obs_l == 1] = np.abs(DC2D_full.dobs[obs_l == 1]) * 0.02 + 2e-5 DC2D_full.std[obs_r == 1] = np.abs(DC2D_full.dobs[obs_r == 1]) * 0.06 + 4e-5 # DC2D_l = DC.SurveyDC(srcLeft) # DC2D_l.dobs = np.asarray(obs[obs_l==1]) # DC2D_l.std = np.abs(np.asarray(DC2D_l.dobs))*0.05 + 2e-5 # # DC2D_r = DC.SurveyDC(srcRight) # DC2D_r.dobs = np.asarray(obs[obs_r==1]) # DC2D_r.std = np.abs(np.asarray(DC2D_r.dobs))*0.05 + 2e-5 survey = DC2D_full # Export data file DC.writeUBC_DCobs(inv_dir + dsep + obsfile2d, survey, '2D', 'SIMPLE') # Write input file fid = open(inv_dir + dsep + inp_file, 'w') fid.write('OBS LOC_X %s \n' % obsfile2d) fid.write('MESH FILE %s \n' % mshfile2d) fid.write('CHIFACT 1 \n') fid.write('TOPO DEFAULT \n') fid.write('INIT_MOD VALUE %e\n' % ini_mod) fid.write('REF_MOD VALUE %e\n' % ref_mod) fid.write('ALPHA VALUE %f %f %F\n' % (1. / dx**4., 1, 1)) fid.write('WEIGHT DEFAULT\n') fid.write('STORE_ALL_MODELS FALSE\n') fid.write('INVMODE CG\n') #fid.write('CG_PARAM 200 1e-4\n') fid.write('USE_MREF FALSE\n') #fid.write('BOUNDS VALUE 1e-4 1e+2\n') fid.close() os.chdir(inv_dir) os.system('dcinv2d ' + inp_file) #%% Load DC model and predicted data minv = DC.readUBC_DC2DModel(inv_dir + dsep + 'dcinv2d.con') minv = np.reshape(minv, (mesh2d.nCy, mesh2d.nCx)) #%% Repeat for IP data indx = np.where(IPlineID == ii)[0] srcLeft = [] obs_l = [] std_l = [] srcRight = [] obs_r = [] std_r = [] obs_full = [] std_full = [] srcList = [] # Split the obs file into left and right for jj in range(len(indx)): srcList.append(IPdobs2D.srcList[indx[jj]]) # Grab corresponding data obs = IPdobs2D.dobs[IPdataID == indx[jj]] std = IPdobs2D.std[IPdataID == indx[jj]] obs_full = np.hstack([obs_full, obs]) std_full = np.hstack([std_full, std]) Tx = IPdobs2D.srcList[indx[jj]].loc Rx = IPdobs2D.srcList[indx[jj]].rxList[0].locs # Create mid-point location Cmid = (Tx[0][0] + Tx[1][0]) / 2 Pmid = (Rx[0][:, 0] + Rx[1][:, 0]) / 2 ileft = Pmid < Cmid iright = Pmid >= Cmid temp = np.zeros(len(ileft)) temp[ileft] = 1 obs_l = np.hstack([obs_l, temp]) temp = np.zeros(len(iright)) temp[iright] = 1 obs_r = np.hstack([obs_r, temp]) if np.any(ileft): rx = DC.RxDipole(Rx[0][ileft, :], Rx[1][ileft, :]) srcLeft.append(DC.SrcDipole([rx], Tx[0], Tx[1])) #std_l = np.hstack([std_l,std[ileft]]) if np.any(iright): rx = DC.RxDipole(Rx[0][iright, :], Rx[1][iright, :]) srcRight.append(DC.SrcDipole([rx], Tx[0], Tx[1])) IP2D_full = DC.SurveyDC(srcList) IP2D_full.dobs = np.asarray(obs_full) IP2D_full.std = np.asarray(std_full) IP2D_l = DC.SurveyDC(srcLeft) IP2D_l.dobs = np.asarray(obs_full[obs_l == 1]) #IP2D_l.std = np.abs(np.asarray(obs_l))*0.03 + 2e-2 IP2D_r = DC.SurveyDC(srcRight) IP2D_r.dobs = np.asarray(obs_full[obs_r == 1]) #IP2D_r.std = np.abs(np.asarray(obs_r))*0.03 + 1e-2 id_lbe = int(IPsurvey.srcList[indx[jj]].loc[0][1]) mesh3d = Mesh.TensorMesh([hx, np.ones(1) * 100., hz], x0=(-np.sum(padx) + np.min(srcMat[0][:, 0]), id_lbe - 50, np.max(srcMat[0][0, 2]) - np.sum(hz))) Mesh.TensorMesh.writeUBC(mesh3d, home_dir + dsep + 'Mesh' + str(id_lbe) + '.msh') global ax1, ax2, ax3, ax5, ax6, fig ax2 = plt.subplot(3, 2, 2) ph = DC.plot_pseudoSection(IP2D_r, ax2, stype='pdp', dtype='volt', colorbar=False) ax2.set_title('Observed P-DP', fontsize=10) plt.xlim([xmin, xmax]) plt.ylim([zmin, zmax]) plt.gca().set_aspect('equal', adjustable='box') ax2.set_xticklabels([]) ax2.set_yticklabels([]) ax1 = plt.subplot(3, 2, 1) DC.plot_pseudoSection(IP2D_l, ax1, stype='pdp', dtype='volt', clim=(ph[0].get_clim()[0], ph[0].get_clim()[1]), colorbar=False) ax1.set_title('Observed DP-P', fontsize=10) plt.xlim([xmin, xmax]) plt.ylim([zmin, zmax]) plt.gca().set_aspect('equal', adjustable='box') ax1.set_xticklabels([]) z = np.linspace(np.min(ph[2]), np.max(ph[2]), 5) z_label = np.linspace(20, 1, 5) ax1.set_yticks(map(int, z)) ax1.set_yticklabels(map(str, map(int, z_label)), size=8) ax1.set_ylabel('n-spacing', fontsize=8) #%% Add labels bbox_props = dict(boxstyle="circle,pad=0.3", fc="r", ec="k", lw=1) ax2.text(0.00, 1, 'A', transform=ax2.transAxes, ha="left", va="center", size=6, bbox=bbox_props) bbox_props = dict(boxstyle="circle,pad=0.3", fc="y", ec="k", lw=1) ax2.text(0.1, 1, 'M', transform=ax2.transAxes, ha="left", va="center", size=6, bbox=bbox_props) bbox_props = dict(boxstyle="circle,pad=0.3", fc="g", ec="k", lw=1) ax2.text(0.2, 1, 'N', transform=ax2.transAxes, ha="left", va="center", size=6, bbox=bbox_props) bbox_props = dict(boxstyle="circle,pad=0.3", fc="g", ec="k", lw=1) ax1.text(0.00, 1, 'N', transform=ax1.transAxes, ha="left", va="center", size=6, bbox=bbox_props) bbox_props = dict(boxstyle="circle,pad=0.3", fc="y", ec="k", lw=1) ax1.text(0.1, 1, 'M', transform=ax1.transAxes, ha="left", va="center", size=6, bbox=bbox_props) bbox_props = dict(boxstyle="circle,pad=0.3", fc="r", ec="k", lw=1) ax1.text(0.2, 1, 'A', transform=ax1.transAxes, ha="left", va="center", size=6, bbox=bbox_props) survey = IP2D_full # Export data file DC.writeUBC_DCobs(inv_dir + dsep + ipfile2d, survey, '2D', 'SIMPLE', iptype=1) fid = open(inv_dir + dsep + inp_file, 'w') fid.write('OBS LOC_X %s \n' % ipfile2d) fid.write('MESH FILE %s \n' % mshfile2d) fid.write('CHIFACT 4 \n') fid.write('COND FILE dcinv2d.con\n') fid.write('TOPO DEFAULT \n') fid.write('INIT_MOD VALUE %e\n' % ini_mod) fid.write('REF_MOD VALUE 0.0\n') fid.write('ALPHA VALUE %f %f %F\n' % (1. / dx**4., 1, 1)) fid.write('WEIGHT DEFAULT\n') fid.write('STORE_ALL_MODELS FALSE\n') fid.write('INVMODE CG\n') #fid.write('CG_PARAM 200 1e-4\n') fid.write('USE_MREF FALSE\n') #fid.write('BOUNDS VALUE 1e-4 1e+2\n') fid.close() os.chdir(inv_dir) os.system('ipinv2d ' + inp_file) #%% Load model and predicted data minv = DC.readUBC_DC2DModel(inv_dir + dsep + 'ipinv2d.chg') minv = np.reshape(minv, (mesh2d.nCy, mesh2d.nCx)) Mesh.TensorMesh.writeModelUBC( mesh3d, home_dir + dsep + 'Model' + str(id_lbe) + '.chg', minv.T) dpre = DC.readUBC_DC2Dpre(inv_dir + dsep + 'ipinv2d.pre') DCpre = dpre['DCsurvey'] DCtemp = IP2D_l DCtemp.dobs = DCpre.dobs[obs_l == 1] ax5 = plt.subplot(3, 2, 3) DC.plot_pseudoSection(DCtemp, ax5, stype='pdp', dtype='volt', clim=(ph[0].get_clim()[0], ph[0].get_clim()[1]), colorbar=False) ax5.set_title('Predicted', fontsize=10) plt.xlim([xmin, xmax]) plt.ylim([zmin, zmax]) plt.gca().set_aspect('equal', adjustable='box') ax5.set_xticklabels([]) z = np.linspace(np.min(ph[2]), np.max(ph[2]), 5) z_label = np.linspace(20, 1, 5) ax5.set_yticks(map(int, z)) ax5.set_yticklabels(map(str, map(int, z_label)), size=8) ax5.set_ylabel('n-spacing', fontsize=8) DCtemp = IP2D_r DCtemp.dobs = DCpre.dobs[obs_r == 1] ax6 = plt.subplot(3, 2, 4) DC.plot_pseudoSection(DCtemp, ax6, stype='pdp', dtype='volt', clim=(ph[0].get_clim()[0], ph[0].get_clim()[1]), colorbar=False) ax6.set_title('Predicted', fontsize=10) plt.xlim([xmin, xmax]) plt.ylim([zmin, zmax]) plt.gca().set_aspect('equal', adjustable='box') ax6.set_xticklabels([]) ax6.set_yticklabels([]) pos = ax6.get_position() cbarax = fig.add_axes([ pos.x0 + 0.325, pos.y0 + 0.2, pos.width * 0.1, pos.height * 0.5 ]) ## the parameters are the specified position you set cb = fig.colorbar(ph[0], cax=cbarax, orientation="vertical", ax=ax6, ticks=np.linspace(ph[0].get_clim()[0], ph[0].get_clim()[1], 4), format="$10^{%.1f}$") cb.set_label("App. Charg.", size=8) ax3 = plt.subplot(3, 1, 3) ax3.set_title('2-D Model (S/m)', fontsize=10) ax3.set_xticks(map(int, x)) ax3.set_xticklabels(map(str, map(int, x))) ax3.set_xlabel('Easting (m)', fontsize=8) ax3.set_yticks(map(int, z)) ax3.set_yticklabels(map(str, map(int, z)), rotation='vertical') ax3.set_ylabel('Depth (m)', fontsize=8) plt.xlim([xmin, xmax]) plt.ylim([zmin / 2, zmax]) plt.gca().set_aspect('equal', adjustable='box') ph2 = plt.pcolormesh(mesh2d.vectorNx, mesh2d.vectorNy, (minv), vmin=vmin, vmax=vmax) plt.gca().tick_params(axis='both', which='major', labelsize=8) plt.draw() for ss in range(survey.nSrc): Tx = survey.srcList[ss].loc[0] plt.scatter(Tx[0], mesh2d.vectorNy[-1] + 10, s=10) pos = ax3.get_position() ax3.set_position([pos.x0 + 0.025, pos.y0, pos.width, pos.height]) pos = ax3.get_position() cbarax = fig.add_axes([ pos.x0 + 0.65, pos.y0 + 0.01, pos.width * 0.05, pos.height * 0.75 ]) ## the parameters are the specified position you set cb = fig.colorbar(ph2, cax=cbarax, orientation="vertical", ax=ax3, ticks=np.linspace(vmin, vmax, 4), format="%4.1f") cb.set_label("Chargeability", size=8) pos = ax1.get_position() ax1.set_position([pos.x0 + 0.03, pos.y0, pos.width, pos.height]) pos = ax5.get_position() ax5.set_position([pos.x0 + 0.03, pos.y0, pos.width, pos.height]) pos = ax2.get_position() ax2.set_position([pos.x0 - 0.03, pos.y0, pos.width, pos.height]) pos = ax6.get_position() ax6.set_position([pos.x0 - 0.03, pos.y0, pos.width, pos.height]) #%% Add the extra bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="w", ec="k", lw=2) ax2.text(0.01, (float(ii) + 1.) / (len(uniqueID) + 2), 'N: ' + str(id_lbe), transform=fig.transFigure, ha="left", va="center", size=8, bbox=bbox_props) mrk_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=2) ax2.text(0.01, 0.9, 'Line ID#', transform=fig.transFigure, ha="left", va="center", size=8, bbox=mrk_props) mrk_props = dict(boxstyle="square,pad=0.3", fc="b", ec="k", lw=2) for jj in range(len(uniqueID)): ax2.text(0.1, (float(jj) + 1.) / (len(uniqueID) + 2), ".", transform=fig.transFigure, ha="right", va="center", size=8, bbox=mrk_props) mrk_props = dict(boxstyle="square,pad=0.3", fc="r", ec="k", lw=2) ax2.text(0.1, (float(ii) + 1.) / (len(uniqueID) + 2), ".", transform=fig.transFigure, ha="right", va="center", size=8, bbox=mrk_props)
def xy_2_lineID(DCsurvey): """ Read DC survey class and append line ID. Assumes that the locations are listed in the order they were collected. May need to generalize for random point locations, but will be more expensive Input: :param DCdict Vectors of station location Output: :param LineID Vector of integers :return Created on Thu Feb 11, 2015 @author: dominiquef """ # Compute unit vector between two points nstn = DCsurvey.nSrc # Pre-allocate space lineID = np.zeros(nstn) linenum = 0 indx = 0 for ii in range(nstn): if ii == 0: A = DCsurvey.srcList[ii].loc[0] B = DCsurvey.srcList[ii].loc[1] xout = np.mean([A[0:2],B[0:2]], axis = 0) xy0 = A[:2] xym = xout # Deal with replicate pole location if np.all(xy0==xym): xym[0] = xym[0] + 1e-3 continue A = DCsurvey.srcList[ii].loc[0] B = DCsurvey.srcList[ii].loc[1] xin = np.mean([A[0:2],B[0:2]], axis = 0) # Compute vector between neighbours vec1, r1 = r_unit(xout,xin) # Compute vector between current stn and mid-point vec2, r2 = r_unit(xym,xin) # Compute vector between current stn and start line vec3, r3 = r_unit(xy0,xin) # Compute vector between mid-point and start line vec4, r4 = r_unit(xym,xy0) # Compute dot product ang1 = np.abs(vec1.dot(vec2)) ang2 = np.abs(vec3.dot(vec4)) # If the angles are smaller then 45d, than next point is on a new line if ((ang1 < np.cos(np.pi/4.)) | (ang2 < np.cos(np.pi/4.))) & (np.all(np.r_[r1,r2,r3,r4] > 0)): # Re-initiate start and mid-point location xy0 = A[:2] xym = xin # Deal with replicate pole location if np.all(xy0==xym): xym[0] = xym[0] + 1e-3 linenum += 1 indx = ii else: xym = np.mean([xy0,xin], axis = 0) lineID[ii] = linenum xout = xin return lineID
def plot_pseudoSection(DCsurvey, axs, stype): """ Read list of 2D tx-rx location and plot a speudo-section of apparent resistivity. Assumes flat topo for now... Input: :param d2D, z0 :switch stype -> Either 'pdp' (pole-dipole) | 'dpdp' (dipole-dipole) Output: :figure scatter plot overlayed on image Edited Feb 17th, 2016 @author: dominiquef """ from SimPEG import np from scipy.interpolate import griddata import pylab as plt # Set depth to 0 for now z0 = 0. # Pre-allocate midx = [] midz = [] rho = [] count = 0 # Counter for data for ii in range(DCsurvey.nSrc): Tx = DCsurvey.srcList[ii].loc Rx = DCsurvey.srcList[ii].rxList[0].locs nD = DCsurvey.srcList[ii].rxList[0].nD data = DCsurvey.dobs[count:count+nD] count += nD # Get distances between each poles A-B-M-N MA = np.abs(Tx[0][0] - Rx[0][:,0]) MB = np.abs(Tx[1][0] - Rx[0][:,0]) NB = np.abs(Tx[1][0] - Rx[1][:,0]) NA = np.abs(Tx[0][0] - Rx[1][:,0]) MN = np.abs(Rx[1][:,0] - Rx[0][:,0]) # Create mid-point location Cmid = (Tx[0][0] + Tx[1][0])/2 Pmid = (Rx[0][:,0] + Rx[1][:,0])/2 # Compute pant leg of apparent rho if stype == 'pdp': leg = data * 2*np.pi * MA * ( MA + MN ) / MN leg = np.log10(abs(1/leg)) elif stype == 'dpdp': leg = data * 2*np.pi / ( 1/MA - 1/MB - 1/NB + 1/NA ) midx = np.hstack([midx, ( Cmid + Pmid )/2 ]) midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + z0 ]) rho = np.hstack([rho,leg]) ax = axs # Grid points grid_x, grid_z = np.mgrid[np.min(midx):np.max(midx), np.min(midz):np.max(midz)] grid_rho = griddata(np.c_[midx,midz], rho.T, (grid_x, grid_z), method='linear') plt.imshow(grid_rho.T, extent = (np.min(midx),np.max(midx),np.min(midz),np.max(midz)), origin='lower', alpha=0.8, vmin = np.min(rho), vmax = np.max(rho)) cbar = plt.colorbar(format = '%.2f',fraction=0.04,orientation="horizontal") cmin,cmax = cbar.get_clim() ticks = np.linspace(cmin,cmax,3) cbar.set_ticks(ticks) # Plot apparent resistivity plt.scatter(midx,midz,s=50,c=rho.T) ax.set_xticklabels([]) ax.set_ylabel('Z') ax.yaxis.tick_right() ax.yaxis.set_label_position('right') plt.gca().set_aspect('equal', adjustable='box') return ax
def run(plotIt=True): """ MT: 1D: Inversion ================= Forward model 1D MT data. Setup and run a MT 1D inversion. """ ## 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, 10, -1.3)]), np.ones( (5, ))), simpeg.Utils.meshTensor([(ct, 5)]))) bot = simpeg.Utils.meshTensor([(core[0], 25, -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 varibles 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, mapping=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) if plotIt: fig = NSEM.Utils.dataUtils.plotMT1DModelData(problem, []) fig.suptitle('Target - smooth true') # Assign uncertainties std = 0.05 # 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() # Set the optimization opt = simpeg.Optimization.ProjectedGNCG(maxIter=25) opt.counter = C opt.lower = np.log(1e-4) opt.upper = np.log(5) opt.LSshorten = 0.1 opt.remember('xc') # Data misfit dmis = simpeg.DataMisfit.l2_DataMisfit(survey) dmis.Wd = 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-1 reg.alpha_x = 1. # Inversion problem invProb = simpeg.InvProblem.BaseInvProblem(dmis, reg, opt) invProb.counter = C # Beta cooling beta = simpeg.Directives.BetaSchedule() beta.coolingRate = 4. beta.coolingFactor = 4. betaest = simpeg.Directives.BetaEstimate_ByEig(beta0_ratio=100.) betaest.beta0 = 1. targmis = simpeg.Directives.TargetMisfit() targmis.target = survey.nD # Create an inversion object inv = simpeg.Inversion.BaseInversion( invProb, directiveList=[beta, betaest, targmis]) ## 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]) plt.show()
LD = sp.tril(A,k=0) phi = mkvc(Ainvb[0]) elif re.match(slvr,'LU'): #Direct Solve phi = Ainv.solve(RHS) # Compute potential at each electrode dtemp = (P1*phi - P2*phi)*np.pi data.append( dtemp ) unct.append( np.abs(dtemp) * pct + flr) print("--- %s seconds ---" % (time.time() - start_time)) #%% Run 2D inversion if pdp or dpdp survey # Otherwise just plot and apparent susceptibility map if not re.match(stype,'gradient'): #%% Write data file in UBC-DCIP3D format DC.writeUBC_DCobs(home_dir+'\FWR_data3D.dat',Tx,Rx,data,unct,'3D') #%% Load 3D data [Tx, Rx, data, wd] = DC.readUBC_DC3Dobs(home_dir + '\FWR_data3D.dat')
def testOnes(self): Adiagtest = diagEst(self.A,self.n,self.n) r = np.abs(Adiagtest-self.Adiag) self.assertTrue(r.dot(r) < TOL)