Beispiel #1
0
    def G(self):

        if getattr(self, '_G', None) is None:
            #print "Computing G"

            # rot = Utils.mkvc(Utils.dipazm_2_xyz(self.prism.pinc, self.prism.pdec))

            # rxLoc = Utils.rotatePointsFromNormals(self.survey.rxLoc, rot, np.r_[0., 1., 0.],
            #                                      np.r_[0, 0, 0])


            xLoc = self.survey.rxLoc[:, 0] - self.prism.xc
            yLoc = self.survey.rxLoc[:, 1] - self.prism.yc
            zLoc = self.survey.rxLoc[:, 2] - self.prism.zc

            R = Utils.rotationMatrix(-self.prism.pinc, -self.prism.pdec, normal=False)

            rxLoc = R.dot(np.c_[xLoc, yLoc, zLoc].T).T

            rxLoc = np.c_[rxLoc[:, 0] + self.prism.xc, rxLoc[:, 1] + self.prism.yc, rxLoc[:, 2] + self.prism.zc]

            # Create the linear forward system
            self._G = Intrgl_Fwr_Op(self.prism.xn, self.prism.yn, self.prism.zn, rxLoc)

        return self._G
Beispiel #2
0
    def extractFields(self, bvec):

        nD = bvec.shape[0]/3
        bvec = np.reshape(bvec, (3, nD))

        # rot = Utils.mkvc(Utils.dipazm_2_xyz(-self.prism.pinc, -self.prism.pdec))

        # bvec = Utils.rotatePointsFromNormals(bvec.T, rot, np.r_[0., 1., 0.],
        #                                      np.r_[0, 0, 0]).T

        R = Utils.rotationMatrix(self.prism.pinc, self.prism.pdec)
        bvec = R.dot(bvec)

        if self.uType == 'bx':
            u = Utils.mkvc(bvec[0, :])

        if self.uType == 'by':
            u = Utils.mkvc(bvec[1, :])

        if self.uType == 'bz':
            u = Utils.mkvc(bvec[2, :])

        if self.uType == 'tf':
            # Projection matrix
            Ptmi = Utils.dipazm_2_xyz(self.Binc, self.Bdec).T

            u = Utils.mkvc(Ptmi.dot(bvec))

        return u
Beispiel #3
0
 def Mind(self):
     # Define magnetization direction as sum of induced and remanence
     mind = Utils.dipazm_2_xyz(self.Binc, self.Bdec)
     R = Utils.rotationMatrix(-self.prism.pinc, -self.prism.pdec, normal=False)
     Mind = self.susc*self.Higrf*R.dot(mind)
     # Mind = self.susc*self.Higrf*Utils.dipazm_2_xyz(self.Binc - self.prism.pinc,
     #                                                self.Bdec - self.prism.pdec)
     return Mind
Beispiel #4
0
    def Mrem(self):

        mrem = Utils.dipazm_2_xyz(self.rinc, self.rdec)
        R = Utils.rotationMatrix(-self.prism.pinc, -self.prism.pdec, normal=False)
        Mrem = self.Q*self.susc*self.Higrf * R.dot(mrem)

        # Mrem = self.Q*self.susc*self.Higrf * \
        #        Utils.dipazm_2_xyz(self.rinc - self.prism.pinc, self.rdec - self.prism.pdec)

        return Mrem
Beispiel #5
0
def animate(ii):

    removePlt()
    #ii=1
    #inc = 45
    #dec = 90
    if ii < 18:
        dec = 90
        inc = 0. + ii * 5.

    elif ii < 36:

        dec = 270.
        inc = 90. - (ii - 18) * 5.

    elif ii < 54:

        dec = 270.
        inc = 0. + (ii - 36) * 5.

    else:

        dec = 90
        inc = 90. - (ii - 54) * 5.

    ax1.axis('equal')
    block_xyz = np.asarray([[-.2, -.2, .2, .2, 0], [
        -.25, -.25, -.25, -.25, 0.5
    ], [-.2, .2, .2, -.2, 0]]) * 10.

    block_xyz[1][:] -= 20.
    # rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec))

    # xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot,
    #                                     np.r_[p.xc, p.yc, p.zc])

    R = Utils.rotationMatrix(inc, dec)

    xyz = R.dot(block_xyz).T
    xyz[:, 2] -= depth + dz / 2.
    #print xyz
    # Face 1
    ax1.add_collection3d(
        Poly3DCollection([zip(xyz[:4, 0], xyz[:4, 1], xyz[:4, 2])],
                         facecolors='b'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[1, 2, 4], 0], xyz[[1, 2, 4], 1], xyz[[1, 2, 4], 2])],
            facecolors='b'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[0, 1, 4], 0], xyz[[0, 1, 4], 1], xyz[[0, 1, 4], 2])],
            facecolors='b'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[2, 3, 4], 0], xyz[[2, 3, 4], 1], xyz[[2, 3, 4], 2])],
            facecolors='b'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[0, 3, 4], 0], xyz[[0, 3, 4], 1], xyz[[0, 3, 4], 2])],
            facecolors='b'))

    block_xyz[1][:] += 20.
    # rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec))

    # xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot,
    #                                     np.r_[p.xc, p.yc, p.zc])

    R = Utils.rotationMatrix(rinc, rdec)

    xyz = R.dot(block_xyz).T
    xyz[:, 2] -= depth + dz / 2.

    #print xyz
    # Face 1
    ax1.add_collection3d(
        Poly3DCollection([zip(xyz[:4, 0], xyz[:4, 1], xyz[:4, 2])],
                         facecolors='y'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[1, 2, 4], 0], xyz[[1, 2, 4], 1], xyz[[1, 2, 4], 2])],
            facecolors='y'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[0, 1, 4], 0], xyz[[0, 1, 4], 1], xyz[[0, 1, 4], 2])],
            facecolors='y'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[2, 3, 4], 0], xyz[[2, 3, 4], 1], xyz[[2, 3, 4], 2])],
            facecolors='y'))

    ax1.add_collection3d(
        Poly3DCollection(
            [zip(xyz[[0, 3, 4], 0], xyz[[0, 3, 4], 1], xyz[[0, 3, 4], 2])],
            facecolors='y'))

    MAG.plotObj3D(p,
                  rx_h,
                  View_elev,
                  View_azim,
                  npts2D,
                  xylim,
                  profile="X",
                  fig=fig,
                  axs=ax1,
                  plotSurvey=False)

    ax1.w_yaxis.set_ticklabels('')
    ax1.w_yaxis.set_label_text('')
    ax1.w_zaxis.set_ticklabels('')
    ax1.w_zaxis.set_label_text('')

    # Create problem
    prob = prismFWR.problem()
    prob.prism = p
    prob.survey = srvy

    prob.Bdec, prob.Binc, prob.Bigrf = dec, inc, Bigrf
    prob.Q, prob.rinc, prob.rdec = Q, rinc, rdec
    prob.uType, prob.mType = 'tf', 'total'
    prob.susc = susc

    # Compute fields from prism
    b_ind, b_rem = prob.fields()
    out = b_ind + b_rem

    prob.uType, prob.mType = 'bx', 'total'
    b_ind, b_rem = prob.fields()
    outx = b_ind + b_rem

    prob.uType = 'by'
    b_ind, b_rem = prob.fields()
    outy = b_ind + b_rem

    prob.uType = 'bz'
    b_ind, b_rem = prob.fields()
    outz = b_ind + b_rem

    out_amp = np.sqrt(outx**2. + outy**2. + outz**2.)

    #out = plogMagSurvey2D(prob, susc, Einc, Edec, Bigrf, x1, y1, x2, y2, comp, irt,  Q, rinc, rdec, fig=fig, axs1=ax2, axs2=ax3)

    #dat = axs1.contourf(X,Y, np.reshape(out, (X.shape)).T
    global im1
    im1 = ax1.contourf(X,
                       Y,
                       np.reshape(out, (X.shape)).T,
                       20,
                       zdir='z',
                       offset=rx_h + 5.,
                       clim=clim,
                       vmin=clim[0],
                       vmax=clim[1],
                       cmap='RdBu_r')

    ax5 = fig.add_axes(
        [pos.x0, pos.y0 + 0.25, pos.height * 0.02, pos.height * 0.4])
    cb = plt.colorbar(im1,
                      cax=ax5,
                      orientation="vertical",
                      ax=ax1,
                      ticks=np.linspace(im1.vmin, im1.vmax, 4),
                      format="${%.0f}$")
    cb.set_label("$B^{TMI}\;(nT)$", size=12)
    cb.ax.yaxis.set_ticks_position('left')
    cb.ax.yaxis.set_label_position('left')

    global im5
    im5 = ax1.text(0,
                   0,
                   -60,
                   '$B_0, I: ' + str(inc) + '^\circ, D: ' + str(dec) +
                   '^\circ$',
                   horizontalalignment='center')

    #%% Run amplitude inversion
    H0 = (Bigrf, 90, 0)

    actv = np.ones(mesh.nC) == 1
    # Create active map to go from reduce space to full
    actvMap = Maps.InjectActiveCells(mesh, actv, -100)
    nC = len(actv)

    # Create a MAGsurvey
    rxLoc = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)]
    rxLoc = PF.BaseMag.RxObs(rxLoc)
    srcField = PF.BaseMag.SrcField([rxLoc], param=H0)
    survey = PF.BaseMag.LinearSurvey(srcField)

    # We can now create a susceptibility model and generate data
    # Lets start with a simple block in half-space
    #    model = np.zeros((mesh.nCx,mesh.nCy,mesh.nCz))
    #    model[(midx-2):(midx+2),(midy-2):(midy+2),-6:-2] = 0.02
    #    model = mkvc(model)
    #    model = model[actv]

    # Create active map to go from reduce set to full
    actvMap = Maps.InjectActiveCells(mesh, actv, -100)

    # Creat reduced identity map
    idenMap = Maps.IdentityMap(nP=nC)

    # Create the forward model operator
    #probinv = PF.Magnetics.MagneticIntegral(mesh, mapping = idenMap, actInd = actv)
    probinv = PF.Magnetics.MagneticAmplitude(mesh,
                                             mapping=idenMap,
                                             actInd=actv)

    # Pair the survey and problem
    survey.pair(probinv)

    # We can now generate data
    data = out_amp + np.random.randn(
        len(out_amp))  # We add some random Gaussian noise (1nT)
    wd = np.ones(len(data)) * 1.  # Assign flat uncertainties

    # Create distance weights from our linera forward operator
    #    wr = np.sum(probinv.G**2.,axis=0)**0.5
    #    wr = ( wr/np.max(wr) )

    #survey.makeSyntheticData(data, std=0.01)
    survey.dobs = data
    survey.std = wd
    survey.mtrue = model

    # Create a regularization
    reg = Regularization.Sparse(mesh, indActive=actv, mapping=idenMap)
    #    reg.cell_weights = wr

    dmis = DataMisfit.l2_DataMisfit(survey)
    dmis.Wd = 1 / wd

    # Add directives to the inversion
    opt = Optimization.ProjectedGNCG(maxIter=100,
                                     lower=0.,
                                     upper=1.,
                                     maxIterLS=20,
                                     maxIterCG=10,
                                     tolCG=1e-3)
    invProb = InvProblem.BaseInvProblem(dmis, reg, opt)
    betaest = Directives.BetaEstimate_ByEig()

    # Here is where the norms are applied
    # Use pick a treshold parameter empirically based on the distribution of model
    # parameters (run last cell to see the histogram before and after IRLS)
    IRLS = Directives.Update_IRLS(norms=([1, 2, 2, 2]),
                                  eps=(2e-3, 2e-3),
                                  f_min_change=1e-3,
                                  minGNiter=3,
                                  coolingRate=3)
    update_Jacobi = Directives.Amplitude_Inv_Iter()
    inv = Inversion.BaseInversion(invProb,
                                  directiveList=[update_Jacobi, IRLS, betaest])

    m0 = np.ones(nC) * 1e-4
    pred0 = probinv.fields(m0)
    mrec = inv.run(m0)

    mamp = (mrec / mrec.max() + 1e-2)**-1.
    #%% Run MVI with constraint
    H0 = (Bigrf, inc, dec)

    actv = np.ones(mesh.nC) == 1
    # Create active map to go from reduce space to full
    actvMap = Maps.InjectActiveCells(mesh, actv, -100)
    nC = len(actv)

    # Create a MAGsurvey
    rxLoc = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)]
    rxLoc = PF.BaseMag.RxObs(rxLoc)
    srcField = PF.BaseMag.SrcField([rxLoc], param=H0)
    survey = PF.BaseMag.LinearSurvey(srcField)

    # Create active map to go from reduce set to full
    actvMap = Maps.InjectActiveCells(mesh, actv, -100)

    # Creat reduced identity map
    idenMap = Maps.IdentityMap(nP=3 * nC)

    # Create the forward model operator
    #probinv = PF.Magnetics.MagneticIntegral(mesh, mapping = idenMap, actInd = actv)
    probinv = PF.Magnetics.MagneticVector(mesh, mapping=idenMap, actInd=actv)

    # Pair the survey and problem
    survey.pair(probinv)

    # We can now generate data
    data = out + np.random.randn(
        len(out))  # We add some random Gaussian noise (1nT)
    wd = np.ones(len(data)) * 1.  # Assign flat uncertainties

    # Create distance weights from our linera forward operator
    wr = np.sum(probinv.G**2., axis=0)**0.5
    wr = (wr / np.max(wr)) * np.r_[mamp, mamp, mamp]

    #survey.makeSyntheticData(data, std=0.01)
    survey.dobs = data
    survey.std = wd
    survey.mtrue = model

    # Create a regularization
    reg = Regularization.Sparse(mesh,
                                indActive=actv,
                                mapping=idenMap,
                                nModels=3)
    reg.cell_weights = wr
    reg.mref = np.zeros(3 * nC)

    dmis = DataMisfit.l2_DataMisfit(survey)
    dmis.Wd = 1 / wd

    # Add directives to the inversion
    opt = Optimization.ProjectedGNCG(maxIter=100,
                                     lower=-1,
                                     upper=1.,
                                     maxIterLS=20,
                                     maxIterCG=10,
                                     tolCG=1e-3)
    invProb = InvProblem.BaseInvProblem(dmis, reg, opt)
    betaest = Directives.BetaEstimate_ByEig()

    # Here is where the norms are applied
    # Use pick a treshold parameter empirically based on the distribution of model
    # parameters (run last cell to see the histogram before and after IRLS)
    IRLS = Directives.Update_IRLS(norms=([2, 2, 2, 2]),
                                  eps=(1e-4, 1e-4),
                                  f_min_change=1e-2,
                                  minGNiter=3,
                                  beta_tol=1e-2)

    update_Jacobi = Directives.Update_lin_PreCond()

    inv = Inversion.BaseInversion(invProb,
                                  directiveList=[update_Jacobi, IRLS, betaest])

    mrec = inv.run(np.ones(3 * len(actv)) * 1e-4)

    # Here is the recovered susceptibility model
    ypanel = midx
    zpanel = -4
    m_lpx = actvMap * mrec[0:nC]
    m_lpy = actvMap * mrec[nC:2 * nC]
    m_lpz = actvMap * -mrec[2 * nC:]

    m_lpx[m_lpx == -100] = np.nan
    m_lpy[m_lpy == -100] = np.nan
    m_lpz[m_lpz == -100] = np.nan

    amp = np.sqrt(m_lpx**2. + m_lpy**2. + m_lpz**2.)

    m_lpx = (m_lpx / amp).reshape(mesh.vnC, order='F')
    m_lpy = (m_lpy / amp).reshape(mesh.vnC, order='F')
    m_lpz = (m_lpz / amp).reshape(mesh.vnC, order='F')
    amp = amp.reshape(mesh.vnC, order='F')
    sub = 2

    #    m_true = actvMap * model
    #    m_true[m_true==-100] = np.nan

    #Plot L2 model
    #    global im2

    xx, zz = mesh.gridCC[:, 0].reshape(
        mesh.vnC, order="F"), mesh.gridCC[:, 2].reshape(mesh.vnC, order="F")
    yy = mesh.gridCC[:, 1].reshape(mesh.vnC, order="F")

    #ptemp = ma.array(ptemp ,mask=np.isnan(ptemp))
    global im2
    im2 = ax2.contourf(xx[:, :, zpanel].T,
                       yy[:, :, zpanel].T,
                       amp[:, :, zpanel].T,
                       40,
                       vmin=vmin,
                       vmax=vmax,
                       clim=[vmin, vmax])
    global im4
    im4 = ax2.quiver(mkvc(xx[::sub, ::sub, zpanel].T),
                     mkvc(yy[::sub, ::sub, zpanel].T),
                     mkvc(m_lpx[::sub, ::sub, zpanel].T),
                     mkvc(m_lpy[::sub, ::sub, zpanel].T),
                     pivot='mid',
                     units="xy",
                     scale=0.2,
                     linewidths=(1, ),
                     edgecolors=('k'),
                     headaxislength=0.1,
                     headwidth=10,
                     headlength=30)
    ax2.set_aspect('equal')
    ax2.xaxis.set_visible(False)
    ax2.set_xlim(-60, 60)
    ax2.set_ylim(-60, 60)
    ax2.set_title('Effective Susceptibility')
    ax2.set_ylabel('Northing (m)', size=14)

    global im3
    im3 = ax3.contourf(xx[:, ypanel, :].T,
                       zz[:, ypanel, :].T,
                       amp[:, ypanel, :].T,
                       40,
                       vmin=vmin,
                       vmax=vmax,
                       clim=[vmin, vmax])

    global im6
    im6 = ax3.quiver(mkvc(xx[::sub, ypanel, ::sub].T),
                     mkvc(zz[::sub, ypanel, ::sub].T),
                     mkvc(m_lpx[::sub, ypanel, ::sub].T),
                     mkvc(m_lpz[::sub, ypanel, ::sub].T),
                     pivot='mid',
                     units="xy",
                     scale=0.2,
                     linewidths=(1, ),
                     edgecolors=('k'),
                     headaxislength=0.1,
                     headwidth=10,
                     headlength=30)
    ax3.set_aspect('equal')
    ax3.set_xlim(-60, 60)
    ax3.set_ylim(-60, 0)
    ax3.set_title('EW Section')
    ax3.set_xlabel('Easting (m)', size=14)
    ax3.set_ylabel('Elevation (m)', size=14)

    ax4 = fig.add_axes(
        [pos.x0 + 0.75, pos.y0 + 0.25, pos.height * 0.02, pos.height * 0.4])
    cb = plt.colorbar(im3,
                      cax=ax4,
                      orientation="vertical",
                      ax=ax1,
                      ticks=np.linspace(im3.vmin, im3.vmax, 4),
                      format="${%.3f}$")
    cb.set_label("$\kappa_{e}$ (SI)", size=12)
Beispiel #6
0
def animate(ii):

    removePlt()
#ii=1
    if ii<18:
        dec = 90
        inc = 0. + ii*5.

    elif ii < 36:

        dec = 270.
        inc = 90. - (ii-18)*5.
        
    elif ii < 54:
        
        dec = 270.
        inc = 0.+ (ii-36)*5.
        
    else:
        
        dec = 90
        inc = 90. - (ii-54)*5.



    ax1.axis('equal')
    block_xyz = np.asarray([[-.2, -.2, .2, .2, 0],
                           [-.25, -.25, -.25, -.25, 0.5],
                           [-.2, .2, .2, -.2, 0]])*10.

    block_xyz[1][:] -=20.
    # rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec))

    # xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot,
    #                                     np.r_[p.xc, p.yc, p.zc])

    R = Utils.rotationMatrix(inc, dec)

    xyz = R.dot(block_xyz).T
    xyz[:,2] -= depth + dz/2.
    #print xyz
    # Face 1
    ax1.add_collection3d(Poly3DCollection([zip(xyz[:4, 0],
                                               xyz[:4, 1],
                                               xyz[:4, 2])], facecolors='b'))

    ax1.add_collection3d(Poly3DCollection([zip(xyz[[1, 2, 4], 0],
                                               xyz[[1, 2, 4], 1],
                                               xyz[[1, 2, 4], 2])], facecolors='b'))

    ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 1, 4], 0],
                                               xyz[[0, 1, 4], 1],
                                               xyz[[0, 1, 4], 2])], facecolors='b'))

    ax1.add_collection3d(Poly3DCollection([zip(xyz[[2, 3, 4], 0],
                                               xyz[[2, 3, 4], 1],
                                               xyz[[2, 3, 4], 2])], facecolors='b'))

    ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 3, 4], 0],
                                           xyz[[0, 3, 4], 1],
                                           xyz[[0, 3, 4], 2])], facecolors='b'))
    ax1.w_yaxis.set_ticklabels('')
    ax1.w_yaxis.set_label_text('')
    ax1.w_zaxis.set_ticklabels('')
    ax1.w_zaxis.set_label_text('')
#    block_xyz[1][:] +=20.
#    # rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec))
#
#    # xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot,
#    #                                     np.r_[p.xc, p.yc, p.zc])
#
#    R = Utils.rotationMatrix(rinc, rdec)
#
#    xyz = R.dot(block_xyz).T
#    xyz[:,2] -= depth + dz/2.
#
#    #print xyz
#    # Face 1
#    ax1.add_collection3d(Poly3DCollection([zip(xyz[:4, 0],
#                                               xyz[:4, 1],
#                                               xyz[:4, 2])], facecolors='y'))
#
#    ax1.add_collection3d(Poly3DCollection([zip(xyz[[1, 2, 4], 0],
#                                               xyz[[1, 2, 4], 1],
#                                               xyz[[1, 2, 4], 2])], facecolors='y'))
#
#    ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 1, 4], 0],
#                                               xyz[[0, 1, 4], 1],
#                                               xyz[[0, 1, 4], 2])], facecolors='y'))
#
#    ax1.add_collection3d(Poly3DCollection([zip(xyz[[2, 3, 4], 0],
#                                               xyz[[2, 3, 4], 1],
#                                               xyz[[2, 3, 4], 2])], facecolors='y'))
#
#    ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 3, 4], 0],
#                                           xyz[[0, 3, 4], 1],
#                                           xyz[[0, 3, 4], 2])], facecolors='y'))

    MAG.plotObj3D(p, rx_h, View_elev, View_azim, npts2D, xylim, profile="X", fig= fig, axs = ax1, plotSurvey=False)
    # Create problem
    prob = PFlocal.problem()
    prob.prism = p
    prob.survey = srvy

    prob.Bdec, prob.Binc, prob.Bigrf = dec, inc, Bigrf
    prob.Q, prob.rinc, prob.rdec = Q, rinc, rdec
    prob.uType, prob.mType = comp, 'total'
    prob.susc = susc

    # Compute fields from prism
    b_ind, b_rem = prob.fields()

    if irt == 'total':
        out = b_ind + b_rem

    elif irt == 'induced':
        out = b_ind

    else:
        out = b_rem

    #out = plogMagSurvey2D(prob, susc, Einc, Edec, Bigrf, x1, y1, x2, y2, comp, irt,  Q, rinc, rdec, fig=fig, axs1=ax2, axs2=ax3)

    #dat = axs1.contourf(X,Y, np.reshape(out, (X.shape)).T
    global im1
    im1 = ax1.contourf(X,Y,np.reshape(out, (X.shape)).T,20,zdir='z',offset=rx_h+5., clim=clim, vmin=clim[0],vmax=clim[1], cmap = 'RdBu_r')

    ax5 = fig.add_axes([pos.x0 , pos.y0+0.25,  pos.height*0.02, pos.height*0.4])
    cb = plt.colorbar(im1,cax=ax5, orientation="vertical", ax = ax1, ticks=np.linspace(im1.vmin,im1.vmax, 4), format="${%.0f}$")
    cb.set_label("$B^{TMI}\;(nT)$",size=12)
    cb.ax.yaxis.set_ticks_position('left')
    cb.ax.yaxis.set_label_position('left')

    global im5
    im5 = ax1.text(0,0,-60,'$B_0, I: ' + str(inc) + '^\circ, D: ' + str(dec) + '^\circ$', horizontalalignment='center')


    H0 = (Bigrf,inc,dec)


    actv = np.ones(mesh.nC)==1
    # Create active map to go from reduce space to full
    actvMap = Maps.InjectActiveCells(mesh, actv, -100)
    nC = len(actv)

    # Create a MAGsurvey
    rxLoc = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)]
    rxLoc = PF.BaseMag.RxObs(rxLoc)
    srcField = PF.BaseMag.SrcField([rxLoc],param = H0)
    survey = PF.BaseMag.LinearSurvey(srcField)

    # We can now create a susceptibility model and generate data
    # Lets start with a simple block in half-space
#    model = np.zeros((mesh.nCx,mesh.nCy,mesh.nCz))
#    model[(midx-2):(midx+2),(midy-2):(midy+2),-6:-2] = 0.02
#    model = mkvc(model)
#    model = model[actv]

    # Create active map to go from reduce set to full
    actvMap = Maps.InjectActiveCells(mesh, actv, -100)

    # Creat reduced identity map
    idenMap = Maps.IdentityMap(nP = nC)

    # Create the forward model operator
    probinv = PF.Magnetics.MagneticIntegral(mesh, mapping = idenMap, actInd = actv)

    # Pair the survey and problem
    survey.pair(probinv)

    # Compute linear forward operator and compute some data
#    d = probinv.fields(model)

    # Plot the model
#    m_true = actvMap * model
#    m_true[m_true==-100] = np.nan
    #plt.figure()
    #ax = plt.subplot(212)
    #mesh.plotSlice(m_true, ax = ax, normal = 'Y', ind=midy, grid=True, clim = (0., model.max()/3.), pcolorOpts={'cmap':'viridis'})
    #plt.title('A simple block model.')
    #plt.xlabel('x'); plt.ylabel('z')
    #plt.gca().set_aspect('equal', adjustable='box')

    # We can now generate data
    data = out + np.random.randn(len(out)) # We add some random Gaussian noise (1nT)
    wd = np.ones(len(data))*1. # Assign flat uncertainties

    # Create distance weights from our linera forward operator
    wr = np.sum(probinv.G**2.,axis=0)**0.5
    wr = ( wr/np.max(wr) )

    #survey.makeSyntheticData(data, std=0.01)
    survey.dobs= data
    survey.std = wd
    survey.mtrue = model

    # Create a regularization
    reg = Regularization.Sparse(mesh, indActive=actv, mapping=idenMap)
    reg.cell_weights = wr

    dmis = DataMisfit.l2_DataMisfit(survey)
    dmis.Wd = 1/wd

    # Add directives to the inversion
    opt = Optimization.ProjectedGNCG(maxIter=100 ,lower=0.,upper=1., maxIterLS = 20, maxIterCG= 10, tolCG = 1e-3)
    invProb = InvProblem.BaseInvProblem(dmis, reg, opt)
    betaest = Directives.BetaEstimate_ByEig()

    # Here is where the norms are applied
    # Use pick a treshold parameter empirically based on the distribution of model
    # parameters (run last cell to see the histogram before and after IRLS)
    IRLS = Directives.Update_IRLS( norms=([2,2,2,2]),  eps=(2e-3,2e-3), f_min_change = 1e-3, minGNiter=3,beta_tol=1e-2)
    update_Jacobi = Directives.Update_lin_PreCond()
    inv = Inversion.BaseInversion(invProb, directiveList=[IRLS,betaest,update_Jacobi])

    m0 = np.ones(nC)*1e-4

    mrec = inv.run(m0)

    # Here is the recovered susceptibility model
    ypanel = midx
    zpanel = -4
    m_l2 = actvMap * reg.l2model
    m_l2[m_l2==-100] = np.nan

    m_lp = actvMap * mrec
    m_lp[m_lp==-100] = np.nan

#    m_true = actvMap * model
#    m_true[m_true==-100] = np.nan

    #Plot L2 model
    #global im2

    xx, zz = mesh.gridCC[:,0].reshape(mesh.vnC, order="F"), mesh.gridCC[:,2].reshape(mesh.vnC, order="F")
    yy = mesh.gridCC[:,1].reshape(mesh.vnC, order="F")

    temp = m_lp.reshape(mesh.vnC, order='F')
    ptemp = temp[:,:,indz].T
    #ptemp = ma.array(ptemp ,mask=np.isnan(ptemp))
    global im2
    im2 = ax2.contourf(xx[:,:,indz].T,yy[:,:,indz].T,ptemp,20, vmin = vmin, vmax= vmax, clim=[vmin,vmax])
    ax2.plot(([mesh.vectorCCx[0],mesh.vectorCCx[-1]]),([mesh.vectorCCy[indy],mesh.vectorCCy[indy]]),color='w')
    ax2.set_aspect('equal')
    ax2.xaxis.set_visible(False)
    ax2.set_xlim(-60,60)
    ax2.set_ylim(-60,60)
    ax2.set_title('Induced Model')
    ax2.set_ylabel('Northing (m)',size=14)


    ptemp = temp[:,indy,:].T
    global im3
    im3 = ax3.contourf(xx[:,indy,:].T,zz[:,indy,:].T,ptemp,20, vmin = vmin, vmax= vmax, clim=[vmin,vmax])
    ax3.set_aspect('equal')
    ax3.set_xlim(-60,60)
    ax3.set_ylim(-60,0)
    ax3.set_title('EW Section')
    ax3.set_xlabel('Easting (m)',size=14)
    ax3.set_ylabel('Elevation (m)',size=14)


    ax4 = fig.add_axes([pos.x0 + 0.75, pos.y0+0.25,  pos.height*0.02, pos.height*0.4])
    cb = plt.colorbar(im3,cax=ax4, orientation="vertical", ax = ax1, ticks=np.linspace(im3.vmin,im3.vmax, 4), format="${%.3f}$")
    cb.set_label("Susceptibility (SI)",size=12)
Beispiel #7
0
#
#    dec = 90.
#    inc = 90. - (ii-19)*10.
    
MAG.plotObj3D(p, rx_h, View_elev, View_azim, npts2D, xylim, profile="X", fig= fig, axs = ax1, plotSurvey=False)
plt.show()
block_xyz = np.asarray([[-.2, -.2, .2, .2, 0],
                       [-.25, -.25, -.25, -.25, 0.5],
                       [-.2, .2, .2, -.2, 0]])

# rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec))

# xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot,
#                                     np.r_[p.xc, p.yc, p.zc])

R = Utils.rotationMatrix(inc, dec)

xyz = R.dot(block_xyz).T

#print xyz
# Face 1
ax1.add_collection3d(Poly3DCollection([zip(xyz[:4, 0]-1,
                                           xyz[:4, 1],
                                           xyz[:4, 2]-4)], facecolors='w'))

ax1.add_collection3d(Poly3DCollection([zip(xyz[[1, 2, 4], 0]-1,
                                           xyz[[1, 2, 4], 1],
                                           xyz[[1, 2, 4], 2]-4)], facecolors='b'))

ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 1, 4], 0]-1,
                                           xyz[[0, 1, 4], 1],
Beispiel #8
0
def plotObj3D(p,
              rx_h,
              elev,
              azim,
              npts2D,
              xylim,
              profile=None,
              x0=15.,
              y0=0.,
              fig=None,
              axs=None,
              plotSurvey=True,
              title=None):

    # define the survey area
    surveyArea = (-xylim, xylim, -xylim, xylim)
    shape = (npts2D, npts2D)

    xr = np.linspace(-xylim, xylim, shape[0])
    yr = np.linspace(-xylim, xylim, shape[1])
    X, Y = np.meshgrid(xr, yr)
    Z = np.ones(np.shape(X)) * rx_h

    rxLoc = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)]

    depth = p.z0
    x1, x2 = p.xn[0] - p.xc, p.xn[1] - p.xc
    y1, y2 = p.yn[0] - p.yc, p.yn[1] - p.yc
    z1, z2 = p.zn[0] - p.zc, p.zn[1] - p.zc
    pinc, pdec = p.pinc, p.pdec

    if fig is None:
        fig = plt.figure(figsize=(7, 7))

    if axs is None:
        axs = fig.add_subplot(111, projection='3d')

    if title is not None:
        axs.set_title(title)

    plt.rcParams.update({'font.size': 13})

    axs.set_xlim3d(surveyArea[:2])
    axs.set_ylim3d(surveyArea[2:])
    #     axs.set_zlim3d(depth+np.array(surveyArea[:2]))
    axs.set_zlim3d(-surveyArea[-1] * 2, 3)

    # Create a rectangular prism, rotate and plot
    block_xyz = np.asarray([[x1, x1, x2, x2, x1, x1, x2, x2],
                            [y1, y2, y2, y1, y1, y2, y2, y1],
                            [z1, z1, z1, z1, z2, z2, z2, z2]])

    # rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec))

    # xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot,
    #                                     np.r_[p.xc, p.yc, p.zc])

    R = Utils.rotationMatrix(pinc, pdec)

    xyz = R.dot(block_xyz).T

    #print xyz
    # Face 1
    axs.add_collection3d(
        Poly3DCollection(
            [zip(xyz[:4, 0] + p.xc, xyz[:4, 1] + p.yc, xyz[:4, 2] + p.zc)],
            facecolors='w'))

    # Face 2
    axs.add_collection3d(
        Poly3DCollection(
            [zip(xyz[4:, 0] + p.xc, xyz[4:, 1] + p.yc, xyz[4:, 2] + p.zc)],
            facecolors='w'))

    # Face 3
    axs.add_collection3d(
        Poly3DCollection([
            zip(xyz[[0, 1, 5, 4], 0] + p.xc, xyz[[0, 1, 5, 4], 1] + p.yc,
                xyz[[0, 1, 5, 4], 2] + p.zc)
        ],
                         facecolors='w'))

    # Face 4
    axs.add_collection3d(
        Poly3DCollection([
            zip(xyz[[3, 2, 6, 7], 0] + p.xc, xyz[[3, 2, 6, 7], 1] + p.yc,
                xyz[[3, 2, 6, 7], 2] + p.zc)
        ],
                         facecolors='w'))
    #
    #    # Face 5
    #    axs.add_collection3d(Poly3DCollection([zip(xyz[[0, 4, 7, 3], 0]+p.xc,
    #                                               xyz[[0, 4, 7, 3], 1]+p.yc,
    #                                               xyz[[0, 4, 7, 3], 2]+p.zc)], facecolors='w'))

    #    # Face 6
    #    axs.add_collection3d(Poly3DCollection([zip(xyz[[1, 5, 6, 2], 0]+p.xc,
    #                                               xyz[[1, 5, 6, 2], 1]+p.yc,
    #                                               xyz[[1, 5, 6, 2], 2]+p.zc)], facecolors='w'))

    plt.show()
    axs.set_xlabel('Easting (X; m)')
    axs.set_ylabel('Northing (Y; m)')
    axs.set_zlabel('Depth (Z; m)')
    # axs.invert_zaxis()
    # axs.invert_yaxis()

    if plotSurvey:
        axs.plot(rxLoc[:, 0], rxLoc[:, 1], rxLoc[:, 2], '.g', alpha=0.5)

    if profile == "X":
        axs.plot(np.r_[surveyArea[:2]], np.r_[0., 0.], np.r_[rx_h, rx_h], 'r-')
    elif profile == "Y":
        axs.plot(np.r_[0., 0.], np.r_[surveyArea[2:]], np.r_[rx_h, rx_h], 'r-')
    elif profile == "XY":
        axs.plot(np.r_[0., 0.], np.r_[surveyArea[:2]], np.r_[rx_h, rx_h], 'r-')
        axs.plot(np.r_[surveyArea[2:]], np.r_[0., 0.], np.r_[rx_h, rx_h], 'r-')

    axs.view_init(elev, azim)
    plt.show()

    return True