Dataset: Jura geochemical survey (data/jura_data.csv, data/jura_grid.csv)

Target: Cadmium (Cd, mg/kg)

Library: pygstat v0.1.0


Table of Contents

  1. Overview
  2. What is Simple Kriging?
  3. How Simple Kriging Works
  4. Python Setup
  5. Load and Explore the Jura Data
  6. Stratified Train / Test Split
  7. Variogram Modeling on Training Data
  8. Fit Simple Kriging
  9. Validate SK on the Test Set
  10. Predict Cd on the Jura Grid
  11. Map Predicted Concentration and Error
  12. Probability Maps of Exceedance
  13. CPU vs GPU SK Timing
  14. Summary and Conclusions
  15. Resources

1. Overview

Simple Kriging (SK) is the BLUE (Best Linear Unbiased Estimator) of a random field when the mean is known. It is the natural next step after variogram modeling: once spatial correlation is quantified, SK uses that model to interpolate at unsampled locations and to report a kriging standard error at every location.

This tutorial applies SK to cadmium (Cd) in the Swiss Jura using PyGStat:

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
Simple Kriging Use the training mean as the known SK mean; fit SK with the winning variogram
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
Probability Map \(P(\text{Cd} > z_c)\) for \(z_c \in \{0.10, 0.25, 0.50, 0.75, 1.00\}\) mg/kg
CPU / GPU Time SimpleKriging.predict on CPU vs GPU for Jura Cd and Great Plains SOC (gp_data_5000.csv)

By the end you will have validated SK predictions, mapped Cd and its uncertainty, produced exceedance-probability surfaces under the Gaussian SK model, and seen when a GPU pays off for SK.


2. What is Simple Kriging?

Kriging predicts \(Z(\mathbf{x}_0)\) at an unsampled location from nearby observations \(Z(\mathbf{x}_1),\ldots,Z(\mathbf{x}_n)\). All linear kriging estimators have the form of a weighted average of residuals around a mean:

\[ \hat{Z}_{\text{SK}}(\mathbf{x}_0) = m + \sum_{i=1}^{n} \lambda_i \, \bigl(Z(\mathbf{x}_i) - m\bigr) \]

where \(m = \mathbb{E}[Z(\mathbf{x})]\) is treated as known (in practice, estimated from the training data and then held fixed).

Assumptions

Assumption Meaning
Second-order stationarity Constant mean \(m\) and covariance \(C(\mathbf{h})\) that depends only on lag
Known mean \(m\) is not estimated jointly with the weights (unlike ordinary kriging)
Variogram / covariance known The spatial model \(\gamma(h)\) (or \(C(h)\)) is fitted beforehand

Simple vs ordinary kriging

Simple Kriging Ordinary Kriging
Mean Known, fixed Unknown, locally estimated
Unbiasedness Weights need not sum to 1 \(\sum \lambda_i = 1\) (Lagrange multiplier)
Kriging matrix Covariance matrix \(C\) only \(C\) augmented with a row/column of ones
When to use Stationary field with a well-estimated global mean Local mean uncertain, or a mild trend

SK typically has smaller kriging variance than OK when the mean really is known, because it does not spend a degree of freedom on estimating \(m\). If the assumed mean is wrong, SK is biased.


3. How Simple Kriging Works

3.1 From variogram to covariance

Under second-order stationarity the covariance and the variogram are linked by

\[ C(h) = C(0) - \gamma(h), \qquad C(0) = C_0 + C \]

where \(C_0\) is the nugget and \(C\) is the partial sill. PyGStat restores \(C(0)\) on the diagonal of the kriging matrix so the nugget is not dropped.

3.2 The SK linear system

The weights \(\boldsymbol{\lambda}\) that minimise the mean squared prediction error solve

\[ \mathbf{C}\,\boldsymbol{\lambda} = \mathbf{c}_0 \]

where \(C_{ij} = C(\mathbf{x}_i - \mathbf{x}_j)\) among training points and \(c_{0,i} = C(\mathbf{x}_0 - \mathbf{x}_i)\) between the target and each training point. Then

\[ \hat{Z}_{\text{SK}}(\mathbf{x}_0) = m + \boldsymbol{\lambda}^\top \bigl(\mathbf{z} - m\mathbf{1}\bigr). \]

3.3 Kriging variance (prediction error)

The SK variance at \(\mathbf{x}_0\) is

\[ \sigma^2_{\text{SK}}(\mathbf{x}_0) = C(0) - \boldsymbol{\lambda}^\top \mathbf{c}_0. \]

PyGStat’s predict(..., return_variance=True) returns the standard error \(\sigma_{\text{SK}} = \sqrt{\sigma^2_{\text{SK}}}\). This is the map of prediction error used later in this notebook.

3.4 Gaussian exceedance probability

If the SK predictor is treated as Gaussian, \(Z(\mathbf{x}_0)\,|\,\text{data} \sim \mathcal{N}\bigl(\hat{Z}_{\text{SK}},\,\sigma^2_{\text{SK}}\bigr)\), then the probability of exceeding a cutoff \(z_c\) is

\[ P\bigl(Z(\mathbf{x}_0) > z_c\bigr) = 1 - \Phi\!\left(\frac{z_c - \hat{Z}_{\text{SK}}(\mathbf{x}_0)}{\sigma_{\text{SK}}(\mathbf{x}_0)}\right). \]

This is a parametric probability map. It is convenient and consistent with SK, but it inherits the Gaussian assumption. Indicator kriging (a later tutorial) estimates the same probabilities without assuming a Gaussian law.

3.5 Workflow in this notebook

  1. Split samples by Landuse so every land-use class appears in both train and test.
  2. Estimate \(\gamma(h)\) from training Cd only (no leakage from the test set).
  3. Take \(m = \overline{\text{Cd}}_{\text{train}}\) as the known SK mean.
  4. Solve the SK system at test locations → validation metrics.
  5. Solve the SK system at every Jura grid node → maps of \(\hat{Z}\) and \(\sigma_{\text{SK}}\).
  6. Convert \((\hat{Z},\sigma_{\text{SK}})\) into \(P(\text{Cd} > z_c)\) at five cutoffs.

4. Python Setup

4.1 CPU and GPU

PyGStat’s SimpleKriging 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 SK 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 SK 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 SimpleKriging.predict on both backends using Jura Cd and prefixes of data/gp_data_5000.csv.

Code
%matplotlib inline
import sys, os, warnings, subprocess, importlib.util
warnings.filterwarnings("ignore")

def _ensure_package(pip_name, import_name=None):
    """Install *pip_name* if it cannot be imported."""
    name = import_name or pip_name
    if importlib.util.find_spec(name) is None:
        print(f"Installing {pip_name} ...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", pip_name, "-q"])
    print(f"{pip_name:12s} installed")

_ensure_package("numpy")
_ensure_package("pandas")
_ensure_package("matplotlib")
_ensure_package("scipy")
_ensure_package("scikit-learn", "sklearn")

# pygstat: prefer the local source tree when running from Tutorial/
_REPO_ROOT = os.path.abspath("..")
sys.path.insert(0, os.path.join(_REPO_ROOT, "src"))
if importlib.util.find_spec("pygstat") is None:
    print("Installing pygstat from local source ...")
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", "-e", f"{_REPO_ROOT}[plot]", "-q"]
    )
print(f"{'pygstat':12s} installed")

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from scipy.stats import skew
from sklearn.model_selection import StratifiedShuffleSplit

import pygstat
from pygstat import Variogram, SimpleKriging
from pygstat.core.variogram_models import MODEL_FUNCS
from pygstat.utils.backend import CUPY_AVAILABLE, cupy_gpu_usable

print(f"pygstat version : {pygstat.__version__}")
print(f"NumPy           : {np.__version__}")
print(f"pandas          : {pd.__version__}")
print(f"matplotlib      : {__import__('matplotlib').__version__}")
print(f"scipy           : {__import__('scipy').__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 cp
    print(f"CuPy            : {cp.__version__}")
    try:
        name = cp.cuda.runtime.getDeviceProperties(0)["name"]
        if isinstance(name, bytes):
            name = name.decode()
        print(f"GPU             : {name}")
    except Exception:
        print("GPU             : available")
    print("Backend         : GPU (CuPy) — SK covariance + solve on GPU")
else:
    if CUPY_AVAILABLE:
        import cupy as cp
        print(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}")
numpy        installed
pandas       installed
matplotlib   installed
scipy        installed
pygstat      installed
pygstat version : 0.1.0
NumPy           : 2.2.6
pandas          : 2.3.3
matplotlib      : 3.10.0
scipy           : 1.15.3
CuPy            : 14.0.1
GPU             : NVIDIA GeForce RTX 2080 Ti
Backend         : GPU (CuPy) — empirical variogram 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.

Code
df = pd.read_csv("../data/jura_data.csv")
grid = pd.read_csv("../data/jura_grid.csv")

print("Samples:", df.shape, "  Grid:", grid.shape)
print("Sample columns:", list(df.columns))
print("Grid columns:  ", list(grid.columns))
df.head()
Samples: (359, 12)   Grid: (5957, 5)
Sample columns: ['Unnamed: 0', 'Xloc', 'Yloc', 'Landuse', 'Rock', 'Cd', 'Co', 'Cr', 'Cu', 'Ni', 'Pb', 'Zn']
Grid columns:   ['Unnamed: 0', 'Xloc', 'Yloc', 'Landuse', 'Rock']
Unnamed: 0 Xloc Yloc Landuse Rock Cd Co Cr Cu Ni Pb Zn
0 1 2.386 3.077 3 3 1.740 9.32 38.32 25.72 21.32 77.36 92.56
1 2 2.544 1.972 2 2 1.335 10.00 40.20 24.76 29.72 77.88 73.56
2 3 2.807 3.347 2 3 1.610 10.60 47.00 8.88 21.40 30.80 64.80
3 4 4.308 1.933 3 2 2.150 11.92 43.52 22.70 29.72 56.40 90.00
4 5 4.383 1.081 3 5 1.565 16.32 38.52 34.32 26.20 66.40 88.40
Code
target = "Cd"
x_col, y_col = "Xloc", "Yloc"
strata_col = "Landuse"

coords = df[[x_col, y_col]].values
z = df[target].values.astype(float)
grid_coords = grid[[x_col, y_col]].values

print(f"\n{target} (mg/kg) summary:")
print(df[target].describe().round(3))
print(f"Skewness: {skew(z):.3f}")
print(f"\nLanduse counts:\n{df[strata_col].value_counts().sort_index().to_string()}")

Cd (mg/kg) summary:
count    359.000
mean       1.288
std        0.859
min        0.135
25%        0.653
50%        1.100
75%        1.680
max        5.129
Name: Cd, dtype: float64
Skewness: 1.472

Landuse counts:
Landuse
1     51
2     82
3    218
4      8
Code
fig, axes = plt.subplots(1, 3, figsize=(16, 4.5))

sc = axes[0].scatter(df[x_col], df[y_col], c=z, cmap="YlOrRd", s=28,
                     edgecolors="k", linewidths=0.25)
plt.colorbar(sc, ax=axes[0], label=f"{target} (mg/kg)")
axes[0].set_title(f"Sampled {target}")
axes[0].set_xlabel("Easting (km)"); axes[0].set_ylabel("Northing (km)")
axes[0].set_aspect("equal")

axes[1].hist(z, bins=30, color="steelblue", edgecolor="white")
axes[1].axvline(z.mean(), color="crimson", ls="--", label=f"mean = {z.mean():.2f}")
axes[1].set_title(f"Distribution of {target}")
axes[1].set_xlabel(f"{target} (mg/kg)"); axes[1].set_ylabel("Frequency")
axes[1].legend()

land_counts = df[strata_col].value_counts().sort_index()
axes[2].bar(land_counts.index.astype(str), land_counts.values, color="seagreen", edgecolor="white")
axes[2].set_title("Landuse strata (split variable)")
axes[2].set_xlabel("Landuse class"); axes[2].set_ylabel("n samples")

plt.tight_layout(); plt.show()

print(f"Grid extent: X [{grid[x_col].min():.2f}, {grid[x_col].max():.2f}], "
      f"Y [{grid[y_col].min():.2f}, {grid[y_col].max():.2f}] km  ({len(grid)} nodes)")

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 and the SK mean are estimated from the training set only.

Code
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.30, random_state=42)
train_idx, test_idx = next(sss.split(df, df[strata_col]))

df_train = df.iloc[train_idx].reset_index(drop=True)
df_test  = df.iloc[test_idx].reset_index(drop=True)

coords_train = df_train[[x_col, y_col]].values
coords_test  = df_test[[x_col, y_col]].values
z_train = df_train[target].values.astype(float)
z_test  = df_test[target].values.astype(float)

print(f"Train: {len(df_train)} ({100*len(df_train)/len(df):.1f}%)")
print(f"Test:  {len(df_test)} ({100*len(df_test)/len(df):.1f}%)")
print(f"\nTraining mean of {target} (SK mean m): {z_train.mean():.4f} mg/kg")

prop = pd.DataFrame({
    "all":    df[strata_col].value_counts(normalize=True).sort_index(),
    "train":  df_train[strata_col].value_counts(normalize=True).sort_index(),
    "test":   df_test[strata_col].value_counts(normalize=True).sort_index(),
})
prop.index.name = "Landuse"
(prop * 100).round(1)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 sss = StratifiedShuffleSplit(n_splits=1, test_size=0.30, random_state=42)
      2 train_idx, test_idx = next(sss.split(df, df[strata_col]))
      4 df_train = df.iloc[train_idx].reset_index(drop=True)

NameError: name 'StratifiedShuffleSplit' is not defined
Code
fig, ax = plt.subplots(figsize=(6.5, 5.5))
ax.scatter(df_train[x_col], df_train[y_col], c="steelblue", s=32,
           edgecolors="k", linewidths=0.3, label=f"Train (n={len(df_train)})", zorder=3)
ax.scatter(df_test[x_col], df_test[y_col], c="crimson", s=42, marker="^",
           edgecolors="k", linewidths=0.3, label=f"Test (n={len(df_test)})", zorder=4)
ax.set_aspect("equal")
ax.set_xlabel("Easting (km)"); ax.set_ylabel("Northing (km)")
ax.set_title("Stratified 70/30 split by Landuse")
ax.legend(frameon=True); ax.grid(alpha=0.25)
plt.tight_layout(); plt.show()


7. Variogram Modeling on Training Data

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 simple 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 > 0 else np.nan
        aic = K * np.log(rss / K) + 2 * p if rss > 0 else -np.inf
        bic = K * np.log(rss / K) + p * np.log(K) if rss > 0 else -np.inf
        fitted[model_name] = v
        extra = round(float(v.fitted_params[3]), 4) if len(v.fitted_params) > 3 else "—"
        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, fitted


best_name, vg_best, df_rank, fitted_models = find_best_variogram(
    coords_train, z_train, estimator="matheron", n_lags=12, criterion="AIC"
)
              Nugget     Sill    Range   Extra       RSS      R²      AIC      BIC
Model                                                                             
Spherical    0.56002  0.15320  1.75505       —  0.032596  0.4580 -64.9017 -63.4470
Cubic        0.57964  0.13343  2.06349       —  0.033115  0.4494 -64.7121 -63.2574
Exponential  0.54989  0.19668  0.97775       —  0.033137  0.4490 -64.7041 -63.2493
Gaussian     0.57923  0.13395  0.84831       —  0.033317  0.4460 -64.6390 -63.1842
Matern       0.56645  0.15393  0.39814  1.3931  0.032745  0.4555 -62.8469 -60.9073
Stable       0.56456  0.15532  0.81914  1.4358  0.032843  0.4539 -62.8111 -60.8715

>>> BEST MODEL: Spherical (by AIC) <<<
Code
h_fine = np.linspace(0, vg_best.maxlag, 300)
palette = {"Spherical": "#1f77b4", "Exponential": "#ff7f0e", "Gaussian": "#2ca02c",
           "Matern": "#d62728", "Stable": "#9467bd", "Cubic": "#8c564b"}

fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(vg_best.lags, vg_best.experimental, color="black", s=55, zorder=6,
           label="Matheron empirical (train)")
for name, v in fitted_models.items():
    cap = name.capitalize()
    is_best = cap == best_name
    ax.plot(h_fine, v(h_fine), color=palette.get(cap, "gray"),
            lw=2.6 if is_best else 1.1,
            alpha=1.0 if is_best else 0.35,
            label=cap + (" ★ BEST" if is_best else ""))
p = vg_best.fitted_params
ax.set_title(f"Training variogram — best: {best_name}\n"
             f"nugget={p[0]:.4f}  sill={p[1]:.4f}  range={p[2]:.3f} km")
ax.set_xlabel("Lag distance (km)"); ax.set_ylabel("Semivariance")
ax.legend(fontsize=9); ax.grid(alpha=0.3)
plt.tight_layout(); plt.show()

df_rank.style.background_gradient(subset=["AIC", "RSS"], cmap="RdYlGn_r")

  Nugget Sill Range Extra RSS R² AIC BIC
Model                
Spherical 0.560020 0.153200 1.755050 — 0.032596 0.458000 -64.901700 -63.447000
Cubic 0.579640 0.133430 2.063490 — 0.033115 0.449400 -64.712100 -63.257400
Exponential 0.549890 0.196680 0.977750 — 0.033137 0.449000 -64.704100 -63.249300
Gaussian 0.579230 0.133950 0.848310 — 0.033317 0.446000 -64.639000 -63.184200
Matern 0.566450 0.153930 0.398140 1.393100 0.032745 0.455500 -62.846900 -60.907300
Stable 0.564560 0.155320 0.819140 1.435800 0.032843 0.453900 -62.811100 -60.871500

8. Fit Simple Kriging

SimpleKriging takes a fitted Variogram and a known mean. We pass the training mean of Cd explicitly so the mean used for prediction is exactly the one estimated from the training sample. use_gpu=USE_GPU builds the covariance matrix and solves the SK system on CuPy when a usable GPU is present.

Code
sk_mean = float(np.mean(z_train))
sk = SimpleKriging(vg_best, mean=sk_mean, use_gpu=USE_GPU).fit(coords_train, z_train)

print(f"SK mean m              : {sk.mean:.4f} mg/kg")
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"use_gpu                : {sk.use_gpu}")
SK mean m              : 1.2995 mg/kg
Variogram model        : spherical
Fitted params [C0, C, a]: [0.56002 0.1532  1.75505]
Training n             : 251

9. Validate SK on the Test Set

Predict Cd at the held-out 30% of samples. These locations were not used to fit the variogram or to set \(m\), so the scores below are an honest check of interpolation skill.

Code
z_hat, se_test = sk.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_test

print("Simple Kriging — test-set validation")
print("=" * 42)
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 SK SE : {se_test.mean():.4f} mg/kg")

metrics = pd.DataFrame([{
    "n_train": len(z_train), "n_test": len(z_test),
    "model": best_name, "mean_m": round(sk_mean, 4),
    "RMSE": round(rmse, 4), "MAE": round(mae, 4),
    "ME": round(me, 4), "R2": round(r2, 4),
}])
metrics
Simple Kriging — test-set validation
==========================================
  n test     : 108
  RMSE       : 0.8026 mg/kg
  MAE        : 0.5941 mg/kg
  Mean error : +0.0001 mg/kg  (predicted − observed)
  R²         : 0.1837
  Mean SK SE : 0.7871 mg/kg
n_train n_test model mean_m RMSE MAE ME R2
0 251 108 Spherical 1.2995 0.8026 0.5941 0.0001 0.1837
Code
fig, axes = plt.subplots(1, 3, figsize=(15, 4.6))

lo, hi = min(z_test.min(), z_hat.min()), max(z_test.max(), z_hat.max())
axes[0].scatter(z_test, z_hat, c="steelblue", edgecolors="k", linewidths=0.3, s=36)
axes[0].plot([lo, hi], [lo, hi], "k--", lw=1, label="1:1")
axes[0].set_xlabel("Observed Cd (mg/kg)"); axes[0].set_ylabel("SK predicted Cd (mg/kg)")
axes[0].set_title(f"Test observed vs predicted\n$R^2$={r2:.3f}, RMSE={rmse:.3f}")
axes[0].set_aspect("equal", adjustable="box"); axes[0].legend(); axes[0].grid(alpha=0.3)

axes[1].hist(resid, bins=20, color="coral", edgecolor="white")
axes[1].axvline(0, color="k", ls="--")
axes[1].set_title(f"Test residuals (pred − obs)\nME={me:+.3f}")
axes[1].set_xlabel("Residual (mg/kg)"); axes[1].set_ylabel("Count")

sc = axes[2].scatter(df_test[x_col], df_test[y_col], c=resid, cmap="RdBu_r",
                     s=45, edgecolors="k", linewidths=0.3,
                     vmin=-np.max(np.abs(resid)), vmax=np.max(np.abs(resid)))
plt.colorbar(sc, ax=axes[2], label="Residual (mg/kg)")
axes[2].set_aspect("equal")
axes[2].set_title("Spatial residual map (test)")
axes[2].set_xlabel("Easting (km)"); axes[2].set_ylabel("Northing (km)")

plt.tight_layout(); plt.show()

# Standardized residuals should be ~ N(0,1) if SK variance is well calibrated
std_resid = resid / np.clip(se_test, 1e-8, None)
print(f"Standardized residual mean: {std_resid.mean():+.3f}   std: {std_resid.std():.3f}  (ideal: 0, 1)")

Standardized residual mean: -0.000   std: 1.021  (ideal: 0, 1)

10. Predict Cd on the Jura Grid

Apply the same fitted SK model to every node in jura_grid.csv. We keep both the predicted concentration and the kriging standard error.

Code
pred_grid, se_grid = sk.predict(grid_coords, return_variance=True)

grid_out = grid.copy()
grid_out["Cd_pred"] = pred_grid
grid_out["Cd_se"] = se_grid

print(f"Grid predictions: n = {len(pred_grid)}")
print(f"  Cd_pred  min/mean/max : {pred_grid.min():.3f} / {pred_grid.mean():.3f} / {pred_grid.max():.3f} mg/kg")
print(f"  Cd_se    min/mean/max : {se_grid.min():.3f} / {se_grid.mean():.3f} / {se_grid.max():.3f} mg/kg")
grid_out[[x_col, y_col, "Cd_pred", "Cd_se"]].head()
Grid predictions: n = 5957
  Cd_pred  min/mean/max : 0.554 / 1.324 / 2.011 mg/kg
  Cd_se    min/mean/max : 0.774 / 0.792 / 0.838 mg/kg
Xloc Yloc Cd_pred Cd_se
0 0.30 1.70 1.275891 0.823194
1 0.35 1.70 1.277579 0.820323
2 0.35 1.75 1.284154 0.820144
3 0.40 1.70 1.277785 0.817229
4 0.40 1.75 1.286312 0.817057

11. Map Predicted Concentration and Error

The left map is the SK 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 — a hallmark of kriging.

Code
fig, axes = plt.subplots(1, 2, figsize=(13, 5.6))

sc0 = axes[0].scatter(grid_out[x_col], grid_out[y_col], c=grid_out["Cd_pred"],
                      cmap="YlOrRd", s=8, marker=".")
axes[0].scatter(df_train[x_col], df_train[y_col], facecolors="none", edgecolors="k",
                s=18, linewidths=0.4, label="train")
plt.colorbar(sc0, ax=axes[0], label="Cd (mg/kg)", fraction=0.046, pad=0.04)
axes[0].set_aspect("equal")
axes[0].set_title(f"Simple Kriging prediction of Cd\n({best_name} variogram)")
axes[0].set_xlabel("Easting (km)"); axes[0].set_ylabel("Northing (km)")
axes[0].legend(loc="lower right", fontsize=8)

sc1 = axes[1].scatter(grid_out[x_col], grid_out[y_col], c=grid_out["Cd_se"],
                      cmap="magma", s=8, marker=".")
axes[1].scatter(df_train[x_col], df_train[y_col], facecolors="none", edgecolors="w",
                s=18, linewidths=0.4, label="train")
plt.colorbar(sc1, ax=axes[1], label="SK standard error (mg/kg)", fraction=0.046, pad=0.04)
axes[1].set_aspect("equal")
axes[1].set_title("Prediction error (kriging SE)")
axes[1].set_xlabel("Easting (km)"); axes[1].set_ylabel("Northing (km)")
axes[1].legend(loc="lower right", fontsize=8, labelcolor="white", framealpha=0.3)

plt.tight_layout(); plt.show()


12. Probability Maps of Exceedance

Under the Gaussian SK model,

\[ P(\text{Cd}(\mathbf{x}_0) > z_c) = 1 - \Phi\!\left(\frac{z_c - \hat{Z}_{\text{SK}}(\mathbf{x}_0)}{\sigma_{\text{SK}}(\mathbf{x}_0)}\right). \]

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/kg
se_safe = np.clip(se_grid, 1e-8, None)

prob_cols = []
for zc in cutoffs:
    col = f"P_Cd_gt_{zc:.2f}".replace(".", "p")
    # P(Z > zc) = 1 - Φ((zc - μ) / σ)
    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}")

# Also report the empirical fraction of training samples above each cutoff
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}")
P(Cd > 0.10)  mean=0.929  min=0.720  max=0.993
P(Cd > 0.25)  mean=0.901  min=0.652  max=0.988
P(Cd > 0.50)  mean=0.838  min=0.528  max=0.973
P(Cd > 0.75)  mean=0.755  min=0.401  max=0.946
P(Cd > 1.00)  mean=0.652  min=0.284  max=0.902

Empirical P(Cd > zc) on training samples:
  0.10 mg/kg : 1.000
  0.25 mg/kg : 0.976
  0.50 mg/kg : 0.873
  0.75 mg/kg : 0.701
  1.00 mg/kg : 0.546
Code
fig, axes = plt.subplots(2, 3, figsize=(15, 9))
axes = axes.ravel()

for ax, zc, col in zip(axes, cutoffs, prob_cols):
    sc = ax.scatter(grid_out[x_col], grid_out[y_col], c=grid_out[col],
                    cmap="RdYlGn_r", s=6, marker=".", vmin=0, vmax=1)
    plt.colorbar(sc, ax=ax, fraction=0.046, pad=0.04, label="Probability")
    ax.set_aspect("equal")
    ax.set_title(f"$P$(Cd > {zc:g} mg/kg)")
    ax.set_xlabel("Easting (km)"); ax.set_ylabel("Northing (km)")

# last panel: histogram of predicted Cd vs cutoffs
axes[5].hist(pred_grid, bins=40, color="steelblue", edgecolor="white", density=True)
for zc in cutoffs:
    axes[5].axvline(zc, color="crimson", ls="--", lw=1, alpha=0.8)
axes[5].set_title("Predicted Cd vs cutoffs")
axes[5].set_xlabel("SK predicted Cd (mg/kg)"); axes[5].set_ylabel("Density")

plt.suptitle("Gaussian Simple Kriging — exceedance probability maps", fontsize=13, y=1.01)
plt.tight_layout(); plt.show()

Code
# Test-set calibration: Brier score for each cutoff (lower is better)
se_test_safe = np.clip(se_test, 1e-8, None)
rows = []
for zc in cutoffs:
    p_hat = 1.0 - norm.cdf((zc - z_hat) / se_test_safe)
    y_ind = (z_test > zc).astype(float)
    brier = float(np.mean((p_hat - y_ind) ** 2))
    rows.append({
        "cutoff_mgkg": zc,
        "empirical_rate_test": round(float(y_ind.mean()), 3),
        "mean_predicted_P": round(float(p_hat.mean()), 3),
        "Brier": round(brier, 4),
    })
pd.DataFrame(rows).set_index("cutoff_mgkg")
empirical_rate_test mean_predicted_P Brier
cutoff_mgkg
0.10 1.000 0.915 0.0112
0.25 0.972 0.884 0.0333
0.50 0.824 0.816 0.1119
0.75 0.639 0.728 0.2023
1.00 0.509 0.622 0.2370

13. CPU vs GPU SK Timing

Section 4.1 showed how to select a backend. Here we measure how long simple 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. Variogram fitting is done once per dataset (spherical model) and is not included in the SK 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 SK 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 SimpleKriging.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.

Code
import time

N_LAGS = 12
N_REPEATS = 3
N_PRED_GP = 500
GP_SIZES = [500, 1000, 2000, 4000, 5000]

df_gp = pd.read_csv("../data/gp_data_5000.csv")
gp_coords = df_gp[["x", "y"]].to_numpy(dtype=float)
gp_vals = df_gp["SOC"].to_numpy(dtype=float)
rng = np.random.default_rng(42)


def _fit_spherical(xy, values, use_gpu=False):
    return Variogram(
        np.asarray(xy, dtype=float),
        np.asarray(values, dtype=float),
        model="spherical",
        n_lags=N_LAGS,
        use_gpu=use_gpu,
    ).fit()


def _time_sk(xy_train, z_train, xy_pred, vg, use_gpu, repeats=N_REPEATS, warmup=True):
    """Median wall time of SimpleKriging.fit + predict(return_variance=True)."""
    mean = float(np.mean(z_train))
    if warmup:
        k_tr = min(40, len(xy_train))
        k_pr = min(40, len(xy_pred))
        SimpleKriging(vg, mean=mean, use_gpu=use_gpu).fit(
            xy_train[:k_tr], z_train[:k_tr]
        ).predict(xy_pred[:k_pr], return_variance=True)
        if use_gpu:
            import cupy as cp
            cp.cuda.Device(0).synchronize()
    times = []
    last = None
    for _ in range(repeats):
        t0 = time.perf_counter()
        sk_m = SimpleKriging(vg, mean=mean, use_gpu=use_gpu).fit(xy_train, z_train)
        last = sk_m.predict(xy_pred, return_variance=True)
        if use_gpu:
            import cupy as cp
            cp.cuda.Device(0).synchronize()
        times.append(time.perf_counter() - t0)
    return float(np.median(times)), last


jobs = [{
    "dataset": "Jura (Cd)",
    "n_obs": len(coords),
    "xy_train": np.asarray(coords, dtype=float),
    "z_train": np.asarray(z, dtype=float),
    "xy_pred": np.asarray(grid_coords, dtype=float),
}]
for n in GP_SIZES:
    n_pred = min(N_PRED_GP, n)
    pred_idx = rng.choice(n, size=n_pred, replace=False)
    jobs.append({
        "dataset": "GP (SOC)",
        "n_obs": n,
        "xy_train": gp_coords[:n],
        "z_train": gp_vals[:n],
        "xy_pred": gp_coords[pred_idx],
    })

print(f"GPU usable : {USE_GPU}")
print(f"Repeats    : {N_REPEATS}  (median wall time of SK fit + predict)")
print(f"Jura Cd    : {len(coords)} samples → {len(grid_coords)} grid nodes")
print(f"GP SOC     : {len(gp_vals)} samples from data/gp_data_5000.csv")
print(f"GP n_pred  : {N_PRED_GP} locations drawn from each prefix")
print()

rows = []
for job in jobs:
    xy_tr, z_tr, xy_pr = job["xy_train"], job["z_train"], job["xy_pred"]
    vg = _fit_spherical(xy_tr, z_tr, use_gpu=False)

    cpu_t, pred_cpu = _time_sk(xy_tr, z_tr, xy_pr, vg, use_gpu=False)
    row = {
        "dataset": job["dataset"],
        "n_train": len(xy_tr),
        "n_pred": len(xy_pr),
        "CPU (s)": cpu_t,
        "GPU (s)": np.nan,
        "speedup": np.nan,
        "match": "—",
    }

    if USE_GPU:
        gpu_t, pred_gpu = _time_sk(xy_tr, z_tr, xy_pr, vg, use_gpu=True)
        row["GPU (s)"] = gpu_t
        row["speedup"] = cpu_t / gpu_t
        z_c, se_c = pred_cpu
        z_g, se_g = pred_gpu
        row["match"] = bool(
            np.allclose(z_c, z_g, rtol=1e-4, atol=1e-4, equal_nan=True)
            and np.allclose(se_c, se_g, rtol=1e-4, atol=1e-4, equal_nan=True)
        )
        import cupy as cp
        cp.get_default_memory_pool().free_all_blocks()
    rows.append(row)

df_bench = pd.DataFrame(rows)
df_show = df_bench.copy()
df_show["CPU (ms)"] = (df_show["CPU (s)"] * 1000).round(1)
df_show["GPU (ms)"] = (df_show["GPU (s)"] * 1000).round(1)
df_show["speedup"] = df_show["speedup"].map(
    lambda x: "—" if pd.isna(x) else f"{x:.2f}×"
)
print(df_show[["dataset", "n_train", "n_pred", "CPU (ms)", "GPU (ms)", "speedup", "match"]].to_string(index=False))

fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
n_vals = df_bench["n_train"].to_numpy()
cpu_ms = df_bench["CPU (s)"].to_numpy() * 1000
gpu_ms = df_bench["GPU (s)"].to_numpy() * 1000
labels = [
    f"{int(n)}\n({ds.split()[0]})"
    for n, ds in zip(n_vals, df_bench["dataset"])
]

x = np.arange(len(n_vals))
w = 0.36
axes[0].bar(x - w / 2, cpu_ms, w, label="CPU (NumPy)", color="steelblue")
if USE_GPU and np.isfinite(gpu_ms).all():
    axes[0].bar(x + w / 2, gpu_ms, w, label="GPU (CuPy)", color="darkorange")
axes[0].set_xticks(x)
axes[0].set_xticklabels(labels, fontsize=8)
axes[0].set_ylabel("Median time (ms)")
axes[0].set_title("SimpleKriging.predict — CPU vs GPU")
axes[0].legend()
axes[0].set_yscale("log")

if USE_GPU:
    axes[1].plot(n_vals, df_bench["speedup"], "o-", color="darkgreen", lw=2)
    axes[1].axhline(1.0, color="grey", ls="--", lw=1)
    axes[1].set_xlabel("Number of training points $n$")
    axes[1].set_ylabel("Speedup (CPU time / GPU time)")
    axes[1].set_title("GPU speedup vs training size")
    axes[1].grid(True, alpha=0.3)
else:
    axes[1].text(
        0.5, 0.5,
        "GPU not usable in this environment\nCPU-only timings shown",
        ha="center", va="center", transform=axes[1].transAxes,
    )
    axes[1].set_axis_off()

plt.tight_layout()
plt.show()
GPU usable : True
Repeats    : 3  (median wall time of SK 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     140.1      18.0   7.79×   True
 GP (SOC)      500     500      44.0      10.9   4.05×   True
 GP (SOC)     1000     500     133.0      24.4   5.46×   True
 GP (SOC)     2000     500     355.9      60.5   5.89×   True
 GP (SOC)     4000     500    1250.0     207.0   6.04×   True
 GP (SOC)     5000     500    1971.8     351.6   5.61×   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 simple kriging workflow for Jura cadmium.

What we did

  1. Split 359 samples 70 / 30 with stratified random sampling by Landuse, so rare land-use class 4 is represented in both sets.
  2. Fitted six theoretical variograms on training Cd only and selected the best model by AIC.
  3. Fitted Simple Kriging with known mean \(m = \overline{\text{Cd}}_{\text{train}}\) (use_gpu=USE_GPU).
  4. Validated at held-out locations (RMSE, MAE, mean error, \(R^2\), residual maps, standardized residuals).
  5. Mapped SK predictions and kriging standard errors on jura_grid.csv.
  6. Converted \((\hat{Z},\sigma_{\text{SK}})\) 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.
  7. Timed SK on CPU vs GPU for Jura Cd and prefixes of gp_data_5000.csv.

Practical takeaways

  • Do not leak the test set into the variogram or the SK mean. Both must come from training data.
  • SK is appropriate when a global mean is credible. If Cd has a strong trend with land use or rock type, ordinary or universal kriging (or regression kriging) is usually a better next step.
  • The prediction-error map is not a map of Cd — it is a map of how well the data constrain the estimate.
  • Gaussian \(P(\text{Cd} > z_c)\) is a convenient SK by-product. Cd is right-skewed, so these probabilities are an approximation. For a distribution-free alternative, use indicator kriging.

Next steps

  • Ordinary kriging (unknown local mean) on the same split, and compare test RMSE with SK
  • Indicator kriging for the same five cutoffs without the Gaussian assumption
  • Sequential Gaussian simulation to map uncertainty beyond the SK variance

15. Resources

Textbooks

Reference Notes
Goovaerts, P. (1997). Geostatistics for Natural Resources Evaluation. Oxford University Press. Jura Cd case study; SK vs OK
Chilès, J.-P. & Delfiner, P. (2012). Geostatistics: Modeling Spatial Uncertainty (2nd ed.). Wiley. SK system and variance
Isaaks, E.H. & Srivastava, R.M. (1989). An Introduction to Applied Geostatistics. Oxford. Clear SK derivations
Webster, R. & Oliver, M.A. (2007). Geostatistics for Environmental Scientists (2nd ed.). Wiley. Applied kriging

Key papers

Paper Contribution
Krige, D.G. (1951). A statistical approach to some mine valuation and allied problems on the Witwatersrand. MSc thesis, University of the Witwatersrand. Origin of kriging
Matheron, G. (1963). Principles of geostatistics. Economic Geology 58, 1246–1266. Formal SK / OK theory
Journel, A.G. & Huijbregts, C.J. (1978). Mining Geostatistics. Academic Press. SK equations in mining practice

In this library

Object Role
pygstat.Variogram Empirical variogram + theoretical fit
pygstat.SimpleKriging SK with known mean; predict(..., return_variance=True); use_gpu=True|False|'auto'
pygstat.OrdinaryKriging Unknown-mean counterpart
Tutorial 02 Variogram models and estimators used here
Tutorial/indicator_kriging_workflow.ipynb Non-Gaussian exceedance probabilities
Back to top