def __compute_jacobian(self, mesh: pg.Mesh, res: np.ndarray,
                           scheme: pb.DataContainerERT):
        """ Computes the Jacobian (sensitivity) matrix.

        Computes the Jacobian (sensitivity) matrix based on a given mesh with resistivities and a set of electrode configurations.

        Parameter:
            mesh: The mesh used as approximate subsurface model.
            res: The resistivity vector containing the resistivities for the mesh cells
            scheme: The electrode configuration scheme for sensitivity calculation

        Returns:
            The Jacobian matrix as numpy matrix
        """
        ert = pb.ERTManager()
        # Simulate data for brute-force sensitivity calculation
        logging.info('Simulating data...')
        data = ert.simulate(mesh=mesh,
                            res=res,
                            scheme=scheme,
                            verbose=False,
                            noiseLevel=0,
                            noiseAbs=0)
        data.markInvalid(data('rhoa') < 0)
        data.removeInvalid()
        # Set essential data for Jacobian computation
        ert = pb.ERTManager()
        ert.setMesh(mesh, omitBackground=True)
        ert.setData(data)
        # Compute Jacobian matrix
        logging.info('Create Jacobian...')
        ert.fop.createJacobian(res)
        return pg.utils.base.gmat2numpy(ert.fop.jacobian())
Exemplo n.º 2
0
def simulate(meshERT, resBulk, ertScheme, fName):
    import pybert as pb
    import numpy as np

    ert = pb.ERTManager(debug=True)
    print('#############################')
    print('Forward Modelling...')

    # Set geometric factors to one, so that rhoa = r
    #    ertScheme.set('k', pb.geometricFactor(ertScheme))
    ertScheme.set('k', np.ones(ertScheme.size()))

    simdata = ert.simulate(mesh=meshERT,
                           res=resBulk,
                           scheme=ertScheme,
                           noiseAbs=0.0,
                           noiseLevel=0.01)
    simdata.set("r", simdata("rhoa"))

    # Calculate geometric factors for flat earth
    flat_earth_K = pb.geometricFactors(ertScheme)
    simdata.set("k", flat_earth_K)

    # Set output name
    dataName = fName[:-4] + '_data.ohm'
    simdata.save(dataName, "a b m n r err k")
    print('Done.')
    print(str('#############################'))
    #    pg.show(meshERT, resBulk)
    return simdata
    def __final_invert(self, folder):
        """ Inverts the synthetic dataset on the final mesh.

        Inverts the simulated, synthetic dataset created by __simulate(...). The final inversion mesh will be used
        instead of the default one.

        Parameter:
            folder: The folder in which the inversion result will be saved.
        """
        ert = pb.ERTManager()
        # Invert data on final grid
        self.__final_inv = ert.invert(
            data=self.__syndata,
            lam=self.__config.inv_final_lambda,
            mesh=self.__inv_final_mesh,
            verbose=self.__config.general_bert_verbose)
        # Save inversion results to file
        ert.saveResult(folder)
    def __invert(self, folder):
        """ Inverts the synthetic dataset.

        Inverts the simulated, synthetic dataset created by __simulate(...). The default inversion mesh will be used.

        Parameter:
            folder: The folder in which the inversion result will be saved.
        """
        ert = pb.ERTManager()
        # Invert data
        self.__inv = ert.invert(data=self.__syndata,
                                lam=self.__config.inv_lambda,
                                mesh=self.__inv_mesh,
                                verbose=self.__config.general_bert_verbose)
        # Save inversion results which are needed for further computations
        self.__fop = ert.fop
        self.__pd = ert.paraDomain
        # Save inversion results to file
        ert.saveResult(folder)
    def __simulate(self, folder):
        """ Simulates a measurement set.

        Creates a set of synthetic data based on world, noise and given electrode configurations.

        Parameter:
            folder: The folder in which the resulting syndata.dat will be saved.
        """
        ert = pb.ERTManager()
        # Simulate synthetic data using pybert
        self.__syndata = ert.simulate(
            mesh=self.__sim_mesh,
            res=self.__res,
            scheme=self.__scheme,
            verbose=self.__config.general_bert_verbose,
            noiseLevel=self.__config.sim_noise_level,
            noiseAbs=self.__config.sim_noise_abs)
        # Removing invalid data
        self.__syndata.markInvalid(self.__syndata('rhoa') < 0)
        self.__syndata.removeInvalid()
        # Saving dataset to file
        self.__syndata.save(folder + 'syndata.dat')
import pandas as pd
import pygimli as pg
import numpy as np
import workbook as w
import tkinter as tk
from tkinter import filedialog

print("pyGIMLI:", pg.__version__)
print("Pandas:", pd.__version__)
print("Numpy:", np.__version__)

tk.Tk().withdraw()
fNames = tk.filedialog.askopenfilenames()
print(fNames)

ert = pb.ERTManager(debug=True)

#fNames = [r"K:\results\QR_Quad_200md_10kCells_3MLpa_Mass.dat"]

dataDict, data, coords = w.loadData(fNames)
hull, bPoly = w.loadHull(r"K:\boundsXY_10kCells.mat")
nodes = w.loadNodes(r"K:\nodesXY.mat")
bPolyMesh = w.fillPoly(bPoly, coords, hull)  # Fill boundary mesh with nodes
w.checkMesh(bPolyMesh)  # Check each node has a value.
topoArray = w.getTopo(hull)  # Extract the topography from the concave hull
dMesh = w.makeDataMesh(coords, 0)  # Make a mesh using datapoints
ertScheme, meshERT = w.createArray(0, 600, 5, 'wa', topoArray, enlarge=1)

dInterpDict = {}
for d in dataDict.keys():
    print(d)
    world_72_dd.createNode(pos + pg.RVector3(0, -0.1))

mesh_72x1_dd = mt.createMesh(world_72_dd, quality=34)

#forward modelling

data_72x1_dd = pb.simulate(mesh_72x1_dd,
                           res=rhomap,
                           scheme=scheme72_dd,
                           noise=noise,
                           verbose=True)
#inversion

print('starting 72x1dd inversion')

ert_72x1_dd = pb.ERTManager(data_72x1_dd)

inversion_72x1_dd = ert_72x1_dd.invert(quality=quality,
                                       maxCellArea=0.3,
                                       robustData=robustData,
                                       lam=lam,
                                       paraDX=paraDX,
                                       verbose=True)

inversion_mesh_72x1_dd = ert_72x1_dd.paraDomain

print('interpolation of inversion data to grid')

#interpolation of inversion data to grid

nan = 99.9
        model_vector2.append(res_model[cell.id()])
    else:
        model_vector2.append(nan)

model_data2 = pb.pg.RVector(model_vector2)

#-------------------18x4 DIP-----------------------------------------

data_18x4_dip = pb.importData('D2_clean.bin')
data_18x4_dip.set('k', pb.geometricFactors(data_18x4_dip))
data_18x4_dip.set('rhoa',
                  data_18x4_dip('u') / data_18x4_dip('i') * data_18x4_dip('k'))

#INVERSION

ert_18x4_dip = pb.ERTManager(data_18x4_dip)
#inv_18x4_dip =ert_18x4_dip.invert(quality=quality, maxCellArea=maxCellArea, robustData=robustData, lam=lam,paraDX=paraDX)
inv_18x4_dip = ert_18x4_dip.invert()
inversion_mesh_18x4_dip = ert_18x4_dip.paraDomain

#interpolación de datos inversión campo a grid

nan = 99.9
inversion_vector_18x4_dip = []
for pos in grid.cellCenters():
    cell = inversion_mesh_18x4_dip.findCell(pos)
    if cell:
        inversion_vector_18x4_dip.append(inv_18x4_dip[cell.id()])
    else:
        inversion_vector_18x4_dip.append(nan)
scheme.set('m', [3, 2, 1])
scheme.set('n', [2, 3, 0])

for pos in scheme.sensorPositions():
    world.createNode(pos)
    # world.createNode(pos + pg.RVector3(0, -0.1))

mesh = mt.createMesh(world, quality=34)

rhomap = [
    [1, 99.595 + 8.987j],
    [2, 99.595 + 8.987j],
    [3, 59.595 + 8.987j],
]

ert = pb.ERTManager()
data = ert.simulate(mesh, res=rhomap, scheme=scheme, verbose=True)
rhoa = data.get('rhoa').array()
phia = data.get('phia').array()

# make sure all computed responses are equal, especially the first two, which
# only differ in the sign of their geometrical factor
np.testing.assert_allclose(rhoa, rhoa[0])
np.testing.assert_allclose(phia, phia[0])

# make sure the phases are positive (for positive input)
assert np.all(phia > 0)

# make sure rhoa is also positive
assert np.all(rhoa > 0)