Fitting lab¶
Fitting an ODE model well takes more than calling a minimizer: which parameters can the data determine, did the optimizer find the best fit, are the residuals noise or missing dynamics, how certain are the estimates and predictions?
mxlpy.lab takes one model and one or several data sets through these questions as a guided pipeline:
| Step | Method | What it does |
|---|---|---|
| 0 | step0_setup |
maps data columns to model outputs (with scale/offset observables), estimates the measurement noise, picks an integrator and times the model |
| 1 | step1_select_parameters |
ranks parameters by their sensitivities, drops collinear ones, limits their number by the sensitivity rank and the time budget |
| 2 | step2_fit |
multi-start fits with a χ² goodness-of-fit test, multi-start convergence and residual whiteness; with several data sets condition-specific parameters |
| 3 | step3_diagnose |
only if step 2 fails: hidden states until the residuals are white, then structural variants of the flagged variables |
| 4 | step4_identifiability |
Fisher information, pulling test and profile likelihoods, proposes parameters to fix |
| 5 | step5_uncertainty |
prediction bands of the observables (and optionally a posterior) |
Every step ends at a review gate with its result and a proposal.
Calling the next step accepts the proposal, decide overrides it, and run(auto=True) goes straight through.
Steps are addressed by key ("fit"), number (2) or method name.
All results are checkpointed in a run directory, so an interrupted run resumes where it stopped.
import shutil
import tempfile
from pathlib import Path
import numpy as np
from mxlpy import Model, Simulator, fit, fns, lab
Example: an inhibited pathway, measured in arbitrary units¶
A substrate \(S\) is converted to \(P\) through an intermediate \(X\), and an inhibitor \(I\) slows the first step.
Two experiments were done: a control and one with the inhibitor.
\(S\) was measured in concentrations, \(P\) only relative to an unknown scale (e.g. a western blot), as the column P_au.
def pathway() -> Model:
return (
Model()
.add_parameters({"k1": 1.0, "k2": 0.5, "kd": 0.05, "Ki": 0.5, "I": 0.0})
.add_variables({"S": 2.0, "X": 0.0, "P": 0.0})
.add_derived("k1_eff", fns.div, args=["k1", "inhibition"])
.add_derived("inhibition", fns.add, args=["one", "I_rel"])
.add_parameter("one", 1.0)
.add_derived("I_rel", fns.div, args=["I", "Ki"])
.add_reaction(
"v1",
fns.mass_action_1s,
args=["S", "k1_eff"],
stoichiometry={"S": -1, "X": 1},
)
.add_reaction(
"v2", fns.mass_action_1s, args=["X", "k2"], stoichiometry={"X": -1, "P": 1}
)
.add_reaction(
"v3", fns.mass_action_1s, args=["P", "kd"], stoichiometry={"P": -1}
)
)
def measure(inhibitor: float, seed: int):
model = pathway().update_parameter("I", inhibitor)
t = np.linspace(0.5, 15, 20)
res = Simulator(model).simulate_time_course(t).get_result().unwrap_or_err()
data = res.variables.loc[t, ["S", "P"]].rename(columns={"P": "P_au"})
data["P_au"] *= 40.0 # unknown scale of the measurement
rng = np.random.default_rng(seed)
return data + rng.normal(0, [0.03, 1.0], data.shape)
data = {
"control": fit.Condition(measure(0.0, 1)),
"inhibitor": fit.Condition(measure(1.0, 2), parameters={"I": 1.0}),
}
Each data set is a fit.Condition: its data plus what is special about the experiment, here the inhibitor concentration.
Conditions can also hold initial values (y0), a protocol and the measurement noise (sigma), which the lab estimates if missing.
observables maps P_au to the model's P with a fitted scale.
run_dir = Path(tempfile.mkdtemp()) / "pathway"
run = lab.FittingLab(
pathway(),
data,
run_dir,
parameters=["k1", "k2", "kd", "Ki"],
observables={"P_au": lab.Observable("P", scale=True)},
time_budget="10min",
n_starts=5,
)
Step 0: setup¶
The noise of every observable is estimated from replicates (repeated time points) or, as here, from pseudo-residuals of neighbouring points (each point against the cubic through its neighbours), pooled over the data sets measuring the same column.
The scale of P_au starts at the ratio of the data's and the simulation's magnitude.
run.step0_setup()
StepResult('setup', done, 0.1 s)
- 2 data set(s), 80 data points, 5 candidate parameters
- Noise: control: estimated (pooled), inhibitor: estimated (pooled)
- Integrator: native-lsoda (stiffness ratio 20)
- One simulation of all data sets: 3 ms, with sensitivities: 54 ms
- Observable parameters: scale_P_au
proposal: {'sigma': {'control': {'S': 0.03795003451280067, 'P_au': 0.826535540316433}, 'inhibitor': {'S': 0.03795003451280067, 'P_au': 0.826535540316433}}, 'integrator': 'native-lsoda'}
run["setup"].summary["sigma"]
{'control': {'S': 0.03795003451280067, 'P_au': 0.826535540316433},
'inhibitor': {'S': 0.03795003451280067, 'P_au': 0.826535540316433}}
Step 1: parameter selection¶
At samples around the nominal values, the residual sensitivities of every candidate are computed (noise-weighted, w.r.t. log parameters).
Parameters are ranked by their mean sensitivity and added greedily unless their sensitivity vector is nearly collinear with those already chosen (collinearity, the minimal sine of the angle).
The number of parameters is limited by the rank of the sensitivities, the time budget (runtimes of the remaining steps are estimated per choice) and max_parameters.
params = run.step1_select_parameters()
params
StepResult('parameters', done, 1.1 s)
- 5 of 5 candidates are sensitive and not collinear
- Rank estimate of the sensitivities: 5
- Proposed 5 parameters (limited by selected): scale_P_au, kd, k2, k1, Ki
- Estimated runtime of steps 2-5: 51 s to 9.9 min (typ. 2.1 min)
proposal: {'parameters': ['scale_P_au', 'kd', 'k2', 'k1', 'Ki']}
import pandas as pd
pd.DataFrame(params.summary["parameters"]).T
| importance | sine | status | |
|---|---|---|---|
| scale_P_au | 69.949716 | 1.0 | selected |
| kd | 19.994836 | 0.40809 | selected |
| k2 | 16.155604 | 0.188084 | selected |
| k1 | 12.268204 | 0.802783 | selected |
| Ki | 7.070973 | 0.522882 | selected |
Step 2: fit¶
Multi-start least-squares fits in log space.
The fit passes if the χ² goodness-of-fit test doesn't reject it and the residuals of every observable look white (runs and Ljung-Box tests, Bonferroni-corrected).
The fraction of starts reaching the best objective tells whether the problem is hard to optimise.
Calling step2_fit accepts the proposal of step 1; run.decide("parameters", parameters=[...]) would have chosen others.
fitted = run.step2_fit()
fitted
StepResult('fit', passed, 3.4 s)
- Best objective 34.78 (χ² = 69.55, dof 75, p = 0.656)
- 100% of 5 finished starts converged to the best (Δχ² < 1), 0 failed
proposal: {'local': {}, 'next': 'identifiability'}
fitted.summary["estimates"]
{'scale_P_au': 39.641325588533945,
'kd': 0.04893701753378441,
'k2': 0.5171018003002189,
'k1': 0.9854453648656728,
'Ki': 0.493322940724618}
With several data sets, everything is shared first.
If that fails but every data set fits on its own, select.condition_specific looks for parameters that differ between conditions, and the proposal holds them as condition-specific estimates (fit.Condition(local={"k1": "k1__mutant"})).
Step 4: identifiability¶
Step 3 is skipped, as the fit passed. The identifiability analysis escalates from the Fisher information (cheap, local) over the pulling test to profile likelihoods with confidence intervals, all on all data sets jointly. Non-identifiable parameters come with the identifiable combination they are part of, and the proposal fixes the less sensitive ones and refits.
ident = run.step4_identifiability()
ident
identifiability test: 0%| | 0/5 [00:00<?, ?it/s]
identifiability test: 20%|██ | 1/5 [00:03<00:13, 3.49s/it]
identifiability test: 100%|██████████| 5/5 [00:04<00:00, 1.46it/s]
identifiability test: 100%|██████████| 5/5 [00:04<00:00, 1.17it/s]
profiles: 0%| | 0/10 [00:00<?, ?it/s]
profiles: 10%|█ | 1/10 [00:04<00:44, 4.97s/it]
profiles: 20%|██ | 2/10 [00:05<00:17, 2.15s/it]
profiles: 50%|█████ | 5/10 [00:07<00:05, 1.17s/it]
profiles: 60%|██████ | 6/10 [00:07<00:03, 1.09it/s]
profiles: 90%|█████████ | 9/10 [00:09<00:00, 1.42it/s]
profiles: 100%|██████████| 10/10 [00:09<00:00, 1.65it/s]
profiles: 100%|██████████| 10/10 [00:09<00:00, 1.06it/s]
StepResult('identifiability', passed, 13.9 s)
- Fisher information: rank 5 of 5
- Pulling test: all estimates identifiable
- Profiles: all profiled estimates identifiable
proposal: {'fix': [], 'refit': False}
ident.summary["profiles"]["ci"]
| value | lower | upper | identifiability | |
|---|---|---|---|---|
| parameter | ||||
| scale_P_au | 39.641326 | 38.447241 | 40.966384 | identifiable |
| kd | 0.048937 | 0.044781 | 0.053447 | identifiable |
| k2 | 0.517102 | 0.479387 | 0.557099 | identifiable |
| k1 | 0.985445 | 0.933314 | 1.042126 | identifiable |
| Ki | 0.493323 | 0.456583 | 0.532951 | identifiable |
Step 5: uncertainty¶
Prediction bands of every observable in every condition (integrated prediction profiles, identify.prediction_band).
mcmc=True additionally samples the posterior of a single data set.
uncertainty = run.step5_uncertainty()
uncertainty
prediction band: 0%| | 0/2 [00:00<?, ?it/s]
prediction band: 50%|█████ | 1/2 [00:14<00:14, 14.79s/it]
prediction band: 100%|██████████| 2/2 [00:14<00:00, 7.40s/it]
prediction band: 0%| | 0/2 [00:00<?, ?it/s]
prediction band: 50%|█████ | 1/2 [00:12<00:12, 12.83s/it]
prediction band: 100%|██████████| 2/2 [00:13<00:00, 5.55s/it]
prediction band: 100%|██████████| 2/2 [00:13<00:00, 6.64s/it]
prediction band: 0%| | 0/2 [00:00<?, ?it/s]
prediction band: 50%|█████ | 1/2 [00:09<00:09, 9.36s/it]
prediction band: 100%|██████████| 2/2 [00:09<00:00, 3.92s/it]
prediction band: 100%|██████████| 2/2 [00:09<00:00, 4.74s/it]
prediction band: 0%| | 0/2 [00:00<?, ?it/s]
prediction band: 50%|█████ | 1/2 [00:12<00:12, 12.36s/it]
prediction band: 100%|██████████| 2/2 [00:12<00:00, 5.16s/it]
prediction band: 100%|██████████| 2/2 [00:12<00:00, 6.24s/it]
StepResult('uncertainty', done, 50.7 s)
- 4 prediction band(s) at 95%
Report, resuming, progress¶
report() writes a self-contained report.html (and report.json) into the run directory.
run.report()
run
FittingLab('/tmp/tmph4oseq2t/pathway')
setup done gate: implicit
parameters done gate: implicit
fit passed gate: implicit
diagnose skipped gate: implicit
identifiability passed gate: implicit
uncertainty done gate: open
The run directory is the source of truth: config.json, the gate decisions in decisions.json, one result per step and the progress stream events.jsonl, which the fits write to from their worker processes.
FittingLab.resume reloads a run; results whose inputs (model, data, settings and the decisions before them) are unchanged are reused, so this returns at once:
resumed = lab.FittingLab.resume(run_dir)
resumed.run(auto=True)
sorted(p.name for p in run_dir.iterdir())
['config.json', 'decisions.json', 'decisions.json.lock', 'events.jsonl', 'inputs.pkl', 'report.html', 'report.json', 'run.lock', 'runtime.json', 'steps']
For batch or cluster runs, run(auto=True) accepts every proposal.
run.on_event(fn) calls fn with a lab.LabEvent (step, best loss so far, number of evaluations, ETA range) while a step runs.
Web UI¶
With the lab extra (pip install "mxlpy[lab]"), a local web UI shows a run while it runs and lets you decide its gates in the browser:
mxlpy lab serve runs/pathway # prints http://127.0.0.1:8765/?token=...
server = run.serve() # the same from Python (also in notebooks)
server.stop()
The server runs the steps in the background with run.run(wait=True): it stops at every gate until it is decided, in the browser or from Python with run.decide(...).
Each step page shows the step's results (data with the fit, multi-start waterfall, parameter sensitivities, profiles, prediction bands, hidden-state corrections) and its gate, a form built from the step's options (lab.Option), which decide checks values against.
While a step runs, the UI shows its loss traces, finished starts, the ETA and, for fits, the best fit so far.
Pause (or run.pause()) stops the run once the running step has finished; Resume (run.unpause()) continues it, and Report downloads report.html.
The run directory stays the source of truth, so the browser is never required: mxlpy lab serve --watch only watches and decides while another process runs the steps (a run.lock lets only one process run them at a time), and mxlpy lab status prints the steps and gates.
The server listens on localhost only and needs the token from the printed address. On a cluster node, forward the port with ssh -L 8765:localhost:8765 node and open the printed address locally.
Missing dynamics¶
If the fit fails, step 3 trains hidden states (add_hidden_states, see augmented ODEs) with 1, 2, ... states until the residuals turn white, and shows where the mechanism is off.
Then it compares structural variants with select.compare: user-given variants={"name": fn(model) -> model} and generic edits of the flagged variables (an extra degradation, an unknown spline input and a delay of the production through a linear chain).
Here, the model lacks the intermediate \(X\):
def without_intermediate() -> Model:
return (
Model()
.add_parameters({"k1": 1.0, "kd": 0.05, "Ki": 0.5, "I": 0.0, "one": 1.0})
.add_variables({"S": 2.0, "P": 0.0})
.add_derived("I_rel", fns.div, args=["I", "Ki"])
.add_derived("inhibition", fns.add, args=["one", "I_rel"])
.add_derived("k1_eff", fns.div, args=["k1", "inhibition"])
.add_reaction(
"v1",
fns.mass_action_1s,
args=["S", "k1_eff"],
stoichiometry={"S": -1, "P": 1},
)
.add_reaction(
"v3", fns.mass_action_1s, args=["P", "kd"], stoichiometry={"P": -1}
)
)
run2 = lab.FittingLab(
without_intermediate(),
data,
run_dir.parent / "pathway-reduced",
parameters=["k1", "kd", "Ki"],
observables={"P_au": lab.Observable("P", scale=True)},
n_starts=5,
max_hidden=1,
)
run2.step2_fit()
StepResult('fit', failed, 7.0 s)
- Best objective 1080 (χ² = 2160, dof 76, p = 0)
- 100% of 5 finished starts converged to the best (Δχ² < 1), 0 failed
- Structured residuals (missing dynamics?): control:S, control:P_au, inhibitor:S, inhibitor:P_au
proposal: {'local': {}, 'next': 'diagnose'}
diagnosis = run2.step3_diagnose()
diagnosis
fits: 0%| | 0/18 [00:00<?, ?it/s]
fits: 6%|▌ | 1/18 [00:02<00:45, 2.68s/it]
fits: 22%|██▏ | 4/18 [00:03<00:09, 1.41it/s]
fits: 28%|██▊ | 5/18 [00:03<00:07, 1.66it/s]
fits: 39%|███▉ | 7/18 [00:07<00:13, 1.26s/it]
fits: 44%|████▍ | 8/18 [00:08<00:11, 1.19s/it]
fits: 72%|███████▏ | 13/18 [00:16<00:07, 1.46s/it]
fits: 78%|███████▊ | 14/18 [00:18<00:05, 1.46s/it]
fits: 100%|██████████| 18/18 [00:18<00:00, 1.02s/it]
StepResult('diagnose', failed, 21.3 s)
- Hidden states correct S, P
- Residuals stay structured with up to 1 hidden state(s)
- The mechanism is off mostly for S, P
- Best structural variant: delay[P]
- Hidden states reach a loss of 869.3, delay[P] 62
proposal: {'model': 'delay[P]'}
pd.DataFrame(diagnosis.summary["variants"]).set_index("model")[
["k", "log_likelihood", "aicc", "delta"]
]
| k | log_likelihood | aicc | delta | |
|---|---|---|---|---|
| model | ||||
| delay[P] | 5 | -62.000763 | 134.812337 | 0.000000 |
| input[P] | 10 | -419.589164 | 862.366735 | 727.554398 |
| input[S] | 10 | -917.291419 | 1857.771243 | 1722.958906 |
| original | 4 | -1080.211158 | 2168.955648 | 2034.143312 |
| degradation[P] | 5 | -1080.211158 | 2171.233127 | 2036.420790 |
| degradation[S] | 5 | -1080.211313 | 2171.233436 | 2036.421100 |
The delay of \(P\)'s production is the variant the data favour, which is what the missing intermediate does. Accepting the proposal hands this model to step 4.
Building blocks¶
The lab is built from parts that work on their own:
fit.Conditionand the multi-data-setdata=ofidentify.*,select.run/select.compareandfit.augmented_time_coursecallback=of every fit (fit.FitEvent,fit.JsonlCallback) andGroupFit.failuresfor failed startsparallel.Cache(content_hash=True)for caches that don't return stale resultsfit.estimate_sigma,fit.check_residualsandfit.chi2_test(mxlpy.fit.diagnostics)identify.Prediction(local=...)for predictions in conditions with condition-specific estimates
shutil.rmtree(run_dir.parent)