from __future__ import annotations
import matplotlib.pyplot as plt
import numpy as np
from mxlpy import Model, fns, forward_sensitivities, plot
Parameter sensitivities¶
Global sensitivity analysis asks how much each parameter matters across a whole range of values. The complementary, local question is: how does every simulated value change when a parameter changes a little, right here? That is the derivative
of every variable, derived quantity and reaction \(y_i\) with respect to every parameter (or initial value) \(\theta_j\). These forward sensitivities are what gradient-based fitting, Fisher-information analyses and identifiability checks are built on.
MxlPy computes them by solving the sensitivity equations alongside the model,
where both the Jacobian \(J = \partial f / \partial x\) and \(\partial f / \partial \theta\) are generated symbolically from the model. This needs a single (larger) simulation instead of one extra simulation per parameter, and is as accurate as the integrator.
A small example¶
A linear chain \(x \to y \to \varnothing\) with mass-action kinetics.
def get_model() -> Model:
return (
Model()
.add_parameters({"k1": 0.5, "k2": 2.0})
.add_variables({"x": 2.0, "y": 0.0})
.add_reaction(
"v1",
fns.mass_action_1s,
args=["x", "k1"],
stoichiometry={"x": -1, "y": 1},
)
.add_reaction(
"v2",
fns.mass_action_1s,
args=["y", "k2"],
stoichiometry={"y": -1},
)
)
time_points = np.linspace(0, 10, 101)
sens = forward_sensitivities.time_course(
get_model(), time_points, wrt=["k1", "k2", "x"]
).unwrap_or_err()
sens.derivatives["k1"].head()
| x | y | v1 | v2 | |
|---|---|---|---|---|
| 0.0 | 0.000000 | 0.000000 | 2.000000 | 0.000000 |
| 0.1 | -0.190246 | 0.172138 | 1.807336 | 0.344276 |
| 0.2 | -0.361935 | 0.296275 | 1.628707 | 0.592550 |
| 0.3 | -0.516425 | 0.382341 | 1.463204 | 0.764682 |
| 0.4 | -0.654985 | 0.438386 | 1.309969 | 0.876772 |
forward_sensitivities.time_course returns a ForwardSensitivities object with
simulated: the simulated values (time × variables, derived quantities and reactions)derivatives: one DataFrame per parameter, with the same shape assimulatedmethod:"forward"or"finite_difference", see below
Variable names in wrt (here x) give the sensitivities with respect to their initial values.
fig, axs = plot.grid_layout(3, n_cols=3, col_width=4, row_height=3)
for ax, name in zip(axs, sens.wrt, strict=True):
plot.lines(sens.derivatives[name].loc[:, ["x", "y"]], ax=ax)
ax.set(title=f"d / d{name}", xlabel="time")
plt.show()
Increasing k1 drains x faster (negative sensitivity of x) and first fills, then empties y faster.
k2 doesn't affect x at all, and a larger initial x scales the whole trajectory.
Steady states¶
At a steady state the sensitivities follow from the implicit function theorem, \(J\,\partial x^* / \partial \theta = -\partial f / \partial \theta\), without integrating anything. Conserved quantities make \(J\) singular; their totals are then fixed by the initial values, which MxlPy takes into account.
reversible = (
Model()
.add_parameters({"kf": 1.0, "kr": 0.5})
.add_variables({"A": 1.0, "B": 0.0})
.add_reaction(
"vf", fns.mass_action_1s, args=["A", "kf"], stoichiometry={"A": -1, "B": 1}
)
.add_reaction(
"vr", fns.mass_action_1s, args=["B", "kr"], stoichiometry={"A": 1, "B": -1}
)
)
forward_sensitivities.steady_state(
reversible, ["kf", "kr", "A"]
).unwrap_or_err().derivatives
{'kf': A B vf vr
1000.0 -0.222222 0.222222 0.111111 0.111111,
'kr': A B vf vr
1000.0 0.444444 -0.444444 0.444444 0.444444,
'A': A B vf vr
1000.0 0.333333 0.666667 0.333333 0.333333}
Here \(A^* = k_r / (k_f + k_r) \cdot (A_0 + B_0)\), so e.g. \(\partial A^* / \partial k_f = -k_r (A_0 + B_0) / (k_f + k_r)^2 \approx -0.22\).
When the model can't be differentiated symbolically¶
Forward sensitivities need every rate function to be convertible to sympy.
Models with e.g. neural-network surrogates or functions that can't be parsed automatically fall back to central finite differences (two extra simulations per parameter) and log a warning.
You can also choose explicitly with method="forward" or method="finite_difference".
Finite differences are only as accurate as the integrator allows: a too small step amplifies the integration error.
The default relative step displacement=1e-3 suits the default tolerances of 1e-8.
fd = forward_sensitivities.time_course(
get_model(), time_points, ["k1"], method="finite_difference"
).unwrap_or_err()
np.abs(fd.derivatives["k1"] - sens.derivatives["k1"]).max()
x 0.000014 y 0.000144 v1 0.000007 v2 0.000289 dtype: float64
The remaining differences are the error of the finite differences: for this model the forward sensitivities match the analytic solution to about \(10^{-7}\), the finite differences only to about \(10^{-4}\).
Explicit initial values, outputs and runners¶
Pass explicit initial values or select only some outputs:
forward_sensitivities.time_course(model, time_points, ["k1"], y0={"x": 1.0, "y": 0.0}, outputs=["v1"])
When y0 isn't given, the initial values are taken from the model, so initial assignments depending on the parameters are differentiated as well.
Runners provide the same with their own integrator and steady-state settings, which is where fits get their derivatives from:
runner = KineticRunner(derivatives="auto", displacement=1e-3)
runner.time_course_sensitivities(model, time_points, ["k1"])
runner.steady_state_sensitivities(model, ["kf"])
!!! note
The Native and Diffrax integrators compile the model themselves and use finite-difference sensitivities.
For the gradient of a loss with many parameters, adjoint gradients are much cheaper: one forward and one backward solve, whatever the number of parameters.