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:
SSP_RK2
¶
SSP_RK104
¶
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:
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:
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 |
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
|
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
|
required | |
sde_key
|
The PRNG key of the Brownian path. It is fixed, so rebuild the
model with another one ( |
required | |
brownian_shape
|
The shape of the Brownian increment. |
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
¶
None: the model advertises no shape contract to a pipekit cycle.
step
¶
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 |
Source code in src/integrix/_src/march/_forward_model.py
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
as_dynamics
¶
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 |
Source code in src/integrix/_src/march/_forward_model.py
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
init
abstractmethod
¶
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
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
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 |
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)
init
¶
step
¶
Leapfrog from the filtered ȳₙ₋₁, then filter yₙ; the history becomes ȳₙ.
Source code in src/integrix/_src/march/_multistep.py
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
initbuilds ξ₀ from x₀ and its first q derivatives by Taylor mode (taylor_coefficients), with zero covariance.- 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. - Linearise f at the predicted mean: J_f for
"ek1", its diagonal for"diagonal_ek1", zero for"ek0". - Predict with
gaussx_infer.sqrt_kalman_predictand condition on r = 0 withgaussx_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. "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"keepsoutput_scale."smoother"also stores each step's backward conditional (gaussx_infer.sqrt_backward_conditional), andODEFilter.solutionrunsgaussx_infer.sqrt_rts_stepback 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']
|
|
strategy |
Literal['filter', 'smoother']
|
|
calibration |
Literal['none', 'mle', 'dynamic']
|
|
covariance |
Literal['dense', 'isotropic', 'blockdiag']
|
|
output_scale |
ScalarLike
|
The prior's fixed scale σ for |
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
¶
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
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
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 |
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
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
|
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 |
offset |
Float[Array, '*time latent'] | None
|
The backward offset b (in the mean's shape), or |
chol_backward |
Float[Array, '*batch coefficient coefficient'] | None
|
The factor L_b of the backward noise, or |
structure |
Literal['dense', 'isotropic', 'blockdiag']
|
|
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 ( |
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
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 |
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;
|
None
|
Returns:
| Type | Description |
|---|---|
SampledPath
|
The |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
GeometryError
|
If the times are not strictly
monotone, or uneven for a scheme that reads in index space
( |
Source code in src/integrix/_src/march/_sampled_path.py
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
|
left
|
bool
|
Unused: û is continuous ( |
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
derivative
¶
û′(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
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 |
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 |
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)
init
¶
No history to bootstrap: the first step is an ordinary one.
step
¶
One split_explicit_step of the pair (y₃, y₂).
Source code in src/integrix/_src/march/_split_explicit.py
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 |
fast |
Callable[..., PyTree]
|
The fast tendency |
slow_forcing |
Callable[..., PyTree] | None
|
|
couple |
Callable[..., PyTree] | None
|
|
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 ( |
required |
rhs
|
Callable[[Any, PyTree], PyTree]
|
The right-hand side f(t, y). |
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 |
required |
Returns:
| Type | Description |
|---|---|
PyTree
|
The state after the step, with the dtypes of |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |
euler_step
¶
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:
Source code in src/integrix/_src/march/_erk.py
heun_step
¶
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
rk3_ssp_step
¶
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
rk4_step
¶
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
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
- Y₁ = yₙ + γh f_I(Y₁):
implicit_solve(yₙ, γh). - Y₂ = yₙ + h f_E(Y₁) + (1 − 2γ) h f_I(Y₁), then
Y₂ = Y₂ + γh f_I(Y₂):
implicit_solve(Y₂*, γh). - 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
imex_solver
¶
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 |
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
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 ( |
None
|
Returns:
| Type | Description |
|---|---|
PIDController | ClipStepSizeController
|
A |
PIDController | ClipStepSizeController
|
when |
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
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; |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
Examples:
Advection only, along one axis of two:
Advection and diffusion add, so the bound is below each alone:
Nothing moves or diffuses:
Source code in src/integrix/_src/march/_imex_control.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | |
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
- A diffrax solver goes to
diffrax.diffeqsolveon the step times t₀ + n h (diffrax.StepTo), so it takes exactly N steps. - An
AbstractSteppertakes its first step withinitand the other N − 1 withstepinsidejax.lax.scan, carrying the state and its history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stepper
|
AbstractStepper | AbstractSolver
|
An |
required |
rhs
|
Callable[..., PyTree] | Any
|
The vector field |
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
|
adjoint
|
Any
|
How reverse mode runs back through the march. |
None
|
Returns:
| Type | Description |
|---|---|
PyTree
|
y_N, or the stacked y₁, …, y_N. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
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]
|
|
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
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
|
|
PyTree
|
the next |
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
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]
|
|
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
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
- x_d⁽⁰⁾ = x − Δt u(t, x).
- 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 |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
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
- x_d =
departure_points(nodes, u, t, Δt). - H = readout(x_d), the read-out of the old field at x_d.
- q(t + Δt) = H q(t).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
PyTree
|
The old field q(t), in whatever layout |
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, |
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 |
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
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
- F =
slow_forcing(state_3d), if given, held fixed over the cycle. - 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. - One forward-Euler step of the 3-D state:
y₃ + h
rhs_3d(state_3d, ⟨y⟩). 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 |
required |
rhs_2d
|
Callable[[ScalarLike, PyTree, PyTree], PyTree]
|
The fast tendency |
required |
couple_2d_to_3d
|
Callable[[PyTree, PyTree], PyTree]
|
|
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
|
|
None
|
t0
|
ScalarLike
|
The time at the start of the slow step. |
0.0
|
Returns:
| Type | Description |
|---|---|
tuple[PyTree, PyTree]
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
count_steps
¶
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 |
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
step_lengths
¶
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 |
required |
step
|
Number
|
Δt > 0, as in |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The K lengths, in float64; empty for T = 0. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
As |
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
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
- Start from [x₀, f(t₀, x₀)].
- 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⁽ᵏ⁺¹⁾. - Without
jet, differentiate x⁽ᵏ⁾(t, x) along (1, f) with nestedjax.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 |
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 |
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]