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:
objectA fitted variogram model
gamma(h) = nugget + psill * shape(h).- model
"spherical","exponential","gaussian"(aka"squared_exponential"/"rbf"– covariancepsill * exp(-(h/rng)**2)), or"matern".- Type:
- nugget
discontinuity at
h=0(measurement error / micro-scale variance).- Type:
- psill
partial sill (correlated variance);
nugget + psillis the total sill.- Type:
- rng
range (correlation length).
- Type:
- nu
Matern smoothness (ignored by other models).
- Type:
- anisotropy
optional
(angle_rad, ratio)geometric anisotropy – coordinates are rotated byangleand the minor axis scaled by1/ratiobefore distances are taken.
- Raises:
ValueError – if
modelis not implemented;nugget/psillare not finite and>= 0;rng/nuare not finite and> 0; oranisotropyis 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 unimplementedmodel, 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.anisotropyis normalized to a(angle, ratio)tuple so it cannot be a mutable pair either.- gamma(h)[source]
Evaluate the semivariogram at lag distances.
- empirical_variogram(coords, values, *, n_bins=15, max_dist=None)[source]
Binned empirical (semi-)variogram: mean
0.5 (z_i - z_j)^2by separation distance.max_distdefaults to half the largest pairwise distance. Bins aren_binsequal-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 exactlymax_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/countcover each non-empty distance bin.insufficient_evidenceisTrue(withreasonset and the other fields empty) only when no valid distinct pair falls within[0, max_dist]– e.g. amax_distnarrower than every pairwise distance – so no bin is identifiable; it isFalse(withreasonempty) whenever at least one bin is populated. Invalid geometry, fewer than two observations, or no distinct locations raise before distance computation.- Parameters:
- Return type:
- 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_FITpopulated bins, so nugget/partial sill/range are not identifiable from the data (seeempirical_variogram()).- Parameters:
- Return type:
Variogram
- ordinary_kriging(coords, values, variogram, query, *, noise=None)[source]
Ordinary kriging: BLUP of the field at
queryunder 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 homoscedasticvariogram.nuggetis used on the diagonal.
- Returns:
{'prediction', 'variance'}arrays of lengthq.- Raises:
ValueError – if
coords/values/queryare empty, mismatched in shape, or contain non-finite values, or ifnoiseis provided and is mismatched in shape, non-finite, or negative.- Return type:
- 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=0uses a constant drift,degree=1removes a linear trend, anddegree=2a 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/queryare empty, mismatched in shape, or contain non-finite values, or ifnoiseis provided and is mismatched in shape, non-finite, or negative.- Parameters:
- Return type:
- 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
csuch that standardised residualsresidual / sqrt(c * predicted_var)achieve at least thetargetempirical central coverage under a Gaussian predictive. Returns the variance multiplierc; multiplypredicted_varby it to recalibrate (generic GP/kriging variance recalibration). No fixed search caps are used.- Parameters:
- Returns:
The variance multiplier
c(> 0).- Raises:
ValueError – if
targetis not finite and strictly in(0, 1)– a target<= 0,>= 1, or NaN previously converged to a silent boundary scale factor (1e-6or1e6) instead of raising; ifpredicted_varandresidualsdo not have the same nonempty one-dimensional shape (a valid paired held-out sample is required); or if either contains non-finite values, orpredicted_varis 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:
- exception VarianceCalibrationError[source]
Bases:
ValueErrorBase error for a variance-calibration request that has no publishable finite factor.
- exception VarianceCalibrationUnidentifiable[source]
Bases:
VarianceCalibrationErrorRaised when the requested coverage holds without any identifiable positive scale.
- exception VarianceCalibrationOutOfRange[source]
Bases:
VarianceCalibrationErrorRaised when the required scale is outside the finite floating-point domain.