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.

Nonlinear dynamics: Lorenz-63 seen through one noisy component, with a moment-matched Kalman likelihood

Open In Colab

In Examples 1 to 5 the dynamics were linear, so a Kalman filter (exact, or with an ensemble standing in for the covariance) gave the log likelihood. Here the dynamics are nonlinear. We take the Lorenz-63 system, the three-variable model of convection that Lorenz used to show sensitive dependence on initial conditions, and observe only its first component, with noise and with gaps. From that one noisy record we infer two of its parameters and the noise variance with NUTS, and we reconstruct all three components through the gaps and a short forecast. The likelihood comes from a moment-matched nonlinear Kalman filter: it pushes a Gaussian belief through the dynamics with a quadrature rule (the unscented transform by default), so it is a surrogate and not the exact marginal. We compare it with the extended Kalman filter at the end.

pyrox-ssm capability shown: nonlinear_ssm_factor with mask=, which runs gaussx.nonlinear_kalman_filter with any gaussx integrator and adds its log likelihood as a NumPyro factor, and NonlinearGaussianSSMPrior, the same model as a prior whose condition runs the filter and gaussx.nonlinear_rts_smoother for the smoothed states. Cost: every log-density evaluation is one filter pass; per step the unscented rule runs the dynamics and the observation map on 2Dx+12 D_x + 1 sigma points and factorises a Dx×DxD_x \times D_x covariance. We measure the value and gradient times in section 3 and compare them with the extended filter in section 6.

What you’ll learn:

  1. How to write a nonlinear state-space model as a plain NumPyro function with nonlinear_ssm_factor, and why forward-mode gradients pay off for NUTS here.

  2. How the NUTS posterior of the Lorenz parameters compares with the truth.

  3. How to get the smoothed state, observed and unobserved components, through the gaps and a forecast with NonlinearGaussianSSMPrior.condition, averaged over posterior draws.

  4. Where the unscented and the extended Kalman filter differ, in the likelihood and in the state.

The NUTS workflow and the average over posterior draws are explained in Example 1, and the linear 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 x\mathbf{x}, the observations y\mathbf{y} and the parameters θ\boldsymbol{\theta}. The classic Lorenz variables (x,y,z)(x, y, z) would collide with the state and the observations, so we write them as the components x1,x2,x3x_1, x_2, x_3 of the state.

SymbolMeaningShape, units
x1,x2,x3x_1, x_2, x_3convection intensity, horizontal and vertical temperature differencesR\mathbb{R}, dimensionless
σ\sigmaPrandtl numberR>0\mathbb{R}_{>0}
ρ\rhoRayleigh number, scaled by its critical valueR>0\mathbb{R}_{>0}
β\betaaspect-ratio factor of the convection cellR>0\mathbb{R}_{>0}
ttmodel timeR\mathbb{R}, model time units (MTU)

The state x(t)=(x1(t),x2(t),x3(t))∈RDx\mathbf{x}(t) = (x_1(t), x_2(t), x_3(t)) \in \mathbb{R}^{D_x}, Dx=3D_x = 3, follows the vector field fc(x;θ):RDx→RDxf_\text{c}(\mathbf{x}; \boldsymbol{\theta}): \mathbb{R}^{D_x} \to \mathbb{R}^{D_x},

dx1dt=σ(x2−x1)\frac{\mathrm{d}x_1}{\mathrm{d}t} = \sigma (x_2 - x_1)
dx2dt=x1(ρ−x3)−x2\frac{\mathrm{d}x_2}{\mathrm{d}t} = x_1 (\rho - x_3) - x_2
dx3dt=x1x2−βx3\frac{\mathrm{d}x_3}{\mathrm{d}t} = x_1 x_2 - \beta x_3

With Lorenz’s values σ=10\sigma = 10, ρ=28\rho = 28 and β=8/3\beta = 8/3 the solutions are chaotic: nearby states separate exponentially, and the trajectory jumps between two lobes at irregular times. We step it on the grid tk=kΔtt_k = k \Delta t, k=0,1,…,Tk = 0, 1, \ldots, T, with Δt=0.05\Delta t = 0.05 MTU, and write xk=x(tk)\mathbf{x}_k = \mathbf{x}(t_k). The dynamics f(x;θ):RDx→RDxf(\mathbf{x}; \boldsymbol{\theta}): \mathbb{R}^{D_x} \to \mathbb{R}^{D_x} are one classical fourth-order Runge-Kutta (RK4) step of fcf_\text{c} over Δt\Delta t. The state-space model is then in its standard form,

xk=f(xk−1;θ)+ηk,ηk∼N(0,Ση)\mathbf{x}_k = f(\mathbf{x}_{k-1}; \boldsymbol{\theta}) + \boldsymbol{\eta}_k, \quad \boldsymbol{\eta}_k \sim \mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma}_\eta)
yk=h(xk;θ)+εk,εk∼N(0,Σε)\mathbf{y}_k = h(\mathbf{x}_k; \boldsymbol{\theta}) + \boldsymbol{\varepsilon}_k, \quad \boldsymbol{\varepsilon}_k \sim \mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma}_\varepsilon)

for k=1,…,Tk = 1, \ldots, T, with x0∼N(μx,0,Σx,0)\mathbf{x}_0 \sim \mathcal{N}(\boldsymbol{\mu}_{x,0}, \boldsymbol{\Sigma}_{x,0}). The model noise ηk∈RDx\boldsymbol{\eta}_k \in \mathbb{R}^{D_x}, with Ση=0.01IDx\boldsymbol{\Sigma}_\eta = 0.01 \mathbf{I}_{D_x}, stands for everything RK4 and the three equations leave out. The observation map h(x;θ)=x1h(\mathbf{x}; \boldsymbol{\theta}) = x_1 picks the first component, so yk∈RDy\mathbf{y}_k \in \mathbb{R}^{D_y} with Dy=1D_y = 1, and Σε∈RDy×Dy\boldsymbol{\Sigma}_\varepsilon \in \mathbb{R}^{D_y \times D_y} is a single variance. We fix β=8/3\beta = 8/3 and infer θ=(σ,ρ,Σε)∈R3\boldsymbol{\theta} = (\sigma, \rho, \boldsymbol{\Sigma}_\varepsilon) \in \mathbb{R}^{3}. Here hh is linear, so all the nonlinearity is in ff.

The moment-matched filter. For linear ff and hh the Kalman filter gives log⁡p(y1:T∣θ)\log p(\mathbf{y}_{1:T} \mid \boldsymbol{\theta}) exactly. For a nonlinear ff the belief about xk\mathbf{x}_k is no longer Gaussian, and gaussx.nonlinear_kalman_filter keeps it Gaussian by matching moments. With q(xk−1∣y1:k−1)=N(xk−1;μx,k−1∣k−1,Σx,k−1∣k−1)q(\mathbf{x}_{k-1} \mid \mathbf{y}_{1:k-1}) = \mathcal{N}(\mathbf{x}_{k-1}; \boldsymbol{\mu}_{x,k-1 \mid k-1}, \boldsymbol{\Sigma}_{x,k-1 \mid k-1}) the filtered belief, the predict step is

μx,k∣k−1=Eq(xk−1∣y1:k−1)[f(xk−1;θ)]\boldsymbol{\mu}_{x,k \mid k-1} = \mathbb{E}_{q(\mathbf{x}_{k-1} \mid \mathbf{y}_{1:k-1})}[f(\mathbf{x}_{k-1}; \boldsymbol{\theta})]
Σx,k∣k−1=Vq(xk−1∣y1:k−1)[f(xk−1;θ)]+Ση\boldsymbol{\Sigma}_{x,k \mid k-1} = \mathbb{V}_{q(\mathbf{x}_{k-1} \mid \mathbf{y}_{1:k-1})}[f(\mathbf{x}_{k-1}; \boldsymbol{\theta})] + \boldsymbol{\Sigma}_\eta

where μ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}. The update matches hh in the same way at the predicted belief, which gives μy,k∈RDy\boldsymbol{\mu}_{y,k} \in \mathbb{R}^{D_y} and Σy,k∈RDy×Dy\boldsymbol{\Sigma}_{y,k} \in \mathbb{R}^{D_y \times D_y} (with Σε\boldsymbol{\Sigma}_\varepsilon added) and the gain. With ok∈{0,1}o_k \in \{0, 1\} the observation mask, the factor is the sum of the one-step-ahead log densities,

log⁡p(y1:T∣θ)≈∑k=1Toklog⁡N(yk;μy,k,Σy,k)\log p(\mathbf{y}_{1:T} \mid \boldsymbol{\theta}) \approx \sum_{k=1}^{T} o_k \log \mathcal{N}(\mathbf{y}_k; \boldsymbol{\mu}_{y,k}, \boldsymbol{\Sigma}_{y,k})

The integrator decides how the expectations are computed. The unscented rule (gaussx.UnscentedIntegrator(alpha=1.0), the factor’s default) evaluates ff at 2Dx+1=72 D_x + 1 = 7 sigma points spread along the columns of a square root of Σx,k−1∣k−1\boldsymbol{\Sigma}_{x,k-1 \mid k-1} and needs no derivatives. The Taylor rule (gaussx.TaylorIntegrator()) is the extended Kalman filter (EKF): it takes f(μx,k−1∣k−1;θ)f(\boldsymbol{\mu}_{x,k-1 \mid k-1}; \boldsymbol{\theta}) for the mean and FkΣx,k−1∣k−1Fk⊤\mathbf{F}_k \boldsymbol{\Sigma}_{x,k-1 \mid k-1} \mathbf{F}_k^\top in place of the variance of ff, with Fk=Jf(μx,k−1∣k−1)∈RDx×Dx\mathbf{F}_k = \mathbf{J}_f(\boldsymbol{\mu}_{x,k-1 \mid k-1}) \in \mathbb{R}^{D_x \times D_x} the Jacobian. Both are exact for affine maps, where the factor equals the Kalman log marginal (the package’s tests check this for every deterministic integrator). For a nonlinear ff the sum above is a surrogate, and NUTS samples the posterior under that surrogate. The RTS smoother runs backwards over the same moments, with the cross-covariance Σxf,k∈RDx×Dx\boldsymbol{\Sigma}_{xf,k} \in \mathbb{R}^{D_x \times D_x} between xk\mathbf{x}_k and f(xk;θ)f(\mathbf{x}_k; \boldsymbol{\theta}) from the same rule in its gain, and gives μx,k∣T\boldsymbol{\mu}_{x,k \mid T} and Σx,k∣T\boldsymbol{\Sigma}_{x,k \mid T}.

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.7.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. Lorenz-63 seen through its first component, with gaps

We simulate one record from the model itself, so that we know the truth: Lorenz’s σ=10\sigma = 10 and ρ=28\rho = 28, and an observation noise variance Σε=1\boldsymbol{\Sigma}_\varepsilon = 1. The record has T=120T = 120 steps (6 MTU), and we add Tf=20T_\text{f} = 20 steps (1 MTU) after it that we keep for the forecast. We start from a point on the attractor (300 noise-free steps from (1,1,25)(1, 1, 25)). Then we punch two kinds of gap into the record: a 20-step outage from t=3t = 3 to t=4t = 4 MTU, and each step missing at random with probability 0.15. The missing steps are NaN, and the mask oko_k says which steps are observed.

T = 120 steps, observed = 90, missing = 30
  outage: 20 steps, random dropouts: 10 steps
<Figure size 1200x700 with 3 Axes>

Only x1x_1 is observed, and with a noise standard deviation of 1 on a signal that swings between about -20 and 20. The other two components never reach the data, and the outage hides one excursion of the trajectory. The forecast window starts at the end of the record.

2. The model as a plain NumPyro function

The priors say what we would know before seeing the record: a Prandtl number of order 10, a Rayleigh number in the twenties and a noise variance below a few units, all positive. So we take σ∼LogNormal(log⁡8,0.52)\sigma \sim \mathrm{LogNormal}(\log 8, 0.5^2), ρ∼LogNormal(log⁡25,0.32)\rho \sim \mathrm{LogNormal}(\log 25, 0.3^2) and Σε∼LogNormal(log⁡0.5,12)\boldsymbol{\Sigma}_\varepsilon \sim \mathrm{LogNormal}(\log 0.5, 1^2). We take a wide initial state, μx,0=(0,0,25)\boldsymbol{\mu}_{x,0} = (0, 0, 25) and Σx,0=64IDx\boldsymbol{\Sigma}_{x,0} = 64 \mathbf{I}_{D_x}, about the spread of the attractor. Then nonlinear_ssm_factor takes ff built from the two sample sites, hh, Ση\boldsymbol{\Sigma}_\eta, Σε\boldsymbol{\Sigma}_\varepsilon, the record, the initial moments and the mask, and registers the factor "y". The first row of y is y1\mathbf{y}_1, scored after one step from x0\mathbf{x}_0.

site 'sigma'        LogNormal  value shape=()
site 'rho'          LogNormal  value shape=()
site 'noise_var'    LogNormal  value shape=()
site 'y'            factor     value shape=(0,)

So the trace holds three scalar sample sites and one factor, as in the earlier examples. The 120-step path of all three components is inside the filter, and NUTS never sees it.

3. NUTS, with forward-mode gradients

NUTS needs the gradient of the log density at every leapfrog step. The filter is a jax.lax.scan over 120 small steps, each with seven RK4 evaluations, so a reverse-mode gradient has to store and replay every one of them. With only three parameters, forward mode (three tangent passes alongside the filter) can be cheaper. We time the log likelihood, its reverse-mode gradient and its forward-mode Jacobian at the truth before choosing.

value                    1.54 ms
reverse-mode gradient   12.26 ms
forward-mode Jacobian    4.42 ms

The forward-mode Jacobian (4.42 ms) costs about a third as much as the reverse-mode gradient (12.26 ms), or about three evaluations of the log likelihood (1.54 ms each). So we pass forward_mode_differentiation=True to NUTS. We run two chains of 200 draws after 100 warm-up steps, with a dense mass matrix, started at the prior medians and run one after the other (chain_method="sequential"). We cap the trajectories at 25 leapfrog steps (max_tree_depth=5), which bounds the cost of the long early warm-up trajectories. The wall-clock time includes JIT compilation.


                 mean       std    median      5.0%     95.0%     n_eff     r_hat
  noise_var      0.91      0.15      0.90      0.66      1.15    304.18      1.00
        rho     28.12      0.46     28.10     27.44     28.91    363.56      1.00
      sigma     10.68      0.63     10.69      9.66     11.69    245.28      1.01

Number of divergences: 0
NUTS wall-clock: 33.6 s for 2 chains x 300 iterations, 0 divergences
leapfrog steps after warm-up: 1992, 5.0 per draw

4. The parameters against the truth

parameter      truth         mean ± sd          90% interval
sigma          10.00   10.683 ± 0.633   [ 9.700, 11.765]  in
rho            28.00   28.124 ± 0.460   [27.438, 28.905]  in
noise_var       1.00    0.909 ± 0.151   [ 0.682,  1.184]  in
<Figure size 1400x350 with 3 Axes>

Both chains agree (R^≤1.01\hat{R} \le 1.01), with no divergences and 5.0 leapfrog steps per draw, and all three 90 % intervals contain the true values. The Rayleigh number is pinned down best, at 28.124 ± 0.460 against the true 28. The Prandtl number comes out at 10.683 ± 0.633, about one posterior standard deviation above the true 10, and the noise variance at 0.909 ± 0.151 against 1. So one noisy component with gaps is enough to identify both parameters: σ\sigma sets how fast x1x_1 follows x2x_2, and ρ\rho sets the size of the excursions of x2x_2 that x1x_1 follows. Keep in mind that this is the posterior under the unscented surrogate. Section 6 shows how much the surrogate depends on the integrator.

5. The smoothed state through the gaps, and a forecast

NonlinearGaussianSSMPrior holds the same model as the factor: ff, hh, the two noise covariances, the initial state and the integrator. Its condition(y, mask=mask) runs the filter and then gaussx.nonlinear_rts_smoother with the same ff and the same integrator, which gives μx,k∣T\boldsymbol{\mu}_{x,k \mid T} and Σx,k∣T\boldsymbol{\Sigma}_{x,k \mid T}. For the forecast we run the filter on all T+TfT + T_\text{f} rows of the record, with the last TfT_\text{f} masked. A masked step only predicts, and the smoother has no data after the record to correct with, so on the forecast steps the smoothed moments are the filter’s predictions. We do this at NE=50N_{\mathcal{E}} = 50 NUTS draws θ(e)\boldsymbol{\theta}^{(e)}, e∈Ee \in \mathcal{E}, with jax.vmap. We combine them per component as in Example 1, with the mean over the draws of μx,k∣T(e)\boldsymbol{\mu}_{x,k \mid T}^{(e)}, and the mean of the variances plus the variance of the means. So the bands carry the uncertainty of θ\boldsymbol{\theta} as well as that of the path. Since we simulated the record, we score them against the true state on the observed steps, the random dropouts, the outage and the forecast.

50 filter and smoother runs: 1.1 s (with JIT)
segment            n    coverage of ±2σ (x1, x2, x3)     RMSE (x1, x2, x3)
observed          90              95.6,  92.2, 100.0    0.25,  0.47,  0.56
random dropouts   10             100.0, 100.0, 100.0    0.21,  0.50,  0.35
outage            20             100.0, 100.0, 100.0    0.24,  0.24,  0.30
forecast          20             100.0, 100.0, 100.0    2.09,  2.65,  4.28
<Figure size 1200x800 with 3 Axes>

The posterior mean follows the truth in all three components, also in x2x_2 and x3x_3, which never reach the data: the dynamics couple them to x1x_1, so the filter infers them from how x1x_1 moves. On the observed steps the ±2σ\pm 2\sigma band covers 95.6 %, 92.2 % and 100 % of the true values of x1x_1, x2x_2 and x3x_3, with RMSEs of 0.25, 0.47 and 0.56. The band hardly widens through the outage, where every true value is inside it and the RMSEs (0.24, 0.24 and 0.30) are no worse than on the observed steps. The smoother has the record on both sides of the gap, and with model noise as small as Ση\boldsymbol{\Sigma}_\eta only a narrow set of paths joins the two ends. The forecast has data on one side only, and there the band opens within 1 MTU to a good part of the range of the attractor. The RMSEs grow to 2.09, 2.65 and 4.28, and the band still covers every true value. This is the predictability limit of a chaotic system, seen from the filter: the record pins the state down tightly, and the forecast loses that within about one MTU.

6. The unscented against the extended Kalman filter

We now swap the integrator for gaussx.TaylorIntegrator(), the EKF, and keep everything else. We compare the two at the NUTS posterior mean θˉ\bar{\boldsymbol{\theta}} in three ways. We look at the log likelihood and its cost per evaluation, at the profile of the log likelihood in ρ\rho with σ\sigma and Σε\boldsymbol{\Sigma}_\varepsilon held at their posterior means (81 values, one filter pass each), and at the smoothed state on the outage and the forecast. A second NUTS run under the EKF would answer the same question more fully, but it costs as much as section 3 again.

integrator           log p(y | theta_bar)  argmax rho  value, ms  fwd grad, ms
unscented                         -139.24       28.20       2.02          4.62
extended (Taylor)                 -140.22       27.70       1.10          8.40

integrator          segment      coverage (x1, x2, x3)    RMSE (x1, x2, x3)
unscented           outage          95.0, 100.0, 100.0   0.24,  0.24,  0.30
unscented           forecast       100.0, 100.0, 100.0   2.24,  2.85,  4.20
extended (Taylor)   outage         100.0, 100.0, 100.0   0.18,  0.21,  0.24
extended (Taylor)   forecast        55.0,  65.0,  95.0   3.70,  5.38,  5.55

max |difference of the smoothed means| on observed : 1.03
max |difference of the smoothed means| on outage   : 0.40
max |difference of the smoothed means| on forecast : 9.58
<Figure size 1400x420 with 2 Axes>

At θˉ\bar{\boldsymbol{\theta}} the two log likelihoods are close, −139.24 for the unscented filter and −140.22 for the EKF. The profiles in ρ\rho tell them apart. Below the true ρ=28\rho = 28 they nearly coincide, but above it the EKF profile falls off much faster. Its maximum on the grid is at ρ=27.70\rho = 27.70 against 28.20 for the unscented one. That shift is about one posterior standard deviation of ρ\rho (0.460), so the choice of rule alone would move the inferred Rayleigh number by that much. Neither surrogate is the exact likelihood, and this comparison does not say which one is closer to it.

The smoothed states agree on the record, where the means differ by at most 1.03. They also agree in the outage, where they differ by at most 0.40 and the EKF is even slightly closer to the truth (RMSEs of 0.18, 0.21 and 0.24 against 0.24, 0.24 and 0.30). In the forecast they part ways. There the means differ by up to 9.58, and the EKF’s RMSEs grow to 3.70, 5.38 and 5.55 against 2.24, 2.85 and 4.20. Its band covers only 55 % and 65 % of the true x1x_1 and x2x_2 (95 % of x3x_3), while the unscented band covers all of them. On the record the belief is narrow, so ff is close to linear across it and both rules give the same moments. In the forecast the belief is wide, and the linearisation at the mean misses the spread that the sigma points pick up, so the EKF is overconfident exactly where the uncertainty matters.

One evaluation costs 2.02 ms with the unscented rule and 1.10 ms with the EKF, so the seven sigma points cost about two Jacobians. The forward-mode gradient goes the other way, 4.62 ms against 8.40 ms, because the EKF’s gradient differentiates through Jf\mathbf{J}_f, a second derivative of the RK4 step. So on this model the unscented default is both the cheaper filter for NUTS and the better-calibrated one.

Summary

  • A nonlinear state-space model is a plain NumPyro function: priors on θ\boldsymbol{\theta}, the dynamics ff built from the sample sites, and nonlinear_ssm_factor("y", f, h, Σ_η, Σ_ε, y, μ_x0, Σ_x0, mask=mask). The default integrator is the unscented rule with alpha=1.0, which needs no derivatives of ff.

  • NUTS on (σ,ρ,Σε)(\sigma, \rho, \boldsymbol{\Sigma}_\varepsilon) from 90 noisy observations of x1x_1 took 33.6 s with forward-mode gradients, with no divergences and 5.0 leapfrog steps per draw. All three 90 % intervals contain the truth, and ρ\rho comes out at 28.124 ± 0.460.

  • NonlinearGaussianSSMPrior(...).condition(y, mask=mask) runs the same filter and the moment-matched smoother, and gives the smoothed state, including the two components that are never observed. Averaged over 50 NUTS draws, the band bridges the 1 MTU outage tightly and opens in the forecast, and it covers every true value in both.

  • The integrator is a modelling choice. The unscented filter and the EKF agree on the record, but their likelihood profiles peak at ρ=28.20\rho = 28.20 and 27.70, and in the forecast the EKF band covers only 55 % of the true x1x_1.

  • One log likelihood costs 1.54 ms and one forward-mode gradient 4.42 ms at T=120T = 120 (the reverse-mode gradient 12.26 ms), so NUTS is the expensive step here.

For linear dynamics, where the Kalman filter is exact, see Example 1. For a state too large to carry a Dx×DxD_x \times D_x covariance, see the ensemble filter of Example 5.