Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

One site, end to end: a station record with NUTS, SVI and prediction through the gaps

Open In Colab

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, O(NDx3)\mathcal{O}(N D_x^3) in the record length NN and the state dimension DxD_x. We measure the wall-clock times for NUTS, SVI and one gradient in section 7.

What you’ll learn:

  1. How to write a Markov-GP regression as a plain NumPyro function, with a mean function and a mask for missing days.

  2. How to fit it with NUTS and with SVI, and how their hyperparameter posteriors compare with the truth.

  3. 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 yky_k (°C) at one station, where tkt_k is the kk-th day of the record, k=1,…,Nk = 1, \ldots, N. We model it as a seasonal climatology plus a weather anomaly plus sensor noise,

yk=μ(tk)+f(tk)+εky_k = \mu(t_k) + f(t_k) + \varepsilon_k
μ(t)=c+acos⁡(ωt)+bsin⁡(ωt)\mu(t) = c + a \cos(\omega t) + b \sin(\omega t)

where c,a,b∈Rc, a, b \in \mathbb{R} (°C) set the climatology and ω=2π/365.25 days−1\omega = 2\pi / 365.25 \text{ days}^{-1}. The anomaly is a Matérn-3/2 GP and the noise is independent and Gaussian,

f∼GP(0,kMateˊrn-3/2(t,t′;σf2,ℓ))f \sim \mathcal{GP}(0, k_\text{Matérn-3/2}(t, t'; \sigma_f^2, \ell))
εk∼N(0,σε2)\varepsilon_k \sim \mathcal{N}(0, \sigma_\varepsilon^2)

with the kernel variance σf2\sigma_f^2, the lengthscale ℓ\ell (days) and the noise variance σε2\sigma_\varepsilon^2 all in R>0\mathbb{R}_{>0}. The Matérn-3/2 kernel has an exact state-space form with a two-dimensional state xk∈RDx\mathbf{x}_k \in \mathbb{R}^{D_x}, Dx=2D_x = 2. So the Kalman filter gives us the marginal likelihood with ff integrated out. A day without an observation runs only the filter’s predict step. So with ok∈{0,1}o_k \in \{0, 1\} the observation mask,

log⁡p(y∣θ)=∑k=1Noklog⁡N(yk;μ(tk)+Hμx,k∣k−1,HΣx,k∣k−1H⊤+σε2)\log p(\mathbf{y} \mid \boldsymbol{\theta}) = \sum_{k=1}^{N} o_k \log \mathcal{N}(y_k; \mu(t_k) + \mathbf{H} \boldsymbol{\mu}_{x,k \mid k-1}, \mathbf{H} \boldsymbol{\Sigma}_{x,k \mid k-1} \mathbf{H}^\top + \sigma_\varepsilon^2)

where y∈RN\mathbf{y} \in \mathbb{R}^{N} is the record, μx,k∣k−1∈RDx\boldsymbol{\mu}_{x,k \mid k-1} \in \mathbb{R}^{D_x} and Σx,k∣k−1∈RDx×Dx\boldsymbol{\Sigma}_{x,k \mid k-1} \in \mathbb{R}^{D_x \times D_x} are the one-step-ahead mean and covariance of the state, H∈R1×Dx\mathbf{H} \in \mathbb{R}^{1 \times D_x} is the measurement row, and θ=(c,a,b,σf2,ℓ,σε2)∈R6\boldsymbol{\theta} = (c, a, b, \sigma_f^2, \ell, \sigma_\varepsilon^2) \in \mathbb{R}^{6} 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.

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 oko_k says which days are observed.

N = 730 days, observed = 596, missing = 134
  outage: 45 days, random dropouts: 89 days
<Figure size 1200x400 with 1 Axes>

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 ±20\pm 20 °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.

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 6×66 \times 6 matrix costs nothing next to the filter. The wall-clock time includes JIT compilation.


                   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 q(θ;ν)q(\boldsymbol{\theta}; \boldsymbol{\nu}), with the variational parameters ν\boldsymbol{\nu} (the Gaussian’s mean and covariance), and SVI minimises the negative ELBO, LELBO(ν)=−ELBO\mathcal{L}_\text{ELBO}(\boldsymbol{\nu}) = -\mathrm{ELBO}. We start the guide at the prior medians (init_to_median) rather than at the autoguide default of random points in [−2,2][-2, 2] in the unconstrained space. From a random start the climatology mean cc 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.

SVI wall-clock: 28.4 s for 1000 steps x 2 particles
final negative ELBO (mean of last 100 steps): 841.8
<Figure size 1200x300 with 1 Axes>

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.

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
<Figure size 1500x650 with 6 Axes>

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 σε2\sigma_\varepsilon^2 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 μ(t∗)+f(t∗)\mu(t_*) + f(t_*) at any test times t∗t_*. 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 NE=200N_{\mathcal{E}} = 200 NUTS draws θ(e)\boldsymbol{\theta}^{(e)}, e∈Ee \in \mathcal{E}, at once with jax.vmap and average them, so the bands carry the hyperparameter uncertainty as well as the uncertainty of the path. With μ∗(e)∈R\mu_*^{(e)} \in \mathbb{R} and (σ∗(e))2∈R>0(\sigma_*^{(e)})^2 \in \mathbb{R}_{>0} the posterior mean and variance under draw ee,

E[μ(t∗)+f(t∗)∣y]≈μˉ∗=1NE∑e∈Eμ∗(e)\mathbb{E}[\mu(t_*) + f(t_*) \mid \mathbf{y}] \approx \bar{\mu}_* = \frac{1}{N_{\mathcal{E}}} \sum_{e \in \mathcal{E}} \mu_*^{(e)}
V[μ(t∗)+f(t∗)∣y]≈1NE∑e∈E(σ∗(e))2+1NE∑e∈E(μ∗(e)−μˉ∗)2\mathbb{V}[\mu(t_*) + f(t_*) \mid \mathbf{y}] \approx \frac{1}{N_{\mathcal{E}}} \sum_{e \in \mathcal{E}} (\sigma_*^{(e)})^2 + \frac{1}{N_{\mathcal{E}}} \sum_{e \in \mathcal{E}} (\mu_*^{(e)} - \bar{\mu}_*)^2

and a new observation y∗y_* adds (σε(e))2(\sigma_\varepsilon^{(e)})^2 to each (σ∗(e))2(\sigma_*^{(e)})^2. The dense grid has a test time every six hours over the record and for 30 days beyond its end.

prediction at 3040 times for 200 draws: 4.6 s (with JIT)
<Figure size 1200x800 with 2 Axes>

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 ±2σ\pm 2\sigma band for y∗y_* (two predictive standard deviations), which should be close to 95 %.

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 ±2σ\pm 2\sigma 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 θ\boldsymbol{\theta} we draw 20 paths of μ(t)+f(t)\mu(t) + f(t) over the 45 outage days, so the 4,000 paths carry both the path’s uncertainty and the hyperparameters’.

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 NN days plus its reverse-mode gradient, which is O(NDx3)\mathcal{O}(N D_x^3) with Dx=2D_x = 2 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 O(N3)\mathcal{O}(N^3) Cholesky path, see section 4 of Kalman filtering and RTS smoothing.

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 NN. A dense GP would pay an O(N3)\mathcal{O}(N^3) 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, and NaN placeholders 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.