This is the shortest complete pyrox-ssm workflow. We take one station with one daily series that has gaps, write one NumPyro model, fit it with two inference methods and draw a posterior predictive through the missing days. The later examples (many sites, a shared regional signal, non-Gaussian counts, ensembles, nonlinear dynamics) all start from this model and change one piece of it.
pyrox-ssm capability shown: markov_gp_factor with mask=, which adds the Kalman-filter marginal likelihood of a Markov GP as a NumPyro factor and leaves the missing observations out, and MarkovGPPrior.condition(...).predict(...), which gives the smoothed posterior at arbitrary times. Cost: every log-density evaluation is one Kalman filter pass, in the record length and the state dimension . We measure the wall-clock times for NUTS, SVI and one gradient in section 7.
What you’ll learn:
How to write a Markov-GP regression as a plain NumPyro function, with a mean function and a mask for missing days.
How to fit it with NUTS and with SVI, and how their hyperparameter posteriors compare with the truth.
How to predict the latent signal and new observations at dense times, through the gaps, averaged over the posterior.
For the Kalman recursions themselves see Kalman filtering and RTS smoothing. For maximum likelihood, mean-field versus full-rank guides and what a record can identify, see Training a Markov GP.
Background¶
Our toy record is the daily mean air temperature (°C) at one station, where is the -th day of the record, . We model it as a seasonal climatology plus a weather anomaly plus sensor noise,
where (°C) set the climatology and . The anomaly is a Matérn-3/2 GP and the noise is independent and Gaussian,
with the kernel variance , the lengthscale (days) and the noise variance all in . The Matérn-3/2 kernel has an exact state-space form with a two-dimensional state , . So the Kalman filter gives us the marginal likelihood with integrated out. A day without an observation runs only the filter’s predict step. So with the observation mask,
where is the record, and are the one-step-ahead mean and covariance of the state, is the measurement row, and are the six parameters that NUTS and SVI infer.
Setup¶
We detect Colab and install pyrox, pyrox-gp[colab] (which pulls in matplotlib and watermark) and pyrox-ssm 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 @ 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 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
import optax
from numpyro import handlers
from numpyro.infer import MCMC, NUTS, SVI, Trace_ELBO, init_to_median
from numpyro.infer.autoguide import AutoMultivariateNormal
from pyrox_ssm import (
MarkovGPPrior,
MaternSDE,
markov_gp_factor,
markov_gp_from_innovations,
)
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,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
gaussx : 0.8.0
pyrox : 0.3.1
pyrox_ssm : 0.2.1
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 station record with gaps¶
We use two years of daily values, drawn from the model itself so that we know the true parameters: a 10 °C mean with an 8 °C annual cycle, a 2 °C weather anomaly that decorrelates over about four days, and 0.5 °C sensor noise. We simulate the anomaly path with markov_gp_from_innovations, which runs the SDE forward from standard normal innovations in linear time. Then we punch two kinds of gap into it: a 45-day logger outage in the second winter, and each day missing at random with probability 0.12. We store the missing days as NaN, as they would be in a real file, and the mask says which days are observed.
# Shapes: N = 730 days; D_x = 2 (the Matérn-3/2 state)
# ω = 2π / 365.25 days⁻¹, the annual angular frequency
OMEGA = 2.0 * jnp.pi / 365.25
def climatology(t, c, a, b):
"""Seasonal mean μ(t) = c + a cos(ωt) + b sin(ωt)."""
return c + a * jnp.cos(OMEGA * t) + b * jnp.sin(OMEGA * t)
truth = {
"mean_temp": 10.0,
"cos_amp": -8.0, # coldest near day 0 (1 January)
"sin_amp": -1.5,
"variance": 4.0, # (2 °C)^2
"lengthscale": 4.0, # days
"noise_var": 0.25, # (0.5 °C)^2
}
N = 2 * 365
# t_k, days since 1 January of year 1
times = jnp.arange(N, dtype=jnp.float64) # → (N,)
key_f, key_eps, key_gap = jr.split(jr.PRNGKey(2024), 3)
# today (pyrox_ssm)
# k_Matérn-3/2(t, t'; σ_f², ℓ) as a linear SDE
sde_true = MaternSDE(truth["variance"], truth["lengthscale"], order=1)
# today (pyrox_ssm)
prior_true = MarkovGPPrior(sde_true, times)
innovations = jr.normal(key_f, (N, prior_true.state_dim)) # → (N, D_x)
# today (pyrox_ssm)
# f(t_k), the SDE run forward from the innovations
f_true = markov_gp_from_innovations(prior_true, innovations) # (N, D_x) → (N,)
# μ(t_k) = c + a cos(ω t_k) + b sin(ω t_k)
mu_true = climatology( # (N,) → (N,)
times, truth["mean_temp"], truth["cos_amp"], truth["sin_amp"]
)
noise_std = jnp.sqrt(truth["noise_var"]) # → ()
# ε_k ~ 𝒩(0, σ_ε²)
obs_noise = noise_std * jr.normal(key_eps, (N,)) # → (N,)
# y_k = μ(t_k) + f(t_k) + ε_k
y_full = mu_true + f_true + obs_noise # (N,) → (N,)
# late January to early March, year 2
outage = (times >= 395) & (times < 440) # → (N,) bool
dropout = jr.uniform(key_gap, (N,)) < 0.12 # → (N,) bool
# o_k = 1 on an observed day
mask = ~(outage | dropout) # → (N,) bool
# what the station file holds
y = jnp.where(mask, y_full, jnp.nan) # → (N,)
print(f"N = {N} days, observed = {int(mask.sum())}, missing = {int((~mask).sum())}")
print(
f" outage: {int(outage.sum())} days, "
f"random dropouts: {int((dropout & ~outage).sum())} days"
)N = 730 days, observed = 596, missing = 134
outage: 45 days, random dropouts: 89 days
fig, ax = plt.subplots(figsize=(12, 4))
ax.plot(times, mu_true + f_true, "k-", lw=0.6, alpha=0.6, label=r"true $\mu + f$")
ax.scatter(times[mask], y[mask], c="C1", s=4, label="observed $y$", zorder=5)
ax.axvspan(395, 440, color="grey", alpha=0.2, label="logger outage")
ax.set_xlabel("day")
ax.set_ylabel("temperature [°C]")
ax.set_title("Toy station record: daily mean temperature with missing days")
ax.legend(loc="lower right", fontsize=8)
plt.tight_layout()
plt.show()
2. The model as a plain NumPyro function¶
Every parameter is an ordinary numpyro.sample site. We choose priors that say what a climatologist would say before seeing this station: a mean somewhere within °C of 10 °C, a seasonal amplitude of up to about 10 °C, an anomaly of a couple of degrees that lasts about a week, and sensor noise well below a degree. We pass the mean function to MarkovGPPrior as mean_fn. Then markov_gp_factor adds the masked Kalman log marginal as a factor site named "y". The NaNs in y are safe, because masked entries are zeroed before any arithmetic, so they reach neither the value nor the gradient.
def station_model(times, y, mask):
# Shapes: N = 730 days; D_θ = 6 parameters
# today (numpyro): the six sample sites of θ
# c ~ 𝒩(10, 10²)
c = numpyro.sample("mean_temp", dist.Normal(10.0, 10.0))
# a ~ 𝒩(0, 10²)
a = numpyro.sample("cos_amp", dist.Normal(0.0, 10.0))
# b ~ 𝒩(0, 10²)
b = numpyro.sample("sin_amp", dist.Normal(0.0, 10.0))
# σ_f² ~ LogNormal(log 2, 1)
variance = numpyro.sample("variance", dist.LogNormal(jnp.log(2.0), 1.0))
# ℓ ~ LogNormal(log 7, 1)
lengthscale = numpyro.sample("lengthscale", dist.LogNormal(jnp.log(7.0), 1.0))
# σ_ε² ~ LogNormal(log 0.1, 1)
noise_var = numpyro.sample("noise_var", dist.LogNormal(jnp.log(0.1), 1.0))
# today (pyrox_ssm)
# k_Matérn-3/2(t, t'; σ_f², ℓ) as a linear SDE
sde = MaternSDE(variance=variance, lengthscale=lengthscale, order=1)
# today (pyrox_ssm)
# μ + f ~ 𝒢𝒫(μ, k_Matérn-3/2) on the N days
prior = MarkovGPPrior(sde, times, mean_fn=lambda t: climatology(t, c, a, b))
# today (pyrox_ssm)
# log p(y ∣ θ) = ∑ₖ oₖ log 𝒩(yₖ; μ(tₖ) + H μ_x,k∣k−1, H Σ_x,k∣k−1 Hᵀ + σ_ε²)
markov_gp_factor("y", prior, y, noise_var, mask=mask)
# today (numpyro)
seeded_model = handlers.seed(station_model, rng_seed=0)
# today (numpyro)
trace = handlers.trace(seeded_model).get_trace(times, y, mask)
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 'mean_temp' Normal value shape=()
site 'cos_amp' Normal value shape=()
site 'sin_amp' Normal value shape=()
site 'variance' LogNormal value shape=()
site 'lengthscale' LogNormal value shape=()
site 'noise_var' LogNormal value shape=()
site 'y' factor value shape=(0,)
So the trace holds six scalar sample sites and one factor. The 730-day latent path is not in the trace at all, because the Kalman filter has integrated it out. This is what makes NUTS cheap on this model, as there is no high-dimensional latent and no funnel between the path and its hyperparameters.
3. NUTS¶
We run two chains of 300 draws after 200 warm-up steps with a dense mass matrix (dense_mass=True). So warm-up adapts to the correlations between the six unconstrained parameters and not only to their scales. With six parameters the matrix costs nothing next to the filter. The wall-clock time includes JIT compilation.
# Shapes: D_θ = 6 parameters; 2 chains × 300 = 600 posterior draws
# today (numpyro)
nuts_kernel = NUTS(station_model, dense_mass=True)
# today (numpyro)
nuts = MCMC(
nuts_kernel,
num_warmup=200,
num_samples=300,
num_chains=2,
chain_method="sequential",
progress_bar=False,
)
t0 = time.perf_counter()
# today (numpyro)
# 600 draws θ ~ p(θ ∣ y)
nuts.run(jr.PRNGKey(1), times, y, mask, 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: (600,)}
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 500 iterations, "
f"{n_div} divergences"
)
print(
f"leapfrog steps after warm-up: {n_grad}, {n_grad / 600:.1f} per draw "
"(one Kalman filter pass and its gradient each)"
)
mean std median 5.0% 95.0% n_eff r_hat
cos_amp -7.74 0.32 -7.74 -8.25 -7.21 914.72 1.00
lengthscale 3.77 0.31 3.74 3.32 4.32 560.40 1.01
mean_temp 10.38 0.20 10.37 10.05 10.71 547.16 1.00
noise_var 0.19 0.02 0.19 0.15 0.23 651.43 1.00
sin_amp -1.22 0.30 -1.21 -1.78 -0.81 702.31 1.00
variance 3.52 0.46 3.48 2.76 4.15 587.75 1.00
Number of divergences: 0
NUTS wall-clock: 94.3 s for 2 chains x 500 iterations, 0 divergences
leapfrog steps after warm-up: 3696, 6.2 per draw (one Kalman filter pass and its gradient each)
4. SVI with a full-rank Gaussian guide¶
AutoMultivariateNormal fits a Gaussian over the six unconstrained parameters with a full covariance, so it can represent the correlations between them (Training a Markov GP shows what a mean-field guide loses). We keep the same model as for NUTS. Its guide is , with the variational parameters (the Gaussian’s mean and covariance), and SVI minimises the negative ELBO, . We start the guide at the prior medians (init_to_median) rather than at the autoguide default of random points in in the unconstrained space. From a random start the climatology mean begins far from 10 °C, and the optimiser can settle in a poor local optimum where a long-lengthscale anomaly and a large noise variance absorb the misfit.
# Shapes: D_θ = 6 parameters; 1,000 guide draws
# today (numpyro)
# q(θ; ν), a full-covariance Gaussian over the unconstrained θ
guide = AutoMultivariateNormal(station_model, init_loc_fn=init_to_median)
# today (optax)
optimizer = optax.adam(0.02)
# today (numpyro)
# ℒ_ELBO(ν) = −ELBO, a Monte Carlo estimate from 2 particles
elbo = Trace_ELBO(num_particles=2)
# today (numpyro)
svi = SVI(station_model, guide, optimizer, elbo)
t0 = time.perf_counter()
# today (numpyro)
# ν⋆ = argmin_ν ℒ_ELBO(ν), 1000 Adam steps
svi_result = svi.run(jr.PRNGKey(3), 1000, times, y, mask, progress_bar=False)
jax.block_until_ready(svi_result.params)
svi_seconds = time.perf_counter() - t0
# today (numpyro)
# 1,000 draws θ ~ q(θ; ν⋆)
svi_samples = guide.sample_posterior( # → {name: (1000,)}
jr.PRNGKey(4), svi_result.params, sample_shape=(1000,)
)
final_loss = float(svi_result.losses[-100:].mean()) # → ()
print(f"SVI wall-clock: {svi_seconds:.1f} s for 1000 steps x 2 particles")
print(f"final negative ELBO (mean of last 100 steps): {final_loss:.1f}")
fig, ax = plt.subplots(figsize=(12, 3))
ax.plot(np.asarray(svi_result.losses), "C0", lw=0.8)
ax.set_ylim(np.percentile(np.asarray(svi_result.losses), [0, 95]))
ax.set_xlabel("SVI step")
ax.set_ylabel("negative ELBO")
ax.set_title("SVI convergence")
plt.tight_layout()
plt.show()SVI wall-clock: 28.4 s for 1000 steps x 2 particles
final negative ELBO (mean of last 100 steps): 841.8

5. The two posteriors against the truth¶
For each parameter we print the posterior mean, standard deviation and 90 % interval from NUTS and from SVI, next to the value we simulated the data with.
param_names = list(truth)
header = (
f"{'parameter':<12}{'truth':>8} {'NUTS mean ± sd':>18} "
f"{'NUTS 90% interval':>22} {'SVI mean ± sd':>18} {'SVI 90% interval':>22}"
)
print(header)
for k in param_names:
row = f"{k:<12}{truth[k]:>8.2f}"
for s in (nuts_samples, svi_samples):
v = np.asarray(s[k])
lo, hi = np.percentile(v, [5, 95])
inside = "in" if lo <= truth[k] <= hi else "out"
row += (
f" {v.mean():>9.3f} ± {v.std():<6.3f} "
f"[{lo:>7.3f}, {hi:>7.3f}] {inside:>3}"
)
print(row)parameter truth NUTS mean ± sd NUTS 90% interval SVI mean ± sd SVI 90% interval
mean_temp 10.00 10.375 ± 0.204 [ 10.045, 10.709] out 10.359 ± 0.228 [ 9.989, 10.740] in
cos_amp -8.00 -7.735 ± 0.316 [ -8.276, -7.238] in -7.670 ± 0.309 [ -8.185, -7.161] in
sin_amp -1.50 -1.217 ± 0.301 [ -1.701, -0.730] in -1.218 ± 0.259 [ -1.641, -0.786] in
variance 4.00 3.521 ± 0.460 [ 2.874, 4.389] in 3.588 ± 0.463 [ 2.907, 4.385] in
lengthscale 4.00 3.767 ± 0.314 [ 3.320, 4.319] in 3.885 ± 0.280 [ 3.441, 4.348] in
noise_var 0.25 0.194 ± 0.025 [ 0.156, 0.238] out 0.196 ± 0.028 [ 0.154, 0.243] out
fig, axes = plt.subplots(2, 3, figsize=(15, 6.5))
for ax, k in zip(axes.ravel(), param_names, strict=True):
for s, label, color in ((nuts_samples, "NUTS", "C0"), (svi_samples, "SVI", "C1")):
ax.hist(
np.asarray(s[k]), bins=40, density=True, alpha=0.5, color=color, label=label
)
ax.axvline(truth[k], color="k", ls="--", lw=1.2, label="truth")
ax.set_title(k)
axes[0, 0].legend(fontsize=8)
fig.suptitle("Hyperparameter posteriors: NUTS vs SVI (full-rank)")
plt.tight_layout()
plt.show()
The NUTS and SVI marginals overlap for every parameter, and their posterior means differ by at most 0.12 (the lengthscale, 3.77 against 3.89 days). With the path integrated out, the six-parameter posterior is close enough to Gaussian in the unconstrained space for a full-rank guide to match it. The NUTS 90 % intervals contain four of the six true values and the SVI ones contain five. Both methods put the noise variance low (posterior mean 0.19 against 0.25), and the NUTS interval for the mean temperature stops at 10.05 °C, just above the true 10 °C; both misses are about two posterior standard deviations. Since the two methods agree, these misses belong to this one realisation of the record and not to either fitting method.
6. Prediction through the gaps¶
For one parameter draw, MarkovGPPrior.condition(y, noise_var, mask=mask) runs the filter and RTS smoother and returns a ConditionedMarkovGP. Its predict(t_star) gives the posterior mean and variance of the latent at any test times . It re-runs the smoother over the merged grid with the test times masked out of the update. The conditioned GP keeps the mask, so the missing days stay unobserved. We do this for NUTS draws , , at once with jax.vmap and average them, so the bands carry the hyperparameter uncertainty as well as the uncertainty of the path. With and the posterior mean and variance under draw ,
and a new observation adds to each . The dense grid has a test time every six hours over the record and for 30 days beyond its end.
# Shapes: N = 730 days; M = 3,040 test times (every 6 h); N_E = 200 draws
t_dense = jnp.arange(0.0, N + 30.0, 0.25) # → (M,)
def predict_one(theta, t_star):
# today (pyrox_ssm)
sde = MaternSDE(theta["variance"], theta["lengthscale"], order=1)
# today (pyrox_ssm)
prior = MarkovGPPrior(
sde,
times,
mean_fn=lambda t: climatology(
t, theta["mean_temp"], theta["cos_amp"], theta["sin_amp"]
),
)
# today (pyrox_ssm)
# p(x_1:N ∣ y; θ⁽ᵉ⁾) by the Kalman filter and RTS smoother
cond = prior.condition(y, theta["noise_var"], mask=mask)
# today (pyrox_ssm)
# μ_*⁽ᵉ⁾, (σ_*⁽ᵉ⁾)² of μ(t_*) + f(t_*)
mean, var = cond.predict(t_star) # (M,) → (M,), (M,)
# (σ_*⁽ᵉ⁾)² + (σ_ε⁽ᵉ⁾)² for a new observation y_*
obs_var = var + theta["noise_var"] # → (M,)
return mean, var, obs_var
def posterior_predict(samples, t_star, n_draws=200):
num_samples = samples["variance"].shape[0]
# N_E draws θ⁽ᵉ⁾, evenly spaced through the chain
idx = jnp.linspace(0, num_samples - 1, n_draws).astype(int) # → (N_E,)
draws = {k: v[idx] for k, v in samples.items()}
# today (jax)
predict_draws = jax.vmap(predict_one, in_axes=(0, None))
# today (jax)
predict_draws = jax.jit(predict_draws)
# μ_*⁽ᵉ⁾, (σ_*⁽ᵉ⁾)², (σ_*⁽ᵉ⁾)² + (σ_ε⁽ᵉ⁾)²
means, f_vars, y_vars = predict_draws(draws, t_star) # → 3 × (N_E, M)
# μ̄_* = (1/N_E) ∑ₑ μ_*⁽ᵉ⁾
mean = einx.mean("member test -> test", means) # (N_E, M) → (M,)
# (1/N_E) ∑ₑ (μ_*⁽ᵉ⁾ − μ̄_*)²
spread = einx.var("member test -> test", means) # (N_E, M) → (M,)
# (1/N_E) ∑ₑ (σ_*⁽ᵉ⁾)²
f_var_mean = einx.mean("member test -> test", f_vars) # (N_E, M) → (M,)
# 𝕍[μ(t_*) + f(t_*) ∣ y] ≈ (1/N_E) ∑ₑ (σ_*⁽ᵉ⁾)² + spread
f_var = f_var_mean + spread # → (M,)
# (1/N_E) ∑ₑ ((σ_*⁽ᵉ⁾)² + (σ_ε⁽ᵉ⁾)²)
y_var_mean = einx.mean("member test -> test", y_vars) # (N_E, M) → (M,)
# the same for a new observation y_*
y_var = y_var_mean + spread # → (M,)
return mean, f_var, y_var
t0 = time.perf_counter()
f_mean, f_var, y_var = posterior_predict(nuts_samples, t_dense) # → 3 × (M,)
jax.block_until_ready(f_mean)
pred_seconds = time.perf_counter() - t0
f_mean_svi, f_var_svi, _ = posterior_predict(svi_samples, t_dense) # → 2 × (M,)
print(
f"prediction at {t_dense.shape[0]} times for 200 draws: "
f"{pred_seconds:.1f} s (with JIT)"
)prediction at 3040 times for 200 draws: 4.6 s (with JIT)
f_sd, y_sd, f_sd_svi = np.sqrt(f_var), np.sqrt(y_var), np.sqrt(f_var_svi)
fig, axes = plt.subplots(2, 1, figsize=(12, 8))
ax = axes[0]
ax.fill_between(
t_dense,
f_mean - 2 * y_sd,
f_mean + 2 * y_sd,
color="C0",
alpha=0.15,
label=r"$y_*$ $\pm 2\sigma$",
)
ax.fill_between(
t_dense,
f_mean - 2 * f_sd,
f_mean + 2 * f_sd,
color="C0",
alpha=0.35,
label=r"$\mu + f$ $\pm 2\sigma$",
)
ax.plot(t_dense, f_mean, "C0", lw=0.8, label="posterior mean")
ax.scatter(times[mask], y[mask], c="C1", s=3, zorder=5, label="observed")
ax.axvline(N - 1, color="grey", ls=":", lw=1)
ax.set_ylabel("temperature [°C]")
ax.set_title("NUTS posterior predictive over the whole record and a 30-day forecast")
ax.legend(loc="lower right", fontsize=8, ncol=2)
ax = axes[1]
win = (t_dense >= 370) & (t_dense <= 470)
twin = (times >= 370) & (times <= 470)
ax.fill_between(
t_dense[win],
(f_mean - 2 * y_sd)[win],
(f_mean + 2 * y_sd)[win],
color="C0",
alpha=0.15,
label=r"NUTS $y_*$ $\pm 2\sigma$",
)
ax.fill_between(
t_dense[win],
(f_mean - 2 * f_sd)[win],
(f_mean + 2 * f_sd)[win],
color="C0",
alpha=0.35,
label=r"NUTS $\mu + f$ $\pm 2\sigma$",
)
ax.plot(t_dense[win], f_mean[win], "C0", lw=1.5, label="NUTS mean")
ax.plot(
t_dense[win],
(f_mean_svi - 2 * f_sd_svi)[win],
"C2--",
lw=1,
label=r"SVI $\mu + f$ $\pm 2\sigma$",
)
ax.plot(t_dense[win], (f_mean_svi + 2 * f_sd_svi)[win], "C2--", lw=1)
ax.plot(times[twin], (mu_true + f_true)[twin], "k--", lw=1, label=r"true $\mu + f$")
ax.scatter(
times[twin & mask],
y[twin & mask],
c="C1",
edgecolors="k",
linewidths=0.5,
s=18,
zorder=5,
label="observed",
)
ax.scatter(
times[twin & ~mask],
y_full[twin & ~mask],
marker="x",
c="C3",
s=18,
zorder=5,
label="withheld (never seen)",
)
ax.axvspan(395, 440, color="grey", alpha=0.15)
ax.set_xlabel("day")
ax.set_ylabel("temperature [°C]")
ax.set_title("Zoom on the 45-day outage")
ax.legend(loc="upper left", fontsize=8, ncol=3)
plt.tight_layout()
plt.show()
Inside the outage, the band widens to the climatology plus the stationary anomaly spread within a few lengthscales of its edges. The posterior mean relaxes to the seasonal cycle, and the same happens in the forecast after the last day. Short random gaps barely widen the band, because the neighbouring days pin the anomaly down. The SVI band lies on top of the NUTS one.
Because the data are simulated, we know the values the model never saw, so we can check the predictive bands. Below we compute the fraction of withheld days whose value falls inside the band for (two predictive standard deviations), which should be close to 95 %.
# Shapes: N_miss = 134 withheld days; N_E = 200 draws
t_withheld = times[~mask] # → (N_miss,)
y_mean_w, _, y_var_w = posterior_predict(nuts_samples, t_withheld) # → 2 × (N_miss,)
# r = y − μ̄_* on the withheld days
residual = y_full[~mask] - y_mean_w # → (N_miss,)
# z = r / σ_*, with σ_* the predictive standard deviation of y_*
z = residual / jnp.sqrt(y_var_w) # → (N_miss,)
for label, sel in (
("outage", outage[~mask]),
("random dropouts", ~outage[~mask]),
("all withheld", jnp.ones_like(z, dtype=bool)),
):
# fraction of days with |z| < 2
cover = float(jnp.mean(jnp.abs(z[sel]) < 2.0)) # → ()
# RMSE = √(mean of r²)
rmse = float(jnp.sqrt(jnp.mean(residual[sel] ** 2))) # → ()
print(
f"{label:<16} n = {int(sel.sum()):>3} "
f"coverage of ±2σ = {100 * cover:5.1f} % RMSE = {rmse:.2f} °C"
)outage n = 45 coverage of ±2σ = 100.0 % RMSE = 1.61 °C
random dropouts n = 89 coverage of ±2σ = 95.5 % RMSE = 0.69 °C
all withheld n = 134 coverage of ±2σ = 97.0 % RMSE = 1.09 °C
All 45 outage days and 95.5 % of the 89 isolated missing days fall inside the band for a new observation. The error is much larger inside the outage (RMSE 1.61 °C) than at isolated missing days (0.69 °C), as it should be. An isolated day is pinned down by its neighbours, whereas in the middle of the outage the best the model can do is the climatology, and its band says so.
Joint paths through the outage¶
The bands above are marginal: they say where each day’s temperature lies, not how neighbouring days move together. A quantity of several days, such as the warmest day of the outage or the mean over it, needs joint draws of the path, because the days of an outage are strongly correlated a posteriori. ConditionedMarkovGP.sample(key, n_paths, t_star) draws whole paths by backward sampling through the Kalman smoother (gaussx’s rts_sample). For each of the 200 NUTS draws of we draw 20 paths of over the 45 outage days, so the 4,000 paths carry both the path’s uncertainty and the hyperparameters’.
# Shapes: N_E = 200 draws; N_P = 20 paths per draw; N_out = 45 outage days
t_outage = times[outage] # → (N_out,)
def outage_paths(theta, key):
# today (pyrox_ssm)
sde = MaternSDE(theta["variance"], theta["lengthscale"], order=1)
# today (pyrox_ssm)
prior = MarkovGPPrior(
sde,
times,
mean_fn=lambda t: climatology(
t, theta["mean_temp"], theta["cos_amp"], theta["sin_amp"]
),
)
# today (pyrox_ssm)
cond = prior.condition(y, theta["noise_var"], mask=mask)
# today (pyrox_ssm)
# joint draws of μ(t) + f(t) over the outage, given y and θ⁽ᵉ⁾
return cond.sample(key, n_paths=20, t_star=t_outage) # → (N_P, N_out)
num_samples = nuts_samples["variance"].shape[0]
idx = jnp.linspace(0, num_samples - 1, 200).astype(int) # → (N_E,)
theta_draws = {k: v[idx] for k, v in nuts_samples.items()}
path_keys = jr.split(jr.PRNGKey(7), 200) # → (N_E,)
t0 = time.perf_counter()
# today (jax)
paths = jax.jit(jax.vmap(outage_paths))(theta_draws, path_keys) # → (N_E, N_P, N_out)
jax.block_until_ready(paths)
path_seconds = time.perf_counter() - t0
paths = einx.id("member path day -> (member path) day", paths) # → (4000, N_out)
print(
f"{paths.shape[0]} joint paths over {t_outage.shape[0]} days: {path_seconds:.1f} s (with JIT)"
)
# the true μ(t) + f(t) over the outage, which the station never reported
true_path = (mu_true + f_true)[outage] # → (N_out,)
statistics = {
"warmest outage day": lambda p: einx.max("... [day]", p),
"outage mean": lambda p: einx.mean("... [day]", p),
}
print(f"{'quantity':<20}{'90 % interval':>20}{'truth':>9}")
for label, stat in statistics.items():
values = stat(paths) # → (4000,)
lo, hi = jnp.quantile(values, jnp.array([0.05, 0.95]))
print(
f"{label:<20}{f'[{float(lo):5.2f}, {float(hi):5.2f}] °C':>20}{float(stat(true_path)):>7.2f} °C"
)
# the outage mean's spread from the joint paths, against the spread it would
# have if the 45 days were independent with the same marginal variances
joint_sd = float(jnp.std(einx.mean("... [day]", paths)))
independent_sd = (
float(jnp.sqrt(einx.sum("[day]", einx.var("[path] day", paths))))
/ t_outage.shape[0]
)
print(
f"sd of the outage mean: {joint_sd:.2f} °C from the joint paths, {independent_sd:.2f} °C if the days were independent"
)4000 joint paths over 45 days: 5.0 s (with JIT)
quantity 90 % interval truth
warmest outage day [ 6.03, 10.27] °C 6.67 °C
outage mean [ 3.10, 5.89] °C 3.99 °C
sd of the outage mean: 0.85 °C from the joint paths, 0.27 °C if the days were independent
Both 90 % intervals contain the true value: the warmest of the 45 outage days lies in [6.03, 10.27] °C (truth 6.67 °C) and the outage mean in [3.10, 5.89] °C (truth 3.99 °C). Neither interval can be read off the marginal bands. The outage mean shows why: its standard deviation over the joint paths is 0.85 °C, about three times the 0.27 °C it would have if the days were independent with the same marginal variances. A 4-day lengthscale makes neighbouring days move together, so the errors of a 45-day mean do not average out the way independent ones would. The 4,000 paths took 5.0 s, including JIT compilation, at 20 paths per posterior draw.
7. Cost¶
Each NUTS leapfrog step and each SVI particle costs one Kalman filter pass over the days plus its reverse-mode gradient, which is with for Matérn-3/2. In the cell below we time one jitted log density and gradient at this record’s length and at records of the same daily station that are 4 and 16 times longer. So we measure the linear scaling rather than assert it. For the crossover against the dense Cholesky path, see section 4 of Kalman filtering and RTS smoothing.
def time_grad(n, repeats=10):
# Shapes: n days (N, 4N or 16N); D_θ = 3 log parameters (σ_f², ℓ, σ_ε²)
t = jnp.arange(n, dtype=jnp.float64) # → (n,)
noise = jr.normal(jr.PRNGKey(0), (n,)) # → (n,)
obs = jnp.sin(OMEGA * t) + noise # → (n,)
all_observed = jnp.ones(n, dtype=bool) # → (n,) bool
def neg_log_marginal(log_params):
params = jnp.exp(log_params) # → (3,)
# today (pyrox_ssm)
sde = MaternSDE(params[0], params[1], order=1)
# today (pyrox_ssm)
prior = MarkovGPPrior(sde, t)
# today (pyrox_ssm)
# ℒ_NLL(θ) = −log p(y; θ), one Kalman filter pass
log_marginal = prior.log_marginal(obs, params[2], mask=all_observed)
return -log_marginal
# today (jax)
# ℒ_NLL(θ) and ∇_θ ℒ_NLL, jitted once
loss_and_grad = jax.jit(jax.value_and_grad(neg_log_marginal))
log_params = jnp.log(jnp.array([4.0, 4.0, 0.25])) # → (3,)
jax.block_until_ready(loss_and_grad(log_params))
t0 = time.perf_counter()
for _ in range(repeats):
jax.block_until_ready(loss_and_grad(log_params))
return (time.perf_counter() - t0) / repeats
grad_ms = {n: 1e3 * time_grad(n) for n in (N, 4 * N, 16 * N)}
for n, ms in grad_ms.items():
print(
f"N = {n:>6}: {ms:7.3f} ms per log density + gradient "
f"({1e6 * ms / 1e3 / n:.2f} µs per day)"
)
print()
print(
f"NUTS: {nuts_seconds:6.1f} s "
f"(2 chains x 500 iterations, {n_grad} leapfrog steps after warm-up)"
)
print(f"SVI : {svi_seconds:6.1f} s (1000 steps x 2 particles)")
print(f"prediction: {pred_seconds:.1f} s (200 draws x {t_dense.shape[0]} times)")N = 730: 20.540 ms per log density + gradient (28.14 µs per day)
N = 2920: 81.974 ms per log density + gradient (28.07 µs per day)
N = 11680: 291.400 ms per log density + gradient (24.95 µs per day)
NUTS: 94.3 s (2 chains x 500 iterations, 3696 leapfrog steps after warm-up)
SVI : 28.4 s (1000 steps x 2 particles)
prediction: 4.6 s (200 draws x 3040 times)
The time per day stays flat while the record grows sixteen-fold, so one log density and its gradient scale linearly in . A dense GP would pay an Cholesky on every one of them. NUTS is the expensive step because it evaluates the gradient thousands of times (the leapfrog count above, plus warm-up). SVI needs about a thousand evaluations per particle, and the posterior predictive is a few filter-and-smoother passes per draw, vectorised over the draws.
Summary¶
A Markov-GP regression for one station is a plain NumPyro function: priors on the SDE kernel, the mean function and the noise, then
markov_gp_factor(..., mask=mask). Missing days are a mask, not a reindexing, andNaNplaceholders are safe.The trace holds only the six parameters, as the Kalman filter integrates the latent path out. So NUTS and SVI both run on a six-dimensional posterior. Here they agree with each other, and their 90 % intervals contain four (NUTS) and five (SVI) of the six true values.
MarkovGPPrior.condition(..., mask=mask).predict(t_star)gives the smoothed posterior at any times, inside gaps and beyond the record. Averaging it over posterior draws gives bands that include the hyperparameter uncertainty.ConditionedMarkovGP.sample(key, n_paths, t_star)draws whole paths through a gap by backward sampling, for quantities of several days. Over the outage, the joint paths give an interval for the warmest day and for the 45-day mean, and the mean’s spread is three times what independent days would give.Every step is linear in the record length.
The next examples change one piece of this model at a time: many sites with pooled hyperparameters, a regional signal shared between sites, and non-Gaussian observations. For the kernels in state-space form see Matérn kernels in state-space form.