gstools.covmodel.SumModel

class gstools.covmodel.SumModel(*models, **kwargs)[source]

Bases: CovModel

Class for sums of covariance models.

This class represents sums of covariance models. The nugget of each contained model will be set to zero and the sum model will have its own nugget. The variance of the sum model is the sum of the sub model variances and the length scale of the sum model is the variance-weighted sum of the length scales of the sub models. This is motivated by the fact, that the integral scale of the sum model is equal to the variance-weighted sum of the integral scales of the sub models. An empty sum represents a pure Nugget model. Resetting the total variance or the total length scale will evenly scale the variances or length scales of the sub models. Sum models will have a constant rescale factor of one.

Parameters:
  • *models – tuple of CovModel instances or subclasses to sum. All models will get a nugget of zero and the nugget will be set in the SumModel directly. Models need to have matching temporal setting, latlon setting, anis, angles and geo_scale. The model dimension will be specified by the first given model.

  • 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 or dimension of the first given model (if instance).

  • vars (list of float, optional) – variances of the models. Will reset present variances.

  • len_scales (list of float, optional) – length scale of the models. Will reset present length scales.

  • nugget (float, optional) – nugget of the sum-model. All summed models will have a nugget of zero. 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 or anis of the first given model (if instance).

  • 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 or angles of the first given model (if instance).

  • 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

  • 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 or latlon config of the first given model (if instance).

  • 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 or geo_scale of the first given model (if instance).

  • 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 or temporal config of the first given model (if instance).

  • 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 (float, optional) – Total variance of the sum-model. Will evenly scale present variances.

  • len_scale (float or list, optional) – Total length scale of the sum-model. Will evenly scale present length scales.

  • **opt_arg – Optional arguments of the sub-models will have and added index of the sub-model. Also covers var_<i> and length_scale_<i> but they should preferably be set by vars and length_scales.

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

dict: hankel.SymmetricFourierTransform kwargs.

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.

len_scales

list: The main length scales of the models.

models

tuple: The summed models.

name

str: The name of the CovModel class.

needs_fourier_transform

Whether the model doesn’t implement an analytical spectral density.

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.

ratios

numpy.ndarray: Variance ratios of the sub-models.

rescale

float: SumModel has a constant rescale factor of one.

sill

float: The sill of the variogram.

size

int: Number of summed models.

spatial_dim

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

sub_arg

list of str: Names of the sub-arguments for var and len_scale.

sub_arg_bounds

dict: Names of the sub-arguments for var and len_scale.

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.

vars

list: The variances of the models.

Methods

anisometrize(pos)

Bring a position tuple into the anisotropic coordinate-system.

calc_integral_scale()

Calculate the integral scale of the isotrope model.

check()

Check consistency of contained models.

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.

cor(h)

Correlation taking a non-dimensional range.

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)

SumModel correlation function.

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.

default_arg_bounds()

Default boundaries for arguments as dict.

default_opt_arg()

Provide default optional arguments by the user.

default_opt_arg_bounds()

Defaults boundaries for optional arguments as dict.

default_rescale()

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.

ln_spectral_rad_pdf(r)

Log radial spectral density of the model.

main_axes()

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.

set_len_weights(weights[, skip, len_scale])

Set length scales of contained models by weights.

set_var_weights(weights[, skip, var])

Set variances of contained models by weights.

spectral_density(k)

Spectral density of the covariance model.

spectral_rad_pdf(r)

Radial spectral density of the model.

spectrum(k)

Spectrum of the covariance model.

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()[source]

Check consistency of contained models.

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)

Correlation taking a non-dimensional range.

cor_axis(r, axis=0)

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)[source]

SumModel correlation function.

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.

cov_yadrenko(zeta)

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

covariance(r)

Covariance of the model.

default_arg_bounds()[source]

Default boundaries for arguments as dict.

default_opt_arg()

Provide default optional arguments by the user.

Should be given as a dictionary when overridden.

default_opt_arg_bounds()[source]

Defaults boundaries for optional arguments as 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.

ln_spectral_rad_pdf(r)

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_yadrenko”

    • “cov_yadrenko”

    • “cor_yadrenko”

    • “vario_axis”

    • “cov_axis”

    • “cor_axis”

    • “spectrum”

    • “spectral_density”

    • “spectral_rad_pdf”

  • **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”).

set_len_weights(weights, skip=None, len_scale=None)[source]

Set length scales of contained models by weights.

The variances of the sub-models act as ratios for the sub-model length scales to determine the total length scale of the sum-model. This function enables to keep the total length scale of the sum-model as well as the variances of the sub-models and reset the individual length scales of the contained sub-models by the given weights.

Parameters:
  • weights (iterable) – Weights to set. Should have a length of len(models) - len(skip)

  • skip (iterable, optional) – Model indices to skip. Should have compatible length, by default None

  • len_scale (float, optional) – Desired len_scale, by default current len_scale

Raises:

ValueError – If number of weights is not matching.

set_var_weights(weights, skip=None, var=None)[source]

Set variances of contained models by weights.

The variances of the sub-models act as ratios for the sum-model. This function enables to keep the total variance of the sum-model and reset the individual variances of the contained sub-models by the given weights.

Parameters:
  • weights (iterable) – Weights to set. Should have a length of len(models) - len(skip)

  • skip (iterable, optional) – Model indices to skip. Should have compatible length, by default None

  • var (float, optional) – Desired variance, by default current variance

Raises:

ValueError – If number of weights is not matching.

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

spectral_rad_pdf(r)

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

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.

vario_yadrenko(zeta)

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:

list of float

property dim

The dimension of the model.

Type:

int

property dist_func

pdf, cdf and ppf.

Spectral distribution info from the model.

Type:

tuple of callable

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

hankel.SymmetricFourierTransform kwargs.

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:

list of float

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 len_scales

The main length scales of the models.

Type:

list

property models

The summed models.

Type:

tuple

property name

The name of the CovModel class.

Type:

str

property needs_fourier_transform

Whether the model doesn’t implement an analytical spectral density.

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 ratios

Variance ratios of the sub-models.

Type:

numpy.ndarray

property rescale

SumModel has a constant rescale factor of one.

Type:

float

property sill

The sill of the variogram.

Notes

This is calculated by:
  • sill = variance + nugget

Type:

float

property size

Number of summed models.

Type:

int

property spatial_dim

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

Type:

int

property sub_arg

Names of the sub-arguments for var and len_scale.

Type:

list of str

property sub_arg_bounds

Names of the sub-arguments for var and len_scale.

Type:

dict

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 vars

The variances of the models.

Type:

list