Skip to content

07. The fit

Download the notebook (executed for this page) · source

What this tutorial shows. One small network-model fit, run the way the command line runs it (api.run): a multistart of four starts on the synthetic example. We look at the two fit engines (sbmlsim, and AMICI with pyPESTO), at the PEtab problem the fit is given, at the per-start record optimization/multistart_summary.csv, at how the reported start is chosen, and at the Fréchet record optimization/frechet_selection.csv.

Place in the series. Tutorial 06 assembled the objective: θ → SBML model solve → fold changes → data term + prior term. This tutorial minimises it. Tutorial 08 reads the metrics of the finished fit, and tutorial 09 asks which parameters the data determine (profiles) and how uncertain they are (posterior).

Data. The synthetic example (phoskintime.networkmodel.example), written to a temporary folder. The time courses and the KinOpt/TFOpt weights are invented. Nothing fitted here means anything biologically.

Where the inputs come from, and what is fitted

step fits how
KinOpt α (kinase → site) and β (kinase activity from its protein and own sites) algebraic prediction of phosphosite series at each time point; no dynamics
TFOpt α (TF → target mRNA) and β (TF activity) algebraic prediction of mRNA series; no dynamics
PhosKinTime the rates of one coupled ODE system (A_i, B_i, C_i, D_i, E_i, Dp_i), the kinase gains c_k and tf_scale the SBML model is solved for every evaluation, and fold changes of all three layers are compared at once

KinOpt's and TFOpt's optimization runs (KinOpt 06, TFOpt 06) solve one constrained least-squares problem in α and β. PhosKinTime reads their α (and TFOpt's TF-level β) as fixed network weights (External tools); they are not parameters of this fit.

# Setup. Find the repository root (the folder with configs/config.toml and phoskintime/), put it on sys.path and work from
# there. A Jupyter kernel started outside pixi does not get pixi's PYTHONPATH, hence the sys.path line.
import json
import logging
import os
import sys
import tempfile
import time
from pathlib import Path

REPO_ROOT = Path.cwd().resolve()
while not ((REPO_ROOT / "configs" / "config.toml").is_file() and (REPO_ROOT / "phoskintime").is_dir()):
    if REPO_ROOT.parent == REPO_ROOT:
        raise RuntimeError("Start this notebook inside the PhosKinTime repository.")
    REPO_ROOT = REPO_ROOT.parent
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))
os.chdir(REPO_ROOT)

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

pd.set_option("display.width", 140)
pd.set_option("display.max_columns", 30)
logging.disable(logging.INFO)  # hide PhosKinTime's INFO log lines; warnings are still shown

from phoskintime.networkmodel import api

# Everything this tutorial writes goes into a new temporary folder, never into the repository.
WORK = Path(tempfile.mkdtemp(prefix="phoskintime-tutorial-07-"))
print("working folder:", WORK)


def show_settings(conf, keys):
    """Print the lines of ``conf`` that set one of ``keys`` (first occurrence each)."""
    seen = set()
    for line in Path(conf).read_text(encoding="utf-8").splitlines():
        key = line.split("=")[0].strip()
        if key in keys and key not in seen:
            seen.add(key)
            print(line)
working folder: /tmp/phoskintime-tutorial-07-gtm0ckxe

1. The example project and the run settings

The example's config.toml is the repository's configs/config.toml, with the input paths of the example and a few starts. Four starts on up to four cores; everything else (bounds, priors, solver tolerances, loss weights) keeps the defaults.

CONF = api.write_example(WORK / "project", n_starts=4, cores=4)
show_settings(CONF, {"fit_engine", "n_starts", "cores", "seed", "observation_model", "prior_file", "lambda_protein",
                     "lambda_rna", "lambda_phospho", "lambda_prior", "relative_tolerance", "absolute_tolerance"})
cores = 4
seed = 42
fit_engine = "sbmlsim"
observation_model = "linear_fc_mse"
lambda_prior   = 0.1
prior_file = "priors_lognormal.toml"
lambda_protein = 1.0
lambda_rna     = 1.0
lambda_phospho = 1.0
n_starts = 4
absolute_tolerance = 1e-8
relative_tolerance = 1e-8

2. The fit engines

The fit is handed to an established parameter-estimation tool as a PEtab problem: the run's SBML model (tutorial 01), its observables (the fold changes of tutorial 06), the measurements, and the parameters with their bounds and priors. Two engines read it ([networkmodel] fit_engine):

  • "sbmlsim" (default): sbmlsim's least-squares fit (trust-region reflective) with the Jacobian of sbmlsim-core, on libroadrunner. The profiles, the Laplace posterior and empirical Bayes (tutorial 09) also run in sbmlsim.
  • "pypesto": AMICI compiles the SBML model to C++ and gives exact gradients (forward sensitivities; adjoint above 100 parameters); pyPESTO runs the fides trust-region optimizer. It needs the amici environment (pixi run -e amici phoskintime run ...), which has the compilers.

The parameters are estimated as \(\ell = \ln\theta\) with the run's prior on \(\ell\). Every start is drawn log-uniformly in the bounds (a Latin hypercube in \(\ell\)), seeded with seed. Whatever the engine, each finished start is scored again with PhosKinTime's own objective (tutorial 06), so final_objective means the same with either engine; the engine's own value (sbmlsim_cost, pypesto_cost) differs from it by a constant.

3. Validate, then run

api.validate_inputs checks the inputs and builds the network without fitting (tutorial 03). api.run then runs python -m phoskintime.networkmodel.runner --conf <config> in a subprocess, exactly as phoskintime run does, and returns the run folder. The console output goes to a log file. This cell takes a minute or two.

report = api.validate_inputs(CONF)
print("inputs ok:", report.ok, "| errors:", report.errors)
t0 = time.perf_counter()
RUN = api.run(CONF, output_dir=WORK / "run", log=WORK / "run.log")
print(f"run finished in {time.perf_counter() - t0:.0f} s: {RUN}")
2026-12-03 14:46:36,264 - phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] orphan TF T2 has no mrna data to drive it: fallback its own state (data_drive_fallback)                          ⏱ 0.08 sec
2026-12-03 14:46:36,265 - phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] orphan TF T3 has no mrna data to drive it: fallback its own state (data_drive_fallback)                          ⏱ 0.08 sec
2026-12-03 14:46:36,273 - phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] observations of data-driven TFs ['T1'] are inputs: 9 rows removed from the loss                                  ⏱ 0.09 sec
inputs ok: True | errors: []
run finished in 48 s: /tmp/phoskintime-tutorial-07-gtm0ckxe/run

4. The PEtab problem

Before the fit the runner writes the problem to problem/petab_v1/ (PEtab v1: the AMICI engine reads it) and problem/petab_v2/ (sbmlsim reads it). Any PEtab tool can read these folders; the SBML file is the model of tutorial 01.

v1 = RUN / "problem" / "petab_v1"
print(sorted(p.name for p in v1.iterdir()))
params = pd.read_csv(v1 / "parameters.tsv", sep="\t")
params.head(8)
['conditions.tsv', 'measurements.tsv', 'model.xml', 'observables.tsv', 'parameters.tsv', 'phoskintime_reference.json', 'phoskintime_reference.tsv', 'problem.yaml']
parameterId parameterName parameterScale lowerBound upperBound estimate initializationPriorType initializationPriorParameters objectivePriorType objectivePriorParameters nominalValue
0 ln_A_A ln A_i[A] lin -11.028033 2.018095 1 uniform -11.02803254096727;2.0180947254913737 normal -4.504968907737949;148.09718444782712 0.000000
1 ln_A_B ln A_i[B] lin -11.028033 2.018095 1 uniform -11.02803254096727;2.0180947254913737 normal -4.504968907737949;148.09718444782712 0.000000
2 ln_A_K1 ln A_i[K1] lin -11.028033 2.018095 1 uniform -11.02803254096727;2.0180947254913737 normal -4.504968907737949;148.09718444782712 0.000000
3 A_T1 A_i[T1] log 1.000000 1.000000 0 NaN NaN NaN NaN 1.000000
4 ln_A_T2 ln A_i[T2] lin -11.028033 2.018095 1 uniform -11.02803254096727;2.0180947254913737 normal -4.504968907737949;148.09718444782712 0.000000
5 ln_A_T3 ln A_i[T3] lin -11.028033 2.018095 1 uniform -11.02803254096727;2.0180947254913737 normal -4.504968907737949;148.09718444782712 0.000000
6 ln_B_A ln B_i[A] lin -9.113125 -0.552262 1 uniform -9.113125240363846;-0.552261915871935 normal -4.83269357811789;97.18131127384524 -2.995732
7 ln_B_B ln B_i[B] lin -9.113125 -0.552262 1 uniform -9.113125240363846;-0.552261915871935 normal -4.83269357811789;97.18131127384524 -2.995732
pd.read_csv(v1 / "observables.tsv", sep="\t").head(6)
observableId observableFormula observableTransformation noiseFormula noiseDistribution
0 obs_protein_A max((P_A + X_A_S_1 + X_A_S_2), 9.9999999999999... lin 5.291503 normal
1 obs_protein_B max((P_B + X_B_Y_4), 9.9999999999999998e-13) / 1 lin 5.291503 normal
2 obs_protein_K1 max((P_K1 + X_K1_T_3), 9.9999999999999998e-13)... lin 5.291503 normal
3 obs_protein_T3 max((P_T3), 9.9999999999999998e-13) / 1 lin 5.291503 normal
4 obs_mrna_A max(R_A, 9.9999999999999998e-13) / max(R4_A, 9... lin 3.674235 normal
5 obs_mrna_B max(R_B, 9.9999999999999998e-13) / max(R4_B, 9... lin 3.674235 normal

Each estimated parameter is \(\ell = \ln\theta\) itself (ln_A_A is \(\ln A_i\) of protein A, on the linear scale of \(\ell\)); its bounds are the design bounds of tutorial 05 on the ln scale, the initialization prior (uniform over the bounds) is where the starts are drawn, and the objective prior is the run's prior on \(\ell\). phoskintime_reference.json records the export's self-check: PhosKinTime's objective at the nominal values and the constant by which the PEtab objective differs from it.

5. The multistart record

metadata.json records how the starts were made and how one was chosen:

meta = json.loads((RUN / "metadata.json").read_text(encoding="utf-8"))
ms_meta = meta["multistart"]
for key in ("engine", "algorithm", "n_starts", "seed", "start_rule", "selection_rule", "acceptance_rule",
            "accepted_starts", "status_counts", "tolerances", "versions"):
    print(f"{key:16s}", ms_meta.get(key))
engine           sbmlsim
algorithm        sbmlsim least_squares (trust region reflective, sbmlsim-core Jacobian)
n_starts         4
seed             42
start_rule       log-uniform Latin hypercube in the bounds of ln θ (sbmlsim SamplingType.LOGUNIFORM_LHS), seeded with seed
selection_rule   lowest PhosKinTime objective
acceptance_rule  sbmlsim reports success and a finite cost
accepted_starts  4
status_counts    {'converged': 4}
tolerances       {'absolute': 1e-08, 'relative': 1e-08}
versions         {'libroadrunner': '2.12.0.dev757', 'sbmlsim': '0.63.0', 'sbmlsim-core': '0.58.0', 'sbmlutils': '0.19.1'}

optimization/multistart_summary.csv has one row per start: the final objective (PhosKinTime's), the engine's cost, whether the engine reported success, the run time and which start is kept (selected_best).

ms = pd.read_csv(RUN / "optimization" / "multistart_summary.csv")
display(ms)
fig, ax = plt.subplots(figsize=(5, 3))
colors = ["tab:orange" if s else "tab:blue" for s in ms["selected_best"]]
ax.bar(ms["start_id"].astype(str), ms["final_objective"], color=colors)
ax.set_xlabel("start")
ax.set_ylabel("final objective")
ax.set_title("Multistart (orange: kept)")
plt.tight_layout()
plt.show()
start_id seed final_objective sbmlsim_cost engine_cost success convergence_status optimizer_success accepted runtime_seconds number_of_iterations stop_reason selected_best
0 0 42 0.087216 394.014421 394.014421 True converged True True 7.817927 NaN sbmlsim least_squares True
1 1 43 0.102593 394.029797 394.029797 True converged True True 9.456381 NaN sbmlsim least_squares False
2 2 44 0.107726 394.034931 394.034931 True converged True True 5.517912 NaN sbmlsim least_squares False
3 3 45 0.107734 394.034939 394.034939 True converged True True 7.464629 NaN sbmlsim least_squares False

png

What to read from this. The starts end at similar but not equal objective values: the objective is not convex, and the starts stop in different places. A start is kept by the lowest PhosKinTime objective among the starts the engine reports as successful. The difference sbmlsim_cost − final_objective is the same for every start (the engine's normalisation constant):

ok = ms[ms["success"]]
print("sbmlsim_cost - final_objective per start:", np.round((ok["sbmlsim_cost"] - ok["final_objective"]).to_numpy(), 8))
sbmlsim_cost - final_objective per start: [393.92720494 393.92720494 393.92720493 393.92720493]

The parameter vectors of all starts are in optimization/multistart_parameters.csv and the kept one in optimization/best_fit.csv, both in the run's raw coordinate (tutorial 05); the physical values are in parameter_status.csv (tutorials 08 and 09). Parameters that differ strongly between starts of similar objective are a first hint that the data do not pin them down:

pars = pd.read_csv(RUN / "optimization" / "multistart_parameters.csv").set_index("start_id")
names = [c for c in pars.columns if c not in ("seed", "success", "selected_best")]
raw = pars[names].T  # one column per start
raw["spread (max - min)"] = raw.max(axis=1) - raw.min(axis=1)
raw.sort_values("spread (max - min)", ascending=False).head(8)
start_id 0 1 2 3 spread (max - min)
D_i[A] -6.395841 -6.332414 4.780035 4.813740 11.209581
C_i[A] -5.170681 -5.021045 5.316847 5.345473 10.516154
D_i[B] 2.980427 -4.909316 -4.926776 -4.926300 7.907204
C_i[B] 2.736585 -4.939938 -4.932482 -4.930397 7.676523
E_i[B] -3.380841 1.653952 3.008751 3.022218 6.403059
E_i[K1] 8.556374 3.025798 3.705315 3.714344 5.530577
B_i[K1] -0.250670 -5.733272 -5.735355 -5.735127 5.484685
C_i[K1] 1.076987 -4.105995 -4.124322 -4.125408 5.202396

Each start's own sbmlsim record (the optimizer trace, settings and timing) is in optimization/sbmlsim_runs/. A rerun into the same folder reuses the finished starts and runs only the missing ones (resumed_start_ids in the metadata).

6. The Fréchet record

For the reported fit the runner simulates the model and computes the discrete Fréchet distance between observed and predicted curves, each curve the sequence of points (time, fold change), summed per layer and weighted with the \(\lambda_m\) (Metrics). optimization/frechet_selection.csv records them:

pd.read_csv(RUN / "optimization" / "frechet_selection.csv")
candidate frechet_total frechet_protein frechet_rna frechet_phospho objective selected
0 0 3.258945 1.149538 0.544947 1.56446 0.087216 True

The distances can be recomputed from the run's model_trajectories.csv (observed and predicted fold changes at the observation times) with phoskintime.common.frechet.frechet_distance:

from phoskintime.common.frechet import frechet_distance

traj = pd.read_csv(RUN / "model_trajectories.csv")
recomputed = {}
for layer, g in traj.groupby("type"):
    total = 0.0
    for _, curve in g.groupby(["protein", "psite"], dropna=False):
        curve = curve.sort_values("time")
        obs = np.ascontiguousarray(curve[["time", "fc_obs"]].to_numpy(dtype=float))
        pred = np.ascontiguousarray(curve[["time", "fc_pred"]].to_numpy(dtype=float))
        total += frechet_distance(obs, pred)
    recomputed[layer] = total
sel = pd.read_csv(RUN / "optimization" / "frechet_selection.csv").iloc[0]
pd.DataFrame({"recomputed": recomputed,
              "frechet_selection.csv": {"Protein": sel["frechet_protein"], "RNA": sel["frechet_rna"],
                                        "Phosphorylation": sel["frechet_phospho"]}})
recomputed frechet_selection.csv
Phosphorylation 1.56446 1.564460
Protein NaN 1.149538
RNA NaN 0.544947

The Fréchet distance is not normalised and is in the units of the data (the time axis, in minutes, is one of its two coordinates). Use it to rank fits of the same data, not as an absolute measure of quality.

Summary

  • api.run runs one fit exactly as the command line does; the run folder holds every record shown here.
  • The fit is a PEtab problem (problem/petab_v1, problem/petab_v2) of the run's SBML model, fitted by sbmlsim (default) or by AMICI and pyPESTO (fit_engine = "pypesto", the amici environment).
  • optimization/multistart_summary.csv records every start; the kept start has the lowest PhosKinTime objective among the successful ones. A rerun resumes the missing starts.
  • optimization/frechet_selection.csv records the Fréchet distances of the reported fit by layer.

Next

08. Fit metrics and diagnostics: the trajectories, residuals, RMSE and MAE of the finished fit, and what metadata.json records.