Differential Equations#
ODE turns a right hand side, an initial state
and a time grid into a path valued expression of the model. The state, the
initial condition and every parameter may be constants,
Param leaves or random variables, so uncertainty
can enter anywhere. The Monte Carlo sample axis becomes the batch of the
native integrator, and gradients flow through the whole trajectory in
reverse mode.
Left: 24 trajectories of the Lorenz system, integrated in one batched call from initial states that differ by a quarter unit, coloured by time. The orange path starts from the nominal state. Right: the mean distance of the ensemble to the nominal path. Within about three time units the small uncertainty of the start has grown to the size of the attractor, which is why a chaotic model needs a distribution and not a single run.
import jax.numpy as jnp
import prophys as prp
def lorenz(t, y, params):
"""The Lorenz 1963 convection model, ``y`` has shape [B, 3]."""
x, v, z = y[:, 0], y[:, 1], y[:, 2]
return jnp.stack([10.0 * (v - x), x * (28.0 - z) - v, x * v - 8.0 / 3.0 * z], axis=1)
times = jnp.linspace(0.0, 9.0, 1801)
path = prp.ODE("lorenz", lorenz, initial_states, times) # initial_states [24, 3]
path.evaluate({}) # [24, 3, 1801], time is the last axis
A random damping or initial state turns the trajectory into a distribution the model can assess.
Fit parameters to observed paths with the exact gradient through the integrator.
Fixed step or adaptive integration, mass matrices and the stable diagnostics of a refused path.
Writing the right hand side#
The right hand side rhs(t, y, params) is a pure jax.numpy function.
y is the state with shape [B, d], t holds one time per batch
element and params is a tuple with one evaluated entry per parameter. It
returns the derivative with exactly the shape of y. A parameter that is a
random variable arrives with its own sample axis [B], so align it with
the state when it multiplies the whole state, c[:, None] * y, or
broadcast it to a component as below. Every axis of a parameter counts as
batch unless you say otherwise, so a coefficient matrix that all samples
share is declared with its two own axes, param_event_ndims=[2].
def pendulum(t, y, params):
"""Angle and angular velocity of a damped pendulum."""
damping, omega2 = params
theta, rate = y[:, 0], y[:, 1]
damping = jnp.broadcast_to(damping, theta.shape) # a scalar or one value per sample
return jnp.stack([rate, -omega2 * jnp.sin(theta) - damping * rate], axis=1)
damping = prp.Param("damping", init=0.3)
path = prp.ODE("pendulum", pendulum, jnp.array([1.2, 0.0]), times, params=[damping, 9.81])
The result holds the state at times[0] and at the end of every interval,
with time as its last axis like every process valued expression, so the
reductions of Processes such as time_mean()
apply to it directly.
Uncertain parameters and initial states#
Pass a random variable as a parameter and the trajectory becomes a distribution. Below, the damping of the pendulum varies by 35 percent and the release angle by 0.08 rad, and 6000 trajectories are one native call.
The probability density of the pendulum angle every 0.2 s, drawn as slices standing on the time axis, with the median angle and its 90 percent band on the floor. The density is sharp where the pendulum turns and slow, and wide where it swings fast through the bottom. As the uncertain damping takes effect the band widens and the swings of different units drift apart.
Inside a compiled model, the probability of an event on the path is one call:
from prophys.symbolic.expr import op
mu = prp.Param("mu", init=jnp.log(0.3))
damping = prp.RandomVariable("damping", prp.LogNormal(mu=mu, sigma=0.4))
path = prp.ODE("pendulum", pendulum, jnp.array([1.2, 0.0]), times, params=[damping, 9.81])
late_swing = op("late_swing", lambda p: jnp.abs(p[..., 0, -1]), path) # |angle| at the end
still_swinging = prp.UncertainAttribute(
"still_swinging",
prp.Bernoulli(prob=op("exceeds", lambda s: (s > 0.1).astype(jnp.float32), late_swing)),
)
compiled = prp.ProbabilityModel(still_swinging).compile(mode="eval", n_samples=1024)
compiled.assess("still_swinging") # the probability with its Monte Carlo standard error
Calibration by gradient#
Gradients are exact reverse mode through the integration. The step vector Jacobian products are native, and the backward pass recomputes each step instead of storing it, so a long horizon costs compute and not memory. A parameter of the right hand side can therefore be fitted to observations like any other parameter of a model.
Left: the log mean squared misfit between the pendulum and twenty noisy observations over its damping and squared frequency, 1681 trajectories in one batched call, with the path of 120 gradient steps from the start (dot) to the fit (star). Right: the observations, the starting guess and the fitted path. The fit recovers a damping of 0.23 and a squared frequency of 5.97 against the true 0.25 and 6.0.
import jax
def misfit(c, w):
"""Mean squared misfit of the modelled angle to the observations."""
theta = path.evaluate({"damping": c, "omega2": w})[0, observed_steps]
return jnp.mean((theta - observations) ** 2)
jax.grad(misfit, argnums=(0, 1))(0.9, 8.2) # exact, through every integration step
The same gradient drives calibrate() and
optimize() when the path sits inside a compiled model,
see Training & Design Optimization.
Methods and guarantees#
|
What it does |
|---|---|
|
One classical fourth order Runge Kutta step per grid interval. Fast and fully predictable, the right choice when the grid resolves the dynamics. |
|
The Dormand Prince 5(4) embedded pair with error control. Each grid
interval is advanced by accepted steps whose scaled error is within
|
path = prp.ODE("chain", spring_chain, y0, times, params=[40.0], method="dp54", rtol=1e-6, atol=1e-9)
With mass the problem is M dy/dt = f(t, y). The right hand side then
returns the force f, and every stage solves the mass system exactly in
the native kernel, differentiable through the solve.
When a trajectory is refused
The integrator never returns a degraded path. A tolerance missed within
the step budget raises DYN101, a step collapsed below min_step
raises DYN102, a singular mass matrix DYN103, a time grid that is
not strictly increasing DYN105 and a state that became non finite
DYN106. The codes are listed with every other on the
Diagnostics page.
ODE, Recurrence or propagate_linear
For a linear system dx/dt = Q x + u the matrix exponential of
propagate_linear() is exact and needs no time
steps. For a state that changes in discrete steps, such as a daily
balance, Recurrence applies an update rule
per step. ODE is for everything continuous
and nonlinear in between.
Reference#
- class prophys.processes.ODE(name, rhs, initial, times, params=(), mass=None, method='rk4', atol=1e-06, rtol=0.001, min_step=None, max_attempts=64, first_step=None, param_event_ndims=None)[source]
A differentiable initial value problem compiled to a path valued leaf.
The fold runs over times (the time axis is the last axis of the result, as for every process valued expression):
"rk4"takes one classical fourth order Runge Kutta step per grid interval inside ajax.lax.scanover the fixed grid, and"dp54"advances each interval with the Dormand Prince 5(4) embedded pair, accepting a step when its scaled mixed error norm is within atol and rtol and retrying with the shrunk step the native controller proposes otherwise. A sample whose interval is not completed within max_attempts attempted steps raisesDYN101, a step that collapses below min_step raisesDYN102and a singular mass matrix raisesDYN103, through the trajectory status gate, never as a quietly wrong path.The right hand side rhs(t, y, params) is a pure function of
jax.numpyvalues: t is the step start with one entry per batch element, y the state[B, d]and params a tuple with one entry per expression of params, constant along the path and passed to the rhs as evaluated, like the params of aRecurrence. The batch of the state broadcasts the leading shape of the initial state, of the mass matrix and of every parameter. A parameter’s shape is batch except for its last param_event_ndims axes, zero by default, so a drawn rate[B](the sample axis of the engine’s marginalization) integrates one path per draw while a coefficient matrix declared with two event axes stays one matrix shared by the batch. A shared scalar parameter multiplies the state naturally, a parameter with the leading batch axis must be aligned explicitly,l[:, None] * y, when it multiplies the whole state. The rhs must return exactly the state shape[B, d], and any other shape raises before it can corrupt the stages. With mass the problem isM dy/dt = f(t, y), the rhs returns the force f and every stage derivative is the exact native solve of the mass system, differentiable through the solve.Gradients are exact reverse mode through the fold: the step vector Jacobian products are hand derived and native, and the scan stores only the per interval carry while the interval bodies are recomputed on the backward pass (
jax.checkpoint), so a long horizon costs compute, not memory. The accept and retry masks are straight branches, so a cotangent only flows through the branch the trajectory took. The adaptive method skips an attempt outright once every sample of the batch has finished its interval, so the attempt budget bounds the work and does not set it.- Parameters:
name (str) – Label of the node.
rhs (Callable[..., Any]) – Pure function
rhs(t, y, params) -> dyof the same trailing dimension as y.initial (Any) – Initial state, shape
[d]or[B, d], an expression or an array.times (Any) – Time grid, one dimensional and strictly increasing, an expression or an array. The result holds the state at
times[0]and at the end of every interval.params (Sequence[Any]) – Expressions or arrays constant along the path, passed to rhs as the params tuple.
mass (Any) – Optional mass matrix
MofM dy/dt = f(t, y), shape[d, d]or[B, d, d].method (str) –
"rk4"for the fixed step fourth order method or"dp54"for the adaptive embedded pair.atol (float) – Absolute tolerance of the adaptive error control.
rtol (float) – Relative tolerance of the adaptive error control.
min_step (float | None) – Step collapse threshold of the adaptive method, by default a scale of the machine epsilon and the grid span.
max_attempts (int) – Attempted step budget of the adaptive method per grid interval, accepted or rejected, by default 64.
first_step (float | None) – Initial step of the adaptive method, by default the first grid interval.
param_event_ndims (Sequence[int] | None) – Number of trailing axes of each parameter that belong to the parameter itself rather than to the batch, one entry per parameter, zero for all by default.
- Raises:
ValueError – If method is unknown, atol or rtol is not positive or max_attempts is less than one.
prophys.diagnostics.ProphysError – With code
DYN101when the tolerance is not met within the step budget,DYN102when the step collapses below the minimum,DYN103when the mass matrix is singular,DYN105when the time grid is not strictly increasing andDYN106when the state becomes non finite.
Example:
from prophys.processes import ODE def decay(t, y, params): (lam,) = params return -lam * y times = jnp.linspace(0.0, 2.0, 65) path = ODE("decay", decay, jnp.array([1.0]), times, params=[prp.Param("lam", init=0.8)]) path.evaluate({}) # shape [1, 65], the state at every grid point