def getCoreModel(self, Type):

        if Type == 'Layer':
            active = self.mesh2D.vectorCCy < self.z0
            ind1 = ((self.mesh2D.vectorCCy < self.z0) &
                    (self.mesh2D.vectorCCy >= self.z1))
            ind2 = ((self.mesh2D.vectorCCy < self.z1) &
                    (self.mesh2D.vectorCCy >= self.z2))
            mapping2D = (
                Maps.SurjectVertical1D(self.mesh2D) * Maps.InjectActiveCells(
                    self.mesh2D, active, self.sig0, nC=self.mesh2D.nCy))
            model2D = np.ones(self.mesh2D.nCy) * self.sig3
            model2D[ind1] = self.sig1
            model2D[ind2] = self.sig2
            model2D = model2D[active]
        elif Type == 'Sphere':
            active = self.mesh2D.gridCC[:, 1] < self.z0
            ind1 = ((self.mesh2D.gridCC[:, 1] < self.z1) &
                    (self.mesh2D.gridCC[:, 1] >= self.z1 - self.h))
            ind2 = np.sqrt((self.mesh2D.gridCC[:, 0])**2 +
                           (self.mesh2D.gridCC[:, 1] - self.z2)**2) <= self.R

            mapping2D = (Maps.InjectActiveCells(self.mesh2D,
                                                active,
                                                self.sig0,
                                                nC=self.mesh2D.nC))
            model2D = np.ones(self.mesh2D.nC) * self.sigb
            model2D[ind1] = self.sig1
            model2D[ind2] = self.sig2
            model2D = model2D[active]

        return model2D, mapping2D
Example #2
0
def spectral_ip_mappings(mesh,
                         indActive=None,
                         inactive_eta=1e-4,
                         inactive_tau=1e-4,
                         inactive_c=1e-4,
                         is_log_eta=True,
                         is_log_tau=True,
                         is_log_c=True):
    """
    Generates Mappings for Spectral Induced Polarization Problem.
    Three parameters are required to be input:
    Chargeability (eta), Time constant (tau), and Frequency dependency (c).
    If there is no topography (indActive is None),
    model (m) can be either set to

    m = np.r_[log(eta), log(tau), log(c)] or m = np.r_[eta, tau, c]

    When indActive is not None, m is

    m = np.r_[log(eta[indAcitve]), log(tau[indAcitve]), log(c[indAcitve])] or
    m = np.r_[eta[indAcitve], tau[indAcitve], c[indAcitve]] or

    TODO: Illustrate input and output variables
    """

    if indActive is None:
        indActive = np.ones(mesh.nC, dtype=bool)

    actmap_eta = Maps.InjectActiveCells(mesh,
                                        indActive=indActive,
                                        valInactive=inactive_eta)
    actmap_tau = Maps.InjectActiveCells(mesh,
                                        indActive=indActive,
                                        valInactive=inactive_tau)
    actmap_c = Maps.InjectActiveCells(mesh,
                                      indActive=indActive,
                                      valInactive=inactive_c)

    wires = Maps.Wires(('eta', indActive.sum()), ('tau', indActive.sum()),
                       ('c', indActive.sum()))

    if is_log_eta:
        eta_map = actmap_eta * Maps.ExpMap(nP=actmap_eta.nP) * wires.eta
    else:
        eta_map = actmap_eta * wires.eta

    if is_log_tau:
        tau_map = actmap_tau * Maps.ExpMap(nP=actmap_tau.nP) * wires.tau
    else:
        tau_map = actmap_tau * wires.tau

    if is_log_c:
        c_map = actmap_c * Maps.ExpMap(nP=actmap_c.nP) * wires.c
    else:
        c_map = actmap_c * wires.c

    return eta_map, tau_map, c_map, wires
    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
    def setUp(self):

        cs = 5.
        ncx = 20
        ncy = 6
        npad = 20
        hx = [(cs, ncx), (cs, npad, 1.3)]
        hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
        mesh = Mesh.CylMesh([hx, 1, hy], '00C')

        active = mesh.vectorCCz < 0.
        activeMap = Maps.InjectActiveCells(mesh,
                                           active,
                                           np.log(1e-8),
                                           nC=mesh.nCz)
        mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap

        rxOffset = 40.
        rx = EM.TDEM.RxTDEM(np.array([[rxOffset, 0., 0.]]),
                            np.logspace(-4, -3, 20), 'bz')
        src = EM.TDEM.SrcTDEM_VMD_MVP([rx], loc=np.array([0., 0., 0.]))

        survey = EM.TDEM.SurveyTDEM([src])

        self.prb = EM.TDEM.ProblemTDEM_b(mesh, mapping=mapping)
        # self.prb.timeSteps = [1e-5]
        self.prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)]
        # self.prb.timeSteps = [(1e-05, 100)]

        try:
            from pymatsolver import MumpsSolver
            self.prb.Solver = MumpsSolver
        except ImportError, e:
            self.prb.Solver = SolverLU
Example #5
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)
    def setThreeLayerParam(self,
                           h1=12,
                           h2=12,
                           sig0=1e-8,
                           sig1=1e-2,
                           sig2=1e-2,
                           sig3=1e-2,
                           chi=0.):
        self.h1 = h1  # 1st layer thickness
        self.h2 = h2  # 2nd layer thickness
        self.z0 = 0.
        self.z1 = self.z0 - h1
        self.z2 = self.z0 - h1 - h2
        self.sig0 = sig0  # 0th layer \sigma (assumed to be air)
        self.sig1 = sig1  # 1st layer \sigma
        self.sig2 = sig2  # 2nd layer \sigma
        self.sig3 = sig3  # 3rd layer \sigma

        active = self.mesh.vectorCCz < self.z0
        ind1 = ((self.mesh.vectorCCz < self.z0) &
                (self.mesh.vectorCCz >= self.z1))
        ind2 = ((self.mesh.vectorCCz < self.z1) &
                (self.mesh.vectorCCz >= self.z2))
        self.mapping = (
            Maps.SurjectVertical1D(self.mesh) *
            Maps.InjectActiveCells(self.mesh, active, sig0, nC=self.mesh.nCz))
        model = np.ones(self.mesh.nCz) * sig3
        model[ind1] = sig1
        model[ind2] = sig2
        self.m = model[active]
        self.mu = np.ones(self.mesh.nC) * mu_0
        self.mu[self.mesh.gridCC[:, 2] < 0.] = (1. + chi) * mu_0
        return self.m
Example #7
0
    def muModel(self):
        # Mu Model
        # here, we want to consider variable magnetic permeability in the
        # simulation. The only permeable item in the domain is the casing.
        if getattr(self, '_muModel', None) is None:
            if getattr(self, '_paramMapPrimary', None) is None:
                self.primaryMapping

            muMap = (Maps.InjectActiveCells(
                        self.meshp, self.indActivePrimary, mu_0) *
                     self._paramMapPrimary)

            muModel = muMap * np.hstack(
                np.r_[
                    mu_0,  # val Background
                    mu_0,  # val Layer
                    mu_0*self.mucasing,  # val Casing
                    mu_0,  # val inside Casing
                    self.layer_z.mean(),  # layer center
                    self.layer_z[1] - self.layer_z[0],  # layer thickness
                    self.casing_r,  # casing radius
                    self.casing_t,  # casing thickness
                    self.casing_z[0],  # casing bottom
                    self.casing_z[1]  # casing top
                ]
            )
            self._muModel = muModel
        return self._muModel
Example #8
0
    def test_tripleMultiply(self):
        M = Mesh.TensorMesh([2, 4], '0C')
        expMap = Maps.ExpMap(M)
        vertMap = Maps.SurjectVertical1D(M)
        actMap = Maps.InjectActiveCells(M, M.vectorCCy <= 0, 10, nC=M.nCy)
        m = np.r_[1., 2.]
        t_true = np.exp(np.r_[1, 1, 2, 2, 10, 10, 10, 10.])

        self.assertLess(
            np.linalg.norm((expMap * vertMap * actMap * m) - t_true, np.inf),
            TOL)
        self.assertLess(
            np.linalg.norm(((expMap * vertMap * actMap) * m) - t_true, np.inf),
            TOL)
        self.assertLess(
            np.linalg.norm((expMap * vertMap * (actMap * m)) - t_true, np.inf),
            TOL)
        self.assertLess(
            np.linalg.norm((expMap * (vertMap * actMap) * m) - t_true, np.inf),
            TOL)
        self.assertLess(
            np.linalg.norm(((expMap * vertMap) * actMap * m) - t_true, np.inf),
            TOL)

        self.assertRaises(ValueError, lambda: expMap * actMap * vertMap)
        self.assertRaises(ValueError, lambda: actMap * vertMap * expMap)
Example #9
0
    def setup(self):
        self.setup_geometry()
        self.setup_measurement()


        # Setup Problem with exponential mapping and Active cells only in the core mesh
        expmap = Maps.ExpMap(self.mesh)
        mapactive = Maps.InjectActiveCells(mesh=self.mesh, indActive=self.actind,
                                           valInactive=-5.)
        self.mapping = expmap * mapactive
        problem = DC.Problem3D_CC(self.mesh, sigmaMap=self.mapping)
        problem.pair(self.survey.simpeg_survey)
        problem.Solver = Solver

        # Compute prediction using the forward model and true conductivity data.
        # survey.dpred(mtrue[actind])
        # Make synthetic data adding a noise to the prediction.
        # In fact prediction is computed again.

        self.set_syntetic_conductivity()
        #self.survey.simpeg_survey.makeSyntheticData(self.mtrue[self.actind], std=0.05, force=True)

        m = self.mtrue[self.actind]
        std = 0.05
        dtrue = self.survey.simpeg_survey.dpred(m, f=None)
        noise = std*abs(dtrue)*np.random.randn(*dtrue.shape)
        self.survey.simpeg_survey.dobs = dtrue+noise
        self.survey.simpeg_survey.std = dtrue*0 + std
Example #10
0
    def test_nC_residual(self):

        # x-direction
        cs, ncx, ncz, npad = 1., 10., 10., 20
        hx = [(cs, ncx), (cs, npad, 1.3)]

        # z direction
        npad = 12
        temp = np.logspace(np.log10(1.), np.log10(12.), 19)
        temp_pad = temp[-1] * 1.3**np.arange(npad)
        hz = np.r_[temp_pad[::-1], temp[::-1], temp, temp_pad]
        mesh = Mesh.CylMesh([hx, 1, hz], '00C')
        active = mesh.vectorCCz < 0.

        active = mesh.vectorCCz < 0.
        actMap = Maps.InjectActiveCells(mesh,
                                        active,
                                        np.log(1e-8),
                                        nC=mesh.nCz)
        mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * actMap

        regMesh = Mesh.TensorMesh([mesh.hz[mapping.maps[-1].indActive]])
        reg = Regularization.Simple(regMesh)

        self.assertTrue(reg._nC_residual == regMesh.nC)
        self.assertTrue(
            all([fct._nC_residual == regMesh.nC for fct in reg.objfcts]))
Example #11
0
    def setup(self):
        self.setup_geometry()
        self.set_syntetic_conductivity()
        self.setup_measurement()

        # Setup Problem with exponential mapping and Active cells only in the core mesh
        expmap = Maps.ExpMap(self.mesh)
        extrude = Maps.Surject2Dto3D(self.mesh_core, normal='Y')
        mapactive = Maps.InjectActiveCells(mesh=self.mesh,
                                           indActive=self.actind,
                                           valInactive=-5.)
        self.mapping = expmap * mapactive * extrude
        assert self.mapping.nP == self.mesh_core.nCx * self.mesh_core.nCz
        problem = DC.Problem3D_CC(self.mesh, sigmaMap=self.mapping)
        problem.pair(self.survey.simpeg_survey)
        problem.Solver = SolverLU
        #problem.Solver = SolverBiCG

        # Compute prediction using the forward model and true conductivity data.
        # survey.dpred(mtrue[actind])
        # Make synthetic data adding a noise to the prediction.
        # In fact prediction is computed again.
        self.survey.simpeg_survey.makeSyntheticData(self.mtrue,
                                                    std=0.05,
                                                    force=True)
Example #12
0
def run(plotIt=True):
    """
        EM: FDEM: 1D: Inversion
        =======================

        Here we will create and run a FDEM 1D inversion.

    """

    cs, ncx, ncz, npad = 5., 25, 15, 15
    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')

    layerz = -100.

    active = mesh.vectorCCz < 0.
    layer = (mesh.vectorCCz < 0.) & (mesh.vectorCCz >= layerz)
    actMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
    mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * actMap
    sig_half = 2e-2
    sig_air = 1e-8
    sig_layer = 1e-2
    sigma = np.ones(mesh.nCz) * sig_air
    sigma[active] = sig_half
    sigma[layer] = sig_layer
    mtrue = np.log(sigma[active])

    if plotIt:
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(1, 1, figsize=(3, 6))
        plt.semilogx(sigma[active], mesh.vectorCCz[active])
        ax.set_ylim(-500, 0)
        ax.set_xlim(1e-3, 1e-1)
        ax.set_xlabel('Conductivity (S/m)', fontsize=14)
        ax.set_ylabel('Depth (m)', fontsize=14)
        ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)

    rxOffset = 10.
    bzi = EM.FDEM.Rx.Point_b(np.array([[rxOffset, 0., 1e-3]]),
                             orientation='z',
                             component='imag')

    freqs = np.logspace(1, 3, 10)
    srcLoc = np.array([0., 0., 10.])

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

    survey = EM.FDEM.Survey(srcList)
    prb = EM.FDEM.Problem3D_b(mesh, mapping=mapping)

    try:
        from pymatsolver import MumpsSolver
        prb.Solver = MumpsSolver
    except ImportError, e:
        prb.Solver = SolverLU
Example #13
0
    def __init__(self, mesh, **kwargs):
        BaseSIPProblem_2D.__init__(self, mesh, **kwargs)
        if self.actinds is None:
            print("You did not put Active indices")
            print("So, set actMap = IdentityMap(mesh)")
            self.actinds = np.ones(mesh.nC, dtype=bool)

        self.actMap = Maps.InjectActiveCells(mesh, self.actinds, 0.)
Example #14
0
def setUp_TDEM(prbtype='b', rxcomp='bz', waveform='stepoff'):
    cs = 5.
    ncx = 8
    ncy = 8
    ncz = 8
    npad = 4
    # hx = [(cs, ncx), (cs, npad, 1.3)]
    # hz = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
    mesh = Mesh.TensorMesh(
        [
            [(cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)],
            [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)],
            [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)]
        ], 'CCC'
    )

    active = mesh.vectorCCz < 0.
    activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
    mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap

    prb = getattr(EM.TDEM, 'Problem3D_{}'.format(prbtype))(mesh, sigmaMap=mapping)

    rxtimes = np.logspace(-4, -3, 20)

    if waveform.upper() == 'RAW':
        out = EM.Utils.VTEMFun(prb.times, 0.00595, 0.006, 100)
        wavefun = interp1d(prb.times, out)
        t0 = 0.006
        waveform = EM.TDEM.Src.RawWaveform(offTime=t0, waveFct=wavefun)
        prb.timeSteps = [(1e-3, 5), (1e-4, 5), (5e-5, 10), (5e-5, 10), (1e-4, 10)]
        rxtimes = t0+rxtimes

    else:
        waveform = EM.TDEM.Src.StepOffWaveform()
        prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)]

    rxOffset = 10.
    rx = getattr(EM.TDEM.Rx, 'Point_{}'.format(rxcomp[:-1]))(
        np.array([[rxOffset, 0., -1e-2]]), rxtimes, rxcomp[-1]
    )
    src = EM.TDEM.Src.MagDipole(
        [rx], loc=np.array([0., 0., 0.]), waveform=waveform
    )

    survey = EM.TDEM.Survey([src])



    prb.Solver = Solver

    m = (np.log(1e-1)*np.ones(prb.sigmaMap.nP) +
         1e-2*np.random.rand(prb.sigmaMap.nP))

    prb.pair(survey)
    mesh = mesh

    return prb, m, mesh
Example #15
0
 def _setupDCProblem(self):
     expMap = Maps.ExpMap(self.mesh)
     inactiveCellIndices = numpy.logical_not(self.activeCellIndices)
     inactiveCellData = self.givenModelCond[inactiveCellIndices]
     mapActive = Maps.InjectActiveCells(mesh=self.mesh, indActive=self.activeCellIndices,
                                        valInactive=inactiveCellData)
     self.mapping = expMap * mapActive
     self.DCproblem = DC.Problem3D_CC(self.mesh, sigmaMap=self.mapping)
     self.DCproblem.pair(self.survey)
     self.DCproblem.Solver = Solver
     pass
Example #16
0
def halfSpaceProblemAnaDiff(meshType, sig_half=1e-2, rxOffset=50., bounds=None, showIt=False):

    print '\nTesting sig_half = {0}, rxOffset= {1}'.format(sig_half, rxOffset)

    if bounds is None:
        bounds = [1e-5, 1e-3]
    if meshType == 'CYL':
        cs, ncx, ncz, npad = 5., 30, 10, 20
        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')
    elif meshType == 'TENSOR':
        cs, nc, npad = 20., 13, 5
        hx = [(cs, npad, -1.3), (cs, nc), (cs, npad, 1.3)]
        hy = [(cs, npad, -1.3), (cs, nc), (cs, npad, 1.3)]
        hz = [(cs, npad, -1.3), (cs, nc), (cs, npad, 1.3)]
        mesh = Mesh.TensorMesh([hx, hy, hz], 'CCC')

    active = mesh.vectorCCz < 0.
    actMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
    mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * actMap

    rx = EM.TDEM.RxTDEM(np.array([[rxOffset, 0., 0.]]),
                        np.logspace(-5, -4, 21), 'bz')
    src = EM.TDEM.SrcTDEM_VMD_MVP([rx], loc=np.array([0., 0., 0.]))
    # src = EM.TDEM.SrcTDEM([rx], loc=np.array([0., 0., 0.]))

    survey = EM.TDEM.SurveyTDEM([src])
    prb = EM.TDEM.ProblemTDEM_b(mesh, mapping=mapping)
    prb.Solver = MumpsSolver

    prb.timeSteps = [(1e-06, 40), (5e-06, 40), (1e-05, 40), (5e-05, 40), (0.0001, 40), (0.0005, 40)]

    sigma = np.ones(mesh.nCz)*1e-8
    sigma[active] = sig_half
    sigma = np.log(sigma[active])
    prb.pair(survey)

    bz_ana = mu_0*EM.Analytics.hzAnalyticDipoleT(rx.locs[0][0]+1e-3, rx.times, sig_half)

    bz_calc = survey.dpred(sigma)

    ind = np.logical_and(rx.times > bounds[0], rx.times < bounds[1])
    log10diff = np.linalg.norm(np.log10(np.abs(bz_calc[ind])) - np.log10(np.abs(bz_ana[ind])))/np.linalg.norm(np.log10(np.abs(bz_ana[ind])))
    print 'Difference: ', log10diff

    if showIt == True:
        plt.loglog(rx.times[bz_calc>0], bz_calc[bz_calc>0], 'r', rx.times[bz_calc<0], -bz_calc[bz_calc<0], 'r--')
        plt.loglog(rx.times, abs(bz_ana), 'b*')
        plt.title('sig_half = {0:e}'.format(sig_half))
        plt.show()

    return log10diff
Example #17
0
    def test_activeCells(self):
        M = Mesh.TensorMesh([2, 4], '0C')
        for actMap in [Maps.InjectActiveCells(M, M.vectorCCy <= 0, 10,
                       nC=M.nCy), Maps.ActiveCells(M, M.vectorCCy <= 0, 10,
                       nC=M.nCy)]:

            vertMap = Maps.SurjectVertical1D(M)
            combo = vertMap * actMap
            m = np.r_[1., 2.]
            mod = Models.Model(m, combo)

            self.assertLess(np.linalg.norm(mod.transform -
                            np.r_[1, 1, 2, 2, 10, 10, 10, 10.]), TOL)
            self.assertLess((mod.transformDeriv -
                            combo.deriv(m)).toarray().sum(), TOL)
Example #18
0
def setUp_TDEM(prbtype='e', rxcomp='ex'):
    cs = 5.
    ncx = 8
    ncy = 8
    ncz = 8
    npad = 0
    # hx = [(cs, ncx), (cs, npad, 1.3)]
    # hz = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
    mesh = Mesh.TensorMesh([[
        (cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)
    ], [(cs, npad, -1.3), (cs, ncy),
        (cs, npad, 1.3)], [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)]],
                           'CCC')
    #
    active = mesh.vectorCCz < 0.
    activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
    mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap

    rxOffset = 0.
    rxlocs = np.array([[20, 20., 0.]])
    rxtimes = np.logspace(-4, -3, 20)
    rx = getattr(EM.TDEM.Rx,
                 'Point_{}'.format(rxcomp[:-1]))(locs=rxlocs,
                                                 times=rxtimes,
                                                 orientation=rxcomp[-1])
    Aloc = np.r_[-10., 0., 0.]
    Bloc = np.r_[10., 0., 0.]
    srcloc = np.vstack((Aloc, Bloc))

    src = EM.TDEM.Src.LineCurrent([rx],
                                  loc=srcloc,
                                  waveform=EM.TDEM.Src.StepOffWaveform())
    survey = EM.TDEM.Survey([src])

    prb = getattr(EM.TDEM, 'Problem3D_{}'.format(prbtype))(mesh,
                                                           sigmaMap=mapping)

    prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)]

    prb.Solver = Solver

    m = (np.log(1e-1) * np.ones(prb.sigmaMap.nP) +
         1e-3 * np.random.randn(prb.sigmaMap.nP))

    prb.pair(survey)
    mesh = mesh

    return prb, m, mesh
    def setup(self):
        self.setup_geometry()
        self.set_real_data_survey()
        #self.set_syntetic_conductivity()
        #self.setup_measurement()

        self.ln_sigback = np.log(self.survey.median_apparent_conductivity())
        print("ln cond med: ", self.ln_sigback)

        # Setup Problem with exponential mapping and Active cells only in the core mesh
        expmap = Maps.ExpMap(self.mesh)
        mapactive = Maps.InjectActiveCells(mesh=self.mesh,
                                           indActive=self.actind,
                                           valInactive=self.ln_sigback)
        self.mapping = expmap * mapactive
        problem = DC.Problem3D_CC(self.mesh, sigmaMap=self.mapping)
        problem.pair(self.survey.simpeg_survey)
        problem.Solver = Solver
Example #20
0
 def test_activeCells(self):
     M = Mesh.TensorMesh([2, 4], '0C')
     expMap = Maps.ExpMap(M)
     for actMap in [
             Maps.InjectActiveCells(M, M.vectorCCy <= 0, 10, nC=M.nCy),
             Maps.ActiveCells(M, M.vectorCCy <= 0, 10, nC=M.nCy)
     ]:
         # actMap = Maps.InjectActiveCells(M, M.vectorCCy <=0, 10, nC=M.nCy)
         vertMap = Maps.SurjectVertical1D(M)
         combo = vertMap * actMap
         m = np.r_[1, 2.]
         mod = Models.Model(m, combo)
         # import matplotlib.pyplot as plt
         # plt.colorbar(M.plotImage(mod.transform)[0])
         # plt.show()
         self.assertLess(
             np.linalg.norm(mod.transform -
                            np.r_[1, 1, 2, 2, 10, 10, 10, 10.]), TOL)
         self.assertLess(
             (mod.transformDeriv - combo.deriv(m)).toarray().sum(), TOL)
def setUp_TDEM(prbtype='b', rxcomp='bz'):

    cs = 5.
    ncx = 20
    ncy = 15
    npad = 20
    hx = [(cs, ncx), (cs, npad, 1.3)]
    hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
    mesh = Mesh.CylMesh([hx, 1, hy], '00C')
#
    active = mesh.vectorCCz < 0.
    activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
    mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap

    rxOffset = 10.

    if prbtype == 'b':
        prb = EM.TDEM.Problem3D_b(mesh, mapping=mapping)
    elif prbtype == 'e':
        prb = EM.TDEM.Problem3D_e(mesh, mapping=mapping)
    prb.timeSteps = [(1e-3, 5), (1e-4, 5), (5e-5, 10), (5e-5, 10), (1e-4, 10)]
    out = EM.Utils.VTEMFun(prb.times, 0.00595, 0.006, 100)
    wavefun = interp1d(prb.times, out)
    t0 = 0.006
    waveform = EM.TDEM.Src.RawWaveform(offTime=t0, waveFct=wavefun)
    timerx = np.logspace(-4, -3, 20)
    rx = EM.TDEM.Rx(np.array([[rxOffset, 0., 0.]]), timerx, rxcomp)
    src = EM.TDEM.Src.MagDipole([rx], waveform= waveform,
                                loc=np.array([0., 0., 0.]))

    survey = EM.TDEM.Survey([src])

    prb.Solver = Solver

    m = np.log(1e-1)*np.ones(prb.mapping.nP)
    # + 1e-2*np.random.randn(prb.mapping.nP)

    prb.pair(survey)
    mesh = mesh

    return prb, m, mesh
def setUp_TDEM(self, rxcomp='bz'):

        cs = 5.
        ncx = 20
        ncy = 6
        npad = 20
        hx = [(cs, ncx), (cs, npad, 1.3)]
        hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
        mesh = Mesh.CylMesh([hx, 1, hy], '00C')

        active = mesh.vectorCCz < 0.
        activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8),
                                           nC=mesh.nCz)
        mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap

        rxOffset = 40.
        rx = EM.TDEM.Rx(np.array([[rxOffset, 0., 0.]]),
                        np.logspace(-4, -3, 20), rxcomp)
        src = EM.TDEM.Src.MagDipole([rx], loc=np.array([0., 0., 0.]))
        rx2 = EM.TDEM.Rx(np.array([[rxOffset-10, 0., 0.]]),
                         np.logspace(-5, -4, 25), rxcomp)
        src2 = EM.TDEM.Src.MagDipole( [rx2], loc=np.array([0., 0., 0.]))

        survey = EM.TDEM.Survey([src, src2])

        prb = EM.TDEM.Problem3D_b(mesh, mapping=mapping)
        # prb.timeSteps = [1e-5]
        prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)]
        # prb.timeSteps = [(1e-05, 100)]

        prb.Solver = Solver

        m = (np.log(1e-1)*np.ones(prb.mapping.nP) +
             1e-2*np.random.randn(prb.mapping.nP))

        prb.pair(survey)

        return mesh, prb, m
    def setLayerSphereParam(self,
                            d1=6,
                            h=6,
                            d2=16,
                            R=4,
                            sig0=1e-8,
                            sigb=1e-2,
                            sig1=1e-1,
                            sig2=1.,
                            chi=0.):
        self.z0 = 0.  # Surface elevation
        self.z1 = self.z0 - d1  # Depth to layer
        self.h = h  # Thickness of layer
        self.z2 = self.z0 - d2  # Depth to center of sphere
        self.R = R  # Radius of sphere
        self.sig0 = sig0  # Air conductivity
        self.sigb = sigb  # Background conductivity
        self.sig1 = sig1  # Layer conductivity
        self.sig2 = sig2  # Sphere conductivity

        active = self.mesh.gridCC[:, 2] < self.z0
        ind1 = ((self.mesh.gridCC[:, 2] < self.z1) &
                (self.mesh.gridCC[:, 2] >= self.z1 - self.h))
        ind2 = np.sqrt((self.mesh.gridCC[:, 0])**2 +
                       (self.mesh.gridCC[:, 2] - self.z2)**2) <= self.R

        self.mapping = (Maps.InjectActiveCells(self.mesh,
                                               active,
                                               sig0,
                                               nC=self.mesh.nC))
        model = np.ones(self.mesh.nC) * sigb
        model[ind1] = sig1
        model[ind2] = sig2
        self.m = model[active]
        self.mu = np.ones(self.mesh.nC) * mu_0
        self.mu[self.mesh.gridCC[:, 2] < 0.] = (1. + chi) * mu_0
        return self.m
def setUp_TDEM(prbtype='b', rxcomp='bz'):
    cs = 5.
    ncx = 20
    ncy = 15
    npad = 20
    hx = [(cs, ncx), (cs, npad, 1.3)]
    hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
    mesh = Mesh.CylMesh([hx, 1, hy], '00C')
    #
    active = mesh.vectorCCz < 0.
    activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
    mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap

    rxOffset = 10.
    rx = EM.TDEM.Rx(np.array([[rxOffset, 0., -1e-2]]), np.logspace(-4, -3, 20),
                    rxcomp)
    src = EM.TDEM.Src.MagDipole([rx], loc=np.array([0., 0., 0.]))

    survey = EM.TDEM.Survey([src])

    if prbtype == 'b':
        prb = EM.TDEM.Problem3D_b(mesh, mapping=mapping)
    elif prbtype == 'e':
        prb = EM.TDEM.Problem3D_e(mesh, mapping=mapping)

    prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)]
    # prb.timeSteps = [(1e-05, 10), (1e-05, 50), (1e-05, 50) ] #, (2.5e-4, 10)]

    prb.Solver = Solver

    m = (np.log(1e-1) * np.ones(prb.mapping.nP) +
         1e-3 * np.random.randn(prb.mapping.nP))

    prb.pair(survey)
    mesh = mesh

    return prb, m, mesh
Example #25
0
def getProb(meshType='CYL', rxTypes='bx,bz', nSrc=1):
    cs = 5.
    ncx = 20
    ncy = 6
    npad = 20
    hx = [(cs, ncx), (cs, npad, 1.3)]
    hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
    mesh = Mesh.CylMesh([hx, 1, hy], '00C')

    active = mesh.vectorCCz < 0.
    activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
    mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap

    rxOffset = 40.

    srcs = []
    for ii in range(nSrc):
        rxs = [
            EM.TDEM.RxTDEM(np.array([[rxOffset, 0., 0.]]),
                           np.logspace(-4, -3, 20 + ii), rxType)
            for rxType in rxTypes.split(',')
        ]
        srcs += [EM.TDEM.SrcTDEM_VMD_MVP(rxs, np.array([0., 0., 0.]))]

    survey = EM.TDEM.SurveyTDEM(srcs)

    prb = EM.TDEM.ProblemTDEM_b(mesh, mapping=mapping)
    # prb.timeSteps = [1e-5]
    prb.timeSteps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)]
    # prb.timeSteps = [(1e-05, 100)]

    try:
        from pymatsolver import MumpsSolver
        prb.Solver = MumpsSolver
    except ImportError, e:
        prb.Solver = SolverLU
def run(runIt=False, plotIt=True, saveIt=False, saveFig=False, cleanup=True):
    """
    Run the bookpurnong 1D stitched RESOLVE inversions.

    :param bool runIt: re-run the inversions? Default downloads and plots saved results
    :param bool plotIt: show the plots?
    :param bool saveIt: save the re-inverted results?
    :param bool saveFig: save the figure
    :param bool cleanup: remove the downloaded results
    """

    # download the data
    downloads, directory = download_and_unzip_data()

    # Load resolve data
    resolve = h5py.File(os.path.sep.join([directory, "booky_resolve.hdf5"]),
                        "r")

    river_path = resolve["river_path"][()]  # River path
    nSounding = resolve["data"].shape[0]  # the # of soundings

    # Bird height from surface
    b_height_resolve = resolve["src_elevation"][()]

    # fetch the frequencies we are considering
    cpi_inds = [0, 2, 6, 8, 10]  # Indices for HCP in-phase
    cpq_inds = [1, 3, 7, 9, 11]  # Indices for HCP quadrature
    frequency_cp = resolve["frequency_cp"][()]

    # build a mesh
    cs, ncx, ncz, npad = 1., 10., 10., 20
    hx = [(cs, ncx), (cs, npad, 1.3)]
    npad = 12
    temp = np.logspace(np.log10(1.), np.log10(12.), 19)
    temp_pad = temp[-1] * 1.3**np.arange(npad)
    hz = np.r_[temp_pad[::-1], temp[::-1], temp, temp_pad]
    mesh = Mesh.CylMesh([hx, 1, hz], '00C')
    active = mesh.vectorCCz < 0.

    # survey parameters
    rxOffset = 7.86  # tx-rx separation
    bp = -mu_0 / (4 * np.pi * rxOffset**3)  # primary magnetic field

    # re-run the inversion
    if runIt:

        # set up the mappings - we are inverting for 1D log conductivity
        # below the earth's surface.
        actMap = Maps.InjectActiveCells(mesh,
                                        active,
                                        np.log(1e-8),
                                        nC=mesh.nCz)
        mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * actMap

        # build starting and reference model
        sig_half = 1e-1
        sig_air = 1e-8
        sigma = np.ones(mesh.nCz) * sig_air
        sigma[active] = sig_half
        m0 = np.log(1e-1) * np.ones(active.sum())  # starting model
        mref = np.log(1e-1) * np.ones(active.sum())  # reference model

        # initalize empty lists for storing inversion results
        mopt_re = []  # recovered model
        dpred_re = []  # predicted data
        dobs_re = []  # observed data

        # downsample the data for the inversion
        nskip = 40

        # set up a noise model
        # 10% for the 3 lowest frequencies, 15% for the two highest
        std = np.repeat(np.r_[np.ones(3) * 0.1, np.ones(2) * 0.15], 2)
        floor = abs(20 * bp * 1e-6)  # floor of 20ppm

        # loop over the soundings and invert each
        for rxind in range(nSounding):

            # convert data from ppm to magnetic field (A/m^2)
            dobs = np.c_[resolve["data"][rxind, :][cpi_inds].astype(float),
                         resolve["data"][rxind, :][cpq_inds].
                         astype(float)].flatten() * bp * 1e-6

            # perform the inversion
            src_height = b_height_resolve[rxind].astype(float)
            mopt, dpred, dobs = resolve_1Dinversions(mesh,
                                                     dobs,
                                                     src_height,
                                                     frequency_cp,
                                                     m0,
                                                     mref,
                                                     mapping,
                                                     std=std,
                                                     floor=floor)

            # add results to our list
            mopt_re.append(mopt)
            dpred_re.append(dpred)
            dobs_re.append(dobs)

        # save results
        mopt_re = np.vstack(mopt_re)
        dpred_re = np.vstack(dpred_re)
        dobs_re = np.vstack(dobs_re)

        if saveIt:
            np.save("mopt_re_final", mopt_re)
            np.save("dobs_re_final", dobs_re)
            np.save("dpred_re_final", dpred_re)

    mopt_re = resolve["mopt"][()]
    dobs_re = resolve["dobs"][()]
    dpred_re = resolve["dpred"][()]

    sigma = np.exp(mopt_re)
    indz = -7  # depth index

    # so that we can visually compare with literature (eg Viezzoli, 2010)
    cmap = "jet"

    # dummy figure for colobar
    fig = plt.figure()
    out = plt.scatter(np.ones(3),
                      np.ones(3),
                      c=np.linspace(-2, 1, 3),
                      cmap=cmap)
    plt.close(fig)

    # plot from the paper
    fs = 13  # fontsize
    # matplotlib.rcParams['font.size'] = fs
    plt.figure(figsize=(13, 7))
    ax0 = plt.subplot2grid((2, 3), (0, 0), rowspan=2, colspan=2)
    ax1 = plt.subplot2grid((2, 3), (0, 2))
    ax2 = plt.subplot2grid((2, 3), (1, 2))

    # titles of plots
    title = [("(a) Recovered model, %.1f m depth") %
             (-mesh.vectorCCz[active][indz]), "(b) Obs (Real 400 Hz)",
             "(c) Pred (Real 400 Hz)"]

    temp = sigma[:, indz]
    tree = cKDTree(list(zip(resolve["xy"][:, 0], resolve["xy"][:, 1])))
    d, d_inds = tree.query(list(zip(resolve["xy"][:, 0], resolve["xy"][:, 1])),
                           k=20)
    w = 1. / (d + 100.)**2.
    w = Utils.sdiag(1. / np.sum(w, axis=1)) * (w)
    xy = resolve["xy"]
    temp = (temp.flatten()[d_inds] * w).sum(axis=1)
    Utils.plot2Ddata(xy,
                     temp,
                     ncontour=100,
                     scale="log",
                     dataloc=False,
                     contourOpts={
                         "cmap": cmap,
                         "vmin": 1e-2,
                         "vmax": 1e1
                     },
                     ax=ax0)
    ax0.plot(resolve["xy"][:, 0], resolve["xy"][:, 1], 'k.', alpha=0.02, ms=1)

    cb = plt.colorbar(out,
                      ax=ax0,
                      ticks=np.linspace(-2, 1, 4),
                      format="$10^{%.1f}$")
    cb.set_ticklabels(["0.01", "0.1", "1", "10"])
    cb.set_label("Conductivity (S/m)")
    ax0.plot(river_path[:, 0], river_path[:, 1], 'k-', lw=0.5)

    # plot observed and predicted data
    freq_ind = 0
    axs = [ax1, ax2]
    temp_dobs = dobs_re[:, freq_ind].copy()
    ax1.plot(river_path[:, 0], river_path[:, 1], 'k-', lw=0.5)
    out = Utils.plot2Ddata(resolve["xy"][()],
                           temp_dobs / abs(bp) * 1e6,
                           ncontour=100,
                           scale="log",
                           dataloc=False,
                           ax=ax1,
                           contourOpts={"cmap": "viridis"})
    vmin, vmax = out[0].get_clim()
    cb = plt.colorbar(out[0],
                      ticks=np.linspace(vmin, vmax, 3),
                      ax=ax1,
                      format="%.1e",
                      fraction=0.046,
                      pad=0.04)
    cb.set_label("Bz (ppm)")
    temp_dpred = dpred_re[:, freq_ind].copy()
    # temp_dpred[mask_:_data] = np.nan
    ax2.plot(river_path[:, 0], river_path[:, 1], 'k-', lw=0.5)
    Utils.plot2Ddata(resolve["xy"][()],
                     temp_dpred / abs(bp) * 1e6,
                     ncontour=100,
                     scale="log",
                     dataloc=False,
                     contourOpts={
                         "vmin": 10**vmin,
                         "vmax": 10**vmax,
                         "cmap": "viridis"
                     },
                     ax=ax2)
    cb = plt.colorbar(out[0],
                      ticks=np.linspace(vmin, vmax, 3),
                      ax=ax2,
                      format="%.1e",
                      fraction=0.046,
                      pad=0.04)
    cb.set_label("Bz (ppm)")

    for i, ax in enumerate([ax0, ax1, ax2]):
        xticks = [460000, 463000]
        yticks = [6195000, 6198000, 6201000]
        xloc, yloc = 462100.0, 6196500.0
        ax.set_xticks(xticks)
        ax.set_yticks(yticks)
        # ax.plot(xloc, yloc, 'wo')
        ax.plot(river_path[:, 0], river_path[:, 1], 'k', lw=0.5)

        ax.set_aspect("equal")
        ax.plot(resolve["xy"][:, 0],
                resolve["xy"][:, 1],
                'k.',
                alpha=0.02,
                ms=1)

        ax.set_yticklabels([str(f) for f in yticks])
        ax.set_ylabel("Northing (m)")
        ax.set_xlabel("Easting (m)")
        ax.set_title(title[i])

    plt.tight_layout()

    if plotIt:
        plt.show()

    if saveFig is True:
        fig.savefig("obspred_resolve.png", dpi=200)

    resolve.close()
    if cleanup:
        os.remove(downloads)
        shutil.rmtree(directory)
Example #27
0
# Get the indicies of the magnetized block
ind = Utils.ModelBuilder.getIndicesBlock(
    np.r_[-20, -20, -10],
    np.r_[20, 20, 25],
    mesh.gridCC,
)[0]

# Assign magnetization values
model[ind, :] = np.kron(np.ones((ind.shape[0], 1)), M_xyz * 0.05)

# Remove air cells
model = model[actv, :]

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

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

# Create the forward model operator
prob = PF.Magnetics.MagneticIntegral(mesh,
                                     chiMap=idenMap,
                                     actInd=actv,
                                     modelType='vector')

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

# Compute some data and add some random noise
data = prob.fields(Utils.mkvc(model))
Example #28
0
    def setUp(self):

        np.random.seed(0)

        # Define the inducing field parameter
        H0 = (50000, 90, 0)

        # Create a mesh
        dx = 5.

        hxind = [(dx, 5, -1.3), (dx, 5), (dx, 5, 1.3)]
        hyind = [(dx, 5, -1.3), (dx, 5), (dx, 5, 1.3)]
        hzind = [(dx, 5, -1.3), (dx, 6)]

        mesh = Mesh.TensorMesh([hxind, hyind, hzind], 'CCC')

        # Get index of the center
        midx = int(mesh.nCx / 2)
        midy = int(mesh.nCy / 2)

        # Lets create a simple Gaussian topo and set the active cells
        [xx, yy] = np.meshgrid(mesh.vectorNx, mesh.vectorNy)
        zz = -np.exp((xx**2 + yy**2) / 75**2) + mesh.vectorNz[-1]

        # Go from topo to actv cells
        topo = np.c_[Utils.mkvc(xx), Utils.mkvc(yy), Utils.mkvc(zz)]
        actv = Utils.surface2ind_topo(mesh, topo, 'N')
        actv = np.asarray([inds for inds, elem in enumerate(actv, 1) if elem],
                          dtype=int) - 1

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

        # Create and array of observation points
        xr = np.linspace(-20., 20., 20)
        yr = np.linspace(-20., 20., 20)
        X, Y = np.meshgrid(xr, yr)

        # Move the observation points 5m above the topo
        Z = -np.exp((X**2 + Y**2) / 75**2) + mesh.vectorNz[-1] + 5.

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

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

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

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

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

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

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

        # Add noise and uncertainties (1nT)
        data = d + np.random.randn(len(d))
        wd = np.ones(len(data)) * 1.

        survey.dobs = data
        survey.std = wd

        # Create sensitivity weights from our linear forward operator
        wr = np.sum(prob.G**2., axis=0)**0.5
        wr = (wr / np.max(wr))

        # Create a regularization
        reg = Regularization.Sparse(mesh, indActive=actv, mapping=idenMap)
        reg.cell_weights = wr
        reg.norms = np.c_[0, 0, 0, 0]
        reg.gradientType = 'component'
        # reg.eps_p, reg.eps_q = 1e-3, 1e-3

        # Data misfit function
        dmis = DataMisfit.l2_DataMisfit(survey)
        dmis.W = 1 / wd

        # Add directives to the inversion
        opt = Optimization.ProjectedGNCG(maxIter=100,
                                         lower=0.,
                                         upper=1.,
                                         maxIterLS=20,
                                         maxIterCG=10,
                                         tolCG=1e-3)

        invProb = InvProblem.BaseInvProblem(dmis, reg, opt)
        betaest = Directives.BetaEstimate_ByEig()

        # Here is where the norms are applied
        IRLS = Directives.Update_IRLS(f_min_change=1e-4, minGNiter=1)
        update_Jacobi = Directives.UpdatePreconditioner()
        self.inv = Inversion.BaseInversion(
            invProb, directiveList=[IRLS, betaest, update_Jacobi])
Example #29
0
import os
cur_dir = "D:/Seogi/Dropbox/Researches/AEM_workshow_2018_simpeg/2d_inv_warm_start"
os.chdir(cur_dir)
cs, ncx, ncy, ncz, = 50., 20, 1, 20
npad_x, npad_y, npad_z = 10, 10, 10
pad_rate = 1.3
hx = [(cs, npad_x, -pad_rate), (cs, ncx), (cs, npad_x, pad_rate)]
hy = [(cs, npad_y, -pad_rate), (cs, ncy), (cs, npad_y, pad_rate)]
hz = [(cs, npad_z, -pad_rate), (cs, ncz), (cs, npad_z, pad_rate)]
mesh_3d = Mesh.TensorMesh([hx, hy, hz], 'CCC')
mesh_2d = Mesh.TensorMesh([hx, hz], 'CC')
actind = mesh_2d.gridCC[:, 1] < 0.
map_2Dto3D = Maps.Surject2Dto3D(mesh_3d)
expmap = Maps.ExpMap(mesh_2d)
actmap = Maps.InjectActiveCells(mesh_2d,
                                indActive=actind,
                                valInactive=np.log(1e-8))
mapping = map_2Dto3D * expmap * actmap

x = mesh_3d.vectorCCx[np.logical_and(mesh_3d.vectorCCx > -450,
                                     mesh_3d.vectorCCx < 450)]
time = np.logspace(np.log10(5e-5), np.log10(2.5e-3), 21)
ind_start = 19
dobs = np.load('../dobs.npy')
DOBS = dobs.reshape((x.size, 2, time.size))[:, :, ind_start:]
dobs_dbdtz = DOBS[:, 0, :].flatten()
dobs_dbdtx = DOBS[:, 1, :].flatten()
#%%
import os
model = []
for File in os.listdir("."):
Example #30
0
zmin, zmax = 0, 0
endl = np.array([[xmin, ymin, zmin], [xmax, ymax, zmax]])
survey3 = DCUtils.gen_DCIPsurvey(endl,
                                 "dipole-dipole",
                                 dim=mesh.dim,
                                 a=3,
                                 b=3,
                                 n=8)

# Concatenate lines
survey = DC.Survey(survey1.srcList + survey2.srcList + survey3.srcList)

# Setup Problem with exponential mapping and Active cells only in the core mesh
expmap = Maps.ExpMap(mesh)
mapactive = Maps.InjectActiveCells(mesh=mesh,
                                   indActive=actind,
                                   valInactive=-5.)
mapping = expmap * mapactive
problem = DC.Problem3D_CC(mesh, sigmaMap=mapping)
problem.pair(survey)
problem.Solver = Solver

survey.dpred(mtrue[actind])
survey.makeSyntheticData(mtrue[actind], std=0.05, force=True)

# Tikhonov Inversion
####################

# Initial Model
m0 = np.median(ln_sigback) * np.ones(mapping.nP)
# Data Misfit