Recovering a hidden input¶
In many ODE models the unknown is a whole function rather than a few numbers, for example a force that drives a mechanical system, a dosing schedule or an inflow. This notebook recovers such a hidden input $u(t)$ from noisy measurements of the state alone, with error bars, and without assuming a parametric form for $u$.
The input $u$ receives a prior of its own, a Gauss-Markov process, and is stacked with the solution into one state. The ODE then becomes information that links the two, and a single filter pass over the data estimates both.
import logging
import jax
import jax.numpy as np
import matplotlib.pyplot as plt
import numpy as onp
from matplotlib_inline.backend_inline import set_matplotlib_formats
from scipy.integrate import solve_ivp
from tueplots import bundles, cycler
from tueplots.constants.color import palettes
from ode_filters import (
IWP,
JointPrior,
MaternPrior,
Measurement,
SecondOrderODEInformationWithHidden,
gaussian_filter,
information_criteria,
interpolate,
joint_taylor_initialization,
sample_posterior,
taylor_surrogate,
)
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: true values and other references
def style(rel_height):
"""The house style at another aspect ratio, for stacked panels."""
return plt.rc_context(
{
**bundles.tue_ai_beamer(rel_height=rel_height),
**cycler.cycler(color=palettes.paultol_bright),
}
)
A driven oscillator¶
A damped oscillator driven by a force $u(t)$:
$$\ddot x = -\omega^2 x - 2 \zeta \omega \dot x + u(t), \qquad x(0) = \dot x(0) = 0,$$
with $\omega = 2$ and $\zeta = 0.1$ known. The force is a push followed by a longer pull, and the solver receives no information about this shape. Only the position is measured, every 0.4 time units, with noise of standard deviation 0.05.
OMEGA, ZETA = 2.0, 0.1
NOISE = 0.05
def u_true(t):
return 1.5 * onp.exp(-0.5 * (t - 6.0) ** 2) - onp.exp(
-0.5 * ((t - 13.0) / 1.5) ** 2
)
def driven(t, z):
x, v = z
return [v, -(OMEGA**2) * x - 2 * ZETA * OMEGA * v + u_true(t)]
ts = np.linspace(0.0, 20.0, 101) # the solver's grid, step 0.2
t_obs = onp.asarray(ts[2::2]) # every second node
x_obs = solve_ivp(
driven, (0.0, 20.0), [0.0, 0.0], t_eval=t_obs, rtol=1e-11, atol=1e-12
).y[0]
y = x_obs[:, None] + NOISE * onp.asarray(
jax.random.normal(jax.random.PRNGKey(0), (t_obs.size, 1))
)
The model¶
The state stacks the solution with its derivatives, $[x, \dot x, \ddot x,
\dddot x]$, under an integrated Wiener process, and the input with its
derivative, $[u, \dot u]$, under a Matern process: a stationary prior that
says $u$ varies on a time scale of about the length scale $\ell = 1.5$ with a
magnitude of about 1, and nothing else. A JointPrior puts the two side by
side. The ODE information SecondOrderODEInformationWithHidden observes
$\ddot x + \omega^2 x + 2 \zeta \omega \dot x - u = 0$ at every grid node,
which couples the blocks.
The initial position and velocity are known, the input is not.
joint_taylor_initialization builds a consistent initial law: the input
starts from its stationary distribution, and the state's higher derivatives,
which depend on $u(0)$ through the ODE, inherit that uncertainty.
def vf(x, v, u, *, t):
return -(OMEGA**2) * x - 2 * ZETA * OMEGA * v + u
prior = JointPrior(IWP(q=3, d=1), MaternPrior(q=1, d=1, length_scale=1.5))
measure = SecondOrderODEInformationWithHidden(
vf, prior.E0_x, prior.E1, prior.E2, prior.E0_hidden
)
m_0, P_0_sqr = joint_taylor_initialization(
vf, (np.zeros(1), np.zeros(1)), prior=prior, order=2
)
U = prior.prior_x.state_dim # index of u in the joint state
print(f"joint state: {prior.state_dim} entries, u at index {U}")
joint state: 6 entries, u at index 4
Recovering the force¶
One filter pass over the data, with the "none" calibration (the priors'
scales are part of the model here), estimates the whole joint state. The
smoothing posterior conditions every time point on all the data;
interpolate evaluates it between the grid nodes as well, so the solver needs
only 100 steps for a smooth curve. sample_posterior draws whole paths from
the same posterior: plausible forces, all consistent with the data.
def solve(keep):
"""A filter pass with the measurements selected by the boolean mask ``keep``."""
data = [Measurement(np.eye(1), y[keep], t_obs[keep], noise=NOISE**2)]
return gaussian_filter(
m_0, P_0_sqr, prior, measure, ts, calibration="none", measurements=data
), data
everything = onp.ones(t_obs.size, dtype=bool)
result, data = solve(everything)
t_fine = np.linspace(0.0, 20.0, 801)
posterior = interpolate(result, prior, t_fine)
u_mean, u_std = posterior.m[:, U], posterior.std[:, U]
paths = jax.vmap(sample_posterior, in_axes=(0, None))(
jax.random.split(jax.random.PRNGKey(1), 3), result
)
error = onp.abs(u_mean - u_true(onp.asarray(t_fine)))
print(f"largest error in u: {error.max():.2f}, average std: {float(u_std.mean()):.2f}")
print(
f"truth inside the 2-std band: {100 * float((error <= 2 * u_std).mean()):.0f}% of the time"
)
largest error in u: 0.32, average std: 0.10 truth inside the 2-std band: 100% of the time
with style(rel_height=1.6):
fig, (top, bottom) = plt.subplots(2, 1, sharex=True)
top.plot(t_obs, y[:, 0], "o", ms=2.0, color=palette[0], label="measured position")
top.plot(t_fine, posterior.m[:, 0], color=palette[0], label="posterior mean of $x$")
top.set_ylabel("position $x$")
bottom.plot(
t_fine, u_true(onp.asarray(t_fine)), color=REFERENCE, lw=2.5, label="true force"
)
bottom.fill_between(
t_fine,
u_mean - 2 * u_std,
u_mean + 2 * u_std,
color=palette[1],
alpha=0.25,
lw=0,
label=r"mean $\pm$ 2 std of $u$",
)
bottom.plot(t_fine, u_mean, color=palette[1], label="posterior mean of $u$")
for k, path in enumerate(paths):
bottom.plot(
ts,
path[:, U],
color=palette[1],
lw=0.6,
alpha=0.8,
label="samples of $u$" if k == 0 else None,
)
bottom.set_ylabel("force $u$")
bottom.set_xlabel("$t$")
handles = [h for ax in (top, bottom) for h in ax.get_legend_handles_labels()[0]]
fig.legend(handles=handles, loc="outside lower center", ncols=3)
plt.show()
The force is never observed, yet both pulses appear at the right times and heights, up to a largest error of 0.32 in the posterior mean, and the band covers the true force everywhere. The samples show what the band means: each is a whole force that is consistent with the data and varies within the band. The band widens at both ends. The force acts on the position only through a double integration, so at the start it has not yet moved the oscillator, and near the end its effect on the position is not yet measured.
Where the data stop¶
We remove the measurements between $t = 8$ and $t = 12$. Inside the gap the data no longer constrain the force. The posterior there relies on the prior and on the information that the ODE carries over from both sides, and its band widens:
in_gap = (t_obs > 8.0) & (t_obs < 12.0)
gapped, gapped_data = solve(~in_gap)
gapped_posterior = interpolate(gapped, prior, t_fine)
g_mean, g_std = gapped_posterior.m[:, U], gapped_posterior.std[:, U]
fine_gap = (t_fine > 8.0) & (t_fine < 12.0)
print(
f"average std of u inside the gap: {float(g_std[fine_gap].mean()):.2f}, "
f"outside: {float(g_std[~fine_gap].mean()):.2f}"
)
g_error = onp.abs(g_mean - u_true(onp.asarray(t_fine)))
print(
f"truth inside the 2-std band: {100 * float((g_error <= 2 * g_std).mean()):.0f}% of the time"
)
fig, ax = plt.subplots()
ax.axvspan(8.0, 12.0, color=REFERENCE, alpha=0.15, lw=0)
ax.plot(
t_fine, u_true(onp.asarray(t_fine)), color=REFERENCE, lw=2.5, label="true force"
)
ax.fill_between(
t_fine, g_mean - 2 * g_std, g_mean + 2 * g_std, color=palette[1], alpha=0.25, lw=0
)
ax.plot(t_fine, g_mean, color=palette[1], label=r"posterior mean $\pm$ 2 std")
ax.set_xlabel("$t$")
ax.set_ylabel("force $u$")
ax.legend(loc="upper right")
plt.show()
average std of u inside the gap: 0.46, outside: 0.11 truth inside the 2-std band: 100% of the time
How much the data say about the force¶
information_criteria measures this in nats. At a fixed linearization, which
is exact here because the ODE is linear, it returns $I(U; Y \mid Z)$, the
information the data $Y$ carry about the input trajectory $U$ beyond the ODE
information $Z$. Removing the nine measurements in the gap reduces this
information:
def information_from_data(result, data):
surrogate = taylor_surrogate(measure, result.m[1:], ts=ts[1:])
return information_criteria(m_0, P_0_sqr, prior, surrogate, ts, data).I_UY_given_Z
full_info = information_from_data(result, data)
gap_info = information_from_data(gapped, gapped_data)
print(
f"I(U; Y | Z) with all data: {float(full_info):.1f} nats, without the gap: {float(gap_info):.1f} nats"
)
I(U; Y | Z) with all data: 29.1 nats, without the gap: 25.2 nats
The same number, differentiable in the hyperparameters, can rank measurement designs before any data are taken.
Choosing the prior of the input¶
The length scale and magnitude of the Matern prior, and the scale of the state
prior, are hyperparameters. They can be selected from the data by maximizing
the evidence, as any other parameter: build the prior inside the traced
region with InferenceProblem(prior_fn=...) and pass the result to
marginal_loglik. See
Selecting hyperparameters from data
for which evidence to use, and Parameter estimation
for the fitting workflow.