In Examples 1 to 4 the state was small, a few values per station, so the Kalman filter carried its full covariance and integrated the path out. Here the state is a gridded field: the anomaly of a tracer in every cell of a channel, moved along by a transport model. On a real grid of thousands of cells the covariance of a Kalman filter cannot be stored, let alone propagated. An ensemble Kalman filter carries copies of the state instead and runs the transport model on each. Its innovations give an estimate of the log likelihood, which we add to a NumPyro model as a factor. In Example 5a we infer the advection speed and the diffusivity of the channel from that factor with NUTS. We keep the channel small and the dynamics linear on purpose, so that the exact Kalman log likelihood still exists and we can measure what the ensemble costs us in bias. In Example 5b we run a different kind of ensemble on the same model, the ensemble of variational fits of pyrox.inference.ensemble_vi. Its members mean something else.
pyrox-ssm capability shown: pyrox_ssm.ensemble.ensemble_factor (behind the [ensemble] extra), which runs filterax.differentiable_assimilate with a deterministic square-root filter (filterax.filters.ETKF here) from an initial ensemble passed in as data. It adds the sum of the per-step log likelihoods as a NumPyro factor and returns the filterax AssimilationResult, whose analysis ensembles give us the filtered field. For 5b, pyrox.inference.ensemble_vi from the core package. Cost: every log-density evaluation is one assimilation run. Per step that is runs of the transport model plus an analysis in the space of the members, , against for the Kalman filter. The gradient adds a backward pass that recomputes the forecasts (filterax’s RecursiveCheckpointAdjoint, the default). We time one gradient at three ensemble sizes and for the Kalman filter in section 6.
What you’ll learn:
How to write a transport model as a filterax dynamics module and infer its parameters with
ensemble_factorin a plain NumPyro model, with the initial ensemble drawn once outside the model.How the NUTS posterior compares with the truth, and how to get the filtered field with bands from the analysis members.
How large the bias of the ensemble log likelihood is at 16, 32 and 128 members, against the exact Kalman filter, and what each costs per gradient.
What
ensemble_viputs in its ensemble (fits from different starts), and when that helps.
The NUTS workflow and the posterior predictive over draws are explained in Example 1, and the Kalman recursions in Kalman filtering and RTS smoothing. We reuse them here without deriving them again.
Background¶
The physical symbols of this page are below. Everything else follows the notation of the earlier examples, with the state , the observations and the parameters .
| Symbol | Meaning | Shape, units |
|---|---|---|
| tracer anomaly (concentration minus its background) | , tracer units | |
| position along the channel | , km | |
| advection speed | , km h⁻¹ | |
| eddy diffusivity | , km² h⁻¹ | |
| wavenumber | , rad km⁻¹ |
The tracer anomaly lives on a periodic channel of length km. It is carried along at the speed and spread by the diffusivity ,
We split the channel into cells of 1 km, so the state is the field in every cell at the time hours, , with and . On a periodic grid each Fourier mode evolves on its own, so we can step the equation exactly. With the discrete Fourier transform of the field at the wavenumber (the wavenumbers that the grid resolves) and the imaginary unit,
This is the dynamics , with the parameters . It has no model noise. It is also linear, with , which a real transport model would not be. We keep it linear so that the exact Kalman log likelihood is there as a reference. The initial field is a draw from a stationary Gaussian, and sensors, one every 8 km, measure the field with noise every hour,
where has unit variance and a Gaussian spectrum with a 4 km lengthscale, picks the sensor cells, so the observation operator is , and with .
The ensemble Kalman log likelihood. The ETKF (ensemble transform Kalman filter) carries members , , in place of a mean and a covariance. It starts from the initial ensemble , whose rows we draw once. At every step it runs the transport model on each member, , and scores under the Gaussian that the forecast members imply,
where column of is the anomaly . Then a square-root analysis moves the members to without drawing random numbers. The Kalman filter computes the same sum exactly, with and in place of and , where and are the forecast mean and covariance.
Two properties decide how we can use this in NUTS or SVI. First, is data and the filter draws no random numbers. So the log likelihood is a deterministic and smooth function of , as every evaluation sees the same members (common random numbers). Second, it is biased, not exact. The mean and covariance of the members are Monte Carlo estimates from draws, and the covariance has rank at most . The bias shrinks as grows. For linear-Gaussian dynamics like ours the log likelihood converges to the Kalman log marginal of lgssm_factor, and that is the check we run in section 6.
Setup¶
We detect Colab and install pyrox, pyrox-gp[colab] (which pulls in matplotlib and watermark) and pyrox-ssm[ensemble] (which pulls in filterax) only when the notebook runs there.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
"pyrox @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox",
"pyrox-gp[colab] @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox-gp",
"pyrox-ssm[ensemble] @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox-ssm",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import time
import einx
import filterax as flx
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import numpyro
import numpyro.distributions as dist
from jaxtyping import Array, Float
from numpyro import handlers
from numpyro.infer import MCMC, NUTS, init_to_median
from numpyro.infer.autoguide import AutoNormal
from pyrox.inference import EnsembleVI, ensemble_vi
from pyrox_ssm import LinearGaussianSSMPrior, lgssm_factor
from pyrox_ssm.ensemble import ensemble_factor
jax.config.update("jax_enable_x64", True)import importlib.util
try:
from IPython import get_ipython
ipython = get_ipython()
except ImportError:
ipython = None
if ipython is not None and importlib.util.find_spec("watermark") is not None:
ipython.run_line_magic("load_ext", "watermark")
ipython.run_line_magic(
"watermark",
"-v -m -p jax,equinox,numpyro,filterax,gaussx,pyrox,pyrox_ssm,matplotlib",
)
else:
print("watermark extension not installed; skipping reproducibility readout.")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.13.0
jax : 0.10.2
equinox : 0.13.8
numpyro : 0.21.0
filterax : 0.0.8
gaussx : 0.6.15
pyrox : 0.2.1
pyrox_ssm : 0.1.0
matplotlib: 3.10.9
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
1. A tracer moved along a periodic channel¶
We simulate one record from the model, so that we know the truth: an advection speed km h⁻¹ and a diffusivity km² h⁻¹. Over the 16 hours the field moves 32 km, so every feature passes four sensors. The AdvectionDiffusion module below is the exact Fourier step of the Background section, written as a filterax.AbstractDynamics whose fields are , and observe is . We draw by colouring white noise with the square root of the spectrum, through the FFT.
# Shapes: D_x = N_Ωx = 64 cells; D_y = N_Ωy = 8 sensors; T = 16 hourly steps
N_CELLS = 64
N_SENSORS = 8
N_STEPS = 16
# Δs = 1 km, so the channel is L = 64 km long
cell_km = jnp.arange(N_CELLS, dtype=jnp.float64) # → (D_x,)
# κ ∈ 𝒲_s,x, the wavenumbers the grid resolves [rad km⁻¹]
wavenumber = 2.0 * jnp.pi * jnp.fft.rfftfreq(N_CELLS, d=1.0) # → (D_x / 2 + 1,)
# every eighth cell, from cell 3
sensor_cells = jnp.arange(3, N_CELLS, N_CELLS // N_SENSORS) # → (D_y,)
# t_k = k hours, k = 1, …, T
obs_times = jnp.arange(1.0, N_STEPS + 1.0) # → (T,)
# today (filterax): the base class of a deterministic dynamics module
class AdvectionDiffusion(flx.AbstractDynamics):
"""f(x; θ): the exact step of ∂x/∂t = −u ∂x/∂s + K ∂²x/∂s² on the periodic grid."""
speed: Float[Array, ""]
diffusivity: Float[Array, ""]
def __call__(self, state, t_prev, t_next):
dt = t_next - t_prev
# x̂(κ, t) for every resolved wavenumber
modes = jnp.fft.rfft(state) # (D_x,) → (D_x / 2 + 1,)
# exp((−i u κ − K κ²) Δt)
growth = jnp.exp(
(-1j * self.speed * wavenumber - self.diffusivity * wavenumber**2) * dt
) # → (D_x / 2 + 1,)
# x(s, t + Δt) = 𝔉⁻¹[exp((−i u κ − K κ²) Δt) x̂(κ, t)]
return jnp.fft.irfft(growth * modes, n=N_CELLS) # → (D_x,)
def observe(state):
"""h(x) = H x: the tracer at the sensor cells."""
return state[sensor_cells] # (D_x,) → (D_y,)
# the spectrum of Σ_x,0: Gaussian in κ, lengthscale ℓ = 4 km, variance σ_x² = 1
LENGTHSCALE = 4.0
all_wavenumbers = 2.0 * jnp.pi * jnp.fft.fftfreq(N_CELLS, d=1.0) # → (D_x,)
spectrum = jnp.exp(-(all_wavenumbers**2) * LENGTHSCALE**2 / 2.0) # → (D_x,)
spectrum = N_CELLS * spectrum / jnp.sum(spectrum) # → (D_x,)
def colour(white):
"""x₀ = Σ_x,0^(1/2) z, with z ~ 𝒩(0, I), through the FFT of the periodic grid."""
modes = jnp.sqrt(spectrum) * jnp.fft.fft(white) # (D_x,) → (D_x,)
return jnp.real(jnp.fft.ifft(modes)) # → (D_x,)
truth = {"speed": 2.0, "diffusivity": 0.3} # u [km h⁻¹], K [km² h⁻¹]
NOISE_STD = 0.1 # σ_ε, tracer units
key_x0, key_eps, key_ens = jr.split(jr.PRNGKey(5), 3)
# x₀ ~ 𝒩(0, Σ_x,0)
x0_true = colour(jr.normal(key_x0, (N_CELLS,))) # → (D_x,)
dynamics_true = AdvectionDiffusion(
jnp.asarray(truth["speed"]), jnp.asarray(truth["diffusivity"])
)
states, state, t_prev = [], x0_true, 0.0
for t_next in obs_times:
# x_k = f(x_k−1; θ)
state = dynamics_true(state, t_prev, t_next) # → (D_x,)
states.append(state)
t_prev = t_next
x_true = jnp.stack(states) # → (T, D_x)
# H x_k for every k
y_clean = jax.vmap(observe)(x_true) # (T, D_x) → (T, D_y)
# y_k = H x_k + ε_k, ε_k ~ 𝒩(0, σ_ε² I)
y = y_clean + NOISE_STD * jr.normal(key_eps, y_clean.shape) # → (T, D_y)
# Σ_ε = σ_ε² I_D_y
obs_noise = NOISE_STD**2 * jnp.eye(N_SENSORS) # → (D_y, D_y)
print(
f"D_x = {N_CELLS} cells, D_y = {N_SENSORS} sensors, T = {N_STEPS} hours, "
f"{y.size} observations"
)
print(f"the tracer moves {truth['speed'] * N_STEPS:.0f} km over the record")D_x = 64 cells, D_y = 8 sensors, T = 16 hours, 128 observations
the tracer moves 32 km over the record
x_plot = np.concatenate([np.asarray(x0_true)[None], np.asarray(x_true)])
extent = (-0.5, N_CELLS - 0.5, N_STEPS + 0.5, -0.5)
fig, axes = plt.subplots(1, 2, figsize=(13, 4.5), width_ratios=(1.2, 1))
ax = axes[0]
im = ax.imshow(x_plot, aspect="auto", cmap="RdBu_r", vmin=-2.5, vmax=2.5, extent=extent)
for n in np.asarray(sensor_cells):
ax.axvline(n, color="k", lw=0.6, ls=":")
ax.set_xlabel("cell $s$ [km]")
ax.set_ylabel("time $t$ [h]")
ax.set_title("True tracer field $x(s, t)$, sensors dotted")
fig.colorbar(im, ax=ax, label="tracer anomaly")
ax = axes[1]
for j, n in enumerate(np.asarray(sensor_cells)[:4]):
ax.plot(obs_times, x_true[:, n], color=f"C{j}", lw=1)
ax.scatter(obs_times, y[:, j], color=f"C{j}", s=10, label=f"sensor at {n} km")
ax.set_xlabel("time $t$ [h]")
ax.set_ylabel("tracer anomaly")
ax.set_title("Four of the eight sensors: truth (line) and $y_k$ (dots)")
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()
The left panel shows the true field as a space-time (Hovmöller) diagram, with the sensor cells dotted. The bands of positive and negative anomaly slope to the right at the advection speed. The right panel shows four of the eight sensor records, where a feature seen at one sensor turns up at the next one about 4 hours later (8 km at 2 km h⁻¹).
2. The model as a plain NumPyro function¶
We draw the initial ensemble of members here, once, outside the model, and pass it in as data. Drawing it inside the model would give every evaluation of the log density new random numbers, so NUTS would see a noisy log density. A wind measurement puts the advection speed near 1.5 km h⁻¹, give or take 1 km h⁻¹, so we take , and the diffusivity gets . Then ensemble_factor takes the filter, the dynamics built from the two sample sites, , , the record, the observation times and , and registers the factor "y".
# Shapes: N_Ex = 32 members; D_x = 64 cells; D_y = 8 sensors; T = 16 steps
N_MEMBERS = 32
# x₀⁽ᵉ⁾ ~ 𝒩(0, Σ_x,0), e ∈ ℰ_x, drawn once and passed in as data
init_ensemble = jax.vmap(colour)( # (N_Ex, D_x) → (N_Ex, D_x)
jr.normal(key_ens, (N_MEMBERS, N_CELLS))
)
def tracer_model(init_ensemble, y):
# Shapes: D_θ = 2 parameters; N_Ex members; T steps; D_y sensors
# today (numpyro): the two sample sites of θ
# u ~ 𝒩(1.5, 1²)
speed = numpyro.sample("speed", dist.Normal(1.5, 1.0))
# K ~ LogNormal(log 0.5, 1)
diffusivity = numpyro.sample("diffusivity", dist.LogNormal(jnp.log(0.5), 1.0))
# user
dynamics = AdvectionDiffusion(speed, diffusivity)
# today (pyrox_ssm), calling filterax
# log p(y_1:T ∣ θ) ≈ ∑ₖ log 𝒩(r̄ₖ; 0, H̃ₖ H̃ₖᵀ + Σ_ε)
return ensemble_factor(
"y",
# today (filterax)
flx.filters.ETKF(),
dynamics,
observe,
init_ensemble,
y,
obs_times,
obs_noise,
)
# today (numpyro)
seeded_model = handlers.seed(tracer_model, rng_seed=0)
# today (numpyro)
trace = handlers.trace(seeded_model).get_trace(init_ensemble, y)
for name, site in trace.items():
kind = "factor" if isinstance(site["fn"], dist.Unit) else type(site["fn"]).__name__
print(f"site {name!r:14} {kind:<10} value shape={tuple(jnp.shape(site['value']))}")site 'speed' Normal value shape=()
site 'diffusivity' LogNormal value shape=()
site 'y' factor value shape=(0,)
So the trace holds two scalar sample sites and one factor, as in Example 1. However, here the factor is an estimate: the 64-cell field is carried by the 32 members inside the filter, and NUTS never sees it.
3. NUTS¶
We run two chains of 200 draws after 100 warm-up steps with a dense mass matrix. Both chains start at the prior medians (init_to_median). The log likelihood in has a second local mode near km h⁻¹, and section 7 shows fits from random starts (NumPyro’s default) ending there. Each leapfrog step is one assimilation run and its gradient. The wall-clock time includes JIT compilation.
# Shapes: D_θ = 2 parameters; 2 chains × 200 = 400 posterior draws
# today (numpyro)
nuts_kernel = NUTS(tracer_model, dense_mass=True, init_strategy=init_to_median)
# today (numpyro)
nuts = MCMC(
nuts_kernel,
num_warmup=100,
num_samples=200,
num_chains=2,
chain_method="sequential",
progress_bar=False,
)
t0 = time.perf_counter()
# today (numpyro)
# 400 draws θ ~ p(θ ∣ y_1:T), each leapfrog step one assimilation run and its gradient
nuts.run(jr.PRNGKey(1), init_ensemble, y, extra_fields=("num_steps",))
jax.block_until_ready(nuts.get_samples())
nuts_seconds = time.perf_counter() - t0
nuts.print_summary()
nuts_samples = nuts.get_samples() # → {name: (400,)}
extra_fields = nuts.get_extra_fields()
n_div = int(extra_fields["diverging"].sum()) # → ()
n_grad = int(extra_fields["num_steps"].sum()) # → ()
print(
f"NUTS wall-clock: {nuts_seconds:.1f} s for 2 chains x 300 iterations, "
f"{n_div} divergences"
)
print(f"leapfrog steps after warm-up: {n_grad}, {n_grad / 400:.1f} per draw")
mean std median 5.0% 95.0% n_eff r_hat
diffusivity 0.31 0.06 0.30 0.21 0.40 346.39 1.00
speed 1.97 0.02 1.97 1.94 1.99 304.32 1.00
Number of divergences: 0
NUTS wall-clock: 52.5 s for 2 chains x 300 iterations, 0 divergences
leapfrog steps after warm-up: 1428, 3.6 per draw
4. The transport parameters against the truth¶
print(f"{'parameter':<12}{'truth':>8} {'mean ± sd':>16} {'90% interval':>20}")
for k in truth:
v = np.asarray(nuts_samples[k])
lo, hi = np.percentile(v, [5, 95])
inside = "in" if lo <= truth[k] <= hi else "out"
print(
f"{k:<12}{truth[k]:>8.2f} {v.mean():>7.3f} ± {v.std():<6.3f} "
f"[{lo:>6.3f}, {hi:>6.3f}] {inside:>3}"
)
fig, ax = plt.subplots(figsize=(5.5, 4.5))
ax.scatter(
nuts_samples["speed"], nuts_samples["diffusivity"], s=4, alpha=0.4, label="NUTS"
)
ax.scatter(
truth["speed"], truth["diffusivity"], marker="*", s=200, c="k", label="truth"
)
ax.set_xlabel("advection speed $u$ [km/h]")
ax.set_ylabel("diffusivity $K$ [km²/h]")
ax.set_title(f"Posterior of $\\theta = (u, K)$, $N_{{\\mathcal{{E}}_x}} = {N_MEMBERS}$")
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()parameter truth mean ± sd 90% interval
speed 2.00 1.966 ± 0.018 [ 1.937, 1.996] out
diffusivity 0.30 0.306 ± 0.061 [ 0.216, 0.414] in

Both chains agree (), with no divergences and 3.6 leapfrog steps per draw. The diffusivity’s 90 % interval, [0.216, 0.414] km² h⁻¹, contains the true 0.3. The speed is pinned down far more tightly, at 1.966 ± 0.018 km h⁻¹, and its 90 % interval [1.937, 1.996] stops just short of the true 2.0. Section 6 shows that this miss is not the ensemble’s doing: the exact Kalman posterior puts the speed at 1.970 ± 0.018 km h⁻¹ as well, so it belongs to this realisation of the record.
5. The filtered field¶
The AssimilationResult that ensemble_factor returns holds the analysis members at every step (analysis_history, shaped ). So for one the filtered field is their mean , and its uncertainty is their variance (with , as in the filter). We run the filter at NUTS draws, the set , with jax.vmap, and combine them as in Example 1, so the bands carry the uncertainty of too,
and the variance in each cell is the mean of the member variances over plus the variance of over . These are filtered estimates, so step uses the observations up to only (the draws of come from the whole record). We score them against the true field, at the sensor cells and in the cells between them.
# Shapes: N_Eθ = 50 posterior draws; N_Ex = 32 members; T = 16 steps; D_x = 64 cells
N_DRAWS = 50
# N_Eθ draws θ, evenly spaced through the chains
draw_idx = jnp.linspace(0, 399, N_DRAWS).astype(int) # → (N_Eθ,)
theta_draws = {k: v[draw_idx] for k, v in nuts_samples.items()}
def analysis_moments(theta):
# today (pyrox_ssm), outside a model, for the returned filterax result
result = ensemble_factor(
"y",
# today (filterax)
flx.filters.ETKF(),
AdvectionDiffusion(theta["speed"], theta["diffusivity"]),
observe,
init_ensemble,
y,
obs_times,
obs_noise,
)
members = result.analysis_history # → (T, N_Ex, D_x)
# x̄_k∣k(θ) = (1/N_Ex) ∑ₑ x_k∣k⁽ᵉ⁾
mean = einx.mean("time member cell -> time cell", members) # → (T, D_x)
# (1/N_Ex) ∑ₑ (x_k∣k⁽ᵉ⁾ − x̄_k∣k(θ))²
spread = einx.var("time member cell -> time cell", members) # → (T, D_x)
# the member variance with 1/(N_Ex − 1), as the filter's covariance has
var = spread * N_MEMBERS / (N_MEMBERS - 1) # → (T, D_x)
return mean, var
t0 = time.perf_counter()
# today (jax)
moments_draws = jax.jit(jax.vmap(analysis_moments))
# x̄_k∣k(θ) and the member variance, for every θ ∈ ℰ_θ
means, member_vars = moments_draws(theta_draws) # → 2 × (N_Eθ, T, D_x)
jax.block_until_ready(means)
filter_seconds = time.perf_counter() - t0
# 𝔼[x_k ∣ y_1:k] ≈ (1/N_Eθ) ∑_θ x̄_k∣k(θ)
field_mean = einx.mean("draw time cell -> time cell", means) # → (T, D_x)
# (1/N_Eθ) ∑_θ of the member variance
within = einx.mean("draw time cell -> time cell", member_vars) # → (T, D_x)
# the spread of x̄_k∣k(θ) over θ ∈ ℰ_θ
between = einx.var("draw time cell -> time cell", means) # → (T, D_x)
# 𝕍[x_k ∣ y_1:k] ≈ within + between
field_sd = jnp.sqrt(within + between) # → (T, D_x)
# z = (x_k − 𝔼[x_k ∣ y_1:k]) / √𝕍[x_k ∣ y_1:k]
z = (x_true - field_mean) / field_sd # → (T, D_x)
observed = jnp.zeros(N_CELLS, dtype=bool).at[sensor_cells].set(True) # → (D_x,)
print(f"{N_DRAWS} assimilation runs: {filter_seconds:.1f} s (with JIT)")
for label, sel in (("sensor cells", observed), ("cells between", ~observed)):
cover = float(jnp.mean(jnp.abs(z[:, sel]) < 2.0)) # → ()
rmse = float(jnp.sqrt(jnp.mean((x_true - field_mean)[:, sel] ** 2))) # → ()
sd = float(jnp.mean(field_sd[:, sel])) # → ()
print(
f"{label:<14} RMSE = {rmse:.3f}, mean sd = {sd:.3f}, "
f"coverage of ±2σ = {100 * cover:5.1f} %"
)50 assimilation runs: 1.8 s (with JIT)
sensor cells RMSE = 0.047, mean sd = 0.050, coverage of ±2σ = 100.0 %
cells between RMSE = 0.114, mean sd = 0.071, coverage of ±2σ = 98.8 %
fig, axes = plt.subplots(2, 3, figsize=(15, 8), height_ratios=(1.3, 1))
extent_k = (-0.5, N_CELLS - 0.5, N_STEPS + 0.5, 0.5)
panels = (
(x_true, "true $x(s, t_k)$", "RdBu_r", (-2.5, 2.5)),
(
field_mean,
r"filtered mean $\mathbb{E}[x_k \mid y_{1:k}]$",
"RdBu_r",
(-2.5, 2.5),
),
(
field_sd,
"filtered standard deviation (colours stop at 0.2)",
"viridis",
(0.0, 0.2),
),
)
for ax, (field, title, cmap, (lo, hi)) in zip(axes[0], panels):
im = ax.imshow(
np.asarray(field), aspect="auto", cmap=cmap, vmin=lo, vmax=hi, extent=extent_k
)
for n in np.asarray(sensor_cells):
ax.axvline(n, color="k", lw=0.5, ls=":")
ax.set_xlabel("cell $s$ [km]")
ax.set_title(title)
fig.colorbar(im, ax=ax)
axes[0, 0].set_ylabel("time $t$ [h]")
for ax, n in zip(axes[1], (int(sensor_cells[2]), int(sensor_cells[2]) + 4, 40)):
sd = field_sd[:, n]
ax.fill_between(
obs_times,
field_mean[:, n] - 2 * sd,
field_mean[:, n] + 2 * sd,
color="C0",
alpha=0.3,
label=r"$\pm 2\sigma$",
)
ax.plot(obs_times, field_mean[:, n], "C0", label="filtered mean")
ax.plot(obs_times, x_true[:, n], "k--", lw=1, label="truth")
if bool(observed[n]):
j = int(jnp.argmax(sensor_cells == n))
ax.scatter(obs_times, y[:, j], c="C1", s=12, zorder=5, label="$y_k$")
ax.set_title(f"cell {n} km (a sensor)")
else:
ax.set_title(f"cell {n} km (no sensor)")
ax.set_xlabel("time $t$ [h]")
axes[1, 0].set_ylabel("tracer anomaly")
axes[1, 0].legend(fontsize=8)
plt.tight_layout()
plt.show()
After the first two or three hours the filtered mean is hard to tell from the truth, also in the cells that no sensor sees. The filter updates the members where the sensors are, and the dynamics carry those corrections along the channel. The standard deviation is largest at the first step, when the members still carry the prior, and it averages 0.050 at the sensor cells and 0.071 between them. Between the sensors the RMSE (0.114) is above that average, and yet 98.8 % of the cell-hours there fall within (100 % at the sensors). The large errors sit in the first hours, where the band is wide too, as the bottom panels show for two cells without a sensor.
6. The bias in , and the cost¶
We now measure the bias of the ensemble log likelihood, and what it does to the posterior, at , 32 (the that NUTS used) and 128 members. The reference is the exact Kalman filter. The dynamics are linear, so we build by applying to the columns of , and give it to LinearGaussianSSMPrior with zero model noise and as the initial covariance. Then lgssm_factor gives the exact log likelihood. With two parameters we can also compute each posterior on a 25 × 15 grid of around the mode, with no sampling error: the weights are normalised over the grid. We also time one jitted evaluation and its gradient, the price of every NUTS leapfrog step and SVI step.
def ensemble_log_lik(theta, members):
"""log p(y_1:T ∣ θ) by the ETKF, from the initial ensemble ``members``."""
def model():
# today (pyrox_ssm), calling filterax
ensemble_factor(
"y",
# today (filterax)
flx.filters.ETKF(),
AdvectionDiffusion(theta[0], theta[1]),
observe,
members,
y,
obs_times,
obs_noise,
)
# today (numpyro)
site = handlers.trace(model).get_trace()["y"]
return site["fn"].log_factor
# Σ_x,0 = Σ_x,0^(1/2) (Σ_x,0^(1/2))ᵀ, materialised for the Kalman reference
colour_matrix = einx.id("col row -> row col", jax.vmap(colour)(jnp.eye(N_CELLS)))
init_cov = einx.dot("row mid, col mid -> row col", colour_matrix, colour_matrix)
# H, the 0/1 rows that pick the sensor cells
obs_matrix = jnp.eye(N_CELLS)[sensor_cells] # → (D_y, D_x)
def kalman_log_lik(theta):
"""The exact log p(y_1:T ∣ θ) by the Kalman filter, with no model noise."""
dynamics = AdvectionDiffusion(theta[0], theta[1])
# F(θ), column n is f(e_n; θ)
columns = jax.vmap(lambda e: dynamics(e, 0.0, 1.0))(jnp.eye(N_CELLS))
transition = einx.id("col row -> row col", columns) # → (D_x, D_x)
# today (pyrox_ssm)
prior = LinearGaussianSSMPrior(
jnp.broadcast_to(transition, (N_STEPS, N_CELLS, N_CELLS)),
obs_matrix,
jnp.zeros((N_STEPS, N_CELLS, N_CELLS)),
obs_noise,
jnp.zeros(N_CELLS),
init_cov,
)
# today (pyrox_ssm)
# log p(y_1:T ∣ θ) = ∑ₖ log 𝒩(r_k; 0, H Σ_x,k∣k−1 Hᵀ + Σ_ε)
model = lambda: lgssm_factor("y", prior, y)
# today (numpyro)
site = handlers.trace(model).get_trace()["y"]
return site["fn"].log_factor
def time_grad(log_lik, repeats=3):
"""One jitted log likelihood and its gradient at the truth, in ms."""
# today (jax)
value_and_grad = jax.jit(jax.value_and_grad(log_lik))
theta = jnp.array([truth["speed"], truth["diffusivity"]]) # → (2,)
jax.block_until_ready(value_and_grad(theta))
t0 = time.perf_counter()
for _ in range(repeats):
jax.block_until_ready(value_and_grad(theta))
return 1e3 * (time.perf_counter() - t0) / repeats
# Shapes: N_grid = 25 × 15 = 375 values of θ; D_θ = 2 parameters
speed_axis = jnp.linspace(1.90, 2.04, 25) # → (25,)
diffusivity_axis = jnp.linspace(0.12, 0.56, 15) # → (15,)
speed_mesh, diffusivity_mesh = jnp.meshgrid(speed_axis, diffusivity_axis, indexing="ij")
# every grid value of θ = (u, K)
theta_grid = einx.id( # 2 × (25, 15) → (N_grid, 2)
"u k, u k -> (u k) (1 + 1)", speed_mesh, diffusivity_mesh
)
# log p(θ) = log 𝒩(u; 1.5, 1²) + log LogNormal(K; log 0.5, 1)
log_prior = dist.Normal(1.5, 1.0).log_prob(theta_grid[:, 0]) + dist.LogNormal(
jnp.log(0.5), 1.0
).log_prob(theta_grid[:, 1]) # → (N_grid,)
def grid_posterior(log_lik):
"""Posterior mean and sd of θ on the grid, from a log likelihood of θ."""
# today (jax): one θ at a time, so the memory stays that of one run
log_liks = jax.jit(lambda grid: jax.lax.map(log_lik, grid))(theta_grid)
# p(θ ∣ y_1:T) ∝ p(y_1:T ∣ θ) p(θ), normalised over the grid
weights = jax.nn.softmax(log_liks + log_prior) # → (N_grid,)
mean = einx.dot("grid, grid param -> param", weights, theta_grid) # → (2,)
deviation = theta_grid - mean # → (N_grid, 2)
var = einx.dot("grid, grid param -> param", weights, deviation**2) # → (2,)
return mean, jnp.sqrt(var)
theta_true = jnp.array([truth["speed"], truth["diffusivity"]]) # → (2,)
exact = float(kalman_log_lik(theta_true)) # → ()
key_16, key_128 = jr.split(jr.PRNGKey(11))
size_ensembles = {
16: jax.vmap(colour)(jr.normal(key_16, (16, N_CELLS))),
32: init_ensemble, # the X₀ that NUTS used
128: jax.vmap(colour)(jr.normal(key_128, (128, N_CELLS))),
}
t0 = time.perf_counter()
rows = {"Kalman": (exact, *grid_posterior(kalman_log_lik), time_grad(kalman_log_lik))}
for n_members, members in size_ensembles.items():
log_lik = lambda th, m=members: ensemble_log_lik(th, m)
rows[f"N_Ex = {n_members}"] = (
float(log_lik(theta_true)),
*grid_posterior(log_lik),
time_grad(log_lik),
)
grid_seconds = time.perf_counter() - t0
print(
f"{'':<12}{'log p(y | theta_true)':>22}{'u mean ± sd':>18}"
f"{'K mean ± sd':>18}{'grad, ms':>10}"
)
for label, (log_p, mean, sd, ms) in rows.items():
print(
f"{label:<12}{log_p:>22.2f}{float(mean[0]):>10.4f} ± {float(sd[0]):.4f}"
f"{float(mean[1]):>10.4f} ± {float(sd[1]):.4f}{ms:>10.1f}"
)
print(f"(4 grid posteriors and gradient timings: {grid_seconds:.1f} s)") log p(y | theta_true) u mean ± sd K mean ± sd grad, ms
Kalman 77.34 1.9696 ± 0.0182 0.3295 ± 0.0561 7.2
N_Ex = 16 67.74 1.9864 ± 0.0171 0.3306 ± 0.0543 6.6
N_Ex = 32 74.36 1.9670 ± 0.0182 0.3046 ± 0.0550 8.6
N_Ex = 128 77.62 1.9696 ± 0.0182 0.3313 ± 0.0560 18.8
(4 grid posteriors and gradient timings: 28.8 s)
At the true the ensemble log likelihood is 9.60 below the exact 77.34 with 16 members, 2.98 below with 32 and 0.28 above with 128. Each row uses one , so the size of the error is itself random, but it shrinks with . On the posterior the effect is smaller than these gaps suggest. What moves the posterior is how the error changes with , not its level. With 16 members the speed shifts by 0.017 km h⁻¹, about one posterior standard deviation. With 32 the speed is within 0.003 km h⁻¹ of the exact posterior mean and the diffusivity is 0.025 km² h⁻¹ low, under half a standard deviation. With 128 both are within 0.002 of the exact values. The grid posterior at 32 members also matches the NUTS one (1.967 against 1.966 km h⁻¹ for , 0.305 against 0.306 km² h⁻¹ for ). So NUTS sampled the ensemble posterior well, and the miss of the true speed in section 4 is in the data.
One gradient costs 6.6 ms with 16 members, 8.6 ms with 32 and 18.8 ms with 128, against 7.2 ms for the Kalman filter. At the Kalman filter is as cheap as a small ensemble, because is small. The ensemble pays off when the state is too large for a covariance: its cost grows with the number of members and model runs, not with , and it never stores .
7. Example 5b: an ensemble of variational fits with ensemble_vi¶
pyrox.inference.ensemble_vi uses the word ensemble for a different object. It runs independent SVI fits of one guide , each from its own random start, vmapped into one computation. It returns the stacked variational parameters , , and the loss history of every fit. So a member in 5a is a state inside one evaluation of the log likelihood, and the members together estimate the distribution of the state for one . A member in 5b is a whole approximate posterior . The spread over these members says where the optimiser can end up, not how uncertain is. That is useful when the loss has several local optima, as this one has in .
ensemble_vi takes any NumPyro model whose two arguments are the data, so we pass tracer_model unchanged, with data=(init_ensemble, y), and an AutoNormal guide. Its default starts each fit at a uniform point in on the unconstrained scale. Each of the fits minimises with Adam for 200 steps. Every step of every fit is one assimilation run with the same 32-member . ensemble_vi does not return where each fit started, so we rebuild the starts with EnsembleVI.init and the same seed.
# Shapes: N_Eν = 8 fits; D_θ = 2 parameters; 200 Adam steps per fit
N_FITS = 8
# today (numpyro)
# q(θ; ν) = 𝒩(u; μ_u, σ_u²) LogNormal(K; μ_K, σ_K²), started at a random point
guide = AutoNormal(tracer_model)
t0 = time.perf_counter()
# today (pyrox)
# ν⁽ᵉ⁾⋆ = argmin_ν ℒ_ELBO(ν), one fit per e ∈ ℰ_ν, vmapped
fit_params, fit_losses = ensemble_vi(
tracer_model,
guide,
ensemble_size=N_FITS,
num_epochs=200,
data=(init_ensemble, y),
seed=jr.PRNGKey(7),
learning_rate=0.05,
)
jax.block_until_ready(fit_losses)
vi_seconds = time.perf_counter() - t0
# the constrained guide medians of u and K, per fit
fit_medians = jax.vmap(guide.median)(fit_params) # → {name: (N_Eν,)}
# a second guide: the first holds tracers from inside ensemble_vi's vmap
# today (numpyro)
start_guide = AutoNormal(tracer_model)
optimizer = numpyro.optim.Adam(0.05)
# today (pyrox): the same seed gives the starts ensemble_vi used
start_states = EnsembleVI(
tracer_model, start_guide, optimizer, ensemble_size=N_FITS
).init(jr.PRNGKey(7), init_ensemble, y)
# today (numpyro)
# ν⁽ᵉ⁾ at step 0, unconstrained; u has real support, so its loc is its median
start_params = jax.vmap(optimizer.get_params)(start_states.optim_state)
start_speed = start_params["speed_auto_loc"] # → (N_Eν,)
# ℒ_ELBO at the end of each fit (mean of the last 50 steps)
final_loss = einx.mean("fit [step]", fit_losses[:, -50:]) # → (N_Eν,)
print(f"ensemble_vi wall-clock: {vi_seconds:.1f} s for {N_FITS} fits x 200 steps")
print(f"{'fit':>4}{'start u':>9}{'u':>8}{'K':>8}{'final -ELBO':>13}")
for e in range(N_FITS):
print(
f"{e:>4}{float(start_speed[e]):>9.2f}"
f"{float(fit_medians['speed'][e]):>8.3f}"
f"{float(fit_medians['diffusivity'][e]):>8.3f}{float(final_loss[e]):>13.1f}"
)ensemble_vi wall-clock: 26.4 s for 8 fits x 200 steps
fit start u u K final -ELBO
0 -1.30 2.000 0.298 -68.3
1 1.29 1.972 0.299 -69.2
2 -0.28 -0.630 0.042 435.8
3 0.28 -0.608 0.025 433.5
4 -1.29 -0.608 0.043 436.4
5 -1.89 -0.611 0.032 434.2
6 0.19 1.967 0.299 -69.4
7 -0.53 1.973 0.310 -69.3
speed_grid = jnp.linspace(-2.5, 4.0, 131) # → (131,)
# log p(y_1:T ∣ u, K_true), exact, one u at a time
profile = jax.jit(
lambda grid: jax.lax.map(
lambda u: kalman_log_lik(jnp.array([u, truth["diffusivity"]])), grid
)
)(speed_grid) # → (131,)
fig, axes = plt.subplots(1, 2, figsize=(13, 4.2))
ax = axes[0]
ax.plot(
speed_grid,
profile,
"k",
lw=1,
label=r"exact $\log p(y_{1:T} \mid u, K_\mathrm{true})$",
)
ax.scatter(
fit_medians["speed"],
-final_loss,
c=[f"C{e}" for e in range(N_FITS)],
s=40,
zorder=5,
label="ensemble_vi fits: median $u$, ELBO",
)
for e in range(N_FITS):
ax.axvline(float(start_speed[e]), color=f"C{e}", lw=0.8, ls=":")
ax.axvline(truth["speed"], color="grey", ls="--", lw=1)
ax.set_xlabel("advection speed $u$ [km/h] (dotted: where each fit started)")
ax.set_ylabel("log likelihood, ELBO")
ax.set_title("The likelihood in $u$ and where each fit ended")
ax.legend(fontsize=8)
ax = axes[1]
for e in range(N_FITS):
ax.plot(np.asarray(fit_losses[e]), color=f"C{e}", lw=0.8)
ax.set_ylim(-150.0, 1100.0)
ax.set_xlabel("Adam step")
ax.set_ylabel(r"$\mathcal{L}_\mathrm{ELBO}$")
ax.set_title("Loss of each fit")
plt.tight_layout()
plt.show()
The black curve is the exact log likelihood in at the true (the Kalman filter of section 6), and the dotted lines mark where each fit started. Four of the eight fits end at the main mode, with between 1.967 and 2.000 km h⁻¹, between 0.298 and 0.310 km² h⁻¹ and a final of about −69. The other four end at the second mode, with between −0.630 and −0.608 km h⁻¹ and almost no diffusion ( between 0.025 and 0.043). Their loss, between 433.5 and 436.4, is about 500 nats worse. (They sit above the black curve because they also lowered , which the curve holds at the truth.) Which mode a fit reaches depends on its start, but not simply. The fit that started at −1.30 km h⁻¹ crossed to the main mode, while the one that started at 0.28 km h⁻¹ went to the second one. Since the final losses separate the two groups by hundreds of nats, we keep the fits at the best loss and drop the rest. Averaging all eight would mix two modes that the posterior does not mix. The uncertainty of then comes from the guide of a best fit, or from NUTS as in section 3, started inside the right mode.
The 8 fits took 26.4 s. Both kinds of ensemble multiply the work, but in different places. 5a multiplies every log-density evaluation by model runs, and 5b multiplies the whole fit by .
Summary¶
A transport model with an ensemble Kalman likelihood is a plain NumPyro function: priors on and , a
filterax.AbstractDynamicsbuilt from them, andensemble_factor("y", flx.filters.ETKF(), dynamics, observe, init_ensemble, y, obs_times, obs_noise). The initial ensemble is drawn once, outside the model, so the factor is deterministic and smooth in .NUTS on the two parameters, with 32 members, took 52.5 s with 3.6 leapfrog steps per draw. The diffusivity’s 90 % interval holds the truth, and the speed’s misses it by 0.004 km h⁻¹, as the exact Kalman posterior does too.
The analysis members in the returned
AssimilationResult, averaged over 50 NUTS draws, give the filtered field with bands. Between the sensors the RMSE is 0.114 and 98.8 % of the cell-hours fall within .The ensemble log likelihood is biased: 9.60 below the exact value at the truth with 16 members, 2.98 with 32 and 0.28 above with 128. Its posterior is within 0.003 km h⁻¹ of the exact one in from 32 members on, and with 16 members it is off by about one posterior standard deviation. Report with any result.
One gradient costs 8.6 ms with 32 members and 7.2 ms with the Kalman filter at . The ensemble is for states too large for a covariance, where the Kalman filter is not an option.
ensemble_viis an ensemble of fits, not of states. On this model four of eight fits from random starts ended at a second mode of , about 500 nats worse in , so it is a way to find the modes before fitting the posterior in the right one.
For nonlinear dynamics or observations with a moment-matched filter, see Example 6. For the exact Kalman filter on a small state, see Example 1.