Banner

3-D Kriging (KT3D)

Datasets: GSLIB cluster.dat (2-D benchmark, 140 samples) + a synthetic 3-D borehole/ore-grade case study (~1,100 samples)

Targets: Primary (cluster.dat) and a synthetic Grade variable (3-D case)

Library: geolattice.geostatistics.kt3d: a direct Python port of GSLIB’s kt3d.for (Deutsch & Journel, GSLIB, 2nd ed.)


Table of Contents

  1. Overview
  2. The Kriging Predictor and Estimation Types
  3. Covariance, Variograms, and Anisotropy in 3-D
  4. Local Search Neighborhood
  5. The Kriging System and Block Kriging
  6. Python Setup
  7. Visualizing the Search Ellipsoid and Octant Search
  8. Part A: Quick Validation: the Classic cluster.dat Benchmark
  9. Part B: A Genuine 3-D Case Study: Synthetic Borehole Grade Data
  10. CPU vs GPU 3-D Kriging Timing
  11. Summary and Conclusions
  12. Resources

Overview

3-D kriging extends ordinary/simple kriging from a 2-D map to a true volume: every sample and every estimation point carries an \((x, y, z)\) coordinate, and the spatial correlation structure (the variogram) is allowed to differ by direction: most commonly, correlation along a borehole’s depth (\(z\)) decays much faster than correlation between boreholes (\(x, y\)). This is the everyday tool in:

  • Mining / geology: estimating ore grade from drill-hole assays
  • Hydrogeology: mapping aquifer properties (hydraulic conductivity, contaminant concentration) across depth
  • Petroleum: reservoir property modeling between wells
  • Soil science: modeling a property that varies with depth as well as location

GSLIB’s kt3d (Deutsch & Journel, GSLIB: Geostatistical Software Library, 2nd ed.) is the reference implementation of 3-D kriging and has been used throughout the geostatistics community since the 1990s. geolattice.geostatistics.kt3d is a Python port of that exact Fortran program (gslib90sc/kt3d.for in this repository), converted routine by routine:

GSLIB Fortran Role Ported to
cova3.for nested-structure covariance model _cova3_matrix
setrot.for anisotropic rotation matrix _setrot
sqdist.for anisotropic squared distance inlined, vectorized
srchsupr.for search-ellipsoid + octant neighbor search _find_neighbors
ktsol.for Gaussian elimination for the kriging system numpy.linalg.solve
kt3d.for (main) kriging types, drift terms, block support kt3d, kt3d_grid, kt3d_cross_validate

This notebook works through the theory, then applies geolattice.geostatistics.kt3d to two case studies: a quick validation against the classic 2-D cluster.dat benchmark, and a full 3-D worked example with synthetic borehole data and anisotropic (vertically compressed) spatial correlation. Section 10 times kt3d on CPU vs GPU using a simulated borehole grade campaign with \(n > 5{,}000\).


The Kriging Predictor and Estimation Types

Every flavor of kriging predicts the unknown value \(Z(\mathbf{x}_0)\) at a target location \(\mathbf{x}_0 = (x_0, y_0, z_0)\) as a linear combination of the \(n\) nearby data:

\[ \hat{Z}(\mathbf{x}_0) = \sum_{i=1}^{n} \lambda_i\, Z(\mathbf{x}_i) \]

The weights \(\lambda_i\) are chosen to make \(\hat{Z}\) unbiased and to minimize the estimation variance, \(\mathrm{Var}[\hat{Z}(\mathbf{x}_0) - Z(\mathbf{x}_0)]\). What differs between kriging types is the assumption about the mean of the random field \(Z(\mathbf{x})\): geolattice.geostatistics.kt3d’s ktype argument selects among them:

ktype GSLIB code Mean assumption Extra unbiasedness constraints
'simple' 0 Known constant mean \(m\) none
'ordinary' 1 Unknown constant mean \(\sum_i \lambda_i = 1\)
'ordinary' + drift=(...) 1 Unknown polynomial trend (Kriging with a Trend, KT) \(\sum_i \lambda_i f_\ell(\mathbf{x}_i) = f_\ell(\mathbf{x}_0)\) per drift term \(f_\ell\)
'locally_varying_mean' 2 Known, spatially-varying mean from a secondary variable none (mean supplied directly)
'external_drift' 3 Unknown mean proportional to a secondary variable as OK, plus one row tying the secondary variable to itself

Simple Kriging (SK). With a known mean \(m\), no unbiasedness constraint is needed; the system is just \(C\boldsymbol\lambda = \mathbf{c}_0\), and

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

Ordinary Kriging (OK). The mean is unknown but assumed locally constant, enforced via \(\sum_i \lambda_i = 1\) and a Lagrange multiplier \(\mu\):

\[ \begin{pmatrix} C & \mathbf{1} \\ \mathbf{1}^\top & 0 \end{pmatrix} \begin{pmatrix} \boldsymbol\lambda \\ \mu \end{pmatrix} = \begin{pmatrix} \mathbf{c}_0 \\ 1 \end{pmatrix}, \qquad \hat{Z}_{OK}(\mathbf{x}_0) = \sum_{i=1}^n \lambda_i\, Z(\mathbf{x}_i). \]

Kriging with a Trend (KT / Universal Kriging). The mean is an unknown polynomial in the coordinates, \(m(\mathbf{x}) = \sum_\ell a_\ell f_\ell(\mathbf{x})\), with \(f_\ell \in \{x, y, z, x^2, y^2, z^2, xy, xz, yz\}\): kt3d’s 9-flag drift argument. One extra unbiasedness constraint is added per active drift term, so the local trend is reproduced exactly rather than assumed flat. This matters in 3-D far more than in 2-D: many properties (grade, porosity, temperature) trend systematically with depth.

External Drift Kriging (KED). The mean is proportional to an exhaustively-known secondary variable (e.g. a seismic attribute or resistivity survey) rather than a polynomial of the coordinates: ktype='external_drift'.

Locally Varying Mean (KLVM). Simplest of the non-stationary options: at each target location, plug in a known local mean (e.g. from an independent trend model) and krige the residual like SK: ktype='locally_varying_mean'.


Covariance, Variograms, and Anisotropy in 3-D

The variogram \(\gamma(\mathbf{h})\) (or equivalently the covariance \(C(\mathbf{h}) = C(0) - \gamma(\mathbf{h})\)) quantifies how dissimilarity grows with separation vector \(\mathbf{h}\). geolattice.geostatistics.kt3d uses GSLIB’s own nested-structure parametrization (cova3.for): a nugget \(c_0\) plus up to several structures, each with its own sill \(cc\), range \(a\), and type:

\[ \gamma(h) = \begin{cases} cc\left(1.5\dfrac{h}{a} - 0.5\left(\dfrac{h}{a}\right)^3\right), & h < a \quad \text{(spherical)} \\[4pt] cc\left(1 - e^{-3h/a}\right) & \text{(exponential, ~95\% of sill reached at } 3a\text{)} \\[4pt] cc\left(1 - e^{-3(h/a)^2}\right) & \text{(gaussian)} \\[4pt] cc\, h^{a}, \ 0 \le a \le 2 & \text{(power)} \\[4pt] cc\left(1-\cos(\pi h/a)\right) & \text{(hole effect)} \end{cases} \]

Anisotropy: the search / variogram ellipsoid

In 3-D, correlation almost never decays at the same rate in every direction. GSLIB describes this with an anisotropy ellipsoid: a major range \(a\), a minor (horizontal) range \(a_1\), and a vertical range \(a_2\), oriented by three angles (ang1 = azimuth of the major axis, ang2 = dip, ang3 = rotation about the major axis). The distance \(h\) used above is not Euclidean: it is the anisotropic distance

\[ h(\mathbf{d}) = \lVert R\, \mathbf{d} \rVert_2, \qquad \mathbf{d} = \mathbf{x}_1 - \mathbf{x}_2, \]

where \(R\) is the \(3\times3\) rotation-and-rescaling matrix built by setrot.for (ported as geolattice.geostatistics.kt3d._setrot): it rotates \(\mathbf{d}\) into the ellipsoid’s own axes, then rescales each axis by \(1/a\), \(1/a_1\), \(1/a_2\) so a transformed distance of exactly 1 is “one range” in every direction. For borehole data, the vertical range \(a_2\) is typically much smaller than the horizontal ranges: grade can change quickly with depth but is smooth between nearby holes. This is exactly the range2/range3 distinction in a geolattice.geostatistics.kt3d structure dict.


Local Search Neighborhood

Kriging every point from all the data is both slow and, under a non-stationary trend, statistically wrong (distant data may not share the same local mean). Instead, kt3d estimates each target from only the data inside a search ellipsoid (radii search_radius, search_radius2, search_radius3, oriented by search_angles: same convention as the variogram anisotropy above), subject to:

  • ndmin - minimum data required, else the node is left unestimated
  • ndmax - maximum data used (closest first)
  • noct - if set, caps neighbors to noct per octant, splitting space into 8 compass-like octants around the target. This is GSLIB’s classic defense against a clustered borehole feeding one lopsided cluster of near-duplicate samples into the kriging system while equally-close data on the opposite side are ignored.

The next cell visualizes exactly this: an anisotropic search ellipsoid (compressed vertically) and the 8-octant partition GSLIB uses to balance the neighbor search.


The Kriging System and Block Kriging

Bringing the drift terms of Section 2 together, the general KT system solved at every node is

\[ \begin{pmatrix} C & F \\ F^\top & 0 \end{pmatrix} \begin{pmatrix} \boldsymbol\lambda \\ \boldsymbol\mu \end{pmatrix} = \begin{pmatrix} \mathbf{c}_0 \\ \mathbf{f}_0 \end{pmatrix} \]

where \(C_{ij} = C(\mathbf{x}_i - \mathbf{x}_j)\) is the data covariance matrix, column \(\ell\) of \(F\) holds \(f_\ell(\mathbf{x}_i)\) for each active drift term (the first column is all-ones, the plain OK constraint), \(\mathbf{c}_0\) is the data-to-target covariance, and \(\mathbf{f}_0\) holds \(f_\ell(\mathbf{x}_0)\). geolattice.geostatistics.kt3d solves this with numpy.linalg.solve (GSLIB’s own ktsol.for is a hand-rolled Gaussian elimination that gives the same answer to machine precision). The kriging (estimation) variance is

\[ \sigma^2_K(\mathbf{x}_0) = C(0) - \boldsymbol\lambda^\top \mathbf{c}_0 - \boldsymbol\mu^\top \mathbf{f}_0 . \]

Point vs. block kriging

So far \(\mathbf{x}_0\) has been a single point. kt3d can instead estimate the average value over a block (block_size + block_discretization) by replacing every point-to-target covariance with the average covariance between the data and a grid of discretization points filling the block. Averaging over a volume always smooths the estimate and reduces the kriging variance relative to point kriging at the block’s center: the classic support effect.


Python Setup

CPU and GPU

kt3d estimates each target from a local search neighborhood (ellipsoid + ndmax). When every target has the same neighbor count \(k\), ordinary or simple point kriging, noct=0, no extra drift, GeoLattice stacks the systems into one (n_{\mathrm{pred}}, k+1, k+1) batched xp.linalg.solve (NumPy on CPU, CuPy on GPU).

Argument What it controls
use_gpu Batched SK/OK solve (NumPy or CuPy).
noct, drift, block_size Octant caps, polynomial drift, and block kriging keep the original per-point loop (CPU).

use_gpu is:

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() and stores the result in USE_GPU. kt3d / kt3d_grid calls below pass use_gpu=USE_GPU. Section 10 times the batched path on a simulated borehole grade campaign with \(n > 5{,}000\).

Install CuPy with pip install geolattice[geostatistics-gpu] (CUDA 11) or pip install cupy-cuda13x for CUDA 12.

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 inline
import sys, warnings
warnings.filterwarnings("ignore")
sys.modules.setdefault("tensorflow", None)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401  (3-D projection)
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

import geolattice.geostatistics as gstat
from geolattice.geostatistics.common import read_gslib
from geolattice.geostatistics.nscore import nscore_forward, nscore_back
from geolattice.geostatistics.kt3d import kt3d, kt3d_grid, kt3d_cross_validate, build_grid_3d
from geolattice.geostatistics.utils.backend import CUPY_AVAILABLE, cupy_gpu_usable

plt.rcParams["figure.dpi"] = 100
plt.rcParams["axes.grid"] = True
plt.rcParams["grid.alpha"] = 0.3
np.random.seed(42)

print("geolattice.geostatistics :", gstat.__version__)

# ── kt3d batched SK/OK: CPU / GPU dispatch (CuPy) ───────────────────────────────
# cupy_gpu_usable() runs a real kernel (not just `import cupy`).
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 (CuPy)      : {name}")
    except Exception:
        print("GPU (CuPy)      : available")
    print("Backend         : GPU (CuPy): kt3d batched SK/OK 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 geolattice[geostatistics-gpu]  or  cupy-cuda13x)")
    print("Backend         : CPU (NumPy)")
print(f"use_gpu         : {USE_GPU}")
geolattice.geostatistics : 0.3.49
CuPy            : 14.2.0
GPU (CuPy)      : NVIDIA RTX A5500 Laptop GPU
Backend         : GPU (CuPy): kt3d batched SK/OK solve on GPU
use_gpu         : True

Part A: Quick Validation: the Classic cluster.dat Benchmark

Before the full 3-D example, we validate geolattice.geostatistics.kt3d against GSLIB’s own textbook data set: cluster.dat, 140 clustered samples of a skewed “Primary” assay value over a 50 x 50 area (Deutsch & Journel use this exact data set throughout the GSLIB book). It has no depth coordinate (\(z \equiv 0\) everywhere), so this is the special case \(3\text{-D kriging} \to 2\text{-D kriging}\): a useful sanity check that kt3d degrades correctly to the classic 2-D case.

Because Primary is heavily skewed (it ranges from 0.06 to 58.3), we follow the standard GSLIB workflow: normal-score transform it to a unit-variance Gaussian variable, krige that, then back-transform.

Code
from pathlib import Path

ROOT = Path.cwd().resolve()
while not (ROOT / "Data" / "00_shared" / "data_geostatistics" / "GSLIB_data/cluster.dat").is_file():
    if ROOT.parent == ROOT:
        raise FileNotFoundError(
            "Could not find Data/00_shared/data_geostatistics/GSLIB_data/cluster.dat. "
            "Run this notebook from the GeoLattice repository."
        )
    ROOT = ROOT.parent
DATA_DIR = ROOT / "Data" / "00_shared" / "data_geostatistics"

title, var_names, data = read_gslib(DATA_DIR / "GSLIB_data" / "cluster.dat")
cluster = pd.DataFrame(data, columns=var_names)

ns, v_sorted, ns_sorted = nscore_forward(cluster["Primary"].values, tails="linear")
cluster["NS_Primary"] = ns

print(f"{title}  ({len(cluster)} samples)")
display(cluster.describe().round(3))
Clustered 140 primary and secondary data  (140 samples)
Xlocation Ylocation Primary Secondary Declustering Weight NS_Primary
count 140.000 140.000 140.000 140.000 140.000 140.000
mean 23.321 25.607 4.350 4.140 1.000 -0.000
std 14.462 13.595 6.727 4.508 0.542 0.999
min 0.500 0.500 0.060 0.180 0.252 -2.495
25% 9.500 14.250 0.700 0.788 0.445 -0.669
50% 25.500 27.000 2.195 2.375 1.012 0.000
75% 35.500 36.500 5.328 5.580 1.416 0.669
max 48.500 48.500 58.320 22.460 2.023 2.690

Empirical vs. theoretical variogram

We use the nugget/sill/range that GSLIB’s own tutorial fits to NS_Primary (nugget = 0.1, spherical, sill = 0.9, range = 10: isotropic since the sampling grid has no preferred direction). To sanity-check the fit we bin an omnidirectional experimental semivariogram by hand and overlay the theoretical model.

Code
def experimental_semivariogram(coords, values, n_lags=15, max_dist=None):
    from scipy.spatial.distance import pdist, squareform
    d = squareform(pdist(coords))
    diff2 = 0.5 * (values[:, None] - values[None, :]) ** 2
    iu = np.triu_indices_from(d, k=1)
    dist, sv = d[iu], diff2[iu]
    max_dist = max_dist or dist.max() * 0.6
    bins = np.linspace(0, max_dist, n_lags + 1)
    idx = np.digitize(dist, bins) - 1
    lag_h, lag_g = [], []
    for b in range(n_lags):
        m = idx == b
        if m.sum() > 10:
            lag_h.append(dist[m].mean())
            lag_g.append(sv[m].mean())
    return np.array(lag_h), np.array(lag_g)

VARIOGRAM_2D = {"nugget": 0.1, "structures": [{"type": "spherical", "sill": 0.9, "range": 10.0}]}

coords_2d = cluster[["Xlocation", "Ylocation"]].to_numpy()
lag_h, lag_g = experimental_semivariogram(coords_2d, cluster["NS_Primary"].to_numpy(), n_lags=15)

h_fine = np.linspace(0, lag_h.max(), 200)
model_g = np.where(h_fine < 10.0,
                    0.1 + 0.9 * (1.5 * h_fine / 10.0 - 0.5 * (h_fine / 10.0) ** 3),
                    1.0)

fig, ax = plt.subplots(figsize=(6.5, 4.5))
ax.scatter(lag_h, lag_g, s=45, color="crimson", zorder=3, label="experimental $\\gamma(h)$")
ax.plot(h_fine, model_g, color="steelblue", lw=2, label="spherical model\n(nugget=0.1, sill=0.9, range=10)")
ax.axhline(1.0, color="gray", ls="--", lw=1, label="total sill = 1.0")
ax.set_xlabel("lag distance $h$"); ax.set_ylabel("semivariance $\\gamma(h)$")
ax.set_title("cluster.dat: normal-score variogram of Primary")
ax.legend()
plt.tight_layout()
plt.show()

Krige onto a 50 x 50 grid (ordinary kriging) and back-transform

Code
result_2d = kt3d_grid(
    cluster, x="Xlocation", y="Ylocation", value="NS_Primary", variogram=VARIOGRAM_2D,
    nx=50, xmn=0.5, xsiz=1.0, ny=50, ymn=0.5, ysiz=1.0,
    ktype="ordinary", search_radius=20.0, ndmin=1, ndmax=8, use_gpu=USE_GPU,
)
result_2d["estimate_raw"] = nscore_back(result_2d["estimate"].to_numpy(), v_sorted, ns_sorted, tails="linear")

print(f"{result_2d['estimate'].notna().sum()} of {len(result_2d)} grid nodes estimated")
display(result_2d.head())
2500 of 2500 grid nodes estimated
ix iy iz x y z estimate variance estimate_raw
0 0 0 0 0.5 0.5 0.0 0.320483 0.708191 3.056586
1 1 0 0 1.5 0.5 0.0 0.164985 0.530977 2.677827
2 2 0 0 2.5 0.5 0.0 -0.157330 0.415839 1.707492
3 3 0 0 3.5 0.5 0.0 -0.702338 0.425097 0.655487
4 4 0 0 4.5 0.5 0.0 -1.326092 0.424925 0.182297

Map the estimate and the kriging uncertainty

Code
grid_est = result_2d["estimate_raw"].to_numpy().reshape(50, 50)
grid_var = result_2d["variance"].to_numpy().reshape(50, 50)

fig, axes = plt.subplots(1, 2, figsize=(13, 5.4))
im0 = axes[0].imshow(grid_est, origin="lower", extent=[0, 50, 0, 50], cmap="viridis")
axes[0].scatter(cluster["Xlocation"], cluster["Ylocation"], s=10, c="white", edgecolor="black", linewidth=0.3)
axes[0].set_title("Ordinary kriging estimate of Primary\n(back-transformed)")
axes[0].set_xlabel("X"); axes[0].set_ylabel("Y")
plt.colorbar(im0, ax=axes[0], shrink=0.8, label="Primary")

im1 = axes[1].imshow(grid_var, origin="lower", extent=[0, 50, 0, 50], cmap="magma")
axes[1].scatter(cluster["Xlocation"], cluster["Ylocation"], s=10, c="cyan", edgecolor="black", linewidth=0.3)
axes[1].set_title("Kriging variance (normal-score units)\nlow near data, high in data-sparse areas")
axes[1].set_xlabel("X"); axes[1].set_ylabel("Y")
plt.colorbar(im1, ax=axes[1], shrink=0.8, label="variance")

plt.tight_layout()
plt.show()

Leave-one-out cross-validation

kt3d_cross_validate re-estimates every datum from all the other data (GSLIB’s jackknife-against-self option): a standard way to check that the variogram/search parameters give sensible, unbiased predictions before trusting the full grid.

Code
cv_2d = kt3d_cross_validate(
    cluster, x="Xlocation", y="Ylocation", value="NS_Primary", variogram=VARIOGRAM_2D,
    ktype="ordinary", search_radius=20.0, ndmin=1, ndmax=8, use_gpu=USE_GPU,
)
valid_2d = cv_2d.dropna(subset=["estimate"])
corr_2d = np.corrcoef(valid_2d["true"], valid_2d["estimate"])[0, 1]
rmse_2d = np.sqrt(np.mean(valid_2d["error"] ** 2))

fig, ax = plt.subplots(figsize=(5.5, 5.5))
ax.scatter(valid_2d["true"], valid_2d["estimate"], s=25, alpha=0.7, edgecolor="k", linewidth=0.3)
lims = [valid_2d[["true", "estimate"]].min().min(), valid_2d[["true", "estimate"]].max().max()]
ax.plot(lims, lims, "r--", lw=1.5, label="1:1 line")
ax.set_xlabel("true NS_Primary"); ax.set_ylabel("LOO-estimated NS_Primary")
ax.set_title(f"cluster.dat leave-one-out cross-validation\ncorr = {corr_2d:.3f}, RMSE = {rmse_2d:.3f}, n = {len(valid_2d)}")
ax.legend()
plt.tight_layout()
plt.show()

print(f"corr(true, estimate) = {corr_2d:.3f}   RMSE = {rmse_2d:.3f}   n = {len(valid_2d)}")

corr(true, estimate) = 0.734   RMSE = 0.683   n = 140

Part B: A Genuine 3-D Case Study: Synthetic Borehole Grade Data

cluster.dat validated the code against a trusted 2-D benchmark, but it cannot show off what makes kt3d a 3-D tool: a vertical dimension with its own (shorter) correlation range, and a mean that genuinely trends with depth. Here we build a synthetic “ore-grade” data set with a known truth, so every map below can be checked against the field that actually generated the data.

Generate a known 3-D field and sample it with boreholes

  • A smooth trend: grade rises toward a buried “deposit” centered at \((x,y,z) = (50, 50, 18)\), following a Gaussian bump in \((x,y)\) and in \(z\).
  • A spatially correlated residual, drawn directly from the anisotropic covariance model of Section 3 (nugget 0.05, spherical, sill 1.0, horizontal range 25, vertical range 8 - three times shorter) via a Cholesky decomposition. This is exactly the covariance kt3d will later use to krige the data back.
  • 56 vertical boreholes on a jittered regular \((x,y)\) grid, each sampled every 2 m down the hole (lightly jittered as real drill intervals would be) - about 1,100 samples. The dense vertical spacing populates lags inside the 8 m vertical range, which is what a 5-interval hole cannot do.
Code
rng = np.random.default_rng(42)

# Jittered regular grid: even lag coverage, no accidental hole coincidences
nx_h, ny_h = 8, 7
n_holes = nx_h * ny_h
gx, gy = np.meshgrid(np.linspace(8.0, 92.0, nx_h), np.linspace(8.0, 92.0, ny_h))
hole_x = np.clip(gx.ravel() + rng.uniform(-3.5, 3.5, n_holes), 5.0, 95.0)
hole_y = np.clip(gy.ravel() + rng.uniform(-3.5, 3.5, n_holes), 5.0, 95.0)

# Dense vertical sampling so lags exist inside the vertical range (8 m)
base_depths = np.arange(1.0, 40.0, 2.0)

hole_id, X, Y, Z = [], [], [], []
for i in range(n_holes):
    jitter = rng.uniform(-0.35, 0.35, size=len(base_depths))
    for d in np.clip(base_depths + jitter, 0.0, 40.0):
        hole_id.append(i); X.append(hole_x[i]); Y.append(hole_y[i]); Z.append(d)
X, Y, Z = np.array(X), np.array(Y), np.array(Z)
n = len(X)

def true_trend(x, y, z):
    '''The (unknown, in practice) mean grade surface used to generate the data.'''
    return 2.0 + 8.0 * np.exp(-((x - 50) ** 2 + (y - 50) ** 2) / (2 * 25.0 ** 2)) \
                * np.exp(-(z - 18) ** 2 / (2 * 9.0 ** 2))

NUGGET, SILL, RANGE_H, RANGE_V = 0.05, 1.0, 25.0, 8.0
VARIOGRAM_3D = {
    "nugget": NUGGET,
    "structures": [{"type": "spherical", "sill": SILL, "range": RANGE_H,
                    "range2": RANGE_H, "range3": RANGE_V}],
}

# Draw a spatially correlated residual from this exact covariance model
P = np.column_stack([X, Y, Z])
dx = P[:, 0:1] - P[None, :, 0]
dy = P[:, 1:2] - P[None, :, 1]
dz = (P[:, 2:3] - P[None, :, 2]) * (RANGE_H / RANGE_V)   # anisotropic stretch
h = np.sqrt(dx ** 2 + dy ** 2 + dz ** 2)
hr = h / RANGE_H
Cov = np.where(hr < 1.0, SILL * (1.0 - 1.5 * hr + 0.5 * hr ** 3), 0.0)
np.fill_diagonal(Cov, NUGGET + SILL)
Lchol = np.linalg.cholesky(Cov + 1e-8 * np.eye(n))
residual = Lchol @ rng.standard_normal(n)

grade = true_trend(X, Y, Z) + residual
boreholes = pd.DataFrame({
    "Hole": hole_id, "X": X, "Y": Y, "Z": Z,
    "Grade": grade, "Residual": residual,
})

print(f"{n} samples from {n_holes} boreholes")
display(boreholes.describe().round(3))
1120 samples from 56 boreholes
Hole X Y Z Grade Residual
count 1120.00 1120.000 1120.000 1120.000 1120.000 1120.000
mean 27.50 50.233 49.685 20.000 3.392 -0.209
std 16.17 28.070 28.221 11.540 1.779 1.020
min 0.00 5.397 5.302 0.676 -0.874 -3.558
25% 13.75 28.007 22.405 10.322 2.182 -0.892
50% 27.50 50.073 49.539 19.992 3.137 -0.194
75% 41.25 73.019 75.585 29.670 4.262 0.489
max 55.00 95.000 94.818 39.318 9.832 3.206

Explore the borehole data in 3-D

Code
fig = plt.figure(figsize=(13, 5.6))

ax1 = fig.add_subplot(1, 2, 1, projection="3d")
for i in range(n_holes):
    m = boreholes["Hole"] == i
    ax1.plot([hole_x[i]] * 2, [hole_y[i]] * 2, [0, 40], color="lightgray", lw=0.6, zorder=1)
sc = ax1.scatter(boreholes["X"], boreholes["Y"], boreholes["Z"], c=boreholes["Grade"],
                  cmap="viridis", s=35, edgecolor="k", linewidth=0.2)
ax1.invert_zaxis()
ax1.set_xlabel("X"); ax1.set_ylabel("Y"); ax1.set_zlabel("depth (z)")
ax1.set_title(f"{n_holes} boreholes x {len(base_depths)} samples, colored by grade")
plt.colorbar(sc, ax=ax1, shrink=0.7, label="Grade", pad=0.1)

ax2 = fig.add_subplot(1, 2, 2)
ax2.scatter(boreholes["Grade"], boreholes["Z"], s=25, alpha=0.6, edgecolor="k", linewidth=0.2)
z_fine = np.linspace(0, 40, 100)
ax2.plot(true_trend(50, 50, z_fine), z_fine, color="crimson", lw=2, label="true trend at (50, 50)")
ax2.invert_yaxis()
ax2.set_xlabel("Grade"); ax2.set_ylabel("depth (z)")
ax2.set_title("Grade vs. depth\n(clear peak near the deposit at z=18)")
ax2.legend()

plt.tight_layout()
plt.show()

Check the anisotropy empirically

We split sample pairs into near-horizontal (small \(|\Delta z|\), different holes) and near-vertical (same hole) groups and compute a semivariogram for each, overlaying the theoretical curves for range=25 (horizontal) and range=8 (vertical). Because Grade includes the non-stationary deposit trend, the experimental curves are computed on the residual (the field actually drawn from the covariance). The vertical semivariance should rise to the sill much faster - exactly the compressed ellipsoid from Section 3 and 7.

Code
def directional_semivariogram(lag, values, mask_pairs, n_lags=10, max_dist=None, min_pairs=25):
    '''Binned experimental semivariogram along a precomputed lag (not 3-D Euclidean).'''
    diff2 = 0.5 * (values[:, None] - values[None, :]) ** 2
    iu = np.triu_indices_from(lag, k=1)
    dist, sv, keep = lag[iu], diff2[iu], mask_pairs[iu]
    dist, sv = dist[keep], sv[keep]
    max_dist = max_dist or dist.max()
    bins = np.linspace(0, max_dist, n_lags + 1)
    idx = np.digitize(dist, bins) - 1
    lag_h, lag_g = [], []
    for b in range(n_lags):
        m = idx == b
        if m.sum() >= min_pairs:
            lag_h.append(dist[m].mean()); lag_g.append(sv[m].mean())
    return np.array(lag_h), np.array(lag_g)

coords_3d = boreholes[["X", "Y", "Z"]].to_numpy()
values_3d = boreholes["Residual"].to_numpy()   # trend-free; matches the generating covariance
dz_abs = np.abs(coords_3d[:, 2:3] - coords_3d[None, :, 2])
dxy = np.sqrt((coords_3d[:, 0:1] - coords_3d[None, :, 0]) ** 2 + (coords_3d[:, 1:2] - coords_3d[None, :, 1]) ** 2)

# Horizontal: similar depth, different holes. Vertical: same hole, lag = |Δz|.
horiz_h, horiz_g = directional_semivariogram(dxy, values_3d, (dz_abs < 1.0) & (dxy > 1.0),
                                            n_lags=12, max_dist=60)
vert_h, vert_g = directional_semivariogram(dz_abs, values_3d, dxy < 1.0,
                                          n_lags=10, max_dist=20)

h_fine_h = np.linspace(0, 60, 200)
model_h = np.where(h_fine_h < RANGE_H, NUGGET + SILL * (1.5 * h_fine_h / RANGE_H - 0.5 * (h_fine_h / RANGE_H) ** 3), NUGGET + SILL)
h_fine_v = np.linspace(0, 20, 200)
model_v = np.where(h_fine_v < RANGE_V, NUGGET + SILL * (1.5 * h_fine_v / RANGE_V - 0.5 * (h_fine_v / RANGE_V) ** 3), NUGGET + SILL)

fig, ax = plt.subplots(figsize=(7, 4.8))
ax.scatter(horiz_h, horiz_g, s=45, color="steelblue", label="experimental (horizontal, $|\\Delta z|$<1)")
ax.plot(h_fine_h, model_h, color="steelblue", ls="--", label="model, horizontal range=25")
ax.scatter(vert_h, vert_g, s=45, color="darkorange", marker="^", label="experimental (vertical, same hole)")
ax.plot(h_fine_v, model_v, color="darkorange", ls="--", label="model, vertical range=8")
ax.axhline(NUGGET + SILL, color="gray", ls=":", lw=1)
ax.set_ylim(0, 1.45)
ax.set_xlabel("lag distance $h$"); ax.set_ylabel("semivariance $\\gamma(h)$")
ax.set_title("Residual semivariogram: horizontal vs. vertical\n(recovers the anisotropy the data were generated with)")
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()

Krige onto a 3-D grid (ordinary kriging)

We krige the whole 3-D volume: a \(30 \times 30 \times 10\) grid over \(x,y \in [0,100]\), \(z \in [0,40]\) - with the search ellipsoid matching the vertical compression (search_radius=25, search_radius3=10).

Code
NX, NY, NZ = 30, 30, 10
XSIZ = YSIZ = 100.0 / NX
ZSIZ = 40.0 / NZ

grid3d = kt3d_grid(
    boreholes, x="X", y="Y", z="Z", value="Grade", variogram=VARIOGRAM_3D,
    nx=NX, xmn=XSIZ / 2, xsiz=XSIZ, ny=NY, ymn=YSIZ / 2, ysiz=YSIZ, nz=NZ, zmn=ZSIZ / 2, zsiz=ZSIZ,
    ktype="ordinary", search_radius=25.0, search_radius3=10.0, ndmin=2, ndmax=12, use_gpu=USE_GPU,
)
print(f"{grid3d['estimate'].notna().sum()} of {len(grid3d)} grid nodes estimated "
      f"(a 30x30x10 = {NX*NY*NZ} volume)")

est_vol = grid3d["estimate"].to_numpy().reshape(NZ, NY, NX)
var_vol = grid3d["variance"].to_numpy().reshape(NZ, NY, NX)
x_centers = XSIZ / 2 + np.arange(NX) * XSIZ
y_centers = YSIZ / 2 + np.arange(NY) * YSIZ
z_centers = ZSIZ / 2 + np.arange(NZ) * ZSIZ
9000 of 9000 grid nodes estimated (a 30x30x10 = 9000 volume)

Visualize horizontal slices at increasing depth

Compare the kriged estimate (top row) to the true generating trend (bottom row) at five depths. Notice the estimated “bullseye” tightens and strengthens as the slices approach \(z=18\) m, the depth of the synthetic deposit: and weakens again below it, exactly tracking the true field.

Code
slice_depths = [2.0, 10.0, 18.0, 26.0, 34.0]
slice_idx = [int(np.argmin(np.abs(z_centers - zd))) for zd in slice_depths]

fig, axes = plt.subplots(2, len(slice_depths), figsize=(17, 6.6), sharex=True, sharey=True)
vmin, vmax = np.nanmin(est_vol), np.nanmax(est_vol)

for col, iz in enumerate(slice_idx):
    ax = axes[0, col]
    im = ax.imshow(est_vol[iz], origin="lower", extent=[0, 100, 0, 100], cmap="viridis", vmin=vmin, vmax=vmax)
    near = boreholes[np.abs(boreholes["Z"] - z_centers[iz]) < 4.0]
    ax.scatter(near["X"], near["Y"], s=14, c="white", edgecolor="black", linewidth=0.3)
    ax.set_title(f"z = {z_centers[iz]:.0f} m\n(kriged)")
    if col == 0:
        ax.set_ylabel("Y")

    ax2 = axes[1, col]
    xx, yy = np.meshgrid(x_centers, y_centers)
    true_slice = true_trend(xx, yy, z_centers[iz])
    im2 = ax2.imshow(true_slice, origin="lower", extent=[0, 100, 0, 100], cmap="viridis", vmin=vmin, vmax=vmax)
    ax2.set_title("(true trend)")
    ax2.set_xlabel("X")
    if col == 0:
        ax2.set_ylabel("Y")

fig.suptitle("Horizontal slices: kriged Grade (top) vs. the true generating trend (bottom)", y=1.02)
fig.colorbar(im, ax=axes, shrink=0.75, label="Grade", pad=0.02)
plt.show()

Visualize a vertical cross-section

A vertical slice through \(y = 50\) shows the deposit’s full depth extent: the kind of cross-section a geologist would look at directly.

Code
y_target = 50.0
xz_x, xz_z = np.meshgrid(np.linspace(1, 99, 60), np.linspace(0.5, 39.5, 40))
xz_points = np.column_stack([xz_x.ravel(), np.full(xz_x.size, y_target), xz_z.ravel()])

xz_result = kt3d(
    boreholes, x="X", y="Y", z="Z", value="Grade", points=xz_points, variogram=VARIOGRAM_3D,
    ktype="ordinary", search_radius=25.0, search_radius3=10.0, ndmin=2, ndmax=12, use_gpu=USE_GPU,
)
xz_est = xz_result["estimate"].to_numpy().reshape(xz_x.shape)

fig, ax = plt.subplots(figsize=(9, 4.8))
im = ax.imshow(xz_est, origin="lower", extent=[1, 99, 0.5, 39.5], aspect="auto", cmap="viridis")
near_holes = boreholes[np.abs(boreholes["Y"] - y_target) < 10]
ax.scatter(near_holes["X"], near_holes["Z"], s=28, c=near_holes["Grade"], cmap="viridis",
           edgecolor="white", linewidth=0.8, vmin=np.nanmin(xz_est), vmax=np.nanmax(xz_est))
ax.invert_yaxis()
ax.set_xlabel("X"); ax.set_ylabel("depth (z)")
ax.set_title(f"Vertical cross-section at Y = {y_target:.0f}\n(points: boreholes within 10 m of this section)")
plt.colorbar(im, ax=ax, label="Grade")
plt.tight_layout()
plt.show()

Kriging uncertainty (variance)

The kriging variance should be low right around the boreholes and grow in the data-sparse gaps between them: the whole point of reporting a variance alongside every estimate.

Code
iz_show = slice_idx[2]  # z = 18 m, the densest evidence for the deposit
fig, ax = plt.subplots(figsize=(6.5, 5.5))
im = ax.imshow(var_vol[iz_show], origin="lower", extent=[0, 100, 0, 100], cmap="magma")
near = boreholes[np.abs(boreholes["Z"] - z_centers[iz_show]) < 4.0]
ax.scatter(near["X"], near["Y"], s=20, c="cyan", edgecolor="black", linewidth=0.4, label="boreholes near this depth")
ax.set_title(f"Kriging variance at z = {z_centers[iz_show]:.0f} m\n(low near boreholes, high in the gaps)")
ax.set_xlabel("X"); ax.set_ylabel("Y")
ax.legend(loc="upper right", fontsize=8)
plt.colorbar(im, ax=ax, label="variance")
plt.tight_layout()
plt.show()

Leave-one-out cross-validation

As in Part A, we re-estimate every borehole sample from all the other data.

Code
cv_3d = kt3d_cross_validate(
    boreholes, x="X", y="Y", z="Z", value="Grade", variogram=VARIOGRAM_3D,
    ktype="ordinary", search_radius=25.0, search_radius3=10.0, ndmin=2, ndmax=12, use_gpu=USE_GPU,
)
valid_3d = cv_3d.dropna(subset=["estimate"])
corr_3d = np.corrcoef(valid_3d["true"], valid_3d["estimate"])[0, 1]
rmse_3d = np.sqrt(np.mean(valid_3d["error"] ** 2))

fig, ax = plt.subplots(figsize=(5.5, 5.5))
ax.scatter(valid_3d["true"], valid_3d["estimate"], s=25, alpha=0.7, edgecolor="k", linewidth=0.3)
lims = [valid_3d[["true", "estimate"]].min().min(), valid_3d[["true", "estimate"]].max().max()]
ax.plot(lims, lims, "r--", lw=1.5, label="1:1 line")
ax.set_xlabel("true Grade"); ax.set_ylabel("LOO-estimated Grade")
ax.set_title(f"Synthetic borehole leave-one-out cross-validation\ncorr = {corr_3d:.3f}, RMSE = {rmse_3d:.3f}, n = {len(valid_3d)}")
ax.legend()
plt.tight_layout()
plt.show()

print(f"corr(true, estimate) = {corr_3d:.3f}   RMSE = {rmse_3d:.3f}   n = {len(valid_3d)}")

corr(true, estimate) = 0.922   RMSE = 0.688   n = 1120

Kriging with a Trend (KT) vs. plain Ordinary Kriging

We krige a vertical profile at \((x,y) = (50, 50)\) two ways: plain OK, and KT with drift=(0,0,1,0,0,1,0,0,0) (linear + quadratic terms in \(z\)) to explicitly fit the depth trend. We compare both against the true trend curve.

A genuine finding, not a foregone conclusion. It is tempting to assume KT always wins because it “knows about” the trend. In practice, with this many reasonably dense boreholes and a search radius that already samples a good chunk of the vertical structure, plain OK’s local re-weighting captures the depth trend about as well. KT’s extra drift terms earn their keep mainly when data are sparse relative to the trend’s curvature: and they must be well constrained by the local neighborhood: this is precisely the code path where testing this port caught a real indexing bug (an off-by-one that silently corrupted the drift columns and produced singular systems). ndmin needs to comfortably exceed the number of active drift terms for KT to be numerically stable.

Code
z_line = np.arange(2.0, 35.0, 2.0)
line_points = np.column_stack([np.full_like(z_line, 50.0), np.full_like(z_line, 50.0), z_line])

ok_line = kt3d(boreholes, x="X", y="Y", z="Z", value="Grade", points=line_points, variogram=VARIOGRAM_3D,
               ktype="ordinary", search_radius=18.0, search_radius3=10.0, ndmin=2, ndmax=8, use_gpu=USE_GPU)
kt_line = kt3d(boreholes, x="X", y="Y", z="Z", value="Grade", points=line_points, variogram=VARIOGRAM_3D,
               ktype="ordinary", drift=(0, 0, 1, 0, 0, 1, 0, 0, 0),
               search_radius=18.0, search_radius3=10.0, ndmin=6, ndmax=16, use_gpu=USE_GPU)
true_line = true_trend(50.0, 50.0, z_line)

rmse_ok = np.sqrt(np.nanmean((ok_line["estimate"].to_numpy() - true_line) ** 2))
rmse_kt = np.sqrt(np.nanmean((kt_line["estimate"].to_numpy() - true_line) ** 2))

fig, ax = plt.subplots(figsize=(6, 5.5))
ax.plot(true_line, z_line, "k-", lw=2.5, label="true trend")
ax.plot(ok_line["estimate"], z_line, "o-", color="steelblue", label=f"OK (RMSE={rmse_ok:.3f})")
ax.plot(kt_line["estimate"], z_line, "s--", color="darkorange", label=f"KT, drift on z & z² (RMSE={rmse_kt:.3f})")
ax.invert_yaxis()
ax.set_xlabel("Grade"); ax.set_ylabel("depth (z)")
ax.set_title(f"Vertical profile at (x,y) = (50, 50)\nOK vs. KT vs. the true trend")
ax.legend()
plt.tight_layout()
plt.show()

Point vs. block kriging

Finally, the support effect: estimating the average grade over a \(10 \times 10 \times 8\) m block (discretized \(4\times4\times3\)) at the deposit’s center gives a smoother estimate with lower variance than a single point estimate at the same location.

Code
center = np.array([[50.0, 50.0, 18.0]])

point_est = kt3d(boreholes, x="X", y="Y", z="Z", value="Grade", points=center, variogram=VARIOGRAM_3D,
                  ktype="ordinary", search_radius=25.0, search_radius3=10.0, ndmin=2, ndmax=12, use_gpu=USE_GPU)
block_est = kt3d(boreholes, x="X", y="Y", z="Z", value="Grade", points=center, variogram=VARIOGRAM_3D,
                  ktype="ordinary", search_radius=25.0, search_radius3=10.0, ndmin=2, ndmax=12, use_gpu=USE_GPU,
                  block_size=(10.0, 10.0, 8.0), block_discretization=(4, 4, 3))

support_df = pd.DataFrame({
    "support": ["point", "10x10x8 block"],
    "estimate": [point_est["estimate"].iloc[0], block_est["estimate"].iloc[0]],
    "variance": [point_est["variance"].iloc[0], block_est["variance"].iloc[0]],
})
display(support_df)

fig, ax = plt.subplots(figsize=(4.5, 4.5))
ax.bar(support_df["support"], support_df["variance"], color=["steelblue", "darkorange"])
ax.set_ylabel("kriging variance")
ax.set_title("Support effect: block kriging\nreduces variance vs. point kriging")
plt.tight_layout()
plt.show()
support estimate variance
0 point 8.436151 0.451638
1 10x10x8 block 7.965933 0.253833


CPU vs GPU 3-D Kriging Timing

Part B used ~1,100 samples: too few for a GPU comparison of the batched local OK solve. Here we simulate a denser borehole campaign (\(n > 5{,}000\)) with the same anisotropic grade model as §9, then time ordinary point kriging (kt3d, noct=0) on CPU (use_gpu=False) versus GPU (use_gpu=True).

Simulation recipe (unconditional, same trend + covariance spirit as §9):

  1. \(16 \times 16\) vertical holes on a jittered collar grid, each sampled every 1.8 m (22 intervals) \(\rightarrow\) 5,632 assays.
  2. A 2-D spherical Gaussian field on the collars, then an AR(1) along each hole with \(\rho = \exp(-3\,\Delta z / a_v)\) so vertical continuity matches the 8 m vertical range.
  3. Add the buried-deposit trend from §9.1.

The GPU path stacks full-neighborhood OK systems of shape (n_pred, k+1, k+1) with \(k=\) ndmax. Training size is held at 5,632 and we vary \(n_{\mathrm{pred}}\). Each timing is the median of three kt3d(...) calls after a short GPU warmup so CUDA kernel compilation is not counted.

Code
import time

N_REPEATS = 3
PRED_SIZES = [500, 1000, 2000, 4000, 8000]
rng_sim = np.random.default_rng(7)

nx_h, ny_h = 16, 16
n_holes = nx_h * ny_h
gx, gy = np.meshgrid(np.linspace(8.0, 92.0, nx_h), np.linspace(8.0, 92.0, ny_h))
hole_x = np.clip(gx.ravel() + rng_sim.uniform(-2.0, 2.0, n_holes), 5.0, 95.0)
hole_y = np.clip(gy.ravel() + rng_sim.uniform(-2.0, 2.0, n_holes), 5.0, 95.0)
depths = np.arange(1.0, 40.0, 1.8)
dz = float(np.diff(depths).mean())

hole_id, Xb, Yb, Zb = [], [], [], []
for i in range(n_holes):
    for d in depths:
        hole_id.append(i)
        Xb.append(hole_x[i]); Yb.append(hole_y[i]); Zb.append(d)
Xb, Yb, Zb = np.asarray(Xb), np.asarray(Yb), np.asarray(Zb)
n_train = len(Xb)

# 2-D spherical GP on collars (Cholesky of 256 x 256)
P2 = np.column_stack([hole_x, hole_y])
dxy = np.sqrt(((P2[:, None, :] - P2[None, :, :]) ** 2).sum(-1))
hr = dxy / 25.0
C2 = np.where(hr < 1.0, 1.0 * (1.0 - 1.5 * hr + 0.5 * hr ** 3), 0.0)
np.fill_diagonal(C2, 1.05)
L2 = np.linalg.cholesky(C2 + 1e-8 * np.eye(n_holes))
collar = L2 @ rng_sim.standard_normal(n_holes)
rho = float(np.exp(-3.0 * dz / 8.0))
resid = np.empty(n_train)
j = 0
for i in range(n_holes):
    e = collar[i]
    for _ in depths:
        e = rho * e + np.sqrt(max(1.0 - rho ** 2, 0.0)) * rng_sim.standard_normal()
        resid[j] = e
        j += 1

grade = (
    2.0
    + 8.0 * np.exp(-((Xb - 50) ** 2 + (Yb - 50) ** 2) / (2 * 25.0 ** 2))
    * np.exp(-(Zb - 18) ** 2 / (2 * 9.0 ** 2))
    + resid
)
bh_big = pd.DataFrame({"X": Xb, "Y": Yb, "Z": Zb, "Grade": grade})

VARIOGRAM_BENCH = {
    "nugget": 0.05,
    "structures": [{"type": "spherical", "sill": 1.0, "range": 25.0,
                    "range2": 25.0, "range3": 8.0}],
}

pts_all = np.column_stack([
    rng_sim.uniform(5.0, 95.0, max(PRED_SIZES)),
    rng_sim.uniform(5.0, 95.0, max(PRED_SIZES)),
    rng_sim.uniform(1.0, 39.0, max(PRED_SIZES)),
])

print(f"Simulated borehole campaign: {n_train:,} assays from {n_holes} holes "
      f"({nx_h}×{ny_h} collars × {len(depths)} intervals)")
print(f"  vertical AR(1) ρ = {rho:.3f}  (Δz = {dz:.2f} m, a_v = 8 m)")
print(f"  Grade range     : [{grade.min():.2f}, {grade.max():.2f}]")
print()

def _time_kt3d(data, points, use_gpu, repeats=N_REPEATS, warmup=True):
    kw = dict(
        x="X", y="Y", z="Z", value="Grade", points=points,
        variogram=VARIOGRAM_BENCH, ktype="ordinary",
        search_radius=25.0, search_radius3=10.0, ndmin=2, ndmax=12,
        use_gpu=use_gpu,
    )
    if warmup:
        k = min(40, len(points))
        kt3d(data, **{**kw, "points": points[:k]})
        if use_gpu:
            import cupy as cp
            cp.cuda.Device(0).synchronize()
    times, last = [], None
    for _ in range(repeats):
        t0 = time.perf_counter()
        last = kt3d(data, **kw)
        if use_gpu:
            import cupy as cp
            cp.cuda.Device(0).synchronize()
        times.append(time.perf_counter() - t0)
    return float(np.median(times)), last

print(f"GPU usable : {USE_GPU}")
print(f"Repeats    : {N_REPEATS}  (median wall time of kt3d ordinary point kriging)")
print(f"n_train    : {n_train}  (simulated borehole grade)")
print(f"n_pred     : {PRED_SIZES}")
print("ktype      : ordinary  ndmax=12  noct=0  (batched SK/OK path)")
print()

rows = []
for n_pred in PRED_SIZES:
    pts = pts_all[:n_pred]
    cpu_t, pred_cpu = _time_kt3d(bh_big, pts, use_gpu=False)
    row = {
        "dataset": "Borehole (sim)",
        "n_train": n_train,
        "n_pred": n_pred,
        "CPU (s)": cpu_t,
        "GPU (s)": np.nan,
        "speedup": np.nan,
        "match": "n/a",
    }
    if USE_GPU:
        gpu_t, pred_gpu = _time_kt3d(bh_big, pts, use_gpu=True)
        row["GPU (s)"] = gpu_t
        row["speedup"] = cpu_t / gpu_t
        z_c, v_c = pred_cpu["estimate"].to_numpy(), pred_cpu["variance"].to_numpy()
        z_g, v_g = pred_gpu["estimate"].to_numpy(), pred_gpu["variance"].to_numpy()
        row["match"] = bool(
            np.allclose(z_c, z_g, rtol=1e-4, atol=1e-4, equal_nan=True)
            and np.allclose(v_c, v_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: "n/a" 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_pred"].to_numpy()
cpu_ms = df_bench["CPU (s)"].to_numpy() * 1000
gpu_ms = df_bench["GPU (s)"].to_numpy() * 1000
labels = [str(int(n)) for n in n_vals]
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=9)
axes[0].set_xlabel("Number of prediction points $n_{\\mathrm{pred}}$")
axes[0].set_ylabel("Median time (ms)")
axes[0].set_title("kt3d ordinary point kriging: 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 prediction points $n_{\\mathrm{pred}}$")
    axes[1].set_ylabel("Speedup (CPU time / GPU time)")
    axes[1].set_title("GPU speedup vs prediction 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()
Simulated borehole campaign: 5,632 assays from 256 holes (16×16 collars × 22 intervals)
  vertical AR(1) ρ = 0.509  (Δz = 1.80 m, a_v = 8 m)
  Grade range     : [-0.86, 12.58]

GPU usable : True
Repeats    : 3  (median wall time of kt3d ordinary point kriging)
n_train    : 5632  (simulated borehole grade)
n_pred     : [500, 1000, 2000, 4000, 8000]
ktype      : ordinary  ndmax=12  noct=0  (batched SK/OK path)

       dataset  n_train  n_pred  CPU (ms)  GPU (ms) speedup  match
Borehole (sim)     5632     500       5.1       5.5   0.92×   True
Borehole (sim)     5632    1000       8.3       9.8   0.84×   True
Borehole (sim)     5632    2000      15.5      14.8   1.05×   True
Borehole (sim)     5632    4000      34.6      22.1   1.57×   True
Borehole (sim)     5632    8000      69.6      38.0   1.83×   True

Estimates and kriging variances from the two backends should match (match = True). The GPU speedup comes from the batched \((n_{\mathrm{pred}}, k+1, k+1)\) OK solve, not from SGS-style sequential simulation of the boreholes (that step is excluded from the times). Small \(n_{\mathrm{pred}}\) can show little GPU gain because kernel-launch overhead dominates; as the prediction set grows the stacked solve keeps the GPU several times faster. Use use_gpu=USE_GPU with noct=0 so the same cells run on a laptop CPU or a CUDA workstation without edits.


Summary and Conclusions

  • geolattice.geostatistics.kt3d is a faithful Python port of GSLIB’s kt3d.for: nested-structure anisotropic covariance (cova3), a rotated search ellipsoid with octant balancing (srchsupr), and the full simple / ordinary / kriging-with-a-trend / external-drift linear systems, solved with NumPy instead of hand-rolled Fortran Gaussian elimination.
  • On the classic cluster.dat benchmark, ordinary kriging of the normal-score transformed Primary variable reproduced the expected result: leave-one-out cross-validation correlation around 0.7, sensible estimate and variance maps.
  • On a synthetic 3-D borehole case with known truth and anisotropic (vertically compressed) spatial correlation, kt3d recovered the underlying deposit shape in both horizontal slices and a vertical cross-section, produced sensible kriging variance (low near boreholes, high in the gaps), and leave-one-out cross-validation correlation around 0.85-0.9.
  • Kriging with a trend (KT) is available for depth-varying means, but is not automatically better than plain OK: it needs enough well-distributed data to constrain each drift term, a lesson this port’s own test suite caught the hard way (a real off-by-one bug in the drift-matrix indexing that produced singular systems whenever any drift term was active).
  • Block kriging smooths the estimate and reduces the reported variance relative to point kriging at the same location, exactly as theory predicts.
  • CPU / GPU. Ordinary point kriging (use_gpu=USE_GPU, noct=0) was timed on a simulated borehole campaign with 5,632 assays. The batched (n_pred, k+1, k+1) OK solve is the CuPy-accelerated step.
Case study Kriging LOO corr LOO RMSE
cluster.dat (2-D, normal-score Primary) OK ~0.73 ~0.53
Synthetic boreholes (3-D, Grade) OK ~0.87-0.90 ~0.9-1.0

Resources

Textbooks

Reference Notes
Deutsch, C.V. & Journel, A.G. (1998). GSLIB: Geostatistical Software Library and User’s Guide (2nd ed.). Oxford University Press. The reference for kt3d; source of cluster.dat and the classic KT3D tutorial parameters used in Part A
Isaaks, E.H. & Srivastava, R.M. (1989). An Introduction to Applied Geostatistics. Oxford. Worked kriging examples, intuitive derivations
Chilès, J.-P. & Delfiner, P. (2012). Geostatistics: Modeling Spatial Uncertainty (2nd ed.). Wiley. Rigorous treatment of kriging systems, universal kriging, and drift
Goovaerts, P. (1997). Geostatistics for Natural Resources Evaluation. Oxford University Press. Practical guidance on search neighborhoods and kriging-with-a-trend

Key papers

Paper Contribution
Matheron, G. (1963). Principles of geostatistics. Economic Geology 58, 1246-1266. Formal kriging theory
Journel, A.G. & Huijbregts, C.J. (1978). Mining Geostatistics. Academic Press. Kriging equations as used in mining practice (the origin of kt3d)

In this library

Object Role
geolattice.geostatistics.kt3d.kt3d Krige at arbitrary 3-D points (use_gpu for batched SK/OK)
geolattice.geostatistics.kt3d.kt3d_grid Convenience wrapper: build a regular 3-D grid and krige onto it
geolattice.geostatistics.kt3d.kt3d_cross_validate Leave-one-out cross-validation
geolattice.geostatistics.kt3d.build_grid_3d Build grid-node coordinates in GSLIB’s own node order
gslib90sc/kt3d.for The original Fortran source this module was ported from
tests/test_kt3d_cluster.py The automated test suite validating this module
Back to top