Skip to content

Marches

A march steps a solution in time, \(\vect{y}_{n+1} = \Phi(\vect{y}_n, t_n, h)\). The single-step schemes are diffrax solvers (design decision 8), so diffrax.diffeqsolve runs them with its step-size controllers, SaveAt and adjoints. Schemes without an embedded error estimate (ForwardEulerDfx, RK4Classic, SSP_RK104, AB3Solver) run under constant steps only, and an adaptive controller raises. The schemes that carry history between steps (AB2Solver, LeapfrogRAFSolver, SplitExplicitRKSolver) are AbstractSteppers instead. run marches them with jax.lax.scan, keeping the history in the loop carry, never on the module, and it also accepts the diffrax solvers, so one entry point covers every stepper. Its adjoint= takes integrix.adjoint.Checkpointed or Truncated for long rollouts. Each scheme also has a pure step function for an autonomous right-hand side \(f(\vect{y})\).

For a model with a stiff term, imex_solver returns diffrax's KenCarp3 with a matrix-free Newton–GMRES implicit stage, imex_stepsize_controller the PID controller to run it under, and stable_step the forward-Euler CFL bound \(h \le \text{CFL} / (\sum_i \lvert u_i \rvert / \Delta x_i + 2 \sum_i K_i / \Delta x_i^2)\), which traces.

Semi-Lagrangian advection reads the old field at departure points: departure_points integrates the trajectory back from each node with the midpoint rule, \(\vect{x}_d = \vect{x} - h \vect{u}(t + h/2, (\vect{x} + \vect{x}_d)/2)\), and semi_lagrangian_step (or SemiLagrangianSolver under diffeqsolve) reads the field there with any functax interpolation plan the caller passes in. It has no CFL limit and no grid of its own.

SampledPath is a functax fit of samples \((t_k, \vect{u}_k)\) as a diffrax path, so any functax 1-D scheme can force an ODE or drive a CDE. A step that straddles a sample loses order there, so imex_stepsize_controller(step_ts=path.ts) makes the adaptive steps land on the samples.

DiffraxForwardModel is one diffeqsolve, of an ODE or an SDE, as a forward model: step(state, dt) for an assimilation cycle, and as_dynamics() with an explicit span for a filter. Its adjoint is a diffrax adjoint, or a pipekit-cycle spec that to_diffrax_adjoint resolves.

taylor_coefficients gives the state of an initial-value problem and its first \(q\) time derivatives at \(t_0\) by Taylor-mode automatic differentiation, which a probabilistic ODE solver needs to start from.

ODEFilter is that solver, an AbstractStepper for run: it conditions the state and its first \(q\) derivatives, under a \(q\)-times integrated Wiener prior, on the ODE's residual at each step, and returns a Gaussian over the solution whose covariance estimates the error of the time stepping. ODEFilter.solution turns the saved steps into the posterior, with the calibrated scale and, for the smoother, the backward chain as arrays (ODEFilterState). Its covariance is dense, or for a large state isotropic (EK0) or block-diagonal (EK0 or diagonal EK1), which cost a step linear in \(D_x\). Every Kalman step is gaussx's square-root form, and probdiffeq is its test oracle.

The steppers moved in from finitevolX at 82090a3, the IMEX solver and step control from sesmax-core at f08f59d, and DiffraxForwardModel from pipekit-jax at 5fb9a12, with their interfaces unchanged; the source libraries' tests run against them (gate G1-port).

The theory is in the Marches chapter of the mathematical reference.

march

Marches: time steppers, yₙ₊₁ = Φ(yₙ, tₙ, h).

The single-step schemes are diffrax solvers (design decision 8, #18), so diffrax.diffeqsolve, its step-size controllers and its adjoints run them: forward Euler, Heun, SSP-RK2, SSP-RK3, classical RK4, Ketcheson's SSP-RK(10,4), IMEX-SSP2 and AB3 (whose history lives in the solver state). The schemes that carry history between steps (AB2, leapfrog with a Robert–Asselin filter, and split-explicit) are AbstractSteppers, run by run with the history in the loop carry; run also takes the diffrax solvers. Each scheme comes with its pure step function for an autonomous right-hand side f(y). imex_solver, imex_stepsize_controller and stable_step (moved from sesmax-core) give a matrix-free IMEX solve, its step control and the explicit CFL bound. semi_lagrangian_step and SemiLagrangianSolver advect a field by reading it at departure points that departure_points integrates along the flow. SampledPath makes sampled data a diffrax path, to force an ODE or drive a CDE. DiffraxForwardModel is one diffrax solve as a forward model, for an assimilation cycle or a filter. taylor_coefficients gives an initial-value problem's first q derivatives by Taylor mode, and ODEFilter solves one probabilistically, returning a Gaussian whose covariance estimates the error.

RK3SSP

Bases: AbstractERK

Third-order strong-stability-preserving Runge–Kutta (Shu–Osher).

Order 3, three stages, SSP coefficient C = 1 (optimal): it keeps the monotonicity, positivity and TVD properties of forward Euler within the same CFL limit. The embedded second-order solution is Heun on the first two stages (b̂ = [½, ½, 0]), so adaptive controllers work.

Butcher tableau: c = (0, 1, ½), a₂₁ = 1, a₃₁ = a₃₂ = ¼, b = (⅙, ⅙, ⅔).

Examples:

>>> RK3SSP().order(None)
3

SSP_RK2

Bases: AbstractERK

Second-order SSP Runge–Kutta, the same scheme as RK2Heun.

Order 2, two stages, SSP coefficient C = 1, with an embedded forward-Euler error estimate.

Examples:

>>> SSP_RK2().order(None)
2

SSP_RK104

Bases: _FixedStepERK

Ketcheson's ten-stage, fourth-order SSP Runge–Kutta, fixed steps only.

Order 4, ten stages, SSP coefficient C = 6, the largest achievable at fourth order. There is no embedded error estimate, so an adaptive controller raises.

Examples:

>>> SSP_RK104().order(None)
4

ForwardEulerDfx

Bases: AbstractSolver

Forward Euler as a diffrax solver: yₙ₊₁ = yₙ + h F(tₙ, yₙ).

Order 1, one stage, no error estimate (fixed steps only). Included for completeness and parity with finitevolX; diffrax.Euler is the same scheme.

Examples:

>>> import diffrax as dfx
>>> import jax.numpy as jnp
>>> solution = dfx.diffeqsolve(
...     dfx.ODETerm(lambda t, y, args: -y),
...     ForwardEulerDfx(),
...     t0=0.0,
...     t1=1.0,
...     dt0=0.1,
...     y0=jnp.array(1.0),
... )
>>> bool(jnp.allclose(solution.ys[0], 0.9**10))
True

RK2Heun

Bases: AbstractERK

Heun's method (RK2), with an embedded forward-Euler error estimate.

Order 2, two stages, SSP with coefficient C = 1. The error weights are b̂ − b = [½, −½] (as diffrax.Heun), so adaptive controllers work.

Butcher tableau: c = (0, 1), a₂₁ = 1, b = (½, ½).

Examples:

>>> RK2Heun().order(None)
2

RK4Classic

Bases: _FixedStepERK

The classical fourth-order Runge–Kutta method, fixed steps only.

Order 4, four stages, not SSP. The tableau has no embedded lower-order solution, so an adaptive controller raises; diffrax.Tsit5 or diffrax.Dopri5 are the adaptive fourth- and fifth-order choices.

Butcher tableau: c = (0, ½, ½, 1), a₂₁ = a₃₂ = ½, a₄₃ = 1, b = (⅙, ⅓, ⅓, ⅙).

Examples:

>>> RK4Classic().order(None)
4

DiffraxForwardModel

Bases: Module

A forward model M: x(t₀) ↦ x(t₁) that one diffrax.diffeqsolve computes.

The state follows ẋ = f(t, x), or dx = f(t, x) dt + g(t, x) dW if a diffusion is given, whose Brownian path is a diffrax.VirtualBrownianTree over each span. step is autonomous: it integrates over [0, dt], because an assimilation cycle calls it with no absolute time. as_dynamics gives the form with an explicit span.

It satisfies pipekit-cycle's ForwardModel and SupportsAdjoint structurally, and filterax's dynamics slots take as_dynamics.

Parameters:

Name Type Description Default
vector_field

The drift f(t, x, args), in diffrax's convention.

required
solver

Any diffrax solver, the schemes of integrix.march included.

required
dt0

The first step of the solver, and every step under a constant one.

required
dt

The window length that the model advertises to a cycle.

required
adjoint

How a reverse-mode gradient goes through the solve: a diffrax adjoint, or a spec of pipekit-cycle that integrix.adjoint.to_diffrax_adjoint resolves.

required
stepsize_controller

The step-size controller; constant steps by default.

required
diffusion

g(t, x, args), which makes the solve an SDE: a linear map from the Brownian increment to the state, as lineax.DiagonalLinearOperator(sigma) for diagonal noise or an (N_x, N_w) matrix.

required
sde_key

The PRNG key of the Brownian path. It is fixed, so rebuild the model with another one (dataclasses.replace) for an independent path per window.

required
brownian_shape

The shape of the Brownian increment. None takes the state's, which is right for diagonal noise; pass (N_w,) for a matrix g.

required
max_steps

The largest number of steps of one solve.

required

Examples:

>>> import diffrax as dfx
>>> import jax.numpy as jnp
>>> model = DiffraxForwardModel(lambda t, x, args: -x, dt0=0.01)
>>> x0 = jnp.array([1.0, 2.0])
>>> bool(jnp.allclose(model.step(x0, 1.0), x0 * jnp.exp(-1.0), atol=1e-6))
True

An explicit span, and another adjoint:

>>> model = model.with_adjoint(dfx.BacksolveAdjoint())
>>> dynamics = model.as_dynamics()
>>> bool(jnp.allclose(dynamics(x0, 1.0, 3.0), x0 * jnp.exp(-2.0)))
True
state_signature property
state_signature: None

None: the model advertises no shape contract to a pipekit cycle.

step
step(state: Any, dt: Any) -> Any

The state after dt, integrated over [0, dt] (autonomous dynamics).

Parameters:

Name Type Description Default
state Any

x(0), an array or, for an ODE, a pytree of them.

required
dt Any

The length of the span.

required

Returns:

Type Description
Any

x(dt), in the structure of state.

Source code in src/integrix/_src/march/_forward_model.py
def step(self, state: Any, dt: Any) -> Any:
    """The state after dt, integrated over [0, dt] (autonomous dynamics).

    Args:
        state: x(0), an array or, for an ODE, a pytree of them.
        dt: The length of the span.

    Returns:
        x(dt), in the structure of ``state``.
    """
    return self._solve(state, jnp.zeros_like(jnp.asarray(dt)), dt)
with_adjoint
with_adjoint(spec: Any) -> DiffraxForwardModel

A copy of the model with another adjoint.

Parameters:

Name Type Description Default
spec Any

A diffrax adjoint, or a spec of pipekit-cycle.

required

Returns:

Type Description
DiffraxForwardModel

The copy.

Source code in src/integrix/_src/march/_forward_model.py
def with_adjoint(self, spec: Any) -> DiffraxForwardModel:
    """A copy of the model with another adjoint.

    Args:
        spec: A diffrax adjoint, or a spec of pipekit-cycle.

    Returns:
        The copy.
    """
    return dataclasses.replace(self, adjoint=spec)
as_dynamics
as_dynamics() -> Callable[[Any, Any, Any], Any]

The model as (state, t₀, t₁) ↦ state, with an explicit span.

Returns:

Type Description
Callable[[Any, Any, Any], Any]

The callable, for an API such as filterax's dynamics slots or a

Callable[[Any, Any, Any], Any]

4D-Var forward argument.

Source code in src/integrix/_src/march/_forward_model.py
def as_dynamics(self) -> Callable[[Any, Any, Any], Any]:
    """The model as (state, t₀, t₁) ↦ state, with an explicit span.

    Returns:
        The callable, for an API such as filterax's dynamics slots or a
        4D-Var ``forward`` argument.
    """
    return self._solve

IMEX_SSP2

Bases: AbstractRungeKutta, AbstractImplicitSolver

IMEX-SSP2(2,2,2) for a diffrax.MultiTerm of an explicit and an implicit term.

The explicit part is SSP with C = 1; the implicit part is A-stable SDIRK with γ = 1 − 1/√2. Order 2. The embedded first-order solution y + h (F_E(Y₁) + F_I(Y₁)) (b̂ = [1, 0] in both tableaux) gives the error estimate for adaptive step-size control. Dense output is linear between steps.

Explicit tableau: c = (0, 1), a₂₁ = 1, b = (½, ½). Implicit tableau: c = (γ, 1 − γ), a₁₁ = a₂₂ = γ, a₂₁ = 1 − 2γ, b = (½, ½).

With fixed steps, give the implicit root finder its own tolerances (IMEX_SSP2(root_finder=dfx.VeryChord(rtol=1e-8, atol=1e-8))); with a diffrax.PIDController, the default root finder takes the controller's.

Examples:

>>> import diffrax as dfx
>>> import jax.numpy as jnp
>>> terms = dfx.MultiTerm(
...     dfx.ODETerm(lambda t, y, args: -y),
...     dfx.ODETerm(lambda t, y, args: -10.0 * y),
... )
>>> solver = IMEX_SSP2(root_finder=dfx.VeryChord(rtol=1e-10, atol=1e-10))
>>> solution = dfx.diffeqsolve(
...     terms, solver, 0.0, 1.0, 0.01, jnp.array(1.0)
... )
>>> bool(jnp.allclose(solution.ys[0], jnp.exp(-11.0), rtol=1e-2))
True

AbstractStepper

Bases: Module

A fixed-step scheme whose history lives in the loop carry.

A stepper takes the diffrax vector field rhs(t, y, args), so a model writes its tendencies once for both kinds of stepper. init takes the first step, bootstrapping whatever history the scheme needs, and step takes every later one; neither mutates the module.

Examples:

>>> import jax.numpy as jnp
>>> class Euler(AbstractStepper):
...     @property
...     def order(self):
...         return 1
...
...     def init(self, rhs, t0, y0, dt, args):
...         return None, y0 + dt * rhs(t0, y0, args)
...
...     def step(self, rhs, t, y, dt, state, args):
...         return y + dt * rhs(t, y, args), state
>>> y = run(Euler(), lambda t, y, args: -y, 0.0, jnp.array(1.0), 0.1, 10)
>>> bool(jnp.allclose(y, 0.9**10))
True
order abstractmethod property
order: int

The global order of accuracy p, error O(hᵖ).

init abstractmethod
init(rhs: Any, t0: ScalarLike, y0: PyTree, dt: ScalarLike, args: Any) -> tuple[PyTree, PyTree]

Take the first step from (t₀, y₀): returns (state, y₁).

Source code in src/integrix/_src/march/_loop.py
@abc.abstractmethod
def init(
    self,
    rhs: Any,
    t0: ScalarLike,
    y0: PyTree,
    dt: ScalarLike,
    args: Any,
) -> tuple[PyTree, PyTree]:
    """Take the first step from (t₀, y₀): returns ``(state, y₁)``."""
step abstractmethod
step(rhs: Any, t: ScalarLike, y: PyTree, dt: ScalarLike, state: PyTree, args: Any) -> tuple[PyTree, PyTree]

Take one step from (tₙ, yₙ) with the history: returns (yₙ₊₁, state).

Source code in src/integrix/_src/march/_loop.py
@abc.abstractmethod
def step(
    self,
    rhs: Any,
    t: ScalarLike,
    y: PyTree,
    dt: ScalarLike,
    state: PyTree,
    args: Any,
) -> tuple[PyTree, PyTree]:
    """Take one step from (tₙ, yₙ) with the history: returns ``(yₙ₊₁, state)``."""

AB2Solver

Bases: AbstractStepper

Second-order Adams–Bashforth, run by integrix.march.run.

yₙ₊₁ = yₙ + (h/2)(3 fₙ − fₙ₋₁), one evaluation of the vector field per step. init bootstraps with one Heun step and keeps f(t₀, y₀) as the history; fixed, uniform steps only (variable steps break the weights).

Examples:

>>> import jax.numpy as jnp
>>> from integrix.march import run
>>> y = run(
...     AB2Solver(), lambda t, y, args: -y, 0.0, jnp.array(1.0), 0.01, 100
... )
>>> bool(jnp.allclose(y, jnp.exp(-1.0), rtol=1e-4))
True
order property
order: int

Second order.

init
init(rhs, t0, y0, dt, args)

Heun to y₁; the history is fₙ₋₁ = f(t₀, y₀).

Source code in src/integrix/_src/march/_multistep.py
def init(self, rhs, t0, y0, dt, args):
    """Heun to y₁; the history is fₙ₋₁ = f(t₀, y₀)."""
    f0, y1 = _heun_bootstrap(rhs, t0, y0, dt, args)
    return f0, y1
step
step(rhs, t, y, dt, state, args)

yₙ₊₁ = yₙ + (h/2)(3 fₙ − fₙ₋₁); the history becomes fₙ.

Source code in src/integrix/_src/march/_multistep.py
def step(self, rhs, t, y, dt, state, args):
    """yₙ₊₁ = yₙ + (h/2)(3 fₙ − fₙ₋₁); the history becomes fₙ."""
    f_curr = rhs(t, y, args)
    y_next = jax.tree.map(
        lambda yi, fi, fi_1: yi + (dt / 2.0) * (3.0 * fi - fi_1),
        y,
        f_curr,
        state,
    )
    return y_next, f_curr

AB3Solver

Bases: AbstractSolver

Third-order Adams–Bashforth as a diffrax solver, with an SSP-RK3 start.

yₙ₊₁ = yₙ + (h/12)(23 fₙ − 16 fₙ₋₁ + 5 fₙ₋₂), one evaluation of F per step. The two-level history lives in the diffrax solver state, and the first two steps are SSP-RK3 steps (a third-order bootstrap).

Fixed, uniform steps only (dt0=, or StepTo with equal spacing): the weights assume a constant step and there is no error estimate, so an adaptive controller raises. Order 3; dense output is linear.

Examples:

>>> import diffrax as dfx
>>> import jax.numpy as jnp
>>> solution = dfx.diffeqsolve(
...     dfx.ODETerm(lambda t, y, args: -y),
...     AB3Solver(),
...     t0=0.0,
...     t1=1.0,
...     dt0=0.01,
...     y0=jnp.array(1.0),
... )
>>> bool(jnp.allclose(solution.ys[0], jnp.exp(-1.0), rtol=1e-5))
True

LeapfrogRAFSolver

Bases: AbstractStepper

Leapfrog with a Robert–Asselin filter, run by integrix.march.run.

ỹₙ₊₁ = ȳₙ₋₁ + 2h F(tₙ, yₙ) and ȳₙ = yₙ + α (ȳₙ₋₁ − 2yₙ + ỹₙ₊₁): the filter damps the computational mode, which grows without it. Second order for α = 0 and first order for α > 0 (the Robert–Asselin degradation). init bootstraps with one Heun step and keeps y₀ as the history; fixed, uniform steps only.

Attributes:

Name Type Description
alpha float | Float[Array, '']

The filter coefficient α ≥ 0, typically 0.01 to 0.1. It is an array leaf, so it can be traced, vmapped over or differentiated; a Python or NumPy value is checked when the stepper is built.

Raises:

Type Description
ValidationError

If a concrete alpha is negative or not finite.

Examples:

>>> import jax.numpy as jnp
>>> from integrix.march import run
>>> stepper = LeapfrogRAFSolver(alpha=0.05)
>>> y = run(
...     stepper, lambda t, y, args: -y, 0.0, jnp.array(1.0), 0.001, 1000
... )
>>> bool(jnp.allclose(y, jnp.exp(-1.0), rtol=1e-3)), stepper.order
(True, 1)
order property
order: int

Second order without the filter, first order with it (or when traced).

init
init(rhs, t0, y0, dt, args)

Heun to y₁; the history is ȳ₀ = y₀.

Source code in src/integrix/_src/march/_multistep.py
def init(self, rhs, t0, y0, dt, args):
    """Heun to y₁; the history is ȳ₀ = y₀."""
    _, y1 = _heun_bootstrap(rhs, t0, y0, dt, args)
    return y0, y1
step
step(rhs, t, y, dt, state, args)

Leapfrog from the filtered ȳₙ₋₁, then filter yₙ; the history becomes ȳₙ.

Source code in src/integrix/_src/march/_multistep.py
def step(self, rhs, t, y, dt, state, args):
    """Leapfrog from the filtered ȳₙ₋₁, then filter yₙ; the history becomes ȳₙ."""
    f_curr = rhs(t, y, args)
    # ỹₙ₊₁ = ȳₙ₋₁ + 2h F(tₙ, yₙ)
    y_next = jax.tree.map(lambda yp, fc: yp + 2.0 * dt * fc, state, f_curr)
    # ȳₙ = yₙ + α (ȳₙ₋₁ − 2yₙ + ỹₙ₊₁)
    y_filtered = jax.tree.map(
        lambda yp, yc, yn: yc + self.alpha * (yp - 2.0 * yc + yn),
        state,
        y,
        y_next,
    )
    return y_next, y_filtered

ODEFilter

Bases: AbstractStepper

A probabilistic ODE solver: a Gaussian filter under an integrated Wiener prior.

ẋ = f(t, x, args),    ξ = [x; ẋ; …; x⁽q⁾] ~ q-times integrated Wiener prior
r_k = E₁ ξ_k − f(t_k, E₀ ξ_k) = 0 observed at each step t_k = t₀ + k h

with E₀ and E₁ selecting x and ẋ from ξ. Each step predicts ξ under the prior and conditions it exactly on the residual r_k linearised at the predicted mean. The mean converges at order q, and the covariance estimates its error once its scale σ is calibrated.

Algorithm
  1. init builds ξ₀ from x₀ and its first q derivatives by Taylor mode (taylor_coefficients), with zero covariance.
  2. Each step works in the preconditioned coordinates ξ̄ = T⁻¹ ξ of gaussx_infer.preconditioned_transition, where the transition F̄ and the noise Σ̄ do not depend on h.
  3. Linearise f at the predicted mean: J_f for "ek1", its diagonal for "diagonal_ek1", zero for "ek0".
  4. Predict with gaussx_infer.sqrt_kalman_predict and condition on r = 0 with gaussx_infer.sqrt_kalman_update (no observation noise), so no covariance is formed. Without a full Jacobian the dimensions decouple: "blockdiag" runs both steps per dimension, and "isotropic" (EK0) shares one factor across them.
  5. "mle" keeps the running mean of the whitened residuals σ̂² = (1 / (k D_x)) ∑ⱼ rⱼᵀ Sⱼ⁻¹ rⱼ; "dynamic" estimates σ̂_k² = r_kᵀ (H Σ_η Hᵀ)⁻¹ r_k / D_x from the predicted mean before each predict, and scales the process noise by it; "none" keeps output_scale.
  6. "smoother" also stores each step's backward conditional (gaussx_infer.sqrt_backward_conditional), and ODEFilter.solution runs gaussx_infer.sqrt_rts_step back through them.
Note

run returns the forward march: filtered states whose "mle" scale is the running estimate up to each step. ODEFilter.solution turns the saved steps into the posterior, with the final scale at every step and, for the smoother, the smoothed states. The "dynamic" scale passes no gradient, as in probdiffeq.

Attributes:

Name Type Description
num_derivatives int

The number of derivatives q ≥ 1 in the prior.

linearisation Literal['ek0', 'ek1', 'diagonal_ek1']

"ek1" (the Jacobian, for stiff and nonlinear problems), "ek0" (zero, explicit and cheapest) or "diagonal_ek1" (the Jacobian's diagonal).

strategy Literal['filter', 'smoother']

"filter" (each state conditioned on the residuals up to it) or "smoother" (on all of them).

calibration Literal['none', 'mle', 'dynamic']

"mle", "dynamic" or "none" (Bosch, Hennig and Tronarp 2021 compare them).

covariance Literal['dense', 'isotropic', 'blockdiag']

"dense" (any linearisation, O(D_x³) a step), "isotropic" (EK0 only, one factor for every dimension, linear in D_x) or "blockdiag" (EK0 or diagonal EK1, a factor and a scale per dimension, linear in D_x).

output_scale ScalarLike

The prior's fixed scale σ for "none".

Examples:

ẋ = −x from x₀ = 1: the mean follows e⁻ᵗ, and the standard deviation is small:

>>> import jax.numpy as jnp
>>> from diffrax import SaveAt
>>> from integrix.march import ODEFilter, run
>>> solver = ODEFilter(num_derivatives=3)
>>> states = run(
...     solver,
...     lambda t, x, args: -x,
...     0.0,
...     jnp.array([1.0]),
...     0.1,
...     10,
...     saveat=SaveAt(steps=True),
... )
>>> posterior = solver.solution(states)
>>> posterior.mean.shape
(10, 4)
>>> bool(jnp.allclose(posterior.mean[-1, 0], jnp.exp(-1.0), atol=1e-6))
True
>>> bool(posterior.std[-1, 0] < 1e-4)
True

The smoother also returns the backward chain, one conditional per step:

>>> smoother = ODEFilter(num_derivatives=3, strategy="smoother")
>>> states = run(
...     smoother,
...     lambda t, x, args: -x,
...     0.0,
...     jnp.array([1.0]),
...     0.1,
...     10,
...     saveat=SaveAt(steps=True),
... )
>>> smoother.solution(states).gain.shape
(10, 4, 4)
References

Schober, Särkkä and Hennig (2019), A probabilistic model for the numerical solution of initial value problems, Statistics and Computing 29(1). Krämer and Hennig (2024), Stable implementation of probabilistic ODE solvers, JMLR 25(111). Bosch, Hennig and Tronarp (2021), Calibrated adaptive probabilistic ODE solvers, AISTATS.

order property
order: int

The order q of the prior, the rate the mean is quoted with.

The tests measure q + 1 on smooth problems (a damped linear system, the logistic equation), for EK0 and EK1 alike.

init
init(rhs: Callable[..., Float[Array, ' state']], t0: ScalarLike, y0: Float[Array, ' state'], dt: ScalarLike, args: Any) -> tuple[None, ODEFilterState]

Build ξ₀ from x₀ by Taylor mode and take the first step: (None, y₁).

Source code in src/integrix/_src/march/_ode_filter.py
def init(
    self,
    rhs: Callable[..., Float[Array, " state"]],
    t0: ScalarLike,
    y0: Float[Array, " state"],
    dt: ScalarLike,
    args: Any,
) -> tuple[None, ODEFilterState]:
    """Build ξ₀ from x₀ by Taylor mode and take the first step: ``(None, y₁)``."""
    # [x₀; ẋ₀; …; x₀⁽q⁾], derivative first
    derivatives = taylor_coefficients(
        rhs, y0, t0, order=self.num_derivatives, args=args
    )
    mean = einx.id("derivative state -> (derivative state)", derivatives)
    dim = derivatives.shape[1]
    size = self.num_derivatives + 1
    # a known start: zero covariance, in the factor's shape
    chol_shape, scale_shape = {
        "dense": ((size * dim, size * dim), ()),
        "isotropic": ((size, size), ()),
        "blockdiag": ((dim, size, size), (dim,)),
    }[self.covariance]
    start_scale = {
        "none": self.output_scale,
        "mle": 0.0,
        "dynamic": 1.0,
    }[self.calibration]
    start = ODEFilterState(
        mean=mean,
        chol=jnp.zeros(chol_shape, dtype=mean.dtype),
        output_scale=jnp.full(scale_shape, start_scale, dtype=mean.dtype),
        num_steps=jnp.asarray(0),
        structure=self.covariance,
    )
    return None, self._step(rhs, t0, start, dt, args)
step
step(rhs: Callable[..., Float[Array, ' state']], t: ScalarLike, y: ODEFilterState, dt: ScalarLike, state: None, args: Any) -> tuple[ODEFilterState, None]

One predict–condition step from tₙ to tₙ + h: (yₙ₊₁, None).

Source code in src/integrix/_src/march/_ode_filter.py
def step(
    self,
    rhs: Callable[..., Float[Array, " state"]],
    t: ScalarLike,
    y: ODEFilterState,
    dt: ScalarLike,
    state: None,
    args: Any,
) -> tuple[ODEFilterState, None]:
    """One predict–condition step from tₙ to tₙ + h: ``(yₙ₊₁, None)``."""
    return self._step(rhs, t, y, dt, args), state
solution
solution(states: ODEFilterState) -> ODEFilterState

The posterior from the march run returns.

"mle" sets every step's scale to the final estimate σ̂, and "smoother" runs the RTS pass back through the stored backward conditionals, from the last filtered state:

μ_k|K = G_k+1 μ_k+1|K + b_k+1,    L_k|K = tria([G_k+1 L_k+1|K, L_b,k+1])

Parameters:

Name Type Description Default
states ODEFilterState

The states of every step, from run with saveat=SaveAt(steps=True); the filter also takes the final state alone.

required

Returns:

Type Description
ODEFilterState

The posterior at every step (or the final one), with the backward

ODEFilterState

chain unchanged.

Raises:

Type Description
ValidationError

If the smoother gets states that are not stacked over steps, or that carry no backward chain.

Source code in src/integrix/_src/march/_ode_filter.py
def solution(self, states: ODEFilterState) -> ODEFilterState:
    """The posterior from the march `run` returns.

    ``"mle"`` sets every step's scale to the final estimate σ̂, and
    ``"smoother"`` runs the RTS pass back through the stored backward
    conditionals, from the last filtered state:

        μ_k|K = G_k+1 μ_k+1|K + b_k+1,    L_k|K = tria([G_k+1 L_k+1|K, L_b,k+1])

    Args:
        states: The states of every step, from `run` with
            ``saveat=SaveAt(steps=True)``; the filter also takes the final
            state alone.

    Returns:
        The posterior at every step (or the final one), with the backward
        chain unchanged.

    Raises:
        ValidationError: If the smoother gets states that are not stacked
            over steps, or that carry no backward chain.
    """
    stacked = states.mean.ndim == 2
    if self.strategy == "smoother" and not stacked:
        raise ValidationError(
            "'states' must hold every step for the smoother: run with "
            "saveat=SaveAt(steps=True)"
        )
    if self.calibration == "mle" and stacked:
        # σ̂ of the whole march at every step
        final = jnp.broadcast_to(states.output_scale[-1], states.output_scale.shape)
        states = eqx.tree_at(lambda s: s.output_scale, states, final)
    if self.strategy == "filter":
        return states

    gain, offset, chol_backward = states.gain, states.offset, states.chol_backward
    if gain is None or offset is None or chol_backward is None:
        raise ValidationError(
            "'states' carry no backward chain: march them with this smoother"
        )
    rts_step = gaussx_infer.sqrt_rts_step
    size = self.num_derivatives + 1
    if self.covariance != "dense":
        # per dimension: means and offsets as (q + 1) × D_x columns
        factor_axis = None if self.covariance == "isotropic" else 0
        rts_step = jax.vmap(
            gaussx_infer.sqrt_rts_step,
            in_axes=(1, factor_axis, factor_axis, 1, factor_axis),
            out_axes=(1, factor_axis),
        )
        offset = einx.id("time (k d) -> time k d", offset, k=size)

    def back(carry, backward):
        # μ_k|K, L_k|K from step k + 1 and its backward conditional
        smoothed = rts_step(*carry, *backward)
        return smoothed, smoothed

    last_mean = states.mean[-1]
    if self.covariance != "dense":
        last_mean = einx.id("(k d) -> k d", last_mean, k=size)
    # the conditional stored at step k + 1 points back to step k
    chain = (gain[1:], offset[1:], chol_backward[1:])
    _, (means, chols) = jax.lax.scan(
        back, (last_mean, states.chol[-1]), chain, reverse=True
    )
    if self.covariance != "dense":
        means = einx.id("time k d -> time (k d)", means)
    mean = jnp.concatenate([means, states.mean[-1:]])
    chol = jnp.concatenate([chols, states.chol[-1:]])
    return eqx.tree_at(lambda s: (s.mean, s.chol), states, (mean, chol))

ODEFilterState

Bases: Module

The Gaussian over ξ = [x; ẋ; …; x⁽q⁾] at one step, or at every step.

ξ ~ 𝒩(μ, Σ),    Σ = σ² L Lᵀ (dense)
Σ = σ² (L Lᵀ ⊗ I_D_x) (isotropic),    Σ = ⊕_d σ_d² L_d L_dᵀ (blockdiag)

The coefficients are stacked derivative first: entries k D_x to (k + 1) D_x − 1 hold x⁽ᵏ⁾, so mean[..., :D_x] is the solution. run with saveat=SaveAt(steps=True) stacks every field on a leading time axis; ODEFilter.solution turns that march into the posterior. The factor's shape follows structure: one (q + 1) D_x square factor (dense), one (q + 1) square factor shared by every dimension (isotropic), or one per dimension, D_x × (q + 1) × (q + 1), with one scale each (blockdiag).

The last three fields are the backward conditional of the step that reached this state, p(ξ_k−1 | ξ_k) = 𝒩(G ξ_k + b, σ² L_b L_bᵀ), for the "smoother" strategy, and None for the "filter". The chain of them is the posterior as a Gauss–Markov process run backwards in time, which a likelihood for an ODE's parameters reads.

Attributes:

Name Type Description
mean Float[Array, '*time latent']

The mean μ, length (q + 1) D_x.

chol Float[Array, '*batch coefficient coefficient']

The lower-triangular factor L, or the factors L_d.

output_scale Float[Array, '*scales']

The scale σ of the covariance, one per dimension for "blockdiag": fixed ("none"), the running maximum-likelihood estimate ("mle"), or one ("dynamic", whose factor carries its local scales).

num_steps Int[Array, '*time']

The number of steps taken.

gain Float[Array, '*batch coefficient coefficient'] | None

The backward gain G (in the factor's shape), or None.

offset Float[Array, '*time latent'] | None

The backward offset b (in the mean's shape), or None.

chol_backward Float[Array, '*batch coefficient coefficient'] | None

The factor L_b of the backward noise, or None.

structure Literal['dense', 'isotropic', 'blockdiag']

"dense", "isotropic" or "blockdiag".

cov property
cov: Float[Array, '*time latent latent']

The dense covariance Σ, (q + 1) D_x square, whatever the structure.

std property
std: Float[Array, '*time latent']

The marginal standard deviations, √ of the covariance's diagonal.

SampledPath

Bases: AbstractPath

û(t), a functax fit of samples (t_k, u_k), read as a diffrax path.

û interpolates the samples in time with the scheme that fitted it. Force an ODE with it, ẋ = f(t, x) + û(t), by calling evaluate in the vector field, or drive a controlled differential equation dx = f(x) dû(t) with diffrax.ControlTerm, which reads the increments û(t₁) − û(t₀).

û has a kink at every t_k (a jump in û′ for functax.interp.Linear, in û″ for functax.interp.Pchip, in û‴ for functax.interp.CubicSpline), and a step that straddles a kink loses order. Pass ts to the step control (imex_stepsize_controller(step_ts=path.ts), or diffrax.ClipStepSizeController), or take fixed steps that divide the sample spacing.

Parameters:

Name Type Description Default
field

The functax field over the samples, with the samples on its last axis (fit builds it).

required

Examples:

Two channels sampled at uneven times:

>>> import jax.numpy as jnp
>>> from functax.interp import Linear, Policies
>>> ts = jnp.array([0.0, 1.0, 3.0])
>>> us = jnp.array([[0.0, 0.0], [1.0, 10.0], [5.0, 30.0]])
>>> path = SampledPath.fit(Linear(), ts, us)
>>> path.evaluate(2.0).tolist()
[3.0, 20.0]

An increment, and the derivative on either side of a sample:

>>> path.evaluate(1.0, 3.0).tolist()
[4.0, 20.0]
>>> left, right = path.derivative(1.0), path.derivative(1.0, left=False)
>>> bool(jnp.allclose(left, jnp.array([1.0, 10.0])))
True
>>> bool(jnp.allclose(right, jnp.array([2.0, 10.0])))
True

Past the samples the default holds the end values; a policy changes it:

>>> path.evaluate(4.0).tolist()
[5.0, 30.0]
>>> policies = Policies(outside="extrapolate")
>>> SampledPath.fit(Linear(), ts, us, policies=policies).evaluate(
...     4.0
... ).tolist()
[7.0, 40.0]

A forcing in an ODE, ẋ = û(t), with the steps on the samples:

>>> import diffrax as dfx
>>> from integrix.march import RK2Heun, imex_stepsize_controller
>>> solution = dfx.diffeqsolve(
...     dfx.ODETerm(lambda t, x, args: path.evaluate(t)),
...     RK2Heun(),
...     path.t0,
...     path.t1,
...     0.5,
...     jnp.zeros(2),
...     stepsize_controller=imex_stepsize_controller(step_ts=path.ts),
... )
>>> bool(jnp.allclose(solution.ys[0], jnp.array([6.5, 45.0])))
True
ts property
ts: Float[Array, ' sample']

The sample times t_k, where û has its kinks.

t0 property
t0: Float[Array, '']

The first sample time.

t1 property
t1: Float[Array, '']

The last sample time.

fit classmethod
fit(scheme: Any, ts: Float[Array, ' sample'], us: Float[Array, 'sample ...'], *, policies: Policies | None = None) -> SampledPath

The path that interpolates the samples with scheme.

The fit runs in JAX, so gradients reach both the samples and their times.

Parameters:

Name Type Description Default
scheme Any

A functax 1-D scheme: a functax.interp.LocalScheme (Linear, Cubic, BSpline, …) or a functax.interp.SeriesScheme (CubicSpline, Pchip, Akima, Steffen).

required
ts Float[Array, ' sample']

The sample times t_k, increasing, at least two.

required
us Float[Array, 'sample ...']

The samples u_k, time first.

required
policies Policies | None

functax's rules off the samples and at missing ones; Policies(outside="clamp") when None, since functax's own default reads NaN a rounding error past the last sample, where a solver's final stage can land.

None

Returns:

Type Description
SampledPath

The SampledPath.

Raises:

Type Description
ValidationError

If scheme is not a functax local or series scheme, there are fewer than two times, us does not have one sample per time, or concrete times decrease (traced ones are checked with equinox.error_if).

GeometryError

If the times are not strictly monotone, or uneven for a scheme that reads in index space (Cubic, and BSpline from order 2).

Source code in src/integrix/_src/march/_sampled_path.py
@classmethod
def fit(
    cls,
    # Any: a LocalScheme | SeriesScheme, checked below, so that a bad one
    # raises ValidationError before the type hook sees it
    scheme: Any,
    ts: Float[Array, " sample"],
    us: Float[Array, "sample ..."],
    *,
    policies: Policies | None = None,
) -> SampledPath:
    """The path that interpolates the samples with ``scheme``.

    The fit runs in JAX, so gradients reach both the samples and their
    times.

    Args:
        scheme: A functax 1-D scheme: a `functax.interp.LocalScheme`
            (`Linear`, `Cubic`, `BSpline`, …) or a
            `functax.interp.SeriesScheme` (`CubicSpline`, `Pchip`, `Akima`,
            `Steffen`).
        ts: The sample times t_k, increasing, at least two.
        us: The samples u_k, time first.
        policies: functax's rules off the samples and at missing ones;
            ``Policies(outside="clamp")`` when ``None``, since functax's
            own default reads NaN a rounding error past the last sample,
            where a solver's final stage can land.

    Returns:
        The `SampledPath`.

    Raises:
        ValidationError: If ``scheme`` is not a functax local or series
            scheme, there are fewer than two times, ``us`` does not have
            one sample per time, or concrete times decrease (traced ones
            are checked with `equinox.error_if`).
        functax.exceptions.GeometryError: If the times are not strictly
            monotone, or uneven for a scheme that reads in index space
            (`Cubic`, and `BSpline` from order 2).
    """
    if not isinstance(scheme, LocalScheme | SeriesScheme):
        raise ValidationError(
            "'scheme' must be a functax LocalScheme or SeriesScheme, got "
            f"{type(scheme).__name__}"
        )
    ts = jnp.asarray(ts)
    us = jnp.asarray(us)
    n_samples = ts.shape[0]
    if n_samples < 2:
        raise ValidationError(f"'ts' must have at least two times, got {n_samples}")
    if us.shape[0] != n_samples:
        raise ValidationError(
            f"'us' must have one sample per time, got shape {us.shape} for "
            f"{n_samples} times"
        )
    message = "'ts' must increase"
    if isinstance(ts, Tracer):
        ts = eqx.error_if(ts, ts[0] > ts[-1], message)
        axis = Axis(ts)
    else:
        # on the host: indexing a concrete array under jit stages a tracer
        first, last = np.asarray(ts)[[0, -1]]
        if first > last:
            raise ValidationError(f"{message}, got {first} to {last}")
        # concrete times stay concrete under jit, so functax can check them
        with jax.ensure_compile_time_eval():
            axis = Axis(ts)
    policies = Policies(outside="clamp") if policies is None else policies
    # functax keeps the samples on the last axis
    data = einx.id("sample ... -> ... sample", us)
    return cls(scheme.fit(axis, data, policies=policies))
evaluate
evaluate(t0: ScalarLike, t1: ScalarLike | None = None, left: bool = True) -> Float[Array, '*channel']

û(t0), or the increment û(t1) − û(t0) when t1 is given.

Parameters:

Name Type Description Default
t0 ScalarLike

The time.

required
t1 ScalarLike | None

The end of the increment, or None for a value.

None
left bool

Unused: û is continuous (functax.interp.Nearest, which jumps halfway between samples, is left-continuous there).

True

Returns:

Type Description
Float[Array, '*channel']

The value or the increment, in the dtype of the samples.

Source code in src/integrix/_src/march/_sampled_path.py
def evaluate(
    self, t0: ScalarLike, t1: ScalarLike | None = None, left: bool = True
) -> Float[Array, "*channel"]:
    """û(t0), or the increment û(t1) − û(t0) when ``t1`` is given.

    Args:
        t0: The time.
        t1: The end of the increment, or ``None`` for a value.
        left: Unused: û is continuous (`functax.interp.Nearest`, which
            jumps halfway between samples, is left-continuous there).

    Returns:
        The value or the increment, in the dtype of the samples.
    """
    del left
    if t1 is not None:
        # û(t₁) − û(t₀)
        return self.evaluate(t1) - self.evaluate(t0)
    return self._read(self.field, self._time(t0))
derivative
derivative(t: ScalarLike, left: bool = True) -> Float[Array, '*channel']

û′(t), from the closed-form derivative of the functax field.

At a sample time inside (t0, t1), where û′ may jump, the one-sided derivative is read 4 ε max(|t0|, |t1|) to that side, since functax reads whichever cell rounding puts the target in.

Parameters:

Name Type Description Default
t ScalarLike

The time.

required
left bool

Whether to read the left or the right derivative.

True

Returns:

Type Description
Float[Array, '*channel']

The derivative, in the dtype of the samples.

Source code in src/integrix/_src/march/_sampled_path.py
def derivative(self, t: ScalarLike, left: bool = True) -> Float[Array, "*channel"]:
    """û′(t), from the closed-form derivative of the functax field.

    At a sample time inside (t0, t1), where û′ may jump, the one-sided
    derivative is read 4 ε max(|t0|, |t1|) to that side, since functax
    reads whichever cell rounding puts the target in.

    Args:
        t: The time.
        left: Whether to read the left or the right derivative.

    Returns:
        The derivative, in the dtype of the samples.
    """
    time = self._time(t)
    # δ = 4 ε max(|t₀|, |t₁|), a few roundings of a time
    largest = jnp.maximum(jnp.abs(self.t0), jnp.abs(self.t1))
    rounding = 4.0 * jnp.finfo(self.ts.dtype).eps * largest
    signed_shift = -rounding if left else rounding
    # only between the ends, so the shift never crosses one
    inside = (time > self.t0 + rounding) & (time < self.t1 - rounding)
    shift = jax.lax.stop_gradient(jnp.where(inside, signed_shift, 0.0))
    side = time + shift.astype(time.dtype)
    return self._read(self.field.derivative(0), side)

SemiLagrangianSolver

Bases: AbstractSolver

Semi-Lagrangian advection as a diffrax solver.

q(tₙ₊₁, x) = q(tₙ, x_d),   x_d = x − h u(tₙ + h/2, (x + x_d)/2)

Run it under diffrax.diffeqsolve with a SemiLagrangianTerm and the field as y0. Order 2 in time with one midpoint iteration or more, order 1 with none (the read-out's spatial order is separate). There is no error estimate, so it runs with fixed steps only, and dense output is linear between steps.

Attributes:

Name Type Description
nodes Float[Array, 'node axis']

The arrival points x, N of them in D dimensions.

readout Readout

Departure points ↦ the map q ↦ q(x_d).

iterations int

The number of midpoint iterations of the trajectory.

Raises:

Type Description
ValidationError

If iterations is not a non-negative int.

Examples:

Two steps of a uniform flow with a linear read-out, against the exact translation:

>>> import diffrax as dfx
>>> import einx
>>> import jax.numpy as jnp
>>> from functax.geometry import Axis, Points
>>> from functax.interp import Linear
>>> x = jnp.arange(8) / 8
>>> axis = Axis(x, period=1.0)
>>> solver = SemiLagrangianSolver(
...     nodes=einx.id("node -> node 1", x),
...     readout=lambda x_d: Linear().plan(axis, Points(x_d)),
... )
>>> term = SemiLagrangianTerm(lambda t, p: jnp.ones_like(p))
>>> q0 = jnp.cos(2 * jnp.pi * x)
>>> solution = dfx.diffeqsolve(term, solver, 0.0, 0.25, 0.125, q0)
>>> bool(jnp.allclose(solution.ys[0], jnp.roll(q0, 2)))
True
References

Staniforth, A. and Côté, J. (1991). Semi-Lagrangian integration schemes for atmospheric models—a review. Mon. Weather Rev. 119(9), 2206–2223.

SemiLagrangianTerm

Bases: AbstractTerm

The characteristic equation Ẋ = u(t, X), as a diffrax term.

SemiLagrangianSolver integrates the characteristics backward from its nodes by calling velocity(t, x) at N points x itself. The field has no tendency, so vf(t, y, args) is a zero field shaped like y: it is what diffrax.diffeqsolve evaluates on y0 to check the term, and a velocity that only reads N points (a functax plan, say) never sees the field.

Attributes:

Name Type Description
velocity Velocity

The velocity u(t, x), evaluated at N points at once.

Examples:

>>> import jax.numpy as jnp
>>> term = SemiLagrangianTerm(lambda t, x: 2.0 * x)
>>> term.velocity(0.0, jnp.array([[1.0]])).tolist()
[[2.0]]
>>> term.vf(0.0, jnp.ones(3), None).tolist()
[0.0, 0.0, 0.0]

SplitExplicitRKSolver

Bases: AbstractStepper

Split-explicit stepping as an AbstractStepper, for integrix.march.run.

The state is the pair y = (y₃, y₂) of the slow and fast modes, and rhs is a SplitExplicitTerms. Each step is split_explicit_step with the fast mode in M RK4 substeps; M follows the external-wave CFL limit. The scheme carries no history, so init is a plain first step. First order in the slow step.

Attributes:

Name Type Description
n_substeps int

The number of fast substeps M ≥ 1 per slow step.

Raises:

Type Description
ValidationError

If n_substeps is below 1.

Examples:

>>> import jax.numpy as jnp
>>> from integrix.march import run
>>> terms = SplitExplicitTerms(
...     slow=lambda t, y3, mean_2d, args: -mean_2d,
...     fast=lambda t, y2, y3, args: 0.0 * y2,
... )
>>> slow, fast = run(
...     SplitExplicitRKSolver(n_substeps=5),
...     terms,
...     0.0,
...     (jnp.array(1.0), jnp.array(1.0)),
...     0.1,
...     10,
... )
>>> bool(jnp.allclose(slow, 0.0, atol=1e-6)), bool(fast == 1.0)
(True, True)
order property
order: int

First order in the slow step.

init
init(rhs, t0, y0, dt, args)

No history to bootstrap: the first step is an ordinary one.

Source code in src/integrix/_src/march/_split_explicit.py
def init(self, rhs, t0, y0, dt, args):
    """No history to bootstrap: the first step is an ordinary one."""
    y1, _ = self.step(rhs, t0, y0, dt, None, args)
    return None, y1
step
step(rhs, t, y, dt, state, args)

One split_explicit_step of the pair (y₃, y₂).

Source code in src/integrix/_src/march/_split_explicit.py
def step(self, rhs, t, y, dt, state, args):
    """One `split_explicit_step` of the pair (y₃, y₂)."""
    terms = _as_terms(rhs)
    state_3d, state_2d = y
    slow_forcing = None
    if terms.slow_forcing is not None:
        forcing_fn = terms.slow_forcing

        def slow_forcing(y3: PyTree) -> PyTree:
            return forcing_fn(t, y3, args)

    couple = terms.couple

    def couple_2d_to_3d(y3: PyTree, mean_2d: PyTree) -> PyTree:
        return y3 if couple is None else couple(y3, mean_2d, args)

    new_3d, new_2d = split_explicit_step(
        state_3d,
        state_2d,
        lambda y3, mean_2d: terms.slow(t, y3, mean_2d, args),
        lambda t_sub, y2, y3: terms.fast(t_sub, y2, y3, args),
        couple_2d_to_3d,
        dt,
        self.n_substeps,
        slow_forcing=slow_forcing,
        t0=t,
    )
    return (new_3d, new_2d), state

SplitExplicitTerms

Bases: Module

The vector fields of a split-explicit model, passed to run as rhs.

Attributes:

Name Type Description
slow Callable[..., PyTree]

The slow tendency slow(t, y_3d, mean_2d, args).

fast Callable[..., PyTree]

The fast tendency fast(t, y_2d, y_3d, args), at the absolute RK4 stage time t.

slow_forcing Callable[..., PyTree] | None

slow_forcing(t, y_3d, args), the baroclinic forcing of the barotropic mode, held fixed over the cycle; None for none.

couple Callable[..., PyTree] | None

couple(y_3d, mean_2d, args), applied after the slow step; None leaves the slow state as it is.

Examples:

>>> terms = SplitExplicitTerms(
...     slow=lambda t, y3, mean_2d, args: -y3,
...     fast=lambda t, y2, y3, args: -y2,
... )
>>> terms.couple is None
True

erk_step

erk_step(solver: AbstractERK, rhs: Callable[[Any, PyTree], PyTree], y: PyTree, t: Any, dt: Any) -> PyTree

One step of an explicit Runge–Kutta solver, unrolled from its tableau.

k_i = f(t + c_i h, y + h ∑_{j<i} a_ij k_j), y ← y + h ∑_i b_i k_i,

with a, b, c the solver's Butcher tableau. The stages are a Python loop over the tableau, so the program has s calls of f and no control flow, and both forward and reverse mode work inside a jax.lax.scan, where diffrax's solver.step supports one mode only. A weight that is exactly 0 is skipped, so a stage with weight 0 never reaches the sum.

Parameters:

Name Type Description Default
solver AbstractERK

An explicit Runge–Kutta solver, of integrix (RK4Classic, RK3SSP, …) or diffrax (diffrax.Tsit5, …), whose tableau is read.

required
rhs Callable[[Any, PyTree], PyTree]

The right-hand side f(t, y). t has the shape of t + dt.

required
y PyTree

The state, any pytree.

required
t Any

The time at the start of the step: a scalar, or one per element of the leading axes of every leaf.

required
dt Any

The step h, negative to step backward: a scalar, or one per element of the leading axes of every leaf, as t.

required

Returns:

Type Description
PyTree

The state after the step, with the dtypes of y.

Raises:

Type Description
ValidationError

If solver is not explicit Runge–Kutta.

Examples:

One step of the classical RK4 is rk4_step:

>>> import jax.numpy as jnp
>>> y = jnp.array([1.0, 2.0])
>>> moved = erk_step(RK4Classic(), lambda t, y: -y, y, 0.0, 0.1)
>>> bool(jnp.allclose(moved, rk4_step(y, lambda y: -y, 0.1)))
True

A step per element, of a time-dependent right-hand side; Heun's method integrates f(t) = t exactly:

>>> moved = erk_step(
...     RK2Heun(), lambda t, y: t, y, 1.0, jnp.array([0.5, 2.0])
... )
>>> moved.tolist()  # y + t h + h²/2
[1.625, 6.0]
Source code in src/integrix/_src/march/_erk.py
def erk_step(
    solver: dfx.AbstractERK,
    rhs: Callable[[Any, PyTree], PyTree],
    y: PyTree,
    t: Any,
    dt: Any,
) -> PyTree:
    """One step of an explicit Runge–Kutta solver, unrolled from its tableau.

    k_i = f(t + c_i h, y + h ∑_{j<i} a_ij k_j),  y ← y + h ∑_i b_i k_i,

    with a, b, c the solver's Butcher tableau. The stages are a Python loop over
    the tableau, so the program has s calls of f and no control flow, and both
    forward and reverse mode work inside a `jax.lax.scan`, where diffrax's
    ``solver.step`` supports one mode only. A weight that is exactly 0 is
    skipped, so a stage with weight 0 never reaches the sum.

    Args:
        solver: An explicit Runge–Kutta solver, of integrix (`RK4Classic`,
            `RK3SSP`, …) or diffrax (`diffrax.Tsit5`, …), whose tableau is read.
        rhs: The right-hand side f(t, y). ``t`` has the shape of ``t + dt``.
        y: The state, any pytree.
        t: The time at the start of the step: a scalar, or one per element of
            the leading axes of every leaf.
        dt: The step h, negative to step backward: a scalar, or one per element
            of the leading axes of every leaf, as ``t``.

    Returns:
        The state after the step, with the dtypes of ``y``.

    Raises:
        ValidationError: If ``solver`` is not explicit Runge–Kutta.

    Examples:
        One step of the classical RK4 is `rk4_step`:

        >>> import jax.numpy as jnp
        >>> y = jnp.array([1.0, 2.0])
        >>> moved = erk_step(RK4Classic(), lambda t, y: -y, y, 0.0, 0.1)
        >>> bool(jnp.allclose(moved, rk4_step(y, lambda y: -y, 0.1)))
        True

        A step per element, of a time-dependent right-hand side; Heun's method
        integrates f(t) = t exactly:

        >>> moved = erk_step(
        ...     RK2Heun(), lambda t, y: t, y, 1.0, jnp.array([0.5, 2.0])
        ... )
        >>> moved.tolist()  # y + t h + h²/2
        [1.625, 6.0]
    """
    if not isinstance(solver, dfx.AbstractERK):
        raise ValidationError(
            "'solver' must be explicit Runge–Kutta (diffrax.AbstractERK), got "
            f"{type(solver).__name__}"
        )
    # every explicit Runge–Kutta solver has one
    tableau = cast(dfx.ButcherTableau, solver.tableau)
    fractions = [float(tableau.c1), *(float(c) for c in tableau.c)]

    def combine(weights: Any, stages: list[PyTree]) -> PyTree:
        # y + h ∑_j w_j k_j
        used = [
            (float(weight), stage)
            for weight, stage in zip(weights, stages, strict=True)
            if float(weight) != 0.0
        ]

        def leaf_sum(leaf: Any, *ks: Any) -> Any:
            total = jnp.zeros_like(leaf)
            for (weight, _), k in zip(used, ks, strict=True):
                total = total + weight * k
            step = _broadcast_step(jnp.asarray(dt, leaf.dtype), leaf)
            return leaf + step * total

        return jax.tree.map(leaf_sum, y, *(stage for _, stage in used))

    stages: list[PyTree] = []
    for index, fraction in enumerate(fractions):
        before = [] if index == 0 else tableau.a_lower[index - 1]
        # k_i = f(t + c_i h, y + h ∑_{j<i} a_ij k_j)
        stage = rhs(t + fraction * dt, combine(before, stages))
        # in the state's dtypes
        stages.append(
            jax.tree.map(lambda k, leaf: jnp.asarray(k, leaf.dtype), stage, y)
        )
    # y ← y + h ∑_i b_i k_i
    return combine(tableau.b_sol, stages)

euler_step

euler_step(state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike) -> PyTree

One forward-Euler step: yₙ₊₁ = yₙ + h f(yₙ).

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
rhs_fn Callable[[PyTree], PyTree]

The autonomous right-hand side f(y).

required
dt ScalarLike

The step h.

required

Returns:

Type Description
PyTree

The state yₙ₊₁.

Examples:

>>> import jax.numpy as jnp
>>> bool(euler_step(jnp.array(1.0), lambda y: -y, 0.1) == 0.9)
True
Source code in src/integrix/_src/march/_erk.py
def euler_step(
    state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike
) -> PyTree:
    """One forward-Euler step: yₙ₊₁ = yₙ + h f(yₙ).

    Args:
        state: The state yₙ, any pytree.
        rhs_fn: The autonomous right-hand side f(y).
        dt: The step h.

    Returns:
        The state yₙ₊₁.

    Examples:
        >>> import jax.numpy as jnp
        >>> bool(euler_step(jnp.array(1.0), lambda y: -y, 0.1) == 0.9)
        True
    """
    k1 = rhs_fn(state)
    return jax.tree.map(lambda y, f: y + dt * f, state, k1)

heun_step

heun_step(state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike) -> PyTree

One Heun (RK2) step, order 2, SSP with C = 1.

k₁ = f(yₙ), k₂ = f(yₙ + h k₁), yₙ₊₁ = yₙ + (h/2)(k₁ + k₂).

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
rhs_fn Callable[[PyTree], PyTree]

The autonomous right-hand side f(y).

required
dt ScalarLike

The step h.

required

Returns:

Type Description
PyTree

The state yₙ₊₁.

Examples:

>>> import jax.numpy as jnp
>>> bool(jnp.allclose(heun_step(jnp.array(1.0), lambda y: -y, 0.1), 0.905))
True
Source code in src/integrix/_src/march/_erk.py
def heun_step(
    state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike
) -> PyTree:
    """One Heun (RK2) step, order 2, SSP with C = 1.

    k₁ = f(yₙ), k₂ = f(yₙ + h k₁), yₙ₊₁ = yₙ + (h/2)(k₁ + k₂).

    Args:
        state: The state yₙ, any pytree.
        rhs_fn: The autonomous right-hand side f(y).
        dt: The step h.

    Returns:
        The state yₙ₊₁.

    Examples:
        >>> import jax.numpy as jnp
        >>> bool(jnp.allclose(heun_step(jnp.array(1.0), lambda y: -y, 0.1), 0.905))
        True
    """
    k1 = rhs_fn(state)
    state_star = jax.tree.map(lambda y, f: y + dt * f, state, k1)
    k2 = rhs_fn(state_star)
    return jax.tree.map(lambda y, f1, f2: y + 0.5 * dt * (f1 + f2), state, k1, k2)

rk3_ssp_step

rk3_ssp_step(state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike) -> PyTree

One third-order SSP Runge–Kutta step in Shu–Osher form, C = 1.

y⁽¹⁾ = yₙ + h f(yₙ); y⁽²⁾ = ¾ yₙ + ¼ y⁽¹⁾ + ¼ h f(y⁽¹⁾); yₙ₊₁ = ⅓ yₙ + ⅔ y⁽²⁾ + ⅔ h f(y⁽²⁾).

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
rhs_fn Callable[[PyTree], PyTree]

The autonomous right-hand side f(y).

required
dt ScalarLike

The step h.

required

Returns:

Type Description
PyTree

The state yₙ₊₁.

Examples:

>>> import jax.numpy as jnp
>>> y = rk3_ssp_step(jnp.array(1.0), lambda y: -y, 0.1)
>>> bool(jnp.allclose(y, 1.0 - 0.1 + 0.1**2 / 2 - 0.1**3 / 6))
True
Source code in src/integrix/_src/march/_erk.py
def rk3_ssp_step(
    state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike
) -> PyTree:
    """One third-order SSP Runge–Kutta step in Shu–Osher form, C = 1.

    y⁽¹⁾ = yₙ + h f(yₙ); y⁽²⁾ = ¾ yₙ + ¼ y⁽¹⁾ + ¼ h f(y⁽¹⁾);
    yₙ₊₁ = ⅓ yₙ + ⅔ y⁽²⁾ + ⅔ h f(y⁽²⁾).

    Args:
        state: The state yₙ, any pytree.
        rhs_fn: The autonomous right-hand side f(y).
        dt: The step h.

    Returns:
        The state yₙ₊₁.

    Examples:
        >>> import jax.numpy as jnp
        >>> y = rk3_ssp_step(jnp.array(1.0), lambda y: -y, 0.1)
        >>> bool(jnp.allclose(y, 1.0 - 0.1 + 0.1**2 / 2 - 0.1**3 / 6))
        True
    """
    k1 = rhs_fn(state)
    y1 = jax.tree.map(lambda y, f: y + dt * f, state, k1)

    k2 = rhs_fn(y1)
    y2 = jax.tree.map(
        lambda y, y1_, f: 0.75 * y + 0.25 * y1_ + 0.25 * dt * f,
        state,
        y1,
        k2,
    )

    k3 = rhs_fn(y2)
    return jax.tree.map(
        lambda y, y2_, f: (1.0 / 3.0) * y + (2.0 / 3.0) * y2_ + (2.0 / 3.0) * dt * f,
        state,
        y2,
        k3,
    )

rk4_step

rk4_step(state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike) -> PyTree

One classical fourth-order Runge–Kutta step.

k₁ = f(yₙ), k₂ = f(yₙ + (h/2) k₁), k₃ = f(yₙ + (h/2) k₂), k₄ = f(yₙ + h k₃), yₙ₊₁ = yₙ + (h/6)(k₁ + 2k₂ + 2k₃ + k₄).

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
rhs_fn Callable[[PyTree], PyTree]

The autonomous right-hand side f(y).

required
dt ScalarLike

The step h.

required

Returns:

Type Description
PyTree

The state yₙ₊₁.

Examples:

>>> import jax.numpy as jnp
>>> y = rk4_step({"a": jnp.array(1.0)}, lambda y: {"a": -y["a"]}, 0.1)
>>> bool(jnp.allclose(y["a"], jnp.exp(-0.1), rtol=1e-6))
True
Source code in src/integrix/_src/march/_erk.py
def rk4_step(
    state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike
) -> PyTree:
    """One classical fourth-order Runge–Kutta step.

    k₁ = f(yₙ), k₂ = f(yₙ + (h/2) k₁), k₃ = f(yₙ + (h/2) k₂), k₄ = f(yₙ + h k₃),
    yₙ₊₁ = yₙ + (h/6)(k₁ + 2k₂ + 2k₃ + k₄).

    Args:
        state: The state yₙ, any pytree.
        rhs_fn: The autonomous right-hand side f(y).
        dt: The step h.

    Returns:
        The state yₙ₊₁.

    Examples:
        >>> import jax.numpy as jnp
        >>> y = rk4_step({"a": jnp.array(1.0)}, lambda y: {"a": -y["a"]}, 0.1)
        >>> bool(jnp.allclose(y["a"], jnp.exp(-0.1), rtol=1e-6))
        True
    """
    k1 = rhs_fn(state)
    y1 = jax.tree.map(lambda y, f: y + 0.5 * dt * f, state, k1)

    k2 = rhs_fn(y1)
    y2 = jax.tree.map(lambda y, f: y + 0.5 * dt * f, state, k2)

    k3 = rhs_fn(y2)
    y3 = jax.tree.map(lambda y, f: y + dt * f, state, k3)

    k4 = rhs_fn(y3)
    return jax.tree.map(
        lambda y, f1, f2, f3, f4: y + (dt / 6.0) * (f1 + 2.0 * f2 + 2.0 * f3 + f4),
        state,
        k1,
        k2,
        k3,
        k4,
    )

imex_ssp2_step

imex_ssp2_step(state: PyTree, rhs_explicit: Callable[[PyTree], PyTree], rhs_implicit: Callable[[PyTree], PyTree], implicit_solve: Callable[[PyTree, ScalarLike], PyTree], dt: ScalarLike) -> PyTree

One IMEX-SSP2(2,2,2) step, with the caller's implicit solve.

Second order in the explicit part, the implicit part and the coupled split (the implicit row (1 − 2γ, γ) gives ∑ᵢ bᵢ cᵢ = ½).

Algorithm
  1. Y₁ = yₙ + γh f_I(Y₁): implicit_solve(yₙ, γh).
  2. Y₂ = yₙ + h f_E(Y₁) + (1 − 2γ) h f_I(Y₁), then Y₂ = Y₂ + γh f_I(Y₂): implicit_solve(Y₂*, γh).
  3. yₙ₊₁ = yₙ + (h/2)(f_E(Y₁) + f_E(Y₂)) + (h/2)(f_I(Y₁) + f_I(Y₂)).

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
rhs_explicit Callable[[PyTree], PyTree]

The non-stiff right-hand side f_E(y).

required
rhs_implicit Callable[[PyTree], PyTree]

The stiff right-hand side f_I(y).

required
implicit_solve Callable[[PyTree, ScalarLike], PyTree]

Solves Y − γh f_I(Y) = r for Y, given (r, γh); for vertical diffusion, a tridiagonal solve along columns.

required
dt ScalarLike

The step h.

required

Returns:

Type Description
PyTree

The state yₙ₊₁.

Examples:

>>> import jax.numpy as jnp
>>> y = imex_ssp2_step(
...     jnp.array(1.0),
...     lambda y: -y,
...     lambda y: -10.0 * y,
...     lambda r, gamma_dt: r / (1.0 + 10.0 * gamma_dt),
...     0.01,
... )
>>> bool(jnp.allclose(y, jnp.exp(-0.11), rtol=1e-4))
True
Source code in src/integrix/_src/march/_imex.py
def imex_ssp2_step(
    state: PyTree,
    rhs_explicit: Callable[[PyTree], PyTree],
    rhs_implicit: Callable[[PyTree], PyTree],
    implicit_solve: Callable[[PyTree, ScalarLike], PyTree],
    dt: ScalarLike,
) -> PyTree:
    """One IMEX-SSP2(2,2,2) step, with the caller's implicit solve.

    Second order in the explicit part, the implicit part and the coupled
    split (the implicit row (1 − 2γ, γ) gives ∑ᵢ bᵢ cᵢ = ½).

    Algorithm:
        1. Y₁ = yₙ + γh f_I(Y₁): ``implicit_solve(yₙ, γh)``.
        2. Y₂* = yₙ + h f_E(Y₁) + (1 − 2γ) h f_I(Y₁), then
           Y₂ = Y₂* + γh f_I(Y₂): ``implicit_solve(Y₂*, γh)``.
        3. yₙ₊₁ = yₙ + (h/2)(f_E(Y₁) + f_E(Y₂)) + (h/2)(f_I(Y₁) + f_I(Y₂)).

    Args:
        state: The state yₙ, any pytree.
        rhs_explicit: The non-stiff right-hand side f_E(y).
        rhs_implicit: The stiff right-hand side f_I(y).
        implicit_solve: Solves Y − γh f_I(Y) = r for Y, given (r, γh); for
            vertical diffusion, a tridiagonal solve along columns.
        dt: The step h.

    Returns:
        The state yₙ₊₁.

    Examples:
        >>> import jax.numpy as jnp
        >>> y = imex_ssp2_step(
        ...     jnp.array(1.0),
        ...     lambda y: -y,
        ...     lambda y: -10.0 * y,
        ...     lambda r, gamma_dt: r / (1.0 + 10.0 * gamma_dt),
        ...     0.01,
        ... )
        >>> bool(jnp.allclose(y, jnp.exp(-0.11), rtol=1e-4))
        True
    """
    gamma_dt = _GAMMA * dt

    # Stage 1: Y₁ = yₙ + γh f_I(Y₁)
    y1 = implicit_solve(state, gamma_dt)
    fe_1 = rhs_explicit(y1)
    fi_1 = rhs_implicit(y1)

    # Stage 2: Y₂* = yₙ + h f_E(Y₁) + (1 − 2γ) h f_I(Y₁); Y₂ = Y₂* + γh f_I(Y₂)
    y2_star = jax.tree.map(
        lambda y, fe, fi: y + dt * fe + (1.0 - 2.0 * _GAMMA) * dt * fi,
        state,
        fe_1,
        fi_1,
    )
    y2 = implicit_solve(y2_star, gamma_dt)
    fe_2 = rhs_explicit(y2)
    fi_2 = rhs_implicit(y2)

    # yₙ₊₁ = yₙ + (h/2)(f_E(Y₁) + f_E(Y₂)) + (h/2)(f_I(Y₁) + f_I(Y₂))
    return jax.tree.map(
        lambda y, fe1, fe2, fi1, fi2: (
            y + 0.5 * dt * (fe1 + fe2) + 0.5 * dt * (fi1 + fi2)
        ),
        state,
        fe_1,
        fe_2,
        fi_1,
        fi_2,
    )

imex_solver

imex_solver(*, rtol: float = 0.0001, atol: float = 1e-06, gmres_restart: int = 20) -> KenCarp3

A KenCarp3 IMEX solver whose implicit stage is matrix-free.

For y′ = F_E(y) + F_I(y) with F_I stiff, each implicit stage solves (I − hγ J_I) Δ = r by Newton (optimistix) with a GMRES inner solve (lineax), so the Jacobian J_I is never formed: memory O(N) rather than the O(N²) dense Jacobian of diffrax's default root finder, which runs out of memory on a 256 × 256 field. Pair it with imex_stepsize_controller carrying the same tolerances: a fixed step cannot reject a step whose Newton solve failed.

Parameters:

Name Type Description Default
rtol float

Relative tolerance of the Newton solve (and of GMRES).

0.0001
atol float

Absolute tolerance of the Newton solve (and of GMRES).

1e-06
gmres_restart int

The Krylov subspace size before GMRES restarts.

20

Returns:

Type Description
KenCarp3

A diffrax.KenCarp3 for a diffrax.MultiTerm of an explicit and an

KenCarp3

implicit term.

Examples:

>>> import diffrax as dfx
>>> import jax.numpy as jnp
>>> terms = dfx.MultiTerm(
...     dfx.ODETerm(lambda t, y, args: -y),
...     dfx.ODETerm(lambda t, y, args: -50.0 * y),
... )
>>> solution = dfx.diffeqsolve(
...     terms,
...     imex_solver(rtol=1e-5, atol=1e-7),
...     0.0,
...     1.0,
...     0.01,
...     jnp.ones(4),
...     stepsize_controller=imex_stepsize_controller(rtol=1e-5, atol=1e-7),
... )
>>> bool(jnp.allclose(solution.ys[0], jnp.exp(-51.0), atol=1e-5))
True
Source code in src/integrix/_src/march/_imex_control.py
def imex_solver(
    *,
    rtol: float = 1e-4,
    atol: float = 1e-6,
    gmres_restart: int = 20,
) -> dfx.KenCarp3:
    """A ``KenCarp3`` IMEX solver whose implicit stage is matrix-free.

    For y′ = F_E(y) + F_I(y) with F_I stiff, each implicit stage solves
    (I − hγ J_I) Δ = r by Newton (optimistix) with a GMRES inner solve
    (lineax), so the Jacobian J_I is never formed: memory O(N) rather than the
    O(N²) dense Jacobian of diffrax's default root finder, which runs out of
    memory on a 256 × 256 field. Pair it with `imex_stepsize_controller`
    carrying the same tolerances: a fixed step cannot reject a step whose
    Newton solve failed.

    Args:
        rtol: Relative tolerance of the Newton solve (and of GMRES).
        atol: Absolute tolerance of the Newton solve (and of GMRES).
        gmres_restart: The Krylov subspace size before GMRES restarts.

    Returns:
        A `diffrax.KenCarp3` for a `diffrax.MultiTerm` of an explicit and an
        implicit term.

    Examples:
        >>> import diffrax as dfx
        >>> import jax.numpy as jnp
        >>> terms = dfx.MultiTerm(
        ...     dfx.ODETerm(lambda t, y, args: -y),
        ...     dfx.ODETerm(lambda t, y, args: -50.0 * y),
        ... )
        >>> solution = dfx.diffeqsolve(
        ...     terms,
        ...     imex_solver(rtol=1e-5, atol=1e-7),
        ...     0.0,
        ...     1.0,
        ...     0.01,
        ...     jnp.ones(4),
        ...     stepsize_controller=imex_stepsize_controller(rtol=1e-5, atol=1e-7),
        ... )
        >>> bool(jnp.allclose(solution.ys[0], jnp.exp(-51.0), atol=1e-5))
        True
    """
    root_finder = optx.Newton(
        rtol=rtol,
        atol=atol,
        linear_solver=lx.GMRES(rtol=rtol, atol=atol, restart=gmres_restart),
    )
    return dfx.KenCarp3(root_finder=root_finder)

imex_stepsize_controller

imex_stepsize_controller(*, rtol: float = 0.0001, atol: float = 1e-06, step_ts: Float[Array, ' step'] | None = None) -> PIDController | ClipStepSizeController

An adaptive PID step-size controller for an IMEX solve.

A fixed-step controller with an implicit solver needs the implicit tolerances set and cannot reject a step when the Newton solve fails to converge; an adaptive controller is the fix. Match its tolerances to the ones given to imex_solver.

Parameters:

Name Type Description Default
rtol float

Relative tolerance of the step-size control.

0.0001
atol float

Absolute tolerance of the step-size control.

1e-06
step_ts Float[Array, ' step'] | None

Times to step to exactly, such as the sample times of a forcing (SampledPath.ts), where it has a kink that would cost a straddling step its order; None for no such times.

None

Returns:

Type Description
PIDController | ClipStepSizeController

A diffrax.PIDController, inside a diffrax.ClipStepSizeController

PIDController | ClipStepSizeController

when step_ts is given.

Examples:

>>> controller = imex_stepsize_controller(rtol=1e-6, atol=1e-8)
>>> controller.rtol, controller.atol
(1e-06, 1e-08)

With times to land on:

>>> clipped = imex_stepsize_controller(step_ts=jnp.array([0.5, 1.0]))
>>> type(clipped).__name__, clipped.step_ts.tolist()
('ClipStepSizeController', [0.5, 1.0])
Source code in src/integrix/_src/march/_imex_control.py
def imex_stepsize_controller(
    *,
    rtol: float = 1e-4,
    atol: float = 1e-6,
    step_ts: Float[Array, " step"] | None = None,
) -> dfx.PIDController | dfx.ClipStepSizeController:
    """An adaptive PID step-size controller for an IMEX solve.

    A fixed-step controller with an implicit solver needs the implicit
    tolerances set and cannot reject a step when the Newton solve fails to
    converge; an adaptive controller is the fix. Match its tolerances to the
    ones given to `imex_solver`.

    Args:
        rtol: Relative tolerance of the step-size control.
        atol: Absolute tolerance of the step-size control.
        step_ts: Times to step to exactly, such as the sample times of a
            forcing (`SampledPath.ts`), where it has a kink that would cost a
            straddling step its order; ``None`` for no such times.

    Returns:
        A `diffrax.PIDController`, inside a `diffrax.ClipStepSizeController`
        when ``step_ts`` is given.

    Examples:
        >>> controller = imex_stepsize_controller(rtol=1e-6, atol=1e-8)
        >>> controller.rtol, controller.atol
        (1e-06, 1e-08)

        With times to land on:

        >>> clipped = imex_stepsize_controller(step_ts=jnp.array([0.5, 1.0]))
        >>> type(clipped).__name__, clipped.step_ts.tolist()
        ('ClipStepSizeController', [0.5, 1.0])
    """
    controller = dfx.PIDController(rtol=rtol, atol=atol)
    if step_ts is None:
        return controller
    return dfx.ClipStepSizeController(controller, step_ts=step_ts)

stable_step

stable_step(spacing: Sequence[float] | ArrayLike, *, speed: Sequence[float | complex] | ArrayLike = (), diffusivity: Sequence[float] | ArrayLike = (), cfl: float | ArrayLike = 1.0) -> Float[Array, '']

The largest stable forward-Euler step for advection and diffusion together.

h_max = CFL / (∑ᵢ |uᵢ| / Δxᵢ + 2 ∑ᵢ Kᵢ / Δxᵢ²). Advection and diffusion act in the same explicit step, so their rates add; taking the smaller of two separate bounds would allow up to twice this step.

This is a first-order, forward-Euler estimate that catches a step orders of magnitude too large. It is not a stability certificate for a high-order reconstruction or a Runge–Kutta scheme, whose stability regions differ.

Parameters:

Name Type Description Default
spacing Sequence[float] | ArrayLike

The grid spacing Δxᵢ along each axis.

required
speed Sequence[float | complex] | ArrayLike

The largest speed |uᵢ| along each axis (its sign is ignored), or empty for no advection.

()
diffusivity Sequence[float] | ArrayLike

The largest diffusivity Kᵢ along each axis, or empty for no diffusion.

()
cfl float | ArrayLike

The safety factor on the bound.

1.0

Returns:

Type Description
Float[Array, '']

The bound, a JAX scalar; inf when nothing moves or diffuses.

Raises:

Type Description
ValidationError

If speed or diffusivity is neither empty nor one value per axis, or, for Python or NumPy inputs, if a spacing or cfl is not finite and positive, or a speed or diffusivity is not finite or a diffusivity is negative. JAX-array inputs are checked with equinox.error_if, so the same checks hold under jax.jit.

Examples:

Advection only, along one axis of two:

>>> bool(stable_step((0.5, 1.0), speed=(1.0, 0.0)) == 0.5)
True

Advection and diffusion add, so the bound is below each alone:

>>> bool(stable_step((1.0,), speed=(1.0,), diffusivity=(0.5,)) == 0.5)
True

Nothing moves or diffuses:

>>> bool(jnp.isinf(stable_step((1.0, 1.0))))
True
Source code in src/integrix/_src/march/_imex_control.py
def stable_step(
    spacing: Sequence[float] | ArrayLike,
    *,
    speed: Sequence[float | complex] | ArrayLike = (),
    diffusivity: Sequence[float] | ArrayLike = (),
    cfl: float | ArrayLike = 1.0,
) -> Float[Array, ""]:
    """The largest stable forward-Euler step for advection and diffusion together.

    h_max = CFL / (∑ᵢ |uᵢ| / Δxᵢ + 2 ∑ᵢ Kᵢ / Δxᵢ²). Advection and diffusion
    act in the same explicit step, so their rates add; taking the smaller of
    two separate bounds would allow up to twice this step.

    This is a first-order, forward-Euler estimate that catches a step orders
    of magnitude too large. It is not a stability certificate for a
    high-order reconstruction or a Runge–Kutta scheme, whose stability
    regions differ.

    Args:
        spacing: The grid spacing Δxᵢ along each axis.
        speed: The largest speed |uᵢ| along each axis (its sign is ignored),
            or empty for no advection.
        diffusivity: The largest diffusivity Kᵢ along each axis, or empty for
            no diffusion.
        cfl: The safety factor on the bound.

    Returns:
        The bound, a JAX scalar; ``inf`` when nothing moves or diffuses.

    Raises:
        ValidationError: If ``speed`` or ``diffusivity`` is neither empty nor
            one value per axis, or, for Python or NumPy inputs, if a spacing
            or ``cfl`` is not finite and positive, or a speed or diffusivity
            is not finite or a diffusivity is negative. JAX-array inputs are
            checked with `equinox.error_if`, so the same checks hold under
            `jax.jit`.

    Examples:
        Advection only, along one axis of two:

        >>> bool(stable_step((0.5, 1.0), speed=(1.0, 0.0)) == 0.5)
        True

        Advection and diffusion add, so the bound is below each alone:

        >>> bool(stable_step((1.0,), speed=(1.0,), diffusivity=(0.5,)) == 0.5)
        True

        Nothing moves or diffuses:

        >>> bool(jnp.isinf(stable_step((1.0, 1.0))))
        True
    """
    # the dtype comes from the JAX arguments; host values are cast to it
    dtype = _working_dtype(spacing, speed, diffusivity, cfl)
    spacings = _as_vector(spacing, "spacing", dtype)
    # a speed's sign (or phase) is ignored: |uᵢ|
    speeds = _as_vector(speed, "speed", dtype, magnitude=True)
    diffusivities = _as_vector(diffusivity, "diffusivity", dtype)
    cfl_value = _as_vector(cfl, "cfl", dtype, scalar=True)
    n_axes = spacings.shape[0]
    for name, values in (("speed", speeds), ("diffusivity", diffusivities)):
        if values.shape[0] not in (0, n_axes):
            raise ValidationError(
                f"stable_step: '{name}' must be empty or have one value per axis, "
                f"got {values.shape[0]} for {n_axes} axes"
            )

    # A blown-up state's NaN speed must not come back as a NaN step.
    traced_checks = [
        _check(spacing, spacings, "spacing", positive=True),
        _check(cfl, cfl_value, "cfl", positive=True),
        _check(speed, speeds, "|speed|", positive=False),
        _check(diffusivity, diffusivities, "diffusivity", positive=False),
    ]

    zero = jnp.zeros((), dtype=dtype)
    # ∑ᵢ |uᵢ| / Δxᵢ
    advective_rate = zero
    if speeds.shape[0]:
        advective_rate = jnp.sum(speeds / spacings)
    # 2 ∑ᵢ Kᵢ / Δxᵢ²
    diffusive_rate = zero
    if diffusivities.shape[0]:
        diffusive_rate = 2.0 * jnp.sum(diffusivities / spacings**2)
    total_rate = advective_rate + diffusive_rate
    # h_max = CFL / rate, inf for a zero rate; the untaken branch divides by one
    moving = total_rate > 0.0
    safe_rate = jnp.where(moving, total_rate, 1.0)
    bound = jnp.where(moving, cfl_value[0] / safe_rate, jnp.inf).astype(dtype)
    # the traced checks ride on the result, so jit cannot drop them even when
    # the inputs they check do not reach the bound (nothing moves)
    for check in traced_checks:
        if check is not None:
            bad, message = check
            bound = eqx.error_if(bound, bad, message)
    return bound

run

run(stepper: AbstractStepper | AbstractSolver, rhs: Callable[..., PyTree] | Any, t0: ScalarLike, y0: PyTree, dt: ScalarLike, n_steps: int, *, args: Any = None, saveat: SaveAt | None = None, adjoint: Any = None) -> PyTree

March y₀ through n_steps constant steps of h from t₀.

yₙ₊₁ = Φ(yₙ, tₙ, h) for n = 0, …, N − 1, with tₙ = t₀ + n h.

Algorithm
  1. A diffrax solver goes to diffrax.diffeqsolve on the step times t₀ + n h (diffrax.StepTo), so it takes exactly N steps.
  2. An AbstractStepper takes its first step with init and the other N − 1 with step inside jax.lax.scan, carrying the state and its history.

Parameters:

Name Type Description Default
stepper AbstractStepper | AbstractSolver

An AbstractStepper, or a diffrax solver (the steppers of integrix.march, or diffrax's own).

required
rhs Callable[..., PyTree] | Any

The vector field rhs(t, y, args). A diffrax solver may also take a diffrax term (a diffrax.MultiTerm for IMEX, say); a split-explicit stepper takes its SplitExplicitTerms.

required
t0 ScalarLike

The start time t₀.

required
y0 PyTree

The initial state y₀, any pytree.

required
dt ScalarLike

The step h.

required
n_steps int

The number of steps N ≥ 1, a Python integer.

required
args Any

Passed to the vector field.

None
saveat SaveAt | None

None for the final state y_N, or SaveAt(steps=True) for every state y₁, …, y_N, stacked on a new leading axis.

None
adjoint Any

How reverse mode runs back through the march. None is plain reverse mode (every state stored for a stepper; diffrax's default for a solver). integrix.adjoint.Checkpointed stores every k-th state and recomputes between (for a diffrax solver, RecursiveCheckpointAdjoint(checkpoints=⌈N / k⌉)). integrix.adjoint.Truncated cuts the gradient through the state before the last k steps, for a stepper only. A diffrax solver also takes a diffrax adjoint or a pipekit-cycle spec (integrix.adjoint.to_diffrax_adjoint). Forward values never depend on the adjoint.

None

Returns:

Type Description
PyTree

y_N, or the stacked y₁, …, y_N.

Raises:

Type Description
ValidationError

If n_steps is not a positive integer, saveat asks for anything but the final state or every step, adjoint does not apply to the stepper (Truncated for a diffrax solve, a diffrax adjoint for an AbstractStepper), or stepper is neither kind.

Examples:

>>> import jax.numpy as jnp
>>> from integrix.march import RK4Classic
>>> y = run(
...     RK4Classic(), lambda t, y, args: -y, 0.0, jnp.array(1.0), 0.1, 10
... )
>>> bool(jnp.allclose(y, jnp.exp(-1.0), rtol=1e-6))
True
>>> from integrix.march import AB2Solver
>>> every = run(
...     AB2Solver(),
...     lambda t, y, args: -y,
...     0.0,
...     jnp.ones(3),
...     0.1,
...     5,
...     saveat=dfx.SaveAt(steps=True),
... )
>>> every.shape
(5, 3)
Source code in src/integrix/_src/march/_loop.py
def run(
    stepper: AbstractStepper | dfx.AbstractSolver,
    rhs: Callable[..., PyTree] | Any,
    t0: ScalarLike,
    y0: PyTree,
    dt: ScalarLike,
    n_steps: int,
    *,
    args: Any = None,
    saveat: dfx.SaveAt | None = None,
    adjoint: Any = None,
) -> PyTree:
    """March y₀ through ``n_steps`` constant steps of h from t₀.

    yₙ₊₁ = Φ(yₙ, tₙ, h) for n = 0, …, N − 1, with tₙ = t₀ + n h.

    Algorithm:
        1. A diffrax solver goes to `diffrax.diffeqsolve` on the step times
           t₀ + n h (`diffrax.StepTo`), so it takes exactly N steps.
        2. An `AbstractStepper` takes its first step with ``init`` and the
           other N − 1 with ``step`` inside `jax.lax.scan`, carrying the
           state and its history.

    Args:
        stepper: An `AbstractStepper`, or a diffrax solver (the steppers of
            `integrix.march`, or diffrax's own).
        rhs: The vector field ``rhs(t, y, args)``. A diffrax solver may also
            take a diffrax term (a `diffrax.MultiTerm` for IMEX, say); a
            split-explicit stepper takes its `SplitExplicitTerms`.
        t0: The start time t₀.
        y0: The initial state y₀, any pytree.
        dt: The step h.
        n_steps: The number of steps N ≥ 1, a Python integer.
        args: Passed to the vector field.
        saveat: ``None`` for the final state y_N, or ``SaveAt(steps=True)``
            for every state y₁, …, y_N, stacked on a new leading axis.
        adjoint: How reverse mode runs back through the march. ``None`` is
            plain reverse mode (every state stored for a stepper; diffrax's
            default for a solver). `integrix.adjoint.Checkpointed` stores
            every k-th state and recomputes between (for a diffrax solver,
            ``RecursiveCheckpointAdjoint(checkpoints=⌈N / k⌉)``).
            `integrix.adjoint.Truncated` cuts the gradient through the state
            before the last k steps, for a stepper only. A diffrax solver
            also takes a diffrax adjoint or a pipekit-cycle spec
            (`integrix.adjoint.to_diffrax_adjoint`). Forward values never
            depend on the adjoint.

    Returns:
        y_N, or the stacked y₁, …, y_N.

    Raises:
        ValidationError: If ``n_steps`` is not a positive integer, ``saveat``
            asks for anything but the final state or every step, ``adjoint``
            does not apply to the stepper (`Truncated` for a diffrax solve, a
            diffrax adjoint for an `AbstractStepper`), or ``stepper`` is
            neither kind.

    Examples:
        >>> import jax.numpy as jnp
        >>> from integrix.march import RK4Classic
        >>> y = run(
        ...     RK4Classic(), lambda t, y, args: -y, 0.0, jnp.array(1.0), 0.1, 10
        ... )
        >>> bool(jnp.allclose(y, jnp.exp(-1.0), rtol=1e-6))
        True
        >>> from integrix.march import AB2Solver
        >>> every = run(
        ...     AB2Solver(),
        ...     lambda t, y, args: -y,
        ...     0.0,
        ...     jnp.ones(3),
        ...     0.1,
        ...     5,
        ...     saveat=dfx.SaveAt(steps=True),
        ... )
        >>> every.shape
        (5, 3)
    """
    try:
        n_steps = operator.index(n_steps)
    except TypeError as err:
        raise ValidationError(
            f"'n_steps' must be a Python integer, got {type(n_steps).__name__}"
        ) from err
    if n_steps < 1:
        raise ValidationError(f"'n_steps' must be at least 1, got {n_steps}")
    save_steps = _save_steps(saveat)

    if isinstance(stepper, dfx.AbstractSolver):
        return _run_diffrax(
            stepper, rhs, t0, y0, dt, n_steps, args, save_steps, adjoint
        )
    if not isinstance(stepper, AbstractStepper):
        raise ValidationError(
            f"'stepper' must be an AbstractStepper or a diffrax solver, got "
            f"{type(stepper).__name__}"
        )
    scan = _loop_scan(adjoint)

    time_dtype = state_time_dtype(y0)
    start = jnp.asarray(t0, dtype=time_dtype)
    step_size = jnp.asarray(dt, dtype=time_dtype)

    state, y1 = stepper.init(rhs, start, y0, step_size, args)
    # y₁ as saved: its own step's gradient survives any truncation
    y1_saved = y1
    if isinstance(adjoint, Truncated) and adjoint.k < n_steps:
        # the first step lies before the last k, so the carry it hands on is cut
        y1, state = jax.lax.stop_gradient((y1, state))

    def body(carry, index):
        y, history = carry
        # tₙ = t₀ + n h
        t = start + index.astype(time_dtype) * step_size
        y_next, history = stepper.step(rhs, t, y, step_size, history, args)
        return (y_next, history), (y_next if save_steps else None)

    indices = jnp.arange(1, n_steps)
    (y_final, _), later = scan(body, (y1, state), indices)
    if not save_steps:
        return y_final
    return jax.tree.map(
        lambda first, rest: jnp.concatenate([first[None], rest]), y1_saved, later
    )

ab2_step

ab2_step(state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike, rhs_nm1: PyTree) -> tuple[PyTree, PyTree, PyTree]

One second-order Adams–Bashforth step.

yₙ₊₁ = yₙ + (h/2)(3 fₙ − fₙ₋₁), one evaluation of f per step.

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
rhs_fn Callable[[PyTree], PyTree]

The autonomous right-hand side f(y).

required
dt ScalarLike

The step h.

required
rhs_nm1 PyTree

fₙ₋₁, the right-hand side one step back.

required

Returns:

Type Description
tuple[PyTree, PyTree, PyTree]

(yₙ₊₁, fₙ, fₙ₋₁): thread fₙ as the next rhs_nm1.

Examples:

>>> import jax.numpy as jnp
>>> y, f_n, _ = ab2_step(jnp.array(1.0), lambda y: -y, 0.1, -1.0)
>>> bool(jnp.allclose(y, 0.9)), bool(f_n == -1.0)
(True, True)
Source code in src/integrix/_src/march/_multistep.py
def ab2_step(
    state: PyTree,
    rhs_fn: Callable[[PyTree], PyTree],
    dt: ScalarLike,
    rhs_nm1: PyTree,
) -> tuple[PyTree, PyTree, PyTree]:
    """One second-order Adams–Bashforth step.

    yₙ₊₁ = yₙ + (h/2)(3 fₙ − fₙ₋₁), one evaluation of f per step.

    Args:
        state: The state yₙ, any pytree.
        rhs_fn: The autonomous right-hand side f(y).
        dt: The step h.
        rhs_nm1: fₙ₋₁, the right-hand side one step back.

    Returns:
        ``(yₙ₊₁, fₙ, fₙ₋₁)``: thread fₙ as the next ``rhs_nm1``.

    Examples:
        >>> import jax.numpy as jnp
        >>> y, f_n, _ = ab2_step(jnp.array(1.0), lambda y: -y, 0.1, -1.0)
        >>> bool(jnp.allclose(y, 0.9)), bool(f_n == -1.0)
        (True, True)
    """
    rhs_n = rhs_fn(state)
    # yₙ₊₁ = yₙ + (h/2)(3 fₙ − fₙ₋₁)
    new_state = jax.tree.map(
        lambda y, fn, fnm1: y + (dt / 2.0) * (3.0 * fn - fnm1),
        state,
        rhs_n,
        rhs_nm1,
    )
    return new_state, rhs_n, rhs_nm1

ab3_step

ab3_step(state: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike, rhs_nm1: PyTree, rhs_nm2: PyTree) -> tuple[PyTree, PyTree, PyTree]

One third-order Adams–Bashforth step.

yₙ₊₁ = yₙ + (h/12)(23 fₙ − 16 fₙ₋₁ + 5 fₙ₋₂), one evaluation of f per step. The start must be at least second-order accurate to keep the global order 3: bootstrap y₁ and y₂ with rk3_ssp_step, as AB3Solver does; the crude start fₙ₋₂ = fₙ₋₁ = f(y₀) degrades AB3 to second order.

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
rhs_fn Callable[[PyTree], PyTree]

The autonomous right-hand side f(y).

required
dt ScalarLike

The step h.

required
rhs_nm1 PyTree

fₙ₋₁, the right-hand side one step back.

required
rhs_nm2 PyTree

fₙ₋₂, two steps back.

required

Returns:

Type Description
PyTree

(yₙ₊₁, fₙ, fₙ₋₁): thread fₙ as the next rhs_nm1 and fₙ₋₁ as

PyTree

the next rhs_nm2.

Examples:

>>> import jax.numpy as jnp
>>> f = lambda y: -y
>>> y, f_n, f_nm1 = ab3_step(jnp.array(1.0), f, 0.1, f(1.0), f(1.0))
>>> bool(jnp.allclose(y, 0.9)), bool(f_n == -1.0)
(True, True)
Source code in src/integrix/_src/march/_multistep.py
def ab3_step(
    state: PyTree,
    rhs_fn: Callable[[PyTree], PyTree],
    dt: ScalarLike,
    rhs_nm1: PyTree,
    rhs_nm2: PyTree,
) -> tuple[PyTree, PyTree, PyTree]:
    """One third-order Adams–Bashforth step.

    yₙ₊₁ = yₙ + (h/12)(23 fₙ − 16 fₙ₋₁ + 5 fₙ₋₂), one evaluation of f per
    step. The start must be at least second-order accurate to keep the
    global order 3: bootstrap y₁ and y₂ with `rk3_ssp_step`, as `AB3Solver`
    does; the crude start fₙ₋₂ = fₙ₋₁ = f(y₀) degrades AB3 to second order.

    Args:
        state: The state yₙ, any pytree.
        rhs_fn: The autonomous right-hand side f(y).
        dt: The step h.
        rhs_nm1: fₙ₋₁, the right-hand side one step back.
        rhs_nm2: fₙ₋₂, two steps back.

    Returns:
        ``(yₙ₊₁, fₙ, fₙ₋₁)``: thread fₙ as the next ``rhs_nm1`` and fₙ₋₁ as
        the next ``rhs_nm2``.

    Examples:
        >>> import jax.numpy as jnp
        >>> f = lambda y: -y
        >>> y, f_n, f_nm1 = ab3_step(jnp.array(1.0), f, 0.1, f(1.0), f(1.0))
        >>> bool(jnp.allclose(y, 0.9)), bool(f_n == -1.0)
        (True, True)
    """
    rhs_n = rhs_fn(state)
    # yₙ₊₁ = yₙ + (h/12)(23 fₙ − 16 fₙ₋₁ + 5 fₙ₋₂)
    new_state = jax.tree.map(
        lambda y, fn, fnm1, fnm2: (
            y + (dt / 12.0) * (23.0 * fn - 16.0 * fnm1 + 5.0 * fnm2)
        ),
        state,
        rhs_n,
        rhs_nm1,
        rhs_nm2,
    )
    return new_state, rhs_n, rhs_nm1

leapfrog_raf_step

leapfrog_raf_step(state: PyTree, state_nm1: PyTree, rhs_fn: Callable[[PyTree], PyTree], dt: ScalarLike, alpha: float = 0.05) -> tuple[PyTree, PyTree]

One leapfrog step with a Robert–Asselin filter on the middle level.

ỹₙ₊₁ = yₙ₋₁ + 2h f(yₙ) and ȳₙ = yₙ + α (yₙ₋₁ − 2yₙ + ỹₙ₊₁). The filtered ȳₙ damps the computational mode of the three-level scheme. Second order for α = 0 and first order for α > 0 (the filter's O(αh) damping; the measured rate is about 1.1 at the default 0.05).

Parameters:

Name Type Description Default
state PyTree

The state yₙ, any pytree.

required
state_nm1 PyTree

The (filtered) state yₙ₋₁.

required
rhs_fn Callable[[PyTree], PyTree]

The autonomous right-hand side f(y).

required
dt ScalarLike

The step h.

required
alpha float

The filter coefficient α, typically 0.01 to 0.1.

0.05

Returns:

Type Description
tuple[PyTree, PyTree]

(yₙ₊₁, ȳₙ): yₙ₊₁ is the next state and ȳₙ the next state_nm1.

Examples:

>>> import jax.numpy as jnp
>>> y_next, filtered = leapfrog_raf_step(1.0, 1.0, lambda y: 0.0 * y, 0.1)
>>> bool(y_next == 1.0), bool(filtered == 1.0)
(True, True)
Source code in src/integrix/_src/march/_multistep.py
def leapfrog_raf_step(
    state: PyTree,
    state_nm1: PyTree,
    rhs_fn: Callable[[PyTree], PyTree],
    dt: ScalarLike,
    alpha: float = 0.05,
) -> tuple[PyTree, PyTree]:
    """One leapfrog step with a Robert–Asselin filter on the middle level.

    ỹₙ₊₁ = yₙ₋₁ + 2h f(yₙ) and ȳₙ = yₙ + α (yₙ₋₁ − 2yₙ + ỹₙ₊₁). The filtered
    ȳₙ damps the computational mode of the three-level scheme. Second order
    for α = 0 and first order for α > 0 (the filter's O(αh) damping; the
    measured rate is about 1.1 at the default 0.05).

    Args:
        state: The state yₙ, any pytree.
        state_nm1: The (filtered) state yₙ₋₁.
        rhs_fn: The autonomous right-hand side f(y).
        dt: The step h.
        alpha: The filter coefficient α, typically 0.01 to 0.1.

    Returns:
        ``(yₙ₊₁, ȳₙ)``: yₙ₊₁ is the next state and ȳₙ the next ``state_nm1``.

    Examples:
        >>> import jax.numpy as jnp
        >>> y_next, filtered = leapfrog_raf_step(1.0, 1.0, lambda y: 0.0 * y, 0.1)
        >>> bool(y_next == 1.0), bool(filtered == 1.0)
        (True, True)
    """
    rhs_n = rhs_fn(state)

    # ỹₙ₊₁ = yₙ₋₁ + 2h f(yₙ)
    y_next = jax.tree.map(
        lambda ynm1, fn: ynm1 + 2.0 * dt * fn,
        state_nm1,
        rhs_n,
    )

    # ȳₙ = yₙ + α (yₙ₋₁ − 2yₙ + ỹₙ₊₁)
    state_filtered = jax.tree.map(
        lambda ynm1, yn, ynp1: yn + alpha * (ynm1 - 2.0 * yn + ynp1),
        state_nm1,
        state,
        y_next,
    )

    return y_next, state_filtered

departure_points

departure_points(nodes: Float[Array, 'node axis'], velocity: Velocity, t: ScalarLike, dt: ScalarLike, *, iterations: int = 2) -> Float[Array, 'node axis']

The points x_d that the flow carries to the nodes x over one step.

x_d = x − Δt u(t + Δt/2, (x + x_d)/2)

The midpoint rule on the trajectory, solved by fixed-point iteration from one Euler step. One iteration or more makes x_d second order in Δt; iterations=0 is the first-order Euler departure point x_d = x − Δt u(t, x).

Algorithm
  1. x_d⁽⁰⁾ = x − Δt u(t, x).
  2. For k = 0, …, K − 1: x_d⁽ᵏ⁺¹⁾ = x − Δt u(t + Δt/2, (x + x_d⁽ᵏ⁾)/2).

Parameters:

Name Type Description Default
nodes Float[Array, 'node axis']

The arrival points x, N of them in D dimensions.

required
velocity Velocity

The velocity u(t, x), evaluated at N points at once.

required
t ScalarLike

The time t at the start of the step.

required
dt ScalarLike

The step Δt (negative steps backward).

required
iterations int

The number K of midpoint iterations.

2

Returns:

Type Description
Float[Array, 'node axis']

The departure points x_d, shaped like nodes.

Raises:

Type Description
ValidationError

If iterations is not a non-negative int.

Examples:

A uniform flow moves every node back by u Δt:

>>> import jax.numpy as jnp
>>> nodes = jnp.array([[0.0], [0.5]])
>>> x_d = departure_points(nodes, lambda t, x: jnp.ones_like(x), 0.0, 0.1)
>>> bool(jnp.allclose(x_d, jnp.array([[-0.1], [0.4]])))
True

A solid-body rotation by a quarter turn, from the point (1, 0); the midpoint departure point is close to the exact (0, −1):

>>> def rotation(t, x):
...     return jnp.column_stack([-x[:, 1], x[:, 0]])
>>> start = jnp.array([[1.0, 0.0]])
>>> euler = departure_points(start, rotation, 0.0, 0.1, iterations=0)
>>> midpoint = departure_points(start, rotation, 0.0, 0.1)
>>> exact = jnp.array([[jnp.cos(0.1), -jnp.sin(0.1)]])
>>> bool(
...     jnp.abs(midpoint - exact).max() < jnp.abs(euler - exact).max() / 10
... )
True
Source code in src/integrix/_src/march/_semi_lagrangian.py
def departure_points(
    nodes: Float[Array, "node axis"],
    velocity: Velocity,
    t: ScalarLike,
    dt: ScalarLike,
    *,
    iterations: int = 2,
) -> Float[Array, "node axis"]:
    """The points x_d that the flow carries to the nodes x over one step.

        x_d = x − Δt u(t + Δt/2, (x + x_d)/2)

    The midpoint rule on the trajectory, solved by fixed-point iteration
    from one Euler step. One iteration or more makes x_d second order in
    Δt; ``iterations=0`` is the first-order Euler departure point
    x_d = x − Δt u(t, x).

    Algorithm:
        1. x_d⁽⁰⁾ = x − Δt u(t, x).
        2. For k = 0, …, K − 1: x_d⁽ᵏ⁺¹⁾ = x − Δt u(t + Δt/2, (x + x_d⁽ᵏ⁾)/2).

    Args:
        nodes: The arrival points x, N of them in D dimensions.
        velocity: The velocity u(t, x), evaluated at N points at once.
        t: The time t at the start of the step.
        dt: The step Δt (negative steps backward).
        iterations: The number K of midpoint iterations.

    Returns:
        The departure points x_d, shaped like ``nodes``.

    Raises:
        ValidationError: If ``iterations`` is not a non-negative int.

    Examples:
        A uniform flow moves every node back by u Δt:

        >>> import jax.numpy as jnp
        >>> nodes = jnp.array([[0.0], [0.5]])
        >>> x_d = departure_points(nodes, lambda t, x: jnp.ones_like(x), 0.0, 0.1)
        >>> bool(jnp.allclose(x_d, jnp.array([[-0.1], [0.4]])))
        True

        A solid-body rotation by a quarter turn, from the point (1, 0); the
        midpoint departure point is close to the exact (0, −1):

        >>> def rotation(t, x):
        ...     return jnp.column_stack([-x[:, 1], x[:, 0]])
        >>> start = jnp.array([[1.0, 0.0]])
        >>> euler = departure_points(start, rotation, 0.0, 0.1, iterations=0)
        >>> midpoint = departure_points(start, rotation, 0.0, 0.1)
        >>> exact = jnp.array([[jnp.cos(0.1), -jnp.sin(0.1)]])
        >>> bool(
        ...     jnp.abs(midpoint - exact).max() < jnp.abs(euler - exact).max() / 10
        ... )
        True
    """
    _check_iterations(iterations)
    # x_d⁽⁰⁾ = x − Δt u(t, x)
    departure = nodes - dt * velocity(t, nodes)
    midtime = t + 0.5 * dt
    for _ in range(iterations):
        # (x + x_d⁽ᵏ⁾)/2
        midpoint = 0.5 * (nodes + departure)
        # x_d⁽ᵏ⁺¹⁾ = x − Δt u(t + Δt/2, (x + x_d⁽ᵏ⁾)/2)
        departure = nodes - dt * velocity(midtime, midpoint)
    return departure

semi_lagrangian_step

semi_lagrangian_step(field: PyTree, nodes: Float[Array, 'node axis'], velocity: Velocity, readout: Readout, t: ScalarLike, dt: ScalarLike, *, iterations: int = 2) -> PyTree

One semi-Lagrangian step: the old field read at the departure points.

q(t + Δt, x) = q(t, x_d)

There is no CFL limit, since the step only reads the old field. A convex read-out (linear) stays within the old extrema; a cubic or B-spline read-out can over- and undershoot, which a monotone plan (functax's Pchip) avoids. Departure points outside the domain are the read-out's business (its periodic axes or boundary policy).

Algorithm
  1. x_d = departure_points (nodes, u, t, Δt).
  2. H = readout(x_d), the read-out of the old field at x_d.
  3. q(t + Δt) = H q(t).

Parameters:

Name Type Description Default
field PyTree

The old field q(t), in whatever layout readout reads.

required
nodes Float[Array, 'node axis']

The arrival points x, N of them in D dimensions.

required
velocity Velocity

The velocity u(t, x), evaluated at N points at once.

required
readout Readout

Departure points ↦ the map q ↦ q(x_d); a functax interpolation plan, lambda x_d: scheme.plan(grid, Points(x_d)).

required
t ScalarLike

The time t at the start of the step.

required
dt ScalarLike

The step Δt.

required
iterations int

The number of midpoint iterations of the trajectory.

2

Returns:

Type Description
PyTree

The new field q(t + Δt), as the read-out returns it.

Raises:

Type Description
ValidationError

If iterations is not a non-negative int.

Examples:

A periodic sine translated by a quarter period with a cubic B-spline read-out:

>>> import einx
>>> import jax.numpy as jnp
>>> from functax.geometry import Axis, Points
>>> from functax.interp import BSpline
>>> x = jnp.arange(32) / 32
>>> axis = Axis(x, period=1.0)
>>> def readout(x_d):
...     return BSpline(3).plan(axis, Points(x_d))
>>> nodes = einx.id("node -> node 1", x)
>>> q = jnp.sin(2 * jnp.pi * x)
>>> q_new = semi_lagrangian_step(
...     q, nodes, lambda t, p: jnp.ones_like(p), readout, 0.0, 0.25
... )
>>> bool(jnp.allclose(q_new, jnp.sin(2 * jnp.pi * (x - 0.25)), atol=1e-4))
True
Source code in src/integrix/_src/march/_semi_lagrangian.py
def semi_lagrangian_step(
    field: PyTree,
    nodes: Float[Array, "node axis"],
    velocity: Velocity,
    readout: Readout,
    t: ScalarLike,
    dt: ScalarLike,
    *,
    iterations: int = 2,
) -> PyTree:
    """One semi-Lagrangian step: the old field read at the departure points.

        q(t + Δt, x) = q(t, x_d)

    There is no CFL limit, since the step only reads the old field. A
    convex read-out (linear) stays within the old extrema; a cubic or
    B-spline read-out can over- and undershoot, which a monotone plan
    (functax's ``Pchip``) avoids. Departure points outside the domain are
    the read-out's business (its periodic axes or boundary policy).

    Algorithm:
        1. x_d = `departure_points` (nodes, u, t, Δt).
        2. H = readout(x_d), the read-out of the old field at x_d.
        3. q(t + Δt) = H q(t).

    Args:
        field: The old field q(t), in whatever layout ``readout`` reads.
        nodes: The arrival points x, N of them in D dimensions.
        velocity: The velocity u(t, x), evaluated at N points at once.
        readout: Departure points ↦ the map q ↦ q(x_d); a functax
            interpolation plan, ``lambda x_d: scheme.plan(grid, Points(x_d))``.
        t: The time t at the start of the step.
        dt: The step Δt.
        iterations: The number of midpoint iterations of the trajectory.

    Returns:
        The new field q(t + Δt), as the read-out returns it.

    Raises:
        ValidationError: If ``iterations`` is not a non-negative int.

    Examples:
        A periodic sine translated by a quarter period with a cubic
        B-spline read-out:

        >>> import einx
        >>> import jax.numpy as jnp
        >>> from functax.geometry import Axis, Points
        >>> from functax.interp import BSpline
        >>> x = jnp.arange(32) / 32
        >>> axis = Axis(x, period=1.0)
        >>> def readout(x_d):
        ...     return BSpline(3).plan(axis, Points(x_d))
        >>> nodes = einx.id("node -> node 1", x)
        >>> q = jnp.sin(2 * jnp.pi * x)
        >>> q_new = semi_lagrangian_step(
        ...     q, nodes, lambda t, p: jnp.ones_like(p), readout, 0.0, 0.25
        ... )
        >>> bool(jnp.allclose(q_new, jnp.sin(2 * jnp.pi * (x - 0.25)), atol=1e-4))
        True
    """
    # x_d
    departure = departure_points(nodes, velocity, t, dt, iterations=iterations)
    # q(t + Δt, x) = q(t, x_d)
    return readout(departure)(field)

split_explicit_step

split_explicit_step(state_3d: PyTree, state_2d: PyTree, rhs_3d: Callable[[PyTree, PyTree], PyTree], rhs_2d: Callable[[ScalarLike, PyTree, PyTree], PyTree], couple_2d_to_3d: Callable[[PyTree, PyTree], PyTree], dt_slow: ScalarLike, n_substeps: int, slow_forcing: Callable[[PyTree], PyTree] | None = None, t0: ScalarLike = 0.0) -> tuple[PyTree, PyTree]

One split-explicit barotropic/baroclinic step.

The fast subcycle is neutrally stable for the oscillatory gravity-wave mode (RK4 amplification 1 − (ωh)⁶/144 per substep); the slow step is first order in h. The returned 2-D state is the end-of-cycle y_M, which stays on time; the slow step used the mean ⟨y⟩, and making the 3-D state consistent with it (replacing the depth mean of the 3-D velocity by the averaged transport, say) is couple_2d_to_3d's job.

Algorithm
  1. F = slow_forcing(state_3d), if given, held fixed over the cycle.
  2. Subcycle the 2-D state with M RK4 steps of h/M on y′ = rhs_2d(t, y, state_3d) + F, and form its trapezoidal mean ⟨y⟩ over the cycle.
  3. One forward-Euler step of the 3-D state: y₃ + h rhs_3d(state_3d, ⟨y⟩).
  4. couple_2d_to_3d(new state_3d, ⟨y⟩).

Parameters:

Name Type Description Default
state_3d PyTree

The slow (baroclinic) state.

required
state_2d PyTree

The fast (barotropic) state.

required
rhs_3d Callable[[PyTree, PyTree], PyTree]

The slow tendency rhs_3d(state_3d, mean_2d).

required
rhs_2d Callable[[ScalarLike, PyTree, PyTree], PyTree]

The fast tendency rhs_2d(t, state_2d, state_3d), at the absolute RK4 stage time t.

required
couple_2d_to_3d Callable[[PyTree, PyTree], PyTree]

couple_2d_to_3d(state_3d, mean_2d), applied after the slow step.

required
dt_slow ScalarLike

The slow step h.

required
n_substeps int

The number of fast substeps M ≥ 1 per slow step.

required
slow_forcing Callable[[PyTree], PyTree] | None

slow_forcing(state_3d), the baroclinic forcing of the barotropic mode, evaluated once per slow step and added to every fast tendency.

None
t0 ScalarLike

The time at the start of the slow step.

0.0

Returns:

Type Description
tuple[PyTree, PyTree]

(new_state_3d, new_state_2d).

Raises:

Type Description
ValidationError

If n_substeps is below 1.

Examples:

>>> import jax.numpy as jnp
>>> slow, fast = split_explicit_step(
...     jnp.array(1.0),
...     jnp.array(1.0),
...     lambda y3, mean_2d: -mean_2d,
...     lambda t, y2, y3: 0.0 * y2,
...     lambda y3, mean_2d: y3,
...     0.1,
...     5,
... )
>>> bool(jnp.allclose(slow, 0.9)), bool(fast == 1.0)
(True, True)
Source code in src/integrix/_src/march/_split_explicit.py
def split_explicit_step(
    state_3d: PyTree,
    state_2d: PyTree,
    rhs_3d: Callable[[PyTree, PyTree], PyTree],
    rhs_2d: Callable[[ScalarLike, PyTree, PyTree], PyTree],
    couple_2d_to_3d: Callable[[PyTree, PyTree], PyTree],
    dt_slow: ScalarLike,
    n_substeps: int,
    slow_forcing: Callable[[PyTree], PyTree] | None = None,
    t0: ScalarLike = 0.0,
) -> tuple[PyTree, PyTree]:
    """One split-explicit barotropic/baroclinic step.

    The fast subcycle is neutrally stable for the oscillatory gravity-wave
    mode (RK4 amplification 1 − (ωh)⁶/144 per substep); the slow step is first
    order in h. The returned 2-D state is the end-of-cycle y_M, which stays on
    time; the slow step used the mean ⟨y⟩, and making the 3-D state consistent
    with it (replacing the depth mean of the 3-D velocity by the averaged
    transport, say) is ``couple_2d_to_3d``'s job.

    Algorithm:
        1. F = ``slow_forcing(state_3d)``, if given, held fixed over the cycle.
        2. Subcycle the 2-D state with M RK4 steps of h/M on
           y′ = ``rhs_2d(t, y, state_3d)`` + F, and form its trapezoidal
           mean ⟨y⟩ over the cycle.
        3. One forward-Euler step of the 3-D state:
           y₃ + h ``rhs_3d(state_3d, ⟨y⟩)``.
        4. ``couple_2d_to_3d(new state_3d, ⟨y⟩)``.

    Args:
        state_3d: The slow (baroclinic) state.
        state_2d: The fast (barotropic) state.
        rhs_3d: The slow tendency ``rhs_3d(state_3d, mean_2d)``.
        rhs_2d: The fast tendency ``rhs_2d(t, state_2d, state_3d)``, at the
            absolute RK4 stage time t.
        couple_2d_to_3d: ``couple_2d_to_3d(state_3d, mean_2d)``, applied after
            the slow step.
        dt_slow: The slow step h.
        n_substeps: The number of fast substeps M ≥ 1 per slow step.
        slow_forcing: ``slow_forcing(state_3d)``, the baroclinic forcing of the
            barotropic mode, evaluated once per slow step and added to every
            fast tendency.
        t0: The time at the start of the slow step.

    Returns:
        ``(new_state_3d, new_state_2d)``.

    Raises:
        ValidationError: If ``n_substeps`` is below 1.

    Examples:
        >>> import jax.numpy as jnp
        >>> slow, fast = split_explicit_step(
        ...     jnp.array(1.0),
        ...     jnp.array(1.0),
        ...     lambda y3, mean_2d: -mean_2d,
        ...     lambda t, y2, y3: 0.0 * y2,
        ...     lambda y3, mean_2d: y3,
        ...     0.1,
        ...     5,
        ... )
        >>> bool(jnp.allclose(slow, 0.9)), bool(fast == 1.0)
        (True, True)
    """
    if n_substeps < 1:
        raise ValidationError(f"n_substeps must be >= 1, got {n_substeps}")

    dt_fast = dt_slow / n_substeps
    forcing = None if slow_forcing is None else slow_forcing(state_3d)

    # --- fast (barotropic) subcycle ---
    y_2d_end, y_2d_avg = _barotropic_cycle(
        state_2d,
        lambda t_sub, y_2d: rhs_2d(t_sub, y_2d, state_3d),
        t0,
        dt_fast,
        n_substeps,
        forcing,
    )

    # --- slow (baroclinic) step ---
    f_slow = rhs_3d(state_3d, y_2d_avg)
    y_3d_new = jax.tree.map(lambda y, f: y + dt_slow * f, state_3d, f_slow)

    # --- coupling ---
    y_3d_new = couple_2d_to_3d(y_3d_new, y_2d_avg)

    return y_3d_new, y_2d_end

count_steps

count_steps(span: Number, step: Number) -> int

K = ⌈T/Δt⌉, with a quotient within 10⁻⁹ K of a whole number taken as it.

Plain ⌈T/Δt⌉ adds a step of zero length when the quotient is a whole number that floating point rounds just above: 2.1 s in steps of 0.15 s is 14 steps, and not 15. Take the span of times counted from an epoch near the run: the difference of two Unix-epoch times has already rounded.

Parameters:

Name Type Description Default
span Number

T ≥ 0, the length of the run, a Python number.

required
step Number

Δt > 0, the length of a step, a Python number.

required

Returns:

Name Type Description
K int

0 for T = 0, and at least 1 for any T > 0, so a span much shorter than

int

a step is still one step.

Raises:

Type Description
ValidationError

If span is negative or not finite, or step is not positive and finite.

Examples:

>>> import math
>>> count_steps(2.1, 0.15), math.ceil(2.1 / 0.15)
(14, 15)
>>> count_steps(122.0, 5.0)
25
>>> count_steps(0.0, 5.0), count_steps(1e-12, 5.0)
(0, 1)
Source code in src/integrix/_src/march/_steps.py
def count_steps(span: Number, step: Number) -> int:
    """K = ⌈T/Δt⌉, with a quotient within 10⁻⁹ K of a whole number taken as it.

    Plain ⌈T/Δt⌉ adds a step of zero length when the quotient is a whole number
    that floating point rounds just above: 2.1 s in steps of 0.15 s is 14 steps,
    and not 15. Take the span of times counted from an epoch near the run: the
    difference of two Unix-epoch times has already rounded.

    Args:
        span: T ≥ 0, the length of the run, a Python number.
        step: Δt > 0, the length of a step, a Python number.

    Returns:
        K: 0 for T = 0, and at least 1 for any T > 0, so a span much shorter than
        a step is still one step.

    Raises:
        ValidationError: If ``span`` is negative or not finite, or ``step`` is not
            positive and finite.

    Examples:
        >>> import math
        >>> count_steps(2.1, 0.15), math.ceil(2.1 / 0.15)
        (14, 15)
        >>> count_steps(122.0, 5.0)
        25
        >>> count_steps(0.0, 5.0), count_steps(1e-12, 5.0)
        (0, 1)
    """
    total, size = _checked(span, step)
    # q = T/Δt, and n its nearest whole number
    quotient = total / size
    nearest = round(quotient)
    if abs(quotient - nearest) <= _SNAP * max(1.0, nearest):
        return nearest if total == 0.0 else max(nearest, 1)
    return math.ceil(quotient)

step_lengths

step_lengths(span: Number, step: Number) -> ndarray

The K step lengths: Δt, and T − (K − 1) Δt for the last, on the host.

They sum to T to rounding; K is count_steps. Each is in (0, Δt], except that the last is up to 10⁻⁹ K Δt longer where the quotient was taken as a whole number.

Parameters:

Name Type Description Default
span Number

T ≥ 0, as in count_steps.

required
step Number

Δt > 0, as in count_steps.

required

Returns:

Type Description
ndarray

The K lengths, in float64; empty for T = 0.

Raises:

Type Description
ValidationError

As count_steps does.

Examples:

>>> step_lengths(12.0, 5.0).tolist()
[5.0, 5.0, 2.0]
>>> step_lengths(2.1, 0.15).shape
(14,)
>>> step_lengths(0.0, 5.0).shape
(0,)
Source code in src/integrix/_src/march/_steps.py
def step_lengths(span: Number, step: Number) -> np.ndarray:
    """The K step lengths: Δt, and T − (K − 1) Δt for the last, on the host.

    They sum to T to rounding; K is `count_steps`. Each is in (0, Δt], except
    that the last is up to 10⁻⁹ K Δt longer where the quotient was taken as a
    whole number.

    Args:
        span: T ≥ 0, as in `count_steps`.
        step: Δt > 0, as in `count_steps`.

    Returns:
        The K lengths, in float64; empty for T = 0.

    Raises:
        ValidationError: As `count_steps` does.

    Examples:
        >>> step_lengths(12.0, 5.0).tolist()
        [5.0, 5.0, 2.0]
        >>> step_lengths(2.1, 0.15).shape
        (14,)
        >>> step_lengths(0.0, 5.0).shape
        (0,)
    """
    total, size = _checked(span, step)
    n_steps = count_steps(total, size)
    lengths = np.full(n_steps, size, dtype=np.float64)
    if n_steps:
        # Δt_K = T − (K − 1) Δt
        lengths[-1] = total - size * (n_steps - 1)
    return lengths

taylor_coefficients

taylor_coefficients(vector_field: Callable[..., Float[Array, ' state']], x0: Float[Array, ' state'], t0: ScalarLike, *, order: int, args: Any = None) -> Float[Array, 'derivative state']

The state and its first q time derivatives at t₀, by Taylor mode.

ẋ = f(t, x, args),    x(t₀) = x₀
x⁽¹⁾ = f,    x⁽²⁾ = ∂ₜf + J_f f,    …,    x⁽ᵏ⁺¹⁾ = dᵏ/dtᵏ f(t, x(t))

Row k of the result is the k-th derivative x⁽ᵏ⁾(t₀) itself, not the Taylor coefficient x⁽ᵏ⁾(t₀) / k!.

Algorithm
  1. Start from [x₀, f(t₀, x₀)].
  2. For k = 1, …, q − 1, propagate the truncated series of (t, x) through f with jax.experimental.jet: the series of t is (1, 0, …), that of x is the derivatives found so far, and the last output term is the next derivative x⁽ᵏ⁺¹⁾.
  3. Without jet, differentiate x⁽ᵏ⁾(t, x) along (1, f) with nested jax.jvp, at a cost that grows exponentially with q.

Parameters:

Name Type Description Default
vector_field Callable[..., Float[Array, ' state']]

The right-hand side f(t, x, args), diffrax's convention, as integrix.march.run takes it.

required
x0 Float[Array, ' state']

The initial state x₀, a vector.

required
t0 ScalarLike

The initial time t₀.

required
order int

The number of derivatives q ≥ 0.

required
args Any

Passed to the vector field.

None

Returns:

Type Description
Float[Array, 'derivative state']

The (q + 1) × D_x array [x₀; x⁽¹⁾(t₀); …; x⁽q⁾(t₀)] in x₀'s dtype.

Raises:

Type Description
ValidationError

If order is not a non-negative Python integer or x0 is not a vector.

Examples:

For ẋ = x every derivative equals x₀:

>>> import jax.numpy as jnp
>>> derivs = taylor_coefficients(
...     lambda t, x, args: x, jnp.array([1.0, 2.0]), 0.0, order=3
... )
>>> derivs.shape
(4, 2)
>>> bool(jnp.allclose(derivs, jnp.array([1.0, 2.0])))
True

A time-dependent field, ẋ = t: x⁽¹⁾(0) = 0, x⁽²⁾ = 1, x⁽³⁾ = 0:

>>> derivs = taylor_coefficients(
...     lambda t, x, args: t * jnp.ones_like(x), jnp.zeros(1), 0.0, order=3
... )
>>> derivs[:, 0].tolist()
[0.0, 0.0, 1.0, 0.0]
Source code in src/integrix/_src/march/_taylor.py
def taylor_coefficients(
    vector_field: Callable[..., Float[Array, " state"]],
    x0: Float[Array, " state"],
    t0: ScalarLike,
    *,
    order: int,
    args: Any = None,
) -> Float[Array, "derivative state"]:
    """The state and its first q time derivatives at t₀, by Taylor mode.

        ẋ = f(t, x, args),    x(t₀) = x₀
        x⁽¹⁾ = f,    x⁽²⁾ = ∂ₜf + J_f f,    …,    x⁽ᵏ⁺¹⁾ = dᵏ/dtᵏ f(t, x(t))

    Row k of the result is the k-th derivative x⁽ᵏ⁾(t₀) itself, not the
    Taylor coefficient x⁽ᵏ⁾(t₀) / k!.

    Algorithm:
        1. Start from [x₀, f(t₀, x₀)].
        2. For k = 1, …, q − 1, propagate the truncated series of (t, x)
           through f with `jax.experimental.jet`: the series of t is
           (1, 0, …), that of x is the derivatives found so far, and the
           last output term is the next derivative x⁽ᵏ⁺¹⁾.
        3. Without ``jet``, differentiate x⁽ᵏ⁾(t, x) along (1, f) with nested
           `jax.jvp`, at a cost that grows exponentially with q.

    Args:
        vector_field: The right-hand side f(t, x, args), diffrax's
            convention, as `integrix.march.run` takes it.
        x0: The initial state x₀, a vector.
        t0: The initial time t₀.
        order: The number of derivatives q ≥ 0.
        args: Passed to the vector field.

    Returns:
        The (q + 1) × D_x array [x₀; x⁽¹⁾(t₀); …; x⁽q⁾(t₀)] in x₀'s dtype.

    Raises:
        ValidationError: If ``order`` is not a non-negative Python integer
            or ``x0`` is not a vector.

    Examples:
        For ẋ = x every derivative equals x₀:

        >>> import jax.numpy as jnp
        >>> derivs = taylor_coefficients(
        ...     lambda t, x, args: x, jnp.array([1.0, 2.0]), 0.0, order=3
        ... )
        >>> derivs.shape
        (4, 2)
        >>> bool(jnp.allclose(derivs, jnp.array([1.0, 2.0])))
        True

        A time-dependent field, ẋ = t: x⁽¹⁾(0) = 0, x⁽²⁾ = 1, x⁽³⁾ = 0:

        >>> derivs = taylor_coefficients(
        ...     lambda t, x, args: t * jnp.ones_like(x), jnp.zeros(1), 0.0, order=3
        ... )
        >>> derivs[:, 0].tolist()
        [0.0, 0.0, 1.0, 0.0]
    """
    try:
        order = operator.index(order)
    except TypeError as err:
        raise ValidationError(
            f"'order' must be a Python integer, got {type(order).__name__}"
        ) from err
    if order < 0:
        raise ValidationError(f"'order' must be non-negative, got {order}")
    state = jnp.asarray(x0)
    if state.ndim != 1:
        raise ValidationError(f"'x0' must be a vector, got shape {state.shape}")
    time = jnp.asarray(t0, dtype=state_time_dtype(state))

    def field(t: Float[Array, ""], x: Float[Array, " state"]) -> Float[Array, " state"]:
        return jnp.asarray(vector_field(t, x, args), dtype=state.dtype)

    if _jet is None:  # pragma: no cover - present in every supported JAX
        return _taylor_jvp(field, state, time, order)
    return _taylor_jet(_jet.jet, field, state, time, order)