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 evolve as , where is the tendency (the right-hand side), and take steps of size between times . Integrating both sides over one step gives
which is exact, so every one-step method is a way of approximating the integral on the right with samples of . This is why 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 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 stages predicts the state at stage times , samples the tendency there and sums the samples with weights ,
where are the stage tendencies and , , the Butcher coefficients. If does not depend on , the stages are just samples of in time and (7.2) becomes
which is a rule on with nodes and weights , scaled by . 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 and weights on , and the order of the full method.
| Stepper | Nodes | Weights | Rule | Order |
|---|---|---|---|---|
ForwardEulerDfx | 0 | 1 | left rectangle | 1 |
RK2Heun, SSP_RK2 | trapezoid | 2 | ||
RK3SSP | Simpson | 3 | ||
RK4Classic | Simpson, midpoint sampled twice | 4 | ||
SSP_RK104 | ten stages (Ketcheson, 2008) | 4 |
The order conditions of a Runge–Kutta method start with exactly these quadrature conditions, for (the moment equations of (2.3) on ), and add conditions on the for the coupling through (Hairer et al., 1993). So a method of order needs a rule of degree at least . We can measure each stepper’s degree directly, by taking one step of on from , where the exact answer is .
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 3Euler 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, 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 , 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 as Gauss–Legendre nodes gives the implicit Gauss collocation methods, of order ; 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 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 , the nodes are , the interval is , and the weights solve the moment equations (2.3) with .
# 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] / 12These 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, , 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 , then after steps to a fixed end time the global error is
one power of lower, since there are steps and the dynamics carry each local error forward without blowing it up (for a stable problem). The order 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 with to and fits the slope of error against . 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.03Each method loses exactly one power of 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 , one step multiplies the state by a stability function of , which for an explicit Runge–Kutta method is a polynomial: for Euler, and the Taylor series of up to for RK4. The step is stable when for every eigenvalue of the linearised tendency, so stability limits 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, for a speed and spacing (the CFL condition), and diffusion with diffusivity adds . 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 sThis 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 ( for every 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 carried by a velocity obeys , so it is constant along the characteristics . A semi-Lagrangian step uses that directly. The new value at a node is the old value at the departure point , the point that the flow carries to in one step,
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,
which is second order in after one iteration; with none it is the first-order Euler point . Reading at 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 on a spacing , the error over a fixed time is . 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.997The 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 often knows its forcing (not the velocity of the last section) only at the samples , such as six-hourly reanalysis winds or daily river discharge. The stages of a step read the forcing at , between the sample times , so the samples must first become a function . This is the interpolation of chapter 4, now in time, and functax owns it: on the interval of width , at the offset , the linear scheme is
and every cubic one is the Hermite form
with , , and . The schemes differ only in the slopes at the samples, and through them in how smooth is (Table 7.2).
Table 7.2:The slopes of each reconstruction of the samples, with the secants .
| Scheme | Slopes | Continuity | What it keeps |
|---|---|---|---|
Linear | none | the range of the neighbouring samples | |
| diffrax’s backward Hermite | causality: an interval reads no sample past its end | ||
Pchip | a weighted harmonic mean of and , 0 at a local extremum | the range of the neighbouring samples, so a discharge stays non-negative | |
CubicSpline | a tridiagonal solve that makes continuous | cubics |
SampledPath is the fitted as a diffrax path. Its evaluate(t) goes into a vector field, and its increments drive a controlled differential equation 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 is only has local error , so with a fixed number of samples the global error is for a method of order , instead of . We integrate the linear interpolant of , 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.00RK4 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 , the state and its first derivatives, numbers. Its prior is a -times integrated Wiener process, so between steps is a random walk and the lower derivatives are its integrals. At each step the solver predicts under this prior and then conditions it on the ODE itself, observed as a residual that must be zero,
where and select and from . The residual is nonlinear in , so it is linearised at the predicted mean: EK1 keeps the Jacobian , 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 comes from by Taylor-mode differentiation (taylor_coefficients), and the steps run in coordinates scaled by , where the prior’s transition does not depend on the step.
The prior’s scale 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, , with 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 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 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 , so the same RK3SSP can step a finite-volume tendency or a spectral one.