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.

Marches

An ocean model stepping forward

An ocean model advances its state (velocities, temperature, salinity, sea surface height) by a fixed time step, many thousands of times. A typical setup uses several schemes at once: a strong-stability-preserving Runge–Kutta method for the advection of tracers, an implicit treatment for vertical diffusion (which is stiff on a fine vertical grid), a leapfrog step with a Robert–Asselin filter in older codes, and fast barotropic substeps inside each slow baroclinic step. These look like a different subject from the global mean of chapter 5, and most libraries keep them apart.

They are not a different subject. Each step of each scheme integrates the model’s tendency over one time step, and each does it with a quadrature rule in time. In this chapter we read the steppers in integrix.march that way: their nodes and weights, their exactness, and the local and global errors that come with them. Stability, which has no counterpart in plain quadrature, is the other half of a stepper and closes the chapter.

An ODE is an integral equation

Let the state x(t)∈RDx\vect{x}(t) \in \mathbb{R}^{D_x} evolve as x˙=f(x,t)\dot{\vect{x}} = f(\vect{x}, t), where f:RDx×R→RDxf: \mathbb{R}^{D_x} \times \mathbb{R} \to \mathbb{R}^{D_x} is the tendency (the right-hand side), and take steps of size hh between times tk=t0+kht_k = t_0 + k h. Integrating both sides over one step gives

x(tk+1)=x(tk)+∫tktk+1f(x(t),t)dt\vect{x}(t_{k+1}) = \vect{x}(t_k) + \int_{t_k}^{t_{k+1}} f(\vect{x}(t), t) \mathrm{d}t

which is exact, so every one-step method is a way of approximating the integral on the right with samples of ff. This is why ff keeps one letter across this section (see Notation): the integrand of a march is the tendency. The difference from chapter 5 is that the integrand depends on the unknown x(t)\vect{x}(t) inside the step, so the samples have to be predicted before they can be weighted.

Runge–Kutta methods as quadrature

An explicit Runge–Kutta method with NstageN_\text{stage} stages predicts the state at stage times tk+ciht_k + c_i h, samples the tendency there and sums the samples with weights bib_i,

ki=f(xk+h∑j<iaijkj,tk+cih),xk+1=xk+h∑i=1Nstagebiki\vect{k}_i = f\Big(\vect{x}_k + h \sum_{j<i} a_{ij} \vect{k}_j, t_k + c_i h\Big), \quad \vect{x}_{k+1} = \vect{x}_k + h \sum_{i=1}^{N_\text{stage}} b_i \vect{k}_i

where ki∈RDx\vect{k}_i \in \mathbb{R}^{D_x} are the stage tendencies and aija_{ij}, bib_i, cic_i the Butcher coefficients. If ff does not depend on x\vect{x}, the stages are just samples of ff in time and (7.2) becomes

∫tktk+hf(t)dt≈h∑i=1Nstagebif(tk+cih)\int_{t_k}^{t_k + h} f(t) \mathrm{d}t \approx h \sum_{i=1}^{N_\text{stage}} b_i f(t_k + c_i h)

which is a rule on [0,1][0, 1] with nodes cic_i and weights bib_i, scaled by hh. So every Runge–Kutta method carries a quadrature rule, and Table 7.1 lists the ones in integrix.march.

Table 7.1:The quadrature rule inside each explicit Runge–Kutta stepper of integrix.march: its nodes cic_i and weights bib_i on [0,1][0, 1], and the order qq of the full method.

StepperNodes cic_iWeights bib_iRuleOrder qq
ForwardEulerDfx01left rectangle1
RK2Heun, SSP_RK20,10, 112,12\frac{1}{2}, \frac{1}{2}trapezoid2
RK3SSP0,1,120, 1, \frac{1}{2}16,16,23\frac{1}{6}, \frac{1}{6}, \frac{2}{3}Simpson3
RK4Classic0,12,12,10, \frac{1}{2}, \frac{1}{2}, 116,13,13,16\frac{1}{6}, \frac{1}{3}, \frac{1}{3}, \frac{1}{6}Simpson, midpoint sampled twice4
SSP_RK104ten stages (Ketcheson, 2008)4

The order conditions of a Runge–Kutta method start with exactly these quadrature conditions, ∑ibicim=1/(m+1)\sum_i b_i c_i^m = 1/(m + 1) for m=0,…,q−1m = 0, \ldots, q - 1 (the moment equations of (2.3) on [0,1][0, 1]), and add conditions on the aija_{ij} for the coupling through x\vect{x} (Hairer et al., 1993). So a method of order qq needs a rule of degree at least q−1q - 1. We can measure each stepper’s degree directly, by taking one step of h=1h = 1 on x˙=tm\dot{x} = t^m from x(0)=0x(0) = 0, where the exact answer is 1/(m+1)1/(m + 1).

import jax

jax.config.update("jax_enable_x64", True)

from collections.abc import Callable
from typing import Any

import diffrax as dfx
import einx
import jax.numpy as jnp
import lineax as lx
import numpy as np
from integrix import march
from jaxtyping import Array, Float

# Shapes: D_x = 1, a scalar state


# user
def one_step(
    solver: dfx.AbstractSolver,
    tendency: Callable[..., Any],
    state: Float[Array, ""],
    step: float,
) -> Float[Array, ""]:
    """One step of h from t = 0 with a diffrax solver."""
    # today (diffrax)
    # ẋ = f(x, t)
    term = dfx.ODETerm(tendency)
    # today (diffrax)
    # x(h) = x(0) + ∫₀ʰ f(x(t), t) dt, one step
    solution = dfx.diffeqsolve(
        term, solver, t0=0.0, t1=step, dt0=step, y0=state, max_steps=2
    )
    return solution.ys[0]


# user
def degree_of_exactness(solver: dfx.AbstractSolver) -> int:
    """The largest m for which one step integrates tᵐ over [0, 1] exactly."""
    # no degree is exact yet
    degree = -1
    for power in range(8):
        # ẋ = tᵐ
        monomial = lambda t, x, args: t**power
        # x(1) = 1/(m + 1)
        estimate = one_step(solver, monomial, jnp.asarray(0.0), 1.0)  # → ()
        # e = |x̂(1) − 1/(m + 1)|
        if abs(float(estimate) - 1.0 / (power + 1)) > 1e-12:
            break
        degree = power
    return degree


# the five steppers whose rules we compare
steppers = {
    # today (integrix)
    "ForwardEulerDfx": march.ForwardEulerDfx(),
    # today (integrix)
    "RK2Heun": march.RK2Heun(),
    # today (integrix)
    "RK3SSP": march.RK3SSP(),
    # today (integrix)
    "RK4Classic": march.RK4Classic(),
    # today (integrix)
    "SSP_RK104": march.SSP_RK104(),
}
for name, solver in steppers.items():
    print(f"{name:16s} degree {degree_of_exactness(solver)}")
ForwardEulerDfx  degree 0
RK2Heun          degree 1
RK3SSP           degree 3
RK4Classic       degree 3
SSP_RK104        degree 3

Euler is the left rectangle and integrates only constants. Heun is the trapezoid rule, degree 1. SSP-RK3 and RK4 both sample the step at 0, 12\frac{1}{2} and 1 with Simpson’s weights, so both have degree 3, even though one is a third-order method and the other fourth-order: the extra order of RK4 comes from its aija_{ij}, not its rule. Ketcheson’s ten-stage method spends its extra stages on a larger strong-stability-preserving step instead of a higher degree. Going the other way, choosing the cic_i as Gauss–Legendre nodes gives the implicit Gauss collocation methods, of order 2Nstage2 N_\text{stage}; integrix does not ship them, but they are the global rule of chapter 3 used as a stepper.

Adams–Bashforth: interpolate the past

A multistep method reuses tendencies it has already computed instead of predicting new stages. Adams–Bashforth interpolates the last few tendencies fk,fk−1,…f_k, f_{k-1}, \ldots with a polynomial in time and integrates that polynomial over the next step, which is the interpolatory construction of chapter 2 with nodes at the past times. In units of hh, the nodes are 0,−1,−2,…0, -1, -2, \ldots, the interval is [0,1][0, 1], and the weights solve the moment equations (2.3) with bm=∫01tmdt=1/(m+1)b_m = \int_0^1 t^m \mathrm{d}t = 1/(m + 1).

# Shapes: N = 2 or 3 past times, the nodes of the rule
for n_past, scale in ((2, 2), (3, 12)):
    # n = 0, …, N − 1
    ordinal = jnp.arange(float(n_past))                         # → (N,)
    # tₙ = −n, the past times (in units of h)
    past_times = -ordinal                                       # → (N,)
    # Vₙₘ = tₙᵐ
    vander = jnp.vander(past_times, increasing=True)            # → (N, N)
    # [V]ₘₙ = tₙᵐ
    vandermonde = einx.id("n m -> m n", vander)                 # → (N, N)
    # m + 1 = 1, …, N
    powers = jnp.arange(1.0, n_past + 1.0)                      # → (N,)
    # bₘ = ∫₀¹ tᵐ dt = 1/(m + 1)
    moments = 1.0 / powers                                      # → (N,)
    # today (lineax)
    # V = [V]ₘₙ as an operator
    operator = lx.MatrixLinearOperator(vandermonde)             # (N, N) operator
    # today (lineax)
    # V w = b
    weights = lx.linear_solve(operator, moments).value          # → (N,)
    print(f"AB{n_past}: {jnp.round(weights * scale, 10).tolist()} / {scale}")
AB2: [3.0, -1.0] / 2
AB3: [23.0, -16.0, 5.0] / 12

These are the coefficients of ab2_step and ab3_step. The rule extrapolates outside its nodes, so it has negative weights, and chapter 2’s warning about negative weights shows up here as a small stability region: AB3 needs a smaller step than RK3 for the same advection problem. The leapfrog step, xk+1=xk−1+2hf(xk)\vect{x}_{k+1} = \vect{x}_{k-1} + 2 h f(\vect{x}_k), is the midpoint rule over two steps, and the split-explicit step of split_explicit_step drives the slow state with the trapezoidal mean of the fast barotropic substeps, which is a rule over the slow step too.

Local and global error

A stepper makes an error on every step, and these local errors add up over the run, like the interval errors of a scan in chapter 6. If one step from the exact state has a local truncation error O(hq+1)O(h^{q+1}), then after T/hT / h steps to a fixed end time TT the global error is

∥xK−x(T)∥=O(hq),K=T/h\Vert \vect{x}_K - \vect{x}(T) \Vert = O(h^q), \quad K = T / h

one power of hh lower, since there are O(1/h)O(1/h) steps and the dynamics carry each local error forward without blowing it up (for a stable problem). The order qq of a method is its global order, and it is what integrix’s order test measures: tests/march/test_order.py runs each stepper on the decay problem x˙=γx\dot{x} = \gamma x with γ=−1\gamma = -1 to T=1T = 1 and fits the slope of log⁡\log error against log⁡h\log h. We run the same problem with the same step sizes and measure both errors.

# Shapes: D_x = 1; K = T/h steps; N_h = 4 step sizes h


# user
def decay(
    t: float, state: Float[Array, ""], args: Any
) -> Float[Array, ""]:
    """ẋ = γ x with γ = −1."""
    # ẋ = γ x
    return -state


# user
def final_state(solver: dfx.AbstractSolver, step: float) -> Float[Array, ""]:
    """x(T) at T = 1 with constant steps h."""
    # K = T/h
    n_steps = round(1.0 / step)
    # today (diffrax)
    # ẋ = γ x
    term = dfx.ODETerm(decay)
    # today (diffrax)
    # x(T) = x(0) + ∫₀ᵀ γ x dt, in K steps of h
    solution = dfx.diffeqsolve(
        term,
        solver,
        t0=0.0,
        t1=1.0,
        dt0=step,
        y0=jnp.asarray(1.0),
        max_steps=n_steps + 1,
    )
    return solution.ys[0]


cases = {
    # today (integrix)
    "RK2Heun": (march.RK2Heun(), np.array([0.04, 0.02, 0.01, 0.005])),
    # today (integrix)
    "RK3SSP": (march.RK3SSP(), np.array([0.04, 0.02, 0.01, 0.005])),
    # today (integrix)
    "RK4Classic": (march.RK4Classic(), np.array([0.1, 0.05, 0.025, 0.0125])),
}
for name, (solver, steps) in cases.items():
    # local: one step from x(0) = 1 against exp(γh)
    # ε_loc(h) = |x̂₁ − exp(−h)|
    local = [
        abs(float(one_step(solver, decay, jnp.asarray(1.0), h)) - np.exp(-h))
        for h in steps
    ]
    # global: K = T/h steps against exp(γT)
    # ε_glob(h) = |x̂_K − exp(−1)|
    global_ = [abs(float(final_state(solver, h)) - np.exp(-1.0)) for h in steps]
    # q_loc = slope of log ε_loc against log h
    local_slope = np.polyfit(np.log(steps), np.log(local), 1)[0]
    # q_glob = slope of log ε_glob against log h
    global_slope = np.polyfit(np.log(steps), np.log(global_), 1)[0]
    print(f"{name:11s} local slope {local_slope:.2f}, global slope {global_slope:.2f}")
RK2Heun     local slope 3.00, global slope 2.01
RK3SSP      local slope 4.00, global slope 3.01
RK4Classic  local slope 4.99, global slope 4.03

Each method loses exactly one power of hh between one step and the whole run, which is the relation in (7.4), and the global slopes are the orders in Table 7.1. It is the same global and local bookkeeping as in chapter 3, now in time: the error is made locally, one step at a time, and judged globally, at the end. Chapter 8 uses the local error of each step to choose the step size against a global tolerance.

Stability: the other half

Quadrature has no counterpart to stability, because a rule’s samples do not feed back into the integrand. A stepper’s do. On the test problem x˙=γx\dot{x} = \gamma x, one step multiplies the state by a stability function R(ζ)R(\zeta) of ζ=hγ\zeta = h \gamma, which for an explicit Runge–Kutta method is a polynomial: R(ζ)=1+ζR(\zeta) = 1 + \zeta for Euler, and the Taylor series of eζe^\zeta up to ζ4\zeta^4 for RK4. The step is stable when ∣R(hγ)∣≤1|R(h \gamma)| \le 1 for every eigenvalue γ\gamma of the linearised tendency, so stability limits hh even when accuracy would allow a larger step.

The global and local thread shows up once more. For advection on a grid, each cell has its own limit, h≤Δs/∣u∣h \le \Delta s / |u| for a speed uu and spacing Δs\Delta s (the CFL condition), and diffusion with diffusivity KK adds h≤Δs2/2Kh \le \Delta s^2 / 2K. These are local conditions, cell by cell, but the model takes one global step, so the most restrictive cell sets the step for the whole domain. stable_step computes that bound. An ocean column with 10 km horizontal cells and 1 m s⁻¹ currents allows a step of about three hours, but adding vertical diffusion of 10-2 m² s⁻¹ on a 1 m vertical grid cuts it to under a minute.

# Shapes: 2 axes (horizontal, vertical), one cell size, speed and diffusivity each
# today (integrix)
# h_max = 1 / (∑ᵢ |uᵢ| / Δsᵢ + 2 ∑ᵢ Kᵢ / Δsᵢ²)
advection_only = march.stable_step((10_000.0,), speed=(1.0,))   # → ()
# today (integrix)
# h_max = 1 / (∑ᵢ |uᵢ| / Δsᵢ + 2 ∑ᵢ Kᵢ / Δsᵢ²)
with_diffusion = march.stable_step(                             # → ()
    (10_000.0, 1.0), speed=(1.0, 0.0), diffusivity=(0.0, 1e-2)
)
print(f"advection only:            h_max = {float(advection_only):.0f} s")
print(f"with vertical diffusion:   h_max = {float(with_diffusion):.1f} s")
advection only:            h_max = 10000 s
with vertical diffusion:   h_max = 49.8 s

This is why the vertical diffusion goes into the implicit half of an IMEX scheme. IMEX_SSP2 treats the explicit term with an SSP Runge–Kutta tableau and the stiff term with an A-stable implicit one (∣R(ζ)∣≤1|R(\zeta)| \le 1 for every ζ\zeta with a negative real part), so the step is set by the advection alone. Three more stability ideas complete the set in integrix.march. SSP methods keep a property of forward Euler, such as no new extrema in a tracer, under a step-size bound. The leapfrog step has a second, computational mode that flips sign every step, which the Robert–Asselin filter damps at the cost of first-order accuracy. The split-explicit step subcycles the fast mode with small steps so that the slow mode can take large ones.

Semi-Lagrangian advection: integrate along the flow

A tracer q(t,x)q(t, \vect{x}) carried by a velocity u(t,x)\vect{u}(t, \vect{x}) obeys ∂tq+u⋅∇q=0\partial_t q + \vect{u} \cdot \nabla q = 0, so it is constant along the characteristics X˙=u(t,X)\dot{\vect{X}} = \vect{u}(t, \vect{X}). A semi-Lagrangian step uses that directly. The new value at a node x\vect{x} is the old value at the departure point xd\vect{x}_d, the point that the flow carries to x\vect{x} in one step,

q(t+h,x)=q(t,xd), where xd=x−∫tt+hu(s,X(s))dsq(t + h, \vect{x}) = q(t, \vect{x}_d), \text{ where } \vect{x}_d = \vect{x} - \int_t^{t+h} \vect{u}(s, \vect{X}(s)) \mathrm{d}s

The integral is a march again, now along the trajectory instead of over the state. departure_points takes it with the midpoint rule at the middle of the trajectory, solved by fixed-point iteration from one Euler step,

xd(k+1)=x−hu(t+h2,x+xd(k)2)\vect{x}_d^{(k+1)} = \vect{x} - h \vect{u}\left(t + \frac{h}{2}, \frac{\vect{x} + \vect{x}_d^{(k)}}{2}\right)

which is second order in hh after one iteration; with none it is the first-order Euler point x−hu(t,x)\vect{x} - h \vect{u}(t, \vect{x}). Reading qq at xd\vect{x}_d is an interpolation, which functax owns, so semi_lagrangian_step takes the read-out as an argument. The step only reads the old field, so it has no CFL limit. The read-out sets the accuracy instead, because the field is interpolated once per step: for a read-out of order pp on a spacing Δs\Delta s, the error over a fixed time is O(h2)+O(Δsp+1/h)O(h^2) + O(\Delta s^{p+1} / h). Long steps are cheap, and a low-order read-out loses accuracy at every one of them.

# Shapes: N = 128 periodic nodes on [0, 1), D = 1; K = 200 steps at CFL 0.37
from functax.geometry import Axis, Points
from functax.interp import BSpline, Linear

nodes_1d = jnp.arange(128) / 128                                  # → (128,)
periodic = Axis(nodes_1d, period=1.0)
nodes = einx.id("node -> node 1", nodes_1d)                       # → (128, 1)
step_size = 0.37 / 128


def tracer(s):
    # q₀(s) = exp(−((s − ½) / 0.05)²), periodic
    return jnp.exp(-(((s - 0.5 + 0.5) % 1.0 - 0.5) / 0.05) ** 2)


def advect(scheme):
    def readout(departure):
        # today (functax)
        # the old field read at x_d
        return scheme.plan(periodic, Points(departure))

    def body(q, k):
        # today (integrix)
        # q(t + h, x) = q(t, x_d)
        q_new = march.semi_lagrangian_step(
            q, nodes, lambda t, p: jnp.ones_like(p), readout, k * step_size, step_size
        )
        return q_new, None

    q, _ = jax.lax.scan(body, tracer(nodes_1d), jnp.arange(200.0))  # → (128,)
    return q


for name, scheme in [("linear", Linear()), ("cubic B-spline", BSpline(3))]:
    print(f"{name:15s} peak {float(advect(scheme).max()):.3f}")
linear          peak 0.552
cubic B-spline  peak 0.997

The exact peak is 1. The linear read-out keeps 55 % of it after 200 steps, while the cubic B-spline (SciPy’s order-3 spline) keeps 99.7 %. A linear read-out never leaves the old field’s range, but a cubic one can overshoot it; functax’s Pchip is the monotone choice. SemiLagrangianSolver runs the same step under diffeqsolve, with the characteristic equation as its term.

Sampled forcing: a tendency known at samples

A forced model x˙=f(x,t)+u(t)\dot{\vect{x}} = f(\vect{x}, t) + \vect{u}(t) often knows its forcing u(t)∈RDx\vect{u}(t) \in \mathbb{R}^{D_x} (not the velocity of the last section) only at the samples uj=u(tˉj)\vect{u}_j = \vect{u}(\bar{t}_j), such as six-hourly reanalysis winds or daily river discharge. The stages of a step read the forcing at tk+ciht_k + c_i h, between the sample times tˉj\bar{t}_j, so the samples must first become a function u^(t)\hat{\vect{u}}(t). This is the interpolation of chapter 4, now in time, and functax owns it: on the interval [tˉj,tˉj+1][\bar{t}_j, \bar{t}_{j+1}] of width Δj\Delta_j, at the offset τ=(t−tˉj)/Δj\tau = (t - \bar{t}_j) / \Delta_j, the linear scheme is

u^(t)=(1−τ)uj+τuj+1\hat{\vect{u}}(t) = (1 - \tau) \vect{u}_j + \tau \vect{u}_{j+1}

and every cubic one is the Hermite form

u^(t)=φ00(τ)uj+φ10(τ)Δjdj+φ01(τ)uj+1+φ11(τ)Δjdj+1\hat{\vect{u}}(t) = \varphi_{00}(\tau) \vect{u}_j + \varphi_{10}(\tau) \Delta_j \vect{d}_j + \varphi_{01}(\tau) \vect{u}_{j+1} + \varphi_{11}(\tau) \Delta_j \vect{d}_{j+1}

with φ00=2τ3−3τ2+1\varphi_{00} = 2 \tau^3 - 3 \tau^2 + 1, φ10=τ3−2τ2+τ\varphi_{10} = \tau^3 - 2 \tau^2 + \tau, φ01=3τ2−2τ3\varphi_{01} = 3 \tau^2 - 2 \tau^3 and φ11=τ3−τ2\varphi_{11} = \tau^3 - \tau^2. The schemes differ only in the slopes dj\vect{d}_j at the samples, and through them in how smooth u^\hat{\vect{u}} is (Table 7.2).

Table 7.2:The slopes of each reconstruction of the samples, with the secants δj=(uj+1−uj)/Δj\gvect{\delta}_j = (\vect{u}_{j+1} - \vect{u}_j) / \Delta_j.

SchemeSlopes dj\vect{d}_jContinuityWhat it keeps
LinearnoneC0C^0the range of the neighbouring samples
diffrax’s backward Hermiteδj−1\gvect{\delta}_{j-1}C1C^1causality: an interval reads no sample past its end
Pchipa weighted harmonic mean of δj−1\gvect{\delta}_{j-1} and δj\gvect{\delta}_j, 0 at a local extremumC1C^1the range of the neighbouring samples, so a discharge stays non-negative
CubicSplinea tridiagonal solve that makes u^¨\ddot{\hat{\vect{u}}} continuousC2C^2cubics

SampledPath is the fitted u^\hat{\vect{u}} as a diffrax path. Its evaluate(t) goes into a vector field, and its increments u^(tk+1)−u^(tk)\hat{\vect{u}}(t_{k+1}) - \hat{\vect{u}}(t_k) drive a controlled differential equation dx=f(x)du^(t)\mathrm{d}\vect{x} = f(\vect{x}) \mathrm{d}\hat{\vect{u}}(t) through diffrax.ControlTerm.

The reconstruction is smooth only between the samples, and that limits the order of the march. A step that straddles a sample where u^\hat{\vect{u}} is only CrC^r has local error O(hr+2)O(h^{r+2}), so with a fixed number of samples the global error is O(hr+2)+O(hq)O(h^{r+2}) + O(h^q) for a method of order qq, instead of O(hq)O(h^q). We integrate the linear interpolant of sin⁡t\sin t, sampled every ½, by RK4, with steps that land on the samples and with steps that do not.

# Shapes: N_t = 9 samples of one channel, K steps
from functax.interp import Linear

sample_times = jnp.linspace(0.0, 4.0, 9)                          # → (9,)
samples = jnp.sin(sample_times)                                   # → (9,)
# today (integrix)
# û(t) = (1 − τ) uⱼ + τ uⱼ₊₁
forcing = march.SampledPath.fit(Linear(), sample_times, samples)  # → path
# ∫₀⁴ û dt, exactly: the trapezoid sum of a linear interpolant
exact = jnp.trapezoid(samples, sample_times)                      # → ()


def forced_error(n_steps):
    term = dfx.ODETerm(lambda t, x, args: forcing.evaluate(t))
    # today (integrix)
    # ẋ = û(t), in K equal steps
    solution = dfx.diffeqsolve(
        term, march.RK4Classic(), 0.0, 4.0, 4.0 / n_steps, jnp.array(0.0)
    )
    return abs(float(solution.ys[-1] - exact))


on_samples = max(forced_error(n) for n in (8, 16, 32))
counts = [15, 31, 63]
straddling = [forced_error(n) for n in counts]
slope = np.polyfit(np.log([4.0 / n for n in counts]), np.log(straddling), 1)[0]
print(f"steps on the samples:   error below 1e-14: {on_samples < 1e-14}")
print(f"steps across them:      error {straddling[0]:.1e} to {straddling[-1]:.1e}")
print(f"                        observed order {slope:.2f}")
steps on the samples:   error below 1e-14: True
steps across them:      error 1.3e-03 to 7.6e-05
                        observed order 2.00

RK4 integrates each linear piece exactly, so the error is at rounding when the steps land on the samples. When they straddle them, the fourth-order method is second order. So the samples should be step times: imex_stepsize_controller(step_ts=forcing.ts) does this for adaptive steps, and a fixed step should divide the sample spacing.

Two rules from functax matter here. A solver’s last stage can land a rounding error past the last sample, where functax’s default is NaN, so SampledPath holds the end values instead; Policies(outside="extrapolate") continues the end interval, as diffrax’s paths do. And Cubic and BSpline read in index space, so they refuse unevenly spaced times, for which CubicSpline and Pchip are the smooth choices.

Probabilistic solvers: a Gaussian over the solution

Every stepper so far returns one solution and says nothing about its error, which we can only estimate by solving again with a smaller step. A probabilistic ODE solver returns a Gaussian instead: its mean is a classical solution, and its covariance estimates the error of the time stepping as the solver goes. integrix has one, the ODE filter ODEFilter, the method of Schober, Särkkä and Hennig (2019) with the stable implementation of Krämer and Hennig (2024).

The solver tracks ξ(t)=[x;x˙;… ;x(q)]\gvect{\xi}(t) = [\vect{x}; \dot{\vect{x}}; \dots; \vect{x}^{(q)}], the state and its first qq derivatives, (q+1)Dx(q + 1) D_x numbers. Its prior is a qq-times integrated Wiener process, so between steps x(q)\vect{x}^{(q)} is a random walk and the lower derivatives are its integrals. At each step tkt_k the solver predicts ξk\gvect{\xi}_k under this prior and then conditions it on the ODE itself, observed as a residual that must be zero,

rk=E1ξk−f(tk,E0ξk)=0\vect{r}_k = \mat{E}_1 \gvect{\xi}_k - f(t_k, \mat{E}_0 \gvect{\xi}_k) = \vect{0}

where E0\mat{E}_0 and E1\mat{E}_1 select x\vect{x} and x˙\dot{\vect{x}} from ξ\gvect{\xi}. The residual is nonlinear in ξ\gvect{\xi}, so it is linearised at the predicted mean: EK1 keeps the Jacobian Jf\mat{J}_f, EK0 drops it, and the update becomes one Kalman step with no observation noise. This is a Kalman filter with the ODE in place of data, and its steps are gaussx’s square-root predict and update, so no covariance is ever formed. The start ξ0\gvect{\xi}_0 comes from x0\vect{x}_0 by Taylor-mode differentiation (taylor_coefficients), and the steps run in coordinates scaled by hh, where the prior’s transition does not depend on the step.

The prior’s scale σ\sigma sets the size of the covariance, and nothing in the prior knows it. The default calibration estimates it by maximum likelihood from the whitened residuals, σ^2=1KDx∑krk⊤Sk−1rk\hat{\sigma}^2 = \frac{1}{K D_x} \sum_k \vect{r}_k^\top \mat{S}_k^{-1} \vect{r}_k, with Sk\mat{S}_k the residual’s predicted covariance; a dynamic calibration re-estimates it at each step instead (Bosch, Hennig and Tronarp 2021). We solve Lorenz-63 for two time units and compare with RK4 at a step a hundred times smaller.

# Shapes: D_x = 3 and q = 3, so ξ has 12 coefficients; K = 200 steps of h = 0.01
def lorenz63(t, x, args):
    sigma, rho, beta = 10.0, 28.0, 8.0 / 3.0
    return jnp.stack(
        [sigma * (x[1] - x[0]), x[0] * (rho - x[2]) - x[1], x[0] * x[1] - beta * x[2]]
    )


x0 = jnp.array([1.0, 1.0, 1.0])                                   # → (3,)
every_step = dfx.SaveAt(steps=True)
# today (integrix)
# ξ = [x; ẋ; ẍ; x⃛], conditioned on ẋ − f(x) = 0 at each step
solver = march.ODEFilter(num_derivatives=3)
states = march.run(solver, lorenz63, 0.0, x0, 0.01, 200, saveat=every_step)
# today (integrix)
# σ̂ of the whole march at every step
posterior = solver.solution(states)                               # → mean (200, 12)
# today (integrix)
# the reference: RK4 at h / 100, every 100th step
fine = march.run(
    march.RK4Classic(), lorenz63, 0.0, x0, 1e-4, 20_000, saveat=every_step
)[99::100]                                                        # → (200, 3)
error = jnp.abs(posterior.mean[:, :3] - fine)                     # → (200, 3)
std = posterior.std[:, :3]                                        # → (200, 3)
print(f"largest error         {float(jnp.max(error)):.1e}")
print(f"largest std           {float(jnp.max(std)):.1e}")
print(f"errors within 2 std   {float(jnp.mean(error < 2.0 * std)):.0%}")
largest error         1.1e-03
largest std           3.3e-03
errors within 2 std   100%

The standard deviation is the right size: every error lies within two standard deviations, and the largest standard deviation is three times the largest error. With fixed steps the maximum-likelihood scale errs on the safe side, and over many initial conditions the normalised errors have a variance well below one. strategy="smoother" conditions each state on every residual, before and after it, and keeps the backward conditional p(ξk−1∣ξk)p(\gvect{\xi}_{k-1} \mid \gvect{\xi}_k) of each step as arrays; that chain is the posterior as a Gauss–Markov process run backwards, which a likelihood for an ODE’s parameters reads.

Local stencils and global transforms in space

Finally, the tendency ff itself sits on one side of chapter 3 or the other. In a finite-volume model it is a local stencil: each cell’s tendency reads a few neighbours, and its Jacobian is sparse. In a spectral model it is a global transform: each tendency goes through spherical harmonics or Fourier modes, and every point depends on every other. integrix does not care which, since the steppers only call ff, so the same RK3SSP can step a finite-volume tendency or a spectral one.