Beispiel #1
0
    def test_e(self, theano_f_1f):
        """
        Two layers a bit curvy, 1 fault
        """


        # Importing the data from csv files and settign extent and resolution
        geo_data = gempy.create_data([0, 10, 0, 10, -10, 0], [50, 50, 50],
                                     path_o=input_path+"/GeoModeller/test_e/test_e_Foliations.csv",
                                     path_i=input_path+"/GeoModeller/test_e/test_e_Points.csv")

        gempy.set_series(geo_data, {'series': ('A', 'B'),
                                        'fault1': 'f1'}, order_series=['fault1', 'series'],
                                                         order_formations=['f1','A','B'],
                         verbose=0)

        interp_data = theano_f_1f

        # Updating the interp data which has theano compiled
        interp_data.update_interpolator(geo_data, u_grade=[1, 1])

        # Compute model
        sol = gempy.compute_model(interp_data)

        if False:
            np.save(input_path + '/test_e_sol.npy', sol)

        gempy.plot_section(geo_data, sol[0][0, :], 25, direction='y', plot_data=True)
        plt.savefig(os.path.dirname(__file__)+'/figs/test_e.png', dpi=200)

        # Load model
        real_sol = np.load(input_path + '/test_e_sol.npy')

        # We only compare the block because the absolute pot field I changed it
        np.testing.assert_array_almost_equal(np.round(sol[0][0, :]), real_sol[0][0, :], decimal=0)
Beispiel #2
0
    def test_a(self, theano_f):
        """
        2 Horizontal layers with drift one
        """

        data_interp = theano_f[0]
        compiled_f = theano_f[1]

        # Importing the data from csv files and settign extent and resolution
        geo_data = gempy.import_data([0, 10, 0, 10, -10, 0], [50, 50, 50],
                                     path_f="./GeoModeller/test_a/test_a_Foliations.csv",
                                     path_i="./GeoModeller/test_a/test_a_Points.csv")

        # rescaled_data = gempy.rescale_data(geo_data)
        #
        # data_interp.interpolator._data_scaled = rescaled_data
        # data_interp.interpolator._grid_scaled = rescaled_data.grid
        # data_interp.interpolator.order_table()
        # data_interp.interpolator.set_theano_shared_parameteres()
        #
        # # Prepare the input data (interfaces, foliations data) to call the theano function.
        # # Also set a few theano shared variables with the len of formations series and so on
        # input_data_P = data_interp.interpolator.data_prep(u_grade=[3])
        # # Compile the theano function.

        data_interp.set_interpolator(geo_data)

        i = data_interp.get_input_data(u_grade=[3])
        sol = compiled_f(*i)

        real_sol = np.load('test_a_sol.npy')
        np.testing.assert_array_almost_equal(sol[:, :2, :], real_sol, decimal=3)

        gempy.plot_section(geo_data, 25, block=sol[0, 0, :], direction='y', plot_data=True)
        gempy.plot_potential_field(geo_data, sol[0, 1, :], 25)
Beispiel #3
0
    def test_b(self, theano_f):
        """
        Two layers a bit curvy, drift degree 1
        """

        # Importing the data from csv files and settign extent and resolution
        geo_data = gempy.create_data([0, 10, 0, 10, -10, 0], [50, 50, 50],
                                     path_o=input_path+"/GeoModeller/test_b/test_b_Foliations.csv",
                                     path_i=input_path+"/GeoModeller/test_b/test_b_Points.csv")

        interp_data = theano_f

        # Updating the interp data which has theano compiled
        interp_data.update_interpolator(geo_data, u_grade=[1])

        gempy.get_kriging_parameters(interp_data, verbose=1)
        # Compute model
        sol = gempy.compute_model(interp_data)

        gempy.plot_section(geo_data, sol[0][0, :], 25, direction='y', plot_data=True)
        plt.savefig(os.path.dirname(__file__)+'/figs/test_b.png', dpi=200)

        if False:
            np.save(input_path + '/test_b_sol.npy', sol)

        # Load model
        real_sol = np.load(input_path + '/test_b_sol.npy')

        # Checking that the plots do not rise errors
        gempy.plot_section(geo_data, sol[0][0, :], 25, direction='y', plot_data=True)
        gempy.plot_scalar_field(geo_data, sol[0][1, :], 25)

        # We only compare the block because the absolute pot field I changed it
        np.testing.assert_array_almost_equal(np.round(sol[0][0, :]), real_sol[0][0, :], decimal=0)
Beispiel #4
0
    def gempy_model(value=0, input_data=input_data, verbose=True):

        # modify input data values accordingly
        interp_data.geo_data_res.interfaces[["X", "Y", "Z"]] = input_data[0]

        # Gx, Gy, Gz are just used for visualization. The theano function gets azimuth dip and polarity!!!
        interp_data.geo_data_res.orientations[[
            "G_x", "G_y", "G_z", "X", "Y", "Z", 'dip', 'azimuth', 'polarity'
        ]] = input_data[1]

        try:
            # try to compute model
            lb, fb = gp.compute_model(interp_data)
            if True:
                gp.plot_section(interp_data.geo_data_res,
                                lb[0],
                                0,
                                plot_data=True)

            return lb, fb

        except np.linalg.linalg.LinAlgError as err:
            # if it fails (e.g. some input data combinations could lead to
            # a singular matrix and thus break the chain) return an empty model
            # with same dimensions (just zeros)
            if verbose:
                print("Exception occured.")
            return np.zeros_like(lith_block), np.zeros_like(fault_block)
Beispiel #5
0
    def test_a(self, theano_f):
        """
        2 Horizontal layers with drift 0
        """
        # Importing the data from csv files and settign extent and resolution
        geo_data = gempy.create_data([0, 10, 0, 10, -10, 0], [50, 50, 50],
                                     path_o=os.path.dirname(__file__)+"/GeoModeller/test_a/test_a_Foliations.csv",
                                     path_i=os.path.dirname(__file__)+"/GeoModeller/test_a/test_a_Points.csv")

        interp_data = theano_f

        # Updating the interp data which has theano compiled

        interp_data.update_interpolator(geo_data)

        # Compute model
        sol = gempy.compute_model(interp_data, u_grade=[1])

        if False:
            np.save(os.path.dirname(__file__)+'/test_a_sol.npy', sol)

        # Load model
        real_sol = np.load(os.path.dirname(__file__)+'/test_a_sol.npy')

        # We only compare the block because the absolute pot field I changed it
        np.testing.assert_array_almost_equal(sol[0][0, :], real_sol[0][0, :], decimal=3)

        # Checking that the plots do not rise errors
        gempy.plot_section(geo_data, sol[0][0, :], 25, direction='y', plot_data=True)
        plt.savefig(os.path.dirname(__file__)+'/figs/test_a.png', dpi=100)

        gempy.plot_scalar_field(geo_data, sol[0][1, :], 25)
Beispiel #6
0
def test_ch2(theano_f):
    # Importing the data from csv files and settign extent and resolution
    geo_data = gp.create_data([696000,747000,6863000,6930000,-20000, 200], [50, 50, 50],
                             path_o=input_path+"/input_data/tut_SandStone/SandStone_Foliations.csv",
                             path_i=input_path+"/input_data/tut_SandStone/SandStone_Points.csv")


    gp.plotting.plot_data(geo_data, direction='z')

    # Assigning series to formations as well as their order (timewise)
    gp.set_series(geo_data, {"EarlyGranite_Series": 'EarlyGranite',
                             "BIF_Series":('SimpleMafic2', 'SimpleBIF'),
                                  "SimpleMafic_Series":'SimpleMafic1'},
                          order_series = ["EarlyGranite_Series",
                                          "BIF_Series",
                                          "SimpleMafic_Series"],
                          order_formations= ['EarlyGranite', 'SimpleMafic2', 'SimpleBIF', 'SimpleMafic1'],
                  verbose=1)


    # interp_data = gp.InterpolatorData(geo_data, theano_optimizer='fast_run',
    #                                   compile_theano=True, verbose=[])
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)


    lith_block, fault_block = gp.compute_model(interp_data)



    import matplotlib.pyplot as plt

    gp.plot_section(geo_data, lith_block[0], -2, plot_data=True, direction='z')
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)



    gp.plot_section(geo_data, lith_block[0],25, plot_data=True, direction='x')
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)


    # In[14]:


    gp.plot_scalar_field(geo_data, lith_block[1], 11, cmap='viridis', N=100)
    import matplotlib.pyplot as plt
    plt.colorbar(orientation='horizontal')


    vertices, simplices = gp.get_surfaces(interp_data, lith_block[1], None, original_scale=False)
    pyevtk = pytest.importorskip("pyevtk")
    gp.export_to_vtk(geo_data, path=os.path.dirname(__file__)+'/vtk_files', lith_block=lith_block[0], vertices=vertices, simplices=simplices)
Beispiel #7
0
    def test_f(self, theano_f_1f):
        """
        Two layers a bit curvy, 1 fault. Checked with geomodeller
        """

        # Importing the data from csv files and settign extent and resolution
        geo_data = gempy.create_data(
            [0, 2000, 0, 2000, -2000, 0], [50, 50, 50],
            path_o=input_path + "/GeoModeller/test_f/test_f_Foliations.csv",
            path_i=input_path + "/GeoModeller/test_f/test_f_Points.csv")

        gempy.set_series(geo_data, {
            'series':
            ('Reservoir', 'Seal', 'SecondaryReservoir', 'NonReservoirDeep'),
            'fault1':
            'MainFault'
        },
                         order_series=['fault1', 'series'],
                         order_formations=[
                             'MainFault', 'SecondaryReservoir', 'Seal',
                             'Reservoir', 'NonReservoirDeep'
                         ],
                         verbose=0)

        interp_data = theano_f_1f

        # Updating the interp data which has theano compiled
        interp_data.update_interpolator(geo_data, u_grade=[1, 1])

        # Compute model
        sol = gempy.compute_model(interp_data)

        if False:
            np.save(input_path + '/test_f_sol.npy', sol)

        real_sol = np.load(input_path + '/test_f_sol.npy')

        gempy.plot_section(geo_data,
                           sol[0][0, :],
                           25,
                           direction='y',
                           plot_data=True)

        plt.savefig(os.path.dirname(__file__) + '/figs/test_f.png', dpi=200)

        # We only compare the block because the absolute pot field I changed it
        np.testing.assert_array_almost_equal(np.round(sol[0][0, :]),
                                             real_sol[0][0, :],
                                             decimal=0)

        ver, sim = gempy.get_surfaces(interp_data,
                                      sol[0][1],
                                      sol[1][1],
                                      original_scale=True)
    def plot_section(self, iteration=1, block='lith', cell_number=3, **kwargs):
        '''kwargs: gempy.plotting.plot_section keyword arguments'''
        self._change_input_data(iteration)
        lith_block, fault_block = gp.compute_model(self.interp_data)

        if 'topography' not in kwargs:
            if self.topography:
                topography = self.topography
            else:
                topography = None
            if block == 'lith':
                gp.plot_section(self.geo_data,
                                lith_block[0],
                                cell_number=cell_number,
                                topography=topography,
                                **kwargs)
            else:
                gp.plot_section(self.geo_data,
                                block,
                                cell_number=cell_number,
                                topography=topography,
                                **kwargs)

        else:
            if block == 'lith':
                gp.plot_section(self.geo_data,
                                lith_block[0],
                                cell_number=cell_number,
                                **kwargs)
            else:
                gp.plot_section(self.geo_data,
                                block,
                                cell_number=cell_number,
                                **kwargs)
Beispiel #9
0
def test_ch6(theano_f_1f):

    # initialize geo_data object
    geo_data = gp.create_data([0, 3000, 0, 20, 0, 2000],
                              resolution=[50, 3, 67])
    # import data points
    geo_data.import_data_csv(
        input_path + "/input_data/tut_chapter6/ch6_data_interf.csv",
        input_path + "/input_data/tut_chapter6/ch6_data_fol.csv")

    gp.set_series(
        geo_data, {
            "fault":
            geo_data.get_formations()[np.where(
                geo_data.get_formations() == "Fault")[0][0]],
            "Rest":
            np.delete(geo_data.get_formations(),
                      np.where(geo_data.get_formations() == "Fault")[0][0])
        },
        order_series=["fault", "Rest"],
        verbose=0,
        order_formations=['Fault', 'Layer 2', 'Layer 3', 'Layer 4', 'Layer 5'])

    gp.plot_data(geo_data)
    plt.xlim(0, 3000)
    plt.ylim(0, 2000)

    interp_data = gp.InterpolatorData(geo_data, u_grade=[0, 1])
    lith_block, fault_block = gp.compute_model(interp_data)

    gp.plot_section(geo_data, lith_block[0], 0)

    G, centroids, labels_unique, lith_to_labels_lot, labels_to_lith_lot = gp.topology_compute(
        geo_data, lith_block[0], fault_block)

    gp.plot_section(geo_data, lith_block[0], 0, direction='y')
    gp.plot_topology(geo_data, G, centroids)

    lith_to_labels_lot["4"].keys()

    gp.topology.check_adjacency(G, 8, 3)

    G.adj[8]

    G.adj[8][2]["edge_type"]
Beispiel #10
0
def test_ch3_b(theano_f):

    geo_data = gp.read_pickle(os.path.dirname(__file__)+"/ch3-pymc2_tutorial_geo_data.pickle")

    # Check the stratigraphic pile for correctness:


    gp.get_sequential_pile(geo_data)


    # Then we can then compile the GemPy modeling function:


    #interp_data = gp.InterpolatorData(geo_data, u_grade=[1])
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)

    # Now we can reproduce the original model:



    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(geo_data, lith_block[0], 0)


    # But of course we want to look at the perturbation results. We have a class for that:

    import gempy.posterior_analysis

    dbname = os.path.dirname(__file__)+"/ch3-pymc2.hdf5"
    post = gempy.posterior_analysis.Posterior(dbname)



    post.change_input_data(interp_data, 80)


    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(interp_data.geo_data_res, lith_block[0], 2, plot_data=True)



    post.change_input_data(interp_data, 15)
    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(interp_data.geo_data_res, lith_block[0], 2, plot_data=True)

    post.change_input_data(interp_data, 95)
    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(geo_data, lith_block[0], 2)

    ver, sim = gp.get_surfaces(interp_data, lith_block[1], None, original_scale= True)
Beispiel #11
0
    def test_f(self, theano_f_1f):
        """
        Two layers a bit curvy, 1 fault. Checked with geomodeller
        """

        # Importing the data from csv files and settign extent and resolution
        geo_data = gempy.create_data([0, 2000, 0, 2000, -2000, 0], [50, 50, 50],
                                     path_o=input_path+"/GeoModeller/test_f/test_f_Foliations.csv",
                                     path_i=input_path+"/GeoModeller/test_f/test_f_Points.csv")

        gempy.set_series(geo_data, {'series': ('Reservoir',
                                               'Seal',
                                               'SecondaryReservoir',
                                               'NonReservoirDeep'
                                               ),
                                    'fault1': 'MainFault'},
                         order_series=['fault1', 'series'],
                         order_formations=['MainFault', 'SecondaryReservoir', 'Seal', 'Reservoir', 'NonReservoirDeep'],
                         verbose=0)

        interp_data = theano_f_1f

        # Updating the interp data which has theano compiled
        interp_data.update_interpolator(geo_data, u_grade=[1, 1])

        # Compute model
        sol = gempy.compute_model(interp_data)

        if False:
            np.save(input_path + '/test_f_sol.npy', sol)

        real_sol = np.load(input_path + '/test_f_sol.npy')

        gempy.plot_section(geo_data, sol[0][0, :], 25, direction='y', plot_data=True)

        plt.savefig(os.path.dirname(__file__)+'/figs/test_f.png', dpi=200)

        # We only compare the block because the absolute pot field I changed it
        np.testing.assert_array_almost_equal(np.round(sol[0][0, :]), real_sol[0][0, :], decimal=0)

        ver, sim = gempy.get_surfaces(interp_data, sol[0][1], sol[1][1], original_scale=True)
Beispiel #12
0
def test_ch6(theano_f_1f):


    # initialize geo_data object
    geo_data = gp.create_data([0, 3000, 0, 20, 0, 2000], resolution=[50, 3, 67])
    # import data points
    geo_data.import_data_csv(input_path+"/input_data/tut_chapter6/ch6_data_interf.csv",
                             input_path+"/input_data/tut_chapter6/ch6_data_fol.csv")


    gp.set_series(geo_data, {"fault":geo_data.get_formations()[np.where(geo_data.get_formations()=="Fault")[0][0]],
                             "Rest":np.delete(geo_data.get_formations(), np.where(geo_data.get_formations()=="Fault")[0][0])},
                               order_series = ["fault", "Rest"], verbose=0, order_formations=['Fault','Layer 2', 'Layer 3', 'Layer 4', 'Layer 5'])


    gp.plot_data(geo_data)
    plt.xlim(0,3000)
    plt.ylim(0,2000);

    interp_data = gp.InterpolatorData(geo_data, u_grade=[0,1])
    lith_block, fault_block = gp.compute_model(interp_data)

    gp.plot_section(geo_data, lith_block[0], 0)

    G, centroids, labels_unique, lith_to_labels_lot, labels_to_lith_lot = gp.topology_compute(
        geo_data, lith_block[0], fault_block)

    gp.plot_section(geo_data, lith_block[0], 0, direction='y')
    gp.plot_topology(geo_data, G, centroids)

    lith_to_labels_lot["4"].keys()

    gp.topology.check_adjacency(G, 8, 3)

    G.adj[8]

    G.adj[8][2]["edge_type"]
Beispiel #13
0
    def gempy_model(value=0,
                    input_data=input_data, verbose=True):

        # modify input data values accordingly
        interp_data.geo_data_res.interfaces[["X", "Y", "Z"]] = input_data[0]

        # Gx, Gy, Gz are just used for visualization. The theano function gets azimuth dip and polarity!!!
        interp_data.geo_data_res.orientations[["G_x", "G_y", "G_z", "X", "Y", "Z",  'dip', 'azimuth', 'polarity']] = input_data[1]

        try:
            # try to compute model
            lb, fb = gp.compute_model(interp_data)
            if True:
                gp.plot_section(interp_data.geo_data_res, lb[0], 0, plot_data=True)

            return lb, fb

        except np.linalg.linalg.LinAlgError as err:
            # if it fails (e.g. some input data combinations could lead to
            # a singular matrix and thus break the chain) return an empty model
            # with same dimensions (just zeros)
            if verbose:
                print("Exception occured.")
            return np.zeros_like(lith_block), np.zeros_like(fault_block)
Beispiel #14
0
def test_ch3_b(theano_f):

    geo_data = gp.read_pickle(
        os.path.dirname(__file__) + "/ch3-pymc2_tutorial_geo_data.pickle")

    # Check the stratigraphic pile for correctness:

    gp.get_sequential_pile(geo_data)

    # Then we can then compile the GemPy modeling function:

    #interp_data = gp.InterpolatorData(geo_data, u_grade=[1])
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)

    # Now we can reproduce the original model:

    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(geo_data, lith_block[0], 0)

    # But of course we want to look at the perturbation results. We have a class for that:

    import gempy.posterior_analysis

    dbname = os.path.dirname(__file__) + "/ch3-pymc2.hdf5"
    post = gempy.posterior_analysis.Posterior(dbname)

    post.change_input_data(interp_data, 80)

    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(interp_data.geo_data_res, lith_block[0], 2, plot_data=True)

    post.change_input_data(interp_data, 15)
    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(interp_data.geo_data_res, lith_block[0], 2, plot_data=True)

    post.change_input_data(interp_data, 95)
    lith_block, fault_block = gp.compute_model(interp_data)
    gp.plot_section(geo_data, lith_block[0], 2)

    ver, sim = gp.get_surfaces(interp_data,
                               lith_block[1],
                               None,
                               original_scale=True)
Beispiel #15
0
def test_ch3_a(theano_f):

    # set cube size and model extent
    cs = 50
    extent = (3000, 200, 2000)  # (x, y, z)
    res = (120, 4, 80)


    # initialize geo_data object
    geo_data = gp.create_data([0, extent[0],
                               0, extent[1],
                               0, extent[2]],
                              resolution=[res[0],  # number of voxels
                                          res[1],
                                          res[2]])

    geo_data.set_interfaces(pn.read_csv(input_path+"/input_data/tut_chapter3/tutorial_ch3_interfaces",
                                        index_col="Unnamed: 0"), append=True)
    geo_data.set_orientations(pn.read_csv(input_path+"/input_data/tut_chapter3/tutorial_ch3_foliations",
                                        index_col="Unnamed: 0"))

    # let's have a look at the upper five interface data entries in the dataframe
    gp.get_data(geo_data, 'interfaces', verbosity=1).head()

    # Original pile
    gp.get_sequential_pile(geo_data)

    # Ordered pile
    gp.set_order_formations(geo_data, ['Layer 2', 'Layer 3', 'Layer 4','Layer 5'])
    gp.get_sequential_pile(geo_data)

    # and at all of the foliation data
    gp.get_data(geo_data, 'orientations', verbosity=0)

    gp.plot_data(geo_data, direction="y")
    plt.xlim(0,3000)
    plt.ylim(0,2000);

    gp.data_to_pickle(geo_data, os.path.dirname(__file__)+"/ch3-pymc2_tutorial_geo_data")

    #interp_data = gp.InterpolatorData(geo_data, u_grade=[1], compile_theano=True)
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)

    # Afterwards we can compute the geological model
    lith_block, fault_block = gp.compute_model(interp_data)


    # And plot a section:
    gp.plot_section(geo_data, lith_block[0], 2, plot_data = True)

    import pymc

    # Checkpoint in case you did not execute the cells above
    geo_data = gp.read_pickle(os.path.dirname(__file__)+"/ch3-pymc2_tutorial_geo_data.pickle")

    gp.get_data(geo_data, 'orientations', verbosity=1).head()

    # So let's assume the vertical location of our layer interfaces is uncertain, and we want to represent this
    #  uncertainty by using a normal distribution. To define a normal distribution, we need a mean and a measure
    #  of deviation (e.g. standard deviation). For convenience the input data is already grouped by a "group_id" value,
    # which allows us to collectively modify data that belongs together. In this example we want to treat the vertical
    # position of each layer interface, on each side of the anticline, as uncertain. Therefore, we want to perturbate
    # the respective three points on each side of the anticline collectively.

    # These are our unique group id's, the number representing the layer, and a/b the side of the anticline.

    group_ids = geo_data.interfaces["group_id"].dropna().unique()
    print(group_ids)


    # As a reminder, GemPy stores data in two main objects, an InputData object (called geo_data in the tutorials) and
    # a InpterpolatorInput object (interp_data) in tutorials. geo_data contains the original data while interp_data the
    # data prepared (and compiled) to compute the 3D model.
    #
    # Since we do not want to compile our code at every new stochastic realization, from here on we will need to work
    # with thte interp_data. And remember that to improve float32 to stability we need to work with rescaled data
    # (between 0 and 1). Therefore all the stochastic data needs to be rescaled accordingly. The object interp_data
    #  contains a property with the rescale factor (see below. As default depends on the model extent), or it is
    # possible to add the stochastic data to the pandas dataframe of the geo_data---when the InterpolatorInput object
    # is created the rescaling happens under the hood.

    interface_Z_modifier = []

    # We rescale the standard deviation
    std = 20./interp_data.rescaling_factor

    # loop over the unique group id's and create a pymc.Normal distribution for each
    for gID in group_ids:
        stoch = pymc.Normal(gID+'_stoch', 0, 1./std**2)
        interface_Z_modifier.append(stoch)

    # Let's have a look at one:


    # sample from a distribtion
    samples = [interface_Z_modifier[3].rand() for i in range(10000)]
    # plot histogram
    plt.hist(samples, bins=24, normed=True);
    plt.xlabel("Z modifier")
    plt.vlines(0, 0, 0.01)
    plt.ylabel("n");


    #  Now we need to somehow sample from these distribution and put them into GemPy

    # ## Input data handling
    #
    # First we need to write a function which modifies the input data for each iteration of the stochastic simulation.
    #  As this process is highly dependant on the simulation (e.g. what input parameters you want modified in which way),
    #  this process generally can't be automated.
    #
    # The idea is to change the column Z (in this case) of the rescaled dataframes in our interp_data object (which can
    #  be found in interp_data.geo_data_res). First we simply create the pandas Dataframes we are interested on:


    import copy
    # First we extract from our original intep_data object the numerical data that is necessary for the interpolation.
    # geo_data_stoch is a pandas Dataframe

    # This is the inital model so it has to be outside the stochastic frame
    geo_data_stoch_init = copy.deepcopy(interp_data.geo_data_res)

    gp.get_data(geo_data_stoch_init, numeric=True).head()

    @pymc.deterministic(trace=True)
    def input_data(value = 0,
                   interface_Z_modifier = interface_Z_modifier,
                   geo_data_stoch_init = geo_data_stoch_init,
                   verbose=0):
        # First we extract from our original intep_data object the numerical data that is necessary for the interpolation.
        # geo_data_stoch is a pandas Dataframe

        geo_data_stoch = gp.get_data(geo_data_stoch_init, numeric=True)
        # Now we loop each id which share the same uncertainty variable. In this case, each layer.
        for e, gID in enumerate(group_ids):
            # First we obtain a boolean array with trues where the id coincide
            sel = gp.get_data(interp_data.geo_data_res, verbosity=2)['group_id'] == gID

            # We add to the original Z value (its mean) the stochastic bit in the correspondant groups id
            geo_data_stoch.loc[sel, 'Z']  += np.array(interface_Z_modifier[e])

        if verbose > 0:
            print(geo_data_stoch)

        # then return the input data to be input into the modeling function. Due to the way pymc2 stores the traces
        # We need to save the data as numpy arrays
        return [geo_data_stoch.xs('interfaces')[["X", "Y", "Z"]].values, geo_data_stoch.xs('orientations').values]


    # ## Modeling function

    @pymc.deterministic(trace=False)
    def gempy_model(value=0,
                    input_data=input_data, verbose=True):

        # modify input data values accordingly
        interp_data.geo_data_res.interfaces[["X", "Y", "Z"]] = input_data[0]

        # Gx, Gy, Gz are just used for visualization. The theano function gets azimuth dip and polarity!!!
        interp_data.geo_data_res.orientations[["G_x", "G_y", "G_z", "X", "Y", "Z",  'dip', 'azimuth', 'polarity']] = input_data[1]

        try:
            # try to compute model
            lb, fb = gp.compute_model(interp_data)
            if True:
                gp.plot_section(interp_data.geo_data_res, lb[0], 0, plot_data=True)

            return lb, fb

        except np.linalg.linalg.LinAlgError as err:
            # if it fails (e.g. some input data combinations could lead to
            # a singular matrix and thus break the chain) return an empty model
            # with same dimensions (just zeros)
            if verbose:
                print("Exception occured.")
            return np.zeros_like(lith_block), np.zeros_like(fault_block)

    # We then create a pymc model with the two deterministic functions (*input_data* and *gempy_model*), as well as all
    #  the prior parameter distributions stored in the list *interface_Z_modifier*:

    params = [input_data, gempy_model, *interface_Z_modifier]
    model = pymc.Model(params)

    # Then we set the number of iterations:

    # Then we create an MCMC chain (in pymc an MCMC chain without a likelihood function is essentially a Monte Carlo
    # forward simulation) and specify an hdf5 database to store the results in

    RUN = pymc.MCMC(model, db="hdf5", dbname=os.path.dirname(__file__)+"/ch3-pymc2.hdf5")

    # and we are finally able to run the simulation:

    RUN.sample(iter=100, verbose=0)
Beispiel #16
0
def test_ch1(theano_f_1f):
    # Importing the data from CSV-files and setting extent and resolution
    geo_data = gp.create_data(
        [0, 2000, 0, 2000, 0, 2000], [50, 50, 50],
        path_o=input_path +
        '/input_data/tut_chapter1/simple_fault_model_orientations.csv',
        path_i=input_path +
        '/input_data/tut_chapter1/simple_fault_model_points.csv')

    gp.get_data(geo_data)

    # Assigning series to formations as well as their order (timewise)
    gp.set_series(
        geo_data, {
            "Fault_Series": 'Main_Fault',
            "Strat_Series":
            ('Sandstone_2', 'Siltstone', 'Shale', 'Sandstone_1')
        },
        order_series=["Fault_Series", 'Strat_Series'],
        order_formations=[
            'Main_Fault',
            'Sandstone_2',
            'Siltstone',
            'Shale',
            'Sandstone_1',
        ],
        verbose=0)

    gp.get_sequential_pile(geo_data)

    print(gp.get_grid(geo_data))

    gp.get_data(geo_data, 'interfaces').head()

    gp.get_data(geo_data, 'orientations')

    gp.plot_data(geo_data, direction='y')

    # interp_data = gp.InterpolatorData(geo_data, u_grade=[1,1],
    #                                   output='geology', compile_theano=True,
    #                                   theano_optimizer='fast_compile',
    #                                   verbose=[])

    interp_data = theano_f_1f
    interp_data.update_interpolator(geo_data)

    gp.get_kriging_parameters(interp_data)  # Maybe move this to an extra part?

    lith_block, fault_block = gp.compute_model(interp_data)

    gp.plot_section(geo_data,
                    lith_block[0],
                    cell_number=25,
                    direction='y',
                    plot_data=True)

    gp.plot_scalar_field(geo_data,
                         lith_block[1],
                         cell_number=25,
                         N=15,
                         direction='y',
                         plot_data=False)

    gp.plot_scalar_field(geo_data,
                         lith_block[1],
                         cell_number=25,
                         N=15,
                         direction='z',
                         plot_data=False)

    gp.plot_section(geo_data,
                    fault_block[0],
                    cell_number=25,
                    plot_data=True,
                    direction='y')

    gp.plot_scalar_field(geo_data,
                         fault_block[1],
                         cell_number=25,
                         N=20,
                         direction='y',
                         plot_data=False)

    ver, sim = gp.get_surfaces(interp_data,
                               lith_block[1],
                               fault_block[1],
                               original_scale=True)

    # Cropping a cross-section to visualize in 2D #REDO this part?
    bool_b = np.array(ver[1][:, 1] > 999) * np.array(ver[1][:, 1] < 1001)
    bool_r = np.array(ver[1][:, 1] > 1039) * np.array(ver[1][:, 1] < 1041)

    # Plotting section
    gp.plot_section(geo_data, lith_block[0], 25, plot_data=True)
    ax = plt.gca()

    # Adding grid
    ax.set_xticks(np.linspace(0, 2000, 100, endpoint=False))
    ax.set_yticks(np.linspace(0, 2000, 100, endpoint=False))
    plt.grid()

    plt.ylim(1000, 1600)
    plt.xlim(500, 1100)
    # Plotting vertices
    ax.plot(ver[1][bool_r][:, 0],
            ver[1][bool_r][:, 2],
            '.',
            color='b',
            alpha=.9)
    ax.get_xaxis().set_ticklabels([])

    ver_s, sim_s = gp.get_surfaces(interp_data,
                                   lith_block[1],
                                   fault_block[1],
                                   original_scale=True)
Beispiel #17
0
def test_ch3_a(theano_f):

    # set cube size and model extent
    cs = 50
    extent = (3000, 200, 2000)  # (x, y, z)
    res = (120, 4, 80)

    # initialize geo_data object
    geo_data = gp.create_data(
        [0, extent[0], 0, extent[1], 0, extent[2]],
        resolution=[
            res[0],  # number of voxels
            res[1],
            res[2]
        ])

    geo_data.set_interfaces(pn.read_csv(
        input_path + "/input_data/tut_chapter3/tutorial_ch3_interfaces",
        index_col="Unnamed: 0"),
                            append=True)
    geo_data.set_orientations(
        pn.read_csv(input_path +
                    "/input_data/tut_chapter3/tutorial_ch3_foliations",
                    index_col="Unnamed: 0"))

    # let's have a look at the upper five interface data entries in the dataframe
    gp.get_data(geo_data, 'interfaces', verbosity=1).head()

    # Original pile
    gp.get_sequential_pile(geo_data)

    # Ordered pile
    gp.set_order_formations(geo_data,
                            ['Layer 2', 'Layer 3', 'Layer 4', 'Layer 5'])
    gp.get_sequential_pile(geo_data)

    # and at all of the foliation data
    gp.get_data(geo_data, 'orientations', verbosity=0)

    gp.plot_data(geo_data, direction="y")
    plt.xlim(0, 3000)
    plt.ylim(0, 2000)

    gp.data_to_pickle(
        geo_data,
        os.path.dirname(__file__) + "/ch3-pymc2_tutorial_geo_data")

    #interp_data = gp.InterpolatorData(geo_data, u_grade=[1], compile_theano=True)
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)

    # Afterwards we can compute the geological model
    lith_block, fault_block = gp.compute_model(interp_data)

    # And plot a section:
    gp.plot_section(geo_data, lith_block[0], 2, plot_data=True)

    import pymc

    # Checkpoint in case you did not execute the cells above
    geo_data = gp.read_pickle(
        os.path.dirname(__file__) + "/ch3-pymc2_tutorial_geo_data.pickle")

    gp.get_data(geo_data, 'orientations', verbosity=1).head()

    # So let's assume the vertical location of our layer interfaces is uncertain, and we want to represent this
    #  uncertainty by using a normal distribution. To define a normal distribution, we need a mean and a measure
    #  of deviation (e.g. standard deviation). For convenience the input data is already grouped by a "group_id" value,
    # which allows us to collectively modify data that belongs together. In this example we want to treat the vertical
    # position of each layer interface, on each side of the anticline, as uncertain. Therefore, we want to perturbate
    # the respective three points on each side of the anticline collectively.

    # These are our unique group id's, the number representing the layer, and a/b the side of the anticline.

    group_ids = geo_data.interfaces["group_id"].dropna().unique()
    print(group_ids)

    # As a reminder, GemPy stores data in two main objects, an InputData object (called geo_data in the tutorials) and
    # a InpterpolatorInput object (interp_data) in tutorials. geo_data contains the original data while interp_data the
    # data prepared (and compiled) to compute the 3D model.
    #
    # Since we do not want to compile our code at every new stochastic realization, from here on we will need to work
    # with thte interp_data. And remember that to improve float32 to stability we need to work with rescaled data
    # (between 0 and 1). Therefore all the stochastic data needs to be rescaled accordingly. The object interp_data
    #  contains a property with the rescale factor (see below. As default depends on the model extent), or it is
    # possible to add the stochastic data to the pandas dataframe of the geo_data---when the InterpolatorInput object
    # is created the rescaling happens under the hood.

    interface_Z_modifier = []

    # We rescale the standard deviation
    std = 20. / interp_data.rescaling_factor

    # loop over the unique group id's and create a pymc.Normal distribution for each
    for gID in group_ids:
        stoch = pymc.Normal(gID + '_stoch', 0, 1. / std**2)
        interface_Z_modifier.append(stoch)

    # Let's have a look at one:

    # sample from a distribtion
    samples = [interface_Z_modifier[3].rand() for i in range(10000)]
    # plot histogram
    plt.hist(samples, bins=24, normed=True)
    plt.xlabel("Z modifier")
    plt.vlines(0, 0, 0.01)
    plt.ylabel("n")

    #  Now we need to somehow sample from these distribution and put them into GemPy

    # ## Input data handling
    #
    # First we need to write a function which modifies the input data for each iteration of the stochastic simulation.
    #  As this process is highly dependant on the simulation (e.g. what input parameters you want modified in which way),
    #  this process generally can't be automated.
    #
    # The idea is to change the column Z (in this case) of the rescaled dataframes in our interp_data object (which can
    #  be found in interp_data.geo_data_res). First we simply create the pandas Dataframes we are interested on:

    import copy
    # First we extract from our original intep_data object the numerical data that is necessary for the interpolation.
    # geo_data_stoch is a pandas Dataframe

    # This is the inital model so it has to be outside the stochastic frame
    geo_data_stoch_init = copy.deepcopy(interp_data.geo_data_res)

    gp.get_data(geo_data_stoch_init, numeric=True).head()

    @pymc.deterministic(trace=True)
    def input_data(value=0,
                   interface_Z_modifier=interface_Z_modifier,
                   geo_data_stoch_init=geo_data_stoch_init,
                   verbose=0):
        # First we extract from our original intep_data object the numerical data that is necessary for the interpolation.
        # geo_data_stoch is a pandas Dataframe

        geo_data_stoch = gp.get_data(geo_data_stoch_init, numeric=True)
        # Now we loop each id which share the same uncertainty variable. In this case, each layer.
        for e, gID in enumerate(group_ids):
            # First we obtain a boolean array with trues where the id coincide
            sel = gp.get_data(interp_data.geo_data_res,
                              verbosity=2)['group_id'] == gID

            # We add to the original Z value (its mean) the stochastic bit in the correspondant groups id
            geo_data_stoch.loc[sel, 'Z'] += np.array(interface_Z_modifier[e])

        if verbose > 0:
            print(geo_data_stoch)

        # then return the input data to be input into the modeling function. Due to the way pymc2 stores the traces
        # We need to save the data as numpy arrays
        return [
            geo_data_stoch.xs('interfaces')[["X", "Y", "Z"]].values,
            geo_data_stoch.xs('orientations').values
        ]

    # ## Modeling function

    @pymc.deterministic(trace=False)
    def gempy_model(value=0, input_data=input_data, verbose=True):

        # modify input data values accordingly
        interp_data.geo_data_res.interfaces[["X", "Y", "Z"]] = input_data[0]

        # Gx, Gy, Gz are just used for visualization. The theano function gets azimuth dip and polarity!!!
        interp_data.geo_data_res.orientations[[
            "G_x", "G_y", "G_z", "X", "Y", "Z", 'dip', 'azimuth', 'polarity'
        ]] = input_data[1]

        try:
            # try to compute model
            lb, fb = gp.compute_model(interp_data)
            if True:
                gp.plot_section(interp_data.geo_data_res,
                                lb[0],
                                0,
                                plot_data=True)

            return lb, fb

        except np.linalg.linalg.LinAlgError as err:
            # if it fails (e.g. some input data combinations could lead to
            # a singular matrix and thus break the chain) return an empty model
            # with same dimensions (just zeros)
            if verbose:
                print("Exception occured.")
            return np.zeros_like(lith_block), np.zeros_like(fault_block)

    # We then create a pymc model with the two deterministic functions (*input_data* and *gempy_model*), as well as all
    #  the prior parameter distributions stored in the list *interface_Z_modifier*:

    params = [input_data, gempy_model, *interface_Z_modifier]
    model = pymc.Model(params)

    # Then we set the number of iterations:

    # Then we create an MCMC chain (in pymc an MCMC chain without a likelihood function is essentially a Monte Carlo
    # forward simulation) and specify an hdf5 database to store the results in

    RUN = pymc.MCMC(model,
                    db="hdf5",
                    dbname=os.path.dirname(__file__) + "/ch3-pymc2.hdf5")

    # and we are finally able to run the simulation:

    RUN.sample(iter=100, verbose=0)
Beispiel #18
0
def test_ch5(theano_f_grav, theano_f):
    # Importing the data from csv files and settign extent and resolution
    geo_data = gp.create_data([696000,747000,6863000,6950000,-20000, 200],[50, 50, 50],
                             path_o = input_path+"/input_data/tut_SandStone/SandStone_Foliations.csv",
                             path_i = input_path+"/input_data/tut_SandStone/SandStone_Points.csv")


    # Assigning series to formations as well as their order (timewise)
    gp.set_series(geo_data, {"EarlyGranite_Series": 'EarlyGranite',
                                  "BIF_Series":('SimpleMafic2', 'SimpleBIF'),
                                  "SimpleMafic_Series":'SimpleMafic1'},
                          order_series = ["EarlyGranite_Series",
                                          "BIF_Series",
                                          "SimpleMafic_Series"],
                          order_formations= ['EarlyGranite', 'SimpleMafic2',
                                             'SimpleBIF', 'SimpleMafic1'],
                  verbose=1)



    gp.plot_data(geo_data)


    #interp_data = gp.InterpolatorData(geo_data, compile_theano=True)
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)

    lith_block, fault_block = gp.compute_model(interp_data)

    import matplotlib.pyplot as plt
    gp.plot_section(geo_data, lith_block[0], 10, plot_data=True, direction='y')
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)

    from matplotlib.patches import Rectangle

    currentAxis = plt.gca()

    currentAxis.add_patch(Rectangle((7.050000e+05, 6863000),
                                    747000 - 7.050000e+05,
                                    6925000 - 6863000,
                          alpha=0.3, fill='none', color ='green' ))

    ver_s, sim_s = gp.get_surfaces(interp_data, lith_block[1],
                                   None,
                                   original_scale=True)

   # gp.plot_surfaces_3D_real_time(interp_data, ver_s, sim_s)

    # Importing the data from csv files and settign extent and resolution
    geo_data_extended = gp.create_data([696000-10000,
                                        747000 + 20600,
                                        6863000 - 20600,6950000 + 20600,
                                        -20000, 600],
                                       [50, 50, 50],
                                   path_o=input_path + "/input_data/tut_SandStone/SandStone_Foliations.csv",
                                   path_i=input_path + "/input_data/tut_SandStone/SandStone_Points.csv")


    # Assigning series to formations as well as their order (timewise)
    gp.set_series(geo_data_extended, {"EarlyGranite_Series": 'EarlyGranite',
                                  "BIF_Series":('SimpleMafic2', 'SimpleBIF'),
                                  "SimpleMafic_Series":'SimpleMafic1'},
                          order_series = ["EarlyGranite_Series",
                                          "BIF_Series",
                                          "SimpleMafic_Series"],
                          order_formations= ['EarlyGranite', 'SimpleMafic2',
                                             'SimpleBIF', 'SimpleMafic1'],
                  verbose=1)

   # interp_data_extended = gp.InterpolatorData(geo_data_extended, output='geology',
    #                                           compile_theano=True)
    interp_data_extended = interp_data
    interp_data_extended.update_interpolator(geo_data_extended)

    geo_data_extended.set_formations(formation_values=[2.61,2.92,3.1,2.92,2.61],
                            formation_order=['EarlyGranite', 'SimpleMafic2',
                                             'SimpleBIF', 'SimpleMafic1',
                                             'basement'])

    lith_ext, fautl = gp.compute_model(interp_data_extended)

    import matplotlib.pyplot as plt

    gp.plot_section(geo_data_extended, lith_ext[0], -1, plot_data=True, direction='z')
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)

    from matplotlib.patches import Rectangle

    currentAxis = plt.gca()

    currentAxis.add_patch(Rectangle((7.050000e+05, 6863000),  747000 - 7.050000e+05,
                                     6925000 - 6863000,
                          alpha=0.3, fill='none', color ='green' ))



    interp_data_grav = theano_f_grav
    interp_data_grav.update_interpolator(geo_data_extended)

    gp.set_geophysics_obj(interp_data_grav,  [7.050000e+05,747000,6863000,6925000,-20000, 200],
                                                 [10, 10],)

    gp.precomputations_gravity(interp_data_grav, 10)

    lith, fault, grav = gp.compute_model(interp_data_grav, 'gravity')

    import matplotlib.pyplot as plt

    plt.imshow(grav.reshape(10, 10), cmap='viridis', origin='lower',
               extent=[7.050000e+05,747000,6863000,6950000] )
    plt.colorbar()
Beispiel #19
0
def test_ch1(theano_f_1f):
    # Importing the data from CSV-files and setting extent and resolution
    geo_data = gp.create_data([0, 2000, 0, 2000, 0, 2000], [50, 50, 50],
                              path_o=input_path+'/input_data/tut_chapter1/simple_fault_model_orientations.csv',
                              path_i=input_path+'/input_data/tut_chapter1/simple_fault_model_points.csv')


    gp.get_data(geo_data)

    # Assigning series to formations as well as their order (timewise)
    gp.set_series(geo_data, {"Fault_Series":'Main_Fault',
                             "Strat_Series": ('Sandstone_2','Siltstone',
                                              'Shale', 'Sandstone_1')},
                           order_series = ["Fault_Series", 'Strat_Series'],
                           order_formations=['Main_Fault',
                                             'Sandstone_2','Siltstone',
                                             'Shale', 'Sandstone_1',
                                             ], verbose=0)


    gp.get_sequential_pile(geo_data)

    print(gp.get_grid(geo_data))

    gp.get_data(geo_data, 'interfaces').head()

    gp.get_data(geo_data, 'orientations')

    gp.plot_data(geo_data, direction='y')

    # interp_data = gp.InterpolatorData(geo_data, u_grade=[1,1],
    #                                   output='geology', compile_theano=True,
    #                                   theano_optimizer='fast_compile',
    #                                   verbose=[])

    interp_data = theano_f_1f
    interp_data.update_interpolator(geo_data)

    gp.get_kriging_parameters(interp_data) # Maybe move this to an extra part?

    lith_block, fault_block = gp.compute_model(interp_data)


    gp.plot_section(geo_data, lith_block[0], cell_number=25,  direction='y', plot_data=True)


    gp.plot_scalar_field(geo_data, lith_block[1], cell_number=25, N=15,
                            direction='y', plot_data=False)


    gp.plot_scalar_field(geo_data, lith_block[1], cell_number=25, N=15,
                            direction='z', plot_data=False)

    gp.plot_section(geo_data, fault_block[0], cell_number=25, plot_data=True, direction='y')

    gp.plot_scalar_field(geo_data, fault_block[1], cell_number=25, N=20,
                            direction='y', plot_data=False)


    ver, sim = gp.get_surfaces(interp_data,lith_block[1], fault_block[1], original_scale=True)

    # Cropping a cross-section to visualize in 2D #REDO this part?
    bool_b = np.array(ver[1][:,1] > 999)* np.array(ver[1][:,1] < 1001)
    bool_r = np.array(ver[1][:,1] > 1039)* np.array(ver[1][:,1] < 1041)

    # Plotting section
    gp.plot_section(geo_data, lith_block[0], 25, plot_data=True)
    ax = plt.gca()

    # Adding grid
    ax.set_xticks(np.linspace(0, 2000, 100, endpoint=False))
    ax.set_yticks(np.linspace(0, 2000, 100, endpoint=False))
    plt.grid()

    plt.ylim(1000,1600)
    plt.xlim(500,1100)
    # Plotting vertices
    ax.plot(ver[1][bool_r][:, 0], ver[1][bool_r][:, 2], '.', color='b', alpha=.9)
    ax.get_xaxis().set_ticklabels([])



    ver_s, sim_s = gp.get_surfaces(interp_data,lith_block[1],
                                   fault_block[1],
                                   original_scale=True)
Beispiel #20
0
def test_rgeomod_integration(theano_f):
    geo_data=gp.create_data(extent=[612000, 622000, 2472000, 2480000, -1000, 1000],
                            resolution=[50, 50, 50],
                            path_f=input_path+"/gempy_foliations.csv",
                            path_i=input_path+"/gempy_interfaces.csv")



    formation_order = ["Unit4", "Unit3", "Unit2", "Unit1"]



    gp.set_series(geo_data, {"Default series": formation_order},
                 order_formations = formation_order, verbose=1)



    gp.plot_data(geo_data, direction="z")


    #interp_data = gp.InterpolatorData(geo_data, compile_theano=True)
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)

    lith_block, fault_block = gp.compute_model(interp_data)
    print("3-D geological model calculated.")


    gp.plot_section(geo_data, lith_block[0], 25, direction='y', plot_data=False)
    #plt.savefig("../data/cross_section_NS_25.pdf", bbox_inches="tight")

    gp.plot_section(geo_data, lith_block[0], 25, direction='x', plot_data=False)
    #plt.savefig("../data/cross_section_EW_25.pdf", bbox_inches="tight")

    vertices, simplices = gp.get_surfaces(interp_data, potential_lith=lith_block[1], step_size=2)

    fig = plt.figure(figsize=(13,10))
    ax = fig.add_subplot(111, projection='3d')
    cs = ["lightblue", "pink", "lightgreen", "orange"]
    for i in range(4):
        surf = ax.plot_trisurf(vertices[i][:,0], vertices[i][:,1], vertices[i][:,2],
                               color=cs[i], linewidth=0, alpha=0.65, shade=False)
    #plt.savefig("../data/surfaces_3D.pdf", bbox_inches="tight")

    # try:
    #     gp.plot_surfaces_3D(geo_data, vertices, simplices)
    # except NameError:
    #     print("3-D visualization library vtk not installed.")

    # load the digital elevation model
    geotiff_filepath = input_path+"/dome_sub_sub_utm.tif"
    raster = gdal.Open(geotiff_filepath)
    dtm = raster.ReadAsArray()
    dtmp = plt.imshow(dtm, origin='upper', cmap="viridis");
    plt.title("Digital elevation model");
    plt.colorbar(dtmp, label="Elevation [m]");
    plt.savefig(input_path+"/DTM.pdf")

    # To be able to use gempy plotting functionality we need to create a dummy geo_data object with the
    # resoluion we want. In this case resolution=[339, 271, 1]
    import copy
    geo_data_dummy = copy.deepcopy(geo_data)
    geo_data_dummy.resolution = [339, 271, 1]



    # convert the dtm to a gempy-suitable raveled grid
    points = rgeomod.convert_dtm_to_gempy_grid(raster, dtm)


    # Now we can use the function `compute_model_at` to get the lithology values at a specific location:

    # In[17]:


    # interp_data_geomap = gp.InterpolatorInput(geo_data, dtype="float64")
    lith_block, fault_block = gp.compute_model_at(points, interp_data)


    # <div class="alert alert-info">
    # **Your task:** Create a visual representation of the geological map in a 2-D plot (note: result is also again saved to the `../data`-folder):
    # </div>
    #
    # And here **the geological map**:

    # In[18]:


    gp.plot_section(geo_data_dummy, lith_block[0], 0, direction='z', plot_data=False)
    plt.title("Geological map");
    #plt.savefig("../geological_map.pdf")


    # ### Export the map for visualization in GoogleEarth

    # <div class="alert alert-info">
    # **Your task:** Execute the following code to export a GeoTiff of the generated geological map, as well as `kml`-files with your picked points inside the data folder. Open these files in GoogleEarth and inspect the generated map:
    # </div>
    #
    #
    # <div class="alert alert-warning">
    # **Note (1)**: Use the normal `File -> Open..` dialog in GoogleEarth to open the data - no need to use the `Import` method, as the GeoTiff contains the correct coordinates in the file.
    # </div>
    #
    #
    # <div class="alert alert-warning">
    # **Note (2)**: For a better interpretation of the generated map, use the transparency feature (directly after opening the map, or using `right-click -> Get Info` on the file).
    # </div>

    # In[19]:


    geo_map = lith_block[0].copy().reshape((339,271))
    geo_map = geo_map.astype('int16')  # change to int for later use


    # In[20]:


    rgeomod.export_geotiff(input_path+"/geomap.tif", geo_map, gp.plotting.colors.cmap, geotiff_filepath)


    # Export the interface data points:

    # In[21]:


    t = input_path+"/templates/ge_template_raw_interf.xml"
    pt = input_path+"/templates/ge_placemark_template_interf.xml"
    rgeomod.gempy_export_points_to_kml(input_path, geo_data, pt, t, gp.plotting.colors.cmap)


    # Export the foliation data:



    t = input_path+"/templates/ge_template_raw_fol.xml"
    pt = input_path+"/templates/ge_placemark_template_fol.xml"
    rgeomod.gempy_export_fol_to_kml(input_path+"/dips.kml", geo_data, pt, t)
Beispiel #21
0
def test_ch5(theano_f_grav, theano_f):
    # Importing the data from csv files and settign extent and resolution
    geo_data = gp.create_data(
        [696000, 747000, 6863000, 6950000, -20000, 200], [50, 50, 50],
        path_o=input_path +
        "/input_data/tut_SandStone/SandStone_Foliations.csv",
        path_i=input_path + "/input_data/tut_SandStone/SandStone_Points.csv")

    # Assigning series to formations as well as their order (timewise)
    gp.set_series(geo_data, {
        "EarlyGranite_Series": 'EarlyGranite',
        "BIF_Series": ('SimpleMafic2', 'SimpleBIF'),
        "SimpleMafic_Series": 'SimpleMafic1'
    },
                  order_series=[
                      "EarlyGranite_Series", "BIF_Series", "SimpleMafic_Series"
                  ],
                  order_formations=[
                      'EarlyGranite', 'SimpleMafic2', 'SimpleBIF',
                      'SimpleMafic1'
                  ],
                  verbose=1)

    gp.plot_data(geo_data)

    #interp_data = gp.InterpolatorData(geo_data, compile_theano=True)
    interp_data = theano_f
    interp_data.update_interpolator(geo_data)

    lith_block, fault_block = gp.compute_model(interp_data)

    import matplotlib.pyplot as plt
    gp.plot_section(geo_data, lith_block[0], 10, plot_data=True, direction='y')
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)

    from matplotlib.patches import Rectangle

    currentAxis = plt.gca()

    currentAxis.add_patch(
        Rectangle((7.050000e+05, 6863000),
                  747000 - 7.050000e+05,
                  6925000 - 6863000,
                  alpha=0.3,
                  fill='none',
                  color='green'))

    ver_s, sim_s = gp.get_surfaces(interp_data,
                                   lith_block[1],
                                   None,
                                   original_scale=True)

    # gp.plot_surfaces_3D_real_time(interp_data, ver_s, sim_s)

    # Importing the data from csv files and settign extent and resolution
    geo_data_extended = gp.create_data(
        [
            696000 - 10000, 747000 + 20600, 6863000 - 20600, 6950000 + 20600,
            -20000, 600
        ], [50, 50, 50],
        path_o=input_path +
        "/input_data/tut_SandStone/SandStone_Foliations.csv",
        path_i=input_path + "/input_data/tut_SandStone/SandStone_Points.csv")

    # Assigning series to formations as well as their order (timewise)
    gp.set_series(geo_data_extended, {
        "EarlyGranite_Series": 'EarlyGranite',
        "BIF_Series": ('SimpleMafic2', 'SimpleBIF'),
        "SimpleMafic_Series": 'SimpleMafic1'
    },
                  order_series=[
                      "EarlyGranite_Series", "BIF_Series", "SimpleMafic_Series"
                  ],
                  order_formations=[
                      'EarlyGranite', 'SimpleMafic2', 'SimpleBIF',
                      'SimpleMafic1'
                  ],
                  verbose=1)

    # interp_data_extended = gp.InterpolatorData(geo_data_extended, output='geology',
    #                                           compile_theano=True)
    interp_data_extended = interp_data
    interp_data_extended.update_interpolator(geo_data_extended)

    geo_data_extended.set_formations(
        formation_values=[2.61, 2.92, 3.1, 2.92, 2.61],
        formation_order=[
            'EarlyGranite', 'SimpleMafic2', 'SimpleBIF', 'SimpleMafic1',
            'basement'
        ])

    lith_ext, fautl = gp.compute_model(interp_data_extended)

    import matplotlib.pyplot as plt

    gp.plot_section(geo_data_extended,
                    lith_ext[0],
                    -1,
                    plot_data=True,
                    direction='z')
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)

    from matplotlib.patches import Rectangle

    currentAxis = plt.gca()

    currentAxis.add_patch(
        Rectangle((7.050000e+05, 6863000),
                  747000 - 7.050000e+05,
                  6925000 - 6863000,
                  alpha=0.3,
                  fill='none',
                  color='green'))

    interp_data_grav = theano_f_grav
    interp_data_grav.update_interpolator(geo_data_extended)

    gp.set_geophysics_obj(
        interp_data_grav,
        [7.050000e+05, 747000, 6863000, 6925000, -20000, 200],
        [10, 10],
    )

    gp.precomputations_gravity(interp_data_grav, 10)

    lith, fault, grav = gp.compute_model(interp_data_grav, 'gravity')

    import matplotlib.pyplot as plt

    plt.imshow(grav.reshape(10, 10),
               cmap='viridis',
               origin='lower',
               extent=[7.050000e+05, 747000, 6863000, 6950000])
    plt.colorbar()

# In[ ]:


lith_block, fault_block = gp.compute_model(interp_data)


# ## 3.4 - Model visualization
# 
# ### 3.4.1 - 2D Sections

# In[ ]:


gp.plot_section(geo_data, lith_block[0], 25, direction='y')


# In[ ]:


gp.plot_section(geo_data, lith_block[0], 25, direction='x')


# ### 3.4.2 - Pseudo-3D surfaces

# In[ ]:


v_l, s_l = gp.get_surfaces(interp_data, potential_lith=lith_block[1], step_size=2)