08. Fit metrics and diagnostics
Download the notebook (executed for this page) · source
What this tutorial shows. How to read a finished network-model fit: the observed and predicted trajectories, the
residuals, RMSE and MAE per layer and per protein through phoskintime.networkmodel.api.read_results, how these metrics relate to
the objective that was minimised, and the provenance a run records in metadata.json (code version, input checksums,
the KinOpt/TFOpt workbooks it read, solver statistics).
Place in the series. Tutorial 07 ran the fit. This tutorial runs the same kind of small fit at the top (a fresh kernel has no run) and reads it. Tutorial 09 asks which parameters the data determine and how uncertain they are.
Data. The synthetic example (phoskintime.networkmodel.example), written to a temporary folder. The time courses and the
KinOpt/TFOpt weights are invented. The metrics below say how well a two-start fit reproduces invented curves, nothing
more.
Contrast with KinOpt and TFOpt
KinOpt and TFOpt report the fit of an algebraic prediction: each phosphosite series (KinOpt) or mRNA series (TFOpt) against an α- and β-weighted sum of input series at the same time points (KinOpt 07, TFOpt 07). Their residuals belong to one layer each. PhosKinTime fits one ODE system to three layers at once (protein, mRNA and phosphosite fold changes), with KinOpt's and TFOpt's weights held fixed. A residual here is the difference between a simulated state and the data. A poor fit can come from the rates, from the network weights the fit cannot change (KNOWN_ISSUES N32, N38) or from the model structure.
# 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 numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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
# 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)
working folder: /tmp/phoskintime-tutorial-07-98spqqou
1. A small fit
The example project with two starts, run as in tutorial 07. This cell takes about a minute.
from phoskintime.networkmodel import api
def show_settings(conf, keys):
"""Print the lines of ``conf`` that set one of ``keys`` (first occurrence each)."""
seen = set()
for line in 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)
CONF = api.write_example(WORK / "project", n_starts=2, cores=2)
show_settings(CONF, {"fit_engine", "n_starts", "cores", "seed", "observation_model"})
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}")
pd.read_csv(RUN / "optimization" / "multistart_summary.csv")[["start_id", "final_objective", "success",
"selected_best", "runtime_seconds"]]
cores = 2
seed = 42
fit_engine = "sbmlsim"
observation_model = "linear_fc_mse"
n_starts = 2
run finished in 47 s: /tmp/phoskintime-tutorial-07-98spqqou/run
| start_id | final_objective | success | selected_best | runtime_seconds | |
|---|---|---|---|---|---|
| 0 | 0 | 0.107728 | True | False | 4.052123 |
| 1 | 1 | 0.078991 | True | True | 6.641124 |
2. The run's tables
api.read_results(run_dir) returns the tables of the run bundle (phoskintime.common.bundle.build_tables) as DataFrames, without
writing a bundle. missing says which tables this run does not have and why.
res = api.read_results(RUN)
print("tables:", sorted(k for k in res if k != "missing"))
for name, reason in res["missing"].items():
print(f" missing {name}: {reason}")
tables: ['kinase_activity', 'matrix_labels', 'metrics', 'multistart', 'parameters', 'state_index', 'steady_state', 'trajectories']
missing profile_likelihood: no profile likelihoods in this run
missing posterior_draws: no posterior sampling in this run ([networkmodel.posterior] method none)
missing sensitivity: the sensitivity analysis was not run for this run (sensitivity = true / --sensitivity)
missing embeddings: the network model has no embeddings (PCA/t-SNE were protwise outputs, removed in v0.7.0)
missing convergence: the network model records no per-iteration objective history
missing pareto: the fit keeps one vector with one scalar objective (scalar_objective.csv); there is no front
missing knockouts: not part of a run: in-silico experiments are written as experiment bundles (phoskintime simulate)
missing perturbations: not part of a run: in-silico experiments are written as experiment bundles (phoskintime simulate)
missing parameter_profiles: not produced by the network model
missing perturbation_samples: not part of a run: in-silico experiments are written as experiment bundles (phoskintime simulate)
3. Trajectories
trajectories has one row per observation: layer, protein, site, time, the observed fold change value_obs and the
predicted one value_pred. It is the run's model_trajectories.csv in the bundle's column names. Fold changes are
taken against each layer's baseline time (protein and phosphosites at t = 0, mRNA at its first time point, 4 min, in
this example), so at the baseline both values are 1 by construction.
traj = res["trajectories"].copy()
traj["residual"] = traj["value_pred"] - traj["value_obs"]
print(traj.groupby("layer").size().rename("observations").to_string())
traj.head()
layer
phospho 56
protein 84
rna 54
| workflow | scenario | sample_id | layer | protein | psite | state | time | value_obs | value_pred | residual | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | networkmodel | fit | best | phospho | A | S_1 | A_S_1 | 0.00 | 1.000000 | 1.000000 | 0.000000 |
| 1 | networkmodel | fit | best | phospho | A | S_1 | A_S_1 | 0.50 | 1.359831 | 1.234988 | -0.124843 |
| 2 | networkmodel | fit | best | phospho | A | S_1 | A_S_1 | 0.75 | 1.507045 | 1.302186 | -0.204859 |
| 3 | networkmodel | fit | best | phospho | A | S_1 | A_S_1 | 1.00 | 1.635100 | 1.351804 | -0.283296 |
| 4 | networkmodel | fit | best | phospho | A | S_1 | A_S_1 | 2.00 | 1.989233 | 1.468304 | -0.520929 |
states = traj.drop_duplicates("state")[["state", "layer"]].to_numpy()
ncol = 4
fig, axes = plt.subplots(int(np.ceil(len(states) / ncol)), ncol, figsize=(13, 2.4 * np.ceil(len(states) / ncol)),
sharex=True)
for ax, (state, layer) in zip(axes.flat, states):
g = traj[traj["state"] == state].sort_values("time")
ax.plot(g["time"], g["value_obs"], "o", ms=4, label="observed (synthetic)")
ax.plot(g["time"], g["value_pred"], "-", label="model")
ax.set_title(f"{state} ({layer})", fontsize=9)
ax.set_xscale("symlog", linthresh=1.0)
for ax in list(axes.flat)[len(states):]:
ax.axis("off")
axes.flat[0].legend(fontsize=7)
fig.supxlabel("time (min, symlog)")
fig.supylabel("fold change")
plt.tight_layout()
plt.show()

4. Residuals
A residual is predicted minus observed fold change. Look at the pattern over time, not only at its size: residuals of one sign over a stretch of time mean that the model misses a feature of the curve (a peak that comes too early, a level it cannot reach). With real data, note that the MS series are Gaussian-process-smoothed means, so neighbouring residuals are correlated and look smaller than measurement error (KNOWN_ISSUES N36).
fig, axes = plt.subplots(1, 3, figsize=(13, 3), sharey=True)
for ax, (layer, g) in zip(axes, traj.groupby("layer")):
for state, s in g.groupby("state"):
ax.plot(s["time"], s["residual"], "o-", ms=3, lw=0.8, label=state)
ax.axhline(0, color="k", lw=0.8)
ax.set_xscale("symlog", linthresh=1.0)
ax.set_title(layer)
ax.set_xlabel("time (min)")
ax.legend(fontsize=6)
axes[0].set_ylabel("predicted - observed")
plt.tight_layout()
plt.show()

5. RMSE and MAE
The metrics table holds RMSE, MAE and the number of observations overall (layer empty), per layer and per
protein, computed from trajectories; plus the objective value and the Fréchet distances of tutorial 07.
m = res["metrics"]
overall = m[m["protein"].isna()].assign(layer=lambda d: d["layer"].fillna("all"))
overall.pivot_table(index="layer", columns="metric", values="value", aggfunc="first")
| metric | frechet_distance | mae | n_obs | objective | rmse |
|---|---|---|---|---|---|
| layer | |||||
| all | 3.051544 | 0.118227 | 139.0 | 0.078991 | 0.167101 |
| phospho | 1.450983 | 0.160535 | 56.0 | NaN | 0.203013 |
| protein | 1.117681 | 0.097711 | 56.0 | NaN | 0.153564 |
| rna | 0.482880 | 0.073032 | 27.0 | NaN | 0.096744 |
per_protein = m[m["protein"].notna() & m["metric"].isin(["rmse", "mae"])]
per_protein.pivot_table(index=["layer", "protein"], columns="metric", values="value")
| metric | mae | rmse | |
|---|---|---|---|
| layer | protein | ||
| phospho | A | 0.185503 | 0.237676 |
| B | 0.120837 | 0.156944 | |
| K1 | 0.150296 | 0.165062 | |
| protein | A | 0.146215 | 0.185162 |
| B | 0.063539 | 0.089255 | |
| K1 | 0.166122 | 0.226765 | |
| T3 | 0.014967 | 0.025563 | |
| rna | A | 0.055646 | 0.072096 |
| B | 0.051874 | 0.065777 | |
| K1 | 0.111577 | 0.136211 |
Baseline rows. The metrics include the baseline observations, where observed and predicted values are both 1. They lower RMSE and MAE a little. Recomputed without them:
baseline = json.loads((RUN / "metadata.json").read_text(encoding="utf-8"))["effective_settings"]["baseline_times"]
print("baseline time per layer (min):", baseline)
is_base = np.isclose(traj["time"], traj["layer"].map(baseline).astype(float))
rows = {}
for label, d in (("with baseline rows", traj), ("without baseline rows", traj[~is_base])):
rows[label] = d.groupby("layer")["residual"].apply(lambda r: np.sqrt(np.mean(r ** 2)))
pd.DataFrame(rows).rename_axis("RMSE by layer")
baseline time per layer (min): {'phospho': 0.0, 'protein': 0.0, 'rna': 4.0}
| with baseline rows | without baseline rows | |
|---|---|---|
| RMSE by layer | ||
| phospho | 0.203013 | 0.210676 |
| protein | 0.153564 | 0.159361 |
| rna | 0.096744 | 0.102612 |
6. Metrics and the objective
The fit minimised the objective, not RMSE. Under the default data term (observation_model = "linear_fc_mse") the
objective is Σ_m λ_m · (weighted MSE of the fold changes of modality m) + λ_prior · (prior penalty). The run writes
its terms to picked_objectives.json. In this example every observation weight is 1 and λ_protein = λ_rna =
λ_phospho = 1, so each data term equals the square of the layer's RMSE above; with other weights or λ they differ.
The prior term has no counterpart in the metrics (tutorial 05).
picked = json.loads((RUN / "picked_objectives.json").read_text(encoding="utf-8"))
rmse = m[(m["metric"] == "rmse") & m["protein"].isna() & m["layer"].notna()].set_index("layer")["value"]
pd.DataFrame({"objective term": {"protein": picked["protein"], "rna": picked["mrna"], "phospho": picked["phospho"],
"prior": picked["prior"], "total": picked["scalar_score"]},
"RMSE^2 from metrics": {**(rmse ** 2).to_dict(), "prior": np.nan,
"total": np.nan}})
| objective term | RMSE^2 from metrics | |
|---|---|---|
| protein | 0.023582 | 0.023582 |
| rna | 0.009359 | 0.009359 |
| phospho | 0.041214 | 0.041214 |
| prior | 0.004836 | NaN |
| total | 0.078991 | NaN |
The metrics table has no R². KinOpt and TFOpt report R² for their algebraic fits; for a PhosKinTime fit it can be
computed from trajectories if needed.
7. Provenance: metadata.json
Every run writes metadata.json next to its results. It records what was run and on what, so that a result can be
traced back through the chain: the code (git commit, whether the working tree had uncommitted changes, a fingerprint
of the code), the package version and pixi environment, every input file with its SHA-256 checksum, and the KinOpt
and TFOpt workbooks with their checksums, the sheets read and their status. If a workbook carries a Metadata
sheet, its tool version and commit are recorded as well (External tools).
meta = json.loads((RUN / "metadata.json").read_text(encoding="utf-8"))
print("keys:", ", ".join(sorted(meta)))
print()
for key in ("package_version", "git_commit", "timestamp", "workflow", "pixi_environment", "config_source"):
print(f"{key:18s} {meta.get(key)}")
print("code ", {k: meta["code"][k] for k in ("git_commit", "git_dirty")})
keys: code, command_arguments, config_source, effective_inputs, effective_settings, external_results, git_commit, inputs, inputs_report, multistart, output_directory, package_version, parameter_status, pixi_environment, priors, python_executable, python_version, regulators, resolved_config_path, scaling, supplied_config_path, timestamp, workflow, zero_influence
package_version 0.7.0
git_commit b613863688dc3242d2f9a52419eee26580eed509
timestamp 2026-12-03T14:46:35.920943+00:00
workflow networkmodel.runner
pixi_environment docs
config_source custom
code {'git_commit': 'b613863688dc3242d2f9a52419eee26580eed509', 'git_dirty': False}
inputs = pd.DataFrame(meta["inputs"])[["path", "sha256", "size_bytes"]]
inputs["path"] = inputs["path"].map(lambda p: Path(p).name)
display(inputs)
ext = pd.DataFrame(meta["external_results"])
ext["path"] = ext["path"].map(lambda p: Path(p).name)
display(ext[[c for c in ("tool", "path", "role", "status", "sheets_read", "sha256", "metadata", "summary_sheet") if c in ext]])
| path | sha256 | size_bytes | |
|---|---|---|---|
| 0 | kinase_net.csv | a0afd1052adf07b0c61422ba7c154858f9464b74c06c5e... | 77 |
| 1 | tf_net.csv | 9bfdd7009f61d752ee71aa6cc950395f734e436e3828b1... | 39 |
| 2 | ms.csv | 24e7eeb0f40c669850a3858e8f4f2e7fe24fd821498a09... | 2195 |
| 3 | rna.csv | fecc7404667f944414bf6894e78d0acbfe5cfa215c964a... | 695 |
| 4 | kinopt_results.xlsx | 95eb52f1422f924c16f2cd95eb83ab94c01788d4c25c45... | 6483 |
| 5 | tfopt_results.xlsx | a5142ecdeaa485c4931ace362cdc5bd700a1d4e3c905cb... | 6472 |
| tool | path | role | status | sheets_read | sha256 | metadata | summary_sheet | |
|---|---|---|---|---|---|---|---|---|
| 0 | KinOpt | kinopt_results.xlsx | kinase priors (networkmodel) | loaded | [Alpha Values, Beta Values] | 95eb52f1422f924c16f2cd95eb83ab94c01788d4c25c45... | None | None |
| 1 | TFOpt | tfopt_results.xlsx | TF priors (networkmodel) | loaded | [Alpha Values, Beta Values] | a5142ecdeaa485c4931ace362cdc5bd700a1d4e3c905cb... | None | None |
The example workbooks have neither a Metadata sheet nor a summary sheet, so metadata and summary_sheet are
empty: nothing records which KinOpt or TFOpt version wrote them. With real workbooks this matters. KinOpt workbooks written before KinOpt 0.11.0 build each kinase's
activity from another protein's series, so every α and β in them is suspect (KNOWN_ISSUES N38). The checksum
in metadata.json identifies the workbook a run used; the workbook's own summary sheet or Metadata sheet tells
which tool version wrote it, and summary_sheet copies that summary (method, objective, R², …) into the run's
provenance.
One more record helps to judge a fit: the multistart record of tutorial 07 (engine, versions, how the starts were made and which was kept).
print({k: meta["multistart"].get(k) for k in ("engine", "algorithm", "best_start_id", "selection_rule",
"accepted_starts", "status_counts", "versions")})
{'engine': 'sbmlsim', 'algorithm': 'sbmlsim least_squares (trust region reflective, sbmlsim-core Jacobian)', 'best_start_id': 1, 'selection_rule': 'lowest PhosKinTime objective', 'accepted_starts': 2, 'status_counts': {'converged': 2}, 'versions': {'libroadrunner': '2.12.0.dev757', 'sbmlsim': '0.63.0', 'sbmlsim-core': '0.58.0', 'sbmlutils': '0.19.1'}}
Summary
api.read_resultsgives the run's tables:trajectories(observed and predicted fold changes),metrics(RMSE, MAE, n_obs overall, per layer and per protein; the objective; Fréchet distances),parameters,multistartand more.- Residuals are predicted minus observed fold change. Their pattern over time says more than one number.
- The fit minimises the weighted, λ-scaled MSE plus a prior term; RMSE and MAE are unweighted and include the baseline rows.
metadata.jsonrecords the code version, input and workbook checksums, the sheets read from the KinOpt and TFOpt workbooks and the multistart record. It is how a result is traced back to the KinOpt and TFOpt runs it depends on.
Next
09. Identifiability and the posterior: which parameters the data determine
(profile likelihoods), the labels of parameter_status.csv, and the posterior (Laplace and MCMC).