Dataset: Jura soil survey, Swiss Jura (Data/00_shared/data_geostatistics/jura_data.csv, 359 samples) + prediction grid (Data/00_shared/data_geostatistics/jura_grid.csv, 5,957 nodes on a 50 m lattice; every second row and column, a 100 m lattice of 1,540 nodes, is used for annealing)
Targets: nickel (Ni, mg/kg) as a continuous variable, rock type (Rock, five geological units) as a categorical variable, and a kriged chromium map as a secondary variable
Sequential, spectral and turning-band simulators all construct a realization from a random-function model. Simulated annealing works the other way round. It starts from any image that already has the right histogram, and rearranges it until the image matches a list of target statistics. The targets can be the variogram, indicator variograms for each class, and the correlation with a secondary variable. The rearrangement is a stochastic optimization borrowed from statistical physics (Kirkpatrick et al., 1983), adapted to geostatistics by Deutsch (1992) and Deutsch & Journel (GSLIB sasim / anneal).
Its strengths and weaknesses follow from that design:
Simulated annealing
Histogram
reproduced exactly: the image is a permutation of the target values
Variogram(s)
reproduced as closely as the optimization allows, at the lags and directions in the objective
yes: any statistic that can be written as an objective component
Data conditioning
hard data are fixed, but their influence on nearby nodes comes only through the variogram pairs
Uncertainty model
none explicit: the spread between realizations depends on the objective and the schedule, not on a random-function model
Cost
many swaps (hundreds per node); CPU only in GeoLattice
The objects:
Object
What it does
SimulatedAnnealing
fit(grid, df, ..., secondary=None) sets up the lattice, hard data, targets and secondary. simulate(nsim, seed) returns realizations at the grid nodes; simulate_lattice returns the full lattice. history_, objective_ and n_swaps_ record the optimization, and experimental_variogram / target_variogram evaluate an image at the objective lags.
sasim
One-call wrapper.
On the Jura data the notebook:
simulates nickel with a variogram objective, and checks exact histogram reproduction, variogram reproduction by direction, the effect of the annealing schedule, and local accuracy at 100 held-out sites against SGS;
adds a correlation component with a kriged chromium map;
simulates rock type with indicator variograms, with exact proportions, checked against the geology map.
Theory
Simulation as optimization
A realization is any image \(\{z(\mathbf{u}_j)\}_{j=1}^{N}\) on the lattice. Annealing defines an objective function\(O \ge 0\) that is 0 when the image has every target statistic, and searches for images with small \(O\). Different random starting images and random swap sequences lead to different low-\(O\) images: the realizations. There is no explicit random-function model. The set of realizations is “all images that match the targets well”, sampled by a randomized search. Two consequences follow:
anything that can be measured on an image can be a target;
the uncertainty between realizations is not calibrated by a probability model.
The objective function
The variogram component compares the image’s experimental variogram with the target model at a set of lag vectors. GeoLattice uses \(K\) = n_lags multiples of each direction \(\mathbf{d}\) in directions (default: the two axes and both diagonals, in cells):
Dividing by \(\gamma^2\) makes every lag count in relative terms, so short lags (small \(\gamma\)) are matched as carefully as long ones. The weights \(1/k\) give extra emphasis to the short lags, which control the look of the image. \(\gamma\) is the model vario in original units, [azimuth, nugget, major_range, minor_range, sill, vtype], evaluated at the lag vectors in coordinate units.
For a categorical variable with classes \(s_1, \dots, s_C\), the indicator component is the same sum over each class’s indicator variogram \(\gamma_I(\mathbf{h}; s_c)\) from indicator_varios.
With an exhaustive secondary \(y(\mathbf{u})\), the correlation component is
with \(\hat\rho_{zy}\) the correlation of the image with the secondary over the lattice, and \(\rho^{\text{target}}\) = target_correlation (default: the correlation of the data with the secondary).
Components live on different scales. As in GSLIB sasim, each is divided by the mean absolute change it undergoes over a set of random swaps of the starting image, \(\overline{|\Delta O_c|}\):
\[
O = \sum_c \frac{\omega_c}{\overline{|\Delta O_c|}}\, O_c ,
\]
so the user weights \(\omega_c\) (component_weights, e.g. {"variogram": 1, "correlation": 5}) are relative importances.
Swaps: the histogram for free
The starting image puts the stratified quantiles of the target histogram (target_values, by default the data) at the free nodes in random order:
Every perturbation is a swap of the values at two free nodes. A swap never changes the set of values, so the histogram is reproduced exactly, in every realization, at every step. For categorical variables this means the class proportions are exact, which sequential indicator simulation cannot guarantee.
The Metropolis rule and the annealing schedule
A swap that changes the objective from \(O\) to \(O'\) is accepted with probability
\[
P(\text{accept}) = \begin{cases} 1 & O' \le O \\ \exp\bigl(-(O' - O)/t\bigr) & O' > O, \end{cases}
\]
the Metropolis rule at temperature \(t\). Accepting some bad swaps early lets the search escape poor local minima. As \(t\) falls, the search becomes greedy. The schedule:
Parameter
Meaning
Default
t0
initial temperature, in units of the mean objective increase of a random swap (1 accepts a typical bad swap with probability \(e^{-1} \approx 0.37\))
1.0
reduction
\(t \leftarrow \lambda\, t\) after each temperature step
0.1
k_accept
accepted swaps per temperature
\(5\,N_{\text{free}}\)
k_max
attempted swaps per temperature
\(50\,N_{\text{free}}\)
max_swaps
total budget
\(500\,N_{\text{free}}\)
tol
stop when \(O \le \text{tol} \cdot O_{\text{init}}\)
\(10^{-3}\)
n_stop
stop after this many temperatures with no accepted swap
3
A fast schedule (small t0, small reduction) is close to a greedy descent: quick, but it can freeze in a poor arrangement. A slow schedule explores more. In GSLIB practice a fairly fast schedule works for variogram objectives because the objective landscape is benign (Deutsch & Journel, 1998).
Incremental updates
Recomputing the variogram after each swap would cost \(O(N)\) per lag. A swap only changes the pairs that involve the two swapped nodes, so GeoLattice updates the per-lag sums of squared differences from those pairs alone: \(O(L)\) per swap, with \(L\) the number of lag vectors. The lattice is padded with missing values so that pairs leaving the lattice are simply skipped. The correlation component is updated in \(O(1)\) from the change in \(\sum z y\).
Hard data, the lattice, and what annealing does not guarantee
Lattice. Annealing works on a regular lattice. fit infers it from the grid (or spacing), and it spans the bounding box of the grid and the data. Lattice nodes outside an irregular study area are simulated too, and they enter the objective, but simulate returns only the requested grid nodes.
Hard data are moved to their nearest lattice node. Several data at one node are averaged (continuous) or take their most frequent class (categorical). Those nodes are never swapped, so the data are honoured exactly at their nodes.
Conditioning is weak. A datum influences its neighbours only through the variogram pairs it belongs to. One pair among thousands at each lag carries almost no weight in \(O\), so nothing forces the nodes next to a high datum to be high. Annealed realizations can show discontinuities around the data, and their spread near the data can be too large. Sequential methods condition through kriging and do not have this problem. Section 9 measures it.
No probability model. The spread between realizations reflects the many images that fit the targets, not a posterior distribution. It is not guaranteed to be calibrated.
The algorithm
For each realization:
Place the hard data on the lattice; fill the free nodes with stratified quantiles of the target histogram in random order.
Compute the objective components, their scaling from random swaps, and the initial temperature.
Repeat until \(O \le \text{tol} \cdot O_{\text{init}}\), the swap budget is spent, or n_stop temperatures pass with no accepted swap:
at temperature \(t\), propose swaps of two random free nodes, update \(O\) incrementally, and accept by the Metropolis rule, until k_accept acceptances or k_max attempts;
record \(O / O_{\text{init}}\) in history_ and set \(t \leftarrow\)reduction\(\cdot\, t\).
Return the image at the grid nodes.
Python Setup
SimulatedAnnealing runs on the CPU only. Each swap is a small NumPy update, and realizations run one after another. The cost grows with the number of lattice nodes, because the default swap budget and the swaps per temperature are proportional to it. The notebook therefore anneals on a 100 m lattice; Section 13 times the 50 m lattice too. Plain SGS (sgsim_gpu) is used for comparison, on the GPU when one is available.
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.
The Jura data (Atteia et al., 1994; Goovaerts, 1997) are 359 topsoil samples from a 14.5 km² area of the Swiss Jura. jura_grid.csv holds 5,957 nodes on a 50 m lattice, with the mapped geology. Coordinates are in kilometres. Every second row and column gives a 100 m grid of 1,540 nodes; its lattice (the bounding box) has 49 × 59 = 2,891 nodes.
As in the earlier notebooks, 100 samples are held out at random as a validation set, and the other 259 are the conditioning data.
100 m grid: 1540 nodes; conditioning data: 259; validation sites: 100
Ni (259): mean 20.14, sd 7.73, skewness -0.06
Target Variograms
Annealing matches a variogram in original units, so the target is the variogram of nickel in mg/kg, with the sill equal to its variance. SGS, used for comparison, needs the variogram of the normal scores. Both are spherical models fitted by weighted least squares with the sill fixed.
The objective uses 10 lags of one cell (100 m) along each of the four default directions, so it controls the variogram up to 1 km along the axes and 1.4 km along the diagonals. That covers the range of about 0.9 km.
Code
N_LAGS =10SA_KW =dict(n_lags=N_LAGS)
A First Run with SimulatedAnnealing
Fit, simulate one realization, and look at what the optimizer did. history_ holds \(O / O_{\text{init}}\) after each temperature, n_swaps_ the swaps attempted, and objective_ the final relative objective.
lattice: 49 x 59 = 2891 nodes, spacing 0.10 km; hard-data nodes: 205 (259 data, some share a node)
one realization: 2.1 s, 57,001 swaps, final O / O_init = 9.9e-04, 3 temperatures
The full lattice includes the nodes outside the irregular study area (the corners of the bounding box); simulate drops them. The starting image is white noise with the right histogram, and annealing rearranges it into a spatially continuous field.
Checks on 20 realizations:
the histogram is exact (each image is a permutation of the start);
hard data are reproduced at their nodes;
the same seed reproduces the image;
sasim equals the class.
Code
N_SIM =20t0 = time.perf_counter()lat_reals = sa.simulate_lattice(nsim=N_SIM, seed=2024)sa_reals = lat_reals[:, sa._grid_idx[:, 0], sa._grid_idx[:, 1]]print(f"{N_SIM} realizations in {time.perf_counter() - t0:.0f} s; final O/O_init: median {np.median(sa.objective_):.1e}, "f"max {sa.objective_.max():.1e}")free = np.isnan(sa._hard)start_values = np.sort(img0[free])same_hist =all(np.allclose(np.sort(lat_reals[r][free]), start_values) for r inrange(N_SIM))record("annealing: histogram of free nodes exactly preserved by swaps", "PASS"if same_hist else"FAIL","sorted values identical to the stratified start in every realization")hard = np.isfinite(sa._hard)err =max(np.abs(lat_reals[r][hard] - sa._hard[hard]).max() for r inrange(N_SIM))record("annealing: hard data honoured at their nodes", "PASS"if err ==0else"FAIL", f"max error {err}")again = SimulatedAnnealing(vario=vario_ni, **SA_KW).fit(grid, df, "Xloc", "Yloc", "Ni").simulate(nsim=2, seed=2024)record("annealing: same seed -> identical", "PASS"if np.array_equal(again, sa_reals[:2]) else"FAIL")one_call = sasim(grid, df, "Xloc", "Yloc", "Ni", vario=vario_ni, nsim=2, seed=2024, **SA_KW)record("sasim == SimulatedAnnealing(...).simulate", "PASS"if np.array_equal(one_call, sa_reals[:2]) else"FAIL")record("annealing converged (O/O_init <= 1e-3) in every realization","PASS"if (sa.objective_ <=1.001e-3).all() else"FAIL", f"max {sa.objective_.max():.1e}")print(f"\nNi data: mean {ni.mean():.2f}, sd {ni.std():.2f}; annealed grid values: mean {sa_reals.mean():.2f}, "f"sd {sa_reals.std(1).mean():.2f}")
20 realizations in 42 s; final O/O_init: median 1.0e-03, max 1.0e-03
✅ [PASS] annealing: histogram of free nodes exactly preserved by swaps sorted values identical to the stratified start in every realization
✅ [PASS] annealing: hard data honoured at their nodes max error 0.0
✅ [PASS] annealing: same seed -> identical
✅ [PASS] sasim == SimulatedAnnealing(...).simulate
✅ [PASS] annealing converged (O/O_init <= 1e-3) in every realization max 1.0e-03
Ni data: mean 20.14, sd 7.73; annealed grid values: mean 20.64, sd 7.48
Variogram Reproduction by Direction
experimental_variogram(image) and target_variogram() evaluate an image and the target at exactly the lag vectors in the objective: four directions × 10 lags. The realizations should follow the target in every direction, because every direction is in the objective. Between the controlled lags, and beyond them, nothing is enforced.
Code
target = sa.target_variogram()[0].reshape(4, N_LAGS)emp = np.stack([sa.experimental_variogram(lat_reals[r])[0].reshape(4, N_LAGS) for r inrange(N_SIM)])names = ["E-W (1, 0)", "N-S (0, 1)", "diagonal (1, 1)", "diagonal (1, −1)"]steps = [1.0, 1.0, np.sqrt(2), np.sqrt(2)]fig, axes = plt.subplots(1, 4, figsize=(21, 4.2), sharey=True)for d, ax inenumerate(axes): h = np.arange(1, N_LAGS +1) * steps[d] * CELLfor r inrange(N_SIM): ax.plot(h, emp[r, d], color="0.7", lw=0.8) ax.plot(h, target[d], "ro-", ms=4, label="target") ax.set_title(names[d]) ax.set_xlabel("h (km)")axes[0].set_ylabel("semivariance (mg/kg)²")axes[0].legend()plt.tight_layout()plt.show()rel = np.abs(emp.mean(0) - target) / targetworst = np.unravel_index(rel.argmax(), rel.shape)print(f"relative error: median {np.median(rel):.3f}, max {rel.max():.3f} ({names[worst[0]]}, lag {worst[1] +1})")record("annealing: variogram within 10% of target at every controlled lag (mean of realizations)","PASS"if rel.max() <0.10else"FAIL", f"max relative error {rel.max():.3f}")
relative error: median 0.032, max 0.072 (E-W (1, 0), lag 7)
✅ [PASS] annealing: variogram within 10% of target at every controlled lag (mean of realizations) max relative error 0.072
At the controlled lags the realizations sit almost exactly on the target, in all four directions, with very little spread between realizations. That is the optimizer at work, and it is the main thing annealing does well. The remaining error (a few per cent, largest at the shortest lags) is set by the stopping rule: annealing stops when \(O\) falls to tol\(= 10^{-3}\) of its initial value. Section 8 tightens it. The narrow spread is also a reminder: the realizations agree with the model, not with the data. Sequential methods reproduce the model variogram only on average, with realistic ergodic fluctuations between realizations.
The Annealing Schedule
Three schedules are compared, each on 3 realizations:
Schedule
t0
reduction
Character
quench
0.01
0.01
almost greedy descent
default
1.0
0.1
GSLIB-style fast annealing
slow
2.0
0.5
many temperature steps
default, tol = 1e-4
1.0
0.1
default schedule, stricter stopping rule
Code
schedules = {"quench": dict(t0=0.01, reduction=0.01), "default": dict(t0=1.0, reduction=0.1),"slow": dict(t0=2.0, reduction=0.5), "default, tol = 1e-4": dict(t0=1.0, reduction=0.1, tol=1e-4)}rows, hist = [], {}for name, kw in schedules.items(): s = SimulatedAnnealing(vario=vario_ni, **SA_KW, **kw).fit(grid, df, "Xloc", "Yloc", "Ni") t0 = time.perf_counter() lr = s.simulate_lattice(nsim=3, seed=7) hist[name] = s.history_[0] vg_err = np.mean([np.abs(s.experimental_variogram(lr[i])[0] / s.target_variogram()[0] -1).max() for i inrange(3)]) rows.append({"schedule": name, "seconds / realization": (time.perf_counter() - t0) /3,"swaps / realization": s.n_swaps_.mean(), "temperatures": np.mean([len(h) -1for h in s.history_]),"final O/O_init": s.objective_.mean(), "max rel. variogram error": vg_err})sched = pd.DataFrame(rows).set_index("schedule")fig, ax = plt.subplots(figsize=(7.5, 4.3))for name, h in hist.items(): ax.semilogy(h, "o-", ms=3, label=name)ax.set_xlabel("temperature step")ax.set_ylabel("O / O_init")ax.legend()plt.tight_layout()plt.show()sched.round(4)
seconds / realization
swaps / realization
temperatures
final O/O_init
max rel. variogram error
schedule
quench
0.5694
15515.3333
1.0
0.0010
0.1242
default
2.0615
56578.3333
3.0
0.0010
0.1109
slow
6.7870
187386.0000
8.0
0.0010
0.0740
default, tol = 1e-4
3.2738
90527.6667
4.0
0.0001
0.0448
All four schedules reach the stopping tolerance. For a variogram objective the landscape is benign, so even an almost greedy quench (one temperature step, 0.6 s) gets there, about 4× faster than the default. The schedule does affect how well the variogram is matched at the end:
max relative variogram error in one realization
quench
12%
default
11%
slow
7%
default with tol = 1e-4
4.5%
Both a slower schedule and a stricter tol buy precision with time. The stopping rule is the more direct lever: the default schedule with tol = 1e-4 was more precise than the slow schedule and took half the time.
For objectives with competing components (Section 10), or for categorical images, where swaps can create isolated pixels that a greedy search never removes, a slower schedule is worth more.
Conditioning and Local Accuracy: Annealing vs SGS
The data are fixed at their nodes, but Section 2.6 warned that their influence on the neighbouring nodes is weak. Three diagnostics compare 20 annealed realizations with 20 SGS realizations on the same 100 m grid:
Continuity across the data: the mean squared difference between a hard-data node and its four lattice neighbours, against the same quantity between other nodes. In a realization without conditioning artefacts the two agree, at about \(2\gamma(100\text{ m})\).
E-type maps: does the mean of the realizations reflect the data?
Held-out sites: RMSE of the E-type and coverage of the 80% interval at the 100 validation sites, each read at its nearest grid node.
Code
sgs_reals = sgsim_gpu(grid, df, "Xloc", "Yloc", "Ni", vario_ns, num_points=16, radius=1.5, nsim=N_SIM, seed=2024, zmin=0.0, use_gpu=USE_GPU)sgs_lat = np.full_like(lat_reals, np.nan)sgs_lat[:, sa._grid_idx[:, 0], sa._grid_idx[:, 1]] = sgs_realsin_grid = np.zeros(sa._hard.shape, bool)in_grid[sa._grid_idx[:, 0], sa._grid_idx[:, 1]] =Truedef neighbour_msd(images, mask):# mean squared difference between masked nodes and their 4 lattice neighbours (inside the grid) out = []for im_ in images: d2 = []for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]: nb = np.roll(np.roll(im_, di, 0), dj, 1) ok = mask & np.roll(np.roll(in_grid, di, 0), dj, 1) & in_grid d2.append((im_[ok] - nb[ok]) **2) out.append(np.concatenate(d2).mean())return np.mean(out)hard_mask = hard & in_gridfree_mask = free & in_gridcont = pd.DataFrame({"around hard data": [neighbour_msd(lat_reals, hard_mask), neighbour_msd(sgs_lat, hard_mask)],"elsewhere": [neighbour_msd(lat_reals, free_mask), neighbour_msd(sgs_lat, free_mask)]}, index=["annealing", "SGS"])cont["ratio"] = cont["around hard data"] / cont["elsewhere"]print("mean squared difference to the 4 neighbours, (mg/kg)²; model 2*gamma(0.1 km) =",round(2* spherical(0.1, *vario_ni[1:3], vario_ni[4]), 1))display(cont.round(2))fig, axes = plt.subplots(1, 3, figsize=(20, 5.5))show_map(axes[0], sa_reals.mean(0), "Annealing: E-type (20)", vmin=5, vmax=35, points=xy)show_map(axes[1], sgs_reals.mean(0), "SGS: E-type (20)", vmin=5, vmax=35, points=xy)sc = axes[2].scatter(xy[:, 0], xy[:, 1], c=ni, s=20, cmap="viridis", vmin=5, vmax=35)axes[2].set_aspect("equal")axes[2].set_title("Ni data (259)")plt.colorbar(sc, ax=axes[2], label="Ni (mg/kg)", fraction=0.046, pad=0.04)plt.tight_layout()plt.show()
mean squared difference to the 4 neighbours, (mg/kg)²; model 2*gamma(0.1 km) = 35.9
around hard data
elsewhere
ratio
annealing
45.95
36.94
1.24
SGS
39.67
39.93
0.99
Code
N_VAL =40node_test = cKDTree(grid).query(xy_test)[1]truth = test["Ni"].to_numpy(float)t0 = time.perf_counter()sa_val = SimulatedAnnealing(vario=vario_ni, **SA_KW).fit(grid, df, "Xloc", "Yloc", "Ni").simulate(nsim=N_VAL, seed=11)print(f"{N_VAL} annealing realizations in {time.perf_counter() - t0:.0f} s")sgs_val = sgsim_gpu(grid, df, "Xloc", "Yloc", "Ni", vario_ns, num_points=16, radius=1.5, nsim=N_VAL, seed=11, zmin=0.0, use_gpu=USE_GPU)# validation sites whose nearest node holds a hard datum get that datum in every annealed realizationgrid_hard = np.isfinite(sa._hard[sa._grid_idx[:, 0], sa._grid_idx[:, 1]])on_hard = grid_hard[node_test]print(f"{on_hard.sum()} of {len(truth)} validation sites fall on a hard-data node of the 100 m lattice")def score(name, ens, sites=slice(None)): e = ens[:, node_test][:, sites] t = truth[sites] et = e.mean(0) lo, hi = np.percentile(e, [10, 90], axis=0)return {"method": name, "n sites": len(t), "RMSE": np.sqrt(np.mean((et - t) **2)), "corr": np.corrcoef(et, t)[0, 1],"cover80": np.mean((t >= lo) & (t <= hi)), "width80": np.mean(hi - lo)}val_table = pd.DataFrame([score("annealing, all sites", sa_val), score("SGS, all sites", sgs_val), score("annealing, free-node sites", sa_val, ~on_hard), score("SGS, free-node sites", sgs_val, ~on_hard)]).set_index("method")display(val_table.round(3))a, g_ = val_table.loc["annealing, free-node sites"], val_table.loc["SGS, free-node sites"]record("annealing 80% intervals under-cover at held-out free-node sites (expected: no probability model)","PASS"if a.cover80 <0.65and0.65<= g_.cover80 <=0.95else"FAIL",f"coverage annealing {a.cover80:.2f} (width {a.width80:.1f}), SGS {g_.cover80:.2f} (width {g_.width80:.1f})")
40 annealing realizations in 83 s
38 of 100 validation sites fall on a hard-data node of the 100 m lattice
n sites
RMSE
corr
cover80
width80
method
annealing, all sites
100
5.623
0.777
0.370
7.811
SGS, all sites
100
5.718
0.773
0.780
12.120
annealing, free-node sites
62
6.358
0.644
0.597
12.599
SGS, free-node sites
62
5.876
0.710
0.742
12.957
✅ [PASS] annealing 80% intervals under-cover at held-out free-node sites (expected: no probability model) coverage annealing 0.60 (width 12.6), SGS 0.74 (width 13.0)
Discontinuities around the data. In the annealed realizations a hard-data node differs from its neighbours by 24% more (mean squared difference 46 vs 37 (mg/kg)²) than other nodes do from theirs. In SGS the two are equal (ratio 0.99). The hard data are fixed, but the objective barely notices how they connect to their surroundings. This is the conditioning artefact described in Section 2.6.
Held-out sites. 38 of the 100 validation sites have a hard datum at their nearest 100 m node. There, every annealed realization returns that datum, a neighbouring sample, with zero spread. Scores over all sites are therefore misleading: annealing appears as accurate as SGS, with absurdly narrow intervals (coverage 0.37).
At the 62 sites with a free node, SGS is clearly better:
E-type RMSE 5.88 vs 6.36 mg/kg, and correlation with the truth 0.71 vs 0.64;
the intervals are equally wide, but SGS’s cover 74% of the true values against annealing’s 60%.
Annealing’s local distributions are both less accurate and less calibrated, because nothing in the objective ties them to the data the way kriging does.
E-type maps. The annealed E-type is noisier, with isolated spots at the data, while the SGS E-type is a smooth, kriging-like surface.
A Secondary Variable: the Correlation Component
Chromium is strongly related to nickel in the Jura soils. A kriged chromium map (from all 359 samples) is passed as secondary, which adds the correlation component \(O_\rho\). The target correlation defaults to the correlation between Ni and Cr at the data (secondary_col="Cr"). The weight of the correlation component relative to the variogram is varied with component_weights.
Code
xy_all = df_all[["Xloc", "Yloc"]].to_numpy(float)cr_all = df_all["Cr"].to_numpy(float)vg_cr = Variogram(xy_all, cr_all, model="spherical", n_lags=15).fit()cr_grid = np.asarray(OrdinaryKriging(vg_cr).fit(xy_all, cr_all).predict(grid), float)rows, corr_reals = [], {}for w in [0.0, 1.0, 5.0]: s = SimulatedAnnealing(vario=vario_ni, **SA_KW, component_weights={"variogram": 1.0, "correlation": w}) s.fit(grid, df, "Xloc", "Yloc", "Ni", secondary=cr_grid, secondary_col="Cr") r_ = s.simulate(nsim=N_SIM, seed=11) corr_reals[w] = r_ rho_real = np.array([np.corrcoef(r_[i], cr_grid)[0, 1] for i inrange(len(r_))]) lat_r = s.simulate_lattice(nsim=1, seed=5)[0] vg_err = np.abs(s.experimental_variogram(lat_r)[0] / s.target_variogram()[0] -1).max() rows.append({"correlation weight": w, "target rho": s.rho_target_, "realized rho (mean)": rho_real.mean(),"realized rho (sd)": rho_real.std(), "max rel. variogram error": vg_err,**{k: v for k, v in score("", r_, ~on_hard).items() if k notin ("method", "n sites")}})corr_table = pd.DataFrame(rows).set_index("correlation weight")corr_table.round(3)
✅ [PASS] correlation component: realized rho within 0.05 of target (weight 1) target 0.701, realized 0.741
Without the correlation component (weight 0), the annealed Ni correlates 0.46 with the Cr map, which is what the hard data alone impose.
With weight 1, the realized correlation reaches 0.74 against the target 0.70. The objective stops at tol of its initial value, so it does not land exactly. The between-realization spread of the correlation (0.006) is tiny. As with the variogram, annealing enforces the target statistic in every realization rather than on average.
Raising the weight to 5 buys nothing for the correlation but costs variogram precision (maximum error 16% against 12%). Competing components trade off through component_weights.
The secondary improves the E-type at the free-node validation sites (RMSE 6.40 → 5.68 mg/kg, correlation 0.64 → 0.75), but not the calibration: coverage stays near 0.6.
Categorical Annealing: Rock Type
With indicator_varios={class: vario} the objective becomes the sum of the indicator-variogram mismatches of the five rock types. Because swaps keep the starting values, the class proportions are exact. In sequential indicator simulation the same rock types drifted (Kimmeridgian 0.44 against 0.36 in the samples).
The indicator variogram of each class is fitted with sill \(p_c(1 - p_c)\). The geology map is the reference, as in the SIS notebook.
Code
CLASSES = [1, 2, 3, 4, 5]rock = df["Rock"].to_numpy(float)ind_varios = {c: fit_spherical(xy, (rock == c).astype(float), (rock == c).mean() * (1- (rock == c).mean()))[0]for c in CLASSES}for c, v in ind_varios.items():print(f"{ROCKS[c]:13s} p = {(rock == c).mean():.3f} vario = {v}")N_CAT =8t0 = time.perf_counter()sac = SimulatedAnnealing(indicator_varios=ind_varios, **SA_KW).fit(grid, df, "Xloc", "Yloc", "Rock")cat_lat = sac.simulate_lattice(nsim=N_CAT, seed=3)cat_reals = cat_lat[:, sac._grid_idx[:, 0], sac._grid_idx[:, 1]]print(f"\n{N_CAT} categorical realizations in {time.perf_counter() - t0:.0f} s; final O/O_init median "f"{np.median(sac.objective_):.1e}")free_c = np.isnan(sac._hard)props_lat = np.array([[np.mean(cat_lat[r][free_c] == c) for c in CLASSES] for r inrange(N_CAT)])counts = np.stack([(cat_reals == c).mean(0) for c in CLASSES])mode = np.array(CLASSES)[counts.argmax(0)]cat_table = pd.DataFrame({"samples (259)": [(rock == c).mean() for c in CLASSES],"annealing, free lattice nodes": props_lat.mean(0),"sd over realizations": props_lat.std(0),"annealing, study-area nodes": [(cat_reals == c).mean() for c in CLASSES],"geology map": [(grid_rock == c).mean() for c in CLASSES]}, index=[ROCKS[c] for c in CLASSES])display(cat_table.round(4))print(f"agreement with the geology map: most probable class {np.mean(mode == grid_rock):.3f}, "f"per realization {np.mean(cat_reals == grid_rock):.3f}")record("categorical annealing: class proportions identical in every realization (free nodes)","PASS"if props_lat.std(0).max() <1e-12else"FAIL", f"max sd over realizations {props_lat.std(0).max():.1e}")
Argovian p = 0.208 vario = [0.0, np.float64(0.029), np.float64(1.189), np.float64(1.189), np.float64(0.165), 'spherical']
Kimmeridgian p = 0.363 vario = [0.0, np.float64(0.078), np.float64(1.346), np.float64(1.346), np.float64(0.231), 'spherical']
Sequanian p = 0.259 vario = [0.0, np.float64(0.0), np.float64(0.568), np.float64(0.568), np.float64(0.192), 'spherical']
Portlandian p = 0.012 vario = [0.0, np.float64(0.0), np.float64(0.363), np.float64(0.363), np.float64(0.011), 'spherical']
Quaternary p = 0.158 vario = [0.0, np.float64(0.0), np.float64(0.378), np.float64(0.378), np.float64(0.133), 'spherical']
8 categorical realizations in 216 s; final O/O_init median 9.5e-04
samples (259)
annealing, free lattice nodes
sd over realizations
annealing, study-area nodes
geology map
Argovian
0.2085
0.2085
0.0
0.2025
0.2026
Kimmeridgian
0.3629
0.3630
0.0
0.3838
0.3448
Sequanian
0.2587
0.2587
0.0
0.2618
0.2636
Portlandian
0.0116
0.0115
0.0
0.0110
0.0558
Quaternary
0.1583
0.1582
0.0
0.1409
0.1331
agreement with the geology map: most probable class 0.642, per realization 0.570
✅ [PASS] categorical annealing: class proportions identical in every realization (free nodes) max sd over realizations 5.6e-17
Proportions are exact. On the free lattice nodes every realization has exactly the target proportions (standard deviation over realizations about \(10^{-17}\)). Sequential indicator simulation cannot guarantee that. Over the study-area nodes alone the proportions differ a little: Kimmeridgian 0.38 against 0.36, because the lattice nodes outside the irregular boundary also take part of the histogram. If the proportions must hold inside an irregular area, use a grid that fills the lattice, or pass a mask by simulating on the bounding box and discarding the outside.
Patterns. The realizations have patchy, map-like units with the target indicator variograms (E-W shown). The most probable class matches the geology map at 64% of the nodes, and single realizations at 57%. Portlandian keeps its sample proportion (1.1%), far below its 5.6% on the map, because annealing can only reproduce the proportions it is given. A better target (for example from the map, through target_values) would have to come from outside the samples.
Cost. Categorical annealing took about 26 s per realization, roughly ten times more than the continuous case on the same lattice: five indicator variograms per swap, and more swaps to converge.
Visualization of Spatial Uncertainty
The 20 continuous realizations from Section 6 are used for an animation and conditional quantile maps. Read them with Section 9 in mind: the spread between annealed realizations is a by-product of the search, not a calibrated probability.
annealing : mean width of the 80% interval 10.9 mg/kg
SGS : mean width of the 80% interval 11.9 mg/kg
Run Time
The default swap budget, swaps per temperature and scaling sample all grow with the number of free lattice nodes, so the cost per realization grows at least linearly with the lattice size. One continuous realization on the 100 m lattice and one on the full 50 m lattice:
Each swap costs about 36 µs on either lattice. The default budget scales with the lattice: 57,000 swaps on the 2,891-node lattice and 255,000 on the 11,349-node one. One realization therefore takes about 2 s at 100 m and 9 s at 50 m for the continuous variogram objective. Categorical objectives cost about ten times more (Section 11). With no GPU engine, large grids and many realizations need a time budget. The quench schedule (Section 8) or a looser tol are the main ways to save time.
Summary and Conclusions
Code
pd.DataFrame(RESULTS)
Feature
Status
Notes
0
annealing: histogram of free nodes exactly pre...
PASS
sorted values identical to the stratified star...
1
annealing: hard data honoured at their nodes
PASS
max error 0.0
2
annealing: same seed -> identical
PASS
3
sasim == SimulatedAnnealing(...).simulate
PASS
4
annealing converged (O/O_init <= 1e-3) in ever...
PASS
max 1.0e-03
5
annealing: variogram within 10% of target at e...
PASS
max relative error 0.072
6
annealing 80% intervals under-cover at held-ou...
PASS
coverage annealing 0.60 (width 12.6), SGS 0.74...
7
correlation component: realized rho within 0.0...
PASS
target 0.701, realized 0.741
8
categorical annealing: class proportions ident...
PASS
max sd over realizations 5.6e-17
Simulated annealing treats simulation as optimization. It swaps values of a random image until an objective made of target statistics is small. Swaps keep the histogram exactly, and hard data are fixed at their nodes. Both were checked on every realization.
Variograms are matched closely at the controlled lags and directions, in every realization, with very little ergodic spread. The precision is set by the stopping rule: about 11% maximum error with tol = 1e-3, and 4.5% with tol = 1e-4. For a variogram objective, even a quench converges; it was about 4× faster than the default schedule.
Conditioning is weak. Annealed realizations show discontinuities around the data (24% larger neighbour differences than elsewhere). At held-out sites away from the data they were less accurate than SGS (RMSE 6.36 vs 5.88 mg/kg) and poorly calibrated (80% intervals covered 60%, against 74% for SGS). Do not use annealing realizations as calibrated local uncertainty.
Extra statistics are easy to add. A correlation component brought the Ni-Cr map correlation from 0.46 to 0.74 (target 0.70) and improved the E-type. Its weight trades off against variogram precision.
Categorical annealing reproduced the rock-type proportions exactly in every realization, which SIS cannot do. Lattice nodes outside an irregular study area take part of the histogram.
Cost: about 36 µs per swap and hundreds of swaps per node: 2 s per continuous realization on the 100 m lattice, 9 s at 50 m, and about ten times more for five-class categorical objectives. CPU only.
Object
Role in this notebook
SimulatedAnnealing
Continuous (Ni, variogram objective), with a correlation component (Cr map), and categorical (rock type, indicator variograms); history_, objective_, n_swaps_, experimental_variogram, target_variogram
sasim
One-call annealing
sgsim_gpu
SGS baseline for conditioning and local accuracy
Variogram / OrdinaryKriging
Kriged Cr map used as the secondary variable
Choosing the options
Situation
Choice
Exact histogram or class proportions required
annealing: swaps preserve them exactly
Several target statistics at once (variograms, correlation, …)
annealing with component_weights
Local accuracy and calibrated local uncertainty near data
sequential simulation (SGS, SIS, DSS)
Post-processing realizations from another method to fix the histogram or proportions
annealing from those values as target_values (with care: annealing reorders the image)
Long-range structure
enough n_lags (or larger lag steps through directions) to cover the range
Large grids
budget time: cost grows at least linearly with lattice size; tune max_swaps, k_accept, tol
Metropolis, N., Rosenbluth, A.W., Rosenbluth, M.N., Teller, A.H. & Teller, E. (1953). Equation of state calculations by fast computing machines. Journal of Chemical Physics 21, 1087-1092.
The acceptance rule
Deutsch, C.V. (1992). Annealing techniques applied to reservoir modeling and the integration of geological and engineering (well test) data. PhD thesis, Stanford University.
Annealing in geostatistics, objective scaling
Deutsch, C.V. & Journel, A.G. (1998). GSLIB: Geostatistical Software Library and User’s Guide, 2nd ed. Oxford University Press.
sasim / anneal, schedule parameters
Goovaerts, P. (1997). Geostatistics for Natural Resources Evaluation. Oxford University Press.
Annealing vs sequential simulation, Jura case study
Atteia, O., Dubois, J.-P. & Webster, R. (1994). Geostatistical analysis of soil contamination in the Swiss Jura. Environmental Pollution 86, 315-327.