# gstools.covmodel.Matern

class gstools.covmodel.Matern(dim=3, var=1.0, len_scale=1.0, nugget=0.0, anis=1.0, angles=0.0, *, integral_scale=None, rescale=None, latlon=False, geo_scale=1.0, temporal=False, spatial_dim=None, var_raw=None, hankel_kw=None, **opt_arg)[source]

Bases: CovModel

The Matérn covariance model.

Notes

This model is given by the following correlation function [Rasmussen2003]:

$\rho(r) = \frac{2^{1-\nu}}{\Gamma\left(\nu\right)} \cdot \left(\sqrt{\nu}\cdot s\cdot\frac{r}{\ell}\right)^{\nu} \cdot \mathrm{K}_{\nu}\left(\sqrt{\nu}\cdot s\cdot\frac{r}{\ell}\right)$

Where the standard rescale factor is $$s=1$$. $$\Gamma$$ is the gamma function and $$\mathrm{K}_{\nu}$$ is the modified Bessel function of the second kind.

$$\nu$$ is a shape parameter and should be >= 0.2.

If $$\nu > 20$$, a gaussian model is used, since it represents the limiting case:

$\rho(r) = \exp\left(-\left(s\cdot\frac{r}{2\ell}\right)^2\right)$

References

Rasmussen2003

Rasmussen, C. E., “Gaussian processes in machine learning.” Summer school on machine learning. Springer, Berlin, Heidelberg, (2003)

Other Parameters

nu (float, optional) – Shape parameter. Standard range: [0.2, 30] Default: 1.0

Parameters
• dim (int, optional) – dimension of the model. Includes the temporal dimension if temporal is true. To specify only the spatial dimension in that case, use spatial_dim. Default: 3

• var (float, optional) – variance of the model (the nugget is not included in “this” variance) Default: 1.0

• len_scale (float or list, optional) – length scale of the model. If a single value is given, the same length-scale will be used for every direction. If multiple values (for main and transversal directions) are given, anis will be recalculated accordingly. If only two values are given in 3D, the latter one will be used for both transversal directions. Default: 1.0

• nugget (float, optional) – nugget of the model. Default: 0.0

• anis (float or list, optional) –

anisotropy ratios in the transversal directions [e_y, e_z].

• e_y = l_y / l_x

• e_z = l_z / l_x

If only one value is given in 3D, e_y will be set to 1. This value will be ignored, if multiple len_scales are given. Default: 1.0

• angles (float or list, optional) –

angles of rotation (given in rad):

• in 2D: given as rotation around z-axis

• in 3D: given by yaw, pitch, and roll (known as Tait–Bryan angles)

Default: 0.0

• integral_scale (float or list or None, optional) – If given, len_scale will be ignored and recalculated, so that the integral scale of the model matches the given one. Default: None

• rescale (float or None, optional) – Optional rescaling factor to divide the length scale with. This could be used for unit conversion or rescaling the length scale to coincide with e.g. the integral scale. Will be set by each model individually. Default: None

• latlon (bool, optional) – Whether the model is describing 2D fields on earths surface described by latitude and longitude. When using this, the model will internally use the associated ‘Yadrenko’ model to represent a valid model. This means, the spatial distance $$r$$ will be replaced by $$2\sin(\alpha/2)$$, where $$\alpha$$ is the great-circle distance, which is equal to the spatial distance of two points in 3D. As a consequence, dim will be set to 3 and anisotropy will be disabled. geo_scale can be set to e.g. earth’s radius, to have a meaningful len_scale parameter. Default: False

• geo_scale (float, optional) – Geographic unit scaling in case of latlon coordinates to get a meaningful length scale unit. By default, len_scale is assumed to be in radians with latlon=True. Can be set to KM_SCALE to have len_scale in km or DEGREE_SCALE to have len_scale in degrees. Default: RADIAN_SCALE

• temporal (bool, optional) – Create a metric spatio-temporal covariance model. Setting this to true will increase dim and field_dim by 1. spatial_dim will be field_dim - 1. The time-dimension is appended, meaning the pos tuple is (x,y,z,…,t). Default: False

• spatial_dim (int, optional) – spatial dimension of the model. If given, the model dimension will be determined from this spatial dimension and the possible temporal dimension if temporal is ture. Default: None

• var_raw (float or None, optional) – raw variance of the model which will be multiplied with CovModel.var_factor to result in the actual variance. If given, var will be ignored. (This is just for models that override CovModel.var_factor) Default: None

• hankel_kw (dict or None, optional) – Modify the init-arguments of hankel.SymmetricFourierTransform used for the spectrum calculation. Use with caution (Better: Don’t!). None is equivalent to {"a": -1, "b": 1, "N": 1000, "h": 0.001}. Default: None

• **opt_arg – Optional arguments are covered by these keyword arguments. If present, they are described in the section Other Parameters.

Attributes
angles

numpy.ndarray: Rotation angles (in rad) of the model.

anis

numpy.ndarray: The anisotropy factors of the model.

anis_bounds

list: Bounds for the nugget.

arg

list of str: Names of all arguments.

arg_bounds

dict: Bounds for all parameters.

arg_list

list of float: Values of all arguments.

dim

int: The dimension of the model.

dist_func

tuple of callable: pdf, cdf and ppf.

do_rotation

bool: State if a rotation is performed.

field_dim

int: The (parametric) field dimension of the model (with time).

geo_scale

float: Geographic scaling for geographical coords.

hankel_kw
has_cdf

bool: State if a cdf is defined by the user.

has_ppf

bool: State if a ppf is defined by the user.

integral_scale

float: The main integral scale of the model.

integral_scale_vec

numpy.ndarray: The integral scales in each direction.

is_isotropic

bool: State if a model is isotropic.

iso_arg

list of str: Names of isotropic arguments.

iso_arg_list

list of float: Values of isotropic arguments.

latlon

bool: Whether the model depends on geographical coords.

len_rescaled

float: The rescaled main length scale of the model.

len_scale

float: The main length scale of the model.

len_scale_bounds

list: Bounds for the length scale.

len_scale_vec

numpy.ndarray: The length scales in each direction.

name

str: The name of the CovModel class.

nugget

float: The nugget of the model.

nugget_bounds

list: Bounds for the nugget.

opt_arg

list of str: Names of the optional arguments.

opt_arg_bounds

dict: Bounds for the optional arguments.

pykrige_angle

2D rotation angle for pykrige.

pykrige_angle_x

3D rotation angle around x for pykrige.

pykrige_angle_y

3D rotation angle around y for pykrige.

pykrige_angle_z

3D rotation angle around z for pykrige.

pykrige_anis

2D anisotropy ratio for pykrige.

pykrige_anis_y

3D anisotropy ratio in y direction for pykrige.

pykrige_anis_z

3D anisotropy ratio in z direction for pykrige.

pykrige_kwargs

Keyword arguments for pykrige routines.

rescale

float: Rescale factor for the length scale of the model.

sill

float: The sill of the variogram.

spatial_dim

int: The spatial field dimension of the model (without time).

temporal

bool: Whether the model is a metric spatio-temporal one.

var

float: The variance of the model.

var_bounds

list: Bounds for the variance.

var_raw

float: The raw variance of the model without factor.

Methods

 anisometrize(pos) Bring a position tuple into the anisotropic coordinate-system. Calculate the integral scale of the isotrope model. Check arguments to be within their given bounds. check_dim(dim) Check the given dimension. Run checks for the optional arguments. cor(h) Matérn normalized correlation function. cor_axis(r[, axis]) Correlation along axis of anisotropy. cor_spatial(pos) Spatial correlation respecting anisotropy and rotation. cor_yadrenko(zeta) Yadrenko correlation for great-circle distance from latlon-pos. correlation(r) Correlation function of the model. cov_axis(r[, axis]) Covariance along axis of anisotropy. cov_nugget(r) Isotropic covariance of the model respecting the nugget at r=0. cov_spatial(pos) Spatial covariance respecting anisotropy and rotation. cov_yadrenko(zeta) Yadrenko covariance for great-circle distance from latlon-pos. covariance(r) Covariance of the model. Provide default boundaries for arguments. Defaults for the optional arguments. Defaults for boundaries of the optional arguments. Provide default rescaling factor. fit_variogram(x_data, y_data[, anis, sill, ...]) Fitting the variogram-model to an empirical variogram. fix_dim() Set a fix dimension for the model. isometrize(pos) Make a position tuple ready for isotropic operations. Log radial spectral density of the model. Axes of the rotated coordinate-system. percentile_scale([per]) Calculate the percentile scale of the isotrope model. plot([func]) Plot a function of a the CovModel. pykrige_vario([args, r]) Isotropic variogram of the model for pykrige. set_arg_bounds([check_args]) Set bounds for the parameters of the model. Spectral density of the covariance model. Radial spectral density of the model. spectrum(k) Spectrum of the covariance model. Factor for the variance. vario_axis(r[, axis]) Variogram along axis of anisotropy. vario_nugget(r) Isotropic variogram of the model respecting the nugget at r=0. vario_spatial(pos) Spatial variogram respecting anisotropy and rotation. vario_yadrenko(zeta) Yadrenko variogram for great-circle distance from latlon-pos. variogram(r) Isotropic variogram of the model.
anisometrize(pos)

Bring a position tuple into the anisotropic coordinate-system.

calc_integral_scale()[source]

Calculate the integral scale of the isotrope model.

check_arg_bounds()

Check arguments to be within their given bounds.

check_dim(dim)

Check the given dimension.

check_opt_arg()

Run checks for the optional arguments.

This is in addition to the bound-checks

Notes

• You can use this to raise a ValueError/warning

• Any return value will be ignored

• This method will only be run once, when the class is initialized

cor(h)[source]

Matérn normalized correlation function.

cor_axis(r, axis=0)

Correlation along axis of anisotropy.

cor_spatial(pos)

Spatial correlation respecting anisotropy and rotation.

Yadrenko correlation for great-circle distance from latlon-pos.

correlation(r)

Correlation function of the model.

cov_axis(r, axis=0)

Covariance along axis of anisotropy.

cov_nugget(r)

Isotropic covariance of the model respecting the nugget at r=0.

cov_spatial(pos)

Spatial covariance respecting anisotropy and rotation.

Yadrenko covariance for great-circle distance from latlon-pos.

covariance(r)

Covariance of the model.

default_arg_bounds()

Provide default boundaries for arguments.

Given as a dictionary.

default_opt_arg()[source]

Defaults for the optional arguments.

• {"nu": 1.0}

Returns

Defaults for optional arguments

Return type

dict

default_opt_arg_bounds()[source]

Defaults for boundaries of the optional arguments.

• {"nu": [0.2, 30.0, "cc"]}

Returns

Boundaries for optional arguments

Return type

dict

default_rescale()

Provide default rescaling factor.

fit_variogram(x_data, y_data, anis=True, sill=None, init_guess='default', weights=None, method='trf', loss='soft_l1', max_eval=None, return_r2=False, curve_fit_kwargs=None, **para_select)

Fitting the variogram-model to an empirical variogram.

Parameters
• x_data (numpy.ndarray) – The bin-centers of the empirical variogram.

• y_data (numpy.ndarray) – The measured variogram If multiple are given, they are interpreted as the directional variograms along the main axis of the associated rotated coordinate system. Anisotropy ratios will be estimated in that case.

• anis (bool, optional) – In case of a directional variogram, you can control anisotropy by this argument. Deselect the parameter from fitting, by setting it “False”. You could also pass a fixed value to be set in the model. Then the anisotropy ratios wont be altered during fitting. Default: True

• sill (float or bool, optional) – Here you can provide a fixed sill for the variogram. It needs to be in a fitting range for the var and nugget bounds. If variance or nugget are not selected for estimation, the nugget will be recalculated to fulfill:

• sill = var + nugget

• if the variance is bigger than the sill, nugget will bet set to its lower bound and the variance will be set to the fitting partial sill.

If variance is deselected, it needs to be less than the sill, otherwise a ValueError comes up. Same for nugget. If sill=False, it will be deselected from estimation and set to the current sill of the model. Then, the procedure above is applied. Default: None

• init_guess (str or dict, optional) –

Initial guess for the estimation. Either:

• “default”: using the default values of the covariance model (“len_scale” will be mean of given bin centers; “var” and “nugget” will be mean of given variogram values (if in given bounds))

• “current”: using the current values of the covariance model

• dict: dictionary with parameter names and given value (separate “default” can bet set to “default” or “current” for unspecified values to get same behavior as given above (“default” by default)) Example: {"len_scale": 10, "default": "current"}

Default: “default”

• weights (str, numpy.ndarray, callable, optional) –

Weights applied to each point in the estimation. Either:

• ‘inv’: inverse distance 1 / (x_data + 1)

• list: weights given per bin

• callable: function applied to x_data

If callable, it must take a 1-d ndarray. Then weights = f(x_data). Default: None

• method ({‘trf’, ‘dogbox’}, optional) –

Algorithm to perform minimization.

• ‘trf’ : Trust Region Reflective algorithm, particularly suitable for large sparse problems with bounds. Generally robust method.

• ‘dogbox’ : dogleg algorithm with rectangular trust regions, typical use case is small problems with bounds. Not recommended for problems with rank-deficient Jacobian.

Default: ‘trf’

• loss (str or callable, optional) – Determines the loss function in scipys curve_fit. The following keyword values are allowed:

• ‘linear’ (default) : rho(z) = z. Gives a standard least-squares problem.

• ‘soft_l1’ : rho(z) = 2 * ((1 + z)**0.5 - 1). The smooth approximation of l1 (absolute value) loss. Usually a good choice for robust least squares.

• ‘huber’ : rho(z) = z if z <= 1 else 2*z**0.5 - 1. Works similarly to ‘soft_l1’.

• ‘cauchy’ : rho(z) = ln(1 + z). Severely weakens outliers influence, but may cause difficulties in optimization process.

• ‘arctan’ : rho(z) = arctan(z). Limits a maximum loss on a single residual, has properties similar to ‘cauchy’.

If callable, it must take a 1-d ndarray z=f**2 and return an array_like with shape (3, m) where row 0 contains function values, row 1 contains first derivatives and row 2 contains second derivatives. Default: ‘soft_l1’

• max_eval (int or None, optional) – Maximum number of function evaluations before the termination. If None (default), the value is chosen automatically: 100 * n.

• return_r2 (bool, optional) – Whether to return the r2 score of the estimation. Default: False

• curve_fit_kwargs (dict, optional) – Other keyword arguments passed to scipys curve_fit. Default: None

• **para_select – You can deselect parameters from fitting, by setting them “False” using their names as keywords. You could also pass fixed values for each parameter. Then these values will be applied and the involved parameters wont be fitted. By default, all parameters are fitted.

Returns

• fit_para (dict) – Dictionary with the fitted parameter values

• pcov (numpy.ndarray) – The estimated covariance of popt from scipy.optimize.curve_fit. To compute one standard deviation errors on the parameters use perr = np.sqrt(np.diag(pcov)).

• r2_score (float, optional) – r2 score of the curve fitting results. Only if return_r2 is True.

Notes

You can set the bounds for each parameter by accessing CovModel.set_arg_bounds.

The fitted parameters will be instantly set in the model.

fix_dim()

Set a fix dimension for the model.

isometrize(pos)

Make a position tuple ready for isotropic operations.

Log radial spectral density of the model.

main_axes()

Axes of the rotated coordinate-system.

percentile_scale(per=0.9)

Calculate the percentile scale of the isotrope model.

This is the distance, where the given percentile of the variance is reached by the variogram

plot(func='variogram', **kwargs)

Plot a function of a the CovModel.

Parameters
• func (str, optional) –

Function to be plotted. Could be one of:

• “variogram”

• “covariance”

• “correlation”

• “vario_spatial”

• “cov_spatial”

• “cor_spatial”

• “vario_axis”

• “cov_axis”

• “cor_axis”

• “spectrum”

• “spectral_density”

• **kwargs – Keyword arguments forwarded to the plotting function “plot_” + func in gstools.covmodel.plot.

pykrige_vario(args=None, r=0)

Isotropic variogram of the model for pykrige.

set_arg_bounds(check_args=True, **kwargs)

Set bounds for the parameters of the model.

Parameters
• check_args (bool, optional) – Whether to check if the arguments are in their valid bounds. In case not, a proper default value will be determined. Default: True

• **kwargs – Parameter name as keyword (“var”, “len_scale”, “nugget”, <opt_arg>) and a list of 2 or 3 values: [a, b] or [a, b, <type>] where <type> is one of "oo", "cc", "oc" or "co" to define if the bounds are open (“o”) or closed (“c”).

spectral_density(k)[source]

Spectral density of the covariance model.

This is given by:

$\tilde{S}(k) = \frac{S(k)}{\sigma^2}$

Where $$S(k)$$ is the spectrum of the covariance model.

Parameters

k (float) – Radius of the phase: $$k=\left\Vert\mathbf{k}\right\Vert$$

Radial spectral density of the model.

spectrum(k)

Spectrum of the covariance model.

This is given by:

$S(\mathbf{k}) = \left(\frac{1}{2\pi}\right)^n \int C(r) e^{i \mathbf{k}\cdot\mathbf{r}} d^n\mathbf{r}$

Internally, this is calculated by the hankel transformation:

$S(k) = \left(\frac{1}{2\pi}\right)^n \cdot \frac{(2\pi)^{n/2}}{k^{n/2-1}} \int_0^\infty r^{n/2} C(r) J_{n/2-1}(kr) dr$

Where $$C(r)$$ is the covariance function of the model.

Parameters

k (float) – Radius of the phase: $$k=\left\Vert\mathbf{k}\right\Vert$$

var_factor()

Factor for the variance.

vario_axis(r, axis=0)

Variogram along axis of anisotropy.

vario_nugget(r)

Isotropic variogram of the model respecting the nugget at r=0.

vario_spatial(pos)

Spatial variogram respecting anisotropy and rotation.

Yadrenko variogram for great-circle distance from latlon-pos.

variogram(r)

Isotropic variogram of the model.

property angles

Rotation angles (in rad) of the model.

Type

numpy.ndarray

property anis

The anisotropy factors of the model.

Type

numpy.ndarray

property anis_bounds

Bounds for the nugget.

Notes

Is a list of 2 or 3 values: [a, b] or [a, b, <type>] where <type> is one of "oo", "cc", "oc" or "co" to define if the bounds are open (“o”) or closed (“c”).

Type

list

property arg

Names of all arguments.

Type

list of str

property arg_bounds

Bounds for all parameters.

Notes

Keys are the arg names and values are lists of 2 or 3 values: [a, b] or [a, b, <type>] where <type> is one of "oo", "cc", "oc" or "co" to define if the bounds are open (“o”) or closed (“c”).

Type

dict

property arg_list

Values of all arguments.

Type
property dim

The dimension of the model.

Type

int

property dist_func

pdf, cdf and ppf.

Spectral distribution info from the model.

Type
property do_rotation

State if a rotation is performed.

Type

bool

property field_dim

The (parametric) field dimension of the model (with time).

Type

int

property geo_scale

Geographic scaling for geographical coords.

Type

float

property hankel_kw
Type

dict

property has_cdf

State if a cdf is defined by the user.

Type

bool

property has_ppf

State if a ppf is defined by the user.

Type

bool

property integral_scale

The main integral scale of the model.

Raises

ValueError – If integral scale is not setable.

Type

float

property integral_scale_vec

The integral scales in each direction.

Notes

This is calculated by:
• integral_scale_vec[0] = integral_scale

• integral_scale_vec[1] = integral_scale*anis[0]

• integral_scale_vec[2] = integral_scale*anis[1]

Type

numpy.ndarray

property is_isotropic

State if a model is isotropic.

Type

bool

property iso_arg

Names of isotropic arguments.

Type

list of str

property iso_arg_list

Values of isotropic arguments.

Type
property latlon

Whether the model depends on geographical coords.

Type

bool

property len_rescaled

The rescaled main length scale of the model.

Type

float

property len_scale

The main length scale of the model.

Type

float

property len_scale_bounds

Bounds for the length scale.

Notes

Is a list of 2 or 3 values: [a, b] or [a, b, <type>] where <type> is one of "oo", "cc", "oc" or "co" to define if the bounds are open (“o”) or closed (“c”).

Type

list

property len_scale_vec

The length scales in each direction.

Notes

This is calculated by:
• len_scale_vec[0] = len_scale

• len_scale_vec[1] = len_scale*anis[0]

• len_scale_vec[2] = len_scale*anis[1]

Type

numpy.ndarray

property name

The name of the CovModel class.

Type

str

property nugget

The nugget of the model.

Type

float

property nugget_bounds

Bounds for the nugget.

Notes

Is a list of 2 or 3 values: [a, b] or [a, b, <type>] where <type> is one of "oo", "cc", "oc" or "co" to define if the bounds are open (“o”) or closed (“c”).

Type

list

property opt_arg

Names of the optional arguments.

Type

list of str

property opt_arg_bounds

Bounds for the optional arguments.

Notes

Keys are the opt-arg names and values are lists of 2 or 3 values: [a, b] or [a, b, <type>] where <type> is one of "oo", "cc", "oc" or "co" to define if the bounds are open (“o”) or closed (“c”).

Type

dict

property pykrige_angle

2D rotation angle for pykrige.

property pykrige_angle_x

3D rotation angle around x for pykrige.

property pykrige_angle_y

3D rotation angle around y for pykrige.

property pykrige_angle_z

3D rotation angle around z for pykrige.

property pykrige_anis

2D anisotropy ratio for pykrige.

property pykrige_anis_y

3D anisotropy ratio in y direction for pykrige.

property pykrige_anis_z

3D anisotropy ratio in z direction for pykrige.

property pykrige_kwargs

Keyword arguments for pykrige routines.

property rescale

Rescale factor for the length scale of the model.

Type

float

property sill

The sill of the variogram.

Notes

This is calculated by:
• sill = variance + nugget

Type

float

property spatial_dim

The spatial field dimension of the model (without time).

Type

int

property temporal

Whether the model is a metric spatio-temporal one.

Type

bool

property var

The variance of the model.

Type

float

property var_bounds

Bounds for the variance.

Notes

Is a list of 2 or 3 values: [a, b] or [a, b, <type>] where <type> is one of "oo", "cc", "oc" or "co" to define if the bounds are open (“o”) or closed (“c”).

Type

list

property var_raw

The raw variance of the model without factor.

(See. CovModel.var_factor)

Type

float