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)
def fit_model_var(coords_df, x_c, y_c, values):
    # fit the model varigrom to the experimental variogram
    bin_num = 40  # number of bins in the experimental variogram

    # first get the coords and determine distances
    x_delta = max(x_c) - min(x_c)  # distance across x coords
    y_delta = max(y_c) - min(y_c)  # distance across y coords
    max_dist = np.sqrt(
        np.square(x_delta +
                  y_delta)) / 4  # assume correlated over 1/4 of distance

    # setup bins for the variogram
    bins_c = np.linspace(0, max_dist,
                         bin_num)  # bin edges in variogram, bin_num of bins

    # compute the experimental variogram
    bin_cent_c, gamma_c = gs.vario_estimate_unstructured((x_c, y_c), values,
                                                         bins_c)
    # bin_center_c is the "lag" of the bin, gamma_c is the value

    gamma_c = smooth(
        gamma_c, 5
    )  # smooth the experimental variogram to help fitting - moving window with 5 samples

    # fit the model variogram
    # potential models are: Gaussian, Exponential, Matern, Rational, Stable, Linear,
    #                       Circular, Spherical, and Intersection
    fit_var = gs.Stable(dim=2)
    fit_var.fit_variogram(bin_cent_c,
                          gamma_c,
                          nugget=False,
                          estimator='cressie')  # fit the model variogram

    # print('max distance', max_dist,'var len scale', fit_var.len_scale)
    # check to see of range of varigram is very small (problem with fit), it so, set it to a value
    # also check to see if it is too long and set it to a value
    if fit_var.len_scale < max_dist / 3:  # check if too short
        fit_var.len_scale = max_dist / 3  # set to value
        # print('too short, set len_scale to: ', max_dist/3)
    elif fit_var.len_scale > max_dist * 1.5:  # check if too long
        fit_var.len_scale = max_dist  # set to value
        # print('too long, set len_scale to: ', max_dist)

    plt_var = False
    if plt_var:
        # plot the variogram to show fit and print out variogram paramters
        # should make it save to pdf file
        ax1 = fit_var.plot(x_max=max_dist)  # plot model variogram
        ax1.plot(bin_cent_c, gamma_c)  # plot experimental variogram
        # krig_plots.savefig()
        plt.close('all')
    return fit_var
Example #3
0
 def test_fit_directional(self):
     model = gs.Stable(dim=3)
     bins = [0, 3, 6, 9, 12]
     model.len_scale_bounds = [0, 20]
     bin_center, emp_vario, counts = gs.vario_estimate(
         *(self.pos, self.field, bins),
         direction=model.main_axes(),
         mesh_type="structured",
         return_counts=True,
     )
     # check if this succeeds
     model.fit_variogram(bin_center, emp_vario, sill=1, return_r2=True)
     self.assertTrue(1 > model.anis[0] > model.anis[1])
     model.fit_variogram(bin_center, emp_vario, sill=1, anis=[0.5, 0.25])
     self.assertTrue(15 > model.len_scale)
     model.fit_variogram(bin_center, emp_vario, sill=1, weights=counts)
     len_save = model.len_scale
     model.fit_variogram(bin_center, emp_vario, sill=1, weights=counts[0])
     self.assertAlmostEqual(len_save, model.len_scale)
     # catch wrong dim for dir.-vario
     with self.assertRaises(ValueError):
         model.fit_variogram(bin_center, emp_vario[:2])
Example #4
0
#
# Now we want to interpolate the "measured" samples
# and we want to normalize the given data with the BoxCox transformation.
#
# Here we set up the kriging routine and use a :any:`Stable` model, that should
# be fitted automatically to the given data
# and we pass the :any:`BoxCox` normalizer in order to gain normality.
#
# The normalizer will be fitted automatically to the data,
# by setting ``fit_normalizer=True``.
#
# The covariance/variogram model will be fitted by an automatic workflow
# by setting ``fit_variogram=True``.

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,
)

###############################################################################
# First, let's have a look at the fitting results:

print(krige.model)
print(krige.normalizer)

###############################################################################
# As we see, it went quite well. Variance is a bit underestimated, but
Example #5
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")
Example #6
0
        ax = fig.add_subplot(121)
        u = np.linspace(0, 2 * np.pi, 100)
        x = np.cos(u)
        y = np.sin(u)
        ax.plot(x, y, color="b", alpha=0.1)
        ax.scatter(norm[0], norm[1])
        ax.set_aspect("equal")
    else:
        ax = fig.add_subplot(121)
        ax.bar(-1, np.sum(np.isclose(norm, -1)), color="C0")
        ax.bar(1, np.sum(np.isclose(norm, 1)), color="C0")
        ax.set_xticks([-1, 1])
        ax.set_xticklabels(("-1", "1"))
    ax.set_title("Direction sampling")

    ax = fig.add_subplot(122)
    x = np.linspace(0, 10 / generator.model.integral_scale)
    y = generator.model.spectral_rad_pdf(x)
    ax.plot(x, y, label="radial spectral density")
    sample_in = np.sum(rad <= np.max(x))
    ax.hist(rad[rad <= np.max(x)], bins=sample_in // 50, density=True)
    ax.set_xlim([0, np.max(x)])
    ax.set_title("Radius samples shown {}/{}".format(sample_in, len(rad)))
    ax.legend()
    fig.show()


model = gs.Stable(dim=3, alpha=1.5)
srf = gs.SRF(model, seed=2020)
plot_rand_meth_samples(srf.generator)
#   bin_center, gamma = gs.vario_estimate((x, y), field)
#
#
# Here, we can use :class:`skg.Variogram <skgstat.Variogram>`. 
# From the shown arguments, :func:`estimator <skgstat.Variogram.estimator>` and
# :func:`bin_func <skgstat.Variogram.bin_func>` are using the default values:

V = skg.Variogram(coords, field, n_lags=21, estimator='matheron', maxlag=45, bin_func='even')
bin_center, gamma = V.get_empirical(bin_center=True)


# %%
# And finally, the exact same code from the GSTools docs can be called:
# 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)

# %%
# Output the model
ax = fit_model.plot(x_max=max(bin_center))
ax.scatter(bin_center, gamma)
print(fit_model)

# %%
#
# 6.1.2 ``bin_center=False``
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# It is important to understand, that ``gstools`` and ``skgstat`` are handling lag bins different.
# While ``skgstat`` uses the upper limit, ``gstools`` assumes the bin center.
Example #8
0
 def test_raise(self):
     # no cond_pos/cond_val given
     self.assertRaises(ValueError, gs.krige.Krige, gs.Stable(), None, None)
scale of a covariance model. We provide two common scales with the covariance
model.

Integral scale
--------------

The `integral scale <https://en.wikipedia.org/wiki/Integral_length_scale>`_
of a covariance model is calculated by:

.. math:: I = \int_0^\infty \rho(r) dr

You can access it by:
"""
import gstools as gs

model = gs.Stable(dim=3, var=2.0, len_scale=10)
print("Main integral scale:", model.integral_scale)
print("All integral scales:", model.integral_scale_vec)


###############################################################################
# You can also specify integral length scales like the ordinary length scale,
# and len_scale/anis will be recalculated:

model = gs.Stable(dim=3, var=2.0, integral_scale=[10, 4, 2])
print("Anisotropy ratios:", model.anis)
print("Main length scale:", model.len_scale)
print("All length scales:", model.len_scale_vec)
print("Main integral scale:", model.integral_scale)
print("All integral scales:", model.integral_scale_vec)
Example #10
0
The resulting kriging variance describes the error variance of the log-values
of the target variable.

In this example we will use ordinary kriging.
"""
import numpy as np

import gstools as gs

# condtions
cond_pos = [0.3, 1.9, 1.1, 3.3, 4.7]
cond_val = [0.47, 0.56, 0.74, 1.47, 1.74]
# resulting grid
gridx = np.linspace(0.0, 15.0, 151)
# stable covariance model
model = gs.Stable(dim=1, var=0.5, len_scale=2.56, alpha=1.9)

###############################################################################
# In order to result in log-normal kriging, we will use the :any:`LogNormal`
# Normalizer. This is a parameter-less normalizer, so we don't have to fit it.
normalizer = gs.normalizer.LogNormal

###############################################################################
# Now we generate the interpolated field as well as the mean field.
# This can be done by setting `only_mean=True` in :any:`Krige.__call__`.
# The result is then stored as `mean_field`.
#
# In terms of log-normal kriging, this mean represents the geometric mean of
# the field.
krige = gs.krige.Ordinary(model, cond_pos, cond_val, normalizer=normalizer)
# interpolate the field