예제 #1
0
 def test_setter(self):
     krige1 = gs.krige.Krige(gs.Exponential(), self.cond_pos, self.cond_val)
     krige2 = gs.krige.Krige(
         gs.Gaussian(var=2),
         self.cond_pos,
         self.cond_val,
         mean=-1,
         trend=-2,
         normalizer=gs.normalizer.YeoJohnson(),
     )
     crf1 = gs.CondSRF(krige1)
     crf2 = gs.CondSRF(krige2, seed=19970221)
     # update settings
     crf1.model = gs.Gaussian(var=2)
     crf1.mean = -1
     crf1.trend = -2
     # also checking correctly setting uninitialized normalizer
     crf1.normalizer = gs.normalizer.YeoJohnson
     # check if setting went right
     self.assertTrue(crf1.model == crf2.model)
     self.assertTrue(crf1.normalizer == crf2.normalizer)
     self.assertAlmostEqual(crf1.mean, crf2.mean)
     self.assertAlmostEqual(crf1.trend, crf2.trend)
     # reset kriging
     crf1.krige.set_condition()
     # compare fields
     field1 = crf1(self.pos, seed=19970221)
     field2 = crf2(self.pos)
     self.assertTrue(np.all(np.isclose(field1, field2)))
예제 #2
0
 def test_krige_mean(self):
     # check for constant mean (simple kriging)
     krige = gs.krige.Simple(gs.Gaussian(), self.cond_pos, self.cond_val)
     mean_f = krige.structured(self.pos, only_mean=True)
     self.assertTrue(np.all(np.isclose(mean_f, 0)))
     krige = gs.krige.Simple(
         gs.Gaussian(),
         self.cond_pos,
         self.cond_val,
         mean=mean_func,
         normalizer=gs.normalizer.YeoJohnson,
         trend=trend,
     )
     # check applying mean, norm, trend
     mean_f1 = krige.structured(self.pos, only_mean=True)
     mean_f2 = gs.normalizer.tools.apply_mean_norm_trend(
         self.pos,
         np.zeros(tuple(map(len, self.pos))),
         mean=mean_func,
         normalizer=gs.normalizer.YeoJohnson,
         trend=trend,
         mesh_type="structured",
     )
     self.assertTrue(np.all(np.isclose(mean_f1, mean_f2)))
     krige = gs.krige.Simple(gs.Gaussian(), self.cond_pos, self.cond_val)
     mean_f = krige.structured(self.pos, only_mean=True)
     self.assertTrue(np.all(np.isclose(mean_f, 0)))
     # check for constant mean (ordinary kriging)
     krige = gs.krige.Ordinary(gs.Gaussian(), self.cond_pos, self.cond_val)
     mean_f = krige.structured(self.pos, only_mean=True)
     self.assertTrue(np.all(np.isclose(mean_f, krige.get_mean())))
예제 #3
0
def test_field_mean_std_convergence(seed):
    np.random.seed(seed)
    np.random.rand(1000)
    # ===========  A structured grid of points: =====================================
    bounds = ([13, 3], [40, 32])
    grid_size = [10, 15]
    grid_points = PointSet(bounds, grid_size)
    random_points = PointSet(bounds, grid_size[0] * grid_size[1])
    exponential = 1.0
    gauss = 2.0
    corr_length = 2
    n_terms = (np.inf, np.inf
               )  # Use full expansion to avoid error in approximation.

    impl = SpatialCorrelatedField
    #print("Test exponential, grid points.")
    impl_test_mu_sigma(impl, exponential, grid_points, n_terms_range=n_terms)
    #print("Test Gauss, grid points.")
    impl_test_mu_sigma(impl, gauss, grid_points, n_terms_range=n_terms)
    #print("Test exponential, random points.")
    impl_test_mu_sigma(impl, exponential, random_points, n_terms_range=n_terms)
    #print("Test Gauss, random points.")
    impl_test_mu_sigma(impl, gauss, random_points, n_terms_range=n_terms)

    len_scale = corr_length * 2 * np.pi

    # Random points gauss model
    gauss_model = gstools.Gaussian(dim=random_points.dim, len_scale=len_scale)
    impl = GSToolsSpatialCorrelatedField(gauss_model)
    impl_test_mu_sigma(impl,
                       gauss,
                       random_points,
                       n_terms_range=n_terms,
                       corr_length=2)
    # Random points exp model
    exp_model = gstools.Exponential(dim=random_points.dim, len_scale=len_scale)
    impl = GSToolsSpatialCorrelatedField(exp_model)
    impl_test_mu_sigma(impl,
                       exponential,
                       random_points,
                       n_terms_range=n_terms,
                       corr_length=2)

    # Grid points gauss model
    gauss_model = gstools.Gaussian(dim=grid_points.dim, len_scale=len_scale)
    impl = GSToolsSpatialCorrelatedField(gauss_model)
    impl_test_mu_sigma(impl,
                       gauss_model,
                       grid_points,
                       n_terms_range=n_terms,
                       corr_length=2)

    # Grid points exp model
    exp_model = gstools.Exponential(dim=grid_points.dim, len_scale=len_scale)
    impl = GSToolsSpatialCorrelatedField(exp_model)
    impl_test_mu_sigma(impl,
                       exp_model,
                       grid_points,
                       n_terms_range=n_terms,
                       corr_length=2)
예제 #4
0
def kriging_fill_grid(input):
    """
    conditioning data:
        input['x'] (array)
        input['y'] (array)
        input['z'] (array)

    grid definition for output field
        input['x_start']
        input['x_stop']
        input['x_step']
        input['y_start']
        input['y_stop']
        input['y_step']
    """
    if len(input['x']) == len(input['y']) == len(input['z']):
        XI = np.arange(input['x_start'], input['x_stop'], input['x_step'])
        YI = np.arange(input['y_start'], input['y_stop'], input['y_step'])

        cov_model = gs.Gaussian(dim=2,
                                len_scale=1,
                                anis=0.2,
                                angles=-0.5,
                                var=0.5,
                                nugget=0.1)
        #pk_kwargs = cov_model.pykrige_kwargs
        #OK = OrdinaryKriging(input['x'], input['y'], input['z'], **pk_kwargs)
        #ZI, ss = OK.execute("grid", XI, YI)

        OK2 = gs.krige.Ordinary(cov_model, [input['x'], input['y']],
                                input['z'])
        ZI, ss = OK2.structured([XI, YI])
        return ZI
    else:
        return None
예제 #5
0
 def setUp(self):
     self.cov_model = gs.Gaussian(dim=2, var=1.5, len_scale=4.0)
     rng = np.random.RandomState(123018)
     x = rng.uniform(0.0, 10, 100)
     y = rng.uniform(0.0, 10, 100)
     self.field = rng.uniform(0.0, 10, 100)
     self.pos = np.array([x, y])
예제 #6
0
    def test_rotation_unstruct_3d(self):
        self.cov_model = gs.Gaussian(dim=3,
                                     var=1.5,
                                     len_scale=4.0,
                                     anis=(0.25, 0.5))
        x_len = len(self.x_grid_c)
        y_len = len(self.y_grid_c)
        z_len = len(self.z_grid_c)
        x_u, y_u, z_u = np.meshgrid(self.x_grid_c, self.y_grid_c,
                                    self.z_grid_c)
        x_u = np.reshape(x_u, x_len * y_len * z_len)
        y_u = np.reshape(y_u, x_len * y_len * z_len)
        z_u = np.reshape(z_u, x_len * y_len * z_len)

        srf = gs.SRF(self.cov_model, mean=self.mean, mode_no=self.mode_no)
        field = srf((x_u, y_u, z_u), seed=self.seed, mesh_type="unstructured")
        field_str = np.reshape(field, (y_len, x_len, z_len))

        self.cov_model.angles = (-np.pi / 2.0, -np.pi / 2.0)
        srf = gs.SRF(self.cov_model, mean=self.mean, mode_no=self.mode_no)
        field_rot = srf((x_u, y_u, z_u),
                        seed=self.seed,
                        mesh_type="unstructured")
        field_rot_str = np.reshape(field_rot, (y_len, x_len, z_len))

        self.assertAlmostEqual(field_str[0, 0, 0], field_rot_str[-1, -1, 0])
        self.assertAlmostEqual(field_str[1, 2, 0], field_rot_str[-3, -1, 1])
        self.assertAlmostEqual(field_str[0, 0, 1], field_rot_str[-1, -2, 0])
예제 #7
0
    def setUp(self):
        self.cmod = gs.Gaussian(latlon=True,
                                var=2,
                                len_scale=777,
                                rescale=gs.EARTH_RADIUS)
        self.lat = self.lon = range(-80, 81)

        self.data = np.array([
            [52.9336, 8.237, 15.7],
            [48.6159, 13.0506, 13.9],
            [52.4853, 7.9126, 15.1],
            [50.7446, 9.345, 17.0],
            [52.9437, 12.8518, 21.9],
            [53.8633, 8.1275, 11.9],
            [47.8342, 10.8667, 11.4],
            [51.0881, 12.9326, 17.2],
            [48.406, 11.3117, 12.9],
            [49.7273, 8.1164, 17.2],
            [49.4691, 11.8546, 13.4],
            [48.0197, 12.2925, 13.9],
            [50.4237, 7.4202, 18.1],
            [53.0316, 13.9908, 21.3],
            [53.8412, 13.6846, 21.3],
            [54.6792, 13.4343, 17.4],
            [49.9694, 9.9114, 18.6],
            [51.3745, 11.292, 20.2],
            [47.8774, 11.3643, 12.7],
            [50.5908, 12.7139, 15.8],
        ])
예제 #8
0
 def test_meshio(self):
     points = np.array([
         [0.0, 0.0, 0.0],
         [0.0, 1.0, 0.0],
         [0.0, 0.0, 1.0],
         [1.0, 0.0, 0.0],
     ])
     cells = [("tetra", np.array([[0, 1, 2, 3]]))]
     mesh = meshio.Mesh(points, cells)
     model = gs.Gaussian(dim=3, len_scale=0.1)
     srf = gs.SRF(model)
     srf.mesh(mesh, points="points")
     self.assertEqual(len(srf.field), 4)
     srf.mesh(mesh, points="centroids")
     self.assertEqual(len(srf.field), 1)
예제 #9
0
    def test_vario_est(self):
        srf = gs.SRF(self.cmod, seed=12345)
        field = srf.structured((self.lat, self.lon))

        bin_edges = [0.01 * i for i in range(30)]
        bin_center, emp_vario = gs.vario_estimate(
            *((self.lat, self.lon), field, bin_edges),
            latlon=True,
            mesh_type="structured",
            sampling_size=2000,
            sampling_seed=12345,
        )
        mod = gs.Gaussian(latlon=True, rescale=gs.EARTH_RADIUS)
        mod.fit_variogram(bin_center, emp_vario, nugget=False)
        # allow 10 percent relative error
        self.assertLess(_rel_err(mod.var, self.cmod.var), 0.1)
        self.assertLess(_rel_err(mod.len_scale, self.cmod.len_scale), 0.1)
예제 #10
0
 def test_incomprrandmeth(self):
     self.cov_model = gs.Gaussian(dim=2, var=0.5, len_scale=1.0)
     srf = gs.SRF(
         self.cov_model,
         mean=self.mean,
         mode_no=self.mode_no,
         generator="IncomprRandMeth",
         mean_velocity=0.5,
     )
     field = srf((self.x_tuple, self.y_tuple), seed=476356)
     self.assertAlmostEqual(field[0, 0], 1.23693272)
     self.assertAlmostEqual(field[0, 1], 0.89242284)
     field = srf((self.x_grid, self.y_grid),
                 seed=4734654,
                 mesh_type="structured")
     self.assertAlmostEqual(field[0, 0, 0], 1.07812013)
     self.assertAlmostEqual(field[0, 1, 0], 1.06180674)
예제 #11
0
    def setUp(self):
        self.cov_model = gs.Gaussian(dim=2, var=1.5, len_scale=4.0)
        self.mean = 0.3
        self.mode_no = 100

        self.seed = 825718662
        self.x_grid = np.linspace(0.0, 12.0, 48)
        self.y_grid = np.linspace(0.0, 10.0, 46)
        self.z_grid = np.linspace(0.0, 10.0, 40)

        self.x_grid_c = np.linspace(-6.0, 6.0, 8)
        self.y_grid_c = np.linspace(-6.0, 6.0, 8)
        self.z_grid_c = np.linspace(-6.0, 6.0, 8)

        rng = np.random.RandomState(123018)
        self.x_tuple = rng.uniform(0.0, 10, 100)
        self.y_tuple = rng.uniform(0.0, 10, 100)
        self.z_tuple = rng.uniform(0.0, 10, 100)
예제 #12
0
 def error_test(self):
     # try fitting directional variogram
     mod = gs.Gaussian(latlon=True)
     with self.assertRaises(ValueError):
         mod.fit_variogram([0, 1], [[0, 1], [0, 1], [0, 1]])
     # try to use fixed dim=2 with latlon
     with self.assertRaises(ValueError):
         ErrMod(latlon=True)
     # try to estimate latlon vario on wrong dim
     with self.assertRaises(ValueError):
         gs.vario_estimate([[1], [1], [1]], [1], [0, 1], latlon=True)
     # try to estimate directional vario with latlon
     with self.assertRaises(ValueError):
         gs.vario_estimate([[1], [1]], [1], [0, 1], latlon=True, angles=1)
     # try to create a vector field with latlon
     with self.assertRaises(ValueError):
         srf = gs.SRF(mod, generator="VectorField", mode_no=2)
         srf([1, 2])
예제 #13
0
    def setUp(self):
        self.cov_model_2d = gs.Gaussian(dim=2, var=1.5, len_scale=2.5)
        self.cov_model_3d = copy.deepcopy(self.cov_model_2d)
        self.cov_model_3d.dim = 3
        self.seed = 19031977
        self.x_grid = np.linspace(0.0, 10.0, 9)
        self.y_grid = np.linspace(-5.0, 5.0, 16)
        self.z_grid = np.linspace(-6.0, 7.0, 8)
        self.x_tuple = np.linspace(0.0, 10.0, 10)
        self.y_tuple = np.linspace(-5.0, 5.0, 10)
        self.z_tuple = np.linspace(-6.0, 8.0, 10)

        self.rm_2d = IncomprRandMeth(
            self.cov_model_2d, mode_no=100, seed=self.seed
        )
        self.rm_3d = IncomprRandMeth(
            self.cov_model_3d, mode_no=100, seed=self.seed
        )
예제 #14
0
 def test_nugget(self):
     model = gs.Gaussian(
         nugget=0.01,
         var=0.5,
         len_scale=2,
         anis=[0.1, 1],
         angles=[0.5, 0, 0],
     )
     krige = gs.krige.Ordinary(model,
                               self.cond_pos,
                               self.cond_val,
                               exact=True)
     crf = gs.CondSRF(krige, seed=19970221)
     field_1 = crf.unstructured(self.pos)
     field_2 = crf.structured(self.pos)
     for i, val in enumerate(self.cond_val):
         self.assertAlmostEqual(val, field_1[i], places=2)
         self.assertAlmostEqual(val, field_2[3 * (i, )], places=2)
예제 #15
0
 def test_auto_fit(self):
     x = y = range(60)
     pos = gs.generate_grid([x, y])
     model = gs.Gaussian(dim=2, var=1, len_scale=10)
     srf = gs.SRF(model,
                  seed=20170519,
                  normalizer=gs.normalizer.LogNormal())
     srf(pos)
     ids = np.arange(srf.field.size)
     samples = np.random.RandomState(20210201).choice(ids,
                                                      size=60,
                                                      replace=False)
     # sample conditioning points from generated field
     cond_pos = pos[:, samples]
     cond_val = srf.field[samples]
     krige = gs.krige.Ordinary(
         model=gs.Stable(dim=2),
         cond_pos=cond_pos,
         cond_val=cond_val,
         normalizer=gs.normalizer.BoxCox(),
         fit_normalizer=True,
         fit_variogram=True,
     )
     # test fitting during kriging
     self.assertTrue(np.abs(krige.normalizer.lmbda - 0.0) < 1e-1)
     self.assertAlmostEqual(krige.model.len_scale, 10.2677, places=4)
     self.assertAlmostEqual(
         krige.model.sill,
         krige.normalizer.normalize(cond_val).var(),
         places=4,
     )
     # test fitting during vario estimate
     bin_center, gamma, normalizer = gs.vario_estimate(
         cond_pos,
         cond_val,
         normalizer=gs.normalizer.BoxCox,
         fit_normalizer=True,
     )
     model = gs.Stable(dim=2)
     model.fit_variogram(bin_center, gamma)
     self.assertAlmostEqual(model.var, 0.6426670183, places=4)
     self.assertAlmostEqual(model.len_scale, 9.635193952, places=4)
     self.assertAlmostEqual(model.nugget, 0.001617908408, places=4)
     self.assertAlmostEqual(model.alpha, 2.0, places=4)
예제 #16
0
 def test_raise(self):
     # vector field on latlon
     fld = gs.field.Field(gs.Gaussian(latlon=True), value_type="vector")
     self.assertRaises(ValueError, fld, [1, 2], [1, 2])
     # no pos tuple present
     fld = gs.field.Field(dim=2)
     self.assertRaises(ValueError, fld.post_field, [1, 2])
     # wrong model type
     with self.assertRaises(ValueError):
         gs.field.Field(model=3.1415)
     # no model and no dim given
     with self.assertRaises(ValueError):
         gs.field.Field()
     # wrong value type
     with self.assertRaises(ValueError):
         gs.field.Field(dim=2, value_type="complex")
     # wrong mean shape
     with self.assertRaises(ValueError):
         gs.field.Field(dim=3, mean=[1, 2])
예제 #17
0
    def setUp(self):
        self.cov_model = gs.Gaussian(dim=2, var=1.5, len_scale=4.0)
        self.mean = 0.3
        self.mode_no = 100

        self.seed = 825718662
        self.x_grid = np.linspace(0.0, 12.0, 48)
        self.y_grid = np.linspace(0.0, 10.0, 46)

        self.methods = [
            "binary",
            "boxcox",
            "zinnharvey",
            "normal_force_moments",
            "normal_to_lognormal",
            "normal_to_uniform",
            "normal_to_arcsin",
            "normal_to_uquad",
        ]
예제 #18
0
def test_cov_func_convergence(seed):
    # TODO:
    # Seems that we have systematic error in covariance function.
    # Error seems to grow with distance. About l**0.1 for corr_exp==1,
    # faster grow for corr_exp == 2.
    # Not clear if it is a selection effect however there is cleare convergence
    # of the error to some smooth limit function.
    # Using (sum of squares) of absolute error gives systemetic error
    # between 0.5 - 4.0, seems o grow a bit with level !! but no grow with distance.
    # No influence of uniform vs. normal points. Just more cosy for larger distances
    # as there is smaller sample set.
    np.random.seed(seed)
    np.random.rand(100)
    # ===========  A structured grid of points: =====================================
    bounds = ([0, 0], [40, 30])
    random_points = PointSet(bounds, 100)
    exponential = 1.0
    gauss = 2.0
    corr_length = 2
    n_terms = (np.inf, np.inf
               )  # Use full expansion to avoid error in approximation.

    impl_test_cov_func(SpatialCorrelatedField,
                       gauss,
                       random_points,
                       n_terms_range=n_terms,
                       corr_length=corr_length)
    impl_test_cov_func(SpatialCorrelatedField,
                       exponential,
                       random_points,
                       n_terms_range=n_terms,
                       corr_length=corr_length)

    len_scale = corr_length * 2 * np.pi
    gauss_model = gstools.Gaussian(dim=random_points.dim, len_scale=len_scale)
    impl = GSToolsSpatialCorrelatedField(gauss_model)
    impl_test_cov_func(impl, gauss, random_points, n_terms_range=n_terms)
    # Random points exp model
    exp_model = gstools.Exponential(dim=random_points.dim, len_scale=len_scale)
    impl = GSToolsSpatialCorrelatedField(exp_model)
    impl_test_cov_func(impl, exponential, random_points, n_terms_range=n_terms)
예제 #19
0
파일: flow_mc.py 프로젝트: GeoMop/MLMC
def create_corr_field(model='gauss',
                      corr_length=0.125,
                      dim=2,
                      log=True,
                      sigma=1):
    """
    Create random fields
    :return:
    """
    len_scale = corr_length * 2 * np.pi

    if model == 'fourier':
        return cf.Fields([
            cf.Field(
                'conductivity',
                cf.FourierSpatialCorrelatedField('gauss',
                                                 dim=dim,
                                                 corr_length=corr_length,
                                                 log=log)),
        ])

    if model == 'exp':
        model = gstools.Exponential(dim=dim, var=sigma**2, len_scale=len_scale)
    elif model == 'TPLgauss':
        model = gstools.TPLGaussian(dim=dim, var=sigma**2, len_scale=len_scale)
    elif model == 'TPLexp':
        model = gstools.TPLExponential(dim=dim,
                                       var=sigma**2,
                                       len_scale=len_scale)
    elif model == 'TPLStable':
        model = gstools.TPLStable(dim=dim, var=sigma**2, len_scale=len_scale)
    else:
        model = gstools.Gaussian(dim=dim, var=sigma**2, len_scale=len_scale)

    return cf.Fields([
        cf.Field('conductivity',
                 cf.GSToolsSpatialCorrelatedField(model, log=log)),
    ])
예제 #20
0
setting the estimation directions in 3D.

Afterwards we will fit a model to this estimated variogram and show the result.
"""
import numpy as np
import gstools as gs
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

###############################################################################
# Generating synthetic field with anisotropy and rotation by Tait-Bryan angles.

dim = 3
# rotation around z, y, x
angles = [np.deg2rad(90), np.deg2rad(45), np.deg2rad(22.5)]
model = gs.Gaussian(dim=3, len_scale=[16, 8, 4], angles=angles)
x = y = z = range(50)
pos = (x, y, z)
srf = gs.SRF(model, seed=1001)
field = srf.structured(pos)

###############################################################################
# Here we generate the axes of the rotated coordinate system
# to get an impression what the rotation angles do.

# All 3 axes of the rotated coordinate-system
main_axes = gs.rotated_main_axes(dim, angles)
axis1, axis2, axis3 = main_axes

###############################################################################
# Now we estimate the variogram along the main axes. When the main axes are
예제 #21
0
"""
Anisotropy and Rotation
=======================

The internally used (semi-) variogram
represents the isotropic case for the model.
Nevertheless, you can provide anisotropy ratios by:
"""
import gstools as gs

model = gs.Gaussian(dim=3, var=2.0, len_scale=10, anis=0.5)
print(model.anis)
print(model.len_scale_vec)

###############################################################################
# As you can see, we defined just one anisotropy-ratio
# and the second transversal direction was filled up with ``1.``.
# You can get the length-scales in each direction by
# the attribute :any:`CovModel.len_scale_vec`. For full control you can set
# a list of anistropy ratios: ``anis=[0.5, 0.4]``.
#
# Alternatively you can provide a list of length-scales:

model = gs.Gaussian(dim=3, var=2.0, len_scale=[10, 5, 4])
model.plot("vario_spatial")
print("Anisotropy representations:")
print("Anis. ratios:", model.anis)
print("Main length scale", model.len_scale)
print("All length scales", model.len_scale_vec)

###############################################################################
예제 #22
0
Artificial data
^^^^^^^^^^^^^^^

Here we generate log-normal data following a Gaussian covariance model.
We will generate the "original" field on a 60x60 mesh, from which we will take
samples in order to pretend a situation of data-scarcity.
"""
import numpy as np
import gstools as gs
import matplotlib.pyplot as plt

# structured field with edge length of 50
x = y = range(51)
pos = gs.generate_grid([x, y])
model = gs.Gaussian(dim=2, var=1, len_scale=10)
srf = gs.SRF(model, seed=20170519, normalizer=gs.normalizer.LogNormal())
# generate the original field
srf(pos)

###############################################################################
# Here, we sample 60 points and set the conditioning points and values.

ids = np.arange(srf.field.size)
samples = np.random.RandomState(20210201).choice(ids, size=60, replace=False)

# sample conditioning points from generated field
cond_pos = pos[:, samples]
cond_val = srf.field[samples]

###############################################################################
예제 #23
0
Let's create an ensemble of conditioned random fields in 2D.
"""
import numpy as np
import matplotlib.pyplot as plt
import gstools as gs

# conditioning data (x, y, value)
cond_pos = [[0.3, 1.9, 1.1, 3.3, 4.7], [1.2, 0.6, 3.2, 4.4, 3.8]]
cond_val = [0.47, 0.56, 0.74, 1.47, 1.74]

# grid definition for output field
x = np.arange(0, 5, 0.1)
y = np.arange(0, 5, 0.1)

model = gs.Gaussian(dim=2, var=0.5, len_scale=5, anis=0.5, angles=-0.5)
krige = gs.Krige(model, cond_pos=cond_pos, cond_val=cond_val)
cond_srf = gs.CondSRF(krige)

###############################################################################
# We create a list containing the generated conditioned fields.

ens_no = 4
field = []
for i in range(ens_no):
    field.append(cond_srf.structured([x, y], seed=i))

###############################################################################
# Now let's have a look at the pairwise differences between the generated
# fields. We will see, that they coincide at the given conditions.
예제 #24
0
print(m2)
print(fit_m2)

format_ax(ax)
fig.tight_layout()
if save:
    fig.savefig(os.path.join("..", "results", "07_matern_tpl_0-5.pdf"),
                dpi=300)
    fig.show()

# model families

fig, ax = plt.subplots(figsize=[5, 3])

gau = gs.Gaussian(integral_scale=1)
exp = gs.Exponential(integral_scale=1)
nus = [0.5, 0.75, 1.0, 1.5, 2.0]
# ax = exp.plot(ax=ax, x_max=3, linestyle="-.", color="k")
ax = gau.plot(ax=ax, x_max=3, linestyle="-", color="k")
for i, nu in enumerate(nus):
    m = gs.Matern(integral_scale=1, nu=nu)
    ax = m.plot(
        ax=ax,
        x_max=3,
        label=f"Matern(nu={nu:.2})",
        linewidth=2,
        dashes=dashes(i),
        color="C0",
    )
format_ax(ax)
예제 #25
0
# sphinx_gallery_thumbnail_path = 'pics/GS_pyvista_cut.png'
import pyvista as pv

import gstools as gs

###############################################################################
# We create a structured grid with PyVista containing 50 segments on all three
# axes each with a length of 2 (whatever unit).

dim, spacing = (50, 50, 50), (2, 2, 2)
grid = pv.UniformGrid(dim, spacing)

###############################################################################
# Now we set up the SRF class as always. We'll use an anisotropic model.

model = gs.Gaussian(dim=3, len_scale=[16, 8, 4], angles=(0.8, 0.4, 0.2))
srf = gs.SRF(model, seed=19970221)

###############################################################################
# The PyVista mesh can now be directly passed to the :any:`SRF.mesh` method.
# When dealing with meshes, one can choose if the field should be generated
# on the mesh-points (`"points"`) or the cell-centroids (`"centroids"`).
#
# In addition we can set a name, under which the resulting field is stored
# in the mesh.

srf.mesh(grid, points="points", name="random-field")

###############################################################################
# Now we have access to PyVista's abundancy of methods to explore the field.
#
예제 #26
0
In the following we will show the influence of the nugget and
measurement errors.
"""

import numpy as np
import gstools as gs

# condtions
cond_pos = [0.3, 1.1, 1.9, 3.3, 4.7]
cond_val = [0.47, 0.74, 0.56, 1.47, 1.74]
cond_err = [0.01, 0.0, 0.1, 0.05, 0]
# resulting grid
gridx = np.linspace(0.0, 15.0, 151)
# spatial random field class
model = gs.Gaussian(dim=1, var=0.9, len_scale=1, nugget=0.1)

###############################################################################
# Here we will use Simple kriging (`unbiased=False`) to interpolate the given
# conditions.

krig = gs.krige.Krige(
    model=model,
    cond_pos=cond_pos,
    cond_val=cond_val,
    mean=1,
    unbiased=False,
    exact=False,
    cond_err=cond_err,
)
krig(gridx)
예제 #27
0
import pyvista as pv

import gstools as gs

# mainly for setting a white background
pv.set_plot_theme("document")

###############################################################################
# create a uniform grid with PyVista
dims, spacing, origin = (40, 30, 10), (1, 1, 1), (-10, 0, 0)
mesh = pv.UniformGrid(dims=dims, spacing=spacing, origin=origin)

###############################################################################
# create an incompressible random 3d velocity field on the given mesh
# with added mean velocity in x-direction
model = gs.Gaussian(dim=3, var=3, len_scale=1.5)
srf = gs.SRF(model, mean=(0.5, 0, 0), generator="VectorField", seed=198412031)
srf.mesh(mesh, points="points", name="Velocity")

###############################################################################
# Now, we can do the plotting
streamlines = mesh.streamlines(
    "Velocity",
    terminal_speed=0.0,
    n_points=800,
    source_radius=2.5,
)

# set a fancy camera position
cpos = [(25, 23, 17), (0, 10, 0), (0, 0, 1)]
예제 #28
0
 def test_raise_error(self):
     self.assertRaises(ValueError, gs.CondSRF, gs.Gaussian())
     krige = gs.krige.Ordinary(gs.Stable(), self.cond_pos, self.cond_val)
     self.assertRaises(ValueError, gs.CondSRF, krige, generator="unknown")
예제 #29
0
import meshzoo
import meshio
import gstools as gs

# generate a triangulated hexagon with meshzoo
points, cells = meshzoo.ngon(6, 4)
mesh = meshio.Mesh(points, {"triangle": cells})

###############################################################################
# Now we prepare the SRF class as always. We will generate an ensemble of
# fields on the generated mesh.

# number of fields
fields_no = 12
# model setup
model = gs.Gaussian(dim=2, len_scale=0.5)
srf = gs.SRF(model, mean=1)

###############################################################################
# To generate fields on a mesh, we provide a separate method: :any:`SRF.mesh`.
# First we generate fields on the mesh-centroids controlled by a seed.
# You can specify the field name by the keyword `name`.

for i in range(fields_no):
    srf.mesh(mesh, points="centroids", name="c-field-{}".format(i), seed=i)

###############################################################################
# Now we generate fields on the mesh-points again controlled by a seed.

for i in range(fields_no):
    srf.mesh(mesh, points="points", name="p-field-{}".format(i), seed=i)
예제 #30
0
.. math:: S(k) = \left(\frac{1}{2\pi}\right)^n \cdot
    \frac{(2\pi)^{n/2}}{(bk)^{n/2-1}}
    \int_0^\infty r^{n/2-1} C(r) J_{n/2-1}(bkr) r dr

Where :math:`k=\left\Vert\mathbf{k}\right\Vert`.

Depending on the spectrum, the spectral-density is defined by:

.. math:: \tilde{S}(k) = \frac{S(k)}{\sigma^2}

You can access these methods by:
"""
import gstools as gs

model = gs.Gaussian(dim=3, var=2.0, len_scale=10)
ax = model.plot("spectrum")
model.plot("spectral_density", ax=ax)

###############################################################################
# .. note::
#    The spectral-density is given by the radius of the input phase. But it is
#    **not** a probability density function for the radius of the phase.
#    To obtain the pdf for the phase-radius, you can use the methods
#    :any:`CovModel.spectral_rad_pdf`
#    or :any:`CovModel.ln_spectral_rad_pdf` for the logarithm.
#
#    The user can also provide a cdf (cumulative distribution function) by
#    defining a method called ``spectral_rad_cdf``
#    and/or a ppf (percent-point function)
#    by ``spectral_rad_ppf``.