Geostatistics is a powerful branch of statistics that focuses on analyzing and making predictions about spatially correlated data. It’s widely used in fields like environmental science, natural resource management, agriculture, epidemiology, and geology, where understanding how things change across space is essential.
Nine parts take a spatial sample from a variogram to a kriged map, a simulation, and a case study.
Introduction to Geostatistical Analysis. This notebook, then Variogram Modeling.
Kriging. Simple, ordinary, and universal kriging, cokriging, and the same four methods on Great Plains soil organic carbon, including a JAX comparison.
Regression Kriging. Fit a trend with covariates and krige the residuals, using scikit-learn, H2O, PyTorch, TensorFlow, and a graph neural network.
Specialized Kriging. Indicator, 3-D, soft, disjunctive, and factorial kriging.
Spatio-Temporal Kriging. Spatio-temporal kriging, then residual models with a convolutional LSTM, a spatio-temporal graph network, and a graph transformer.
Poisson Kriging. Area-to-area and area-to-point disease rates, Poisson cokriging, and a spatio-temporal Poisson model.
Geostatistical Simulation. Sequential Gaussian and indicator simulation and co-simulation, direct sequential simulation, simulated annealing, plurigaussian simulation, and multiple-point methods, including SNESIM.
Bayesian kriging. Empirical Bayesian kriging, a full Bayesian model, GLM and transformed-Gaussian versions, a conjugate model, a one-call function, and correlation functions.
Capstones:
Groundwater Arsenic Risk in Bangladesh,
Arsenic Exposure and Cancer Risk from Groundwater and Rice,
Uncertainty of Geostatistical Risk Mapping of Paddy Soil Arsenic,
Cadmium in the Soils of the Conterminous USA,
Diabetes and Obesity in US Counties: Multivariate Poisson Cokriging,
Micronutrient Deficiency Mapping in Bangladesh Soils,
Sexually Transmitted Infections and HIV in California Counties: Poisson Kriging in Space, Time and Across Diseases, and
Spatio-Temporal Forecasting of Groundwater Levels in Rajshahi Division, Bangladesh.
A notebook at the folder root, bangladesh_groundwater_eda.ipynb, explores Bangladesh groundwater from 1985 to 2020.
Library: geolattice.geostatistics
Kriging
Kriging is a way to guess the value of something at a place you didn’t measure, using the places you did. Soil lead, rainfall, disease rate, elevation, anything that varies smoothly over space. What makes it special is that it doesn’t just average nearby points; it works out the smartest possible weighted average by first learning how your variable’s similarity decays with distance, and it hands you an uncertainty estimate for free.
Everything rests on one idea (Tobler’s first law): near things are more alike than distant things. Kriging’s whole job is to measure exactly how fast alikeness fades with distance, then use that to weight the neighbors.
the estimator is just a weighted average
To predict the value at an unsampled spot \(s_0\), you take a weighted sum of your \(n\) measurements:
The whole game is choosing the weights \(\lambda_i\). Two rules govern them: closer and better-connected points get more weight, and (for ordinary kriging) the weights must sum to 1, i.e. \(\sum \lambda_i = 1\), so the prediction is unbiased: no systematic over- or under-shooting.
Illustration of kriging weights: the closest sample exerts the strongest pull, the farthest the weakest. The four weights sum to 1.
The closest point (λ = 0.34) pulls the hardest; the farthest contributes least; the four weights sum to 1. But notice we haven’t said where those numbers come from yet. That’s the heart of kriging.
the variogram is the engine
Before computing any weight, kriging measures how your variable’s similarity decays with distance. The tool for this is the semivariogram. For every pair of points separated by distance \(h\), compute half the squared difference of their values, then average over all pairs at that distance:
Small \(h\) (nearby points) → small \(\gamma\) (very alike). Large \(h\) → larger \(\gamma\) (less alike), until it flattens out. Plotting \(\gamma\) against \(h\) gives the curve every kriging model is built on:The gray dots are your raw data (the empirical variogram); the purple line is a smooth model fitted through them (spherical, exponential, Gaussian, etc.).
Variogram
Three numbers define it:
Nugget: where the curve meets the y-axis. In theory two points at zero distance should be identical (γ = 0), so any gap here is measurement noise or variation finer than your sampling.
Sill: the plateau. Beyond this, points are so far apart they’re effectively unrelated; it equals the overall variance of the data.
Range: the distance at which the curve reaches the sill. Inside the range, points inform each other; past it, they don’t. This is literally “how far does the neighborhood extend.”
solve for the weights
Now the payoff. Kriging picks the weights that minimize the prediction error variance subject to the unbiasedness constraint. Solving that constrained optimization (via a Lagrange multiplier \(\mu\)) gives a tidy linear system: one equation per sample point, plus one for the constraint:
The left matrix \(\mathbf{A}\) contains the variogram value between every pair of samples, this is what lets kriging de-cluster: two samples sitting on top of each other are near-redundant, and the matrix automatically splits their weight instead of double-counting them. The right vector \(\mathbf{b}\) contains the variogram value between each sample and the target location, this is what makes closer, better-connected points get more weight. Every \(\gamma\) in there is read straight off the fitted curve from Step 2.
Uncertainty map
Because kriging minimized error variance, it can also report that minimized variance at every point:
This is why kriging beats simple inverse-distance weighting: alongside the prediction map, you get a kriging variance map showing where predictions are trustworthy (dense sampling, low variance) and where they’re shaky (sparse areas, high variance), invaluable for deciding where to sample next.
Types of Variogram
A variogram describes how the similarity between sample points changes as the distance between them increases. It’s a plot (and mathematical function) that summarizes spatial correlation as distance grows, letting you see how much nearby values “know” about each other versus faraway ones. There are different types of variogram models: some flatten out beyond a certain distance (“bounded” types), while others keep rising (“unbounded” types). The shape you choose (spherical, exponential, Gaussian, etc.) controls how interpolation works, especially how smooth or sensitive your spatial predictions will be.
The experimental or empirical variogram is the cloud of points you compute directly from your data,
The theoretical (model) variogram, the smooth authorized function you fit through those points and actually feed to kriging and those split cleanly into bounded models (they flatten out at a sill) and unbounded ones (they rise forever, for data with a trend). Here’s how the common shapes compare with the same sill and range: The single most important thing to read off that plot is the behavior near the origin, because it dictates how smooth the resulting surface is: Gaussian leaves the origin flat (parabolic) → very smooth fields; spherical and exponential leave linearly → continuous but rougher; the power/linear model just keeps climbing → no sill at all.
Throughout, I’ll use \(c_0\) = nugget, \(c\) = partial sill, \(a\) = range, so total sill \(= c_0 + c\).
Bounded models (reach a sill)
These are for second-order stationary data: variance settles down at large distances.
Pure nugget: no spatial structure at all; \(\gamma(h)=c_0\) for \(h>0\) and \(0\) at \(h=0\). This is white noise; kriging with it just returns the global mean. Useful as a diagnostic (if your empirical variogram looks like this, there’s no correlation to exploit at your sampling scale).
Spherical: the workhorse in mining and soil science: \[\gamma(h)=c_0+c\left[\tfrac{3}{2}\tfrac{h}{a}-\tfrac{1}{2}\left(\tfrac{h}{a}\right)^3\right]\ \text{for } h\le a,\quad =c_0+c \text{ for } h>a\] It reaches the sill exactly at the range \(a\): a genuine “correlation stops here” distance, which is why it’s intuitive.
Exponential: rises fast then approaches the sill asymptotically: \[\gamma(h)=c_0+c\left[1-\exp\!\left(-\tfrac{h}{a}\right)\right]\] It never quite reaches the sill, so people quote a practical range of \(\approx 3a\) (95% of the sill). Good for phenomena with abrupt local variation. It’s also the Ornstein-Uhlenbeck / Markov correlation, so it shows up a lot in environmental data.
Gaussian: parabolic at the origin → extremely smooth interpolation: \[\gamma(h)=c_0+c\left[1-\exp\!\left(-\tfrac{h^2}{a^2}\right)\right]\] Practical range \(\approx a\sqrt{3}\). Beware: with a zero or tiny nugget it makes the kriging matrix nearly singular and produces unrealistic overshoots: always pair it with a small nugget.
Matérn: the general parent of the family, with an extra smoothness parameter \(\nu\): \[\gamma(h)=c_0+c\left[1-\tfrac{1}{2^{\nu-1}\Gamma(\nu)}\left(\tfrac{h}{a}\right)^{\nu}K_\nu\!\left(\tfrac{h}{a}\right)\right]\] where \(K_\nu\) is the modified Bessel function. It contains the others as special cases: \(\nu=0.5\) gives exponential, \(\nu\to\infty\) gives Gaussian. Instead of guessing which shape fits, you let the data estimate \(\nu\). This is the modern default in spatial statistics (e.g. gstat, fields, most Gaussian-process libraries).
Also in this bucket, less common: circular, cubic, and pentaspherical: alternative bounded shapes that differ mainly in near-origin curvature; you’ll rarely need them over the four above plus Matérn.
Unbounded models (no sill)
These describe data with a trend or fractal-like behavior: variance keeps growing with distance, so the process isn’t stationary in the mean.
Power: \(\gamma(h)=c_0+b\,h^{\omega}\) with \(0<\omega<2\). The exponent controls roughness; \(\omega\to 2\) is smooth, small \(\omega\) is rough. Linear is just the \(\omega=1\) special case, \(\gamma(h)=c_0+bh\). The logarithmic (De Wijsian) model, \(\gamma(h)=c_0+b\ln(h)\), is the classic mining variant (only valid for regularized/block support, not as a point model). Unbounded variograms go with universal kriging or intrinsic kriging, where a trend is modeled separately.
Special-purpose
Hole-effect: a damped oscillation for periodic or cyclic phenomena (repeating ore bands, seasonal spatial patterns): \[\gamma(h)=c_0+c\left[1-\tfrac{\sin(h/a)}{h/a}\right]\] The dip below and rise above the sill encode negative-then-positive correlation at regular spacings.
Beyond the single univariate curve
The word “variogram” also extends in two directions that are genuinely different types, not just different shapes:
By direction: an omnidirectional variogram pools all point pairs regardless of orientation, while directional variograms compute \(\gamma\) within angular bands to detect anisotropy. If the range differs by direction (correlation reaches farther N-S than E-W) that’s geometric anisotropy; if the sill differs, it’s zonal anisotropy. This is often where the real modeling effort goes.
By what’s being correlated, the cross-variogram measures joint spatial covariation between two variables and is the engine of co-kriging; the indicator variogram is computed on a 0/1 threshold indicator of the variable and drives indicator kriging (for non-Gaussian data or probability mapping). There are also robust alternatives to the classic estimator, the madogram (uses \(|Z_i-Z_j|\) instead of squared differences) and rodogram (square-root differences), which resist outliers, plus relative variograms (general and pairwise) for data whose variability scales with the local mean.
One expert caveat that ties it all together: you can’t fit any curve you like. A valid model must be conditionally negative definite so the kriging system stays solvable and variances stay non-negative: that’s exactly why this short, blessed list of “authorized” models exists, and why nested combinations (a nugget plus a spherical plus another structure) are built by adding authorized models rather than inventing new ones.
The next notebook, 05_01_variogram_modeling.ipynb, fits these shapes on the Jura survey, including Matérn and a directional anisotropy check.
It measure how similarity fades with distance (the variogram), then solve a small linear system that turns that decay curve into optimal, de-clustered, unbiased weights for a weighted average: and get a built-in uncertainty estimate as a bonus.
Types Kriging
Kriging is a family of geostatistical interpolation algorithms used to predict values at unsampled locations based on observed data. At its core, kriging is a Best Linear Unbiased Predictor (BLUP).
The differences between the types of kriging lie in their assumptions about the mean (trend) of the spatial process and the resulting mathematical constraints used to solve for the weights \(\lambda_i\).
Simple Kriging (SK)
Assumption: The global mean of the spatial process is known and constant. (This is rare in practice but mathematically the simplest). Model:\(Z(x) = \mu + \epsilon(x)\), where \(\mu\) is a known constant and \(E[\epsilon(x)] = 0\).
Mathematics & Optimization: Because the mean is known, the predictor is inherently unbiased without restricting the sum of the weights. The goal is to minimize the estimation variance \(\sigma_{SK}^2 = E[(\hat{Z}_{SK}(x_0) - Z(x_0))^2]\).
Taking the derivative with respect to \(\lambda_i\) and setting it to zero yields the Simple Kriging System: \[ \sum_{j=1}^n \lambda_j C(x_i, x_j) = C(x_i, x_0) \quad \text{for } i = 1, \dots, n \]
In matrix form: \[ \mathbf{C} \boldsymbol{\lambda} = \mathbf{c}_0 \] * \(\mathbf{C}\) is the \(n \times n\) covariance matrix between data points: \(C_{ij} = C(x_i, x_j)\). * \(\mathbf{c}_0\) is the \(n \times 1\) covariance vector between data points and the prediction location: \(c_{0i} = C(x_i, x_0)\). * \(\boldsymbol{\lambda}\) is the vector of weights.
Ordinary Kriging (OK)
Assumption: The global mean is unknown but constant (intrinsic stationarity). This is the most commonly used form of kriging. Model:\(Z(x) = \mu + \epsilon(x)\), where \(\mu\) is an unknown constant.
Mathematics & Optimization: To ensure the predictor is unbiased (\(E[\hat{Z}_{OK}(x_0)] = \mu\)), the weights must sum to 1: \[ \sum_{i=1}^n \lambda_i = 1 \]
We minimize the variance \(\sigma_{OK}^2\) subject to this constraint using a Lagrange multiplier (\(\psi\)). The Lagrangian is: \[ \mathcal{L} = \sigma_{OK}^2 - 2\psi \left( \sum_{i=1}^n \lambda_i - 1 \right) \]
Taking derivatives and setting to zero yields the Ordinary Kriging System. It is traditionally written using the variogram\(\gamma(h)\) rather than covariance: \[ \sum_{j=1}^n \lambda_j \gamma(x_i, x_j) - \psi = \gamma(x_i, x_0) \quad \text{for } i = 1, \dots, n \]\[ \sum_{i=1}^n \lambda_i = 1 \]
In matrix form: \[ \begin{bmatrix} \mathbf{\Gamma} & \mathbf{1} \\ \mathbf{1}^T & 0 \end{bmatrix} \begin{bmatrix} \boldsymbol{\lambda} \\ \psi \end{bmatrix} = \begin{bmatrix} \boldsymbol{\gamma}_0 \\ 1 \end{bmatrix} \] * \(\mathbf{\Gamma}\) is the \(n \times n\) variogram matrix between data points. * \(\boldsymbol{\gamma}_0\) is the \(n \times 1\) variogram vector to the prediction location. * \(\mathbf{1}\) is a column vector of ones. * \(\psi\) is the Lagrange multiplier (which also represents the minimized kriging variance when multiplied out).
Universal Kriging (UK) / Kriging with a Trend
Assumption: The mean is not constant, but is a deterministic function of the spatial coordinates (a trend or polynomial). Model:\(E[Z(x)] = m(x) = \sum_{k=0}^K a_k f_k(x)\), where \(f_k(x)\) are known basis functions (e.g., \(1, x, y, x^2, xy\)) and \(a_k\) are unknown coefficients.
Mathematics & Optimization: For the predictor to be unbiased, the weights must perfectly reproduce the trend at the prediction location: \[ \sum_{i=1}^n \lambda_i f_k(x_i) = f_k(x_0) \quad \text{for } k = 0, \dots, K \]
This requires \(K+1\) Lagrange multipliers (\(\mu_k\)). The resulting Universal Kriging System is: \[ \sum_{j=1}^n \lambda_j C(x_i, x_j) + \sum_{k=0}^K \mu_k f_k(x_i) = C(x_i, x_0) \quad \text{for } i = 1, \dots, n \]\[ \sum_{i=1}^n \lambda_i f_k(x_i) = f_k(x_0) \quad \text{for } k = 0, \dots, K \]
In matrix form: \[ \begin{bmatrix} \mathbf{C} & \mathbf{F} \\ \mathbf{F}^T & \mathbf{0} \end{bmatrix} \begin{bmatrix} \boldsymbol{\lambda} \\ \boldsymbol{\mu} \end{bmatrix} = \begin{bmatrix} \mathbf{c}_0 \\ \mathbf{f}_0 \end{bmatrix} \] * \(\mathbf{F}\) is an \(n \times (K+1)\) matrix where \(F_{ik} = f_k(x_i)\). * \(\mathbf{f}_0\) is a \((K+1) \times 1\) vector where \(f_{0k} = f_k(x_0)\). * \(\boldsymbol{\mu}\) is the vector of Lagrange multipliers.
Co-Kriging (Multivariate Kriging)
Assumption: You are trying to predict a primary variable \(Z_1\), but you have secondary, cheaper-to-measure variables \(Z_2, \dots, Z_M\) that are spatially correlated with \(Z_1\).
Predictor:\[ \hat{Z}_1(x_0) = \sum_{m=1}^M \sum_{i=1}^{n_m} \lambda_{m,i} Z_m(x_{m,i}) \](Where \(n_m\) is the number of samples for variable \(m\)).
Mathematics & Optimization: The optimization minimizes the variance of the prediction error for \(Z_1\), subject to unbiasedness constraints for each variable. The math is identical to Ordinary Kriging, but the covariance/variogram matrices are replaced by block matrices of cross-covariances.
For two variables (\(Z_1\) and \(Z_2\)), the matrix system looks like this: \[ \begin{bmatrix}
\mathbf{C}_{11} & \mathbf{C}_{12} & \mathbf{1} & \mathbf{0} \\
\mathbf{C}_{21} & \mathbf{C}_{22} & \mathbf{0} & \mathbf{1} \\
\mathbf{1}^T & \mathbf{0}^T & 0 & 0 \\
\mathbf{0}^T & \mathbf{1}^T & 0 & 0
\end{bmatrix}
\begin{bmatrix}
\boldsymbol{\lambda}_1 \\
\boldsymbol{\lambda}_2 \\
\psi_1 \\
\psi_2
\end{bmatrix} =
\begin{bmatrix}
\mathbf{c}_{10} \\
\mathbf{c}_{20} \\
1 \\
1
\end{bmatrix} \] * \(\mathbf{C}_{11}\) is the auto-covariance of \(Z_1\). * \(\mathbf{C}_{12}\) is the cross-covariance between \(Z_1\) and \(Z_2\). * \(\boldsymbol{\lambda}_1\) and \(\boldsymbol{\lambda}_2\) are the weight vectors for the two variables.
Indicator Kriging (IK)
Assumption: Used for categorical data, or to estimate the probability that a variable exceeds a certain threshold \(z\) (e.g., probability of soil lead levels exceeding safety limits).
Mathematics: IK transforms the continuous variable \(Z(x)\) into a binary indicator variable \(I(x; z)\): \[ I(x; z) = \begin{cases} 1 & \text{if } Z(x) \le z \\ 0 & \text{if } Z(x) > z \end{cases} \]
The expected value of the indicator is the probability: \(E[I(x; z)] = P(Z(x) \le z)\).
IK is mathematically identical to Ordinary Kriging, but it is applied to the binary indicator variable \(I\) instead of the raw data \(Z\). \[ \hat{I}(x_0; z) = \sum_{i=1}^n \lambda_i I(x_i; z) \] The resulting prediction \(\hat{I}(x_0; z)\) is an estimate of the conditional probability \(P(Z(x_0) \le z | \text{data})\). By running IK across multiple thresholds \(z\), you can reconstruct the entire local probability distribution at \(x_0\).
Regression Kriging (RK) / Residual Kriging
The Problem it Solves: Universal Kriging (UK) models a spatial trend, but if you have a massive dataset (e.g., \(n > 10,000\)), solving the massive \((n+K+1) \times (n+K+1)\) matrix for UK becomes computationally impossible. The Solution: Regression Kriging splits the prediction into two distinct, computationally cheaper steps: modeling the deterministic trend using auxiliary covariates (Regression), and then modeling the spatially correlated leftovers (Kriging).
Assumption: The spatial process is composed of a deterministic mean driven by external covariates, plus a spatially autocorrelated stochastic residual. Model:\(Z(x) = m(x) + e(x) = \mathbf{X}(x)\boldsymbol{\beta} + e(x)\) * \(\mathbf{X}(x)\) is a vector of auxiliary covariates at location \(x\) (e.g., elevation, satellite imagery). * \(\boldsymbol{\beta}\) is a vector of regression coefficients. * \(e(x)\) is the spatially correlated residual with \(E[e(x)] = 0\).
Mathematics & Optimization (The Two-Step Process): Unlike Universal Kriging which solves for trend and spatial correlation simultaneously via Generalized Least Squares (GLS), Regression Kriging is typically implemented in two steps using Ordinary Least Squares (OLS):
Step 1: Global Regression Estimate the trend coefficients \(\boldsymbol{\beta}\) using OLS across all data points: \[ \hat{\boldsymbol{\beta}} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{Z} \] Calculate the residuals at the sample locations: \[ \hat{e}(x_i) = Z(x_i) - \mathbf{X}(x_i)\hat{\boldsymbol{\beta}} \]
Step 2: Ordinary Kriging of Residuals Fit a variogram to the residuals \(\hat{e}(x_i)\) and apply standard Ordinary Kriging to predict the residual at the unsampled location: \[ \hat{e}(x_0) = \sum_{i=1}^n \lambda_i \hat{e}(x_i) \](Where \(\lambda_i\) are solved using the standard OK matrix system shown in the previous response).
Note on Equivalence: If Step 1 uses Generalized Least Squares (GLS) instead of OLS, incorporating the spatial covariance matrix \(\mathbf{C}\), Regression Kriging becomes mathematically identical to Universal Kriging. However, the OLS+OK two-step approach is heavily preferred in practice because inverting \(\mathbf{X}^T \mathbf{X}\) is vastly faster than inverting the spatial covariance matrix for large datasets.
Poisson Kriging (PK)
The Problem it Solves: Standard kriging assumes data is continuous and Gaussian. It fails for spatial count data (e.g., number of disease cases, crime incidents in a county). Count data follows a Poisson distribution, meaning the variance is tied to the mean. Furthermore, areas with small populations have highly unreliable rates (high variance), violating the assumption of homoscedasticity (constant variance). The Solution: Poisson Kriging smooths the observed rates by accounting for the population size, effectively filtering out the “Poisson noise” (random fluctuations due to small populations) to reveal the true underlying spatial risk.
Assumption: The observed counts \(Y(x_i)\) in area \(i\) follow a Poisson distribution. The underlying true relative risk \(\theta(x)\) is spatially correlated. Model:\[ Y(x_i) \sim \text{Poisson}(E_i \theta(x_i)) \] * \(E_i\) is the expected count (e.g., population at risk \(\times\) baseline disease rate). * \(\theta(x_i)\) is the true, unobserved relative risk. * The observed rate is \(Z(x_i) = Y(x_i) / E_i\).
Predictor:\[ \hat{\theta}_{PK}(x_0) = \sum_{i=1}^n \lambda_i Z(x_i) \] Subject to the unbiasedness constraint: \(\sum_{i=1}^n \lambda_i = 1\).
Mathematics & Optimization: Because the variance of the observed rate \(Z(x_i)\) is \(\theta(x_i)/E_i\), the variance changes depending on the population \(E_i\) (heteroscedasticity). If we just calculate a standard variogram of the rates \(Z\), it will be artificially inflated by this Poisson noise.
1. Deconvolution of the Variogram: Before kriging, we must separate the true spatial variance from the Poisson noise. The observed variogram of the rates \(\gamma_Z(h)\) is a convolution of the true risk variogram \(\gamma_\theta(h)\) and the Poisson noise: \[ \gamma_Z(h) = \gamma_\theta(h) + q(h) \] Where the noise term \(q(h)\) for a pair of locations \((i, j)\) separated by distance \(h\) is: \[ q(h) = \frac{\bar{\theta}}{2} \left( \frac{1}{E_i} + \frac{1}{E_j} \right) \](Here, \(\bar{\theta}\) is the global weighted average of the rates, estimated as \(\sum Y_i / \sum E_i\)). We calculate \(\gamma_Z(h)\) from the data, subtract the calculated noise \(q(h)\), and fit a model to get the deconvolved variogram\(\gamma_\theta(h)\).
2. The Modified Kriging System: We minimize the variance of the prediction error for the true risk \(\theta(x_0)\). Because the variance of the data points depends on their populations, the diagonal of the kriging matrix must be adjusted to include the Poisson variance for each specific location.
The Poisson Kriging System is: \[ \sum_{j \neq i}^n \lambda_j \gamma_\theta(x_i, x_j) + \lambda_i \left[ \gamma_\theta(0) + \frac{\bar{\theta}}{E_i} \right] - \psi = \gamma_\theta(x_i, x_0) \quad \text{for } i = 1, \dots, n \]\[ \sum_{i=1}^n \lambda_i = 1 \]
In matrix form: \[ \begin{bmatrix} \mathbf{\Gamma}^* + \mathbf{D} & \mathbf{1} \\ \mathbf{1}^T & 0 \end{bmatrix} \begin{bmatrix} \boldsymbol{\lambda} \\ \psi \end{bmatrix} = \begin{bmatrix} \boldsymbol{\gamma}_0 \\ 1 \end{bmatrix} \] * \(\mathbf{\Gamma}^*\) is the \(n \times n\) matrix of the deconvolved variogram \(\gamma_\theta(x_i, x_j)\). * \(\mathbf{D}\) is a diagonal matrix where \(D_{ii} = \frac{\bar{\theta}}{E_i}\). This adds the Poisson noise back only to the variance (the diagonal) of the specific data points, properly weighting areas with small populations. * \(\boldsymbol{\gamma}_0\) is the vector of the deconvolved variogram \(\gamma_\theta(x_i, x_0)\) to the prediction location (which does not include Poisson noise, because we are predicting the true underlying risk, not a noisy observation).
Summary of All Kriging Types
Type
Mean / Data Assumption
Key Constraint
Class
Simple (SK)
Known constant mean
None (no sum-to-one)
SimpleKriging
Ordinary (OK)
Unknown constant mean
\(\sum \lambda_i = 1\)
OrdinaryKriging
Universal (UK)
Polynomial trend
Reproduce trend at \(x_0\)
UniversalKriging
Regression (RK)
Trend via covariates (OLS/ML)
\(\sum \lambda_i = 1\) on residuals
RegressionKriging + deep variants
Co-Kriging
Unknown mean, multivariate
\(\sum \lambda_{m,i} = 1\) per variable
Cokriging, MultivariateCokriging
Indicator (IK)
Binary threshold probability
\(\sum \lambda_i = 1\)
IndicatorKriging
Disjunctive (DK)
Gaussian anamorphosis (Hermite)
\(\sum \lambda_i = 1\) per factor
DisjunctiveKriging
Factorial (FK)
Nested variogram decomposition
\(\sum \lambda_i = 1\) per component
FactorialKriging
Empirical Bayesian (EBK)
Bootstrap variogram ensemble
\(\sum \lambda_i = 1\)
EmpiricalBayesianKriging
Soft (SK-soft)
Soft probability / secondary data
\(\sum \lambda_i = 1\)
SoftKriging
Poisson (PK)
Count data, Poisson noise
\(\sum \lambda_i = 1\); modified diagonal
PoissonKriging, AreaPoissonKriging
Spatio-Temporal (ST)
Metric space-time variogram
\(\sum \lambda_i = 1\)
STKriging
ST Poisson
Count data + space-time covariance
\(\sum \lambda_i = 1\)
STPoissonKriging
GeoLattice geostatistics
Geostatistics in GeoLattice is geolattice.geostatistics (vendored PyGStat 0.1.1). It covers empirical variogram estimation (Matheron, Cressie-Hawkins, Dowd), theoretical model fitting, the kriging family (point, block, spatio-temporal, Poisson, and regression kriging), sequential simulation, and cross-validation. The same calls run on CPU (NumPy/SciPy) or GPU (CuPy), and accept GeoPandas, pandas, and NumPy inputs.
Install the extra in the kernel this notebook uses:
python-m pip install "geolattice[geostatistics]"
Optional backends: geolattice[geostatistics-gpu] (CuPy), geolattice[geostatistics-plot] (matplotlib), geolattice[geostatistics-pytorch], geolattice[geostatistics-tensorflow], and geolattice[geostatistics-h2o]. Submodules such as sisim and krigeST are imported from geolattice.geostatistics.
geolattice.geostatistics.__version__ is the vendored PyGStat release (0.1.1). The GeoLattice package version is separate (geolattice.__version__).
Validation & backends - loo_cv, kfold_cv: leave-one-out and k-fold CV for all core kriging types - KFoldCV_RK, LOOCV_RK, KFoldCV_Cokriging, IndicatorKrigingCV, KFoldCV_AutoML: type-specific helpers - GPU acceleration via CuPy (use_gpu='auto'); automatic CPU (NumPy/SciPy) fallback - Interoperable with GeoPandas (from_geodataframe), pandas, NumPy, scikit-learn - Heavy optional backends (H2O, PyTorch, TensorFlow) are lazy-imported: import geolattice.geostatistics never raises if they are absent
Quick start: Meuse zinc
The cells below use the Meuse heavy-metal survey shipped with GeoLattice (Data/00_shared/data_geostatistics/meuse.csv). Zinc is log-transformed, a spherical variogram is fitted, and ordinary kriging predicts a thinned copy of meuse_grid.csv. Leave-one-out cross-validation reports RMSE and R² on the log scale.
Paths are resolved from the repository root, so the notebook can be started from this folder or from the GeoLattice root.
Installation. This notebook needs installation option 4 (core, spatial analysis, spatial statistics and geostatistics): pip install "geolattice[geostats]". See “Installation options” in the GeoLattice README.
Code
%matplotlib inlinefrom pathlib import Pathimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport geolatticeimport geolattice.geostatistics as gstatfrom geolattice.geostatistics import OrdinaryKriging, Variogram, loo_cvprint("geolattice", geolattice.__version__)print("geolattice.geostatistics", gstat.__version__)ROOT = Path.cwd().resolve()whilenot (ROOT /"Data"/"00_shared"/"data_geostatistics"/"meuse.csv").is_file():if ROOT.parent == ROOT:raiseFileNotFoundError("Could not find Data/00_shared/data_geostatistics/meuse.csv. ""Open this notebook from the GeoLattice repository." ) ROOT = ROOT.parentmeuse = pd.read_csv(ROOT /"Data"/"00_shared"/"data_geostatistics"/"meuse.csv")grid = pd.read_csv(ROOT /"Data"/"00_shared"/"data_geostatistics"/"meuse_grid.csv")coords = meuse[["x", "y"]].to_numpy(dtype=float)values = np.log(meuse["zinc"].to_numpy(dtype=float))meuse.head()
Important Python Packages for Geostatistical Analysis
PyKrige: Kriging toolkit for geostatistical modeling (supports Ordinary, Universal, and other kriging methods)
geostatspy: Geostatistical tools for spatial analysis, including variogram modeling, simulation, and kriging.
gstools: Flexible framework for geostatistical modeling, variograms, kriging, and simulation.
scikit-gstat: Tools for variogram estimation, model fitting, and kriging with a simple scikit-learn-like API.
SGeMS / pygslib: Python bindings and tools related to Stanford Geostatistical Modeling Software.
Summary
This notebook provides an introduction to spatial data analysis and geostatistics using geolattice.geostatistics.
You will learn the essential steps for: - Loading and visualizing spatial data (using the Meuse dataset as an example) - Calculating and modeling experimental variograms - Fitting theoretical variogram models to your data - Performing ordinary kriging to predict values at unknown locations and generate prediction uncertainty maps - Validating kriging results with leave-one-out (LOO) cross-validation
The workflow demonstrates working with both pandas DataFrames and GeoPandas GeoDataFrames for spatial data, and introduces key objects like Variogram and OrdinaryKriging.
By following this notebook, you’ll gain a foundational understanding of how to implement and interpret basic geostatistical workflows in Python, and will be ready to build more advanced spatial models and analyses.
Resources
Foundational & Advanced Textbooks
“Model-Based Geostatistics” by Peter J. Diggle & Paulo J. Ribeiro Jr. Why it’s relevant: Bridges classical geostatistics (kriging) with modern statistical modeling (GLMMs). It provides the rigorous mathematical foundation for Regression Kriging and Poisson Kriging, framing them within a unified likelihood-based framework.
“Geostatistics for Environmental Scientists” by Richard Webster & Margaret A. Oliver Why it’s relevant: The gold standard for understanding variograms, cross-variograms, and the assumptions behind Ordinary and Universal Kriging. Excellent for grounding your rigorous model validation protocols.
“A Practical Guide to Geostatistical Mapping” by Tomislav Hengl Why it’s relevant: Written by the pioneer of Regression Kriging. It provides practical, step-by-step mathematical and computational guidance on combining machine learning/regression with kriging of residuals, including handling large environmental datasets.
“Spatial and Spatio-Temporal Geostatistics with R” by Edzer Pebesma & Roger Bivand Why it’s relevant: The definitive guide to implementing geostatistics in R, directly linking theory to the gstat and sp/sf ecosystems.
Seminal & Modern Academic Papers
Poisson Kriging: Goovaerts, P. (2006). “Geostatistical analysis of disease data: accounting for spatial support and population density in the isopleth mapping of cancer risk.”International Journal of Health Geographics. Why it’s relevant: The definitive mathematical breakdown of how to deconvolve Poisson noise from the variogram and adjust the kriging matrix diagonal for population-based variance, exactly as outlined in the previous response.
Regression Kriging: Hengl, T., Heuvelink, G. B., & Stein, A. (2004). “A generic protocol for spatial prediction of soil properties based on regression-kriging.”Geoderma. Why it’s relevant: Establishes the mathematical equivalence (and practical differences) between Universal Kriging and Regression Kriging, and provides protocols for validation.
Scalable Geostatistics (Large-Scale / GPU): Datta, A., Banerjee, S., Finley, A. O., & Gelfand, A. E. (2016). “Hierarchical Nearest-Neighbor Gaussian Process Models for Large Geostatistical Datasets.”Journal of the American Statistical Association. Why it’s relevant: Since you work with large-scale environmental problems and GPU acceleration, NNGP (Nearest Neighbor Gaussian Processes) is the modern mathematical solution to the \(\mathcal{O}(n^3)\) bottleneck of traditional kriging matrices.
Software
This tutorial series uses geolattice.geostatistics. The notebooks under Tutorials/notebooks/05_geostatistics/ walk through variograms, ordinary and universal kriging, cokriging, regression kriging, Poisson kriging, and sequential simulation.
Related libraries, if you want to compare implementations:
GSTools: variogram fitting, kriging, and conditional random fields on SciPy.
scikit-gstat: variogram estimation and kriging with a scikit-learn-style API.
R gstat: the reference implementation for ordinary, universal, and co-kriging that PyGStat follows.
R-INLA: fast spatial GLMMs, including Poisson counts with spatial random effects.
Advanced Validation & Best Practices Resources
Given your emphasis on robust evaluation (multiple random splits, stratified sampling, cross-validation, loss plots, and 1:1 plots): * Hengl, T. (2007). “A Practical Guide to Geostatistical Mapping of Environmental Variables.” (Chapter on Validation). It explicitly details why standard random cross-validation in spatial data leads to over-optimistic results due to spatial autocorrelation, and advocates for spatial block cross-validation (which aligns with your stratified sampling approach). * blockCV (R package) / spatialCV (Python concepts): Look into methodologies for spatial block cross-validation. Papers by Valavi et al. (2019) on blockCV provide the mathematical justification for ensuring your training and testing folds are spatially independent, preventing data leakage in your kriging/ML ensemble models.
Where to go next in GeoLattice
Variograms: 05_01_variogram_modeling.ipynb fits spherical, exponential, Gaussian, Matérn, stable, and cubic models on the Jura survey.
Classic kriging: 05_02_00_introduction_kriging.ipynb through 05_02_04_cokriging.ipynb cover simple, ordinary, and universal kriging, then cokriging.
Regression kriging: 05_03_00_introduction_regression_kriging.ipynb and the later 05_03_* notebooks add a covariate trend (scikit-learn, H2O, PyTorch, TensorFlow, or a graph network) and krige the residuals.
Specialized kriging, Poisson kriging, and simulation: indicator, disjunctive, factorial, and soft kriging, then area-to-area Poisson kriging and sgsim / sisim.
GPU paths use use_gpu="auto", True, or False after python -m pip install "geolattice[geostatistics-gpu]".