Target: Zinc (zinc, ppm), modelled as \(\log(\mathrm{zinc})\) for sequential Gaussian simulation
Library:pygstat.sgsim — Sequential Gaussian Simulation in the GSLIB sgsim family (Deutsch & Journel, GSLIB, 2nd ed.)
1. Overview
src/pygstat/sgsim.py is a new module ported from GSLIB’s sgsim algorithm. Important caveat: Helper_packages/Gslib90/sgsim.exe is a compiled 2005 Windows binary – there is no Fortran source anywhere in this project, so it could not be literally “converted.” This is instead a from-scratch Python implementation of the documented GSLIB SGS algorithm (Deutsch & Journel), built on GStatSim’s (gstatsim.py) proven kriging engine (rotation matrix, octant search, covariance functions) given as the starting point, extended with two real sgsim.exe capabilities gstatsim.py’s per-call functions don’t bundle: multiple realizations per call (nsim) and an integrated normal-score transform/back-transform (itrans, using this repo’s own nscore.py).
This notebook validates the actual algorithmic properties SGS is supposed to have, not just “it runs”:
Exact conditioning – simulated values at data locations must equal the input data exactly, in every realization.
Realization variability – unconditioned nodes must differ between realizations (that’s the point of simulation vs. kriging).
Global statistics reproduction – across many realizations, the simulated distribution should resemble the original data distribution (SGS is designed to reproduce the histogram, unlike smoothing kriging).
Local kriging honesty – averaged over many realizations, the E-type mean at each node should be close to ordinary kriging’s estimate there (simulation’s expected value should agree with kriging).
itrans correctness – with itrans=True on raw (non-Gaussian) zinc, results should come back in original units, not normal-score units.
Reproducibility – same seed gives identical realizations; no seed (or a different seed) gives different ones.
Variogram reproduction — experimental variograms of every realization should cluster around the covariance model used to drive SGS.
Spatial uncertainty — an animation of the ensemble plus conditional quantile maps (q10, median, q90) distinguish areas that stay stable across realizations (low uncertainty) from those that fluctuate (high uncertainty).
CPU vs GPU — time sgsim on prefixes of meuse_grid.csv (use_gpu=False vs True), both at nsim=1 (nodes one at a time — often slower at typical \(k\), §12.1) and scanning nsim (realizations don’t depend on each other, so pygstat.sgsim batches them together on the GPU when nsim >= 2 instead of dispatching one node at a time, §12.2).
sgsim(..., use_gpu=False|'auto'|True) dispatches local covariance build + solve to NumPy (CPU) or CuPy (GPU). Sequential Gaussian simulation visits nodes in a random path: the local kriging system at node \(i\) depends on already-simulated nodes, so the \(n_{\mathrm{pred}}\) systems within one realization cannot be stacked the way independent kriging predictions can. What GPU dispatch does depends on nsim:
nsim == 1: one node at a time (nothing to batch against) — §12.1.
nsim >= 2: realizations don’t depend on each other, so all nsim local kriging systems at each step are batched into one GPU call instead of one per node per realization — §12.2.
Argument
What it controls
use_gpu
Covariance + solve dispatch (NumPy or CuPy); per-node at nsim=1, batched across realizations at nsim>=2. Default False.
itrans
Normal-score transform / back-transform; stays on CPU.
use_gpu is:
Value
Behaviour
False (default)
Always CPU (NumPy).
'auto'
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.
This notebook probes the GPU once with cupy_gpu_usable() and stores the result in USE_GPU. The Meuse maps in §3–11 keep the default use_gpu=False. §12 times CPU vs GPU on prefixes of meuse_grid.csv (§12.1, nsim=1) and across a range of nsim at a fixed grid size (§12.2).
Install CuPy with pip install pygstat[gpu] (CUDA 11) or pip install cupy-cuda12x for CUDA 12.
Code
%matplotlib inlineimport sys, os, time, warningswarnings.filterwarnings("ignore")sys.path.insert(0, os.path.abspath("../src"))import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom IPython.display import HTML, displayimport pygstatfrom pygstat import sgsim, Variogram, OrdinaryKrigingprint("pygstat version:", pygstat.__version__)from pygstat.utils.backend import CUPY_AVAILABLE, cupy_gpu_usable# ── sgsim per-node covariance + lstsq: CPU / GPU dispatch (CuPy) ────────────# 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 (CuPy) : {name}")exceptException:print("GPU (CuPy) : available")print("Backend : GPU (CuPy) — sgsim per-node covariance + lstsq")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}")RESULTS = []def record(section, status, note=""): RESULTS.append({"Feature": section, "Status": status, "Notes": note}) marker = {"PASS": "\u2705", "FAIL": "\u274c", "BLOCKED": "\u26a0\ufe0f"}.get(status, "?")print(f"{marker} [{status}] {section}{note}")
Simulate on a grid that includes several real meuse sample locations plus new points, across several realizations. Every realization must reproduce the true conditioning value exactly at the real locations.
Code
n_cond_check =15cond_idx = np.random.default_rng(0).choice(len(coords), size=n_cond_check, replace=False)cond_pts = coords[cond_idx]new_pts = np.column_stack([ np.random.default_rng(1).uniform(xmin, xmax, 20), np.random.default_rng(2).uniform(ymin, ymax, 20),])grid = np.vstack([cond_pts, new_pts])sims = sgsim(grid, df, "x", "y", "log_zinc", num_points=16, vario=vario, radius=3000, kriging_type="ordinary", nsim=5, itrans=True, seed=42, quiet=True)true_vals = log_zinc[cond_idx]exact =all(np.allclose(sims[r, :n_cond_check], true_vals, atol=1e-8) for r inrange(sims.shape[0]))record("Exact conditioning at data locations", "PASS"if exact else"FAIL",f"max abs error across {sims.shape[0]} realizations = "f"{np.max(np.abs(sims[:, :n_cond_check] - true_vals)):.2e}")varies =not np.allclose(sims[:, n_cond_check:], sims[0, n_cond_check:])record("Realizations vary at unconditioned nodes", "PASS"if varies else"FAIL",f"std across realizations at new points: mean={sims[:, n_cond_check:].std(axis=0).mean():.3f}")
✅ [PASS] Exact conditioning at data locations max abs error across 5 realizations = 0.00e+00
✅ [PASS] Realizations vary at unconditioned nodes std across realizations at new points: mean=0.311
4. Global Statistics Reproduction
Run many realizations over the full meuse extent and compare the pooled simulated-value histogram to the original zinc data’s histogram. SGS is designed to reproduce the input distribution (unlike kriging, which smooths it).
✅ [PASS] Global distribution reproduction original: mean=5.886 std=0.720; pooled SGS: mean=6.029 std=0.822
5. Local Kriging Honesty (E-type vs. Ordinary Kriging)
SGS’s expected value at each node (averaged over many realizations, the “E-type” estimate) should be close to what ordinary kriging predicts at the same node – simulation adds variability around the same underlying kriging estimate, it doesn’t change it.
✅ [PASS] SGS E-type agrees with ordinary kriging correlation=0.932, mean abs diff=0.192
6. itrans Correctness
With itrans=True on raw (non-Gaussian) zinc, simulated output should come back in original zinc units (hundreds-to-thousands range), not normal-score units (roughly -3 to 3).
Code
vario_raw = [0, 0.05*np.var(df["zinc"].values), 900.0, 900.0, float(np.var(df["zinc"].values)), "exponential"]sims_raw = sgsim(grid[:10], df, "x", "y", "zinc", num_points=16, vario=vario_raw, radius=3000, kriging_type="ordinary", nsim=3, itrans=True, seed=3, quiet=True)in_original_units = sims_raw.min() >0and sims_raw.max() <5000print(f"sgsim(itrans=True) on raw zinc -> range [{sims_raw.min():.1f}, {sims_raw.max():.1f}] "f"(original zinc range: [{df['zinc'].min():.1f}, {df['zinc'].max():.1f}])")record("itrans=True returns original units", "PASS"if in_original_units else"FAIL",f"range [{sims_raw.min():.1f}, {sims_raw.max():.1f}]")# Conditioning still exact in raw-unit space tootrue_raw = df["zinc"].values[cond_idx[:10]] iflen(cond_idx) >=10elseNone
sgsim(itrans=True) on raw zinc -> range [155.0, 906.0] (original zinc range: [113.0, 1839.0])
✅ [PASS] itrans=True returns original units range [155.0, 906.0]
7. Reproducibility
Same seed -> identical realizations. Different seed (or seed=None) -> different realizations.
✅ [PASS] kriging_type='simple' and Matern covariance simple range=[5.04,6.81], matern range=[5.04,6.81]
9. Full Prediction on meuse_grid.csv
Everything above used small synthetic grids to keep validation fast. Here sgsim predicts on the realexamples/data/meuse_grid.csv (3103 masked points on meuse’s actual 40m lattice) with 20 realizations – enough for a meaningful E-type estimate. 4 of the 20 realizations are picked at random to show individually, alongside the E-type (mean) and simulation standard deviation (uncertainty) across all 20.
Code
grid_df = pd.read_csv("../data/meuse_grid.csv")full_grid = grid_df[["x", "y"]].valuesprint(f"meuse_grid.csv: {len(full_grid)} points")N_REALIZATIONS =20t0 = time.time()sims_grid = sgsim(full_grid, df, "x", "y", "log_zinc", num_points=16, vario=vario, radius=1200, kriging_type="ordinary", nsim=N_REALIZATIONS, itrans=True, seed=2024, quiet=True)elapsed = time.time() - t0print(f"{N_REALIZATIONS} realizations x {len(full_grid)} points in {elapsed/60:.1f} min "f"({elapsed/N_REALIZATIONS:.1f}s/realization)")finite = np.all(np.isfinite(sims_grid))record("sgsim on full meuse_grid.csv", "PASS"if finite else"FAIL",f"{N_REALIZATIONS} realizations x {len(full_grid)} points, "f"range=[{sims_grid.min():.2f}, {sims_grid.max():.2f}], {elapsed/60:.1f} min")
meuse_grid.csv: 3103 points
20 realizations x 3103 points in 16.6 min (49.7s/realization)
✅ [PASS] sgsim on full meuse_grid.csv 20 realizations x 3103 points, range=[4.60, 7.67], 16.6 min
✅ [PASS] meuse_grid.csv E-type agrees with ordinary kriging correlation=0.985
10. Variogram of All Realizations
A well-specified sequential Gaussian simulation should reproduce the input variogram: each realization is a random field whose spatial continuity matches the covariance model used to krige along the random path.
Here we compute the experimental (Matheron) semivariogram \(\hat{\gamma}(h)\) of every realization on meuse_grid.csv and overlay them on the sample variogram and the GSLIB exponential model that drove sgsim. Realizations that cluster around the model (without collapsing toward a pure nugget or a much longer range) confirm that SGS is reproducing spatial structure, not just the histogram.
The theoretical curve uses GSLIB’s practical-range exponential,
with nugget \(c_0\), total sill \(c\), and practical range \(a\) taken from the vario list passed to sgsim (this is notpygstat.Variogram’s \(1-\exp(-h/\mathrm{range})\) parametrization).
Code
from scipy.spatial.distance import pdist, squareformn_lags =15maxlag =1500.0bins = np.linspace(0.0, maxlag, n_lags +1)lag_centers =0.5* (bins[:-1] + bins[1:])# Distances on the prediction grid (shared by every realization)grid_dists = squareform(pdist(full_grid))def matheron_gamma(values, dists, bins):# Classical experimental (Matheron) semivariogram at the given lag bins. diffs = values[:, None] - values[None, :] gamma = np.empty(len(bins) -1, dtype=float)for i inrange(len(bins) -1): mask = (dists > bins[i]) & (dists <= bins[i +1]) gamma[i] =0.5* np.mean(diffs[mask] **2) if np.any(mask) else np.nanreturn gamma# Sample variogram of log(zinc)sample_dists = squareform(pdist(coords))gamma_sample = matheron_gamma(log_zinc, sample_dists, bins)# One experimental variogram per realizationgamma_reals = np.vstack( [matheron_gamma(sims_grid[r], grid_dists, bins) for r inrange(N_REALIZATIONS)])gamma_mean = np.nanmean(gamma_reals, axis=0)# GSLIB practical-range exponential used by sgsimnugget, prac_range, total_sill = vario[1], vario[2], vario[4]h_th = np.linspace(0.0, maxlag, 250)gamma_model = nugget + (total_sill - nugget) * (1.0- np.exp(-3.0* h_th / prac_range))fig, ax = plt.subplots(figsize=(8.2, 5.4))for r inrange(N_REALIZATIONS): ax.plot( lag_centers, gamma_reals[r], color="0.75", lw=0.8, alpha=0.7, label="realizations"if r ==0elseNone, )ax.plot(lag_centers, gamma_mean, color="tab:orange", lw=2.2, label="mean of realizations")ax.plot(lag_centers, gamma_sample, "o", color="tab:blue", ms=7, zorder=4, label="sample variogram (log zinc)")ax.plot(h_th, gamma_model, color="crimson", lw=2.0, ls="--", label="GSLIB exponential model")ax.axhline(total_sill, color="0.4", ls=":", lw=1, label="sill")ax.set_xlim(0, maxlag)ax.set_ylim(0, None)ax.set_xlabel("Lag distance $h$ (m)")ax.set_ylabel(r"Semivariance $\gamma(h)$")ax.set_title("Variogram reproduction across SGS realizations")ax.legend(loc="lower right", frameon=True)plt.tight_layout()plt.show()# Realizations should sit near the model, not collapse to a nuggetmean_abs_dev = np.nanmean(np.abs(gamma_mean - ( nugget + (total_sill - nugget) * (1.0- np.exp(-3.0* lag_centers / prac_range)))))record("Variogram of all realizations tracks the SGS model","PASS"if mean_abs_dev <0.25else"FAIL",f"mean |gamma_bar - model| = {mean_abs_dev:.3f} over {N_REALIZATIONS} realizations",)
✅ [PASS] Variogram of all realizations tracks the SGS model mean |gamma_bar - model| = 0.043 over 20 realizations
11. Visualization of Spatial Uncertainty
The set of realizations provides a measure of uncertainty about the spatial distribution of zinc concentration. Differences among the realizations describe the uncertainty. Such uncertainty can be visualized through an animated display of all realizations, which allows one to distinguish areas that remain stable over all realizations (low uncertainty) from those where large fluctuations occur between realizations (high uncertainty).
The same ensemble is then summarized by conditional quantile maps. At each grid node the 0.10, 0.50, and 0.90 quantiles of the simulated values are mapped. High values (yellow) of the 0.1-quantile map indicate areas where the unknown concentration is certainly large, whereas low values (dark yellow) of the 0.9-quantile map indicate areas where the concentration is certainly small.
11.1 Animated Display of All Realizations
Play the 20 realizations in sequence (same colour scale). Floodplain patches that barely change colour are well constrained by nearby samples; patches that flash between dark and bright yellow are poorly informed and carry most of the spatial uncertainty.
✅ [PASS] Animated display of all realizations 20 frames, colour scale [4.75, 7.32] log(zinc)
11.2 Conditional Quantile Maps (q10, Median, q90)
For each floodplain node \(\mathbf{x}_0\) the local ccdf is the empirical distribution of the \(L\) simulated values \(\{z^{(\ell)}(\mathbf{x}_0)\}_{\ell=1}^{L}\). The maps below are the 0.10, 0.50, and 0.90 quantiles of that local distribution.
How to read them (Goovaerts, 1997):
High values (yellow) of the 0.1-quantile map mark areas where the unknown concentration is certainly large — even the lower tail of the local ccdf is high.
Low values (dark yellow) of the 0.9-quantile map mark areas where the unknown concentration is certainly small — even the upper tail of the local ccdf is low.
Where q10 is dark and q90 is bright, the local distribution is wide: the concentration is poorly constrained (high uncertainty).
Code
q10 = np.quantile(sims_grid, 0.10, axis=0)q50 = np.quantile(sims_grid, 0.50, axis=0)q90 = np.quantile(sims_grid, 0.90, axis=0)print(f"q10 log(zinc): min {q10.min():.2f} mean {q10.mean():.2f} max {q10.max():.2f}")print(f"q50 log(zinc): min {q50.min():.2f} mean {q50.mean():.2f} max {q50.max():.2f}")print(f"q90 log(zinc): min {q90.min():.2f} mean {q90.mean():.2f} max {q90.max():.2f}")fig, axes = plt.subplots(1, 3, figsize=(16, 5.2))panels = [ (q10, "0.10-quantile (q10)"), (q50, "Median (q50)"), (q90, "0.90-quantile (q90)"),]for ax, (vals, title) inzip(axes, panels): sc = ax.scatter( full_grid[:, 0], full_grid[:, 1], c=vals, cmap="YlOrRd", s=8, marker=".", vmin=vmin, vmax=vmax, ) ax.scatter( df["x"], df["y"], facecolors="none", edgecolors="k", s=22, linewidths=0.5, ) plt.colorbar(sc, ax=ax, label="log(zinc)", fraction=0.046, pad=0.04) ax.set_title(title) ax.set_xlabel("Easting (m)") ax.set_ylabel("Northing (m)") ax.set_aspect("equal")fig.suptitle("Conditional quantile maps of log(zinc)", y=1.02, fontsize=13)plt.tight_layout()plt.show()# Width of the local 80% probability interval as a scalar uncertainty checkiqr80 = q90 - q10record("Conditional quantile maps (q10, median, q90)","PASS",f"mean 80% interval width = {iqr80.mean():.3f} log(zinc); "f"q10 max = {q10.max():.2f} (certainly large); "f"q90 min = {q90.min():.2f} (certainly small)",)
q10 log(zinc): min 4.69 mean 5.33 max 7.35
q50 log(zinc): min 4.76 mean 5.67 max 7.46
q90 log(zinc): min 4.80 mean 6.06 max 7.53
✅ [PASS] Conditional quantile maps (q10, median, q90) mean 80% interval width = 0.728 log(zinc); q10 max = 7.35 (certainly large); q90 min = 4.80 (certainly small)
12. CPU vs GPU Sequential Gaussian Simulation Timing
Sequential Gaussian simulation is sequentialwithin one realization: each node’s local ordinary-kriging system depends on already-simulated neighbours, so pygstat cannot batch nodes the way OrdinaryKriging.predict or k-NN Poisson kriging can. But the realizations (nsim) don’t depend on each other at all, and pygstat.sgsim exploits that: when use_gpu=True and nsim >= 2, it runs all realizations in lockstep and batches every step’s local kriging systems into one GPU call, instead of dispatching them one node at a time. Two experiments separate the two regimes:
§12.1 times nsim=1 – nothing to batch against, so this is the “one node at a time” GPU dispatch, included as the baseline.
§12.2 fixes the grid size and scans nsim from 1 up to 32, isolating what realization-batching buys on top of §12.1.
Both use Meuse zinc conditioning data (data/meuse.csv, 155 samples) and prefixes of data/meuse_grid.csv, neighborhood \(k=16\), radius=1200 m (same as §9), itrans=False (the normal-score transform is CPU-only and would otherwise mix into the times), and a short GPU warmup so CUDA kernel compilation is not counted. If CuPy cannot run a kernel here, the GPU columns are skipped. The full 3,103-node × 20-realization grid in §9 is not re-timed.
12.1 Per-Node GPU Dispatch (nsim=1)
Baseline: nsim=1, so there is nothing to batch across realizations – use_gpu=True dispatches each node’s own covariance build + lstsq to CuPy individually, one node at a time. Timed here on prefixes of meuse_grid.csv, median of three repeats.
Code
import timeN_REPEATS =3PRED_SIZES = [200, 400, 800, 1600]K =16RADIUS =1200.0SEED =7grid_xy = pd.read_csv("../data/meuse_grid.csv")[["x", "y"]].to_numpy(dtype=float)n_cond =len(df)print("Meuse zinc sequential Gaussian simulation")print(f" conditioning : {n_cond} samples from data/meuse.csv (log zinc)")print(" vario : azimuth=0, nugget=0.05, range=900 m, exponential")print(f" grid : prefixes of meuse_grid.csv ({len(grid_xy)} nodes, 40 m lattice)")print(f" neighbors : k={K}; radius={RADIUS:.0f} m; nsim=1; ordinary kriging")print()def _time_sgs(xy, use_gpu, repeats=N_REPEATS, warmup=True):"""Median wall time of sgsim (nsim=1, itrans=False).""" kw =dict( prediction_grid=xy, df=df, xx="x", yy="y", zz="log_zinc", num_points=K, vario=vario, radius=RADIUS, kriging_type="ordinary", nsim=1, itrans=False, seed=SEED, quiet=True, use_gpu=use_gpu, )if warmup: sgsim( prediction_grid=xy[: min(40, len(xy))],**{k: v for k, v in kw.items() if k !="prediction_grid"}, )if use_gpu:import cupy as cp cp.cuda.Device(0).synchronize() times = [] last =Nonefor _ inrange(repeats): t0 = time.perf_counter() last = sgsim(**kw)if use_gpu:import cupy as cp cp.cuda.Device(0).synchronize() times.append(time.perf_counter() - t0)returnfloat(np.median(times)), lastprint(f"GPU usable : {USE_GPU}")print(f"Repeats : {N_REPEATS} (median wall time of sgsim, nsim=1)")print(f"n_cond : {n_cond} (Meuse samples)")print(f"n_pred : {PRED_SIZES} (prefixes of meuse_grid.csv)")print(f"neighbors : {K}; radius={RADIUS:.0f}")print()rows = []for n_pred in PRED_SIZES: xy = grid_xy[:n_pred] cpu_t, pred_cpu = _time_sgs(xy, use_gpu=False) row = {"dataset": "Meuse zinc","n_cond": n_cond,"n_pred": n_pred,"CPU (s)": cpu_t,"GPU (s)": np.nan,"speedup": np.nan,"match": "—", }if USE_GPU: gpu_t, pred_gpu = _time_sgs(xy, use_gpu=True) row["GPU (s)"] = gpu_t row["speedup"] = cpu_t / gpu_t row["match"] =bool(np.allclose(pred_cpu, pred_gpu, rtol=1e-4, atol=1e-4))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 (s)"] = df_show["CPU (s)"].round(3)df_show["GPU (s)"] = df_show["GPU (s)"].round(3)df_show["speedup"] = df_show["speedup"].map(lambda x: "—"if pd.isna(x) elsef"{x:.2f}×")print(df_show[["dataset", "n_cond", "n_pred", "CPU (s)", "GPU (s)", "speedup", "match"]].to_string(index=False))print()fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))n_vals = df_bench["n_pred"].to_numpy()cpu_s = df_bench["CPU (s)"].to_numpy()gpu_s = df_bench["GPU (s)"].to_numpy()labels = [str(int(n)) for n in n_vals]x = np.arange(len(n_vals))w =0.36axes[0].bar(x - w /2, cpu_s, w, label="CPU (NumPy)", color="steelblue")if USE_GPU and np.isfinite(gpu_s).all(): axes[0].bar(x + w /2, gpu_s, w, label="GPU (CuPy)", color="darkorange")axes[0].set_xticks(x)axes[0].set_xticklabels(labels, fontsize=9)axes[0].set_xlabel(r"Number of simulation nodes $n_{\mathrm{pred}}$")axes[0].set_ylabel("Median time (s)")axes[0].set_title("sgsim (nsim=1, k=16) — CPU vs GPU")axes[0].legend()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(r"Number of simulation nodes $n_{\mathrm{pred}}$") axes[1].set_ylabel("Speedup (CPU time / GPU time)") axes[1].set_title("GPU speedup vs grid 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()
Meuse zinc sequential Gaussian simulation
conditioning : 155 samples from data/meuse.csv (log zinc)
vario : azimuth=0, nugget=0.05, range=900 m, exponential
grid : prefixes of meuse_grid.csv (3103 nodes, 40 m lattice)
neighbors : k=16; radius=1200 m; nsim=1; ordinary kriging
GPU usable : True
Repeats : 3 (median wall time of sgsim, nsim=1)
n_cond : 155 (Meuse samples)
n_pred : [200, 400, 800, 1600] (prefixes of meuse_grid.csv)
neighbors : 16; radius=1200
dataset n_cond n_pred CPU (s) GPU (s) speedup match
Meuse zinc 155 200 1.427 1.973 0.72× True
Meuse zinc 155 400 2.793 3.858 0.72× True
Meuse zinc 155 800 5.602 7.740 0.72× True
Meuse zinc 155 1600 11.410 15.390 0.74× True
CPU and GPU realizations should match (match = True) for the same seed. Speedup stays below \(1\) at every grid size: SGS cannot batch nodes, so each of the \(n_{\mathrm{pred}}\) local \(17\times 17\) solves is a separate CuPy launch and copy. Wall time scales linearly with \(n_{\mathrm{pred}}\) on both backends (~7 ms/node CPU, ~10 ms/node GPU on this RTX 2080 Ti). The GPU path is there for unusually large num_points; for typical SGS neighbourhoods, keep the default use_gpu=False.
12.2 Batching Realizations on the GPU (nsim ≥ 2)
Realizations don’t depend on each other – only nodes within one realization do. _simulate_batch (used automatically when use_gpu=True and nsim >= 2) runs all nsim realizations in lockstep: at each shared step, all nsim local kriging systems are stacked into one batched covariance build + xp.linalg.solve, instead of one CuPy dispatch per node per realization. That should turn §12.1’s “always below 1×” into a real win once there is enough to batch.
This fixes the grid to meuse_grid.csv’s first 200 nodes (same k=16, radius=1200) and scans nsim from 1 to 32, comparing:
CPU: nsim independent calls to _simulate_one (unchanged).
These calls are already long enough (seconds, not milliseconds) that run-to-run variance is small next to the trend, so each nsim is timed once rather than as a median of repeats. Because _simulate_batch solves with a small ridge via xp.linalg.solve where the CPU path uses lstsq (see _simulate_batch’s docstring), CPU and GPU realizations are compared with a looser tolerance (atol=rtol=1e-2) than an exact match. A quick diagnostic at the end times _octant_search itself (the per-realization, pandas-based neighbor lookup that batching does not touch) against total wall time, to show what actually caps the achievable speedup.
Code
import importlibNSIM_LIST = [1, 2, 4, 8, 16, 32]N_PRED_NSIM =200grid_xy_nsim = grid_xy[:N_PRED_NSIM]print(f"n_pred : {N_PRED_NSIM} (fixed, first {N_PRED_NSIM} nodes of meuse_grid.csv)")print(f"neighbors : k={K}; radius={RADIUS:.0f}")print(f"nsim : {NSIM_LIST}")print()def _time_sgs_nsim(nsim, use_gpu):"""Single-call wall time of sgsim at a given nsim.""" kw =dict( prediction_grid=grid_xy_nsim, df=df, xx="x", yy="y", zz="log_zinc", num_points=K, vario=vario, radius=RADIUS, kriging_type="ordinary", nsim=nsim, itrans=False, seed=SEED, quiet=True, use_gpu=use_gpu, ) t0 = time.perf_counter() out = sgsim(**kw)if use_gpu:import cupy as cp cp.cuda.Device(0).synchronize()return time.perf_counter() - t0, outrows_nsim = []for nsim in NSIM_LIST: cpu_t, out_cpu = _time_sgs_nsim(nsim, use_gpu=False) row = {"nsim": nsim, "CPU (s)": cpu_t, "GPU (s)": np.nan, "speedup": np.nan, "match": "—"}if USE_GPU: gpu_t, out_gpu = _time_sgs_nsim(nsim, use_gpu=True) row["GPU (s)"] = gpu_t row["speedup"] = cpu_t / gpu_t row["match"] =bool(np.allclose(out_cpu, out_gpu, rtol=1e-2, atol=1e-2))import cupy as cp cp.get_default_memory_pool().free_all_blocks() rows_nsim.append(row)df_bench_nsim = pd.DataFrame(rows_nsim)df_show_nsim = df_bench_nsim.copy()df_show_nsim["CPU (s)"] = df_show_nsim["CPU (s)"].round(3)df_show_nsim["GPU (s)"] = df_show_nsim["GPU (s)"].round(3)df_show_nsim["speedup"] = df_show_nsim["speedup"].map(lambda x: "—"if pd.isna(x) elsef"{x:.2f}×")print(df_show_nsim.to_string(index=False))print()# Where does the time actually go? Time _octant_search itself (CPU, pandas,# per-realization -- unaffected by GPU batching) against total wall time at# the largest nsim, on the GPU path.if USE_GPU: _sgsim_mod = importlib.import_module("pygstat.sgsim") _orig_octant_search = _sgsim_mod._octant_search _octant_elapsed = {"total": 0.0}def _timed_octant_search(*args, **kwargs): _t0 = time.perf_counter() _result = _orig_octant_search(*args, **kwargs) _octant_elapsed["total"] += time.perf_counter() - _t0return _result _sgsim_mod._octant_search = _timed_octant_searchtry: _t0 = time.perf_counter() sgsim(prediction_grid=grid_xy_nsim, df=df, xx="x", yy="y", zz="log_zinc", num_points=K, vario=vario, radius=RADIUS, kriging_type="ordinary", nsim=NSIM_LIST[-1], itrans=False, seed=SEED, quiet=True, use_gpu=True)import cupy as cp cp.cuda.Device(0).synchronize() _total = time.perf_counter() - _t0finally: _sgsim_mod._octant_search = _orig_octant_searchprint(f"At nsim={NSIM_LIST[-1]}: octant search (CPU, pandas, per-realization) took "f"{_octant_elapsed['total']:.2f}s of {_total:.2f}s total "f"({100* _octant_elapsed['total'] / _total:.0f}%) -- batching the GPU solve "f"doesn't touch this, so it caps how much §12.2's batching can win.")fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))n_vals = df_bench_nsim["nsim"].to_numpy()cpu_s = df_bench_nsim["CPU (s)"].to_numpy()gpu_s = df_bench_nsim["GPU (s)"].to_numpy()x = np.arange(len(n_vals))w =0.36axes[0].bar(x - w /2, cpu_s, w, label="CPU (NumPy)", color="steelblue")if USE_GPU and np.isfinite(gpu_s).all(): axes[0].bar(x + w /2, gpu_s, w, label="GPU (CuPy, batched)", color="darkorange")axes[0].set_xticks(x)axes[0].set_xticklabels([str(int(n)) for n in n_vals], fontsize=9)axes[0].set_xlabel("nsim")axes[0].set_ylabel("Wall time (s)")axes[0].set_title(f"sgsim (n_pred={N_PRED_NSIM}, k={K}) — CPU vs batched GPU")axes[0].legend()if USE_GPU: axes[1].plot(n_vals, df_bench_nsim["speedup"], "o-", color="darkgreen", lw=2) axes[1].axhline(1.0, color="grey", ls="--", lw=1) axes[1].set_xlabel("nsim") axes[1].set_ylabel("Speedup (CPU time / GPU time)") axes[1].set_title("GPU speedup vs nsim (realization batching)") 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()record("GPU realization-batching speedup grows with nsim","PASS"if (not USE_GPU or df_bench_nsim["speedup"].iloc[-1] >= df_bench_nsim["speedup"].iloc[0]) else"FAIL", (f"speedup at nsim={NSIM_LIST[0]}: {df_bench_nsim['speedup'].iloc[0]:.2f}x, "f"at nsim={NSIM_LIST[-1]}: {df_bench_nsim['speedup'].iloc[-1]:.2f}x") if USE_GPU else"GPU not usable",)
n_pred : 200 (fixed, first 200 nodes of meuse_grid.csv)
neighbors : k=16; radius=1200
nsim : [1, 2, 4, 8, 16, 32]
nsim CPU (s) GPU (s) speedup match
1 1.459 2.057 0.71× True
2 2.897 3.235 0.90× True
4 5.765 5.912 0.98× True
8 11.394 11.488 0.99× True
16 22.929 22.360 1.03× True
32 45.613 44.155 1.03× True
At nsim=32: octant search (CPU, pandas, per-realization) took 40.19s of 44.86s total (90%) -- batching the GPU solve doesn't touch this, so it caps how much §12.2's batching can win.
✅ [PASS] GPU realization-batching speedup grows with nsim speedup at nsim=1: 0.71x, at nsim=32: 1.03x
Realization batching turns §12.1’s “always below 1×” into roughly break-even to a modest win as nsim grows. Measured on the RTX 2080 Ti this notebook runs on, at n_pred=200, k=16: 0.80× at nsim=1 climbing to 1.02× by nsim=32 (re-running may shift these slightly; see the printed table above for this run’s own numbers). match = True at every nsim confirms _simulate_batch and the CPU path agree within its documented ridge/solve tolerance.
The ceiling on that speedup is _octant_search – the per-realization, pandas-based neighbor lookup that GPU batching does not touch. The diagnostic above measured it eating ≈89% of total wall time at nsim=32 here. Batching the covariance build + solve was the batchable part of the bottleneck; the dominant part turned out to be somewhere else entirely. So: use_gpu=True with a large nsim is worth trying and won’t cost you (roughly break-even at worst), but a big win would need a different change – moving _octant_search off pandas, not further GPU work on the kriging solve itself.
13. Summary and Conclusions
Sequential Gaussian simulation builds each realization by visiting grid nodes in a random path, kriging from the nearby data plus already- simulated nodes, and drawing a Gaussian value from that local distribution. Conditioning data are honoured exactly in every realization.
pygstat.sgsim implements that algorithm in 2-D with octant search, simple or ordinary kriging, multiple realizations (nsim), and an optional normal-score transform (itrans).
On Meuse zinc, 20 realizations on meuse_grid.csv reproduce the input histogram, agree with ordinary kriging in the E-type mean (correlation \(\approx 0.98\)), and reproduce the input exponential variogram (Section 10).
The animation of all realizations (Section 11.1) makes spatial uncertainty visible: areas that stay the same colour are well informed; areas that flicker between realizations are not.
Conditional quantile maps (Section 11.2) summarize the same ensemble. High (yellow) values of the 0.1-quantile map are where zinc is certainly large; low (dark yellow) values of the 0.9-quantile map are where zinc is certainly small.
CPU / GPU. Nodes within one realization can’t be batched, so at nsim=1 GPU dispatch is per-node and often slower than NumPy (~0.72– 0.80× on this RTX 2080 Ti, §12.1). But realizations don’t depend on each other: at nsim >= 2, sgsim(..., use_gpu=True) batches all realizations’ local kriging systems together (§12.2), turning that into roughly break-even (~1.0× by nsim=32 here). Even batched, the octant search – not the kriging solve – dominates wall time (~89% at nsim=32), so the batched GPU path is a safe thing to try at large nsim, not yet a decisive win. Default remains use_gpu=False.
Covariance + solve dispatch to CuPy; per-node at nsim=1, batched across realizations at nsim>=2 (default False; roughly break-even to a modest win at typical \(k\))
Variogram / OrdinaryKriging
E-type honesty check
Experimental \(\gamma(h)\) of realizations
Variogram reproduction
q10 / q50 / q90 maps
Conditional quantile summary of spatial uncertainty