mixle.analysis.kriging module

Geostatistics: variograms and kriging (best linear unbiased spatial prediction).

Kriging predicts a spatially correlated field at unobserved locations and – unlike a black-box regressor – returns a prediction variance that grows with distance from data. The spatial correlation is encoded by a variogram gamma(h) (how fast values decorrelate with separation h):

  • empirical_variogram() / fit_variogram() – estimate and fit a variogram model (spherical / exponential / gaussian / matern; the Gaussian model is also reachable as "squared_exponential" / "rbf", its covariance being the squared-exponential kernel) with nugget (measurement error / micro-scale variance), sill (total variance), and range (correlation length), plus geometric anisotropy (direction-dependent range).

  • ordinary_kriging() – BLUP with an unknown constant mean; exact interpolation with no nugget, smoothing with one, and heteroscedastic (per-observation) noise.

  • universal_kriging() – kriging with a polynomial trend / external drift.

  • calibrate_variance() – rescale kriging variances so their predictive intervals hit a target coverage on held-out data (generic GP/kriging recalibration).

Coordinates are (n, d) arrays (typically d = 2); values are the measured field.

class Variogram(model, nugget, psill, rng, nu=1.5, anisotropy=None)[source]

Bases: object

A fitted variogram model gamma(h) = nugget + psill * shape(h).

model

"spherical", "exponential", "gaussian" (aka "squared_exponential" / "rbf" – covariance psill * exp(-(h/rng)**2)), or "matern".

Type:

str

nugget

discontinuity at h=0 (measurement error / micro-scale variance).

Type:

float

psill

partial sill (correlated variance); nugget + psill is the total sill.

Type:

float

rng

range (correlation length).

Type:

float

nu

Matern smoothness (ignored by other models).

Type:

float

anisotropy

optional (angle_rad, ratio) geometric anisotropy – coordinates are rotated by angle and the minor axis scaled by 1/ratio before distances are taken.

Type:

tuple[float, float] | None

Raises:

ValueError – if model is not implemented; nugget/psill are not finite and >= 0; rng/nu are not finite and > 0; or anisotropy is set with a non-finite angle or a ratio that is not finite and > 0 (a zero or negative ratio collapses or flips the minor axis, which previously produced NaN predictions and variances downstream instead of an error).

Parameters:

Frozen. Every kriging solver reads these fields directly and trusts the construction-time validation below without re-checking; while the record was mutable, setting rng = 0, a negative sill, an unimplemented model, or a collapsed anisotropy ratio after construction bypassed the whole check and put the invalid parameter straight into the solve. Freezing keeps the validated state true for the variogram’s lifetime, which is what those solvers assume. anisotropy is normalized to a (angle, ratio) tuple so it cannot be a mutable pair either.

gamma(h)[source]

Evaluate the semivariogram at lag distances.

Parameters:

h (ndarray)

Return type:

ndarray

cov_field(h)[source]

Covariance of the correlated field part (excludes the nugget): psill (1 - shape).

Parameters:

h (ndarray)

Return type:

ndarray

empirical_variogram(coords, values, *, n_bins=15, max_dist=None)[source]

Binned empirical (semi-)variogram: mean 0.5 (z_i - z_j)^2 by separation distance.

max_dist defaults to half the largest pairwise distance. Bins are n_bins equal-width intervals, left-closed and right-open ([edges[b], edges[b+1])) except the last, which is closed on both ends – so a pair separated by exactly max_dist (routine, not an edge case: e.g. the endpoints of an evenly spaced line always sit exactly on the default cutoff) lands in the last bin instead of being classified as “beyond the last bin” and silently dropped.

Returns:

{'lag', 'semivariance', 'count', 'insufficient_evidence', 'reason'} – lag / semivariance / count cover each non-empty distance bin. insufficient_evidence is True (with reason set and the other fields empty) only when no valid distinct pair falls within [0, max_dist] – e.g. a max_dist narrower than every pairwise distance – so no bin is identifiable; it is False (with reason empty) whenever at least one bin is populated. Invalid geometry, fewer than two observations, or no distinct locations raise before distance computation.

Parameters:
Return type:

dict[str, ndarray | bool | str]

fit_variogram(coords, values, *, model='spherical', n_bins=15, nu=1.5)[source]

Fit a variogram model to data by least squares on the empirical variogram.

Returns:

A fitted Variogram (nugget, partial sill, range).

Raises:

ValueError – if the empirical variogram has fewer than _MIN_POPULATED_BINS_FOR_FIT populated bins, so nugget/partial sill/range are not identifiable from the data (see empirical_variogram()).

Parameters:
Return type:

Variogram

ordinary_kriging(coords, values, variogram, query, *, noise=None)[source]

Ordinary kriging: BLUP of the field at query under an unknown constant mean.

Parameters:
  • coords (ndarray) – (n, d) data locations.

  • values (ndarray) – (n,) measured field.

  • variogram (Variogram) – a fitted Variogram.

  • query (ndarray) – (q, d) prediction locations.

  • noise (ndarray | None) – optional (n,) per-observation measurement variance (heteroscedastic nugget); if None the homoscedastic variogram.nugget is used on the diagonal.

Returns:

{'prediction', 'variance'} arrays of length q.

Raises:

ValueError – if coords/values/query are empty, mismatched in shape, or contain non-finite values, or if noise is provided and is mismatched in shape, non-finite, or negative.

Return type:

dict[str, ndarray]

universal_kriging(coords, values, variogram, query, *, degree=1, noise=None)[source]

Universal kriging: kriging with a polynomial spatial trend (drift) of the given degree.

degree=0 uses a constant drift, degree=1 removes a linear trend, and degree=2 a quadratic one. No other degree is implemented. Use when the field has a large-scale drift on top of the stationary residual the variogram describes. The selected drift basis must be full-rank with at least one observation per coefficient.

Returns:

{'prediction', 'variance'}.

Raises:

ValueError – if coords/values/query are empty, mismatched in shape, or contain non-finite values, or if noise is provided and is mismatched in shape, non-finite, or negative.

Parameters:
Return type:

dict[str, ndarray]

calibrate_variance(predicted_var, residuals, *, target=0.9)[source]

Scale factor that makes kriging predictive intervals hit a target coverage.

Finds the smallest observed order-statistic scale c such that standardised residuals residual / sqrt(c * predicted_var) achieve at least the target empirical central coverage under a Gaussian predictive. Returns the variance multiplier c; multiply predicted_var by it to recalibrate (generic GP/kriging variance recalibration). No fixed search caps are used.

Parameters:
  • predicted_var (ndarray) – (m,) held-out kriging variances (must be strictly positive).

  • residuals (ndarray) – (m,) held-out actual - predicted.

  • target (float) – desired central coverage (e.g. 0.9); must be finite and strictly in (0, 1).

Returns:

The variance multiplier c (> 0).

Raises:
  • ValueError – if target is not finite and strictly in (0, 1) – a target <= 0, >= 1, or NaN previously converged to a silent boundary scale factor (1e-6 or 1e6) instead of raising; if predicted_var and residuals do not have the same nonempty one-dimensional shape (a valid paired held-out sample is required); or if either contains non-finite values, or predicted_var is not strictly positive everywhere.

  • VarianceCalibrationUnidentifiable – if zero residuals already meet the target for every positive multiplier.

  • VarianceCalibrationOutOfRange – if the required factor is outside finite representable range.

Return type:

float

exception VarianceCalibrationError[source]

Bases: ValueError

Base error for a variance-calibration request that has no publishable finite factor.

exception VarianceCalibrationUnidentifiable[source]

Bases: VarianceCalibrationError

Raised when the requested coverage holds without any identifiable positive scale.

exception VarianceCalibrationOutOfRange[source]

Bases: VarianceCalibrationError

Raised when the required scale is outside the finite floating-point domain.