Second-order systems¶
Many physical models are second-order ordinary differential equations (ODEs) of the form
$$x''(t) = f\big(x(t),\, x'(t),\, t\big),$$
where the acceleration $x''$ depends on the position $x$ and the velocity $x'$. The standard approach reduces such a system to first order: it stacks $[x, x']$ into a new state and solves a first-order ODE of twice the dimension. The reduction discards structure, since the solver no longer represents the second component as the derivative of the first.
This notebook solves a second-order ODE directly, with two components:
- We use an integrated Wiener process (IWP) prior
IWP(q, d=1). A second-order ODE constrains the acceleration $x''$, so the state of the prior must contain at least $x''$, which requires $q \ge 2$. We takeq=3(state $[x, x', x'', x''']$). One derivative beyond the constraint gives a smoother prior of higher order, which tracks the oscillation over many periods. As in the quickstart, a higherqgives a higher order of accuracy. Withq=2the largest error of the mean over this horizon would be 0.2 instead of $1.5 \times 10^{-4}$. - The information operator
SecondOrderODEInformationimposes the dynamics on the acceleration: it conditions on $x''(t) = f(x, x', t)$ at every step. The matricesE0,E1,E2extract $x$, $x'$, $x''$ from the state, and the constraint acts throughE2.
The vector field therefore has the second-order signature:
def vf(x, dx, *, t):
return ddx # the acceleration
The output of the solve is a Gaussian posterior over the solution, which consists of a mean and a calibrated uncertainty band. The test case is the damped harmonic oscillator, whose closed-form solution serves as the reference.
The imports are the IWP prior, the SecondOrderODEInformation measurement
model, gaussian_filter for the forward pass, rts_smoother (RTS =
Rauch-Tung-Striebel) for the backward smoothing pass, and
taylor_mode_initialization for the initial state. The last lines set the plot
style of the docs.
import logging
import equinox as eqx
import jax
import jax.numpy as np
import matplotlib.pyplot as plt
from matplotlib_inline.backend_inline import set_matplotlib_formats
from tueplots import bundles, cycler
from tueplots.constants.color import palettes
from ode_filters import (
gaussian_filter,
interpolate,
rts_smoother,
taylor_mode_initialization,
)
from ode_filters.information import ODEInformation, SecondOrderODEInformation
from ode_filters.priors import IWP
jax.config.update("jax_enable_x64", True)
plt.rcParams.update(bundles.tue_ai_beamer())
plt.rcParams.update(cycler.cycler(color=palettes.paultol_bright))
set_matplotlib_formats("svg") # vector figures stay sharp at any size
# Fall back to the default font quietly where Roboto Condensed is not installed.
logging.getLogger("matplotlib.font_manager").setLevel(logging.ERROR)
palette = plt.rcParams["axes.prop_cycle"].by_key()["color"]
REFERENCE = palette[6] # grey: exact solutions and other references
The damped harmonic oscillator¶
A mass on a spring with friction obeys
$$x'' = -\omega^2\, x - \gamma\, x',$$
where $\omega$ is the natural frequency and $\gamma = 2\zeta\omega$ sets the damping (with damping ratio $\zeta$). The restoring force pulls the mass back towards zero, and the friction term dissipates energy, so the oscillation decays over time.
The vector field below is the second-order equation as written: it takes the
position x and the velocity dx and returns the acceleration. We start the
oscillator at $x=1$ and at rest ($x'=0$), and integrate over $t \in [0, 30]$ on
a grid of 100 steps.
omega, zeta = 1.0, 0.1
gamma = 2 * zeta * omega
omega_d = np.sqrt(1 - zeta**2) * omega # damped frequency
tspan, N = (0, 30), 100
ts = np.linspace(tspan[0], tspan[1], N + 1)
def vf(x, dx, *, t):
return -(omega**2) * x - gamma * dx
x0, dx0 = np.array([1.0]), np.array([0.0])
Prior, measurement model, and initial state¶
We choose an IWP(q=3, d=1) prior. With the order q=3, the modeled state at
each time is $[x, x', x'', x''']$, and d=1 because the oscillator is scalar
(one spatial dimension). A second-order ODE requires only q=2, so that $x''$
is in the state and can be constrained. On an oscillation over many periods,
q=3 is more accurate, and with q=2 the mean would lag behind the true curve.
Xi is the prior's diffusion scale matrix (here 1×1). We use the identity,
since the per-step diffusion calibration sets the overall scale on top of it.
SecondOrderODEInformation holds the vector field and the extraction matrices
E0, E1, E2, which select $x$, $x'$, $x''$. It imposes
$x''(t) = f(x, x', t)$ during filtering.
taylor_mode_initialization builds a consistent initial mean, with a zero
(Dirac) initial covariance, from the initial position and velocity. We pass
order=2, since the ODE is of second order and we supply $x(0)$ and $x'(0)$.
The function then differentiates the vector field to obtain the remaining
initial derivatives of the q=3 state.
prior = IWP(q=3, d=1, Xi=np.eye(1))
measure = SecondOrderODEInformation(vf, prior.E0, prior.E1, prior.E2)
m_0, P_0_sqr = taylor_mode_initialization(vf, (x0, dx0), q=3, order=2)
Solve: filter, then smooth¶
gaussian_filter runs the forward pass of the extended Kalman filter (EKF),
from left to right, and conditions on the ODE at each step. We leave
calibration at its default ("dynamic"), so the solver rescales the
diffusion at each step from the ODE residuals (an approximate quasi-MLE). The
width of the uncertainty band then follows the observed residuals instead of a
fixed scale.
rts_smoother then runs the backward pass, which conditions every state
estimate on the information from later times. We compile both passes with
equinox.filter_jit. It traces the arrays, which include the time grid and the
arrays of the prior and the measurement model, and treats the other values,
such as the vector field, as static.
jit_filter = eqx.filter_jit(gaussian_filter)
jit_smoother = eqx.filter_jit(rts_smoother)
result = jit_filter(m_0, P_0_sqr, prior, measure, np.linspace(*tspan, N + 1))
smoothed = jit_smoother(result) # a Gaussian: mean smoothed.m, factor smoothed.P_sqr
m_smooth = np.array(smoothed.m)
Compare against the closed-form solution¶
An underdamped oscillator ($\zeta < 1$) with the initial conditions $x(0)=1$, $x'(0)=0$ has the closed-form solution
$$x(t) = e^{-\zeta\omega t}\Big(\cos(\omega_d t) + \tfrac{\zeta\omega}{\omega_d}\sin(\omega_d t)\Big), \qquad x'(t) = -\frac{\omega^2}{\omega_d}\, e^{-\zeta\omega t} \sin(\omega_d t),$$
with the damped frequency $\omega_d = \sqrt{1-\zeta^2}\,\omega$.
The state contains the velocity as well as the position, so the left panel
shows the solution in the phase plane. The oscillation spirals in towards rest,
and the posterior mean lies on the exact spiral. interpolate evaluates the
smoothed posterior between the grid points (dense output), so the curves are
smooth. The right panel compares the error in the position with two standard
deviations (.std computes the square root of the diagonal of
$P = P_{\text{sqr}}^\top P_{\text{sqr}}$ from the factor). The error is at most
0.08 times the band at every point, so on this problem the uncertainty estimate
is conservative.
t_dense = np.linspace(tspan[0], tspan[1], 1201)
dense = interpolate(result, prior, t_dense) # the smoothed posterior at t_dense
x, dx, x_std = dense.m[:, 0], dense.m[:, 1], dense.std[:, 0]
decay = np.exp(-zeta * omega * t_dense)
x_true = decay * (np.cos(omega_d * t_dense) + (zeta * omega / omega_d) * np.sin(omega_d * t_dense))
dx_true = -(omega**2 / omega_d) * decay * np.sin(omega_d * t_dense)
fig, (left, right) = plt.subplots(1, 2)
left.plot(x_true, dx_true, color=REFERENCE, lw=2.5, label="exact solution")
left.plot(x, dx, color=palette[0], label="posterior mean")
left.set_xlabel("position $x$")
left.set_ylabel("velocity $x'$")
left.legend(loc="upper right")
right.semilogy(t_dense, np.abs(x - x_true), color=REFERENCE, lw=2.5, label="actual error")
right.semilogy(t_dense, 2 * x_std, color=palette[0], label="2 std")
right.set_xlabel("$t$")
right.set_ylabel("error in $x$")
right.legend(loc="lower center", ncols=2)
plt.show()
When to use second-order form¶
For a model of second order, such as an oscillator, an $N$-body or
celestial-mechanics problem, a structural-dynamics model or any Newtonian
system in which forces set accelerations, use SecondOrderODEInformation with
an IWP of order q >= 2. When the solution oscillates over many periods, use
one order more, q = 3 as here. In second-order form the prior encodes that
the velocity is the derivative of the position. A first-order reduction models
the two as independent processes, which the ODE information couples only at
the grid nodes. The vector field is the acceleration law vf(x, dx, *, t)
itself. For first-order problems, use the first-order interface (see
Multi-dimensional systems).
ODEs of order three and higher¶
ODEInformation and SecondOrderODEInformation cover equations of first and
second order, and taylor_mode_initialization accepts order=1 or order=2.
An equation of higher order is reduced to a first-order system. A third-order
equation,
$$x''' = f(x, x', x''),$$
becomes a first-order system in $z = (x, x', x'')$, the solution stacked with its first two derivatives:
$$z' = \big(x',\, x'',\, f(x, x', x'')\big).$$
The reduction gives up the structure that the second-order form keeps. With
IWP(q, d=3) the state holds $z$ and its first $q$ derivatives, so $x'$ and
$x''$ appear twice: as components of $z$ and as derivatives of $x$. The prior
models the three components of $z$ as independent processes, and the ODE
information equates the duplicates at the grid nodes.
We check the reduction on $x''' = -x'$ with $x(0) = 0$, $x'(0) = 1$ and
$x''(0) = 0$, whose solution is $x(t) = \sin t$. The field vf3 below is the
reduced system, and taylor_mode_initialization differentiates it to obtain
the initial derivatives of $z$. We use q=3, as for the oscillator above.
def vf3(z, *, t):
# x''' = -x' as a first-order system in z = (x, x', x''); x itself is unused.
_, dx, ddx = z
return np.array([dx, ddx, -dx])
prior3 = IWP(q=3, d=3)
measure3 = ODEInformation(vf3, prior3.E0, prior3.E1)
m_0, P_0_sqr = taylor_mode_initialization(vf3, np.array([0.0, 1.0, 0.0]), q=3)
ts3 = np.linspace(0.0, 10.0, 101)
posterior3 = rts_smoother(gaussian_filter(m_0, P_0_sqr, prior3, measure3, ts3))
# The state is derivative-major, so entry 0 is the first component of z: x.
x3, x3_std = posterior3.m[:, 0], posterior3.std[:, 0]
error = np.abs(x3 - np.sin(ts3))
print(f"largest error in x on [0, 10]: {float(error.max()):.1e}")
print(f"largest error / std after t = 0: {float((error / x3_std)[1:].max()):.2f}")
largest error in x on [0, 10]: 1.4e-05 largest error / std after t = 0: 0.68
The posterior mean of $x$ agrees with $\sin t$ to $1.4 \times 10^{-5}$, and
after the exact initial value the error stays below one posterior standard
deviation at every node. The same reduction applies to any order $k$: stack
$x, x', \dots, x^{(k-1)}$ into $z$, write the field of $z$, and solve with
ODEInformation and IWP(q, d=k d_x) for a solution $x$ of dimension $d_x$.