Quickstart¶
This notebook solves an ordinary differential equation (ODE) with a probabilistic solver. Instead of a single trajectory, the solver returns a Gaussian posterior over the solution, which consists of a mean and a calibrated uncertainty.
The ODE together with a known initial value forms an initial value problem (IVP). Every solve combines the same four ingredients:
- a prior describing how smooth the solution is (an integrated Wiener process),
- a measurement model asserting that the solution's derivative matches the vector field (the ODE-information operator),
- an extended Kalman filter (EKF) forward pass, and
- a Rauch-Tung-Striebel (RTS) smoother backward pass that refines the forward estimate into the full smoothed posterior.
For the concepts behind these ingredients, read What is a probabilistic ODE solver? first.
We import the four public building blocks, the Taylor-mode initializer and
interpolate, and set the shared plot style of the documentation. jax.numpy
is imported as np, so the code reads like NumPy while it runs on JAX, which
allows the just-in-time (JIT) compilation below.
import logging
import equinox as eqx
import jax
import jax.numpy as np
import matplotlib.pyplot as plt
from matplotlib_inline.backend_inline import set_matplotlib_formats
from tueplots import bundles, cycler
from tueplots.constants.color import palettes
from ode_filters import (
IWP,
ODEInformation,
gaussian_filter,
interpolate,
rts_smoother,
taylor_mode_initialization,
)
jax.config.update("jax_enable_x64", True)
plt.rcParams.update(bundles.tue_ai_beamer())
plt.rcParams.update(cycler.cycler(color=palettes.paultol_bright))
set_matplotlib_formats("svg") # vector figures stay sharp at any size
# Fall back to the default font quietly where Roboto Condensed is not installed.
logging.getLogger("matplotlib.font_manager").setLevel(logging.ERROR)
palette = plt.rcParams["axes.prop_cycle"].by_key()["color"]
REFERENCE = palette[6] # gray: exact solutions and other references
Example problem: the logistic ODE¶
We solve the logistic equation, a classic model of constrained growth:
$$\dot{x}(t) = x(t)\,(1-x(t)), \qquad x(0) = x_0 = 0.01, \qquad t \in [0, 10].$$
The solution starts near zero, grows fastest at $x = 1/2$ (near $t = 4.6$), and saturates at $x = 1$. We use this problem because it has a closed-form solution, against which we check the probabilistic estimate at the end.
1. Define the initial value problem¶
The vector field vf returns the time-derivative $\dot{x}$ given the current
state. The state is a length-1 array (d = 1), x0 is the initial value, and
tspan is the time interval. Time is passed as a keyword-only argument, matching
the library convention.
def vf(x, *, t):
return x * (1 - x)
x0 = np.array([0.01])
tspan = (0, 10)
d = x0.shape[0]
2. Select a prior¶
The prior is a Gaussian process that encodes our smoothness assumptions about the solution before the ODE enters. We use an integrated Wiener process (IWP):
qis the number of derivatives the prior tracks, so the state it models is the stack $[x, \dot{x}, \ddot{x}, \dots]$ up to the $q$-th derivative. A largerqassumes a smoother solution and gives a higher order of accuracy when that assumption holds.q = 2(value, velocity, acceleration) is the default for most problems.Xiis the diffusion scale of the prior. Here (d = 1) it is a scalar that scales the variance of the Wiener process driving the highest derivative, so a largerXigives a wider prior. In generalXiis ad-by-dpositive-(semi)definite matrix that enters the process noise askron(Q_scalar(h), Xi). A diagonalXitherefore sets independent scales per component, and off-diagonal entries correlate the components.
taylor_mode_initialization then turns the IVP into a consistent initial
Gaussian. It computes the initial mean of the full stacked state
$[x, \dot{x}, \ddot{x}]$ by repeatedly differentiating the vector field at x0
(Taylor-mode initialization) and pairs it with a zero (Dirac) covariance. The
filter therefore starts from a point estimate with zero uncertainty that
already satisfies the ODE.
q = 2
Xi = 0.5 * np.eye(d)
prior = IWP(q, d, Xi=Xi)
m_0, P_0_sqr = taylor_mode_initialization(vf, x0, q)
3. Define the measurement model¶
A probabilistic ODE solver treats the ODE itself as data. At each time step it forms the residual $\dot{x}(t) - f(x(t), t)$ and conditions on the residual being zero.
ODEInformation is this residual operator. It needs two projection matrices
supplied by the prior:
E0selects the solution value $x$ from the stacked state, andE1selects the first derivative $\dot{x}$.
With these it conditions on $\dot{x}(t) = f(x(t), t)$ at every grid point.
measure = ODEInformation(vf, prior.E0, prior.E1)
4. Run the filter and smoother¶
The forward pass is gaussian_filter. We compile it just in time with
equinox.filter_jit, which traces every array among the arguments (m_0,
P_0_sqr, the time grid and the arrays inside the prior and the measurement
model) and treats everything else as static. The static parts, such as the
order q and the vector field, define the structure of the computation, so JAX
compiles them into the code. jax.jit with static arguments does not work
here, because a model that holds arrays is not hashable; see
Sharp bits.
We keep the default "dynamic" calibration (Bosch et al. 2021). At each step
it rescales the prior diffusion by a scalar quasi-maximum-likelihood estimate
(quasi-MLE) computed from the ODE residual. The posterior covariance thereby
adapts to the observed misfit instead of using a fixed diffusion, and the band
reflects the solver's estimated uncertainty instead of an arbitrary fixed
scale. The estimator is approximate, because it conditions on the EK1
linearization and assumes that the residual covariance scales linearly with the
diffusion.
jit_filter = eqx.filter_jit(gaussian_filter)
jit_smoother = eqx.filter_jit(rts_smoother)
# A deliberately coarse grid of 10 steps, on which the band is wide enough to
# compare with the error below. On finer grids band and error shrink together.
N = 10
result = jit_filter(m_0, P_0_sqr, prior, measure, np.linspace(*tspan, N + 1))
gaussian_filter returns a FilterResult whose fields are stacked sequences,
one entry per grid point. The two we use are:
result.m, the posterior mean of the stacked state, andresult.P_sqr, its square-root covariance, from which the full covariance isP = P_sqr.T @ P_sqr.
It also carries result.log_likelihood, the marginal log-likelihood of the
ODE-information residuals after diffusion calibration. It can serve for model
comparison. Because calibration rescales the process noise of every step,
these values are comparable only between runs with the same calibration mode.
This notebook does not use it.
The filter is a single forward pass. rts_smoother then runs a backward pass
over the same result and conditions every estimate on the information from the
whole interval. We report the smoothed posterior.
m_smooth, P_smooth_sqr = jit_smoother(result)
5. Visualize the results¶
The smoother gives the posterior at the grid points. interpolate also
evaluates it between them (dense output). It bridges consecutive grid points
with the prior, so the solution and its band are drawn as smooth curves that
show the posterior between the steps. Standard deviations come from .std,
which computes the square root of the diagonal of
$P = P_\text{sqr}^\top P_\text{sqr}$ from the factor without forming $P$.
def logistic_exact(t):
return 1.0 / (1.0 + (1.0 / x0[0] - 1.0) * np.exp(-t))
ts = np.linspace(tspan[0], tspan[1], N + 1)
t_dense = np.linspace(tspan[0], tspan[1], 401)
dense = interpolate(result, prior, t_dense) # the smoothed posterior at t_dense
mean, sigma = dense.m[:, 0], dense.std[:, 0]
The logistic equation has the closed-form solution
$$x(t) = \frac{1}{1 + (1/x_0 - 1)\,e^{-t}},$$
which we overlay as a reference (left). On this grid the band is too narrow to see next to the solution, so the right panel compares its half-width, two standard deviations, with the actual error on a logarithmic axis.
fig, (left, right) = plt.subplots(1, 2)
left.plot(t_dense, logistic_exact(t_dense), color=REFERENCE, lw=2.5, label="exact solution")
left.fill_between(t_dense, mean - 2 * sigma, mean + 2 * sigma, color=palette[0], alpha=0.25, lw=0)
left.plot(t_dense, mean, color=palette[0], label=r"mean $\pm$ 2 std")
left.plot(ts, m_smooth[:, 0], "o", ms=3, color=palette[0]) # the grid points
left.set_xlabel("$t$")
left.set_ylabel("$x$")
left.legend(loc="upper left")
error = np.abs(mean - logistic_exact(t_dense))
right.semilogy(t_dense, error, color=REFERENCE, lw=2.5, label="actual error")
right.semilogy(t_dense, 2 * sigma, color=palette[0], label="2 std")
right.set_xlabel("$t$")
right.set_ylabel("error in $x$")
right.legend(loc="lower right")
plt.show()
The band is the 2-sigma credible interval, an uncertainty quantification that a classical solver does not provide. The actual error stays below two standard deviations everywhere, so the band contains the true curve. Both are largest near $t = 5$, where the solution changes fastest and the coarse steps leave the solver most uncertain.
The band is calibrated: its width follows the numerical error instead of a fixed prior scale. Varying the grid resolution shows this.
def smoothed_solution(n_steps):
grid = np.linspace(tspan[0], tspan[1], n_steps + 1)
res = jit_filter(m_0, P_0_sqr, prior, measure, grid)
m_nodes = jit_smoother(res).m[:, 0]
return grid, m_nodes, interpolate(res, prior, t_dense)
fig, axes = plt.subplots(1, 2, sharey=True)
for ax, n_steps in zip(axes, [6, 40], strict=True):
grid, m_nodes, dense = smoothed_solution(n_steps)
m, s = dense.m[:, 0], dense.std[:, 0]
ax.plot(t_dense, logistic_exact(t_dense), color=REFERENCE, lw=2.5, label="exact solution")
ax.fill_between(t_dense, m - 2 * s, m + 2 * s, color=palette[0], alpha=0.25, lw=0)
ax.plot(t_dense, m, color=palette[0], label=r"mean $\pm$ 2 std")
ax.plot(grid, m_nodes, "o", ms=2, color=palette[0]) # the grid points
ax.set_title(f"$N = {n_steps}$ steps")
ax.set_xlabel("$t$")
axes[0].set_ylabel("$x$")
axes[0].legend(loc="upper left")
plt.show()
With 6 steps the band is wide, because long steps leave the solver uncertain between the grid points. With 40 steps the band narrows to a thin line, since the solver conditions on the ODE at more points. Its largest half-width falls from 0.09 to 0.0009, by two orders of magnitude. At both resolutions the band contains the true solution. This uncertainty, which depends on the step size and tracks the discretization error, is what a probabilistic solver returns in addition to a point estimate.
These four steps make up the solver: pick a prior, state the ODE as a measurement, filter forward and smooth backward. The result is the solution together with its uncertainty. The other notebooks apply the same four ingredients to systems with several components, conservation laws, data and hidden inputs.