예제 #1
0
    def test_mappings_and_cell_weights(self):
        mesh = discretize.TensorMesh([8, 7, 6])
        m = np.random.rand(2 * mesh.nC)
        v = np.random.rand(2 * mesh.nC)

        cell_weights = np.random.rand(mesh.nC)

        wires = maps.Wires(("sigma", mesh.nC), ("mu", mesh.nC))

        reg = regularization.SimpleSmall(mesh,
                                         mapping=wires.sigma,
                                         cell_weights=cell_weights)

        objfct = objective_function.L2ObjectiveFunction(W=utils.sdiag(
            np.sqrt(cell_weights)),
                                                        mapping=wires.sigma)

        self.assertTrue(reg(m) == objfct(m))
        self.assertTrue(np.all(reg.deriv(m) == objfct.deriv(m)))
        self.assertTrue(np.all(reg.deriv2(m, v=v) == objfct.deriv2(m, v=v)))
예제 #2
0
    def test_sum(self):
        M2 = discretize.TensorMesh([np.ones(10), np.ones(20)], "CC")
        block = maps.ParametricEllipsoid(M2) * maps.Projection(
            7, np.r_[1, 2, 3, 4, 5, 6])
        background = (maps.ExpMap(M2) * maps.SurjectFull(M2) *
                      maps.Projection(7, np.r_[0]))

        summap0 = maps.SumMap([block, background])
        summap1 = block + background

        m0 = np.hstack([
            np.random.rand(3),
            np.r_[M2.x0[0], 2 * M2.hx.min()],
            np.r_[M2.x0[1], 4 * M2.hy.min()],
        ])

        self.assertTrue(np.all(summap0 * m0 == summap1 * m0))

        self.assertTrue(summap0.test(m0))
        self.assertTrue(summap1.test(m0))
예제 #3
0
def setup1DSurvey(sigmaHalf, tD=False, structure=False):

    # Frequency
    nFreq = 33
    freqs = np.logspace(3, -3, nFreq)
    # Make the mesh
    ct = 5
    air = meshTensor([(ct, 25, 1.3)])
    # coreT0 = meshTensor([(ct,15,1.2)])
    # coreT1 = np.kron(meshTensor([(coreT0[-1],15,1.3)]),np.ones((7,)))
    core = np.concatenate((np.kron(meshTensor([(ct, 15, -1.2)]), np.ones(
        (10, ))), meshTensor([(ct, 20)])))
    bot = meshTensor([(core[0], 20, -1.3)])
    x0 = -np.array([np.sum(np.concatenate((core, bot)))])
    m1d = discretize.TensorMesh([np.concatenate((bot, core, air))], x0=x0)
    # Make the model
    sigma = np.zeros(m1d.nC) + sigmaHalf
    sigma[m1d.gridCC > 0] = 1e-8
    sigmaBack = sigma.copy()
    # Add structure
    if structure:
        shallow = (m1d.gridCC < -200) * (m1d.gridCC > -600)
        deep = (m1d.gridCC < -3000) * (m1d.gridCC > -5000)
        sigma[shallow] = 1
        sigma[deep] = 0.1

    rxList = []
    for rxType in ["z1d", "z1d"]:
        rxList.append(Point1DImpedance(mkvc(np.array([0.0]), 2).T, "real"))
        rxList.append(Point1DImpedance(mkvc(np.array([0.0]), 2).T, "imag"))
    # Source list
    srcList = []
    if tD:
        for freq in freqs:
            srcList.append(Planewave_xy_1DhomotD(rxList, freq))
    else:
        for freq in freqs:
            srcList.append(Planewave_xy_1Dprimary(rxList, freq))

    survey = Survey(srcList)
    return (survey, sigma, sigmaBack, m1d)
예제 #4
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 = discretize.TensorMesh([hx, hy], x0="CN")

        x = np.linspace(-200, 200.0, 20)
        M = utils.ndgrid(x - 12.5, np.r_[0.0])
        N = utils.ndgrid(x + 12.5, np.r_[0.0])
        A0loc = np.r_[-150, 0.0]
        A1loc = np.r_[-130, 0.0]
        B0loc = np.r_[-130, 0.0]
        B1loc = np.r_[-110, 0.0]

        rx = dc.Rx.Dipole(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)

        source_lists = [src0, src1]
        source_lists_ip = [src0_ip, src1_ip]
        surveyDC = dc.Survey([src0, src1])

        sigmaInf = np.ones(mesh.nC) * 1.0
        blkind = utils.model_builder.getIndicesSphere(np.r_[0, -150], 40,
                                                      mesh.gridCC)

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

        self.surveyDC = surveyDC
        self.mesh = mesh
        self.sigmaInf = sigmaInf
        self.sigma0 = sigma0
        self.source_lists = source_lists
        self.source_lists_ip = source_lists_ip
        self.eta = eta
예제 #5
0
    def setUp(self):

        np.random.seed(518936)

        # Create a cloud of  random points from a random gaussian mixture
        self.ndim = 2
        self.n_components = 3
        sigma = np.random.randn(self.n_components, self.ndim, self.ndim)
        sigma = np.c_[[sigma[i].dot(sigma[i].T) for i in range(sigma.shape[0])]]
        sigma[0] += np.eye(self.ndim)
        sigma[1] += np.eye(self.ndim) - 0.25 * np.eye(self.ndim).transpose((1, 0))
        self.sigma = sigma
        self.means = (
            np.abs(np.random.randn(self.n_components, self.ndim))
            * np.c_[[-100, 100], [100, 1], [-100, -100]].T
        )
        self.rv_list = [
            multivariate_normal(mean, sigma)
            for i, (mean, sigma) in enumerate(zip(self.means, self.sigma))
        ]
        proportions = np.round(np.abs(np.random.rand(self.n_components)), decimals=1)
        proportions = np.abs(np.random.rand(self.n_components))
        self.proportions = proportions / proportions.sum()
        nsample = 1000
        self.samples = np.concatenate(
            [
                rv.rvs(int(nsample * prp))
                for i, (rv, prp) in enumerate(zip(self.rv_list, self.proportions))
            ]
        )
        self.nsample = self.samples.shape[0]
        self.model = mkvc(self.samples)
        self.mesh = discretize.TensorMesh(
            [np.maximum(1e-1, np.random.randn(self.nsample) ** 2.0)]
        )
        self.wires = Wires(("s0", self.mesh.nC), ("s1", self.mesh.nC))
        self.cell_weights_list = [
            np.maximum(1e-1, np.random.randn(self.mesh.nC) ** 2.0),
            np.maximum(1e-1, np.random.randn(self.mesh.nC) ** 2.0),
        ]
        self.PlotIt = False
예제 #6
0
    def test_addition(self):
        mesh = discretize.TensorMesh([8, 7, 6])
        m = np.random.rand(mesh.nC)

        reg1 = regularization.Tikhonov(mesh)
        reg2 = regularization.Simple(mesh)

        reg_a = reg1 + reg2
        self.assertTrue(len(reg_a) == 2)
        self.assertTrue(reg1(m) + reg2(m) == reg_a(m))
        reg_a.test(eps=TOL)

        reg_b = 2 * reg1 + reg2
        self.assertTrue(len(reg_b) == 2)
        self.assertTrue(2 * reg1(m) + reg2(m) == reg_b(m))
        reg_b.test(eps=TOL)

        reg_c = reg1 + reg2 / 2
        self.assertTrue(len(reg_c) == 2)
        self.assertTrue(reg1(m) + 0.5 * reg2(m) == reg_c(m))
        reg_c.test(eps=TOL)
예제 #7
0
    def setUp(self):

        nC = 20
        M = discretize.TensorMesh([nC, nC])
        y = np.linspace(0.0, 1.0, nC // 2)
        rlocs = np.c_[y * 0 + M.vectorCCx[-1], y]
        rx = tomo.Rx(locations=rlocs)

        source_list = [
            tomo.Src(location=np.r_[M.vectorCCx[0], yi], receiver_list=[rx])
            for yi in y
        ]

        survey = tomo.Survey(source_list)
        problem = tomo.Simulation(M,
                                  survey=survey,
                                  slownessMap=maps.IdentityMap(M))

        self.M = M
        self.problem = problem
        self.survey = survey
예제 #8
0
    def setUp(self):
        mesh = discretize.TensorMesh([4, 4, 4])

        # Magnetic inducing field parameter (A,I,D)
        B = [50000, 90, 0]

        # Create a MAGsurvey
        rx = mag.Point(np.vstack([[0.25, 0.25, 0.25], [-0.25, -0.25, 0.25]]))
        srcField = mag.SourceField([rx], parameters=(B[0], B[1], B[2]))
        survey = mag.Survey(srcField)

        # Create the forward model operator
        sim = mag.Simulation3DIntegral(mesh,
                                       survey=survey,
                                       chiMap=maps.IdentityMap(mesh))

        # Compute forward model some data
        m = np.random.rand(mesh.nC)
        data = sim.make_synthetic_data(m, add_noise=True)

        reg = regularization.Sparse(mesh)
        reg.mref = np.zeros(mesh.nC)
        reg.norms = np.c_[0, 1, 1, 1]
        reg.eps_p, reg.eps_q = 1e-3, 1e-3

        # Data misfit function
        dmis = data_misfit.L2DataMisfit(data)
        dmis.W = 1.0 / data.relative_error

        # Add directives to the inversion
        opt = optimization.ProjectedGNCG(maxIter=2,
                                         lower=-10.0,
                                         upper=10.0,
                                         maxIterCG=2)

        invProb = inverse_problem.BaseInvProblem(dmis, reg, opt)

        self.mesh = mesh
        self.invProb = invProb
        self.sim = sim
예제 #9
0
    def setUp(self):
        mesh = discretize.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.0])
        srcLoc = np.r_[0, 0, 0.0]
        receiver_list0 = survey.BaseRx(XYZ)
        Src0 = survey.BaseSrc(receiver_list=[receiver_list0], location=srcLoc)
        receiver_list1 = survey.BaseRx(XYZ)
        Src1 = survey.BaseSrc(receiver_list=[receiver_list1], location=srcLoc)
        receiver_list2 = survey.BaseRx(XYZ)
        Src2 = survey.BaseSrc(receiver_list=[receiver_list2], location=srcLoc)
        receiver_list3 = survey.BaseRx(XYZ)
        Src3 = survey.BaseSrc(receiver_list=[receiver_list3], location=srcLoc)
        Src4 = survey.BaseSrc(
            receiver_list=[
                receiver_list0,
                receiver_list1,
                receiver_list2,
                receiver_list3,
            ],
            location=srcLoc,
        )
        source_list = [Src0, Src1, Src2, Src3, Src4]
        mysurvey = survey.BaseSurvey(source_list=source_list)
        sim = simulation.BaseTimeSimulation(mesh,
                                            time_steps=[(10.0, 3), (20.0, 2)],
                                            survey=mysurvey)

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

        self.F = fields.TimeFields(sim,
                                   knownFields={"b": "F"},
                                   aliasFields={"e": ["b", "E", alias]})
        self.Src0 = Src0
        self.Src1 = Src1
        self.mesh = mesh
        self.XYZ = XYZ
        self.simulation = sim
예제 #10
0
    def test_vangenuchten_k_m(self):
        mesh = discretize.TensorMesh([50])

        expmap = maps.ExpMap(nP=mesh.nC)
        idnmap = maps.IdentityMap(nP=mesh.nC)

        seeds = {
            "Ks":
            np.random.triangular(np.log(1e-7), np.log(1e-6), np.log(1e-5),
                                 mesh.nC),
            "I":
            np.random.rand(mesh.nC),
            "n":
            np.random.rand(mesh.nC) + 1,
            "alpha":
            np.random.rand(mesh.nC),
        }

        opts = [
            ("Ks", dict(KsMap=expmap), 1),
            ("I", dict(IMap=idnmap), 1),
            ("n", dict(nMap=idnmap), 1),
            ("alpha", dict(alphaMap=idnmap), 1),
        ]

        u = np.random.randn(mesh.nC)

        for name, opt, nM in opts:
            van = richards.empirical.Vangenuchten_k(mesh, **opt)

            x0 = np.concatenate([seeds[n] for n in name.split("-")])

            def fun(m):
                van.model = m
                return van(u), van.derivM(u)

            print("Vangenuchten_k test m deriv:  ", name)

            passed = checkDerivative(fun, x0, plotIt=False)
            self.assertTrue(passed, True)
예제 #11
0
 def setUp(self):
     mesh = discretize.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.0])
     srcLoc = np.r_[0, 0, 0.0]
     receiver_list0 = survey.BaseRx(XYZ)
     Src0 = survey.BaseSrc([receiver_list0], location=srcLoc)
     receiver_list1 = survey.BaseRx(XYZ)
     Src1 = survey.BaseSrc([receiver_list1], location=srcLoc)
     receiver_list2 = survey.BaseRx(XYZ)
     Src2 = survey.BaseSrc([receiver_list2], location=srcLoc)
     receiver_list3 = survey.BaseRx(XYZ)
     Src3 = survey.BaseSrc([receiver_list3], location=srcLoc)
     Src4 = survey.BaseSrc(
         [receiver_list0, receiver_list1, receiver_list2, receiver_list3],
         location=srcLoc,
     )
     source_list = [Src0, Src1, Src2, Src3, Src4]
     mysurvey = survey.BaseSurvey(source_list=source_list)
     self.D = data.Data(mysurvey)
예제 #12
0
    def test_faceDiv(self):

        hx, hy, hz = np.r_[1., 2, 3, 4], np.r_[5., 6, 7, 8], np.r_[9., 10, 11,
                                                                   12]
        M = discretize.TreeMesh([hx, hy, hz], levels=2)
        M.refine(lambda xc: 2)
        # M.plotGrid(showIt=True)
        Mr = discretize.TensorMesh([hx, hy, hz])
        self.assertEqual(M.nC, Mr.nC)
        self.assertEqual(M.nF, Mr.nF)
        self.assertEqual(M.nFx, Mr.nFx)
        self.assertEqual(M.nFy, Mr.nFy)
        self.assertEqual(M.nE, Mr.nE)
        self.assertEqual(M.nEx, Mr.nEx)
        self.assertEqual(M.nEy, Mr.nEy)

        self.assertTrue(np.allclose(Mr.area, M.permuteF * M.area))
        self.assertTrue(np.allclose(Mr.edge, M.permuteE * M.edge))
        self.assertTrue(np.allclose(Mr.vol, M.permuteCC * M.vol))

        A = Mr.faceDiv - M.permuteCC * M.faceDiv * M.permuteF.T
        self.assertTrue(np.allclose(A.data, 0))
예제 #13
0
    def test_invPropertyTensor3D(self):
        M = discretize.TensorMesh([6, 6, 6])
        a1 = np.random.rand(M.nC)
        a2 = np.random.rand(M.nC)
        a3 = np.random.rand(M.nC)
        a4 = np.random.rand(M.nC)
        a5 = np.random.rand(M.nC)
        a6 = np.random.rand(M.nC)
        prop1 = a1
        prop2 = np.c_[a1, a2, a3]
        prop3 = np.c_[a1, a2, a3, a4, a5, a6]

        for prop in [4, prop1, prop2, prop3]:
            b = invPropertyTensor(M, prop)
            A = makePropertyTensor(M, prop)
            B1 = makePropertyTensor(M, b)
            B2 = invPropertyTensor(M, prop, returnMatrix=True)

            Z = B1 * A - sp.identity(M.nC * 3)
            self.assertTrue(np.linalg.norm(Z.todense().ravel(), 2) < TOL)
            Z = B2 * A - sp.identity(M.nC * 3)
            self.assertTrue(np.linalg.norm(Z.todense().ravel(), 2) < TOL)
    def set_G(self, N=20, M=100, p=-0.25, q=0.25, j1=1, jn=60):
        """
        Parameters
        ----------
        N: # of data
        M: # of model parameters
        ...

        """
        self.N = N
        self.M = M
        self._mesh = discretize.TensorMesh([M])
        jk = np.linspace(j1, jn, N)
        self._G = np.zeros((N, self.mesh.nC), dtype=float, order="C")

        def g(k):
            return np.exp(p * jk[k] * self.mesh.vectorCCx) * np.cos(
                np.pi * q * jk[k] * self.mesh.vectorCCx)

        for i in range(N):
            self._G[i, :] = g(i) * self.mesh.hx
        self._jk = jk
예제 #15
0
    def test_mappings(self):
        mesh = discretize.TensorMesh([8, 7, 6])
        m = np.random.rand(2 * mesh.nC)

        wires = maps.Wires(("sigma", mesh.nC), ("mu", mesh.nC))

        for regType in ["Tikhonov", "Sparse", "Simple"]:
            reg1 = getattr(regularization, regType)(mesh, mapping=wires.sigma)
            reg2 = getattr(regularization, regType)(mesh, mapping=wires.mu)

            reg3 = reg1 + reg2

            self.assertTrue(reg1.nP == 2 * mesh.nC)
            self.assertTrue(reg2.nP == 2 * mesh.nC)
            self.assertTrue(reg3.nP == 2 * mesh.nC)

            print(reg3(m), reg1(m), reg2(m))
            self.assertTrue(reg3(m) == reg1(m) + reg2(m))

            reg1.test(eps=TOL)
            reg2.test(eps=TOL)
            reg3.test(eps=TOL)
예제 #16
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 = discretize.TensorMesh([hx, hy, hz], x0="CCN")

        x = mesh.vectorCCx[(mesh.vectorCCx > -80.0) & (mesh.vectorCCx < 80.0)]
        y = mesh.vectorCCy[(mesh.vectorCCy > -80.0) & (mesh.vectorCCy < 80.0)]
        Aloc = np.r_[-100.0, 0.0, 0.0]
        Bloc = np.r_[100.0, 0.0, 0.0]
        M = utils.ndgrid(x - 12.5, y, np.r_[0.0])
        N = utils.ndgrid(x + 12.5, y, np.r_[0.0])
        radius = 50.0
        xc = np.r_[0.0, 0.0, -100]
        blkind = utils.model_builder.getIndicesSphere(xc, radius, mesh.gridCC)
        sigmaInf = np.ones(mesh.nC) * 1e-2
        eta = np.zeros(mesh.nC)
        eta[blkind] = 0.1
        sigma0 = sigmaInf * (1.0 - eta)

        rx = dc.receivers.Dipole(M, N)
        src = dc.sources.Dipole([rx], Aloc, Bloc)
        survey_dc = dc.survey.Survey([src])

        rx_ip = dc.receivers.Dipole(M, N, data_type="apparent_chargeability")
        src_ip = dc.sources.Dipole([rx_ip], Aloc, Bloc)
        survey_ip = ip.Survey([src_ip])

        self.survey_dc = survey_dc
        self.survey_ip = survey_ip
        self.mesh = mesh
        self.sigmaInf = sigmaInf
        self.sigma0 = sigma0
        self.src = src
        self.eta = eta
    def test_tensor_to_tree_sub(self):
        h1 = np.ones(32)
        h2 = np.ones(16)

        h1s = [h1]
        h2s = [h2]
        insert_2 = [4]
        for i in range(1, 3):
            print(f"Tensor to smaller Tree {i+1}D: ", end="")
            h1s.append(h1)
            h2s.append(h2)
            insert_2.append(4)
            mesh1 = discretize.TensorMesh(h1s)
            mesh2 = discretize.TreeMesh(h2s)
            mesh2.insert_cells([insert_2], [4])

            in_put = np.random.rand(mesh1.nC)
            out_put = np.empty(mesh2.nC)
            # test the three ways of calling...
            out1 = volume_average(mesh1, mesh2, in_put, out_put)
            assert_array_equal(out1, out_put)

            out2 = volume_average(mesh1, mesh2, in_put)
            assert_allclose(out1, out2)

            Av = volume_average(mesh1, mesh2)
            out3 = Av @ in_put
            assert_allclose(out1, out3)

            # get cells in extent of smaller mesh
            cells = mesh1.gridCC < [16] * (i + 1)
            if i > 0:
                cells = np.all(cells, axis=1)

            vol1 = np.sum(mesh1.vol[cells] * in_put[cells])
            vol2 = np.sum(mesh2.vol * out3)
            print(vol1, vol2)
            self.assertAlmostEqual(vol1, vol2)
예제 #18
0
파일: test_Props.py 프로젝트: yjx520/simpeg
    def test_reciprocal_no_map(self):
        expMap = maps.ExpMap(discretize.TensorMesh((3,)))

        PM = ReciprocalExample()
        self.assertRaises(AttributeError, getattr, PM, "sigma")

        PM.sigmaMap = expMap
        # PM = pickle.loads(pickle.dumps(PM))
        PM.model = np.r_[1.0, 2.0, 3.0]
        assert np.all(PM.sigma == np.exp(np.r_[1.0, 2.0, 3.0]))
        assert np.all(PM.rho == 1.0 / np.exp(np.r_[1.0, 2.0, 3.0]))

        PM.rho = np.r_[1.0, 2.0, 3.0]
        assert PM.sigmaMap is None
        assert PM.sigmaDeriv == 0
        assert np.all(PM.sigma == 1.0 / np.r_[1.0, 2.0, 3.0])

        PM.sigmaMap = expMap
        assert len(PM.sigmaMap) == 1
        # PM = pickle.loads(pickle.dumps(PM))
        assert np.all(PM.rho == 1.0 / np.exp(np.r_[1.0, 2.0, 3.0]))
        assert np.all(PM.sigma == np.exp(np.r_[1.0, 2.0, 3.0]))
        assert isinstance(PM.sigmaDeriv.todense(), np.ndarray)
예제 #19
0
    def test_segmented_tree(self):

        hx = np.ones(16) * 1.0
        hy = np.ones(16) * 2.0
        hz = np.ones(16) * 3.0

        px = np.r_[0, 3, 5]
        py = np.r_[0, 3, 5]
        pz = np.r_[2.0, 3.0, 4.0]

        xorig = np.r_[0.0, 0.0, 0.0]

        tensor_mesh = discretize.TensorMesh((hx, hy, hz), x0=xorig)
        tree_mesh = discretize.TreeMesh((hx, hy, hz), x0=xorig)
        tree_mesh.refine(4)

        locs = np.c_[px, py, pz]
        out1 = segmented_line_current_source_term(tensor_mesh, locs)
        out2 = segmented_line_current_source_term(tree_mesh, locs)

        sort1 = np.lexsort(tensor_mesh.edges.T)
        sort2 = np.lexsort(tree_mesh.edges.T)
        np.testing.assert_allclose(out1[sort1], out2[sort2])
def doTestFace(h, rep, fast, meshType, invProp=False, invMat=False):
    if meshType == 'Curv':
        hRect = discretize.utils.exampleLrmGrid(h, 'rotate')
        mesh = discretize.CurvilinearMesh(hRect)
    elif meshType == 'Tree':
        mesh = discretize.TreeMesh(h, levels=3)
        mesh.refine(lambda xc: 3)
    elif meshType == 'Tensor':
        mesh = discretize.TensorMesh(h)
    v = np.random.rand(mesh.nF)
    sig = np.random.rand(1) if rep is 0 else np.random.rand(mesh.nC * rep)

    def fun(sig):
        M = mesh.getFaceInnerProduct(sig, invProp=invProp, invMat=invMat)
        Md = mesh.getFaceInnerProductDeriv(sig,
                                           invProp=invProp,
                                           invMat=invMat,
                                           doFast=fast)
        return M * v, Md(v)

    print(meshType, 'Face', h, rep, fast,
          ('harmonic' if invProp and invMat else 'standard'))
    return discretize.Tests.checkDerivative(fun, sig, num=5, plotIt=False)
예제 #21
0
    def setUp(self):
        aSpacing = 2.5
        nElecs = 5

        surveySize = nElecs * aSpacing - aSpacing
        cs = surveySize / nElecs / 4

        self.mesh = discretize.TensorMesh(
            [
                [(cs, 10, -1.3), (cs, surveySize / cs), (cs, 10, 1.3)],
                [(cs, 3, -1.3), (cs, 3, 1.3)],
                # [(cs, 5, -1.3), (cs, 10)]
            ],
            "CN",
        )

        survey_end_points = np.array([-surveySize / 2, surveySize / 2, 0, 0])

        source_list = generate_dcip_sources_line(
            "dipole-dipole", "volt", "2D", survey_end_points, 0.0, 5, 2.5
        )
        self.d_d_survey = dc.survey.Survey(source_list)

        source_list = generate_dcip_sources_line(
            "dipole-pole", "volt", "2D", survey_end_points, 0.0, 5, 2.5
        )
        self.d_p_survey = dc.survey.Survey(source_list)

        source_list = generate_dcip_sources_line(
            "pole-dipole", "volt", "2D", survey_end_points, 0.0, 5, 2.5
        )
        self.p_d_survey = dc.survey.Survey(source_list)

        source_list = generate_dcip_sources_line(
            "pole-pole", "volt", "2D", survey_end_points, 0.0, 5, 2.5
        )
        self.p_p_survey = dc.survey.Survey(source_list)
예제 #22
0
    def setUp(self):
        mesh = discretize.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.0])
        srcLoc = np.r_[0, 0, 0.0]
        receiver_list0 = survey.BaseRx(XYZ)
        Src0 = survey.BaseSrc([receiver_list0], location=srcLoc)

        receiver_list1 = survey.BaseRx(XYZ)
        Src1 = survey.BaseSrc([receiver_list1], location=srcLoc)

        receiver_list2 = survey.BaseRx(XYZ)
        Src2 = survey.BaseSrc([receiver_list2], location=srcLoc)

        receiver_list3 = survey.BaseRx(XYZ)
        Src3 = survey.BaseSrc([receiver_list3], location=srcLoc)
        Src4 = survey.BaseSrc(
            [receiver_list0, receiver_list1, receiver_list2, receiver_list3],
            location=srcLoc,
        )

        source_list = [Src0, Src1, Src2, Src3, Src4]
        mysurvey = survey.BaseSurvey(source_list=source_list)
        sim = simulation.BaseSimulation(mesh=mesh, survey=mysurvey)
        self.F = fields.Fields(
            sim,
            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
        self.simulation = sim
예제 #23
0
    def setUp(self):
        cs = 10.0
        ncx, ncy, ncz = 30.0, 30.0, 30.0
        npad = 10.0
        hx = [(cs, npad, -1.5), (cs, ncx), (cs, npad, 1.5)]
        hy = [(cs, npad, -1.5), (cs, ncy), (cs, npad, 1.5)]
        hz = [(cs, npad, -1.5), (cs, ncz), (cs, npad, 1.5)]
        self.mesh = discretize.TensorMesh([hx, hy, hz], "CCC")
        mapping = maps.ExpMap(self.mesh)

        self.frequency = 1.0

        self.prob_e = fdem.Simulation3DElectricField(self.mesh,
                                                     sigmaMap=mapping)
        self.prob_b = fdem.Simulation3DMagneticFluxDensity(self.mesh,
                                                           sigmaMap=mapping)
        self.prob_h = fdem.Simulation3DMagneticField(self.mesh,
                                                     sigmaMap=mapping)
        self.prob_j = fdem.Simulation3DCurrentDensity(self.mesh,
                                                      sigmaMap=mapping)

        loc = np.r_[0.0, 0.0, 0.0]
        self.location = utils.mkvc(
            self.mesh.gridCC[utils.closestPoints(self.mesh, loc, "CC"), :])
예제 #24
0
    def setUp(self):

        np.random.seed(518936)

        # Create a cloud of  random points from a random gaussian mixture
        self.ndim = 2
        self.n_components = 2
        sigma = np.random.randn(self.n_components, self.ndim, self.ndim)
        sigma = np.c_[[
            sigma[i].dot(sigma[i].T) for i in range(sigma.shape[0])
        ]]
        sigma[0] += np.eye(self.ndim)
        sigma[1] += np.eye(self.ndim) - 0.25 * np.eye(self.ndim).transpose(
            (1, 0))
        self.sigma = sigma
        self.means = (np.abs(np.random.randn(self.ndim, self.ndim)) *
                      np.c_[[100.0, -100.0]])
        self.rv0 = multivariate_normal(self.means[0], self.sigma[0])
        self.rv1 = multivariate_normal(self.means[1], self.sigma[1])
        self.proportions = np.r_[0.6, 0.4]
        self.nsample = 1000
        self.s0 = self.rv0.rvs(int(self.nsample * self.proportions[0]))
        self.s1 = self.rv1.rvs(int(self.nsample * self.proportions[1]))
        self.samples = np.r_[self.s0, self.s1]
        self.model = mkvc(self.samples)
        self.mesh = discretize.TensorMesh(
            [np.maximum(1e-1,
                        np.random.randn(self.nsample)**2.0)])
        self.wires = Wires(("s0", self.mesh.nC), ("s1", self.mesh.nC))
        self.cell_weights_list = [
            np.maximum(1e-1,
                       np.random.randn(self.mesh.nC)**2.0),
            np.maximum(1e-1,
                       np.random.randn(self.mesh.nC)**2.0),
        ]
        self.PlotIt = False
예제 #25
0
def run(plotIt=True):
    sz = [16, 16]
    tM = discretize.TensorMesh(sz)
    qM = discretize.TreeMesh(sz)

    def refine(cell):
        if np.sqrt(((np.r_[cell.center] - 0.5)**2).sum()) < 0.4:
            return 4
        return 3

    qM.refine(refine)
    rM = discretize.CurvilinearMesh(
        discretize.utils.exampleLrmGrid(sz, 'rotate'))

    if not plotIt:
        return
    fig, axes = plt.subplots(1, 3, figsize=(14, 5))
    opts = {}
    tM.plotGrid(ax=axes[0], **opts)
    axes[0].set_title('TensorMesh')
    qM.plotGrid(ax=axes[1], **opts)
    axes[1].set_title('TreeMesh')
    rM.plotGrid(ax=axes[2], **opts)
    axes[2].set_title('CurvilinearMesh')
예제 #26
0
    def setUp(self):
        mesh = self.get_mesh()
        params = richards.empirical.HaverkampParams().celia1990
        k_fun, theta_fun = richards.empirical.haverkamp(mesh, **params)

        self.setup_maps(mesh, k_fun, theta_fun)
        bc, h = self.get_conditions(mesh)

        time_steps = [(40, 3), (60, 3)]
        time_mesh = discretize.TensorMesh([time_steps])
        rx_list = self.get_rx_list(time_mesh.nodes_x)
        survey = richards.Survey(rx_list)

        prob = richards.SimulationNDCellCentered(
            mesh,
            survey=survey,
            hydraulic_conductivity=k_fun,
            water_retention=theta_fun,
            root_finder_tol=1e-6,
            debug=False,
            boundary_conditions=bc,
            initial_conditions=h,
            do_newton=False,
            method="mixed",
        )
        prob.time_steps = time_steps
        prob.solver = Solver

        self.h0 = h
        self.mesh = mesh
        self.Ks = params["Ks"] * np.ones(self.mesh.nC)
        self.A = params["A"] * np.ones(self.mesh.nC)
        self.theta_s = params["theta_s"] * np.ones(self.mesh.nC)
        self.prob = prob
        self.survey = survey
        self.setup_model()
예제 #27
0
def run(plotIt=True):
    M = discretize.TensorMesh([32, 32])
    v = discretize.utils.random_model(M.vnC, seed=789)
    v = discretize.utils.mkvc(v)

    O = discretize.TreeMesh([32, 32])

    def function(cell):
        if (cell.center[0] < 0.75 and cell.center[0] > 0.25
                and cell.center[1] < 0.75 and cell.center[1] > 0.25):
            return 5
        if (cell.center[0] < 0.9 and cell.center[0] > 0.1
                and cell.center[1] < 0.9 and cell.center[1] > 0.1):
            return 4
        return 3

    O.refine(function)

    P = M.getInterpolationMat(O.gridCC, 'CC')

    ov = P * v

    if not plotIt:
        return

    fig, axes = plt.subplots(1, 2, figsize=(10, 5))

    out = M.plotImage(v, grid=True, ax=axes[0])
    cb = plt.colorbar(out[0], ax=axes[0])
    cb.set_label("Random Field")
    axes[0].set_title('TensorMesh')

    out = O.plotImage(ov, grid=True, ax=axes[1], clim=[0, 1])
    cb = plt.colorbar(out[0], ax=axes[1])
    cb.set_label("Random Field")
    axes[1].set_title('TreeMesh')
예제 #28
0
def run(plotIt=True, n=60):

    np.random.seed(5)

    # Here we are going to rearrange the equations:

    # (phi_ - phi)/dt = A*(d2fdphi2*(phi_ - phi) + dfdphi - L*phi_)
    # (phi_ - phi)/dt = A*(d2fdphi2*phi_ - d2fdphi2*phi + dfdphi - L*phi_)
    # (phi_ - phi)/dt = A*d2fdphi2*phi_ + A*( - d2fdphi2*phi + dfdphi - L*phi_)
    # phi_ - phi = dt*A*d2fdphi2*phi_ + dt*A*(- d2fdphi2*phi + dfdphi - L*phi_)
    # phi_ - dt*A*d2fdphi2 * phi_ =  dt*A*(- d2fdphi2*phi + dfdphi - L*phi_) + phi
    # (I - dt*A*d2fdphi2) * phi_ =  dt*A*(- d2fdphi2*phi + dfdphi - L*phi_) + phi
    # (I - dt*A*d2fdphi2) * phi_ =  dt*A*dfdphi - dt*A*d2fdphi2*phi - dt*A*L*phi_ + phi
    # (dt*A*d2fdphi2 - I) * phi_ =  dt*A*d2fdphi2*phi + dt*A*L*phi_ - phi - dt*A*dfdphi
    # (dt*A*d2fdphi2 - I - dt*A*L) * phi_ =  (dt*A*d2fdphi2 - I)*phi - dt*A*dfdphi

    h = [(0.25, n)]
    M = discretize.TensorMesh([h, h])

    # Constants
    D = a = epsilon = 1.
    I = discretize.utils.speye(M.nC)

    # Operators
    A = D * M.faceDiv * M.cellGrad
    L = epsilon**2 * M.faceDiv * M.cellGrad

    duration = 75
    elapsed = 0.
    dexp = -5
    phi = np.random.normal(loc=0.5, scale=0.01, size=M.nC)
    ii, jj = 0, 0
    PHIS = []
    capture = np.logspace(-1, np.log10(duration), 8)
    while elapsed < duration:
        dt = min(100, np.exp(dexp))
        elapsed += dt
        dexp += 0.05

        dfdphi = a**2 * 2 * phi * (1 - phi) * (1 - 2 * phi)
        d2fdphi2 = discretize.utils.sdiag(a**2 * 2 * (1 - 6 * phi * (1 - phi)))

        MAT = (dt * A * d2fdphi2 - I - dt * A * L)
        rhs = (dt * A * d2fdphi2 - I) * phi - dt * A * dfdphi
        phi = Solver(MAT) * rhs

        if elapsed > capture[jj]:
            PHIS += [(elapsed, phi.copy())]
            jj += 1
        if ii % 10 == 0:
            print(ii, elapsed)
        ii += 1

    if plotIt:
        fig, axes = plt.subplots(2, 4, figsize=(14, 6))
        axes = np.array(axes).flatten().tolist()
        for ii, ax in zip(np.linspace(0, len(PHIS) - 1, len(axes)), axes):
            ii = int(ii)
            M.plotImage(PHIS[ii][1], ax=ax)
            ax.axis('off')
            ax.set_title('Elapsed Time: {0:4.1f}'.format(PHIS[ii][0]))
예제 #29
0
 def test_ParametricSplineMap(self):
     M2 = discretize.TensorMesh([np.ones(10), np.ones(10)], "CN")
     x = M2.vectorCCx
     mParamSpline = maps.ParametricSplineMap(M2, x, normal="Y", order=1)
     self.assertTrue(mParamSpline.test())
     self.assertTrue(mParamSpline.testVec())
예제 #30
0
 def test_ParametricPolyMap(self):
     M2 = discretize.TensorMesh([np.ones(10), np.ones(10)], "CN")
     mParamPoly = maps.ParametricPolyMap(M2, 2, logSigma=True, normal="Y")
     self.assertTrue(mParamPoly.test(m=np.r_[1.0, 1.0, 0.0, 0.0, 0.0]))
     self.assertTrue(mParamPoly.testVec(m=np.r_[1.0, 1.0, 0.0, 0.0, 0.0]))