Esempio n. 1
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)
Esempio n. 2
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)))
Esempio n. 3
0
 def test_multi_field(self):
     x = np.random.RandomState(19970221).rand(100) * 100.0
     model = gs.Exponential(dim=1, var=2, len_scale=10)
     srf = gs.SRF(model)
     field1 = srf(x, seed=19970221)
     field2 = srf(x, seed=20011012)
     bins = np.arange(20) * 2
     bin_center, gamma1 = gs.vario_estimate(x, field1, bins)
     bin_center, gamma2 = gs.vario_estimate(x, field2, bins)
     bin_center, gamma = gs.vario_estimate(x, [field1, field2], bins)
     gamma_mean = 0.5 * (gamma1 + gamma2)
     for i in range(len(gamma)):
         self.assertAlmostEqual(gamma[i], gamma_mean[i], places=2)
Esempio n. 4
0
    def test_extdrift(self):
        ext_drift = []
        cond_drift = []
        for i, grid in enumerate(self.grids):
            dim = i + 1
            model = gs.Exponential(
                dim=dim,
                var=2,
                len_scale=10,
                anis=[0.9, 0.8],
                angles=[2, 1, 0.5],
            )
            srf = gs.SRF(model)
            field = srf(grid)
            ext_drift.append(field)
            field = field.reshape(self.grid_shape[:dim])
            cond_drift.append(field[self.data_idx[:dim]])

        for Model in self.cov_models:
            for dim in self.dims:
                model = Model(
                    dim=dim,
                    var=2,
                    len_scale=10,
                    anis=[0.5, 0.2],
                    angles=[0.4, 0.2, 0.1],
                )
                extdrift = gs.krige.ExtDrift(
                    model,
                    self.cond_pos[:dim],
                    self.cond_val,
                    cond_drift[dim - 1],
                )
                field_1, __ = extdrift.unstructured(
                    self.grids[dim - 1], ext_drift=ext_drift[dim - 1]
                )
                field_1 = field_1.reshape(self.grid_shape[:dim])
                field_2, __ = extdrift.structured(
                    self.pos[:dim], ext_drift=ext_drift[dim - 1]
                )
                # extdrift.plot()
                self.assertAlmostEqual(
                    np.max(np.abs(field_1 - field_2)), 0.0, places=2
                )
                for i, val in enumerate(self.cond_val):
                    self.assertAlmostEqual(
                        field_2[self.data_idx[:dim]][i], val, places=2
                    )
Esempio n. 5
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)
Esempio n. 6
0
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)),
    ])
Esempio n. 7
0
 def setUp(self):
     model = gs.Exponential(dim=3, len_scale=[12, 6, 3])
     x = y = z = range(10)
     self.pos = (x, y, z)
     srf = gs.SRF(model, seed=123456)
     self.field = srf((x, y, z), mesh_type="structured")
Esempio n. 8
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)
fig.tight_layout()
Esempio n. 9
0
# the grid
x = np.arange(100)
y = np.arange(100)

# a smooth Gaussian covariance model
model = gs.Gaussian(dim=2, var=1, len_scale=10)
srf = gs.SRF(model, generator="VectorField", seed=19841203)
srf((x, y), mesh_type="structured")
srf.plot()

###############################################################################
# Let us have a look at the influence of the covariance model. Choosing the
# exponential model and keeping all other parameters the same

# a rougher exponential covariance model
model2 = gs.Exponential(dim=2, var=1, len_scale=10)
srf.model = model2
srf((x, y), mesh_type="structured", seed=19841203)
srf.plot()

###############################################################################
# and we see, that the wiggles are much "rougher" than the smooth Gaussian ones.

###############################################################################
# Applications
# ------------
#
# One great advantage of the Kraichnan method is, that after some initializations,
# one can compute the velocity field at arbitrary points, online, with hardly any
# overhead.
# This means, that for a Lagrangian transport simulation for example, the velocity
Esempio n. 10
0
7. ...

The rotation direction in these planes have alternating signs
in order to match Tait-Bryan in 3D.

Let's have a look at a 4D example, where we naively add a 4th dimension.
"""

import matplotlib.pyplot as plt

import gstools as gs

dim = 4
size = 20
pos = [range(size)] * dim
model = gs.Exponential(dim=dim, len_scale=5)
srf = gs.SRF(model, seed=20170519)
field = srf.structured(pos)

###############################################################################
# In order to "prove" correctness, we can calculate an empirical variogram
# of the generated field and fit our model to it.

bin_center, vario = gs.vario_estimate(pos,
                                      field,
                                      sampling_size=2000,
                                      mesh_type="structured")
model.fit_variogram(bin_center, vario)
print(model)

###############################################################################
Esempio n. 11
0
"""
Creating Fancier Fields
-----------------------

Only using Gaussian covariance fields gets boring. Now we are going to create
much rougher random fields by using an exponential covariance model and we are going to make them anisotropic.

The code is very similar to the previous examples, but with a different
covariance model class :any:`Exponential`. As model parameters we a using
following

- variance :math:`\sigma^2=1`
- correlation length :math:`\lambda=(12, 3)^T`
- rotation angle :math:`\theta=\pi/8`

"""

import numpy as np
import gstools as gs

x = y = np.arange(100)
model = gs.Exponential(dim=2, var=1, len_scale=[12.0, 3.0], angles=np.pi / 8)
srf = gs.SRF(model, seed=20170519)
srf.structured([x, y])
srf.plot()

###############################################################################
# The anisotropy ratio could also have been set with

model = gs.Exponential(dim=2, var=1, len_scale=12, anis=0.25, angles=np.pi / 8)
Esempio n. 12
0
--------------------------------------------------

In this example, we demonstrate how to estimate a directional variogram by
setting the direction angles in 2D.

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

###############################################################################
# Generating synthetic field with anisotropy and a rotation of 22.5 degree.

angle = np.pi / 8
model = gs.Exponential(dim=2, len_scale=[10, 5], angles=angle)
x = y = range(100)
srf = gs.SRF(model, seed=123456)
field = srf((x, y), mesh_type="structured")

###############################################################################
# Now we are going to estimate a directional variogram with an angular
# tolerance of 11.25 degree and a bandwith of 8.

bins = range(0, 40, 2)
bin_center, dir_vario, counts = gs.vario_estimate(
    *((x, y), field, bins),
    direction=gs.rotated_main_axes(dim=2, angles=angle),
    angles_tol=np.pi / 16,
    bandwidth=8,
    mesh_type="structured",
Esempio n. 13
0
      \sigma^2\cdot\left(1-\rho\left(r\right)\right)+n

- ``CovModel.covariance`` : The (auto-)covariance of the model given by

  .. math::
      C\left(r\right)= \sigma^2\cdot\rho\left(r\right)

- ``CovModel.correlation`` : The (auto-)correlation
  (or normalized covariance) of the model given by

  .. math::
      \rho\left(r\right)

- ``CovModel.cor`` : The normalized correlation taking a
  normalized range given by:

  .. math::
      \mathrm{cor}\left(\frac{r}{\ell}\right) = \rho\left(r\right)


As you can see, it is the easiest way to define a covariance model by giving a
correlation function as demonstrated in the introductory example.
If one of the above functions is given, the others will be determined:
"""
import gstools as gs

model = gs.Exponential(dim=3, var=2.0, len_scale=10, nugget=0.5)
ax = model.plot("variogram")
model.plot("covariance", ax=ax)
model.plot("correlation", ax=ax)
Esempio n. 14
0
    sampling_seed=19920516,
)

###############################################################################
# The estimated variogram is calculated on the centre of the given bins,
# therefore, the ``bin_center`` array is also returned.

###############################################################################
# Fitting the Variogram
# ^^^^^^^^^^^^^^^^^^^^^
#
# Now, we can see, if the estimated variogram can be modelled by a common
# variogram model. Let's try the :any:`Exponential` model.

# fit an exponential model
fit_model = gs.Exponential(dim=2)
fit_model.fit_variogram(bin_center, gamma, nugget=False)

###############################################################################
# Finally, we can visualise some results. For quickly plotting a covariance
# model, GSTools provides some helper functions.

ax = fit_model.plot(x_max=max(bin_center))
ax.plot(bin_center, gamma)

###############################################################################
# That looks like a pretty good fit! By printing the model, we can directly see
# the fitted parameters

print(fit_model)
Esempio n. 15
0
"""
Fit Variogram with automatic binning
------------------------------------
"""
import numpy as np
import gstools as gs

###############################################################################
# Generate a synthetic field with an exponential model.

x = np.random.RandomState(19970221).rand(1000) * 100.0
y = np.random.RandomState(20011012).rand(1000) * 100.0
model = gs.Exponential(dim=2, var=2, len_scale=8)
srf = gs.SRF(model, mean=0, seed=19970221)
field = srf((x, y))
print(field.var())
###############################################################################
# Estimate the variogram of the field with automatic binning.

bin_center, gamma = gs.vario_estimate((x, y), field)
print("estimated bin number:", len(bin_center))
print("maximal bin distance:", max(bin_center))

###############################################################################
# Fit the variogram with a stable model (no nugget fitted).

fit_model = gs.Stable(dim=2)
fit_model.fit_variogram(bin_center, gamma, nugget=False)
print(fit_model)

###############################################################################
Esempio n. 16
0
import gstools as gs

# fix the seed for reproducibility
seed = 20170521
# spatial axis of 50km with a resolution of 1km
x = np.arange(0, 50, 1.0)
# half daily timesteps over three months
t = np.arange(0.0, 90.0, 0.5)

# total spatio-temporal dimension
st_dim = 1 + 1
# space-time anisotropy ratio given in units d / km
st_anis = 0.4

# an exponential variogram with a corr. lengths of 2d and 5km
model = gs.Exponential(dim=st_dim, var=1.0, len_scale=5.0, anis=st_anis)
# create a spatial random field instance
srf = gs.SRF(model, seed=seed)

pos, time = [x], [t]

# a Gaussian random field which is also saved internally for the transformations
srf.structured(pos + time)
P_gau = copy.deepcopy(srf.field)

###############################################################################
# Next, we could take care of the dry periods. Therefore we would simply
# introduce a lower threshold value. But we will combine this step with the
# next one. Anyway, for demonstration purposes, we will also do it with the
# threshold value now.
Esempio n. 17
0
We can even generate the same field realisation on different grids. Let's try
to merge two unstructured rectangular fields.

"""
# sphinx_gallery_thumbnail_number = 2
import numpy as np
import gstools as gs

# creating our own unstructured grid
seed = gs.random.MasterRNG(19970221)
rng = np.random.RandomState(seed())
x = rng.randint(0, 100, size=10000)
y = rng.randint(0, 100, size=10000)

model = gs.Exponential(dim=2, var=1, len_scale=[12, 3], angles=np.pi / 8)
srf = gs.SRF(model, seed=20170519)
field1 = srf((x, y))
srf.plot()
###############################################################################
# But now we extend the field on the right hand side by creating a new
# unstructured grid and calculating a field with the same parameters and the
# same seed on it:

# new grid
seed = gs.random.MasterRNG(20011012)
rng = np.random.RandomState(seed())
x2 = rng.randint(99, 150, size=10000)
y2 = rng.randint(20, 80, size=10000)

field2 = srf((x2, y2))