Time-dependent inputs¶
Models are often driven by an external signal: a ligand added to the medium, light, a drug dose, or an upstream species that isn't part of the model.
mxlpy.fns_input provides parameterised shapes for such inputs.
Their parameters are ordinary model parameters, so they can be fitted together with the kinetic ones.
This lets you estimate an unknown input from downstream measurements ("input estimation").
Unlike protocols, which change parameters between integrations, inputs are model functions of time.
They work with fitting, forward sensitivities, symbolic analysis, serialisation and code generation.
import matplotlib.pyplot as plt
import numpy as np
from mxlpy import Model, Simulator, fit, fns, select
from mxlpy import fns_input as inp
from mxlpy.distributions import LogUniform
Shapes¶
All inputs are used as derived values with "time" as the first argument.
smooth_step(t, level1, switch_time, level2, steepness): logistic switchstep(t, level1, switch_time, level2): hard switch. It is discontinuous, so prefersmooth_step, or a protocol if the levels aren't fittedperiodic_step(t, low, high, period, on_fraction, sharpness): smooth periodic switching, e.g. day and nightbolus(t, area, peak_time, width): Gaussian pulse with a given total area, e.g. an injected dosemulti_step(switch_times, steepness=...): factory for several switches at fixed times with fitted levels (steepness=Nonefor hard switches)cubic_spline(knots, positive=False, monotone=False, initial_slope=None): factory for a spline through fitted values at fixed knot times
t = np.linspace(0, 48, 481)
spline = inp.cubic_spline([0, 12, 24, 36, 48])
shapes = {
"smooth_step": [inp.smooth_step(x, 0.0, 12.0, 1.0, 1.0) for x in t],
"periodic_step": [inp.periodic_step(x, 0.0, 1.0, 24.0, 2 / 3, 20.0) for x in t],
"bolus": [inp.bolus(x, 5.0, 20.0, 3.0) for x in t],
"multi_step": [
inp.multi_step([10, 30], steepness=2.0)(x, 0.2, 1.0, 0.5) for x in t
],
"cubic_spline": [spline(x, 0.2, 1.0, 0.4, 0.8, 0.6) for x in t],
}
fig, axs = plt.subplots(1, len(shapes), figsize=(15, 2.5), sharey=True)
for ax, (name, values) in zip(axs, shapes.items(), strict=True):
ax.plot(t, values)
ax.set(title=name, xlabel="time")
plt.show()
Estimating an unknown stimulus¶
As an example, a species \(x\) is produced in response to a stimulus \(u(t)\) and degraded with rate constant \(k\):
We only measure \(x\), and we know \(k\) from a separate experiment (e.g. the decay after washing the stimulus out). The stimulus, unknown to us, is a pulse on top of a baseline.
def true_stimulus(t: float, baseline: float, area: float) -> float:
return baseline + inp.bolus(t, area, 10.0, 3.0)
truth = (
Model()
.add_parameters({"k": 0.3, "baseline": 0.2, "area": 5.0})
.add_variables({"x": 0.5})
.add_derived("u", true_stimulus, args=["time", "baseline", "area"])
.add_reaction("production", fns.constant, args=["u"], stoichiometry={"x": 1})
.add_reaction(
"degradation", fns.mass_action_1s, args=["x", "k"], stoichiometry={"x": -1}
)
)
sigma = 0.02
times = np.linspace(0, 40, 41)
res = Simulator(truth).simulate_time_course(times).get_result().unwrap_or_err()
data = res.variables.loc[times, ["x"]]
data += np.random.default_rng(0).normal(0, sigma, data.shape)
We replace the unknown stimulus with a spline.
add_spline_input adds one parameter per knot (u_0, u_1, ...) and the derived value u.
With positive=True the spline interpolates the logarithms of the knot values, so the stimulus can't become negative.
def model(n_knots: int) -> Model:
return (
Model()
.add_parameters({"k": 0.3})
.add_variables({"x": 0.5})
.add_spline_input(
"u", knots=np.linspace(0, 40, n_knots), initial=0.5, positive=True
)
.add_reaction("production", fns.constant, args=["u"], stoichiometry={"x": 1})
.add_reaction(
"degradation", fns.mass_action_1s, args=["x", "k"], stoichiometry={"x": -1}
)
)
How many knots?¶
Too few knots can't follow the pulse, and too many fit the noise.
We fit the knot values for several knot counts and compare the fits with select.compare, which ranks models by an information criterion (here BIC, see model selection).
knot_counts = [3, 5, 7, 9, 11]
p0 = {f"u_{i}": LogUniform(0.05, 2.0) for i in range(max(knot_counts))}
selection = select.compare(
{f"{n} knots": model(n) for n in knot_counts},
data,
p0,
loss_fn=fit.GaussianNll(sigma),
criterion="bic",
n_starts=5,
transform="log",
)
selection.table[["k", "log_likelihood", "bic", "delta", "weight"]]
fits: 0%| | 0/30 [00:00<?, ?it/s]
fits: 3%|▎ | 1/30 [00:02<01:22, 2.84s/it]
fits: 17%|█▋ | 5/30 [00:03<00:13, 1.79it/s]
fits: 20%|██ | 6/30 [00:03<00:11, 2.14it/s]
fits: 23%|██▎ | 7/30 [00:03<00:09, 2.49it/s]
fits: 27%|██▋ | 8/30 [00:04<00:07, 2.81it/s]
fits: 30%|███ | 9/30 [00:04<00:08, 2.53it/s]
fits: 37%|███▋ | 11/30 [00:04<00:05, 3.23it/s]
fits: 43%|████▎ | 13/30 [00:05<00:06, 2.61it/s]
fits: 47%|████▋ | 14/30 [00:06<00:05, 2.97it/s]
fits: 50%|█████ | 15/30 [00:06<00:04, 3.33it/s]
fits: 57%|█████▋ | 17/30 [00:07<00:05, 2.44it/s]
fits: 60%|██████ | 18/30 [00:07<00:04, 2.91it/s]
fits: 63%|██████▎ | 19/30 [00:08<00:04, 2.38it/s]
fits: 67%|██████▋ | 20/30 [00:08<00:03, 2.78it/s]
fits: 70%|███████ | 21/30 [00:09<00:05, 1.69it/s]
fits: 77%|███████▋ | 23/30 [00:10<00:03, 2.02it/s]
fits: 80%|████████ | 24/30 [00:10<00:02, 2.22it/s]
fits: 83%|████████▎ | 25/30 [00:12<00:03, 1.28it/s]
fits: 87%|████████▋ | 26/30 [00:12<00:02, 1.62it/s]
fits: 90%|█████████ | 27/30 [00:13<00:02, 1.46it/s]
fits: 93%|█████████▎| 28/30 [00:13<00:01, 1.80it/s]
fits: 97%|█████████▋| 29/30 [00:14<00:00, 1.51it/s]
fits: 100%|██████████| 30/30 [00:14<00:00, 1.95it/s]
fits: 100%|██████████| 30/30 [00:14<00:00, 2.03it/s]
| k | log_likelihood | bic | delta | weight | |
|---|---|---|---|---|---|
| model | |||||
| 9 knots | 9 | -11.148134 | 55.718416 | 0.000000 | 7.744161e-01 |
| 11 knots | 11 | -8.667979 | 58.185250 | 2.466834 | 2.255839e-01 |
| 7 knots | 7 | -154.903665 | 335.802334 | 280.083918 | 1.173612e-61 |
| 5 knots | 5 | -166.188112 | 350.944083 | 295.225667 | 6.046934e-65 |
| 3 knots | 3 | -6664.330573 | 13339.801862 | 13284.083446 | 0.000000e+00 |
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 3.5))
t = np.linspace(0, 40, 401)
ax1.plot(
t,
[true_stimulus(x, 0.2, 5.0) for x in t],
color="black",
linestyle="--",
label="true",
)
for name in ["3 knots", selection.best_id]:
candidate = selection[name]
fitted = (
Simulator(candidate.model).simulate_time_course(t).get_result().unwrap_or_err()
)
ax1.plot(t, fitted.get_combined()["u"], label=name)
ax2.plot(t, fitted.variables["x"], label=name)
ax2.plot(data.index, data["x"], "o", color="black", markersize=3, label="data")
ax1.set(xlabel="time", ylabel="stimulus u")
ax2.set(xlabel="time", ylabel="x")
ax1.legend()
ax2.legend()
plt.show()
The best spline recovers the timing and size of the pulse from measurements of \(x\) alone.
Why did we fix \(k\)? A flexible input can absorb any degradation constant: for every \(k\), the input \(u(t) = \frac{dx}{dt} + k\,x\) reproduces the same \(x(t)\).
So \(k\) and the input can't be estimated together from \(x\) alone, and fitting both would give an arbitrary \(k\) with a matching input.
Inputs are identifiable only together with enough independent information about the rest of the model.
For a confidence band of the estimated stimulus, profile the knot values with identify.profile_likelihood.
Other options of the spline:
monotone=Trueuses a monotone cubic, which doesn't overshoot between knotsinitial_slope=0.0fixes the slope at the first knot, e.g. for an input that starts at steady state
Splines are piecewise polynomials whose expression grows roughly quadratically with the number of knots, so up to about 20 knots are cheap.
Replacing a constant input by a spline¶
To turn an existing parameter or derived value into a time-dependent input, remove it first and add the spline under the same name.
add_spline_input never overwrites a name, so the replacement is explicit.
Everything that read the constant now reads the spline, in simulations, fits and sensitivities.
unit and display_name are passed on to the spline and its knot values.
constant = (
Model()
.add_parameters({"k": 0.3, "u": 0.5})
.add_variables({"x": 0.5})
.add_reaction("production", fns.constant, args=["u"], stoichiometry={"x": 1})
.add_reaction(
"degradation", fns.mass_action_1s, args=["x", "k"], stoichiometry={"x": -1}
)
)
driven = constant.remove_parameter("u").add_spline_input(
"u",
knots=np.linspace(0, 40, 7),
initial=0.5,
positive=True,
display_name="stimulus",
)
fitted = fit.time_course(
driven,
p0={f"u_{i}": 0.5 for i in range(7)},
data=data,
loss_fn=fit.GaussianNll(sigma),
minimizer=fit.LeastSquaresMinimizer(),
transform="log",
).unwrap_or_err()
fitted.best_pars
{'u_0': np.float64(0.09313085917404341),
'u_1': np.float64(0.6074890811000446),
'u_2': np.float64(0.5874008410783835),
'u_3': np.float64(0.17088725299292118),
'u_4': np.float64(0.21778225667286752),
'u_5': np.float64(0.18817425524277961),
'u_6': np.float64(0.22959050065531614)}