How does a model get better, and how does it get fast without getting wrong?
GeoStack · background · predict → compare → improve
Abstract¶
Two cycles organise the modelling in the stack. The modeling cycle says how a model improves: compare its predictions with observations, and let the kind of misfit decide whether to tune the model or to change it. The six-step cycle says how a trusted but slow method becomes a fast one, with each step checked against the one before. Three worked examples follow it, one per page: retrieval, quantification and persistency, on the stack’s own libraries. This page explains the two cycles first, on one small methane plume, where the first model is wrong in a way that tuning cannot fix.
The running example¶
Part 1 · The modeling cycle: how a model improves¶
Real-world systema leaking facility
MODELING
OBSERVINGmore or better data
Conceptual modela steady plume, blown downwind
Sensoran imaging spectrometer
Equations and codethe Gaussian plume simulator
Measurementsradiance per pixel
Predictionsthe expected column map
Observationsthe retrieved column map
Comparepredictions vs observations
random misfit
systematic misfit
Estimatestate : data assimilationparameters : calibration
Refine the modelequations, code,sensors, processing
inner loop · fast: update and , run the same model againouter loop · slow: change the structure only when validation demands it
The modeling cycle of the overview, with this page’s example in the small print. Two tracks start from the same real system and meet at compare. What the misfit looks like decides which loop runs next.
The modeling track turns an idea of how the system works into equations, then code, then predictions. The observing track turns the same system into measurements, then observations. Neither is the truth; each is a simplification, and compare is where they are confronted.
def plume(rate, spread, direction):
"""f(θ): column mass of a time-averaged Gaussian plume, in g m⁻².
Ω(s) = Q / (U √(2π) σ_cw(s₁)) · exp(−s₂² / 2σ_cw(s₁)²), σ_cw(s₁) = a s₁^0.9
with s = (s₁, s₂) the downwind and crosswind distance from the source.
"""
col, row = np.meshgrid(np.arange(SIDE), np.arange(SIDE))
east = (col[..., None, None] + SUB[:, None] - SOURCE[0]) * PIXEL_M # (H, W, 3, 1) m
north = (row[..., None, None] + SUB[None, :] - SOURCE[1]) * PIXEL_M # (H, W, 1, 3) m
angle = direction + MEANDER[:, None, None, None, None] # (K, 1, 1, 1, 1)
downwind = east * np.cos(angle) + north * np.sin(angle) # (K, H, W, 3, 3) m
crosswind = -east * np.sin(angle) + north * np.cos(angle)
sigma = spread * np.maximum(downwind, 1.0) ** 0.9 # σ_cw, m
column = rate / (WIND_M_S * np.sqrt(2 * np.pi) * sigma) * np.exp(-(crosswind**2) / (2 * sigma**2))
column = np.where(downwind > 0, column, 0.0)
return 1e3 * column.mean(axis=(0, 3, 4)) # (H, W) g m⁻²Compare: is the misfit random or systematic?¶
Subtract the prediction from the observation and divide by the noise level. If the model is right, what is left is noise: it averages one when squared () and a pixel tells you nothing about its neighbour. If the model is wrong, what is left has a shape.
def compare(scene, prediction):
"""Is the misfit random (the error model explains it) or systematic?"""
residual = (scene - prediction) / NOISE
# χ²: mean squared residual in units of the noise; 1 if the model is right
chi2 = float(np.mean(residual**2))
# ρ₁: correlation of each residual with its right-hand neighbour; 0 if random
neighbour = float(np.mean(residual[:, :-1] * residual[:, 1:]) / np.mean(residual**2))
count = residual.size
random = chi2 < 1 + 3 * np.sqrt(2 / count) and abs(neighbour) < 3 / np.sqrt(count)
return {"chi2": round(chi2, 3), "neighbour": round(neighbour, 3), "verdict": "random" if random else "systematic",
"chi2_limit": round(1 + 3 * np.sqrt(2 / count), 3), "neighbour_limit": round(3 / np.sqrt(count), 3)}
Observation · the scene: plume plus noise

Model 1, fitted · wind along the forecast

Misfit 1 · : a pattern

Model 2, fitted · wind direction estimated

Misfit 2 · : noise
Column maps in (dark is zero); misfits in units of the noise, blue -4 to red +4. The scene is across; the source is at the left.
| χ² (1 if only noise) | Neighbour correlation (0 if only noise) | Verdict | |
|---|---|---|---|
| Limits for this scene | below 1.13 | within ±0.09 | — |
| Model 1 before estimating | 3.30 | 0.72 | systematic |
| Model 1 after the inner loop | 2.41 | 0.62 | systematic |
| Model 2 after the inner loop | 0.95 | 0.01 | random |
The inner loop: estimate, with the model held fixed¶
The inner loop keeps the model’s structure and adjusts its numbers: the state (data assimilation) or the parameters (calibration). Here it is a sampler that proposes parameter values, runs the simulator, and keeps values in proportion to how well they explain the scene.
def log_posterior(theta, scene, forward, low, high):
"""log p(θ | y) up to a constant: flat prior in a box, Gaussian noise."""
if np.any(theta < low) or np.any(theta > high):
return -np.inf
residual = scene - forward(theta)
return -0.5 * np.sum(residual**2) / NOISE**2
def metropolis(scene, forward, start, low, high, steps, rng):
"""Random-walk Metropolis; the proposal adapts to the chain during burn-in."""
dims = len(start)
theta, value = np.array(start, float), log_posterior(start, scene, forward, low, high)
step = np.diag(((high - low) * 0.02) ** 2)
chain, calls = [], 1
for index in range(steps):
if index in (300, 700, 1200):
step = 2.38**2 / dims * np.cov(np.array(chain[index // 2:]).T) + 1e-12 * np.eye(dims)
proposal = rng.multivariate_normal(theta, step)
proposed = log_posterior(proposal, scene, forward, low, high)
calls += 1
if np.log(rng.uniform()) < proposed - value:
theta, value = proposal, proposed
chain.append(theta.copy())
return np.array(chain[1500:]), calls| Inner loop with | Emission rate (kg s⁻¹) | Spread coefficient | Wind direction (degrees) | Simulator calls | Time |
|---|---|---|---|---|---|
| Truth | 2.00 | 0.300 | 12.0 | — | — |
| Model 1 | 2.09 ± 0.04 | 0.580 ± 0.013 | fixed at 0 | 4 001 | 36 s |
| Model 2 | 2.00 ± 0.03 | 0.310 ± 0.010 | 11.96 ± 0.24 | 6 001 | 67 s |
The outer loop: change the structure¶
A systematic misfit means something is missing. The misfit map says what: positive on one side of the plume, negative on the other, the mark of a plume pointing the wrong way. The refinement is one new parameter, the wind direction. The same inner loop then finds 12.0° and the misfit becomes noise. The other branch of the outer loop, dashed in the figure, changes the observing side instead: a better wind product, a second overpass, a finer sensor.
Part 2 · The six-step cycle: how a trusted method becomes a fast one¶
Model 2 passes compare. The inference that established it takes about a minute per scene, which is fine for one plume and hopeless for a satellite archive. The six-step cycle makes it fast without losing track of whether it is still right.
oracle: step 2 is the trusted reference for steps 3 to 5
1 simple model
2 model-based
3 emulator
4 emulator-based
5 amortized
simulated pairs: the training data for steps 3 and 5
6 improvethe outer loop
step 2against step 1
step 3against step 2
step 4against step 3
step 5against step 4
The six-step cycle of the overview. Arrows along the row are the order of work. Dashed arrows are the feedback: who trains whom (green) and who checks whom (orange).
1 · Simple model
A generative story you can simulate: the parameters go through the model and the observation operator to a column map, plus Gaussian noise. One call takes 11 ms.
| Role | Symbol | Name | Shape | Unit | Note |
|---|---|---|---|---|---|
| Input | emission rate | () | kg s⁻¹ | with and , the entries of : what we want to infer | |
| spread coefficient | () | — | |||
| wind direction | () | degrees | |||
| the entries together | (3,) | kg s⁻¹, —, degrees | |||
| External input | wind speed | () | m s⁻¹ | from a forecast | |
| Constant | noise level | () | g m⁻² | of the retrieval | |
| noise draw | (row, col) | g m⁻² | |||
| , | simulator and observation operator | , | |||
| Output | column map | (row, col) | g m⁻² | 11 ms per call; is the flattened (row, col) map, |
2 · Model-based inference
Invert the simple model slowly and carefully, by sampling its posterior. This is the trusted reference and the inner loop of the cycle; it takes 6 001 simulator calls and 67 s.
| Role | Symbol | Name | Shape | Unit | Note |
|---|---|---|---|---|---|
| Input | observed column map | (row, col) | g m⁻² | one scene | |
| Constant | simulator | ||||
| observation operator | |||||
| prior density | () | ||||
| Output | samples of | posterior samples | (sample, 3) | kg s⁻¹, —, degrees | 6 001 simulator calls, 67 s |
3 · Emulator
Learn the simulator from its own output: fit a fast stand-in to pairs made with step 1. Afterwards one call takes 0.35 ms.
| Role | Symbol | Name | Shape | Unit | Note |
|---|---|---|---|---|---|
| Input | pairs | training pairs: parameters and simulated maps | (pair, 3), (pair, row, col) | kg s⁻¹, —, degrees; g m⁻² | from step 1 |
| Output | emulator weights | 0.35 ms per call afterwards |
4 · Emulator-based inference
Rerun step 2 with the stand-in in place of the simulator. The same posterior now takes 3.2 s instead of 67 s.
| Role | Symbol | Name | Shape | Unit | Note |
|---|---|---|---|---|---|
| Input | observed column map | (row, col) | g m⁻² | one scene | |
| Parameter | emulator weights | frozen | |||
| Output | samples of | posterior samples | (sample, 3) | kg s⁻¹, —, degrees | 6 001 emulator calls, 3.2 s |
5 · Amortized inference
Skip the inversion altogether: train a network once on simulated pairs, so that it maps observations straight to a posterior. Each new scene then takes 0.46 ms.
| Role | Symbol | Name | Shape | Unit | Note |
|---|---|---|---|---|---|
| Input | pairs | training pairs: parameters and noisy maps | (pair, 3), (pair, row, col) | kg s⁻¹, —, degrees; g m⁻² | from step 1, with noise added |
| Parameter | network weights | trained once | |||
| Output | mean and spread of | posterior mean and spread | (3,), (3,) | kg s⁻¹, —, degrees | 0.46 ms per scene |
Step 1 · Simple model¶
The generative story: parameters go through the physics and the instrument , and noise is added. It serves twice: as the thing step 2 inverts, and as a source of as many labelled examples as you care to simulate. Here, 4 000 pairs took 45 s.
Step 2 · Model-based inference: the oracle¶
The classical method, already run above as the inner loop: 6 001 simulator calls, 67 s. It is called the oracle because it is the most trusted reference available, and not because it is exact. Everything faster is judged against it.
Step 3 · Emulator¶
A cheap function trained to imitate the simulator. This one compresses the simulated maps to 40 numbers and learns how those numbers depend on the parameters. Its referee is step 1: on 300 simulations it never saw, how far is it from the simulator, in units of the observation noise?
class Emulator:
"""f̂(θ; θ_emu): θ → principal components of the field → field."""
def __init__(self, components=40, seed=0):
self.scale_in = sklearn.preprocessing.StandardScaler()
self.basis = sklearn.decomposition.PCA(components, random_state=seed)
self.scale_out = sklearn.preprocessing.StandardScaler()
self.network = sklearn.neural_network.MLPRegressor(
hidden_layer_sizes=(128, 128), max_iter=3000, tol=1e-6, random_state=seed
)
def fit(self, thetas, fields):
# the field is linear in Q, so emulate the field per unit rate
unit = fields.reshape(len(fields), -1) / thetas[:, :1]
codes = self.scale_out.fit_transform(self.basis.fit_transform(unit))
self.network.fit(self.scale_in.fit_transform(thetas[:, 1:]), codes)
return self
def __call__(self, theta):
code = self.network.predict(self.scale_in.transform(np.atleast_2d(theta)[:, 1:]))
unit = self.basis.inverse_transform(self.scale_out.inverse_transform(code))
return (theta[0] * unit).reshape(SIDE, SIDE)| Training pairs | Error against the simulator | Time to fit |
|---|---|---|
| 250 | 0.23 × the noise | 2 s |
| 1 000 | 0.12 × the noise | 7 s |
| 4 000 | 0.07 × the noise | 25 s |
This table is step 6 at work on step 3: measure against the ground truth, change something (here, the amount of training data), measure again. At 0.07 × the noise the emulator’s error is small beside the noise in the scene, and each call costs 0.35 ms where the simulator costs 11 ms.
Step 4 · Emulator-based inference¶
Step 2 again, with the emulator in place of the simulator. Nothing else changes, which is what makes the comparison clean: any difference from step 2 is the emulator’s doing.
· emission rate
step 2 · simulator
step 4 · emulator
step 5 · amortized
truth 2.00
· spread coefficient—
step 2 · simulator
step 4 · emulator
step 5 · amortized
truth 0.300
· wind directiondegrees
step 2 · simulator
step 4 · emulator
step 5 · amortized
truth 12.00
The same scene, three ways to infer from it. Bars are 90 % intervals. Step 4 lands on step 2; step 5 is close and says, with its wider bars, that it is less sure.
| Step 4 against step 2 | Emission rate | Spread coefficient | Wind direction |
|---|---|---|---|
| Shift of the mean, in step-2 widths | 0.34 | 0.91 | 0.15 |
| Ratio of the widths | 1.01 | 1.24 | 1.02 |
The means agree to within one posterior width and the widths to within 20 %, for 3.2 s where step 2 took 67 s.
Step 5 · Amortized inference¶
The last step removes the sampler. A network is trained on simulated scenes to output the answer directly: a mean and a spread for each parameter. All the cost is paid in training; a new scene takes one forward pass.
class Amortized:
"""q(θ | y; ν): scene → a Gaussian over θ, in one forward pass."""
def __init__(self, hidden=(128, 128), seed=0):
self.basis = sklearn.decomposition.PCA(60, random_state=seed)
self.scale = sklearn.preprocessing.StandardScaler()
self.scale_theta = sklearn.preprocessing.StandardScaler()
options = dict(max_iter=600, tol=1e-6, early_stopping=True, random_state=seed)
self.mean = sklearn.neural_network.MLPRegressor(hidden_layer_sizes=hidden, **options)
self.spread = sklearn.neural_network.MLPRegressor(hidden_layer_sizes=(64, 64), **options)
def features(self, scenes):
return self.basis.transform(scenes.reshape(len(scenes), -1))
def fit(self, thetas, scenes):
half = len(thetas) // 2
self.basis.fit(scenes.reshape(len(scenes), -1))
features = self.scale.fit_transform(self.features(scenes))
targets = self.scale_theta.fit_transform(thetas)
# ν for the mean, on the first half
self.mean.fit(features[:half], targets[:half])
# ν for the spread, on the second half's squared errors: log e² ≈ log σ² − 1.27
error = targets[half:] - self.mean.predict(features[half:])
self.spread.fit(features[half:], np.log(error**2 + 1e-9) + 1.27)
return self
def __call__(self, scene):
features = self.scale.transform(self.features(scene[None]))
mean = self.scale_theta.inverse_transform(self.mean.predict(features))[0]
std = np.sqrt(np.exp(self.spread.predict(features)[0])) * self.scale_theta.scale_
return mean, std| Amortized map | Training scenes | Mean off by (step-4 widths): Q, a, φ | Its width ÷ step 4’s: Q, a, φ | 90 % intervals contain the truth | Time to fit |
|---|---|---|---|---|---|
| First try | 16 000 | 2.0, 3.1, 9.1 | 5.8, 7.0, 14.1 | 96%, 92%, 93% | 7 s |
| After the improve step | 48 000 | 1.6, 1.6, 3.4 | 2.6, 2.6, 4.6 | 93%, 94%, 88% | 50 s |
Step 5’s referee is step 4, on twenty fresh scenes. The first map is blunt: its best guess sits 2.0 to 9.1 posterior widths from where the sampler puts it, depending on the parameter. It is honest about that, though: its own error bars are several times wider, and they contain the truth as often as they claim. A larger network on three times the data closes most of the gap. It is still less sharp than the sampler, at 0.46 ms a scene.
Cost of one query (one scene in, one posterior out), log scale
step 2 · simulator in the loop
step 4 · emulator in the loop
step 5 · one forward pass
Paid once, up front: of simulations, to fit the emulator, to fit the amortized map.
Moving right along the six steps, each query gets cheaper by orders of magnitude, because work is moved to a one-off training stage. Here step 4 pays for itself by the second scene.
Step 6 · Improve¶
| To improve | Score it against | On this page |
|---|---|---|
| Step 2, the inference | step 1: simulate with known parameters, check they are recovered | the truth lies inside the posterior of model 2: Q 2.00 ± 0.03 for a true 2.00 |
| Step 3, the emulator | step 1: the simulator it replaces | error 0.23 → 0.07 × the noise as training grew |
| Step 4, emulator-based inference | step 2: the oracle’s posterior | means within 0.9 widths, widths within 24 % |
| Step 5, the amortized map | step 4, and the truth on simulated scenes | up to 9.1 widths off → at most 3.4; error bars checked |
| The model itself | observations, through compare | the outer loop: model 1 → model 2 |
Step 6 is shared by all the others, and its last row is the outer loop of the modeling cycle. That is where the two cycles join.
How the two cycles fit together¶
How the two cycles nest
The modelconceptual model, equations, code
update , run again
Step 2: estimate the inner loop of the modeling cycle
systematic misfit: change the model
Comparerandom or systematic?
step 6, when it changes the structure
random
Steps 3 to 5emulator, emulator-based, amortized
A change of model sends everything trained on the old one (steps 3 to 5) back to be retrained.
The six-step cycle sits inside the modeling cycle. Step 2 is the inner loop; the outer loop is step 6 when it changes the model. The fast steps inherit whatever the model gets wrong, so they are built only after compare says “random”.
Three worked examples¶
The toy above is plain NumPy. The three pages that follow do the same on the stack’s own libraries, at three levels of one problem.
One facility, three questions, each answer the next one’s input
Radiance cubewhat the sensor recorded
radiance per pixel and band
Example 1 · Retrievalradtrax · how much gas in each pixel?
column map
Example 2 · Quantificationplumax · how much is coming out?
one emission rate per overpass
Example 3 · Persistencyplumax · how often, and how much in a year?
rate, wait time, annual total
The three examples are one chain. Each page runs the modeling cycle on its own link and hands its output, with its uncertainty, to the next.
| 1 · Retrieval | 2 · Quantification | 3 · Persistency | |
|---|---|---|---|
| Question | How much extra methane in each pixel? | How much is the facility emitting? | How often does it emit? |
| First model | Matched filter | Integrated mass enhancement | Detection fraction |
| What compare found | ×0.37 over dark ground, ×1.08 over bright, an offset off-plume | Nothing to compare at first; then a residual with reduced χ² 2.09 | 9 %, 20 % or 37 % by instrument and hour |
| Structural changes | Plume-free background, per-pixel sensitivity, saturation | A model that predicts the image, then its direction | A rate thinned by detection and coverage, then a daily cycle |
| After them | ×0.99 and ×0.98; mass ×1.00 | χ² 0.99; line density 0.500 for a true 0.50 kg m⁻¹ | χ² 4.0 → 0.3; 2 007 events a year for a true 2 216 |
| The referee | Nonlinear retrieval, 75 s a scene | NUTS on the same posterior, 12 s | Counts in groups of overpasses the fit did not single out |
| Six steps used | 1, 2, 3, 4 and 6 | 1, 2 and 6; the model is cheap, so 3 and 4 are skipped | 1 and 2; the careful fit is already fast |
| What no model could supply | Real spectroscopy | The wind speed | The hours nobody looks |
Where each piece lives¶
The same structure exists outside the stack: variational and ensemble data assimilation are step 2 in weather and ocean centres; learned weather models and learned radiative-transfer codes are step 3; simulation-based inference, in particular neural posterior estimation, is step 5. In the stack, from the overview:
| Step | Lives in |
|---|---|
| 1 · Simple model | the GeoModels layer: somax, plumax, radtrax |
| 2 · Model-based inference | pipekit’s cycle with classical analysis steps (filterax, vardax, pyrox) |
| 3 · Emulator | pipekit-train’s simulation dataset; the model registry of pipekit-experiment |
| 4 · Emulator-based inference | pipekit’s cycle with a neural forward model |
| 5 · Amortized inference | pipekit-train with gauss_flows or pyrox |
| 6 · Improve | pipekit-evaluate benchmarks, rerun and compared row by row, with lineage in pipekit-experiment |
| Compare | pipekit-evaluate; xrtoolz for verification of fields |
Where this goes next¶
| Idea here | Shows up as |
|---|---|
| The two loops and the six steps | axes 1 and 3 of the overview, with the equations in full |
| One model, one transition | processing levels: every transition between levels can go through its own six steps |
| A model, an algorithm, a step, a recipe | the role ladder: where the simulator, the sampler and the cycle sit in a library |
| Rerunning the referees | versions and identity and recipe registries: which model, which weights, which data made a score |
Sources and status
Sources: the modeling cycle and the six-step cycle are those of the GeoStack overview (axes 1 and 3), whose figures this page redraws and whose equations it uses. The example is notebooks/background/modeling_cycle.py (314 lines of NumPy, SciPy and scikit-learn), run as shown on a synthetic scene, with its recorded output in docs/images/background_modeling_cycle/; every random draw is seeded, and two runs on one machine gave the same numbers apart from the timings; no GeoStack package is used. The sampler is a plain random-walk Metropolis; the emulator and the amortized map are small multilayer networks on principal components, and the amortized map assumes a Gaussian posterior per parameter. Timings are from one 2-core machine. The examples from outside the stack are named from what I know and were not re-checked online.