Ordinary Kriging (OK) is the workhorse interpolator in geostatistics. Unlike simple kriging, it does not assume that the mean of the random field is known. Instead it estimates a local mean at every prediction location by forcing the kriging weights to sum to one. The result is still a Best Linear Unbiased Estimator (BLUE), but it is robust to a slowly varying, unknown mean.
This tutorial applies OK to cadmium (Cd) in the Swiss Jura using PyGStat, with the same data split as Tutorial 03 so the two methods can be compared:
Step
What we do
Data
Load jura_data.csv (359 samples) and jura_grid.csv (prediction nodes)
Split
Stratified 70% / 30% train–test split by Landuse
Variogram
Fit spherical, exponential, gaussian, Matérn, stable, and cubic models on the training set; pick the best by AIC
Ordinary Kriging
Fit OK with the winning variogram (mean unknown; weights constrained to sum to 1)
Validation
Predict the held-out test locations; report RMSE, MAE, \(R^2\), and mean error
Mapping
Predict Cd and kriging standard error on the Jura grid
Time OrdinaryKriging.predict on CPU vs GPU for Jura Cd and Great Plains SOC (gp_data_5000.csv)
By the end you will have validated OK predictions, mapped Cd and its uncertainty, produced exceedance-probability surfaces under the Gaussian OK model, and seen when a GPU pays off for OK.
2. What is Ordinary Kriging?
Kriging predicts \(Z(\mathbf{x}_0)\) at an unsampled location as a weighted average of nearby observations:
That single constraint is what lets OK absorb an unknown constant mean. If the true mean is \(m\), then
\[
\mathbb{E}\bigl[\hat{Z}_{\text{OK}}(\mathbf{x}_0)\bigr] = m \sum_i \lambda_i = m = \mathbb{E}\bigl[Z(\mathbf{x}_0)\bigr],
\]
so the predictor is unbiased without knowing \(m\).
Assumptions
Assumption
Meaning
Intrinsic stationarity
Increments \(Z(\mathbf{x})-Z(\mathbf{x}+\mathbf{h})\) have mean 0 and variance \(2\gamma(h)\)
Unknown, locally constant mean
\(m\) may exist but is not supplied; OK estimates it implicitly
Variogram known
\(\gamma(h)\) is fitted from data before kriging
Intrinsic stationarity is weaker than the second-order stationarity required by simple kriging: the mean need not be defined globally, only the variogram of the increments.
Covariance \(C\)augmented with a row/column of ones
\(C\) only
Extra unknown
Lagrange multiplier \(\mu\)
none
Kriging variance
Usually larger than SK (one extra constraint)
Smaller if \(m\) is correct
When to use
Default choice; mean uncertain or slowly varying
Stationary field with a trusted global mean
OK is the default in environmental mapping precisely because a global mean for Cd, soil metals, or rainfall is rarely known with enough confidence to lock it in as SK does.
3. How Ordinary Kriging Works
3.1 From variogram to covariance
PyGStat builds the OK system in covariance form. Under second-order stationarity
where \(C_0\) is the nugget and \(C\) is the partial sill. The diagonal of \(C\) is restored to \(C(0)\) so the nugget is not dropped. The same \(\gamma(h)\) also justifies OK under the weaker intrinsic hypothesis (the system can be written with \(-\gamma\) in place of \(C\)).
3.2 The OK linear system
Minimise the mean squared error subject to \(\sum\lambda_i = 1\) with a Lagrange multiplier \(\mu\):
The extra \(-\mu\) term is the cost of not knowing the mean: OK variance is typically a little larger than SK variance at the same location. PyGStat returns the standard error\(\sigma_{\text{OK}} = \sqrt{\sigma^2_{\text{OK}}}\) when return_variance=True.
3.4 Gaussian exceedance probability
Treating the OK predictor as Gaussian, \(Z(\mathbf{x}_0)\,|\,\text{data} \sim \mathcal{N}\bigl(\hat{Z}_{\text{OK}},\,\sigma^2_{\text{OK}}\bigr)\),
This is a parametric probability map. Cd is right-skewed, so the Gaussian law is an approximation. Indicator kriging estimates the same probabilities without that assumption.
3.5 Workflow in this notebook
Split samples by Landuse so every land-use class appears in both train and test.
Estimate \(\gamma(h)\) from training Cd only (no leakage from the test set).
Fit OrdinaryKriging with the winning variogram (no mean is passed).
Solve the OK system at test locations → validation metrics.
Solve the OK system at every Jura grid node → maps of \(\hat{Z}\) and \(\sigma_{\text{OK}}\).
Convert \((\hat{Z},\sigma_{\text{OK}})\) into \(P(\text{Cd} > z_c)\) at five cutoffs.
4. Python Setup
4.1 CPU and GPU
PyGStat’s OrdinaryKriging builds the covariance matrix and solves the kriging system on CPU (NumPy/SciPy) or GPU (CuPy). Pass use_gpu as:
Value
Behaviour
'auto' (default)
GPU when CuPy can run a kernel on this card. Falls back to CPU otherwise.
True
Force GPU. Warns and falls back to CPU if CuPy is missing or cannot run a kernel.
False
Always CPU (NumPy/SciPy).
This notebook probes the GPU once with cupy_gpu_usable() (a real op, not just import cupy) and stores the result in USE_GPU. The OK fit below passes use_gpu=USE_GPU, so the same cells run on a laptop CPU or a CUDA workstation without edits.
Two caveats:
The Matérn model always evaluates on CPU (SciPy Bessel functions have no CuPy equivalent). The OK linear algebra is still GPU-accelerated when USE_GPU is true.
Small \(n\) (a few hundred training points, like Jura) often shows little GPU gain unless you predict a large grid: host→device copies and kernel-launch overhead can dominate a small \(n \times n\) system.
Install CuPy with pip install pygstat[gpu] (CUDA 11) or pip install cupy-cuda12x for CUDA 12.
Section 13 times OrdinaryKriging.predict on both backends using Jura Cd and prefixes of data/gp_data_5000.csv.
Code
%matplotlib inlineimport sys, os, warningswarnings.filterwarnings("ignore")sys.path.insert(0, os.path.abspath("../src"))import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom scipy.stats import norm, skewfrom sklearn.model_selection import StratifiedShuffleSplitfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_scoreimport pygstatfrom pygstat import Variogram, OrdinaryKrigingfrom pygstat.utils.backend import CUPY_AVAILABLE, cupy_gpu_usableprint(f"pygstat version : {pygstat.__version__}")print(f"NumPy : {np.__version__}")print(f"pandas : {pd.__version__}")# ── CPU / GPU dispatch ────────────────────────────────────────────────────────# cupy_gpu_usable() runs a real kernel (not just `import cupy`). Older cards can# import CuPy and still fail at compile time; those stay on CPU.USE_GPU = cupy_gpu_usable()if USE_GPU:import cupy as cpprint(f"CuPy : {cp.__version__}")try: name = cp.cuda.runtime.getDeviceProperties(0)["name"]ifisinstance(name, bytes): name = name.decode()print(f"GPU : {name}")exceptException:print("GPU : available")print("Backend : GPU (CuPy) — OK covariance + solve on GPU")else:if CUPY_AVAILABLE:import cupy as cpprint(f"CuPy : {cp.__version__} (installed, but cannot run a kernel on this GPU/CUDA setup)")else:print("CuPy : not installed (pip install pygstat[gpu] or cupy-cuda12x)")print("Backend : CPU (NumPy)")print(f"use_gpu : {USE_GPU}")
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1788925350.890650 551216 cpu_feature_guard.cc:227] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
pygstat version : 0.1.0
NumPy : 2.4.6
pandas : 3.0.3
CuPy : 14.2.0
GPU : NVIDIA GeForce RTX 2080 Ti
Backend : GPU (CuPy) — OK covariance + solve on GPU
use_gpu : True
5. Load and Explore the Jura Data
The Jura dataset (Goovaerts, 1997) contains 359 soil samples of heavy metals in the Swiss Jura. We model Cd at sample locations and predict it on the dense prediction grid in jura_grid.csv.
Land-use codes in the sample file are integers (1–4); the grid file stores land use as labels. The stratified split uses the integer Landuse column from the samples.
Grid extent: X [0.30, 5.10], Y [0.10, 5.90] km (5957 nodes)
6. Stratified Train / Test Split
A purely random split can leave a land-use class under-represented in the test set (class 4 has only 8 samples). Stratified random sampling draws the 70% / 30% split inside each Landuse class, so the class proportions are preserved.
The variogram is estimated from the training set only. Ordinary kriging does not use a global mean, but the same split is used so results can be compared with Tutorial 03 (simple kriging).
We fit all six PyGStat models to the training Cd values with the Matheron estimator, then rank them by AIC (Tutorial 02). The winning model is the covariance structure used for ordinary kriging.
Code
def find_best_variogram(coords, values, estimator="matheron", n_lags=15, criterion="AIC", verbose=True):"""Fit all standard models; return the best Variogram by ``criterion``.""" models = ["spherical", "exponential", "gaussian", "matern", "stable", "cubic"] n_params = {"spherical": 3, "exponential": 3, "gaussian": 3,"matern": 4, "stable": 4, "cubic": 3} fitted, records = {}, []for model_name in models: v = Variogram(coords=np.asarray(coords, dtype=float), values=np.asarray(values, dtype=float), model=model_name, estimator=estimator, n_lags=n_lags) v.fit() obs = v.experimental mask =~np.isnan(obs) obs_v, pred = obs[mask], v(v.lags)[mask] K, p = mask.sum(), n_params[model_name] rss =float(np.sum((pred - obs_v) **2)) tss =float(np.sum((obs_v - obs_v.mean()) **2)) r2 =1.0- rss / tss if tss >0else np.nan aic = K * np.log(rss / K) +2* p if rss >0else-np.inf bic = K * np.log(rss / K) + p * np.log(K) if rss >0else-np.inf fitted[model_name] = v extra =round(float(v.fitted_params[3]), 4) iflen(v.fitted_params) >3else"—" records.append({"Model": model_name.capitalize(),"Nugget": round(float(v.fitted_params[0]), 5),"Sill": round(float(v.fitted_params[1]), 5),"Range": round(float(v.fitted_params[2]), 5),"Extra": extra,"RSS": round(rss, 6),"R²": round(r2, 4),"AIC": round(aic, 4),"BIC": round(bic, 4), }) df_results = pd.DataFrame(records).set_index("Model") df_results = df_results.sort_values(criterion, ascending=(criterion !="R²")) best_cap = df_results.index[0] best_key = best_cap.lower()if verbose:print(df_results.to_string())print(f"\n>>> BEST MODEL: {best_cap} (by {criterion}) <<<")return best_cap, fitted[best_key], df_results, fittedbest_name, vg_best, df_rank, fitted_models = find_best_variogram( coords_train, z_train, estimator="matheron", n_lags=12, criterion="AIC")
OrdinaryKriging takes only a fitted Variogram. No mean is passed: the unbiasedness constraint estimates the local mean at each prediction location. use_gpu=USE_GPU builds the covariance matrix and solves the OK system on CuPy when a usable GPU is present.
Code
ok = OrdinaryKriging(vg_best, use_gpu=USE_GPU).fit(coords_train, z_train)print(f"Estimator : Ordinary Kriging")print(f"Variogram model : {vg_best.model}")print(f"Fitted params [C0, C, a]: {np.round(vg_best.fitted_params[:3], 5)}")print(f"Training n : {len(z_train)}")print(f"Mean is not supplied : OK enforces sum(weights) = 1")print(f"use_gpu : {ok.use_gpu}")
Estimator : Ordinary Kriging
Variogram model : spherical
Fitted params [C0, C, a]: [0.56002 0.1532 1.75505]
Training n : 251
Mean is not supplied : OK enforces sum(weights) = 1
use_gpu : True
9. Validate OK on the Test Set
Predict Cd at the held-out 30% of samples. These locations were not used to fit the variogram, so the scores below are an honest check of interpolation skill.
Code
z_hat, se_test = ok.predict(coords_test, return_variance=True)rmse =float(np.sqrt(mean_squared_error(z_test, z_hat)))mae =float(mean_absolute_error(z_test, z_hat))r2 =float(r2_score(z_test, z_hat))me =float(np.mean(z_hat - z_test)) # mean error (bias)resid = z_hat - z_testprint("Ordinary Kriging — test-set validation")print("="*44)print(f" n test : {len(z_test)}")print(f" RMSE : {rmse:.4f} mg/kg")print(f" MAE : {mae:.4f} mg/kg")print(f" Mean error : {me:+.4f} mg/kg (predicted − observed)")print(f" R² : {r2:.4f}")print(f" Mean OK SE : {se_test.mean():.4f} mg/kg")metrics = pd.DataFrame([{"n_train": len(z_train), "n_test": len(z_test),"model": best_name, "estimator": "ordinary","RMSE": round(rmse, 4), "MAE": round(mae, 4),"ME": round(me, 4), "R2": round(r2, 4),}])metrics
Ordinary Kriging — test-set validation
============================================
n test : 108
RMSE : 0.8026 mg/kg
MAE : 0.5944 mg/kg
Mean error : +0.0022 mg/kg (predicted − observed)
R² : 0.1836
Mean OK SE : 0.7874 mg/kg
The left map is the OK estimate of Cd. The right map is the prediction error (kriging standard error). Error is smallest near training samples and grows toward the edges of the domain and in sparsely sampled pockets. Because OK estimates a local mean, the SE is typically a little larger than the corresponding simple-kriging SE (Tutorial 03).
We map this probability for cutoffs 0.10, 0.25, 0.50, 0.75, and 1.00 mg/kg. Values near 1 mean Cd is almost surely above the cutoff; values near 0 mean it is almost surely below.
Because the sample mean of Cd is about 1.3 mg/kg, probabilities of exceeding 0.10–0.75 mg/kg will be high over much of the domain. The 1.00 mg/kg map is the most spatially informative of this set.
Code
cutoffs = [0.10, 0.25, 0.50, 0.75, 1.00] # mg/kgse_safe = np.clip(se_grid, 1e-8, None)prob_cols = []for zc in cutoffs: col =f"P_Cd_gt_{zc:.2f}".replace(".", "p") grid_out[col] =1.0- norm.cdf((zc - pred_grid) / se_safe) prob_cols.append(col)print(f"P(Cd > {zc:4.2f}) mean={grid_out[col].mean():.3f} "f"min={grid_out[col].min():.3f} max={grid_out[col].max():.3f}")emp = {zc: float(np.mean(z_train > zc)) for zc in cutoffs}print("\nEmpirical P(Cd > zc) on training samples:")for zc, p in emp.items():print(f" {zc:4.2f} mg/kg : {p:.3f}")
Section 4.1 showed how to select a backend. Here we measure how long ordinary kriging takes on CPU (use_gpu=False, NumPy/SciPy) versus GPU (use_gpu=True, CuPy) — first on the Jura samples (\(n_{\text{train}} = 359\)) predicting the Jura grid, then on prefixes of the Great Plains soil-organic-carbon survey (data/gp_data_5000.csv, \(n\) up to 5{,}000).
The GPU-accelerated steps are the \(n \times n\) covariance matrix among training points, the \(n_{\text{pred}} \times n\) covariance to the targets, and the linear solve of the augmented OK system (ones row/column plus Lagrange multiplier). Variogram fitting is done once per dataset (spherical model) and is not included in the OK times.
Two practical notes:
Small \(n\) and few targets (a few hundred training and prediction points) often shows little GPU gain: host→device copies and kernel-launch overhead dominate.
Larger \(n\), or a dense prediction grid, is where the GPU pays off: the OK system scales as \(O(n^3)\) for the solve and \(O(n \cdot n_{\text{pred}})\) for the target covariances.
Each timing is the median of three OrdinaryKriging.fit + predict(..., return_variance=True) calls after a short GPU warmup so CUDA kernel compilation is not counted. If CuPy cannot run a kernel here, the GPU column is skipped and only CPU times are reported.
GPU usable : True
Repeats : 3 (median wall time of OK fit + predict)
Jura Cd : 359 samples → 5957 grid nodes
GP SOC : 5000 samples from data/gp_data_5000.csv
GP n_pred : 500 locations drawn from each prefix
dataset n_train n_pred CPU (ms) GPU (ms) speedup match
Jura (Cd) 359 5957 162.3 18.5 8.77× True
GP (SOC) 500 500 46.3 10.3 4.49× True
GP (SOC) 1000 500 150.8 24.4 6.19× True
GP (SOC) 2000 500 384.9 65.7 5.85× True
GP (SOC) 4000 500 1363.0 209.0 6.52× True
GP (SOC) 5000 500 2179.9 361.0 6.04× True
Predictions and kriging standard errors from the two backends should match (match = True). On this workstation the Jura run still benefits from the GPU because we predict 5{,}957 grid nodes even though \(n = 359\) is small. On the Great Plains SOC prefixes the \(O(n^2)\) covariance build and \(O(n^3)\) solve keep the GPU several times faster as \(n\) grows to 5{,}000. Use use_gpu=USE_GPU (as the rest of this notebook does) so the same cells run on a laptop CPU or a CUDA workstation without edits.
14. Summary and Conclusions
This tutorial walked through a complete ordinary kriging workflow for Jura cadmium.
What we did
Split 359 samples 70 / 30 with stratified random sampling by Landuse, so rare land-use class 4 is represented in both sets.
Fitted six theoretical variograms on training Cd only and selected the best model by AIC.
Fitted Ordinary Kriging with the unbiasedness constraint \(\sum\lambda_i = 1\) (unknown mean) and use_gpu=USE_GPU.
Validated at held-out locations (RMSE, MAE, mean error, \(R^2\), residual maps, standardized residuals).
Mapped OK predictions and kriging standard errors on jura_grid.csv.
Converted \((\hat{Z},\sigma_{\text{OK}})\) into Gaussian exceedance probabilities at 0.10, 0.25, 0.50, 0.75, and 1.00 mg/kg, and checked them on the test set with the Brier score.
Timed OrdinaryKriging.predict on CPU vs GPU for Jura Cd and prefixes of data/gp_data_5000.csv.
Practical takeaways
Do not leak the test set into the variogram. OK does not need a global mean, but the covariance model must still be trained only on the training sample.
OK is the default interpolator when the mean is unknown or only locally constant. Use simple kriging (Tutorial 02) only when you trust a global mean.
The extra Lagrange multiplier makes OK variance slightly larger than SK variance — that extra uncertainty is the price of not knowing \(m\).
The prediction-error map is not a map of Cd; it shows how well the data constrain the estimate.
Gaussian \(P(\text{Cd} > z_c)\) is a convenient OK by-product. Cd is right-skewed, so these probabilities are an approximation. For a distribution-free alternative, use indicator kriging.
A GPU pays off for OK when \(n\) is large or you predict a dense grid. Small \(n\) with few targets is often CPU-bound after host–device copies.
Next steps
Compare test RMSE and mean SE with Tutorial 02 (simple kriging) on this same split (random_state=42)
Universal kriging if Cd has a trend with coordinates, land use, or rock type
Indicator kriging for the same five cutoffs without the Gaussian assumption
15. Resources
Textbooks
Reference
Notes
Goovaerts, P. (1997). Geostatistics for Natural Resources Evaluation. Oxford University Press.
Jura Cd case study; OK as the default interpolator