Ejemplo n.º 1
0
    def test_ana_forward(self):

        survey = PF.BaseMag.BaseMagSurvey()

        Inc = 45.
        Dec = 45.
        Btot = 51000

        b0 = PF.MagAnalytics.IDTtoxyz(Inc, Dec, Btot)
        survey.setBackgroundField(Inc, Dec, Btot)
        xr = np.linspace(-300, 300, 41)
        yr = np.linspace(-300, 300, 41)
        X, Y = np.meshgrid(xr, yr)
        Z = np.ones((xr.size, yr.size))*150
        rxLoc = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)]
        survey.rxLoc = rxLoc

        self.prob.pair(survey)
        u = self.prob.fields(self.chi)
        B = u['B']

        bxa, bya, bza = PF.MagAnalytics.MagSphereAnaFunA(rxLoc[:, 0], rxLoc[:, 1], rxLoc[:, 2], 100., 0., 0., 0., 0.01, b0, 'secondary')

        dpred = survey.projectFieldsAsVector(B)
        err = np.linalg.norm(dpred-np.r_[bxa, bya, bza])/np.linalg.norm(np.r_[bxa, bya, bza])
        self.assertTrue(err < 0.08)
Ejemplo n.º 2
0
    def test_ana_forward(self):

        survey = PF.BaseMag.BaseMagSurvey()

        Inc = 45.0
        Dec = 45.0
        Btot = 51000

        b0 = PF.MagAnalytics.IDTtoxyz(Inc, Dec, Btot)
        survey.setBackgroundField(Inc, Dec, Btot)
        xr = np.linspace(-300, 300, 41)
        yr = np.linspace(-300, 300, 41)
        X, Y = np.meshgrid(xr, yr)
        Z = np.ones((xr.size, yr.size)) * 150
        rxLoc = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)]
        survey.rxLoc = rxLoc

        self.prob.pair(survey)
        u = self.prob.fields(self.chi)
        B = u["B"]

        bxa, bya, bza = PF.MagAnalytics.MagSphereAnaFunA(
            rxLoc[:, 0], rxLoc[:, 1], rxLoc[:, 2], 100.0, 0.0, 0.0, 0.0, 0.01, b0, "secondary"
        )

        dpred = survey.projectFieldsAsVector(B)
        err = np.linalg.norm(dpred - np.r_[bxa, bya, bza]) / np.linalg.norm(np.r_[bxa, bya, bza])
        self.assertTrue(err < 0.08)
Ejemplo n.º 3
0
def run(plotIt=True):
    """
        PF: Magnetics: Analytics
        ========================

        Comparing the magnetics field in Vancouver to Seoul

    """

    xr = np.linspace(-300, 300, 41)
    yr = np.linspace(-300, 300, 41)
    X, Y = np.meshgrid(xr, yr)
    Z = np.ones((np.size(xr), np.size(yr)))*150

    # Bz component in Korea
    inckr = -8. + 3./60
    deckr = 54. + 9./60
    btotkr = 50898.6
    Bokr = PF.MagAnalytics.IDTtoxyz(inckr, deckr, btotkr)

    bx, by, bz = PF.MagAnalytics.MagSphereAnaFunA(
        X, Y, Z, 100., 0., 0., 0., 0.01, Bokr, 'secondary'
    )
    Bzkr = np.reshape(bz, (np.size(xr), np.size(yr)), order='F')

    # Bz component in Canada
    incca = 16. + 49./60
    decca = 70. + 19./60
    btotca = 54692.1
    Boca = PF.MagAnalytics.IDTtoxyz(incca, decca, btotca)

    bx, by, bz = PF.MagAnalytics.MagSphereAnaFunA(
        X, Y, Z, 100., 0., 0., 0., 0.01, Boca, 'secondary'
    )
    Bzca = np.reshape(bz, (np.size(xr), np.size(yr)), order='F')

    if plotIt:
        import matplotlib.pyplot as plt
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        fig = plt.figure(figsize=(14, 5))

        ax1 = plt.subplot(121)
        dat1 = plt.imshow(Bzkr, extent=[min(xr), max(xr), min(yr), max(yr)])
        divider = make_axes_locatable(ax1)
        cax1 = divider.append_axes("right", size="5%", pad=0.05)
        ax1.set_xlabel('East-West (m)')
        ax1.set_ylabel('South-North (m)')
        plt.colorbar(dat1, cax=cax1)
        ax1.set_title('$B_z$ field at Seoul, South Korea')

        ax2 = plt.subplot(122)
        dat2 = plt.imshow(Bzca, extent=[min(xr), max(xr), min(yr), max(yr)])
        divider = make_axes_locatable(ax2)
        cax2 = divider.append_axes("right", size="5%", pad=0.05)
        ax2.set_xlabel('East-West (m)')
        ax2.set_ylabel('South-North (m)')
        plt.colorbar(dat2, cax=cax2)
        ax2.set_title('$B_z$ field at Vancouver, Canada')
        plt.show()
Ejemplo n.º 4
0
def run(plotIt=True):
    """

        Plotting 2D data
        ================

        Often measured data is in 2D, but locations are not gridded.
        Data can be vectoral, hence we want to plot direction and
        amplitude of the vector. Following example use SimPEG's
        analytic function (electric dipole) to generate data
        at 2D plane.

    """
    # Make un-gridded xyz points

    x = np.linspace(-50, 50, 30)
    x += np.random.randn(x.size) * 0.1 * x
    y = np.linspace(-50, 50, 30)
    y += np.random.randn(x.size) * 0.1 * y
    z = np.r_[50.]
    xyz = Utils.ndgrid(x, y, z)
    sig = 1.
    f = np.r_[1.]
    srcLoc = np.r_[0., 0., 0.]

    # Use analytic fuction to compute Ex, Ey, Ez
    Ex, Ey, Ez = EM.Analytics.E_from_ElectricDipoleWholeSpace(
        xyz, srcLoc, sig, f)

    if plotIt:
        plt.figure()
        ax1 = plt.subplot(121)
        ax2 = plt.subplot(122)
        # Plot Real Ex (scalar)
        cont1, ax1 = Utils.plot2Ddata(xyz,
                                      Ex.real,
                                      dataloc=True,
                                      ax=ax1,
                                      contourOpts={"cmap": "viridis"})
        # Make it as (ndata,2) matrix
        E = np.c_[Ex, Ey]
        # Plot Real E (vector)
        cont2, ax2 = Utils.plot2Ddata(xyz,
                                      E.real,
                                      vec=True,
                                      ax=ax2,
                                      contourOpts={"cmap": "viridis"})
        plt.colorbar(cont1, ax=ax1, orientation="horizontal")
        plt.colorbar(cont2, ax=ax2, orientation="horizontal")
        ax1.set_xlabel("x")
        ax1.set_ylabel("y")
        ax2.set_xlabel("x")
        ax2.set_ylabel("y")

        ax1.set_aspect('equal', adjustable='box')
        ax2.set_aspect('equal', adjustable='box')
Ejemplo n.º 5
0
def run(plotIt = True):
    """

        Plotting 2D data
        ================

        Often measured data is in 2D, but locations are not gridded.
        Data can be vectoral, hence we want to plot direction and
        amplitude of the vector. Following example use SimPEG's
        analytic function (electric dipole) to generate data
        at 2D plane.

    """
    # Make un-gridded xyz points

    x = np.linspace(-50, 50, 30)
    x += np.random.randn(x.size)*0.1*x
    y = np.linspace(-50, 50, 30)
    y += np.random.randn(x.size)*0.1*y
    z = np.r_[50.]
    xyz = Utils.ndgrid(x, y, z)
    sig = 1.
    f = np.r_[1.]
    srcLoc = np.r_[0., 0., 0.]

    # Use analytic fuction to compute Ex, Ey, Ez
    Ex, Ey, Ez = EM.Analytics.E_from_ElectricDipoleWholeSpace(xyz, srcLoc, sig, f)

    if plotIt:
        import matplotlib.pyplot as plt
        plt.figure()
        ax1 = plt.subplot(121)
        ax2 = plt.subplot(122)
        # Plot Real Ex (scalar)
        cont1, ax1 = Utils.plot2Ddata(xyz, Ex.real, dataloc=True,
                                      ax=ax1, contourOpts={"cmap": "viridis"})
        # Make it as (ndata,2) matrix
        E = np.c_[Ex, Ey]
        # Plot Real E (vector)
        cont2, ax2 = Utils.plot2Ddata(xyz, E.real, vec=True,
                                      ax=ax2, contourOpts={"cmap": "viridis"})
        cb1 = plt.colorbar(cont1, ax=ax1, orientation="horizontal")
        cb2 = plt.colorbar(cont2, ax=ax2, orientation="horizontal")
        ax1.set_xlabel("x")
        ax1.set_ylabel("y")
        ax2.set_xlabel("x")
        ax2.set_ylabel("y")

        ax1.set_aspect('equal', adjustable='box')
        ax2.set_aspect('equal', adjustable='box')
        plt.show()
Ejemplo n.º 6
0
    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')
Ejemplo n.º 7
0
    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")
        sighalf = 1e-2
        sigma = np.ones(mesh.nC)*sighalf
        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)]]
        data_anal = EM.Analytics.DCAnalyticHalf(np.r_[A0loc, 0.], rxloc, sighalf, earth_type="halfspace")

        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Pole([rx], A0loc)
        survey = DC.Survey_ky([src0])

        self.survey = survey
        self.mesh = mesh
        self.sigma = sigma
        self.data_anal = data_anal

        try:
            from pymatsolver import MumpsSolver
            self.Solver = MumpsSolver
        except ImportError, e:
            self.Solver = SolverLU
Ejemplo n.º 8
0
    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")
        sighalf = 1e-2
        sigma = np.ones(mesh.nC) * sighalf
        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)]]
        data_anal = EM.Analytics.DCAnalytic_Pole_Dipole(np.r_[A0loc, 0.],
                                                        rxloc,
                                                        sighalf,
                                                        earth_type="halfspace")

        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Pole([rx], A0loc)
        survey = DC.Survey_ky([src0])

        self.survey = survey
        self.mesh = mesh
        self.sigma = sigma
        self.data_anal = data_anal

        try:
            from pymatsolver import PardisoSolver
            self.Solver = PardisoSolver
        except ImportError:
            self.Solver = SolverLU
Ejemplo n.º 9
0
    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_xyz = PF.Gravity.GravityIntegral(mesh,
                                                   mapping=idenMap,
                                                   actInd=sph_ind,
                                                   forwardOnly=True,
                                                   rtype='xyz')

        self.prob_z = PF.Gravity.GravityIntegral(mesh,
                                                 mapping=idenMap,
                                                 actInd=sph_ind,
                                                 forwardOnly=True,
                                                 rtype='z')
Ejemplo n.º 10
0
    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')
Ejemplo n.º 11
0
    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_xyz = PF.Gravity.GravityIntegral(mesh, mapping=idenMap,
                                                   actInd=sph_ind,
                                                   forwardOnly=True,
                                                   rtype='xyz')

        self.prob_z = PF.Gravity.GravityIntegral(mesh, mapping=idenMap,
                                                 actInd=sph_ind,
                                                 forwardOnly=True,
                                                 rtype='z')
Ejemplo n.º 12
0
    def plot(self, m):
        import matplotlib.pyplot as plt

        m = m[0]
        h = np.linspace(-100, 20, 1000)
        ax = plt.subplot(121)
        ax.plot(self.theta(h, m), h)
        ax = plt.subplot(122)
        ax.semilogx(self.k(h, m), h)
Ejemplo n.º 13
0
    def plot(self, m):
        import matplotlib.pyplot as plt

        m = m[0]
        h = np.linspace(-100, 20, 1000)
        ax = plt.subplot(121)
        ax.plot(self.theta(h, m), h)
        ax = plt.subplot(122)
        ax.semilogx(self.k(h, m), h)
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
0
topo = np.genfromtxt(topofile, skip_header=1)

# Offset data above topo
zoffset = 2

# Load mesh file
B = np.array(([90., 0., 50000.]))

M = np.array(([90., 0., 315.]))

# Sphere radius
R = 25.

#%% Script starts here
# # Create a grid of observations and offset the z from topo
xr = np.linspace(-99., 99., 40)
yr = np.linspace(-49., 49., 20)
X, Y = np.meshgrid(xr, yr)

F = interpolation.NearestNDInterpolator(topo[:, 0:2], topo[:, 2])
Z = F(X, Y) + zoffset
rxLoc = np.c_[Utils.mkvc(X.T), Utils.mkvc(Y.T), Utils.mkvc(Z.T)]

ndata = rxLoc.shape[0]

sclx = 100.

dx = 10

nc = int(sclx / dx)
Ejemplo n.º 18
0
def run(plotIt=True):
    """
    1D FDEM Mu Inversion
    ====================

    1D inversion of Magnetic Susceptibility from FDEM data assuming a fixed
    electrical conductivity

    """

    # Set up cylindrically symmeric mesh
    cs, ncx, ncz, npad = 10., 15, 25, 13  # padded cyl mesh
    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')

    # Geologic Parameters model
    layerz = np.r_[-100., -50.]
    layer = (mesh.vectorCCz >= layerz[0]) & (mesh.vectorCCz <= layerz[1])
    active = mesh.vectorCCz < 0.

    # Electrical Conductivity
    sig_half = 1e-2  # Half-space conductivity
    sig_air = 1e-8  # Air conductivity
    sig_layer = 1e-2  # Layer conductivity
    sigma = np.ones(mesh.nCz) * sig_air
    sigma[active] = sig_half
    sigma[layer] = sig_layer

    # mur - relative magnetic permeability
    mur_half = 1.
    mur_air = 1.
    mur_layer = 2.
    mur = np.ones(mesh.nCz) * mur_air
    mur[active] = mur_half
    mur[layer] = mur_layer

    mtrue = mur[active]

    # Maps
    actMap = Maps.InjectActiveCells(mesh, active, mur_air, nC=mesh.nCz)
    surj1Dmap = Maps.SurjectVertical1D(mesh)
    murMap = Maps.MuRelative(mesh)

    # Mapping
    muMap = murMap * surj1Dmap * actMap

    # ----- FDEM problem & survey -----
    rxlocs = Utils.ndgrid([np.r_[10.], np.r_[0], np.r_[30.]])
    bzr = FDEM.Rx.Point_bSecondary(rxlocs, 'z', 'real')
    # bzi = FDEM.Rx.Point_bSecondary(rxlocs, 'z', 'imag')

    freqs = np.linspace(2000, 10000, 10)  #np.logspace(3, 4, 10)
    srcLoc = np.array([0., 0., 30.])

    print('min skin depth = ', 500. / np.sqrt(freqs.max() * sig_half),
          'max skin depth = ', 500. / np.sqrt(freqs.min() * sig_half))
    print('max x ', mesh.vectorCCx.max(), 'min z ', mesh.vectorCCz.min(),
          'max z ', mesh.vectorCCz.max())

    srcList = [
        FDEM.Src.MagDipole([bzr], freq, srcLoc, orientation='Z')
        for freq in freqs
    ]

    surveyFD = FDEM.Survey(srcList)
    prbFD = FDEM.Problem3D_b(mesh,
                             sigma=surj1Dmap * sigma,
                             muMap=muMap,
                             Solver=Solver)
    prbFD.pair(surveyFD)
    std = 0.03
    surveyFD.makeSyntheticData(mtrue, std)
    surveyFD.eps = np.linalg.norm(surveyFD.dtrue) * 1e-6

    # FDEM inversion
    np.random.seed(13472)
    dmisfit = DataMisfit.l2_DataMisfit(surveyFD)
    regMesh = Mesh.TensorMesh([mesh.hz[muMap.maps[-1].indActive]])
    reg = Regularization.Simple(regMesh)
    opt = Optimization.InexactGaussNewton(maxIterCG=10)
    invProb = InvProblem.BaseInvProblem(dmisfit, reg, opt)

    # Inversion Directives    betaest = Directives.BetaEstimate_ByEig(beta0_ratio=2.)

    beta = Directives.BetaSchedule(coolingFactor=4, coolingRate=3)
    betaest = Directives.BetaEstimate_ByEig(beta0_ratio=2.)
    target = Directives.TargetMisfit()
    directiveList = [beta, betaest, target]

    inv = Inversion.BaseInversion(invProb, directiveList=directiveList)
    m0 = mur_half * np.ones(mtrue.size)
    reg.alpha_s = 2e-2
    reg.alpha_x = 1.
    prbFD.counter = opt.counter = Utils.Counter()
    opt.remember('xc')
    moptFD = inv.run(m0)

    dpredFD = surveyFD.dpred(moptFD)

    if plotIt:
        fig, ax = plt.subplots(1, 3, figsize=(10, 6))

        fs = 13  # fontsize
        matplotlib.rcParams['font.size'] = fs

        # Plot the conductivity model
        ax[0].semilogx(sigma[active], mesh.vectorCCz[active], 'k-', lw=2)
        ax[0].set_ylim(-500, 0)
        ax[0].set_xlim(5e-3, 1e-1)

        ax[0].set_xlabel('Conductivity (S/m)', fontsize=fs)
        ax[0].set_ylabel('Depth (m)', fontsize=fs)
        ax[0].grid(which='both',
                   color='k',
                   alpha=0.5,
                   linestyle='-',
                   linewidth=0.2)
        ax[0].legend(['Conductivity Model'], fontsize=fs, loc=4)

        # Plot the permeability model
        ax[1].plot(mur[active], mesh.vectorCCz[active], 'k-', lw=2)
        ax[1].plot(moptFD, mesh.vectorCCz[active], 'b-', lw=2)
        ax[1].set_ylim(-500, 0)
        ax[1].set_xlim(0.5, 2.1)

        ax[1].set_xlabel('Relative Permeability', fontsize=fs)
        ax[1].set_ylabel('Depth (m)', fontsize=fs)
        ax[1].grid(which='both',
                   color='k',
                   alpha=0.5,
                   linestyle='-',
                   linewidth=0.2)
        ax[1].legend(['True', 'Predicted'], fontsize=fs, loc=4)

        # plot the data misfits - negative b/c we choose positive to be in the
        # direction of primary

        ax[2].plot(freqs, -surveyFD.dobs, 'k-', lw=2)
        # ax[2].plot(freqs, -surveyFD.dobs[1::2], 'k--', lw=2)

        ax[2].loglog(freqs, -dpredFD, 'bo', ms=6)
        # ax[2].loglog(freqs, -dpredFD[1::2], 'b+', markeredgewidth=2., ms=10)

        # Labels, gridlines, etc
        ax[2].grid(which='both', alpha=0.5, linestyle='-', linewidth=0.2)
        ax[2].grid(which='both', alpha=0.5, linestyle='-', linewidth=0.2)

        ax[2].set_xlabel('Frequency (Hz)', fontsize=fs)
        ax[2].set_ylabel('Vertical magnetic field (-T)', fontsize=fs)

        # ax[2].legend(("Obs", "Pred"), fontsize=fs)
        ax[2].legend(("z-Obs (real)", "z-Pred (real)"), fontsize=fs)
        ax[2].set_xlim(freqs.max(), freqs.min())

        ax[0].set_title("(a) Conductivity Model", fontsize=fs)
        ax[1].set_title("(b) $\mu_r$ Model", fontsize=fs)
        ax[2].set_title("(c) FDEM observed vs. predicted", fontsize=fs)
        # ax[2].set_title("(c) TDEM observed vs. predicted", fontsize=fs)

        plt.tight_layout(pad=1.5)
Ejemplo n.º 19
0
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
Ejemplo n.º 20
0
dsep = '\\'

topo = np.genfromtxt(home_dir + dsep + topo_file, skip_header=1)
Ftopo = NearestNDInterpolator(topo[:, :2], topo[:, 2])

# Forward solver

# Number of padding cells to remove from plotting
padc = 15

# Plotting parameters
xmin, xmax = 10500, 13000
zmin, zmax = -600, 600
vmin, vmax = 0, 75

z = np.linspace(zmin, zmax, 4)
x = np.asarray([11000, 11750, 12500])
#%% load obs file 3D
dobs = DC.readUBC_DC3Dobs(home_dir + dsep + DCobs_file)
DCsurvey = dobs['DCsurvey']

dobs = DC.readUBC_DC3Dobs(home_dir + dsep + IPobs_file, rtype='IP')
IPsurvey = dobs['DCsurvey']

# Assign Z-value from topo
for ii in range(IPsurvey.nSrc):
    IPsurvey.srcList[ii].loc[0][2] = Ftopo(IPsurvey.srcList[ii].loc[0][0:2])
    IPsurvey.srcList[ii].loc[1][2] = Ftopo(IPsurvey.srcList[ii].loc[1][0:2])

    rx_x = IPsurvey.srcList[ii].rxList[0].locs[0][:, 0]
    rx_y = IPsurvey.srcList[ii].rxList[0].locs[0][:, 1]
Ejemplo n.º 21
0
mesh = Mesh.TensorMesh([hxind, hyind, hzind], 'CCC')

# Get cells inside the sphere
sph_ind = PF.MagAnalytics.spheremodel(mesh, 0., 0., 0., rad)

# Adjust susceptibility for volume difference
Vratio = (4./3.*np.pi*rad**3.) / (np.sum(sph_ind)*cs**3.)
model = np.zeros(mesh.nC)
model[sph_ind] = chi*Vratio
m = 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(-10, 10, 21)
yr = np.linspace(-10, 10, 21)
X, Y = np.meshgrid(xr, yr)

# Move obs plane 2 radius away from sphere
Z = np.ones((xr.size, yr.size))*2.*rad
locXyz = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)]
rxLoc = PF.BaseMag.RxObs(locXyz)
srcField = PF.BaseMag.SrcField([rxLoc], param=H0)
survey = PF.BaseMag.LinearSurvey(srcField)

prob_xyz = PF.Magnetics.MagneticIntegral(mesh, chiMap=idenMap,
                                              actInd=sph_ind,
                                              forwardOnly=True,
                                              rtype='xyz')
Ejemplo n.º 22
0
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)))
Ejemplo n.º 23
0
    #%%
    #Load model
    minv = DC.readUBC_DC2DModel(inv_dir + dsep + 'dcinv2d.con')
    #plt.figure()
    axs = plt.subplot(2,1,2)
    
    plt.xlim([0,nc*dx])
    plt.ylim([mesh2d.vectorNy[-1]-dl_len/2,mesh2d.vectorNy[-1]])
    plt.gca().set_aspect('equal', adjustable='box')
    
    minv = np.reshape(minv,(mesh2d.nCy,mesh2d.nCx))
    plt.pcolormesh(mesh2d.vectorNx,mesh2d.vectorNy,np.log10(m2D),alpha=0.5, cmap='gray')
    plt.pcolormesh(mesh2d.vectorNx,mesh2d.vectorNy,np.log10(minv),alpha=0.5, clim=(np.min(np.log10(m2D)),np.max(np.log10(m2D))))
    cbar = plt.colorbar(format = '%.2f',fraction=0.02)
    cmin,cmax = cbar.get_clim()
    ticks = np.linspace(cmin,cmax,3)
    cbar.set_ticks(ticks)

#%% Othrwise it is a gradient array, plot surface of apparent resisitivty
elif re.match(stype,'gradient'):
    
    rC1P1 = np.sqrt( np.sum( (npm.repmat(Tx[0][0:2,0],Rx[0].shape[0], 1) - Rx[0][:,0:2])**2, axis=1 ))
    rC2P1 = np.sqrt( np.sum( (npm.repmat(Tx[0][0:2,1],Rx[0].shape[0], 1) - Rx[0][:,0:2])**2, axis=1 ))
    rC1P2 = np.sqrt( np.sum( (npm.repmat(Tx[0][0:2,0],Rx[0].shape[0], 1) - Rx[0][:,3:5])**2, axis=1 ))
    rC2P2 = np.sqrt( np.sum( (npm.repmat(Tx[0][0:2,1],Rx[0].shape[0], 1) - Rx[0][:,3:5])**2, axis=1 )) 
    
    rC1C2 = np.sqrt( np.sum( (npm.repmat(Tx[0][0:2,0]-Tx[0][0:2,1],Rx[0].shape[0], 1) )**2, axis=1 ))
    rP1P2 = np.sqrt( np.sum( (Rx[0][:,0:2] - Rx[0][:,3:5])**2, axis=1 ))
    
    rho = np.abs(data[0]) *np.pi *2. / ( 1/rC1P1 - 1/rC2P1 - 1/rC1P2 + 1/rC2P2 )#*((rC1P1)**2 / rP1P2)#