Calibration modes¶
A probabilistic ODE solver returns a mean trajectory and an uncertainty band. The
band comes from the prior, a random process whose size is set by a scale, the
diffusion $\sigma^2$. Nothing about the ODE tells the solver what that scale
should be, so it has to be estimated while solving. That estimate is
calibration. This notebook shows what it does, and what the modes of the
calibration= argument change:
| Mode | $\widehat\sigma^2$ |
|---|---|
"none" |
no estimate: the prior's own scale is used as is |
| post-hoc | one value for the whole run, fitted after a "none" solve |
"dynamic" (default) |
one value per step |
"diagonal" |
one value per step and per component |
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,
posthoc_mle_sigma_sqr,
rescale_sqr_seq,
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] # gray: exact solutions and other references
def std_of(P_sqr, i=0):
# P = P_sqr.T @ P_sqr, so Var(x_i) is the squared norm of column i of P_sqr
# (what Gaussian.std computes).
return np.linalg.norm(P_sqr[:, :, i], axis=1)
Without calibration, the band width is arbitrary¶
Take the logistic equation $\dot x = x(1 - x)$, $x(0) = 0.1$, whose exact solution
$x(t) = 1/(1 + 9e^{-t})$ we know. Solve it twice without calibration, with the
prior's scale matrix Xi set to 1 and to 100, a factor that nothing in the problem
fixes:
def vf(x, *, t):
return x * (1.0 - x)
def exact(t):
return 1.0 / (1.0 + 9.0 * np.exp(-t))
m_0, P_0_sqr = taylor_mode_initialization(vf, np.array([0.1]), q=2)
tspan, N = (0.0, 8.0), 40
def solve(xi, calibration):
prior = IWP(q=2, d=1, Xi=xi * np.eye(1))
measure = ODEInformation(vf, prior.E0, prior.E1)
return gaussian_filter(
m_0, P_0_sqr, prior, measure, np.linspace(*tspan, N + 1), calibration=calibration
)
run_1, run_100 = solve(1.0, "none"), solve(100.0, "none")
t = run_1.t
error = np.abs(run_1.m[:, 0] - exact(t))
mean_difference = np.max(np.abs(run_1.m - run_100.m))
band_ratio = std_of(run_100.P_sqr)[-1] / std_of(run_1.P_sqr)[-1]
print(f"largest difference between the two means: {mean_difference:.0e}")
print(f"band width (Xi = 100) / band width (Xi = 1): {band_ratio:.1f}")
largest difference between the two means: 2e-16 band width (Xi = 100) / band width (Xi = 1): 10.0
The two means are identical; only the bands differ, by a factor of $\sqrt{100} = 10$. Without calibration the width of the band reflects this arbitrary choice, not how accurate the solution is.
What calibration measures¶
At every step, before it looks at the ODE, the solver predicts the residual
$\dot x - f(x)$ it is about to see: a Gaussian with mean result.mz and standard
deviation from result.Pz_sqr. If the band were the right size, the residual it
then actually sees would be about as large as predicted, so their ratio would be
of order one. Without calibration it is not:
def scaled_residuals(result):
# the residual divided by its predicted standard deviation (here d = 1)
return np.abs(result.mz[:, 0] / result.Pz_sqr[:, 0, 0])
sigma_sqr = posthoc_mle_sigma_sqr(run_1.mz, run_1.Pz_sqr)
fig, ax = plt.subplots()
ax.axhline(1.0, color=REFERENCE, lw=2.5, label="expected size")
ax.semilogy(t[1:], scaled_residuals(run_1), "o", ms=3, color=palette[0], label="uncalibrated")
ax.semilogy(
t[1:], scaled_residuals(run_1) / np.sqrt(sigma_sqr), "o", ms=3,
color=palette[2], label="calibrated",
)
ax.set_xlabel("$t$")
ax.set_ylabel("residual / predicted std")
ax.set_ylim(bottom=3e-5) # room for the legend below the data
ax.legend(loc="lower center", ncols=3)
plt.show()
The residuals are about forty times smaller than the uncalibrated solver
predicts, so its band is too wide by the same factor. Calibration picks the
$\sigma^2$ that makes them the right size on average,
$\widehat\sigma^2 = \operatorname{mean}_n (\text{residual}_n / \text{predicted std}_n)^2$,
and rescales every covariance by it. The same estimate on the Xi = 100 run comes
out a hundred times smaller, so both runs end up with the same band:
sigma_sqr_100 = posthoc_mle_sigma_sqr(run_100.mz, run_100.Pz_sqr)
band_1 = std_of(rescale_sqr_seq(run_1.P_sqr, sigma_sqr))
band_100 = std_of(rescale_sqr_seq(run_100.P_sqr, sigma_sqr_100))
print(f"sigma^2 estimate: {float(sigma_sqr):.2e} (Xi = 1), {float(sigma_sqr_100):.2e} (Xi = 100)")
band_difference = np.max(np.abs(band_1 - band_100)[1:] / band_1[1:])
print(f"largest relative difference between the calibrated bands: {band_difference:.0e}")
sigma^2 estimate: 5.47e-04 (Xi = 1), 5.47e-06 (Xi = 100) largest relative difference between the calibrated bands: 3e-15
The plot compares the bands with the actual error. The uncalibrated bands are
43 times (Xi = 1) and 430 times (Xi = 100) wider than the calibrated band,
which lies above the error by less than an order of magnitude. (The error is
plotted instead of the solution because every band here is too thin to see on
the solution itself.)
fig, ax = plt.subplots()
ax.semilogy(t[1:], std_of(run_100.P_sqr)[1:], color=palette[1], label="uncalibrated, Xi = 100")
ax.semilogy(t[1:], std_of(run_1.P_sqr)[1:], color=palette[0], label="uncalibrated, Xi = 1")
ax.semilogy(t[1:], band_1[1:], color=palette[2], label="calibrated (either)")
ax.semilogy(t[1:], error[1:], color=REFERENCE, lw=2.5, label="actual error")
ax.set_ylim(top=1.0)
ax.set_xlabel("$t$")
ax.set_ylabel("standard deviation of $x$")
ax.legend(loc="upper right", ncols=2)
plt.show()
The calibrated band is three to eight times wider than the error. It has the right order of magnitude and overestimates the error rather than underestimating it.
One value, or one per step: post-hoc vs "dynamic"¶
Post-hoc calibration uses one $\widehat\sigma^2$ for the whole run: the average over
all steps. With "dynamic", the default, the solver estimates $\widehat\sigma^2$ at
every step and uses it for that step right away, so the band can grow where the
problem is hard and shrink where it is easy. The per-step values are in
result.sigma_sqr:
dynamic = solve(1.0, "dynamic")
fig, ax = plt.subplots()
ax.semilogy(t[1:], dynamic.sigma_sqr, "o-", ms=3, color=palette[2], label='per step ("dynamic")')
ax.axhline(float(sigma_sqr), color=palette[1], label="one value (post-hoc)")
ax.set_xlabel("$t$")
ax.set_ylabel(r"$\widehat\sigma^2$")
ax.legend(loc="upper right")
plt.show()
The per-step estimate peaks while the solution changes fastest and falls off as it settles: it varies by a factor of a thousand over this run, which a single value cannot follow.
One value, or one per component: "diagonal"¶
With several components, "dynamic" still uses one $\widehat\sigma^2$ for all of
them. Take two independent components, an easy one and a hard one:
$$\dot x_1 = -x_1, \qquad \dot x_2 = -x_2 + \sin(10\,t), \qquad x(0) = (1, 0).$$
The shared value is set by the hard component, $x_2$, and is too large for the
easy one. "diagonal" estimates a separate $\widehat\sigma_i^2$ per component, which
needs a diagonal Xi.
def vf2(x, *, t):
return np.array([-x[0], -x[1] + np.sin(10.0 * t)])
def exact2(t):
x2 = (np.sin(10 * t) - 10 * np.cos(10 * t) + 10 * np.exp(-t)) / 101
return np.stack([np.exp(-t), x2], axis=1)
prior2 = IWP(q=2, d=2)
mu_0_2, P0_sqr_2 = taylor_mode_initialization(vf2, np.array([1.0, 0.0]), q=2)
measure2 = ODEInformation(vf2, prior2.E0, prior2.E1)
tspan2, N2 = (0.0, 5.0), 200
results = {
mode: gaussian_filter(
mu_0_2, P0_sqr_2, prior2, measure2, np.linspace(*tspan2, N2 + 1), calibration=mode
)
for mode in ("dynamic", "diagonal")
}
t2 = results["dynamic"].t
error2 = np.abs(results["dynamic"].m[:, :2] - exact2(t2))
fig, axes = plt.subplots(1, 2, sharey=True)
for i, ax in enumerate(axes):
ax.semilogy(t2[1:], error2[1:, i], color=REFERENCE, lw=2.5, label="actual error")
for mode, color in (("dynamic", palette[2]), ("diagonal", palette[5])):
ax.semilogy(t2[1:], std_of(results[mode].P_sqr, i)[1:], color=color, label=f'std., "{mode}"')
ax.set_title(f"$x_{i + 1}$")
ax.set_xlabel("$t$")
axes[1].legend(loc="lower left")
plt.show()
For $x_2$ both modes give a similar band. For $x_1$, the shared value of
"dynamic" makes the band about a thousand times wider than the actual error;
the per-component estimate brings it within about a factor of ten of the error.
Which mode to use¶
- Start with the default,
"dynamic". - If the components differ in how hard they are to solve, as $x_1$ and $x_2$
above, use
"diagonal". - Use
"none"to keep the prior's own scale, for example to calibrate post-hoc withposthoc_mle_sigma_sqrandrescale_sqr_seq, or when the scale is a parameter of a fitted model (see Diffusion calibration).
Each run's log_likelihood is computed after calibration, so compare
log-likelihoods only between runs in the same mode.