Adaptive step-size control¶
A fixed grid uses the same step size on the whole interval. An adaptive solver chooses its steps instead, with long steps where the solution is smooth and short steps where it changes quickly. After every trial step it estimates the local error from quantities that the filter step computes in any case, and compares the error with a tolerance. If the error exceeds the tolerance, the step is retried with a smaller step size $h$. Otherwise the step is accepted, and a controller proposes the next $h$.
import logging
import jax
import jax.numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator, NullFormatter, ScalarFormatter
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,
PController,
gaussian_filter_adaptive,
rts_smoother,
taylor_mode_initialization,
)
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
Basic usage¶
gaussian_filter_adaptive takes the times at which the solution is needed,
save_at, and chooses its steps in between. It returns a FilterResult on
save_at, as gaussian_filter does on its grid, and the whole solve can be
jit-compiled, vmap-ed and differentiated.
As an example, we take a solution that decays slowly and receives a short pulse at $t = 5$:
$$\dot x = -0.3\,x + 5\,e^{-((t - 5)/0.15)^2}, \qquad x(0) = 1, \qquad t \in [0, 10].$$
def vf(x, *, t):
return -0.3 * x + 5.0 * np.exp(-(((t - 5.0) / 0.15) ** 2))
prior = IWP(q=2, d=1)
m_0, P_0_sqr = taylor_mode_initialization(vf, np.array([1.0]), q=2)
measure = ODEInformation(vf, prior.E0, prior.E1)
save_at = np.linspace(0.0, 10.0, 101)
result = gaussian_filter_adaptive(
m_0, P_0_sqr, prior, measure, save_at, atol=1e-4, rtol=1e-3
)
print("reached every save time:", bool(result.success))
reached every save time: True
Where the steps go¶
The result on the save grid does not contain the steps that the solver took,
and record_steps= records them. In the figure, each dot on the solution (top)
is an accepted step, and the bottom panel shows the size of each step.
60 accepted steps (17 rejected), from h = 0.017 to h = 0.51. A fixed grid with the smallest step would need 598.
Away from the pulse the steps are about half a time unit long. As the pulse
arrives the error estimate grows, and rejected steps are retried with a smaller
step size (17 rejections in the whole solve). Through the pulse the steps are
about thirty times shorter, and after the pulse they grow back. By default the
solver reports only the save grid, with the numbers of accepted and rejected
steps per save interval in result.n_accepted and result.n_rejected.
Tolerances¶
A step is accepted when its tolerance-weighted local error is at most one:
$$\mathrm{err} = \sqrt{\frac{1}{d} \sum_{i=1}^{d} \left(\frac{D_i}{\mathrm{atol} + \mathrm{rtol}\,|x_i|}\right)^2} \;\le\; 1,$$
where $x_i$ is the predicted value of component $i$ and $D_i$ the standard deviation
that the step's (calibrated) process noise adds to it. The defaults are
atol=1e-4 and rtol=1e-2. Tighter tolerances give shorter steps and a more
accurate solution.
Controllers¶
The controller computes the next step size from the error of the step just
taken. Two controllers are built in, and either is passed as controller=:
| Controller | Next step | Use when |
|---|---|---|
PIController(order=q) (default) |
$h \cdot s \cdot \mathrm{err}^{-\alpha} \cdot (\mathrm{err}_\mathrm{prev} / \mathrm{err})^{\beta}$ | in general; the last factor damps oscillations of the error around the tolerance |
PController(order=q) |
$h \cdot s \cdot \mathrm{err}^{-\alpha}$ | the next step should depend on the current error only |
The default safety factor is $s = 0.9$. The default gains are $\alpha = 0.7/q$
and $\beta = 0.4/q$ for PIController (Gustafsson, 1991) and $\alpha = 1/q$ for
PController. The factor applied to $h$ is clipped to
[min_factor, max_factor] = [0.2, 5].
A custom controller needs only a propose(h, err, err_prev) method. The solver
calls it inside its compiled loop, so write it with jax.numpy. A non-positive
err_prev signals that there is no previous error (at the first step, or right
after a rejected one).
result_p = gaussian_filter_adaptive(
m_0, P_0_sqr, prior, measure, save_at, atol=1e-4, rtol=1e-3,
controller=PController(order=2),
)
Step bounds¶
Steps never cross a save time, and apart from this only the error estimate
limits them. With a loose tolerance, the solver can therefore step over a
feature shorter than its steps, since each step evaluates the vector field at
its end only. With a pulse three times narrower and looser tolerances, the
solver misses the pulse: it ends near $x(10) = 0.050$, the value without a
pulse, instead of the exact $0.149$. max_step= bounds every step, the first
one included. A bound no longer than the pulse lets the solver resolve it:
def vf_narrow(x, *, t):
return -0.3 * x + 5.0 * np.exp(-(((t - 5.0) / 0.05) ** 2))
m_0_narrow, P_0_narrow_sqr = taylor_mode_initialization(vf_narrow, np.array([1.0]), q=2)
measure_narrow = ODEInformation(vf_narrow, prior.E0, prior.E1)
for max_step in (None, 0.05):
x_end = gaussian_filter_adaptive(
m_0_narrow, P_0_narrow_sqr, prior, measure_narrow, np.array([0.0, 10.0]),
atol=1e-3, rtol=1e-2, max_step=max_step,
).m[-1, 0]
print(f"max_step={max_step}: x(10) = {x_end:.3f}")
max_step=None: x(10) = 0.050
max_step=0.05: x(10) = 0.149
The default, max_step=None, bounds the steps by the save times only. There is
no minimum step. A save interval that would need more than max_steps steps
ends the solve with success = False (see below).
The first step¶
The first trial step is h_init. The default, h_init=None, is a hundredth of
the save span, (save_at[-1] - save_at[0]) / 100, independent of the time
scale of the solution. h_init="auto" computes the first step from the initial
state and the tolerances, by the starting step-size rule of Hairer, Nørsett &
Wanner (Solving Ordinary Differential Equations I, Sec. II.4). With the scale
$s = \mathrm{atol} + \mathrm{rtol}\,|x_0|$ and the root-mean-square norms
$d_0 = \lVert x_0 / s \rVert$, $d_1 = \lVert x_0' / s \rVert$ and
$d_2 = \lVert x_0'' / s \rVert$, the first step is
$$h = \min(100\,h_0,\ h_1), \qquad h_0 = 0.01\,\frac{d_0}{d_1}, \qquad h_1 = \left(\frac{0.01}{\max(d_1, d_2)}\right)^{1/(q+1)},$$
where $h_0 = 10^{-6}$ if $d_0$ or $d_1$ is below $10^{-5}$, and
$h_1 = \max(10^{-6}, 10^{-3} h_0)$ if $\max(d_1, d_2) \le 10^{-15}$. The rule
reads $x_0'$ and $x_0''$ from the initial mean, which must therefore carry them,
as taylor_mode_initialization provides. For q = 1 the state holds no $x''$,
and $x_0''$ is the difference quotient
$(f(x_0 + h_0 x_0', t_0 + h_0) - f(x_0, t_0)) / h_0$ of the vector field. For
the decay $x' = -k x$ with $k \ge 1$, the norms are $d_1 = k\,d_0$ and
$d_2 = k^2 d_0$, so $h_1$ scales as $k^{-2/(q+1)}$. max_step and the save
times bound the first step like every other step.
Smoothing¶
By default the adaptive solver only filters. With smoother=True it also runs a
fixed-point smoother during the forward pass, which stores one backward step per
save interval, independent of the number of steps in the interval (Krämer,
Adaptive Probabilistic ODE Solvers Without Adaptive Memory Requirements, 2025).
rts_smoother then applies to the result. The smoother also conditions on data
passed as obs_model.
result = gaussian_filter_adaptive(
m_0, P_0_sqr, prior, measure, save_at, atol=1e-4, rtol=1e-3, smoother=True
)
m_smooth, P_smooth_sqr = rts_smoother(result)
When a solve does not finish¶
The solver does not raise inside a compiled solve. If a save interval needs more
than max_steps steps (4096 by default), the solver stops there and sets
result.success = False, and the saves from that point on hold the last
accepted state. In that case, raise max_steps or loosen the tolerances.
success is also False when the log-likelihood is not finite.
See also Diffusion calibration, for the $\sigma^2$ that enters the error estimate, and the Calibration modes notebook.