Banner

Geostatistical Simulation

Kriging gives one map: the best estimate at every location. That map is deliberately smooth. Away from the samples it relaxes toward the mean, so the highs are too low, the lows are too high, and the map has less spatial variability than the ground it describes. For a question about a single location (“what is the most likely value here?”) that is the right answer. For a question about many locations at once (“how much of this field exceeds the threshold?”, “is there a connected path of high permeability?”, “how much ore is in this block?”) the smooth map gives a biased answer, and the kriging variance cannot fix it, because it describes one location at a time.

Geostatistical simulation answers those questions by drawing many maps instead of one. Each map, a realization, honours the data, has the histogram of the variable and its variogram, and is as rough as the real field. The realizations differ from one another away from the data, and that spread is the uncertainty. Every quantity you compute from a map (a volume, a probability, a flow, a cost) is computed on each realization in turn, which gives a distribution of answers instead of a single, smoothed one.

This notebook is the map for simulation in GeoLattice. It explains why kriging smooths, how simulation works, and what each method in geolattice.geostatistics.simulation does. It then runs every one of them on the same synthetic field, where the truth is known.

Ten notebooks draw many maps from one sample, so a volume, a threshold, or a connected path has a distribution.

  • Geostatistical Simulation. This notebook. Why a kriged map is smooth, and one realization of each method on a synthetic field with known truth.
  • Sequential Gaussian Simulation (sgsim). Meuse zinc, simulated as the logarithm of zinc. Conditioning, histogram and variogram checks, an E-type map beside kriging, quantile maps, and a CPU and GPU timing check.
  • Sequential Gaussian Co-Simulation (sgcosim). Jura nickel, with chromium as the secondary variable.
  • Sequential Indicator Simulation (sisim). Meuse zinc through indicator thresholds, order relations, and tail models.
  • Sequential Indicator Co-Simulation (sicosim). Jura cadmium through six thresholds, and rock type as five categories, with soft zinc, geology, and cobalt.
  • Direct Sequential Simulation (dssim_direct). Jura cadmium simulated in mg/kg, with zinc as a secondary variable.
  • Simulated Annealing Simulation (sasim). Jura nickel, rock type, and a kriged chromium map, on a coarser lattice.
  • Plurigaussian Simulation (PluriGaussianSimulator). Five Jura rock types from truncated Gaussian fields.
  • Multiple-Point Statistics Simulation (DirectSampling, SNESIM). Direct Sampling and SNESIM on a synthetic channel system and on the Jura geology map.
  • SNESIM: Single Normal Equation Simulation (SNESIM). A three-facies fluvial training image, wells, and a noisy seismic secondary.

Library: geolattice.geostatistics

Worked example: a synthetic lognormal field on a 50 × 50 grid (20 m cells), sampled at 60 locations, plus a three-facies version of the same field

Library: geolattice.geostatistics (modules in geolattice.geostatistics.simulation)

Before this notebook: Getting started, variogram modeling, and the introduction to kriging. Every simulator here solves a kriging system at its core and reads a variogram model; neither is re-derived here.


Table of Contents

  1. Notebooks in this chapter
  2. What geostatistical simulation is
  3. How simulation works
  4. The simulation methods
  5. Choosing a method
  6. Simulation in GeoLattice
  7. Python setup
  8. A synthetic truth and 60 samples
  9. Kriging versus simulation
  10. One realization from every method
  11. Categorical simulation: indicators versus plurigaussian
  12. From realizations to decisions
  13. Where the next notebooks go
  14. Resources

Notebooks in this chapter

Notebook Method What it covers
05_07_00_introduction_geostatistical_sumulations.ipynb (this) All simulators, side by side Why simulate, and one realization of each method on a synthetic field
05_07_01_sgsim.ipynb Sequential Gaussian simulation (sgsim) Meuse zinc: conditioning, histogram and variogram reproduction, E-type versus kriging, quantile maps, CPU versus GPU
05_07_02_sgcosim.ipynb Sequential Gaussian co-simulation (sgcosim) Jura nickel with chromium as the secondary variable
05_07_03_sisim.ipynb Sequential indicator simulation (sisim) Meuse zinc through indicator thresholds, order relations, and tail models
05_07_04_sicosim.ipynb Sequential indicator co-simulation (sicosim) Jura cadmium through six thresholds, and rock type, with soft zinc, geology, and cobalt
05_07_05_dssim.ipynb Direct sequential simulation (dssim_direct) Jura cadmium in mg/kg, with zinc as a secondary variable
05_07_06_sasim.ipynb Simulated annealing (sasim) Jura nickel, rock type, and a kriged chromium map
05_07_07_pgs.ipynb Plurigaussian simulation Five Jura rock types from truncated Gaussian fields
05_07_08_mps.ipynb Direct Sampling and SNESIM A synthetic channel system, and the Jura geology map
05_07_09_snesim.ipynb SNESIM A three-facies fluvial training image, wells, and a noisy seismic secondary

–

What geostatistical simulation is

The smoothing effect of kriging

Write the variable as a random field \(Z(\mathbf{x})\) and the kriging estimate as \(Z^*(\mathbf{x})\). Kriging is unbiased and minimizes the error variance \(\sigma_K^2(\mathbf{x}) = \operatorname{Var}\bigl(Z(\mathbf{x}) - Z^*(\mathbf{x})\bigr)\). For simple kriging the error is orthogonal to the estimate, which gives

\[ \operatorname{Var}\bigl(Z^*(\mathbf{x})\bigr) = \sigma^2 - \sigma_K^2(\mathbf{x}). \]

The estimate has the full variance \(\sigma^2\) only at a sample, where \(\sigma_K^2 = 0\). Everywhere else it has less variance than the variable, and far from the data, where \(\sigma_K^2 \to \sigma^2\), it has almost none. That is the smoothing effect. It also changes the variogram of the map: the kriged surface is more continuous at short lags than the field it estimates.

Realizations

A conditional simulation draws fields \(z^{(\ell)}(\mathbf{x})\), \(\ell = 1, \ldots, L\), from the distribution of \(Z\) given the data. Each realization:

  • honours the data: \(z^{(\ell)}(\mathbf{x}_i) = z(\mathbf{x}_i)\) at every sample (for a model without nugget);
  • reproduces the histogram of the variable (in expectation over realizations);
  • reproduces the variogram, so it has the right roughness.

The realizations differ away from the data. Averaged node by node they converge to the kriging estimate (the E-type map). Their spread at a node converges to the kriging variance. Their joint behaviour, which kriging cannot describe, is what simulation adds.

An unconditional simulation drops the first property: it reproduces the histogram and variogram but ignores the data. It is used as a building block (conditioning by kriging, below), and to study what a model implies before any data are collected.

Transfer functions

The reason to simulate is usually downstream. A transfer function is anything computed from a whole map: the area above a threshold, the volume of ore above a cutoff, a contaminant-transport model, a flow simulator, a cost. Running the transfer function on each realization gives a distribution of outcomes. Running it on the kriged map gives one outcome, and for a non-linear transfer function that outcome is biased. Extremes are muted, and connected features break up.


How simulation works

The workflow

Most simulation studies follow the same steps:

  1. Explore and decluster the data so the histogram represents the area, not the sampling pattern.
  2. Transform to a convenient space. Gaussian methods use the normal-score transform \(y = G^{-1}\bigl(F(z)\bigr)\), where \(F\) is the data cdf and \(G\) the standard normal cdf.
  3. Model the spatial structure. A variogram (two-point statistics) for most methods, indicator variograms for indicator and annealing methods, a truncation rule for plurigaussian simulation, a training image for multiple-point statistics.
  4. Simulate \(L\) realizations.
  5. Back-transform to original units.
  6. Check each realization: data honoured, histogram and variogram reproduced.
  7. Post-process: E-type and conditional variance maps, probabilities of exceeding a threshold, quantile maps, or a transfer function run on each realization.

The sequential principle

The joint distribution of the values at \(N\) grid nodes, given the data \((n)\), factorizes into a product of univariate conditionals:

\[ f(z_1, \ldots, z_N \mid (n)) = f(z_1 \mid (n))\, f(z_2 \mid (n), z_1) \cdots f(z_N \mid (n), z_1, \ldots, z_{N-1}). \]

Sequential simulation draws from that product one factor at a time. It visits the nodes along a random path, estimates the local conditional distribution from the data and the previously simulated nodes, draws a value, and adds it to the conditioning set. For a Gaussian field the local distribution is \(\mathcal{N}\bigl(y^*_{SK}, \sigma^2_{SK}\bigr)\), so each step is one simple-kriging system. Re-using the simulated nodes is what gives the realization the full variogram. In practice the search is limited to the nearest neighbours, which is an approximation.

Conditioning by kriging

A method that produces only unconditional fields can still be conditioned (Journel and Huijbregts, 1978). Simulate an unconditional field \(y_u\) at the data locations and the grid, krige the data and the simulated values at the data locations with the same weights, and combine:

\[ z_{cs}(\mathbf{x}) = z^*_K(\mathbf{x}) + \bigl[y_u(\mathbf{x}) - y^*_{u,K}(\mathbf{x})\bigr]. \]

The kriged data give the right local mean. The bracket is a simulated kriging error with the right variance and covariance. Turning bands and FFT simulation are conditioned this way in GeoLattice.


The simulation methods

Each module in geolattice.geostatistics.simulation implements one family. All of them are imported from geolattice.geostatistics.

Module Main call Variable How a realization is built Exact?
sgsim.py sgsim continuous Sequential Gaussian simulation, GSLIB style: octant search, simple or ordinary kriging, normal-score transform approximate (neighbourhood)
sgcosim.py GaussianCoSimulator, sgcosim, sgcosim_hierarchical, sgsim_gpu continuous (+ secondary) Sequential Gaussian simulation with precomputed neighbour lists, and co-simulation with a secondary variable by collocated cokriging (Markov model 1) approximate (neighbourhood)
sisim.py sisim continuous, by thresholds Sequential indicator simulation, GSLIB style: indicator kriging at each threshold, order-relation correction, tail models approximate
sicosim.py IndicatorCoSimulator, sicosim, SoftCalibration categorical or continuous (+ soft data) Sequential indicator simulation and co-simulation with soft secondary data (Markov-Bayes) approximate
lusim.py LUSimulator, lusim continuous Cholesky (LU) factor of the full covariance matrix; conditional by simple or ordinary kriging exact
tbsim.py TBSimulator, tbsim continuous Turning bands: a sum of 1-D line processes over many directions, conditioned by kriging exact covariance in expectation
fftsim.py FFTSimulator, fftsim continuous, regular grid FFT circulant embedding of the covariance, conditioned by kriging exact
direct_sequential.py DirectSequentialSimulator, dssim_direct continuous, original units Direct sequential simulation: kriging in original units, draws from the global histogram approximate
annealing.py SimulatedAnnealing, sasim continuous or categorical Simulated annealing: swap values until the image matches target variograms (and a correlation with a secondary) target-matching, not a probability model
pgs.py PluriGaussianSimulator, pgsim, TruncationRule categorical Plurigaussian: truncate one or two latent Gaussian fields with a rule that controls which facies may touch exact latent fields; Gibbs sampler for the data
_conditioning.py (internal) n/a Dual kriging used by turning bands and FFT for conditioning, and the neighbour search shared by the sequential simulators n/a

Sequential methods

sgsim and GaussianCoSimulator simulate a Gaussian (normal-score) field along a random path. sisim and IndicatorCoSimulator replace the Gaussian conditional distribution with one estimated by indicator kriging, so each threshold or class can have its own continuity. DirectSequentialSimulator krigs in original units and draws from the global histogram. That keeps the original-unit variogram, which normal-score methods reproduce only after back-transformation, if at all. All of them are approximate because each node sees only its nearest neighbours.

Matrix and spectral methods

LUSimulator factorizes the covariance of all data and grid nodes once. Every realization is then a matrix-vector product, exact for any model, but the matrix is dense, so the method is limited to a few thousand locations. FFTSimulator embeds the grid covariance in a periodic torus whose eigenvalues come from one FFT, which makes it exact and fast on regular grids of millions of nodes. TBSimulator sums 1-D processes along many lines. It works on any set of points and scales linearly with their number; the covariance is exact on average over realizations.

Categorical methods

Indicator simulation gives each class its own indicator variogram but no control over which classes touch. Plurigaussian simulation truncates latent Gaussian fields with a truncation rule. With one field and ordered thresholds (truncated Gaussian), class 1 can touch class 2, but class 1 never touches class 3. With two fields the rule can encode any contact pattern.

Optimization

Simulated annealing starts from a random image with the target histogram and swaps pairs of values, accepting swaps that improve an objective (variogram mismatch, correlation with a secondary) under a cooling schedule. It can match almost any statistic you can write down, but it is not sampling from a defined probability model, so the spread between realizations is not a calibrated uncertainty.

Co-simulation

A secondary variable known everywhere (seismic, a DEM, a remote-sensing index) enters through GaussianCoSimulator (collocated cokriging), IndicatorCoSimulator (soft indicators), or DirectSequentialSimulator (collocated cokriging in original units). sgcosim_hierarchical simulates two variables jointly when both are known only at the samples.


Choosing a method

Situation Method Why
Continuous variable, Gaussian after a normal-score transform GaussianCoSimulator / sgsim The standard; fast, simple, any grid
Small problem (≤ ~10 000 data + nodes) and an exact answer is wanted LUSimulator Exact; extra realizations are almost free once factorized
Large regular grid FFTSimulator Exact and \(O(N \log N)\)
Large irregular set of points TBSimulator Linear in the number of points
Original-unit variogram must be reproduced (skewed variable) DirectSequentialSimulator No normal-score transform of the field
Highs and lows have different continuity IndicatorCoSimulator / sisim One indicator variogram per threshold
Facies with ordered or restricted contacts PluriGaussianSimulator The truncation rule controls contacts
Facies without contact rules IndicatorCoSimulator (categorical) One indicator variogram per class
A secondary variable known everywhere GaussianCoSimulator, IndicatorCoSimulator, DirectSequentialSimulator with a secondary Collocated cokriging or soft data
Several custom statistics to match at once SimulatedAnnealing Any objective that can be written down
Connected, curvilinear shapes (channels) DirectSampling, SNESIM in geolattice.geostatistics.mps Two-point statistics cannot describe them

Simulation in GeoLattice

The variogram list

The simulators share GSLIB’s variogram convention, a list

vario = [azimuth, nugget, major_range, minor_range, sill, vtype]   # plus smoothness for "matern"
  • azimuth is in degrees, major_range and minor_range are practical ranges (the distance at which the model reaches about 95 % of its sill), and sill is the total \(C(0)\) = nugget + partial sill.
  • vtype is "spherical", "exponential", "gaussian" or "matern" (Matérn needs a 7th element, the smoothness).
  • For Gaussian methods with itrans=True the variogram is that of the normal scores, so its sill is 1.
  • DirectSequentialSimulator and SimulatedAnnealing use the variogram in original units.

The call pattern

The functions follow GSLIB:

sims = sgsim(grid, df, "X", "Y", "Z", num_points=16, vario=vario, radius=500, nsim=50, itrans=True, seed=1)

The classes fit once and simulate many times:

sim = LUSimulator(vario, kriging_type="ordinary", itrans=True).fit(grid, df, "X", "Y", "Z")
sims = sim.simulate(nsim=200, seed=1)            # shape (nsim, len(grid))

grid is an (n, 2) array of node coordinates and df a DataFrame with the samples. The output always has one row per realization, in grid order. The same seed gives the same realizations. itrans=True normal-scores the data and back-transforms the realizations, and zmin / zmax bound the back-transform’s tails.

GPU acceleration

Simulator use_gpu When it pays off
GaussianCoSimulator, sgsim_gpu one CUDA thread per realization from about 16 realizations; about 100× at 1 000
IndicatorCoSimulator one CUDA thread per realization from about 16 realizations; about 110× at 1 000
DirectSequentialSimulator one thread (Soares) or one block (lookup) per realization from about 16 realizations
TBSimulator line processes and conditioning on the GPU from a single realization; 25-100×
sgsim, sisim batched local systems little gain; their octant search dominates

GPU realizations are identical to the CPU ones for the same seed, and every simulator falls back to the CPU (with a warning) when no GPU is usable. This notebook runs on the CPU so it gives the same numbers on any machine.


Python setup

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 os
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")

import time
import warnings

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

warnings.filterwarnings("ignore")

import geolattice.geostatistics as gstat
from geolattice.geostatistics import (
    sgsim, sisim, LUSimulator, TBSimulator, FFTSimulator, GaussianCoSimulator,
    DirectSequentialSimulator, SimulatedAnnealing, IndicatorCoSimulator,
    PluriGaussianSimulator, TruncationRule, category_proportions,
    nscore_forward, nscore_back,
)

USE_GPU = False  # the same numbers on any machine; GPU timings are in the method notebooks

print(f"geolattice.geostatistics : {gstat.__version__}")
print("simulation modules  :", ", ".join(sorted(
    m for m in dir(gstat.simulation) if not m.startswith("__"))))
geolattice.geostatistics : 0.3.49
simulation modules  : _conditioning, annealing, direct_sequential, fftsim, lusim, pgs, sgcosim, sgsim, sicosim, sis_local_means, sisim, tbsim

A synthetic truth and 60 samples

Every simulator is judged here against a field whose truth is known. The field is built from a Gaussian random field \(Y\) with a spherical variogram (practical ranges 400 m along 30° and 200 m across, sill 1), drawn on a 50 × 50 grid of 20 m cells. The variable of interest is lognormal, like a metal concentration:

\[ Z = \exp(0.8\,Y + 3). \]

Sixty grid nodes are sampled at random. Because \(Y\) is a monotone transform of \(Z\), the normal scores of the samples follow the same variogram as \(Y\). All the Gaussian simulators below therefore use the variogram that generated the truth, so the comparison is between simulation methods, not between variogram fits. (Fitting is the subject of the variogram notebook.)

Code
NX, DX = 50, 20.0                                   # 50 x 50 nodes, 20 m cells
xs = np.arange(NX) * DX
grid = np.array(np.meshgrid(xs, xs, indexing="ij")).reshape(2, -1).T

VARIO_NS = [30, 0.0, 400.0, 200.0, 1.0, "spherical"]  # azimuth, nugget, major, minor, sill, model

y_true = FFTSimulator(VARIO_NS).fit(grid).simulate(1, seed=11)[0]   # unconditional Gaussian field
z_true = np.exp(0.8 * y_true + 3.0)

rng = np.random.default_rng(7)
pick = rng.choice(len(grid), 60, replace=False)
samples = pd.DataFrame({"X": grid[pick, 0], "Y": grid[pick, 1], "Z": z_true[pick]})


def as_map(values):
    """Grid-ordered values -> (ny, nx) image with north up."""
    return np.asarray(values).reshape(NX, NX).T


summary = pd.DataFrame({
    "truth (2 500 nodes)": pd.Series(z_true).describe(),
    "samples (60)": samples["Z"].describe(),
}).T.round(2)
print(summary.to_string())

fig, axes = plt.subplots(1, 2, figsize=(12.4, 5.0), gridspec_kw={"width_ratios": [1.15, 1]})
im = axes[0].imshow(as_map(z_true), origin="lower", extent=[0, NX * DX, 0, NX * DX], cmap="YlOrRd")
axes[0].scatter(samples["X"] + DX / 2, samples["Y"] + DX / 2, s=22, facecolors="none",
                edgecolors="k", linewidths=0.8, label="samples")
axes[0].set_title("Synthetic truth Z and the 60 samples")
axes[0].set_xlabel("Easting (m)"); axes[0].set_ylabel("Northing (m)")
axes[0].legend(loc="upper right", frameon=True)
plt.colorbar(im, ax=axes[0], label="Z")
axes[1].hist(z_true, bins=40, density=True, alpha=0.55, color="#d95f02", label="truth")
axes[1].hist(samples["Z"], bins=15, density=True, alpha=0.55, color="#1b9e77", label="samples")
axes[1].set_xlabel("Z"); axes[1].set_ylabel("density"); axes[1].set_title("Histograms")
axes[1].legend(frameon=False)
plt.tight_layout(); plt.show()
                      count   mean    std   min    25%    50%    75%     max
truth (2 500 nodes)  2500.0  33.99  28.21  2.94  15.76  26.88  44.36  438.01
samples (60)           60.0  36.27  28.06  7.16  17.75  30.74  48.41  180.49

The truth is right-skewed: half of the field is below 27 while the mean is 34, and one hot spot near (620 m E, 470 m N) reaches 438. The 60 samples match the truth’s mean and spread closely (36.3 and 28.1 against 34.0 and 28.2), but their maximum is 180: no sample falls on the peak of the hot spot. The sample histogram is also lumpy, as any histogram of 60 values is. Both facts come back below, because every Gaussian simulator with itrans=True rebuilds its histogram from these 60 values.


Kriging versus simulation

LUSimulator gives both objects from one fit: its conditional_mean_ is the ordinary-kriging estimate of the normal scores, and simulate draws exact conditional realizations from the same covariance. The kriged normal scores are back-transformed for display. Below, the truth, the kriging map, and one realization are compared on three counts: the map, the histogram, and the variogram of \(\log Z\) (computed along the grid rows and columns).

Code
lu = LUSimulator(VARIO_NS, kriging_type="ordinary", itrans=True).fit(grid, samples, "X", "Y", "Z")
ns_data, v_sorted, ns_sorted = nscore_forward(samples["Z"].to_numpy())
z_krig = nscore_back(lu.conditional_mean_, v_sorted, ns_sorted)      # kriged normal scores, back-transformed
z_real = lu.simulate(1, seed=3)[0]


def grid_variogram(values, max_lag=15):
    """Experimental semivariogram along grid rows and columns, lags 1..max_lag cells."""
    img = np.asarray(values).reshape(NX, NX)
    gam = []
    for h in range(1, max_lag + 1):
        d = np.concatenate([(img[h:, :] - img[:-h, :]).ravel(), (img[:, h:] - img[:, :-h]).ravel()])
        gam.append(0.5 * np.mean(d ** 2))
    return np.arange(1, max_lag + 1) * DX, np.array(gam)


fields = {"truth": z_true, "ordinary kriging": z_krig, "one realization": z_real}
rows = []
for name, f in fields.items():
    lags, gam = grid_variogram(np.log(f))
    rows.append({"map": name, "mean": f.mean(), "std": f.std(), "max": f.max(),
                 "RMSE vs truth": np.sqrt(np.mean((f - z_true) ** 2)),
                 "gamma(log Z) at 20 m": gam[0], "gamma(log Z) at 100 m": gam[4]})
print(pd.DataFrame(rows).round(3).to_string(index=False))

vmin, vmax = np.percentile(z_true, [1, 99])
fig, axes = plt.subplots(2, 3, figsize=(15, 9.4))
for ax, (name, f) in zip(axes[0], fields.items()):
    im = ax.imshow(as_map(f), origin="lower", extent=[0, NX * DX, 0, NX * DX],
                   cmap="YlOrRd", vmin=vmin, vmax=vmax)
    ax.scatter(samples["X"] + DX / 2, samples["Y"] + DX / 2, s=9, c="k")
    ax.set_title(name); ax.set_xticks([]); ax.set_yticks([])
plt.colorbar(im, ax=axes[0].tolist(), label="Z", shrink=0.85)

bins = np.linspace(0, np.percentile(z_true, 99.5), 40)
for (name, f), color in zip(fields.items(), ["#d95f02", "#1f78b4", "#33a02c"]):
    axes[1, 0].hist(f, bins=bins, density=True, histtype="step", lw=2, color=color, label=name)
axes[1, 0].set_xlabel("Z"); axes[1, 0].set_title("Histograms"); axes[1, 0].legend(frameon=False)

for (name, f), color in zip(fields.items(), ["#d95f02", "#1f78b4", "#33a02c"]):
    lags, gam = grid_variogram(np.log(f))
    axes[1, 1].plot(lags, gam, "o-", ms=3, color=color, label=name)
axes[1, 1].set_xlabel("lag (m)"); axes[1, 1].set_ylabel(r"$\gamma(h)$ of log Z")
axes[1, 1].set_title("Variograms"); axes[1, 1].legend(frameon=False)

axes[1, 2].scatter(z_true, z_krig, s=4, alpha=0.4, color="#1f78b4", label="kriging")
axes[1, 2].scatter(z_true, z_real, s=4, alpha=0.4, color="#33a02c", label="realization")
lim = [0, np.percentile(z_true, 99.5)]
axes[1, 2].plot(lim, lim, "k--", lw=1)
axes[1, 2].set_xlim(lim); axes[1, 2].set_ylim(lim)
axes[1, 2].set_xlabel("true Z"); axes[1, 2].set_ylabel("map value")
axes[1, 2].set_title("Map versus truth, node by node"); axes[1, 2].legend(frameon=False, markerscale=3)
plt.show()
             map   mean    std     max  RMSE vs truth  gamma(log Z) at 20 m  gamma(log Z) at 100 m
           truth 33.986 28.203 438.007          0.000                 0.073                  0.294
ordinary kriging 31.692 16.297 180.485         21.877                 0.008                  0.106
 one realization 38.644 30.240 319.925         31.207                 0.060                  0.269

The three panels look like the formula in What geostatistical simulation is.

  • Variance. The kriging map’s standard deviation is 16.3 against the truth’s 28.2, about a third of the variance. Its maximum is 180, the largest sample: kriging never invents a value above the data. The realization has a standard deviation of 30.2 and reaches 320, much closer to the truth’s 438.
  • Variogram. At the 20 m lag the kriging map’s variogram of \(\log Z\) is 0.008, against 0.073 for the truth, so the map is about nine times too smooth at short range. The realization gives 0.060, and its whole curve follows the truth’s, while the kriging curve stays far below.
  • Accuracy node by node. Kriging wins here: its RMSE against the truth is 21.9, against 31.2 for the realization. The ratio, 1.43, is close to \(\sqrt 2\). That is expected: a conditional realization equals the kriging estimate plus a simulated error with the kriging variance, so its squared error is about twice kriging’s.

So the two answer different questions. Use the kriging map for the best value at a location. Use realizations for anything that depends on the spatial pattern: extremes, areas, connectivity.

The realization’s histogram has narrow peaks. These are not noise. With itrans=True the back-transform interpolates between the 60 sample quantiles, so every realization inherits the sample histogram’s clusters and gaps. In a real study the reference histogram is usually declustered and smoothed, or extended with tail models, before simulation.


One realization from every method

Each simulator now produces one realization from the same 60 samples. The Gaussian methods use the normal-score variogram above with itrans=True. DirectSequentialSimulator and SimulatedAnnealing work in original units, so they get the same model shape with the sill set to the sample variance of \(Z\). sisim uses nine thresholds, the sample deciles, with one indicator variogram for all of them (a dict gives each threshold its own). GaussianCoSimulator is run twice: alone, and with a secondary variable known at every node. The secondary is the true \(Y\) blurred by an independent smooth field, a stand-in for something like a geophysical survey.

The table records the run time, whether the samples are honoured (the largest difference at the 60 data nodes), the mean and standard deviation of the realization, and the correlation of \(\log Z\) with the truth.

Code
VARIO_Z = [30, 0.0, 400.0, 200.0, float(samples["Z"].var(ddof=0)), "spherical"]   # original units
deciles = np.arange(1, 10) / 10
thresholds = np.quantile(samples["Z"], deciles)
secondary = 0.7 * y_true + 0.71 * FFTSimulator([0, 0, 150, 150, 1.0, "exponential"]).fit(grid).simulate(1, seed=5)[0]

methods = {
    "sgsim": lambda: sgsim(grid, samples, "X", "Y", "Z", num_points=16, vario=VARIO_NS, radius=500,
                           nsim=1, itrans=True, seed=1, quiet=True),
    "GaussianCoSimulator (SGS)": lambda: GaussianCoSimulator(VARIO_NS, radius=500, use_gpu=USE_GPU)
        .fit(grid, samples, "X", "Y", "Z").simulate(1, seed=1),
    "GaussianCoSimulator (+ secondary)": lambda: GaussianCoSimulator(VARIO_NS, radius=500, use_gpu=USE_GPU)
        .fit(grid, samples, "X", "Y", "Z", secondary=secondary).simulate(1, seed=1),
    "LUSimulator": lambda: LUSimulator(VARIO_NS, itrans=True).fit(grid, samples, "X", "Y", "Z").simulate(1, seed=1),
    "TBSimulator": lambda: TBSimulator(VARIO_NS, itrans=True, nlines=1000, use_gpu=USE_GPU)
        .fit(grid, samples, "X", "Y", "Z").simulate(1, seed=1),
    "FFTSimulator": lambda: FFTSimulator(VARIO_NS, itrans=True).fit(grid, samples, "X", "Y", "Z").simulate(1, seed=1),
    "DirectSequentialSimulator": lambda: DirectSequentialSimulator(VARIO_Z, radius=500, use_gpu=USE_GPU)
        .fit(grid, samples, "X", "Y", "Z").simulate(1, seed=1),
    "sisim": lambda: sisim(grid, samples, "X", "Y", "Z", thresholds, deciles,
                           [30, 0.0, 400.0, 200.0, 0.2, "spherical"], 12, 500, nsim=1, seed=1, quiet=True),
    "SimulatedAnnealing": lambda: SimulatedAnnealing(vario=VARIO_Z, target_values=samples["Z"].to_numpy(), n_lags=8)
        .fit(grid, samples, "X", "Y", "Z").simulate(1, seed=1),
}

realizations, rows = {}, []
for name, run in methods.items():
    t0 = time.perf_counter()
    r = np.asarray(run())[0]
    dt = time.perf_counter() - t0
    realizations[name] = r
    rows.append({
        "method": name,
        "time (s)": dt,
        "max |sim - data|": np.abs(r[pick] - samples["Z"].to_numpy()).max(),
        "mean": r.mean(),
        "std": r.std(),
        "corr(log Z, truth)": np.corrcoef(np.log(np.maximum(r, 1e-9)), y_true)[0, 1],
    })
rows.append({"method": "truth", "time (s)": np.nan, "max |sim - data|": 0.0, "mean": z_true.mean(),
             "std": z_true.std(), "corr(log Z, truth)": 1.0})
table = pd.DataFrame(rows).set_index("method")
print(table.round({"time (s)": 2, "mean": 1, "std": 1, "corr(log Z, truth)": 2}).to_string(
    formatters={"max |sim - data|": "{:.1e}".format}))
                                   time (s) max |sim - data|  mean   std  corr(log Z, truth)
method                                                                                      
sgsim                                 14.09          0.0e+00  38.2  36.6                0.50
GaussianCoSimulator (SGS)              0.15          0.0e+00  38.2  32.2                0.47
GaussianCoSimulator (+ secondary)      0.17          0.0e+00  37.5  30.8                0.64
LUSimulator                            0.37          5.1e-05  33.8  23.7                0.40
TBSimulator                            0.08          3.2e-08  31.6  21.7                0.56
FFTSimulator                           0.03          1.1e-07  43.1  38.6                0.41
DirectSequentialSimulator              0.22          0.0e+00  37.4  26.4                0.38
sisim                                 15.33          0.0e+00  38.0  26.8                0.22
SimulatedAnnealing                     4.50          0.0e+00  36.3  27.9                0.17
truth                                   NaN          0.0e+00  34.0  28.2                1.00
Code
panels = [("truth", z_true)] + list(realizations.items())
fig, axes = plt.subplots(2, 5, figsize=(19, 8.2))
for ax, (name, f) in zip(axes.flat, panels):
    im = ax.imshow(as_map(f), origin="lower", extent=[0, NX * DX, 0, NX * DX], cmap="YlOrRd", vmin=vmin, vmax=vmax)
    ax.set_title(name.replace(" (", "\n("), fontsize=10)
    ax.set_xticks([]); ax.set_yticks([])
plt.colorbar(im, ax=axes.ravel().tolist(), label="Z", shrink=0.8)
plt.show()

  • Data. Every method honours the 60 samples. The sequential, DSS, SIS and annealing methods copy the data exactly. LU, turning bands and FFT reproduce them through kriging, to within \(10^{-7}\) to \(10^{-4}\), the size of the numerical jitter in their kriging systems.
  • Speed (times vary a little between runs). sgsim and sisim take about 15 s for 2 500 nodes; their GSLIB-style octant search dominates. GaussianCoSimulator runs the same algorithm in about 0.15 s with precomputed neighbour lists. FFT takes a few hundredths of a second, turning bands about 0.1 s, and LU about 0.4 s including the factorization (later realizations are almost free, as the next section shows). Annealing takes about 4.5 s.
  • One realization is not the model. Single-realization means range from 31.6 to 43.1 and standard deviations from 21.7 to 38.6, around the truth’s 34.0 and 28.2. That spread is fluctuation between realizations of a field only 2.5 ranges wide, not a defect of any method; statistics are judged over many realizations.
  • The secondary variable helps. Collocated co-simulation raises the correlation of \(\log Z\) with the truth from 0.47 to 0.64, the best of the set, because the secondary carries information about the field everywhere, not only at the samples.
  • Simulated annealing reproduces the histogram best (mean 36.3, standard deviation 27.9, the samples’ own values, since it only rearranges them). It has the lowest correlation with the truth, 0.17. It honours the data values but has no kriging step, so away from the samples it is held only by the variogram target. Its map shows the right kind of texture, in the wrong places.
  • Indicator simulation with one variogram for all nine thresholds gives a patchy texture: values inside a class band are drawn by interpolation, so neighbouring cells often share a narrow range. Its correlation with the truth is 0.22. Indicator methods earn their place when the low and high values have different continuity, which this Gaussian truth does not have.

Categorical simulation: indicators versus plurigaussian

Many variables are classes, not numbers: facies, soil types, land cover. Here the truth is cut into three ordered facies by thresholds on the latent field, low (\(Y < -0.5\)), middle, and high (\(Y > 0.6\)). Because the latent field is continuous, the low and high facies are separated by the middle one. On a 20 m grid they meet only where the field happens to jump across the whole middle band between neighbouring cells, which is rare.

  • IndicatorCoSimulator (categorical sequential indicator simulation) gives each facies an indicator variogram but has no notion of order.
  • PluriGaussianSimulator with a truncated-Gaussian rule (TruncationRule.truncated_gaussian) simulates the latent field and cuts it at thresholds set from the facies proportions of the samples. The rule puts the middle facies between the other two, as in the truth.

Both honour the facies at the samples and both take their proportions from the samples. The check that separates them is the number of grid edges where a low cell sits directly beside a high one.

Code
facies_true = np.digitize(y_true, [-0.5, 0.6]).astype(float)        # 0 = low, 1 = middle, 2 = high
samples_f = samples.assign(facies=facies_true[pick])
proportions = {k: float((samples_f["facies"] == k).mean()) for k in (0.0, 1.0, 2.0)}   # from the samples, not the truth


def low_high_contacts(f):
    img = np.asarray(f).reshape(NX, NX)
    pairs = [(img[1:, :], img[:-1, :]), (img[:, 1:], img[:, :-1])]
    return int(sum((((a == 0) & (b == 2)) | ((a == 2) & (b == 0))).sum() for a, b in pairs))


sis_f = IndicatorCoSimulator([0, 1, 2], [30, 0.0, 400.0, 200.0, 0.22, "spherical"], radius=500,
                             use_gpu=USE_GPU).fit(grid, samples_f, "X", "Y", "facies").simulate(1, seed=1)[0]
rule = TruncationRule.truncated_gaussian(proportions)
pgs_f = PluriGaussianSimulator(rule, VARIO_NS).fit(grid, samples_f, "X", "Y", "facies").simulate(1, seed=1)[0]

cat_rows = []
for name, f in [("truth", facies_true), ("IndicatorCoSimulator", sis_f), ("PluriGaussianSimulator", pgs_f)]:
    props = category_proportions(f[None, :].astype(int), 3)[0]
    cat_rows.append({"map": name, "low": props[0], "middle": props[1], "high": props[2],
                     "low-high contacts": low_high_contacts(f),
                     "samples honoured": bool((f[pick] == samples_f["facies"].to_numpy()).all()),
                     "cells equal to truth": float((f == facies_true).mean())})
print(pd.DataFrame(cat_rows).round(3).to_string(index=False))

cmap3 = ListedColormap(["#2c7bb6", "#ffffbf", "#d7191c"])
fig, axes = plt.subplots(1, 3, figsize=(15, 5.0))
for ax, (name, f) in zip(axes, [("truth", facies_true), ("IndicatorCoSimulator", sis_f),
                                ("PluriGaussianSimulator (truncated Gaussian)", pgs_f)]):
    ax.imshow(as_map(f), origin="lower", extent=[0, NX * DX, 0, NX * DX], cmap=cmap3, vmin=-0.5, vmax=2.5)
    ax.scatter(samples_f["X"] + DX / 2, samples_f["Y"] + DX / 2, c=samples_f["facies"], cmap=cmap3,
               vmin=-0.5, vmax=2.5, s=26, edgecolors="k", linewidths=0.6)
    ax.set_title(name); ax.set_xticks([]); ax.set_yticks([])
plt.show()
                   map   low  middle  high  low-high contacts  samples honoured  cells equal to truth
                 truth 0.194   0.402 0.404                  8              True                 1.000
  IndicatorCoSimulator 0.127   0.337 0.536                237              True                 0.449
PluriGaussianSimulator 0.153   0.410 0.437                  8              True                 0.496

Both simulators honour all 60 facies samples, and both take their proportions from the samples. The samples over-represent the high facies (48 % of the samples against 40 % of the truth), and both realizations follow them.

The contact count is where they part. The truth has 8 low-high edges, from the rare places where the field jumps the middle band in one cell. The plurigaussian realization has 16, for the same reason: it is the truncation of a continuous field. The indicator realization has 237. Indicator simulation builds each facies from its own indicator kriging and has no notion that the middle facies lies between the other two, so blue and red patches meet directly. When contacts matter (a lagoon facies that must sit between shoreface and shelf, a soil that only forms between two others), that is the reason to use a truncation rule. With two latent fields, TruncationRule.from_flag encodes any contact pattern, not just an ordering.


From realizations to decisions

One realization is one plausible field; the information is in the set. LUSimulator has already factorized the covariance, so 500 more realizations cost a fraction of a second. Three summaries are mapped from them:

  • the E-type map, the node-by-node mean of the realizations, which converges to the conditional expectation;
  • the conditional standard deviation, small near the samples and large between them;
  • the probability that \(Z\) exceeds a threshold \(z_c\), the fraction of realizations above it at each node.

The last line answers a question kriging alone cannot: the probability that more than 15 % of the area exceeds \(z_c\). That is a property of whole maps, so it can only be read from the realizations.

Code
t0 = time.perf_counter()
ensemble = lu.simulate(500, seed=42)
print(f"500 realizations in {time.perf_counter() - t0:.2f} s, shape {ensemble.shape}")

z_c = float(np.quantile(samples["Z"], 0.80))
etype = ensemble.mean(axis=0)
cond_sd = ensemble.std(axis=0)
p_exceed = (ensemble > z_c).mean(axis=0)

area_true = (z_true > z_c).mean()
area_krig = (z_krig > z_c).mean()
area_sims = (ensemble > z_c).mean(axis=1)
print(f"threshold z_c = {z_c:.1f} (80th percentile of the samples)")
print(f"fraction of area above z_c:  truth {area_true:.3f}   kriging map {area_krig:.3f}   "
      f"realizations: mean {area_sims.mean():.3f}, 90% interval [{np.quantile(area_sims, 0.05):.3f}, "
      f"{np.quantile(area_sims, 0.95):.3f}]")
print(f"P(more than 15% of the area is above z_c) = {(area_sims > 0.15).mean():.2f}")
inside = np.abs(z_true - etype) <= 1.645 * cond_sd
print(f"truth within E-type +/- 1.645 sd at {inside.mean():.1%} of nodes")

fig, axes = plt.subplots(1, 4, figsize=(20, 4.8))
for ax, (name, f, cmap) in zip(axes[:3], [("E-type (mean of 500)", etype, "YlOrRd"),
                                          ("conditional standard deviation", cond_sd, "viridis"),
                                          (f"P(Z > {z_c:.0f})", p_exceed, "magma")]):
    im = ax.imshow(as_map(f), origin="lower", extent=[0, NX * DX, 0, NX * DX], cmap=cmap)
    ax.scatter(samples["X"] + DX / 2, samples["Y"] + DX / 2, s=8, c="w", edgecolors="k", linewidths=0.4)
    ax.set_title(name); ax.set_xticks([]); ax.set_yticks([])
    plt.colorbar(im, ax=ax, shrink=0.85)
axes[3].hist(area_sims, bins=30, color="#7570b3", alpha=0.8)
axes[3].axvline(area_true, color="#d95f02", lw=2, label="truth")
axes[3].axvline(area_krig, color="#1f78b4", lw=2, ls="--", label="kriging map")
axes[3].set_xlabel(f"fraction of area with Z > {z_c:.0f}")
axes[3].set_title("Area above the threshold"); axes[3].legend(frameon=False)
plt.tight_layout(); plt.show()
500 realizations in 0.10 s, shape (500, 2500)
threshold z_c = 50.9 (80th percentile of the samples)
fraction of area above z_c:  truth 0.186   kriging map 0.083   realizations: mean 0.176, 90% interval [0.128, 0.227]
P(more than 15% of the area is above z_c) = 0.81
truth within E-type +/- 1.645 sd at 89.2% of nodes

  • E-type and spread. The E-type map looks like the kriging map, as it should: the mean of the realizations converges to the kriging estimate. The conditional standard deviation is zero at the samples and grows between them. It is largest in the hot spot, because a lognormal variable’s uncertainty grows with its value (the proportional effect), which a single Gaussian kriging variance cannot show in original units.
  • Calibration. The truth falls inside E-type ± 1.645 standard deviations at 89.2 % of the nodes, against a nominal 90 %. The spread is honest.
  • Area above the threshold. 18.6 % of the true field exceeds \(z_c = 51\). The kriging map says 8.3 %, less than half: smoothing removes the highs. The realizations put the area between 12.8 % and 22.7 % (90 % interval) with a mean of 17.6 %, which brackets the truth. The probability that more than 15 % of the area exceeds the threshold is 0.81, a statement about the whole map that no kriging map or kriging variance can provide.

The 500 realizations took 0.10 s because LUSimulator reuses its factorization. On larger grids FFTSimulator or TBSimulator play that role, and the sequential simulators can use the GPU.


Where the next notebooks go

The calls above are the whole API: build a variogram list, construct a simulator, fit the samples and the grid, simulate as many realizations as the question needs. The method notebooks take one simulator each to a real dataset and check it in more depth.

Next notebook What it adds
Sequential Gaussian simulation Meuse zinc: conditioning, histogram and variogram reproduction, E-type against ordinary kriging, quantile maps, CPU versus GPU
Sequential Gaussian co-simulation Jura nickel with chromium as the secondary
Sequential indicator simulation Meuse zinc through thresholds, order relations, and tail models
Sequential indicator co-simulation Jura cadmium and rock type, with soft information
Direct sequential simulation Jura cadmium in the original units, with zinc
Simulated annealing Jura nickel, rock type, and a chromium map
Plurigaussian simulation Five Jura rock types
Multiple-point statistics Direct Sampling and SNESIM on channels and the Jura geology map
SNESIM A three-facies fluvial system with wells and a seismic secondary

For more than a handful of realizations on a CUDA machine, pass use_gpu=True to the simulators in the GPU table above.


Resources

Textbooks

Reference What to read it for
Deutsch, C.V. & Journel, A.G. (1998). GSLIB: Geostatistical Software Library and User’s Guide (2nd ed.). Oxford University Press. The sgsim, sisim, lusim and sasim programs these modules follow, and the variogram convention
Goovaerts, P. (1997). Geostatistics for Natural Resources Evaluation. Oxford University Press. Simulation versus estimation, E-type and quantile maps, sequential Gaussian and indicator simulation in practice
Chilès, J.-P. & Delfiner, P. (2012). Geostatistics: Modeling Spatial Uncertainty (2nd ed.). Wiley. The theory of every family here: LU, turning bands, spectral, sequential, conditioning by kriging, truncated Gaussian
Lantuéjoul, C. (2002). Geostatistical Simulation: Models and Algorithms. Springer. The algorithms in depth, including turning bands and the dilution processes behind TBSimulator
Pyrcz, M.J. & Deutsch, C.V. (2014). Geostatistical Reservoir Modeling (2nd ed.). Oxford University Press. Workflows: declustering, transforms, checking and post-processing realizations, transfer functions
Armstrong, M., Galli, A., Beucher, H., Le Loc’h, G., Renard, D., Doligez, B., Eschard, R. & Geffroy, F. (2011). Plurigaussian Simulations in Geosciences (2nd ed.). Springer. Truncation rules, the Gibbs sampler, and plurigaussian simulation in practice

Papers and origins

Reference Contribution
Matheron, G. (1973). The intrinsic random functions and their applications. Advances in Applied Probability 5, 439-468. The turning bands method
Journel, A.G. (1974). Geostatistics for conditional simulation of ore bodies. Economic Geology 69, 673-687. Conditional simulation, and conditioning by kriging
Journel, A.G. & Huijbregts, C.J. (1978). Mining Geostatistics. Academic Press. Simulation for mining, and the smoothing effect of kriging
Davis, M.W. (1987). Production of conditional simulations via the LU triangular decomposition of the covariance matrix. Mathematical Geology 19, 91-98. LU simulation
Journel, A.G. & Alabert, F. (1989). Non-Gaussian data expansion in the earth sciences. Terra Nova 1, 123-134. Sequential indicator simulation
Deutsch, C.V. (1992). Annealing Techniques Applied to Reservoir Modeling and the Integration of Geological and Engineering (Well Test) Data. PhD thesis, Stanford University. Simulated annealing for geostatistics
Xu, W., Tran, T.T., Srivastava, R.M. & Journel, A.G. (1992). Integrating seismic data in reservoir modeling: the collocated cokriging alternative. SPE 24742. Collocated cokriging and Markov model 1, used by GaussianCoSimulator
Zhu, H. & Journel, A.G. (1993). Formatting and integrating soft data: stochastic imaging via the Markov-Bayes algorithm. In Soares, A. (ed.), Geostatistics Tróia ’92, 1-12. Kluwer. Soft indicator data, used by IndicatorCoSimulator
Dietrich, C.R. & Newsam, G.N. (1993). A fast and exact method for multidimensional Gaussian stochastic simulations. Water Resources Research 29, 2861-2869. Circulant embedding, the basis of FFTSimulator
Wood, A.T.A. & Chan, G. (1994). Simulation of stationary Gaussian processes in \([0,1]^d\). Journal of Computational and Graphical Statistics 3, 409-432. Circulant embedding
Soares, A. (2001). Direct sequential simulation and cosimulation. Mathematical Geology 33, 911-926. Direct sequential simulation
Oz, B., Deutsch, C.V., Tran, T.T. & Xie, Y. (2003). DSSIM-HR: A FORTRAN 90 program for direct sequential simulation with histogram reproduction. Computers & Geosciences 29, 39-51. The lookup-table variant, the default in DirectSequentialSimulator
Emery, X. & Lantuéjoul, C. (2006). TBSIM: A computer program for conditional simulation of three-dimensional Gaussian random fields via the turning bands method. Computers & Geosciences 32, 1615-1628. Turning bands with 3-D lines, as in TBSimulator

In this library

Object Role
sgsim, GaussianCoSimulator, sgcosim, sgcosim_hierarchical, sgsim_gpu Sequential Gaussian simulation and co-simulation
sisim, IndicatorCoSimulator, sicosim, SoftCalibration Sequential indicator simulation and co-simulation
LUSimulator, TBSimulator, FFTSimulator Exact and spectral Gaussian simulation
DirectSequentialSimulator, GlobalDistribution Direct sequential simulation in original units
SimulatedAnnealing, sasim Simulated annealing
PluriGaussianSimulator, TruncationRule, category_probabilities, category_proportions Plurigaussian simulation of facies
nscore_forward, nscore_back Normal-score transform and back-transform
Back to top