Augmented ODEs: terms and hidden states¶
When a mechanistic model can't fit the data and the residuals are structured, the question is what is missing, and where. MxlPy answers it inside the regular toolchain, without translating the model to JAX:
- a term rewrites a variable's derivative or a reaction's rate through an explicit
mechanism; - a hidden-state block adds latent states
hdriven by a small neural network,dh/dt = nn_h(x, h), and corrects each target withW h. The hidden states give the model memory: delays, unmodelled slow processes, history dependence.
Both are lowered to symbolic equations, so every integrator (including Native), fits, forward and adjoint sensitivities, code generation and .mxl.json files work with them. The contributions of the terms show which variables or reactions miss dynamics, and when.
import numpy as np
from mxlpy import Model, Simulator, fit, fns, plot
A model that misses a delay¶
The data come from S → X → P; our mechanistic model only knows S → P.
def truth() -> Model:
return (
Model()
.add_parameters({"k": 1.0, "kx": 0.7})
.add_variables({"S": 1.0, "X": 0.0, "P": 0.0})
.add_reaction(
"v1", fns.mass_action_1s, args=["S", "k"], stoichiometry={"S": -1, "X": 1}
)
.add_reaction(
"v2", fns.mass_action_1s, args=["X", "kx"], stoichiometry={"X": -1, "P": 1}
)
)
def mechanistic() -> Model:
return (
Model()
.add_parameters({"k": 1.0})
.add_variables({"S": 1.0, "P": 0.0})
.add_reaction(
"v1", fns.mass_action_1s, args=["S", "k"], stoichiometry={"S": -1, "P": 1}
)
)
time = np.linspace(0, 8, 17)
rng = np.random.default_rng(0)
res = Simulator(truth()).simulate_time_course(time).get_result().unwrap_or_err()
data = res.variables.loc[:, ["S", "P"]]
data = data + rng.normal(0, 0.01, size=data.shape)
mech_fit = fit.time_course(
mechanistic(),
p0={"k": 1.0},
data=data,
minimizer=fit.LocalScipyMinimizer(method="L-BFGS-B"),
loss_fn=fit.GaussianNll(0.01),
).unwrap_or_err()
mech_fit.best_pars, mech_fit.loss
({'k': np.float64(0.579155322362733)}, 2164.87922072883)
Terms¶
add_term(name, fn, args, target=..., mechanism=...) works on variables and (kinetic models) reactions. The mechanism is required: "additive" (base + term), "relative" (base · (1 + term)) or any callable (base, term) -> value. A reaction term rewrites the rate before the stoichiometry fans it out, so it corrects every variable the reaction touches. Each term's contribution Δ = mechanism(base, term) − base is a named output, and dx/dt = base + ΣΔ. Terms never enter the stoichiometric matrix.
m = mechanistic().add_parameter("f", 0.2)
m.add_term(
"slow_down",
fns.constant,
args=["f"],
target="v1",
mechanism=lambda base, term: base * (1 - term),
)
print(
m.get_fluxes(), m.get_fluxes(corrected=True), m.get_term_contributions(), sep="\n\n"
)
v1 1.0 dtype: float64 v1 0.8 dtype: float64 slow_down -0.2 dtype: float64
Hidden states¶
One hidden state with a small network, correcting the derivative of P relatively: S decays as modelled, only the appearance of P is delayed. (A correction of the reaction v1 would change S and P alike and couldn't fit.) The weights are not parameters: get_weight_names() lists them and get_addressable_names() lists parameters and weights, the names fits, sensitivities and the simulator accept.
model = mechanistic().add_hidden_states(
"aug", n_hidden=1, layers=(4,), targets=["P"], mechanism="relative"
)
model.get_variable_names(), model.get_parameter_names(), len(model.get_weight_names())
(['S', 'P', 'aug_h0'], ['k'], 22)
Training¶
fit.augmented_time_course starts at the mechanistic optimum: it scales the block's inputs and outputs along the mechanistic trajectory, fits the weights alone with Normal(0, 0.1) priors and a smooth penalty on the correction (so the mechanism keeps explaining what it can), then refines weights and the mechanistic parameters jointly.
res = fit.augmented_time_course(
model, data=data, p0=mech_fit.best_pars, noise=0.01
).unwrap_or_err()
print(f"loss: mechanistic {mech_fit.loss:.1f}, augmented {res.loss:.1f}")
loss: mechanistic 2164.9, augmented 135.1
sim = (
Simulator(res.model)
.simulate_time_course(np.linspace(0, 8, 101))
.get_result()
.unwrap_or_err()
)
fig, ax = plot.lines(sim.variables.loc[:, ["S", "P"]])
ax.plot(data.index, data["P"], "o", color="C1")
ax.plot(data.index, data["S"], "o", color="C0")
ax.set(xlabel="time", ylabel="concentration")
plot.show()
The correction shows where and when the mechanism falls short: the production of P is slowed down early (the missing intermediate X is still filling up) and sped up later.
fig, axs = plot.correction(res)
plot.show()
Saving¶
Terms and blocks are saved to .mxl.json (spec_version 0.5), with the weights in a sidecar file. Blocks authored in mxlweb (nn_blocks, any mechanism) load the same way.
import tempfile
from pathlib import Path
import mxlpy
with tempfile.TemporaryDirectory() as tmp:
mxlpy.save(res.model, Path(tmp) / "augmented.mxl.json")
loaded = mxlpy.load(Path(tmp) / "augmented.mxl.json")
loaded.get_raw_hidden_states()["aug"].n_hidden
1
Code and LaTeX¶
meta.generate_mxlpy_code writes a block as an add_hidden_states(...) call with its structure, followed by update_hidden_states(...) with the weights, readout W and h0 as literals. The LaTeX exporters show a block compactly: s (W h)_x on each target with the block's mechanism, one network equation dh/dt = NN(u / s_u, h) per block and a table of its layer sizes, activations and scales, instead of every weight.
from mxlpy import meta
print(meta.generate_model_code_latex(model).as_default()[-1])
\begin{align*}
\frac{d\ \mathrm{S}}{dt} &= - 1.0 \cdot v_{1} \\
\frac{d\ \mathrm{P}}{dt} &= 1.0 \cdot v_{1} \cdot \left(s^{\mathrm{aug}}_{\mathrm{P}}\, \left(W_{\mathrm{aug}}\, h_{\mathrm{aug}}\right)_{\mathrm{P}} + 1\right) \\
\frac{d h_{\mathrm{aug}}}{dt} &= \mathrm{NN}_{\mathrm{aug}}\left(u_{\mathrm{aug}} / s^{\mathrm{aug}}_{u},\, h_{\mathrm{aug}}\right)
\end{align*}
\begin{tabular}{ll}
\multicolumn{2}{l}{Hidden-state block $\mathrm{aug}$} \\
\hline
Hidden states $h_{\mathrm{aug}}$ & $\mathrm{aug\_h0}$ \\
Inputs $u_{\mathrm{aug}}$ & $\mathrm{S}, \mathrm{P}$ \\
Input scales $s^{\mathrm{aug}}_{u}$ & $1, 1$ \\
Targets & $\mathrm{P}$ \\
Output scales $s^{\mathrm{aug}}$ & $1$ \\
Mechanism & relative \\
$h_{\mathrm{aug}}(0)$ & $0$ \\
Layer sizes & $3 \to 4 \to 1$ \\
Activations & tanh, linear \\
Weights & 22 \\
\end{tabular}
Notes¶
- With the readout
W = 0the derivatives of the mechanistic variables are exactly those of the mechanistic model. Simulations agree to the solver's tolerance, as the hidden states take part in its step-size control. model.remove_hidden_states("aug")restores the mechanistic model, e.g. to tryn_hidden = 1, 2, ….- Gradients w.r.t. many weights are cheapest with adjoints (
mxlpy.adjoint_sensitivities), chosen automatically for large problems.