Example #1
0
def run(plotIt=True):

    cs = 25.
    hx = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)]
    hy = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)]
    hz = [(cs, 7, -1.3), (cs, 20)]
    mesh = Mesh.TensorMesh([hx, hy, hz], 'CCN')
    sighalf = 1e-2
    sigma = np.ones(mesh.nC)*sighalf
    xtemp = np.linspace(-150, 150, 21)
    ytemp = np.linspace(-150, 150, 21)
    xyz_rxP = Utils.ndgrid(xtemp-10., ytemp, np.r_[0.])
    xyz_rxN = Utils.ndgrid(xtemp+10., ytemp, np.r_[0.])
    xyz_rxM = Utils.ndgrid(xtemp, ytemp, np.r_[0.])

    # if plotIt:
    #     fig, ax = plt.subplots(1,1, figsize = (5,5))
    #     mesh.plotSlice(sigma, grid=True, ax = ax)
    #     ax.plot(xyz_rxP[:,0],xyz_rxP[:,1], 'w.')
    #     ax.plot(xyz_rxN[:,0],xyz_rxN[:,1], 'r.', ms = 3)

    rx = DC.Rx.Dipole(xyz_rxP, xyz_rxN)
    src = DC.Src.Dipole([rx], np.r_[-200, 0, -12.5], np.r_[+200, 0, -12.5])
    survey = DC.Survey([src])
    problem = DC.Problem3D_CC(mesh, Solver=Solver, sigma=sigma)
    problem.pair(survey)

    data = survey.dpred()

    def DChalf(srclocP, srclocN, rxloc, sigma, I=1.):
        rp = (srclocP.reshape([1, -1])).repeat(rxloc.shape[0], axis=0)
        rn = (srclocN.reshape([1, -1])).repeat(rxloc.shape[0], axis=0)
        rP = np.sqrt(((rxloc-rp)**2).sum(axis=1))
        rN = np.sqrt(((rxloc-rn)**2).sum(axis=1))
        return I/(sigma*2.*np.pi)*(1/rP-1/rN)

    data_anaP = DChalf(
        np.r_[-200, 0, 0.], np.r_[+200, 0, 0.], xyz_rxP, sighalf
    )
    data_anaN = DChalf(
        np.r_[-200, 0, 0.], np.r_[+200, 0, 0.], xyz_rxN, sighalf
    )
    data_ana = data_anaP - data_anaN
    Data_ana = data_ana.reshape((21, 21), order='F')
    Data = data.reshape((21, 21), order='F')
    X = xyz_rxM[:, 0].reshape((21, 21), order='F')
    Y = xyz_rxM[:, 1].reshape((21, 21), order='F')

    if plotIt:
        fig, ax = plt.subplots(1, 2, figsize=(12, 5))
        vmin = np.r_[data, data_ana].min()
        vmax = np.r_[data, data_ana].max()
        dat0 = ax[0].contourf(X, Y, Data_ana, 60, vmin=vmin, vmax=vmax)
        dat1 = ax[1].contourf(X, Y, Data, 60, vmin=vmin, vmax=vmax)
        plt.colorbar(dat0, orientation='horizontal', ax=ax[0])
        plt.colorbar(dat1, orientation='horizontal', ax=ax[1])
        ax[1].set_title('Analytic')
        ax[0].set_title('Computed')

    return np.linalg.norm(data-data_ana)/np.linalg.norm(data_ana)
Example #2
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
Example #3
0
    def setUp(self):

        cs = 25.
        hx = [(cs,7, -1.3),(cs,21),(cs,7, 1.3)]
        hy = [(cs,7, -1.3),(cs,21),(cs,7, 1.3)]
        hz = [(cs,7, -1.3),(cs,20)]
        mesh = Mesh.TensorMesh([hx, hy, hz],x0="CCN")
        sigma = np.ones(mesh.nC)*1e-2

        x = mesh.vectorCCx[(mesh.vectorCCx>-155.)&(mesh.vectorCCx<155.)]
        y = mesh.vectorCCx[(mesh.vectorCCy>-155.)&(mesh.vectorCCy<155.)]
        Aloc = np.r_[-200., 0., 0.]
        Bloc = np.r_[200., 0., 0.]
        M = Utils.ndgrid(x-25.,y, np.r_[0.])
        N = Utils.ndgrid(x+25.,y, np.r_[0.])
        phiA = EM.Analytics.DCAnalyticHalf(Aloc, [M,N], 1e-2, earth_type="halfspace")
        phiB = EM.Analytics.DCAnalyticHalf(Bloc, [M,N], 1e-2, earth_type="halfspace")
        data_anal = phiA-phiB

        rx = DC.Rx.Dipole(M, N)
        src = DC.Src.Dipole([rx], Aloc, Bloc)
        survey = DC.Survey([src])

        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
Example #4
0
    def setUp(self):

        cs = 12.5
        npad = 2
        hx = [(cs, npad, -1.3), (cs, 21), (cs, npad, 1.3)]
        hy = [(cs, npad, -1.3), (cs, 21), (cs, npad, 1.3)]
        hz = [(cs, npad, -1.3), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy, hz], x0="CCN")

        x = mesh.vectorCCx[(mesh.vectorCCx > -80.) & (mesh.vectorCCx < 80.)]
        y = mesh.vectorCCx[(mesh.vectorCCy > -80.) & (mesh.vectorCCy < 80.)]
        Aloc = np.r_[-100., 0., 0.]
        Bloc = np.r_[100., 0., 0.]
        M = Utils.ndgrid(x-12.5, y, np.r_[0.])
        N = Utils.ndgrid(x+12.5, y, np.r_[0.])
        radius = 50.
        xc = np.r_[0., 0., -100]
        blkind = Utils.ModelBuilder.getIndicesSphere(xc, radius, mesh.gridCC)
        sigmaInf = np.ones(mesh.nC)*1e-2
        eta = np.zeros(mesh.nC)
        eta[blkind] = 0.1
        sigma0 = sigmaInf*(1.-eta)

        rx = DC.Rx.Dipole(M, N)
        src = DC.Src.Dipole([rx], Aloc, Bloc)
        surveyDC = DC.Survey([src])

        self.surveyDC = surveyDC
        self.mesh = mesh
        self.sigmaInf = sigmaInf
        self.sigma0 = sigma0
        self.src = src
        self.eta = eta
Example #5
0
    def setUp(self):

        cs = 25.
        hx = [(cs, 0, -1.3), (cs, 21), (cs, 0, 1.3)]
        hy = [(cs, 0, -1.3), (cs, 21), (cs, 0, 1.3)]
        hz = [(cs, 0, -1.3), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy, hz], x0="CCN")
        blkind0 = Utils.ModelBuilder.getIndicesSphere(
            np.r_[-100., -100., -200.], 75., mesh.gridCC
        )
        blkind1 = Utils.ModelBuilder.getIndicesSphere(
            np.r_[100., 100., -200.], 75., mesh.gridCC
        )
        sigma = np.ones(mesh.nC)*1e-2
        eta = np.zeros(mesh.nC)
        tau = np.ones_like(sigma)*1.
        eta[blkind0] = 0.1
        eta[blkind1] = 0.1
        tau[blkind0] = 0.1
        tau[blkind1] = 0.01

        x = mesh.vectorCCx[(mesh.vectorCCx > -155.) & (mesh.vectorCCx < 155.)]
        y = mesh.vectorCCx[(mesh.vectorCCy > -155.) & (mesh.vectorCCy < 155.)]
        Aloc = np.r_[-200., 0., 0.]
        Bloc = np.r_[200., 0., 0.]
        M = Utils.ndgrid(x-25., y, np.r_[0.])
        N = Utils.ndgrid(x+25., y, np.r_[0.])

        times = np.arange(10)*1e-3 + 1e-3
        rx = SIP.Rx.Dipole(M, N, times)
        src = SIP.Src.Dipole([rx], Aloc, Bloc)
        survey = SIP.Survey([src])
        wires = Maps.Wires(('eta', mesh.nC), ('taui', mesh.nC))
        problem = SIP.Problem3D_N(
            mesh,
            sigma=sigma,
            etaMap=wires.eta,
            tauiMap=wires.taui
        )
        problem.Solver = Solver
        problem.pair(survey)
        mSynth = np.r_[eta, 1./tau]
        survey.makeSyntheticData(mSynth)
        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Tikhonov(mesh)
        opt = Optimization.InexactGaussNewton(
            maxIterLS=20, maxIter=10, tolF=1e-6,
            tolX=1e-6, tolG=1e-6, maxIterCG=6
        )
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e4)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
    def setUp(self):

        cs = 25.
        hx = [(cs, 0, -1.3), (cs, 21), (cs, 0, 1.3)]
        hz = [(cs, 0, -1.3), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hz], x0="CN")
        blkind0 = Utils.ModelBuilder.getIndicesSphere(np.r_[-100., -200.], 75.,
                                                      mesh.gridCC)
        blkind1 = Utils.ModelBuilder.getIndicesSphere(np.r_[100., -200.], 75.,
                                                      mesh.gridCC)

        sigma = np.ones(mesh.nC) * 1e-2
        eta = np.zeros(mesh.nC)
        tau = np.ones_like(sigma) * 1.
        eta[blkind0] = 0.1
        eta[blkind1] = 0.1
        tau[blkind0] = 0.1
        tau[blkind1] = 0.1

        x = mesh.vectorCCx[(mesh.vectorCCx > -155.) & (mesh.vectorCCx < 155.)]

        Aloc = np.r_[-200., 0.]
        Bloc = np.r_[200., 0.]
        M = Utils.ndgrid(x - 25., np.r_[0.])
        N = Utils.ndgrid(x + 25., np.r_[0.])

        times = np.arange(10) * 1e-3 + 1e-3
        rx = SIP.Rx.Dipole(M, N, times)
        src = SIP.Src.Dipole([rx], Aloc, Bloc)
        survey = SIP.Survey([src])
        wires = Maps.Wires(('eta', mesh.nC), ('taui', mesh.nC))
        problem = SIP.Problem2D_CC(mesh,
                                   rho=1. / sigma,
                                   etaMap=wires.eta,
                                   tauiMap=wires.taui,
                                   verbose=False)
        problem.Solver = Solver
        problem.pair(survey)
        mSynth = np.r_[eta, 1. / tau]
        problem.model = mSynth
        survey.makeSyntheticData(mSynth)
        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Tikhonov(mesh)
        opt = Optimization.InexactGaussNewton(maxIterLS=20,
                                              maxIter=10,
                                              tolF=1e-6,
                                              tolX=1e-6,
                                              tolG=1e-6,
                                              maxIterCG=6)
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e4)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
Example #7
0
    def setUp(self):

        cs = 25.
        hx = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)]
        hy = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)]
        hz = [(cs, 7, -1.3), (cs, 20), (cs, 7, -1.3)]
        mesh = Mesh.TensorMesh([hx, hy, hz], x0="CCC")
        sigma = np.ones(mesh.nC)*1e-2

        x = mesh.vectorCCx[(mesh.vectorCCx > -155.) & (mesh.vectorCCx < 155.)]
        y = mesh.vectorCCx[(mesh.vectorCCy > -155.) & (mesh.vectorCCy < 155.)]

        Aloc = np.r_[-200., 0., 0.]
        Bloc = np.r_[200., 0., 0.]
        M = Utils.ndgrid(x-25., y, np.r_[0.])
        N = Utils.ndgrid(x+25., y, np.r_[0.])
        phiA = EM.Analytics.DCAnalytic_Pole_Dipole(
            Aloc, [M, N], 1e-2, earth_type="wholespace"
        )
        phiB = EM.Analytics.DCAnalytic_Pole_Dipole(
            Bloc, [M, N], 1e-2, earth_type="wholespace"
        )
        data_anal = phiA-phiB

        rx = DC.Rx.Dipole(M, N)
        src = DC.Src.Dipole([rx], Aloc, Bloc)
        survey = DC.Survey([src])

        self.survey = survey
        self.mesh = mesh
        self.sigma = sigma
        self.data_anal = data_anal
Example #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.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
Example #9
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(0, 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_[-125, 0.]
        rxloc = np.c_[M, np.zeros(20)]
        data_ana = EM.Analytics.DCAnalytic_Dipole_Pole(
                    [np.r_[A0loc, 0.], np.r_[A1loc, 0.]],
                    rxloc, sighalf, earth_type="halfspace")

        rx = DC.Rx.Pole_ky(M)
        src0 = DC.Src.Dipole([rx], A0loc, A1loc)
        survey = DC.Survey_ky([src0])

        self.survey = survey
        self.mesh = mesh
        self.sigma = sigma
        self.data_ana = data_ana
        self.plotIt = False

        try:
            from pymatsolver import PardisoSolver
            self.Solver = PardisoSolver
        except ImportError:
            self.Solver = SolverLU
Example #10
0
    def setUp(self):

        cs = 25.
        hx = [(cs,0, -1.3),(cs,21),(cs,0, 1.3)]
        hy = [(cs,0, -1.3),(cs,21),(cs,0, 1.3)]
        hz = [(cs,0, -1.3),(cs,20),(cs,0, 1.3)]
        mesh = Mesh.TensorMesh([hx, hy, hz],x0="CCC")
        blkind0 = Utils.ModelBuilder.getIndicesSphere(np.r_[-100., -100., -200.], 75., mesh.gridCC)
        blkind1 = Utils.ModelBuilder.getIndicesSphere(np.r_[100., 100., -200.], 75., mesh.gridCC)
        sigma = np.ones(mesh.nC)*1e-2
        airind = mesh.gridCC[:,2]>0.
        sigma[airind] = 1e-8
        eta = np.zeros(mesh.nC)
        tau = np.ones_like(sigma)*1.
        eta[blkind0] = 0.1
        eta[blkind1] = 0.1
        tau[blkind0] = 0.1
        tau[blkind1] = 0.01

        actmapeta = Maps.InjectActiveCells(mesh, ~airind, 0.)
        actmaptau = Maps.InjectActiveCells(mesh, ~airind, 1.)

        x = mesh.vectorCCx[(mesh.vectorCCx>-155.)&(mesh.vectorCCx<155.)]
        y = mesh.vectorCCx[(mesh.vectorCCy>-155.)&(mesh.vectorCCy<155.)]
        Aloc = np.r_[-200., 0., 0.]
        Bloc = np.r_[200., 0., 0.]
        M = Utils.ndgrid(x-25.,y, np.r_[0.])
        N = Utils.ndgrid(x+25.,y, np.r_[0.])

        times = np.arange(10)*1e-3 + 1e-3
        rx = SIP.Rx.Dipole(M, N, times)
        src = SIP.Src.Dipole([rx], Aloc, Bloc)
        survey = SIP.Survey([src])
        colemap = [("eta", Maps.IdentityMap(mesh)*actmapeta), ("taui", Maps.IdentityMap(mesh)*actmaptau)]
        problem = SIP.Problem3D_N(mesh, sigma=sigma, mapping=colemap)
        problem.Solver = Solver
        problem.pair(survey)
        mSynth = np.r_[eta[~airind], 1./tau[~airind]]
        survey.makeSyntheticData(mSynth)
        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        regmap = Maps.IdentityMap(nP=int(mSynth[~airind].size*2))
        reg = SIP.MultiRegularization(mesh, mapping=regmap, nModels=2, indActive=~airind)
        opt = Optimization.InexactGaussNewton(maxIterLS=20, maxIter=10, tolF=1e-6, tolX=1e-6, tolG=1e-6, maxIterCG=6)
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e4)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p =     problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
Example #11
0
    def getSlices(self,
                  mesh,
                  vec,
                  itime,
                  normal="Z",
                  loc=0.0,
                  isz=False,
                  isy=False):
        VEC = vec[:, itime].reshape((mesh.nC, 3), order="F")
        if normal == "Z":
            ind = np.argmin(abs(mesh.vectorCCz - loc))
            vx = VEC[:, 0].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[:, :, ind]
            vy = VEC[:, 1].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[:, :, ind]
            vz = VEC[:, 2].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[:, :, ind]
            xy = Utils.ndgrid(mesh.vectorCCx, mesh.vectorCCy)
            if isz:
                return Utils.mkvc(vz), xy
            else:
                return np.c_[Utils.mkvc(vx), Utils.mkvc(vy)], xy

        elif normal == "Y":
            ind = np.argmin(abs(mesh.vectorCCx - loc))
            vx = VEC[:, 0].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[:, ind, :]
            vy = VEC[:, 1].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[:, ind, :]
            vz = VEC[:, 2].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[:, ind, :]
            xz = Utils.ndgrid(mesh.vectorCCx, mesh.vectorCCz)
            if isz:
                return Utils.mkvc(vz), xz
            elif isy:
                return Utils.mkvc(vy), xz
            else:
                return np.c_[Utils.mkvc(vx), Utils.mkvc(vz)], xz

        elif normal == "X":
            ind = np.argmin(abs(mesh.vectorCCy - loc))
            vx = VEC[:, 0].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[ind, :, :]
            vy = VEC[:, 1].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[ind, :, :]
            vz = VEC[:, 2].reshape((mesh.nCx, mesh.nCy, mesh.nCz),
                                   order="F")[ind, :, :]
            yz = Utils.ndgrid(mesh.vectorCCy, mesh.vectorCCz)
            if isz:
                return Utils.mkvc(vy), yz
            elif isy:
                return Utils.mkvc(vy), yz
            else:
                return np.c_[Utils.mkvc(vy), Utils.mkvc(vz)], yz
    def setUp(self):

        mesh = Mesh.TensorMesh([20, 20, 20], "CCN")
        sigma = np.ones(mesh.nC) * 1. / 100.
        actind = mesh.gridCC[:, 2] < -0.2
        # actMap = Maps.InjectActiveCells(mesh, actind, 0.)

        xyzM = Utils.ndgrid(
            np.ones_like(mesh.vectorCCx[:-1]) * -0.4,
            np.ones_like(mesh.vectorCCy) * -0.4, np.r_[-0.3])
        xyzN = Utils.ndgrid(mesh.vectorCCx[1:], mesh.vectorCCy, np.r_[-0.3])

        problem = SP.Problem_CC(mesh,
                                sigma=sigma,
                                qMap=Maps.IdentityMap(mesh),
                                Solver=PardisoSolver)
        rx = SP.Rx.Dipole(xyzN, xyzM)
        src = SP.Src.StreamingCurrents([rx],
                                       L=np.ones(mesh.nC),
                                       mesh=mesh,
                                       modelType="CurrentSource")
        survey = SP.Survey([src])
        survey.pair(problem)

        q = np.zeros(mesh.nC)
        inda = Utils.closestPoints(mesh, np.r_[-0.5, 0., -0.8])
        indb = Utils.closestPoints(mesh, np.r_[0.5, 0., -0.8])
        q[inda] = 1.
        q[indb] = -1.

        mSynth = q.copy()
        survey.makeSyntheticData(mSynth)

        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Simple(mesh)
        opt = Optimization.InexactGaussNewton(maxIterLS=20,
                                              maxIter=10,
                                              tolF=1e-6,
                                              tolX=1e-6,
                                              tolG=1e-6,
                                              maxIterCG=6)
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e-2)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
    def setUp(self):

        cs = 12.5
        hx = [(cs, 7, -1.3), (cs, 61), (cs, 7, 1.3)]
        hy = [(cs, 7, -1.3), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy], x0="CN")

        # x = np.linspace(-200, 200., 20)
        x = np.linspace(-200, 200., 2)
        M = Utils.ndgrid(x - 12.5, np.r_[0.])
        N = Utils.ndgrid(x + 12.5, np.r_[0.])

        A0loc = np.r_[-150, 0.]
        A1loc = np.r_[-130, 0.]
        B0loc = np.r_[-130, 0.]
        B1loc = np.r_[-110, 0.]

        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Dipole([rx], A0loc, B0loc)
        src1 = DC.Src.Dipole([rx], A1loc, B1loc)
        survey = IP.Survey([src0, src1])

        sigma = np.ones(mesh.nC) * 1.
        problem = IP.Problem2D_CC(mesh,
                                  sigma=sigma,
                                  etaMap=Maps.IdentityMap(mesh),
                                  verbose=False)
        problem.pair(survey)

        mSynth = np.ones(mesh.nC) * 0.1
        survey.makeSyntheticData(mSynth)
        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Tikhonov(mesh)
        opt = Optimization.InexactGaussNewton(maxIterLS=20,
                                              maxIter=10,
                                              tolF=1e-6,
                                              tolX=1e-6,
                                              tolG=1e-6,
                                              maxIterCG=6)
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e4)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
Example #14
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")

        # x = np.linspace(-200, 200., 20)
        x = np.linspace(-200, 200., 2)
        M = Utils.ndgrid(x-12.5, np.r_[0.])
        N = Utils.ndgrid(x+12.5, np.r_[0.])

        A0loc = np.r_[-150, 0.]
        A1loc = np.r_[-130, 0.]
        B0loc = np.r_[-130, 0.]
        B1loc = np.r_[-110, 0.]

        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Dipole([rx], A0loc, B0loc)
        src1 = DC.Src.Dipole([rx], A1loc, B1loc)
        survey = IP.Survey([src0, src1])

        sigma = np.ones(mesh.nC) * 1.
        problem = IP.Problem2D_CC(
            mesh, sigma=sigma, etaMap=Maps.IdentityMap(mesh),
            verbose=False
        )
        problem.pair(survey)

        mSynth = np.ones(mesh.nC)*0.1
        survey.makeSyntheticData(mSynth)
        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Tikhonov(mesh)
        opt = Optimization.InexactGaussNewton(
            maxIterLS=20, maxIter=10, tolF=1e-6,
            tolX=1e-6, tolG=1e-6, maxIterCG=6
        )
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e4)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
Example #15
0
    def setUp(self):

        cs = 25.
        hx = [(cs, 7, -1.5), (cs, 21), (cs, 7, 1.5)]
        hy = [(cs, 7, -1.5), (cs, 21), (cs, 7, 1.5)]
        hz = [(cs, 7, -1.5), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy, hz], x0="CCN")
        sigma = np.ones(mesh.nC) * 1e-2

        x = mesh.vectorCCx[(mesh.vectorCCx > -155.) & (mesh.vectorCCx < 155.)]
        y = mesh.vectorCCy[(mesh.vectorCCy > -155.) & (mesh.vectorCCy < 155.)]

        Aloc = np.r_[-200., 0., 0.]

        M = Utils.ndgrid(x, y, np.r_[0.])
        phiA = EM.Analytics.DCAnalytic_Pole_Pole(Aloc,
                                                 M,
                                                 1e-2,
                                                 earth_type="halfspace")
        data_ana = phiA

        rx = DC.Rx.Pole(M)
        src = DC.Src.Pole([rx], Aloc)
        survey = DC.Survey([src])

        self.survey = survey
        self.mesh = mesh
        self.sigma = sigma
        self.data_ana = data_ana
Example #16
0
    def setUp(self):
        M = Mesh.TensorMesh([np.ones(8),np.ones(20),np.ones(10)])

        M.setCellGradBC(['neumann','neumann','dirichlet'])

        params = Richards.Empirical.HaverkampParams().celia1990
        params['Ks'] = np.log(params['Ks'])
        E = Richards.Empirical.Haverkamp(M, **params)

        bc = np.array([-61.5,-20.7])
        bc = np.r_[np.zeros(M.nCy*M.nCz*2),np.zeros(M.nCx*M.nCz*2),np.ones(M.nCx*M.nCy)*bc[0],np.ones(M.nCx*M.nCy)*bc[1]]
        h = np.zeros(M.nC) + bc[0]
        prob = Richards.RichardsProblem(M,E, timeSteps=[(40,3),(60,3)], boundaryConditions=bc, initialConditions=h, doNewton=False, method='mixed', tolRootFinder=1e-6, debug=False)
        prob.Solver = Solver

        locs = Utils.ndgrid(np.r_[5,7.],np.r_[5,15.],np.r_[6,8.])
        times = prob.times[3:5]
        rxSat = Richards.RichardsRx(locs, times, 'saturation')
        rxPre = Richards.RichardsRx(locs, times, 'pressureHead')
        survey = Richards.RichardsSurvey([rxSat, rxPre])

        prob.pair(survey)

        self.h0 = h
        self.M = M
        self.Ks = params['Ks']
        self.prob = prob
        self.survey = survey
Example #17
0
    def setUp(self):
        # Note: Pole-Pole requires bigger boundary to obtain good accuracy.
        # One can use greater padding rate. Here 1.5 is used.
        cs = 12.5
        hx = [(cs, 7, -1.5), (cs, 61), (cs, 7, 1.5)]
        hy = [(cs, 7, -1.5), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy], x0="CN")
        sighalf = 1e-2
        sigma = np.ones(mesh.nC) * sighalf
        x = np.linspace(0, 250., 20)
        M = Utils.ndgrid(x - 12.5, np.r_[0.])
        A0loc = np.r_[-150, 0.]
        rxloc = np.c_[M, np.zeros(20)]
        data_anal = EM.Analytics.DCAnalytic_Pole_Pole(np.r_[A0loc, 0.],
                                                      rxloc,
                                                      sighalf,
                                                      earth_type="halfspace")

        rx = DC.Rx.Pole_ky(M)
        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
Example #18
0
    def setUp(self):
        cs = 10
        nc = 20
        npad = 10
        mesh = Mesh.CylMesh([[(cs, nc), (cs, npad, 1.3)], np.r_[2 * np.pi],
                             [(cs, npad, -1.3), (cs, nc), (cs, npad, 1.3)]])

        mesh.x0 = np.r_[0., 0., -mesh.hz[:npad + nc].sum()]

        # receivers
        rx_x = np.linspace(10, 200, 20)
        rx_z = np.r_[-5]
        rx_locs = Utils.ndgrid([rx_x, np.r_[0], rx_z])
        rx_list = [DC.Rx.BaseRx(rx_locs, 'ex')]

        # sources
        src_a = np.r_[0., 0., -5.]
        src_b = np.r_[55., 0., -5.]

        src_list = [DC.Src.Dipole(rx_list, locA=src_a, locB=src_b)]

        self.mesh = mesh
        self.sigma_map = Maps.ExpMap(mesh) * Maps.InjectActiveCells(
            mesh, mesh.gridCC[:, 2] <= 0, np.log(1e-8))
        self.prob = DC.Problem3D_CC(mesh,
                                    sigmaMap=self.sigma_map,
                                    Solver=Pardiso,
                                    bc_type="Dirichlet")
        self.survey = DC.Survey(src_list)
        self.prob.pair(self.survey)
Example #19
0
    def setUp(self):
        mesh = Mesh.TensorMesh([30, 30], x0=[-0.5, -1.])
        sigma = np.ones(mesh.nC)
        model = np.log(sigma)

        prob = DC.Problem3D_CC(mesh, rhoMap=Maps.ExpMap(mesh))

        rx = DC.Rx.Pole(
            Utils.ndgrid([mesh.vectorCCx, np.r_[mesh.vectorCCy.max()]])
        )
        src = DC.Src.Dipole(
            [rx], np.r_[-0.25, mesh.vectorCCy.max()],
            np.r_[0.25, mesh.vectorCCy.max()]
        )
        survey = DC.Survey([src])

        prob.pair(survey)

        self.std = 0.01
        survey.std = self.std
        dobs = survey.makeSyntheticData(model)
        self.eps = 1e-8 * np.min(np.abs(dobs))
        survey.eps = self.eps
        dmis = DataMisfit.l2_DataMisfit(survey)

        self.model = model
        self.mesh = mesh
        self.survey = survey
        self.prob = prob
        self.dobs = dobs
        self.dmis = dmis
Example #20
0
    def setUp(self):
        # Note: Pole-Pole requires bigger boundary to obtain good accuracy.
        # One can use greater padding rate. Here 1.5 is used.
        cs = 12.5
        hx = [(cs, 7, -1.5), (cs, 61), (cs, 7, 1.5)]
        hy = [(cs, 7, -1.5), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy], x0="CN")
        sighalf = 1e-2
        sigma = np.ones(mesh.nC)*sighalf
        x = np.linspace(0, 250., 20)
        M = Utils.ndgrid(x-12.5, np.r_[0.])
        A0loc = np.r_[-150, 0.]
        rxloc = np.c_[M, np.zeros(20)]
        data_ana = EM.Analytics.DCAnalytic_Pole_Pole(
                    np.r_[A0loc, 0.],
                    rxloc, sighalf, earth_type="halfspace")

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

        self.survey = survey
        self.mesh = mesh
        self.sigma = sigma
        self.data_ana = data_ana

        try:
            from pymatsolver import PardisoSolver
            self.Solver = PardisoSolver
        except ImportError:
            self.Solver = SolverLU
Example #21
0
def run(plotIt=True):
    # 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, cont1l = Utils.plot2Ddata(xyz,
                                              Ex.real,
                                              dataloc=True,
                                              ax=ax1,
                                              contourOpts={"cmap": "viridis"},
                                              ncontour=5,
                                              level=True,
                                              levelOpts={
                                                  'colors': 'k',
                                                  'linestyles': 'dashed',
                                                  'linewidths': 1
                                              })
        # 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"},
                                      ncontour=5)
        cb1 = plt.colorbar(cont1,
                           ax=ax1,
                           orientation="horizontal",
                           format='%.1e')
        cb1.ax.set_xticklabels(cb1.ax.get_xticklabels(), rotation=45)
        cb2 = plt.colorbar(cont2,
                           ax=ax2,
                           orientation="horizontal",
                           format='%.1e')
        cb2.ax.set_xticklabels(cb2.ax.get_xticklabels(), rotation=45)
        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')
Example #22
0
    def setUp(self):
        cs = 10
        nc = 20
        npad = 10
        mesh = Mesh.CylMesh([
            [(cs, nc), (cs, npad, 1.3)],
            np.r_[2*np.pi],
            [(cs, npad, -1.3), (cs, nc), (cs, npad, 1.3)]
        ])

        mesh.x0 = np.r_[0., 0., -mesh.hz[:npad+nc].sum()]

        # receivers
        rx_x = np.linspace(10, 200, 20)
        rx_z = np.r_[-5]
        rx_locs = Utils.ndgrid([rx_x, np.r_[0], rx_z])
        rx_list = [DC.Rx.BaseRx(rx_locs, 'ex')]

        # sources
        src_a = np.r_[0., 0., -5.]
        src_b = np.r_[55., 0., -5.]

        src_list = [DC.Src.Dipole(rx_list, locA=src_a, locB=src_b)]

        self.mesh = mesh
        self.sigma_map = Maps.ExpMap(mesh) * Maps.InjectActiveCells(
            mesh, mesh.gridCC[:, 2] <=0, np.log(1e-8)
        )
        self.prob = DC.Problem3D_CC(
            mesh, sigmaMap=self.sigma_map, Solver=Pardiso, bc_type="Dirichlet"
        )
        self.survey = DC.Survey(src_list)
        self.prob.pair(self.survey)
Example #23
0
    def setUp(self):
        mesh = Mesh.TensorMesh([np.ones(n) * 5 for n in [10, 11, 12]],
                               [0, 0, -30])
        x = np.linspace(5, 10, 3)
        XYZ = Utils.ndgrid(x, x, np.r_[0.])
        srcLoc = np.r_[0, 0, 0.]
        rxList0 = Survey.BaseRx(XYZ, 'exi')
        Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
        rxList1 = Survey.BaseRx(XYZ, 'bxi')
        Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
        rxList2 = Survey.BaseRx(XYZ, 'bxi')
        Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
        rxList3 = Survey.BaseRx(XYZ, 'bxi')
        Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
        Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
        srcList = [Src0, Src1, Src2, Src3, Src4]
        survey = Survey.BaseSurvey(srcList=srcList)
        prob = Problem.BaseTimeProblem(mesh, timeSteps=[(10., 3), (20., 2)])
        survey.pair(prob)

        def alias(b, srcInd, timeInd):
            return self.F.mesh.edgeCurl.T * b + timeInd

        self.F = Problem.TimeFields(mesh,
                                    survey,
                                    knownFields={'b': 'F'},
                                    aliasFields={'e': ['b', 'E', alias]})
        self.Src0 = Src0
        self.Src1 = Src1
        self.mesh = mesh
        self.XYZ = XYZ
Example #24
0
 def setUp(self):
     mesh = Mesh.TensorMesh([np.ones(n)*5 for n in [10, 11, 12]],
                            [0, 0, -30])
     x = np.linspace(5, 10, 3)
     XYZ = Utils.ndgrid(x, x, np.r_[0.])
     srcLoc = np.r_[0, 0, 0.]
     rxList0 = Survey.BaseRx(XYZ, 'exi')
     Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
     rxList1 = Survey.BaseRx(XYZ, 'bxi')
     Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
     rxList2 = Survey.BaseRx(XYZ, 'bxi')
     Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
     rxList3 = Survey.BaseRx(XYZ, 'bxi')
     Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
     Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
     srcList = [Src0, Src1, Src2, Src3, Src4]
     survey = Survey.BaseSurvey(srcList=srcList)
     self.F = Problem.Fields(mesh, survey, knownFields={'e': 'E'},
                             aliasFields={'b': ['e', 'F',
                                                (lambda e, ind:
                                                 self.F.mesh.edgeCurl *
                                                 e)]})
     self.Src0 = Src0
     self.Src1 = Src1
     self.mesh = mesh
     self.XYZ = XYZ
Example #25
0
 def setUp(self):
     mesh = Mesh.TensorMesh([np.ones(n) * 5 for n in [10, 11, 12]],
                            [0, 0, -30])
     x = np.linspace(5, 10, 3)
     XYZ = Utils.ndgrid(x, x, np.r_[0.])
     srcLoc = np.r_[0., 0., 0.]
     rxList0 = Survey.BaseRx(XYZ, 'exi')
     Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
     rxList1 = Survey.BaseRx(XYZ, 'bxi')
     Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
     rxList2 = Survey.BaseRx(XYZ, 'bxi')
     Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
     rxList3 = Survey.BaseRx(XYZ, 'bxi')
     Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
     Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
     srcList = [Src0, Src1, Src2, Src3, Src4]
     survey = Survey.BaseSurvey(srcList=srcList)
     self.D = Survey.Data(survey)
     self.F = Problem.Fields(mesh,
                             survey,
                             knownFields={
                                 'phi': 'CC',
                                 'e': 'E',
                                 'b': 'F'
                             },
                             dtype={
                                 "phi": float,
                                 "e": complex,
                                 "b": complex
                             })
     self.Src0 = Src0
     self.Src1 = Src1
     self.mesh = mesh
     self.XYZ = XYZ
Example #26
0
    def setupSecondarySurvey(
        self, primaryProblem, primarySurvey, map2meshSecondary
    ):

        print('Setting up Secondary Survey')

        nx = 41
        ny = nx
        rx_x, rx_y = 2*[np.linspace(-2050, 2050, nx)]
        self.rxlocs = Utils.ndgrid([rx_x, rx_y, np.r_[-1]])
        self.rx_x = self.rxlocs[:, 0].reshape(nx, ny, order='F')
        self.rx_y = self.rxlocs[:, 1].reshape(nx, ny, order='F')

        rx_ex = FDEM.Rx.Point_e(self.rxlocs, orientation='x', component='real')
        rx_ey = FDEM.Rx.Point_e(self.rxlocs, orientation='y', component='real')

        RxList = [rx_ex, rx_ey]

        sec_src = [
            FDEM.Src.PrimSecMappedSigma(
                RxList, freq, primaryProblem, primarySurvey,
                map2meshSecondary=map2meshSecondary
            )
            for freq in self.freqs
        ]
        print('... done secondary survey')

        return FDEM.Survey(sec_src)
Example #27
0
    def setUp(self):
        mesh = Mesh.TensorMesh([30, 30], x0=[-0.5, -1.])
        sigma = np.ones(mesh.nC)
        model = np.log(sigma)

        prob = DC.Problem3D_CC(mesh, rhoMap=Maps.ExpMap(mesh))

        rx = DC.Rx.Pole(
            Utils.ndgrid([mesh.vectorCCx, np.r_[mesh.vectorCCy.max()]])
        )
        src = DC.Src.Dipole(
            [rx], np.r_[-0.25, mesh.vectorCCy.max()],
            np.r_[0.25, mesh.vectorCCy.max()]
        )
        survey = DC.Survey([src])

        prob.pair(survey)

        dobs = survey.makeSyntheticData(model)

        dmis = DataMisfit.l2_DataMisfit(survey)

        self.model = model
        self.mesh = mesh
        self.survey = survey
        self.prob = prob
        self.dobs = dobs
        self.dmis = dmis
Example #28
0
    def test_Transect(self):

        for src in self.prb.survey.srcList:
            print(' --- testing {} --- '.format(src.__class__.__name__))
            bfz = self.mesh.r(self.u[src, 'b'],'F','Fz','M')
            x = np.linspace(-55,55,12)
            XYZ = Utils.ndgrid(x,np.r_[0],np.r_[0])

            P = self.mesh.getInterpolationMat(XYZ, 'Fz')

            ana = mu_0*np.imag(EM.Analytics.FDEM.hzAnalyticDipoleF(x, src.freq, self.sig))
            num = P*np.imag(self.u[src, 'b'])

            diff = np.linalg.norm(num - ana)

            if plotIt:
                import matplotlib.pyplot as plt
                plt.plot(x, np.log10(np.abs(num)))
                plt.plot(x, np.log10(np.abs(ana)), 'r')
                plt.plot(x, diff, 'g')
                plt.show()

            norm_num = np.linalg.norm(num)
            norm_ana = np.linalg.norm(ana)
            tol = tol_Transect*(norm_num + norm_ana)/2.

            passed = diff < tol
            print ('analytic: {}, numeric {}, difference {} < tolerance {} ? '
                   ' {}'.format(norm_ana, norm_num, diff,
                                tol, passed))

            self.assertTrue(passed)
Example #29
0
    def test_Transect(self):

        for src in self.prb.survey.srcList:
            print ' --- testing {} --- '.format(src.__class__.__name__)
            bfz = self.mesh.r(self.u[src, 'b'], 'F', 'Fz', 'M')
            x = np.linspace(-55, 55, 12)
            XYZ = Utils.ndgrid(x, np.r_[0], np.r_[0])

            P = self.mesh.getInterpolationMat(XYZ, 'Fz')

            ana = mu_0 * np.imag(
                EM.Analytics.FDEM.hzAnalyticDipoleF(x, src.freq, self.sig))
            num = P * np.imag(self.u[src, 'b'])

            diff = np.linalg.norm(num - ana)

            if plotIt:
                import matplotlib.pyplot as plt
                plt.plot(x, np.log10(np.abs(num)))
                plt.plot(x, np.log10(np.abs(ana)), 'r')
                plt.plot(x, diff, 'g')
                plt.show()

            norm_num = np.linalg.norm(num)
            norm_ana = np.linalg.norm(ana)
            tol = tol_Transect * (norm_num + norm_ana) / 2.

            passed = diff < tol
            print(
                'analytic: {}, numeric {}, difference {} < tolerance {} ? '
                ' {}'.format(norm_ana, norm_num, diff, tol, passed))

            self.assertTrue(passed)
def run(XYZ=None, loc=np.r_[0., 0., 0.], sig=1.0, freq=1.0, orientation='Z',
        plotIt=True):


    if XYZ is None:
        # avoid putting measurement points where source is
        x = np.arange(-100.5, 100.5, step=1.)
        y = np.r_[0]
        z = x
        XYZ = Utils.ndgrid(x, y, z)

    Bx, By, Bz = EM.Analytics.FDEM.MagneticDipoleWholeSpace(
        XYZ,
        loc,
        sig,
        freq,
        orientation=orientation
    )
    absB = np.sqrt(Bx*Bx.conj()+By*By.conj()+Bz*Bz.conj()).real

    if plotIt:
        fig, ax = plt.subplots(1, 1, figsize=(6, 5))
        bxplt = Bx.reshape(x.size, z.size)
        bzplt = Bz.reshape(x.size, z.size)
        pc = ax.pcolor(x, z, absB.reshape(x.size, z.size), norm=LogNorm())
        ax.streamplot(x, z, bxplt.real, bzplt.real, color='k', density=1)
        ax.set_xlim([x.min(), x.max()])
        ax.set_ylim([z.min(), z.max()])
        ax.set_xlabel('x')
        ax.set_ylabel('z')
        cb = plt.colorbar(pc, ax=ax)
        cb.set_label('|B| (T)')


        return fig, ax
Example #31
0
    def setUp(self):
        mesh = Mesh.TensorMesh([np.ones(n)*5 for n in [10, 11, 12]],
                               [0, 0, -30])
        x = np.linspace(5, 10, 3)
        XYZ = Utils.ndgrid(x, x, np.r_[0.])
        srcLoc = np.r_[0, 0, 0.]
        rxList0 = Survey.BaseRx(XYZ, 'exi')
        Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
        rxList1 = Survey.BaseRx(XYZ, 'bxi')
        Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
        rxList2 = Survey.BaseRx(XYZ, 'bxi')
        Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
        rxList3 = Survey.BaseRx(XYZ, 'bxi')
        Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
        Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
        srcList = [Src0, Src1, Src2, Src3, Src4]
        survey = Survey.BaseSurvey(srcList=srcList)
        prob = Problem.BaseTimeProblem(mesh, timeSteps=[(10., 3), (20., 2)])
        survey.pair(prob)

        def alias(b, srcInd, timeInd):
            return self.F.mesh.edgeCurl.T * b + timeInd
        self.F = Problem.TimeFields(mesh, survey, knownFields={'b': 'F'},
                                    aliasFields={'e': ['b', 'E', alias]})
        self.Src0 = Src0
        self.Src1 = Src1
        self.mesh = mesh
        self.XYZ = XYZ
Example #32
0
 def setUp(self):
     mesh = Mesh.TensorMesh([np.ones(n)*5 for n in [10, 11, 12]],
                            [0, 0, -30])
     x = np.linspace(5, 10, 3)
     XYZ = Utils.ndgrid(x, x, np.r_[0.])
     srcLoc = np.r_[0., 0., 0.]
     rxList0 = Survey.BaseRx(XYZ, 'exi')
     Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
     rxList1 = Survey.BaseRx(XYZ, 'bxi')
     Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
     rxList2 = Survey.BaseRx(XYZ, 'bxi')
     Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
     rxList3 = Survey.BaseRx(XYZ, 'bxi')
     Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
     Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
     srcList = [Src0, Src1, Src2, Src3, Src4]
     survey = Survey.BaseSurvey(srcList=srcList)
     self.D = Survey.Data(survey)
     self.F = Problem.Fields(mesh, survey, knownFields={'phi': 'CC',
                                                        'e': 'E', 'b': 'F'},
                             dtype={"phi": float, "e": complex,
                                    "b": complex})
     self.Src0 = Src0
     self.Src1 = Src1
     self.mesh = mesh
     self.XYZ = XYZ
Example #33
0
 def setUp(self):
     mesh = Mesh.TensorMesh([np.ones(n) * 5 for n in [10, 11, 12]],
                            [0, 0, -30])
     x = np.linspace(5, 10, 3)
     XYZ = Utils.ndgrid(x, x, np.r_[0.])
     srcLoc = np.r_[0, 0, 0.]
     rxList0 = Survey.BaseRx(XYZ, 'exi')
     Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
     rxList1 = Survey.BaseRx(XYZ, 'bxi')
     Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
     rxList2 = Survey.BaseRx(XYZ, 'bxi')
     Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
     rxList3 = Survey.BaseRx(XYZ, 'bxi')
     Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
     Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
     srcList = [Src0, Src1, Src2, Src3, Src4]
     survey = Survey.BaseSurvey(srcList=srcList)
     self.F = Problem.Fields(
         mesh,
         survey,
         knownFields={'e': 'E'},
         aliasFields={
             'b': ['e', 'F', (lambda e, ind: self.F.mesh.edgeCurl * e)]
         })
     self.Src0 = Src0
     self.Src1 = Src1
     self.mesh = mesh
     self.XYZ = XYZ
Example #34
0
    def setUp(self):
        mesh = Mesh.TensorMesh([30, 30], x0=[-0.5, -1.])
        sigma = np.random.rand(mesh.nC)
        model = np.log(sigma)

        prob = DC.Problem3D_CC(mesh, rhoMap=Maps.ExpMap(mesh))
        prob1 = DC.Problem3D_CC(mesh, rhoMap=Maps.ExpMap(mesh))

        rx = DC.Rx.Pole(
            Utils.ndgrid([mesh.vectorCCx, np.r_[mesh.vectorCCy.max()]])
        )
        rx1 = DC.Rx.Pole(
            Utils.ndgrid([mesh.vectorCCx, np.r_[mesh.vectorCCy.min()]])
        )
        src = DC.Src.Dipole(
            [rx], np.r_[-0.25, mesh.vectorCCy.max()],
            np.r_[0.25, mesh.vectorCCy.max()]
        )
        src1 = DC.Src.Dipole(
            [rx1], np.r_[-0.25, mesh.vectorCCy.max()],
            np.r_[0.25, mesh.vectorCCy.max()]
        )
        survey = DC.Survey([src])
        prob.pair(survey)

        survey1 = DC.Survey([src1])
        prob1.pair(survey1)

        dobs0 = survey.makeSyntheticData(model)
        dobs1 = survey1.makeSyntheticData(model)

        self.mesh = mesh
        self.model = model

        self.survey0 = survey
        self.prob0 = prob

        self.survey1 = survey1
        self.prob1 = prob1

        self.dmis0 = DataMisfit.l2_DataMisfit(self.survey0)
        self.dmis1 = DataMisfit.l2_DataMisfit(self.survey1)

        self.dmiscobmo = self.dmis0 + self.dmis1
Example #35
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')
    def setUp(self):

        mesh = Mesh.TensorMesh([20, 20, 20], "CCN")
        sigma = np.ones(mesh.nC)*1./100.
        actind = mesh.gridCC[:, 2] < -0.2
        # actMap = Maps.InjectActiveCells(mesh, actind, 0.)

        xyzM = Utils.ndgrid(np.ones_like(mesh.vectorCCx[:-1])*-0.4, np.ones_like(mesh.vectorCCy)*-0.4, np.r_[-0.3])
        xyzN = Utils.ndgrid(mesh.vectorCCx[1:], mesh.vectorCCy, np.r_[-0.3])

        problem = SP.Problem_CC(mesh, sigma=sigma, qMap=Maps.IdentityMap(mesh), Solver=PardisoSolver)
        rx = SP.Rx.Dipole(xyzN, xyzM)
        src = SP.Src.StreamingCurrents([rx], L=np.ones(mesh.nC), mesh=mesh,
                                       modelType="CurrentSource")
        survey = SP.Survey([src])
        survey.pair(problem)

        q = np.zeros(mesh.nC)
        inda = Utils.closestPoints(mesh, np.r_[-0.5, 0., -0.8])
        indb = Utils.closestPoints(mesh, np.r_[0.5, 0., -0.8])
        q[inda] = 1.
        q[indb] = -1.

        mSynth = q.copy()
        survey.makeSyntheticData(mSynth)

        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Simple(mesh)
        opt = Optimization.InexactGaussNewton(
            maxIterLS=20, maxIter=10, tolF=1e-6,
            tolX=1e-6, tolG=1e-6, maxIterCG=6
        )
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e-2)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
    def setUp(self):

        cs = 12.5
        hx = [(cs, 7, -1.3), (cs, 61), (cs, 7, 1.3)]
        hy = [(cs, 7, -1.3), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy], x0="CN")
        x = np.linspace(-135, 250., 20)
        M = Utils.ndgrid(x - 12.5, np.r_[0.])
        N = Utils.ndgrid(x + 12.5, np.r_[0.])
        A0loc = np.r_[-150, 0.]
        A1loc = np.r_[-130, 0.]
        rxloc = [np.c_[M, np.zeros(20)], np.c_[N, np.zeros(20)]]
        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Pole([rx], A0loc)
        src1 = DC.Src.Pole([rx], A1loc)
        survey = DC.Survey_ky([src0, src1])
        problem = DC.Problem2D_N(mesh,
                                 mapping=[('rho', Maps.IdentityMap(mesh))])
        problem.pair(survey)

        mSynth = np.ones(mesh.nC) * 1.
        survey.makeSyntheticData(mSynth)

        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Tikhonov(mesh)
        opt = Optimization.InexactGaussNewton(maxIterLS=20,
                                              maxIter=10,
                                              tolF=1e-6,
                                              tolX=1e-6,
                                              tolG=1e-6,
                                              maxIterCG=6)
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e0)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
Example #38
0
    def setUp(self):

        cs = 12.5
        hx = [(cs, 2, -1.3), (cs, 61), (cs, 2, 1.3)]
        hy = [(cs, 2, -1.3), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy], x0="CN")
        x = np.linspace(-135, 250., 20)
        M = Utils.ndgrid(x-12.5, np.r_[0.])
        N = Utils.ndgrid(x+12.5, np.r_[0.])
        A0loc = np.r_[-150, 0.]
        A1loc = np.r_[-130, 0.]
        # rxloc = [np.c_[M, np.zeros(20)], np.c_[N, np.zeros(20)]]
        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Pole([rx], A0loc)
        src1 = DC.Src.Pole([rx], A1loc)
        survey = DC.Survey_ky([src0, src1])
        problem = DC.Problem2D_N(
            mesh, rhoMap=Maps.IdentityMap(mesh),
            Solver=Solver
        )
        problem.pair(survey)

        mSynth = np.ones(mesh.nC)*1.
        survey.makeSyntheticData(mSynth)

        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg = Regularization.Tikhonov(mesh)
        opt = Optimization.InexactGaussNewton(
            maxIterLS=20, maxIter=10, tolF=1e-6,
            tolX=1e-6, tolG=1e-6, maxIterCG=6
        )
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e0)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
Example #39
0
    def setUp(self):
        print ('\nTesting Transect for analytic')

        cs = 10.
        ncx, ncy, ncz = 10, 10, 10
        npad = 5
        freq = 1e2

        hx = [(cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)]
        hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
        hz = [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)]
        mesh = Mesh.TensorMesh([hx, hy, hz], 'CCC')

        x = np.linspace(-10, 10, 5)
        XYZ = Utils.ndgrid(x, np.r_[0], np.r_[0])
        rxList = EM.FDEM.Rx.Point_e(XYZ, orientation='x', component='imag')
        SrcList = [
            EM.FDEM.Src.MagDipole(
                [rxList], loc=np.r_[0., 0., 0.],
                freq=freq
            ),
            EM.FDEM.Src.CircularLoop(
                [rxList], loc=np.r_[0., 0., 0.],
                freq=freq, radius=np.sqrt(1./np.pi)
            ),
            # EM.FDEM.Src.MagDipole_Bfield(
            #     [rxList], loc=np.r_[0., 0., 0.],
            #     freq=freq
            # ), # less accurate
        ]

        survey = EM.FDEM.Survey(SrcList)

        sig = 1e-1
        sigma = np.ones(mesh.nC)*sig
        sigma[mesh.gridCC[:, 2] > 0] = 1e-8

        prb = EM.FDEM.Problem3D_b(mesh, sigma=sigma)
        prb.pair(survey)

        try:
            from pymatsolver import Pardiso
            prb.Solver = Pardiso
        except ImportError:
            prb.Solver = SolverLU

        self.prb = prb
        self.mesh = mesh
        self.sig = sig

        print(' starting solve ...')
        u = self.prb.fields()
        print(' ... done')
        self.u = u
Example #40
0
def run(plotIt=True):
    # 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, cont1l = Utils.plot2Ddata(
            xyz, Ex.real, dataloc=True,
            ax=ax1, contourOpts={"cmap": "viridis"},
            ncontour=5, level=True,
            levelOpts={'colors': 'k', 'linestyles': 'dashed', 'linewidths': 1}
        )
        # 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"},
            ncontour=5
        )
        cb1 = plt.colorbar(
            cont1, ax=ax1, orientation="horizontal",
            format='%.1e'
        )
        cb1.ax.set_xticklabels(cb1.ax.get_xticklabels(), rotation=45)
        cb2 = plt.colorbar(
            cont2, ax=ax2, orientation="horizontal",
            format='%.1e'
        )
        cb2.ax.set_xticklabels(cb2.ax.get_xticklabels(), rotation=45)
        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')
Example #41
0
    def setUp(self):
        print('\nTesting Transect for analytic')

        cs = 10.
        ncx, ncy, ncz = 10, 10, 10
        npad = 5
        freq = 1e2

        hx = [(cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)]
        hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
        hz = [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)]
        mesh = Mesh.TensorMesh([hx, hy, hz], 'CCC')

        x = np.linspace(-10, 10, 5)
        XYZ = Utils.ndgrid(x, np.r_[0], np.r_[0])
        rxList = EM.FDEM.Rx.Point_e(XYZ, orientation='x', component='imag')
        SrcList = [
            EM.FDEM.Src.MagDipole(
                [rxList], loc=np.r_[0., 0., 0.],
                freq=freq
            ),
            EM.FDEM.Src.CircularLoop(
                [rxList], loc=np.r_[0., 0., 0.],
                freq=freq, radius=np.sqrt(1./np.pi)
            ),
            # EM.FDEM.Src.MagDipole_Bfield(
            #     [rxList], loc=np.r_[0., 0., 0.],
            #     freq=freq
            # ), # less accurate
        ]

        survey = EM.FDEM.Survey(SrcList)

        sig = 1e-1
        sigma = np.ones(mesh.nC)*sig
        sigma[mesh.gridCC[:, 2] > 0] = 1e-8

        prb = EM.FDEM.Problem3D_b(mesh, sigma=sigma)
        prb.pair(survey)

        try:
            from pymatsolver import Pardiso
            prb.Solver = Pardiso
        except ImportError:
            prb.Solver = SolverLU

        self.prb = prb
        self.mesh = mesh
        self.sig = sig

        print(' starting solve ...')
        u = self.prb.fields()
        print(' ... done')
        self.u = u
Example #42
0
def create_local_mesh(
    src_location,
    rx_location,
    topo_location,
    topo,
    h = [10., 10., 5.],
    x_core_lim = (-100., 100.),
    y_core_lim = (-20., 20.),
    ):

    # TODO: All parameters used for generating this mesh should be input parameters
    # Currently fixed for a specific case

    xyz = np.vstack((rx_location, src_location))
    x = np.linspace(x_core_lim[0], x_core_lim[1]) + src_location[0]
    y = np.linspace(y_core_lim[0], y_core_lim[1]) + src_location[1]
    dem = Utils.ndgrid(x, y, np.r_[topo_location[2]])

    mesh_local = discretize.utils.mesh_builder_xyz(
        dem,
        h,
        padding_distance=[[2000., 2000.], [2000., 2000.], [2000., 2000.]],
        base_mesh=None,
        depth_core=None,
        expansion_factor=1.3,
        mesh_type='tree'
    )

    mesh_local = discretize.utils.refine_tree_xyz(
        mesh_local,
        dem,
        method='surface',
        octree_levels=[5, 10, 10],
        octree_levels_padding=None,
        finalize=False,
        min_level=0,
        max_distance=np.inf,
    )


    mesh_local = discretize.utils.refine_tree_xyz(
        mesh_local,
        xyz,
        method='radial',
        octree_levels=[2, 0, 0],
        octree_levels_padding=None,
        finalize=True,
        min_level=1,
        max_distance=np.inf,
    )

    actv_local = Utils.surface2ind_topo(mesh_local, topo)

    return mesh_local, actv_local
Example #43
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")

        x = np.linspace(-200, 200., 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.]
        B0loc = np.r_[-130, 0.]
        B1loc = np.r_[-110, 0.]

        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Dipole([rx], A0loc, B0loc)
        src1 = DC.Src.Dipole([rx], A1loc, B1loc)

        src0_ip = DC.Src.Dipole([rx], A0loc, B0loc)
        src1_ip = DC.Src.Dipole([rx], A1loc, B1loc)

        srcLists = [src0, src1]
        srcLists_ip = [src0_ip, src1_ip]
        surveyDC = DC.Survey_ky([src0, src1])

        sigmaInf = np.ones(mesh.nC) * 1.
        blkind = Utils.ModelBuilder.getIndicesSphere(
            np.r_[0, -150], 40, mesh.gridCC)

        eta = np.zeros(mesh.nC)
        eta[blkind] = 0.1
        sigma0 = sigmaInf * (1.-eta)

        self.surveyDC = surveyDC
        self.mesh = mesh
        self.sigmaInf = sigmaInf
        self.sigma0 = sigma0
        self.srcLists = srcLists
        self.srcLists_ip = srcLists_ip
        self.eta = eta
Example #44
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")

        x = np.linspace(-200, 200., 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.]
        B0loc = np.r_[-130, 0.]
        B1loc = np.r_[-110, 0.]

        rx = DC.Rx.Dipole_ky(M, N)
        src0 = DC.Src.Dipole([rx], A0loc, B0loc)
        src1 = DC.Src.Dipole([rx], A1loc, B1loc)

        src0_ip = DC.Src.Dipole([rx], A0loc, B0loc)
        src1_ip = DC.Src.Dipole([rx], A1loc, B1loc)

        srcLists = [src0, src1]
        srcLists_ip = [src0_ip, src1_ip]
        surveyDC = DC.Survey_ky([src0, src1])

        sigmaInf = np.ones(mesh.nC) * 1.
        blkind = Utils.ModelBuilder.getIndicesSphere(np.r_[0, -150], 40,
                                                     mesh.gridCC)

        eta = np.zeros(mesh.nC)
        eta[blkind] = 0.1
        sigma0 = sigmaInf * (1. - eta)

        self.surveyDC = surveyDC
        self.mesh = mesh
        self.sigmaInf = sigmaInf
        self.sigma0 = sigma0
        self.srcLists = srcLists
        self.srcLists_ip = srcLists_ip
        self.eta = eta
Example #45
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()
Example #46
0
    def setUp(self):
        mesh = Mesh.TensorMesh([30, 30], x0=[-0.5, -1.])
        sigma = np.random.rand(mesh.nC)
        model = np.log(sigma)

        prob = DC.Problem3D_CC(mesh, rhoMap=Maps.ExpMap(mesh))
        prob1 = DC.Problem3D_CC(mesh, rhoMap=Maps.ExpMap(mesh))

        rx = DC.Rx.Pole(
            Utils.ndgrid([mesh.vectorCCx, np.r_[mesh.vectorCCy.max()]]))
        rx1 = DC.Rx.Pole(
            Utils.ndgrid([mesh.vectorCCx, np.r_[mesh.vectorCCy.min()]]))
        src = DC.Src.Dipole([rx], np.r_[-0.25, mesh.vectorCCy.max()],
                            np.r_[0.25, mesh.vectorCCy.max()])
        src1 = DC.Src.Dipole([rx1], np.r_[-0.25, mesh.vectorCCy.max()],
                             np.r_[0.25, mesh.vectorCCy.max()])
        survey = DC.Survey([src])
        prob.pair(survey)

        survey1 = DC.Survey([src1])
        prob1.pair(survey1)

        dobs0 = survey.makeSyntheticData(model)
        dobs1 = survey1.makeSyntheticData(model)

        self.mesh = mesh
        self.model = model

        self.survey0 = survey
        self.prob0 = prob

        self.survey1 = survey1
        self.prob1 = prob1

        self.dmis0 = DataMisfit.l2_DataMisfit(self.survey0)
        self.dmis1 = DataMisfit.l2_DataMisfit(self.survey1)

        self.dmiscobmo = self.dmis0 + self.dmis1
Example #47
0
    def setUp(self):

        cs = 25.
        hx = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)]
        hy = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)]
        hz = [(cs, 7, -1.3), (cs, 20)]
        mesh = Mesh.TensorMesh([hx, hy, hz], x0="CCN")
        sigma = np.ones(mesh.nC) * 1e-2

        x = mesh.vectorCCx[(mesh.vectorCCx > -155.) & (mesh.vectorCCx < 155.)]
        y = mesh.vectorCCx[(mesh.vectorCCy > -155.) & (mesh.vectorCCy < 155.)]
        Aloc = np.r_[-200., 0., 0.]
        Bloc = np.r_[200., 0., 0.]
        M = Utils.ndgrid(x - 25., y, np.r_[0.])
        N = Utils.ndgrid(x + 25., y, np.r_[0.])
        phiA = EM.Analytics.DCAnalyticHalf(Aloc, [M, N],
                                           1e-2,
                                           earth_type="halfspace")
        phiB = EM.Analytics.DCAnalyticHalf(Bloc, [M, N],
                                           1e-2,
                                           earth_type="halfspace")
        data_anal = phiA - phiB

        rx = DC.Rx.Dipole(M, N)
        src = DC.Src.Dipole([rx], Aloc, Bloc)
        survey = DC.Survey([src])

        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
Example #48
0
    def get_interpolation_matrix(
        self,
        npts=20,
        epsilon=None
    ):

        tree_2d = kdtree(self.topography[:, :2])
        xy = Utils.ndgrid(self.mesh_3d.vectorCCx, self.mesh_3d.vectorCCy)

        distance, inds = tree_2d.query(xy, k=npts)
        if epsilon is None:
            epsilon = np.min([self.mesh_3d.hx.min(), self.mesh_3d.hy.min()])

        w = 1. / (distance + epsilon)**2
        w = Utils.sdiag(1./np.sum(w, axis=1)) * (w)
        I = Utils.mkvc(
            np.arange(inds.shape[0]).reshape([-1, 1]).repeat(npts, axis=1)
        )
        J = Utils.mkvc(inds)

        self._P = sp.coo_matrix(
            (Utils.mkvc(w), (I, J)),
            shape=(inds.shape[0], self.topography.shape[0])
        )

        mesh_1d = Mesh.TensorMesh([np.r_[self.hz[:-1], 1e20]])

        z = self.P*self.topography[:, 2]

        self._actinds = Utils.surface2ind_topo(self.mesh_3d, np.c_[xy, z])

        Z = np.empty(self.mesh_3d.vnC, dtype=float, order='F')
        Z = self.mesh_3d.gridCC[:, 2].reshape(
            (self.mesh_3d.nCx*self.mesh_3d.nCy, self.mesh_3d.nCz), order='F'
        )
        ACTIND = self._actinds.reshape(
            (self.mesh_3d.nCx*self.mesh_3d.nCy, self.mesh_3d.nCz), order='F'
        )

        self._Pz = []

        # This part can be cythonized or parallelized
        for i_xy in range(self.mesh_3d.nCx*self.mesh_3d.nCy):
            actind_temp = ACTIND[i_xy, :]
            z_temp = -(Z[i_xy, :] - z[i_xy])
            self._Pz.append(mesh_1d.getInterpolationMat(z_temp[actind_temp]))
Example #49
0
 def setUp(self):
     mesh = Mesh.TensorMesh([np.ones(n)*5 for n in [10,11,12]],[0,0,-30])
     x = np.linspace(5,10,3)
     XYZ = Utils.ndgrid(x,x,np.r_[0.])
     srcLoc = np.r_[0,0,0.]
     rxList0 = Survey.BaseRx(XYZ, 'exi')
     Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
     rxList1 = Survey.BaseRx(XYZ, 'bxi')
     Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
     rxList2 = Survey.BaseRx(XYZ, 'bxi')
     Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
     rxList3 = Survey.BaseRx(XYZ, 'bxi')
     Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
     Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
     srcList = [Src0,Src1,Src2,Src3,Src4]
     survey = Survey.BaseSurvey(srcList=srcList)
     self.D = Survey.Data(survey)
Example #50
0
 def setUp(self):
     mesh = Mesh.TensorMesh([np.ones(n)*5 for n in [10,11,12]],[0,0,-30])
     x = np.linspace(5,10,3)
     XYZ = Utils.ndgrid(x,x,np.r_[0.])
     srcLoc = np.r_[0,0,0.]
     rxList0 = Survey.BaseRx(XYZ, 'exi')
     Src0 = Survey.BaseSrc([rxList0], loc=srcLoc)
     rxList1 = Survey.BaseRx(XYZ, 'bxi')
     Src1 = Survey.BaseSrc([rxList1], loc=srcLoc)
     rxList2 = Survey.BaseRx(XYZ, 'bxi')
     Src2 = Survey.BaseSrc([rxList2], loc=srcLoc)
     rxList3 = Survey.BaseRx(XYZ, 'bxi')
     Src3 = Survey.BaseSrc([rxList3], loc=srcLoc)
     Src4 = Survey.BaseSrc([rxList0, rxList1, rxList2, rxList3], loc=srcLoc)
     srcList = [Src0,Src1,Src2,Src3,Src4]
     survey = Survey.BaseSurvey(srcList=srcList)
     self.D = Survey.Data(survey)
Example #51
0
    def get_interpolation_matrix(
        self,
        npts=20,
        epsilon=None
    ):

        tree_2d = kdtree(self.topography[:, :2])
        xy = Utils.ndgrid(self.mesh_3d.vectorCCx, self.mesh_3d.vectorCCy)

        distance, inds = tree_2d.query(xy, k=npts)
        if epsilon is None:
            epsilon = np.min([self.mesh_3d.hx.min(), self.mesh_3d.hy.min()])

        w = 1. / (distance + epsilon)**2
        w = Utils.sdiag(1./np.sum(w, axis=1)) * (w)
        I = Utils.mkvc(
            np.arange(inds.shape[0]).reshape([-1, 1]).repeat(npts, axis=1)
        )
        J = Utils.mkvc(inds)

        self._P = sp.coo_matrix(
            (Utils.mkvc(w), (I, J)),
            shape=(inds.shape[0], self.topography.shape[0])
        )

        mesh_1d = Mesh.TensorMesh([np.r_[self.hz[:-1], 1e20]])

        z = self.P*self.topography[:, 2]

        self._actinds = Utils.surface2ind_topo(self.mesh_3d, np.c_[xy, z])

        Z = np.empty(self.mesh_3d.vnC, dtype=float, order='F')
        Z = self.mesh_3d.gridCC[:, 2].reshape(
            (self.mesh_3d.nCx*self.mesh_3d.nCy, self.mesh_3d.nCz), order='F'
        )
        ACTIND = self._actinds.reshape(
            (self.mesh_3d.nCx*self.mesh_3d.nCy, self.mesh_3d.nCz), order='F'
        )

        self._Pz = []

        # This part can be cythonized or parallelized
        for i_xy in range(self.mesh_3d.nCx*self.mesh_3d.nCy):
            actind_temp = ACTIND[i_xy, :]
            z_temp = -(Z[i_xy, :] - z[i_xy])
            self._Pz.append(mesh_1d.getInterpolationMat(z_temp[actind_temp]))
Example #52
0
    def plot_survey_data(self, percentage, floor, seed, add_noise, plot_type,
                         update):
        self._percentage = percentage
        self._floor = floor
        self._seed = seed
        self._dobs = self.add_noise()
        self.survey.dobs = self._dobs.copy()

        fig, axs = plt.subplots(1, 2, figsize=(8, 4))
        out = self.mesh.plotImage(1.0 / self.slowness, ax=axs[0])
        cb = plt.colorbar(out[0], ax=axs[0], fraction=0.02)
        cb.set_label("Velocity (m/s)")
        self.survey.plot(ax=axs[0])
        axs[0].set_title("Survey")
        axs[0].set_xlabel("x (m)")
        axs[0].set_ylabel("z (m)")

        x = np.arange(10) + 1
        y = np.arange(10) + 1
        xy = Utils.ndgrid(x, y)
        if plot_type == "tx_rx_plane":
            if add_noise:
                out = Utils.plot2Ddata(xy, self.dobs, ax=axs[1])
            else:
                out = Utils.plot2Ddata(xy, self.pred, ax=axs[1])
            axs[1].set_xlabel("Rx")
            axs[1].set_ylabel("Tx")
            axs[1].set_xticks(x)
            axs[1].set_yticks(y)
            cb = plt.colorbar(out[0], ax=axs[1], fraction=0.02)
            cb.set_label("Traveltime (s)")
            for ax in axs:
                ax.set_aspect(1)
        else:
            if add_noise:
                out = axs[1].hist(self.pred, edgecolor="k")
            else:
                out = axs[1].hist(self.dobs, edgecolor="k")
            axs[1].set_ylabel("Count")
            axs[1].set_xlabel("Travel time (s)")
            axs[0].set_aspect(1)
        plt.tight_layout()
Example #53
0
def run(XYZ=None, loc=np.r_[0., 0., 0.], sig=1.0, freq=1.0, orientation='Z',
        plotIt=True):

    """
        EM: Magnetic Dipole in a Whole-Space
        ====================================

        Here we plot the magnetic flux density from a harmonic dipole in a
        wholespace.

    """

    if XYZ is None:
        # avoid putting measurement points where source is
        x = np.arange(-100.5, 100.5, step = 1.)
        y = np.r_[0]
        z = x
        XYZ = Utils.ndgrid(x, y, z)

    Bx, By, Bz = EM.Analytics.FDEM.MagneticDipoleWholeSpace(XYZ, loc, sig,
                                                            freq,
                                                            orientation=orientation)
    absB = np.sqrt(Bx*Bx.conj()+By*By.conj()+Bz*Bz.conj()).real

    if plotIt:
        import matplotlib.pyplot as plt
        from matplotlib.colors import LogNorm
        fig, ax = plt.subplots(1, 1, figsize=(6, 5))
        bxplt = Bx.reshape(x.size, z.size)
        bzplt = Bz.reshape(x.size, z.size)
        pc = ax.pcolor(x, z, absB.reshape(x.size, z.size), norm=LogNorm())
        ax.streamplot(x, z, bxplt.real, bzplt.real, color='k', density=1)
        ax.set_xlim([x.min(), x.max()])
        ax.set_ylim([z.min(), z.max()])
        ax.set_xlabel('x')
        ax.set_ylabel('z')
        cb = plt.colorbar(pc, ax = ax)
        cb.set_label('|B| (T)')
        plt.show()

        return fig, ax
Example #54
0
    def setUp(self):

        cs = 25.
        hx = [(cs, 0, -1.3), (cs, 21), (cs, 0, 1.3)]
        hy = [(cs, 0, -1.3), (cs, 21), (cs, 0, 1.3)]
        hz = [(cs, 0, -1.3), (cs, 20), (cs, 0, 1.3)]
        mesh = Mesh.TensorMesh([hx, hy, hz], x0="CCC")
        blkind0 = Utils.ModelBuilder.getIndicesSphere(
            np.r_[-100., -100., -200.], 75., mesh.gridCC
        )
        blkind1 = Utils.ModelBuilder.getIndicesSphere(
            np.r_[100., 100., -200.], 75., mesh.gridCC
        )
        sigma = np.ones(mesh.nC)*1e-2
        airind = mesh.gridCC[:, 2] > 0.
        sigma[airind] = 1e-8
        eta = np.zeros(mesh.nC)
        tau = np.ones_like(sigma) * 1.
        c = np.ones_like(sigma) * 0.5

        eta[blkind0] = 0.1
        eta[blkind1] = 0.1
        tau[blkind0] = 0.1
        tau[blkind1] = 0.01

        actmapeta = Maps.InjectActiveCells(mesh, ~airind, 0.)
        actmaptau = Maps.InjectActiveCells(mesh, ~airind, 1.)
        actmapc = Maps.InjectActiveCells(mesh, ~airind, 1.)

        x = mesh.vectorCCx[(mesh.vectorCCx > -155.) & (mesh.vectorCCx < 155.)]
        y = mesh.vectorCCy[(mesh.vectorCCy > -155.) & (mesh.vectorCCy < 155.)]
        Aloc = np.r_[-200., 0., 0.]
        Bloc = np.r_[200., 0., 0.]
        M = Utils.ndgrid(x-25., y, np.r_[0.])
        N = Utils.ndgrid(x+25., y, np.r_[0.])

        times = np.arange(10)*1e-3 + 1e-3
        rx = SIP.Rx.Dipole(M, N, times)
        src = SIP.Src.Dipole([rx], Aloc, Bloc)
        survey = SIP.Survey([src])

        wires = Maps.Wires(('eta', actmapeta.nP), ('taui', actmaptau.nP), ('c', actmapc.nP))
        problem = SIP.Problem3D_N(
            mesh,
            sigma=sigma,
            etaMap=actmapeta*wires.eta,
            tauiMap=actmaptau*wires.taui,
            cMap=actmapc*wires.c,
            actinds=~airind,
            storeJ = True,
            verbose=False
        )

        problem.Solver = Solver
        problem.pair(survey)
        mSynth = np.r_[eta[~airind], 1./tau[~airind], c[~airind]]
        survey.makeSyntheticData(mSynth)
        # Now set up the problem to do some minimization
        dmis = DataMisfit.l2_DataMisfit(survey)
        dmis = DataMisfit.l2_DataMisfit(survey)
        reg_eta = Regularization.Simple(mesh, mapping=wires.eta, indActive=~airind)
        reg_taui = Regularization.Simple(mesh, mapping=wires.taui, indActive=~airind)
        reg_c = Regularization.Simple(mesh, mapping=wires.c, indActive=~airind)
        reg = reg_eta + reg_taui + reg_c
        opt = Optimization.InexactGaussNewton(
            maxIterLS=20, maxIter=10, tolF=1e-6,
            tolX=1e-6, tolG=1e-6, maxIterCG=6
        )
        invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta=1e4)
        inv = Inversion.BaseInversion(invProb)

        self.inv = inv
        self.reg = reg
        self.p = problem
        self.mesh = mesh
        self.m0 = mSynth
        self.survey = survey
        self.dmis = dmis
Example #55
0
 def _getTensorGrid(self, key):
     if getattr(self, '_grid' + key, None) is None:
         setattr(self, '_grid' + key, Utils.ndgrid(self.getTensor(key)))
     return getattr(self, '_grid' + key)
Example #56
0
    def test_CylMeshEBDipoles(self):
        print ("Testing CylMesh Electric and Magnetic Dipoles in a wholespace-"
               " Analytic: J-formulation")
        sigmaback = 1.
        mur = 2.
        freq = 1.
        skdpth = 500./np.sqrt(sigmaback*freq)

        csx, ncx, npadx = 5, 50, 25
        csz, ncz, npadz = 5, 50, 25
        hx = Utils.meshTensor([(csx,ncx), (csx,npadx,1.3)])
        hz = Utils.meshTensor([(csz,npadz,-1.3), (csz,ncz), (csz,npadz,1.3)])
        mesh = Mesh.CylMesh([hx, 1, hz], [0., 0., -hz.sum()/2]) # define the cylindrical mesh

        if plotIt:
            mesh.plotGrid()

        # make sure mesh is big enough
        self.assertTrue(mesh.hz.sum() > skdpth*2.)
        self.assertTrue(mesh.hx.sum() > skdpth*2.)

        SigmaBack = sigmaback*np.ones((mesh.nC))
        MuBack = mur*mu_0*np.ones((mesh.nC))

        # set up source
        # test electric dipole
        src_loc = np.r_[0., 0., 0.]
        s_ind = Utils.closestPoints(mesh, src_loc, 'Fz') + mesh.nFx

        de = np.zeros(mesh.nF, dtype=complex)
        de[s_ind] = 1./csz
        de_p = [EM.FDEM.Src.RawVec_e([], freq, de/mesh.area)]

        dm_p = [EM.FDEM.Src.MagDipole([], freq, src_loc)]

        # Pair the problem and survey
        surveye = EM.FDEM.Survey(de_p)
        surveym = EM.FDEM.Survey(dm_p)

        mapping = [('sigma', Maps.IdentityMap(mesh)),
                   ('mu', Maps.IdentityMap(mesh))]

        prbe = EM.FDEM.Problem3D_h(mesh, mapping=mapping)
        prbm = EM.FDEM.Problem3D_e(mesh, mapping=mapping)

        prbe.pair(surveye) # pair problem and survey
        prbm.pair(surveym)

        # solve
        fieldsBackE = prbe.fields(np.r_[SigmaBack, MuBack]) # Done
        fieldsBackM = prbm.fields(np.r_[SigmaBack, MuBack]) # Done


        rlim = [20., 500.]
        lookAtTx = de_p
        r = mesh.vectorCCx[np.argmin(np.abs(mesh.vectorCCx-rlim[0])) : np.argmin(np.abs(mesh.vectorCCx-rlim[1]))]
        z = 100.

        # where we choose to measure
        XYZ = Utils.ndgrid(r, np.r_[0.], np.r_[z])

        Pf = mesh.getInterpolationMat(XYZ, 'CC')
        Zero = sp.csr_matrix(Pf.shape)
        Pfx,Pfz = sp.hstack([Pf,Zero]),sp.hstack([Zero,Pf])

        jn = fieldsBackE[de_p,'j']
        bn = fieldsBackM[dm_p,'b']

        Rho = Utils.sdiag(1./SigmaBack)
        Rho = sp.block_diag([Rho,Rho])

        en = Rho*mesh.aveF2CCV*jn
        bn = mesh.aveF2CCV*bn

        ex, ez = Pfx*en, Pfz*en
        bx, bz = Pfx*bn, Pfz*bn

        # get analytic solution
        exa, eya, eza = EM.Analytics.FDEM.ElectricDipoleWholeSpace(XYZ, src_loc, sigmaback, freq,orientation='Z',mu= mur*mu_0)
        exa, eya, eza = Utils.mkvc(exa, 2), Utils.mkvc(eya, 2), Utils.mkvc(eza, 2)

        bxa, bya, bza = EM.Analytics.FDEM.MagneticDipoleWholeSpace(XYZ, src_loc, sigmaback, freq,orientation='Z',mu= mur*mu_0)
        bxa, bya, bza = Utils.mkvc(bxa, 2), Utils.mkvc(bya, 2), Utils.mkvc(bza, 2)

        print(' comp,       anayltic,       numeric,       num - ana,       (num - ana)/ana')
        print('  ex:', np.linalg.norm(exa), np.linalg.norm(ex), np.linalg.norm(exa-ex), np.linalg.norm(exa-ex)/np.linalg.norm(exa))
        print('  ez:', np.linalg.norm(eza), np.linalg.norm(ez), np.linalg.norm(eza-ez), np.linalg.norm(eza-ez)/np.linalg.norm(eza))

        print('  bx:', np.linalg.norm(bxa), np.linalg.norm(bx), np.linalg.norm(bxa-bx), np.linalg.norm(bxa-bx)/np.linalg.norm(bxa))
        print('  bz:', np.linalg.norm(bza), np.linalg.norm(bz), np.linalg.norm(bza-bz), np.linalg.norm(bza-bz)/np.linalg.norm(bza))

        if plotIt is True:
            # Edipole
            plt.subplot(221)
            plt.plot(r,ex.real,'o',r,exa.real,linewidth=2)
            plt.grid(which='both')
            plt.title('Ex Real')
            plt.xlabel('r (m)')

            plt.subplot(222)
            plt.plot(r,ex.imag,'o',r,exa.imag,linewidth=2)
            plt.grid(which='both')
            plt.title('Ex Imag')
            plt.legend(['Num','Ana'],bbox_to_anchor=(1.5,0.5))
            plt.xlabel('r (m)')

            plt.subplot(223)
            plt.plot(r,ez.real,'o',r,eza.real,linewidth=2)
            plt.grid(which='both')
            plt.title('Ez Real')
            plt.xlabel('r (m)')

            plt.subplot(224)
            plt.plot(r,ez.imag,'o',r,eza.imag,linewidth=2)
            plt.grid(which='both')
            plt.title('Ez Imag')
            plt.xlabel('r (m)')

            plt.tight_layout()

            # Bdipole
            plt.subplot(221)
            plt.plot(r,bx.real,'o',r,bxa.real,linewidth=2)
            plt.grid(which='both')
            plt.title('Bx Real')
            plt.xlabel('r (m)')

            plt.subplot(222)
            plt.plot(r,bx.imag,'o',r,bxa.imag,linewidth=2)
            plt.grid(which='both')
            plt.title('Bx Imag')
            plt.legend(['Num','Ana'],bbox_to_anchor=(1.5,0.5))
            plt.xlabel('r (m)')

            plt.subplot(223)
            plt.plot(r,bz.real,'o',r,bza.real,linewidth=2)
            plt.grid(which='both')
            plt.title('Bz Real')
            plt.xlabel('r (m)')

            plt.subplot(224)
            plt.plot(r,bz.imag,'o',r,bza.imag,linewidth=2)
            plt.grid(which='both')
            plt.title('Bz Imag')
            plt.xlabel('r (m)')

            plt.tight_layout()

        self.assertTrue(np.linalg.norm(exa-ex)/np.linalg.norm(exa) < tol_EBdipole)
        self.assertTrue(np.linalg.norm(eza-ez)/np.linalg.norm(eza) < tol_EBdipole)

        self.assertTrue(np.linalg.norm(bxa-bx)/np.linalg.norm(bxa) < tol_EBdipole)
        self.assertTrue(np.linalg.norm(bza-bz)/np.linalg.norm(bza) < tol_EBdipole)