Conservation laws¶
Some systems obey an exact algebraic invariant, a quantity that stays constant
along every trajectory. ode_filters enforces such an invariant during the
solve through the public gaussian_filter API.
The mechanism is the one the solver already uses for the ODE. A probabilistic
solver treats the ordinary differential equation (ODE) itself as a
measurement. At each step it evaluates the residual of dx/dt = f(x, t) at the
current estimate and corrects the Gaussian posterior accordingly. A
conservation law is one more measurement in the same Kalman update.
The problem is an initial value problem (IVP), an ODE solved forward from a known initial value. The filter is an extended Kalman filter, and the Rauch–Tung–Striebel (RTS) smoother refines its result after the forward pass.
We import the fixed-grid filter, the RTS smoother, the IWP prior, and the
Taylor-mode initializer from the top level, and Conservation from the
ode_filters.information submodule. The final lines set the shared
documentation plot style.
import logging
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 (
IWP,
ODEInformation,
gaussian_filter,
rts_smoother,
taylor_mode_initialization,
)
from ode_filters.information import Conservation
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] # gray: exact solutions and other references
An epidemic that conserves its population¶
A classic example is the SIR epidemic model, which splits the population into
susceptible (S), infected (I) and recovered (R) fractions. Individuals only
move along S → I → R, so the total S + I + R is conserved and equals 1 for
all time.
A plain ODE solve has no information about this invariant. Each step introduces a numerical error, the errors accumulate, and the total drifts away from 1. Passing the invariant to the solver as a noiseless pseudo-observation keeps the total at 1 up to rounding.
In the SIR vector field below, susceptibles become infected at rate
beta * S * I, and infected individuals recover at rate gamma * I. The
initial infected fraction is 1%.
beta_sir = 0.5
gamma_sir = 0.1
def vf_sir(x, *, t):
"""SIR epidemic model with state x = [S, I, R]."""
S, I, _ = x # noqa: E741 (R does not enter the dynamics)
return np.array(
[
-beta_sir * S * I,
beta_sir * S * I - gamma_sir * I,
gamma_sir * I,
]
)
x0_sir = np.array([0.99, 0.01, 0.0])
tspan_sir = (0.0, 100.0)
N_sir = 100
ts_sir = np.linspace(*tspan_sir, N_sir + 1)
prior_sir = IWP(q=2, d=3, Xi=1.0 * np.eye(3))
mu_0_sir, P0_sqr_sir = taylor_mode_initialization(vf_sir, x0_sir, q=2)
A Conservation(A, p) object enforces the linear invariant A @ x = p as a
noiseless pseudo-observation. At every step the filter also conditions on this
invariant, which moves the estimate to states that satisfy it exactly. For the
population sum the invariant is [1, 1, 1] @ [S, I, R] = 1, so A is a single
row of ones and p is [1.0].
We attach it through the constraints= argument of ODEInformation. A
conservation law is active at every step and has a fixed shape, so it is part
of the ODE-information model. Data, in contrast, exist only at some times and
enter as a separate observation model (see the
Inference from data tutorials).
A_sum = np.array([[1.0, 1.0, 1.0]])
p_sum = np.array([1.0])
conservation = Conservation(A_sum, p_sum)
# Two measurement models: the plain ODE, and the ODE plus the invariant.
measure_free = ODEInformation(vf_sir, prior_sir.E0, prior_sir.E1)
measure_cons = ODEInformation(
vf_sir, prior_sir.E0, prior_sir.E1, constraints=[conservation]
)
We solve the IVP twice, once without the constraint and once with it, and
smooth each forward pass with the RTS smoother. Both runs use the default
"dynamic" calibration. This example examines the mean trajectory and its
invariant, not the uncertainty band.
def solve(measure):
result = gaussian_filter(
mu_0_sir, P0_sqr_sir, prior_sir, measure, np.linspace(*tspan_sir, N_sir + 1)
)
m_smooth, _ = rts_smoother(result)
return np.array(m_smooth)
m_free = solve(measure_free)
m_cons = solve(measure_cons)
# The conserved quantity along each trajectory, and its drift from 1.
total_free = m_free[:, :3].sum(axis=1)
total_cons = m_cons[:, :3].sum(axis=1)
resid_free = np.abs(total_free - 1.0)
resid_cons = np.abs(total_cons - 1.0)
On a logarithmic axis we plot how far S + I + R strays from 1. Without the
constraint the total drifts to about 7e-5. With it, what remains is rounding
in float64 arithmetic of at most 4.4e-16, twice machine epsilon (the gray
line). At more than half of the steps the total is exactly 1, which a
logarithmic axis cannot show.
fig, ax = plt.subplots()
ax.axhline(np.finfo(float).eps, color=REFERENCE, lw=2.5, label="machine epsilon")
# A total of exactly 1 (zero drift) cannot be drawn on a log axis: leave it out.
ax.semilogy(ts_sir, np.where(resid_free > 0, resid_free, np.nan), color=palette[1], label="ODE only")
ax.semilogy(
ts_sir, np.where(resid_cons > 0, resid_cons, np.nan), "o", ms=2.5,
color=palette[0], label="ODE + conservation law",
)
ax.set_ylim(1e-17, 1e-2)
ax.set_xlabel("$t$ (days)")
ax.set_ylabel("$|S + I + R - 1|$")
ax.legend(loc="center right")
plt.show()
print(f"max drift without constraint: {resid_free.max():.2e}")
print(f"max drift with constraint: {resid_cons.max():.2e}")
max drift without constraint: 6.78e-05 max drift with constraint: 4.44e-16
Summary¶
A Conservation(A, p) object enforces the linear invariant A @ x = p as a
noiseless pseudo-observation. It is active at every step, so it is part of
ODEInformation(..., constraints=[...]) and reuses the Kalman update of the
ODE itself. With the SIR population sum constrained, the invariant holds to
float64 rounding (~1e-16) instead of drifting to ~7e-5.
Data are the other kind of additional information. They exist only at some
times, so they enter as a separate observation model, a list of Measurement
objects passed to the solver as measurements=. The
Inference from data tutorials use them to
estimate parameters and hidden inputs. The library also
offers nonlinear observation models through BlackBoxMeasurement and
TransformedMeasurement, and Gaussian-process priors through MaternPrior.
To choose a linearization, see Linearization schemes. To
match the prior and the step size to a problem, see
How to choose.