Skip to content

10. End-to-end reproducible pipeline

Download the notebook (executed for this page) · source

What this tutorial shows. The whole network-model workflow from the command line, on the synthetic example project: phoskintime example → phoskintime validate → phoskintime run → phoskintime bundle verify / bundle inspect → phoskintime export sbml / export petab. Then it opens the files that make a run reproducible: pixi.lock, the run's metadata.json (code commit, sha256 of every input), config_resolved.yaml, command.txt and the multistart seed.

Place in the series. Tutorials 01–09 took the network model apart (model, inputs, network, parameters, objective, fit, diagnostics, identifiability and posterior). This one runs it as a user would, as one pipeline; tutorial 11 does the same through the Python library and looks inside the run bundle.

Where the inputs come from. PhosKinTime is the last step of a chain of three tools:

step tool fits dynamics?
1 KinOpt α (kinase → phosphosite weights) and β (each kinase's activity as a combination of its own protein level and phosphosites) no: a static, constrained regression on the time series
2 TFOpt α (TF → target mRNA weights) and β (each TF's activity from its own protein level and phosphosites) no: likewise static
3 PhosKinTime (this page) the rates of a coupled ODE system (transcription, mRNA decay, translation, protein turnover, phosphorylation and dephosphorylation) yes: fitted to protein, mRNA and phosphosite time series together

PhosKinTime takes the KinOpt and TFOpt weights as fixed network weights; it does not refit them. It reads them only from the two result workbooks, checked against the file contract on the External tools page. The KinOpt and TFOpt tutorials with the same number run their own end-to-end pipelines; their outputs are what data/kinopt_results.xlsx and data/tfopt_results.xlsx stand for here.

Invented numbers

Every number in this tutorial comes from the synthetic example (phoskintime.networkmodel.example): smooth invented curves and hand-written KinOpt/TFOpt workbooks, not measurements and not the output of a real KinOpt or TFOpt run. The fit illustrates the files and the procedure; it means nothing biologically.

Setup

A Jupyter kernel started outside pixi does not get pixi's activation environment, so the first cell finds the repository root, puts it on sys.path and makes it the working folder (the same pattern as the other notebooks). Everything the tutorial writes goes into a new temporary folder, never into the repository.

pixi run phoskintime <command> is python -m phoskintime.config.cli <command> with the repository root on PYTHONPATH (Command line). The helper phoskintime(...) below runs exactly that in a subprocess, with the kernel's Python, and shortens the log lines for display (no colours, timestamps or timers; the temporary folder is shown as <work>).

import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path

import pandas as pd

# Repository root: the first folder upwards that holds pixi.toml and phoskintime/networkmodel/.
REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
                 if (p / "pixi.toml").is_file() and (p / "phoskintime" / "networkmodel").is_dir())
sys.path.insert(0, str(REPO_ROOT))
os.chdir(REPO_ROOT)

WORK = Path(tempfile.mkdtemp(prefix="phoskintime-tutorial-09-"))  # all outputs of this tutorial
pd.set_option("display.width", 140)
pd.set_option("display.max_colwidth", 80)

_ANSI = re.compile(r"\x1b\[[0-9;]*m")
_STAMP = re.compile(r"^\d{4}-\d\d-\d\d [\d:,]+ - ")


def tidy(line: str) -> str:
    """One log line without colour codes, timestamp and the trailing timer; the temporary folder as <work>."""
    line = _STAMP.sub("", _ANSI.sub("", line)).split("⏱")[0].rstrip()
    return line.replace(str(WORK), "<work>")


def phoskintime(*args, log=None, check=True):
    """Run `pixi run phoskintime <args>` (= python -m phoskintime.config.cli <args>); return (exit code, tidied output lines)."""
    env = {**os.environ, "PYTHONPATH": os.pathsep.join(filter(None, [str(REPO_ROOT), os.environ.get("PYTHONPATH")]))}
    proc = subprocess.run([sys.executable, "-m", "phoskintime.config.cli", *map(str, args)], cwd=REPO_ROOT, env=env,
                          stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    if log is not None:
        Path(log).write_text(proc.stdout, encoding="utf-8")  # the full console output
    lines = [tidy(x) for x in proc.stdout.splitlines() if x.strip()]
    if check and proc.returncode != 0:
        raise RuntimeError(f"phoskintime {args[0]} exited with {proc.returncode}:\n" + "\n".join(lines[-30:]))
    return proc.returncode, lines


def sha256(path) -> str:
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


print("repository:", REPO_ROOT.name, "| work folder: <work>")
repository: phoskintime | work folder: <work>

Step 1: write the example project

phoskintime example <folder> writes a small project: data/ with the four input tables and the two workbooks, priors_lognormal.toml, a config.toml (the repository's configs/config.toml with absolute input paths, output folder results/, a few multistart starts and no profile likelihoods) and a README.md. We ask for 2 starts on 2 cores to keep the run short.

PROJECT = WORK / "project"
code_, out = phoskintime("example", PROJECT, "--n-starts", 2, "--cores", 2)
print("\n".join(out))
sorted(p.relative_to(PROJECT).as_posix() for p in PROJECT.rglob("*") if p.is_file())
wrote <work>/project (config: <work>/project/config.toml)
['README.md',
 'config.toml',
 'data/kinase_net.csv',
 'data/kinopt_results.xlsx',
 'data/ms.csv',
 'data/rna.csv',
 'data/tf_net.csv',
 'data/tfopt_results.xlsx',
 'priors_lognormal.toml']

The six files in data/ are what a real study would bring from three sources:

file role real-world source
kinase_net.csv kinase → phosphosite network (GeneID, Psite, Kinase as {K1, K2}) the same interaction table KinOpt was given
tf_net.csv TF → target network (Source, Target) the same TF network TFOpt was given
ms.csv protein (empty Psite) and phosphosite time series, columns x1…x14 mass spectrometry
rna.csv mRNA time series, columns x1…x9 RNA-seq or arrays
kinopt_results.xlsx sheets Alpha Values, Beta Values a KinOpt run
tfopt_results.xlsx sheets Alpha Values, Beta Values a TFOpt run

The two workbooks are small, so we can look at the weights PhosKinTime will hold fixed. In the KinOpt workbook, α sums to 1 per site and the site A S_2 has a vertex solution (K2 gets α = 0, so that edge carries no weight in the model; KNOWN_ISSUES N32). In the TFOpt workbook, TF A's TF-level β is negative.

data = PROJECT / "data"
kinopt_alpha = pd.read_excel(data / "kinopt_results.xlsx", sheet_name="Alpha Values")
tfopt_alpha = pd.read_excel(data / "tfopt_results.xlsx", sheet_name="Alpha Values")
display(kinopt_alpha)   # KinOpt: kinase -> site weights (fixed in PhosKinTime)
tfopt_alpha             # TFOpt: TF -> mRNA weights (fixed in PhosKinTime)
Gene Psite Kinase Alpha
0 A S_1 K1 1.0
1 A S_2 K1 1.0
2 A S_2 K2 0.0
3 B Y_4 K1 0.7
4 B Y_4 K2 0.3
5 K1 T_3 K2 1.0
mRNA TF Value
0 A T1 0.6
1 B T1 0.5
2 A T2 0.4
3 K1 T3 1.0
4 B A 0.5

How KinOpt and TFOpt arrive at these α and β, and why α lands on a vertex of the simplex, is the subject of their tutorial 05 (KinOpt, TFOpt). Here they are inputs.

Step 2: validate

phoskintime validate --conf config.toml reads everything a run would read and builds the network, without fitting: the input files, the KinOpt/TFOpt file contract, the time columns against the time grids. Exit code 0 means a run can start. We show only the warnings and the verdict.

CONF = PROJECT / "config.toml"
rc, out = phoskintime("validate", "--conf", CONF, check=False)
print("exit code:", rc)
print("\n".join(x for x in out if "WARNING" in x or x in ("ok", "failed") or x.startswith(("error", "warning"))))
exit code: 0
phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] orphan TF T2 has no mrna data to drive it: fallback its own state (data_drive_fallback)
phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] orphan TF T3 has no mrna data to drive it: fallback its own state (data_drive_fallback)
phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] observations of data-driven TFs ['T1'] are inputs: 9 rows removed from the loss
ok

The warnings are expected for this example. T1, T2 and T3 are orphan TFs: TFs of the TF network that are not proteins with phosphosites in the kinase network. Under tf_orphan_policy = "data_drive" (the only policy since v0.7.0, KNOWN_ISSUES N31) an orphan's activity is its own measured mRNA (T1), and those data become an input; an orphan without mRNA (T2, T3) becomes its own mRNA and protein state. The example contains orphans on purpose, so the behaviour is visible; see Global network model.

Step 3: run

phoskintime run --conf config.toml is one network-model run (python -m phoskintime.networkmodel.runner). It writes the run's SBML model and PEtab problem, fits it with a multistart in sbmlsim (fit_engine), writes the run folder and ends by writing the run bundle results/results.pkt.zip. The full console output goes to a log file; we print the bundle line and the last line. This cell takes a minute or two.

t0 = time.perf_counter()
rc, out = phoskintime("run", "--conf", CONF, log=WORK / "run.log")
print(f"exit code {rc}, {time.perf_counter() - t0:.0f} s")
print("\n".join(x for x in out if "[Bundle]" in x or "[Complete]" in x))
exit code 0, 44 s
__main__ - INFO - [Bundle] Saved run bundle: <work>/project/results/results.pkt.zip (ok)
__main__ - INFO - [Complete] All results saved to: <work>/project/results
RUN = PROJECT / "results"
top = sorted(p.name for p in RUN.iterdir())
print(len(top), "entries in the run folder, among them:")
[n for n in top if n in ("metadata.json", "config_resolved.yaml", "command.txt", "console.log", "parameter_status.csv",
                         "model_trajectories.csv", "network_W_global.csv", "network_tf_mat.csv", "optimization",
                         "results.pkt.zip")]
53 entries in the run folder, among them:
['command.txt',
 'config_resolved.yaml',
 'console.log',
 'metadata.json',
 'model_trajectories.csv',
 'network_W_global.csv',
 'network_tf_mat.csv',
 'optimization',
 'parameter_status.csv',
 'results.pkt.zip']

The layout of the run folder is described in the result directory contract. A start counts as accepted when the fit engine reports success and a finite cost; the run keeps the accepted start with the lowest PhosKinTime objective (tutorial 07). Tutorial 08 shows how to read the fit's diagnostics.

Step 4: verify and inspect the bundle

bundle verify checks the bundle against the published contract (manifest schema, the sha256 and size of every file, table columns and dtypes, parameter and state order hashes, the copied inputs). bundle inspect summarises it. Both are plain Python and need no model code.

BUNDLE = RUN / "results.pkt.zip"
rc, out = phoskintime("bundle", "verify", BUNDLE, check=False)
print("verify exit code:", rc, "|", out[-1])
rc, out = phoskintime("bundle", "inspect", BUNDLE)
print("\n".join(out))
verify exit code: 0 | ok
pkt-e41c11a4b79ccaf2  schema 1.1  created 2026-12-03T14:47:26Z
producer: phoskintime 0.7.0 @ b613863688dc3242d2f9a52419eee26580eed509; model distributive (networkmodel)
  array  matrix_W_site_kinase   shape [4, 2]
  array  matrix_tf_target_tf    shape [3, 4]
  table  kinase_activity        2020 rows
  table  matrix_labels          13 rows
  table  metrics                47 rows
  table  multistart             2 rows
  table  parameters             111 rows
  table  state_index            16 rows
  table  steady_state           24 rows
  table  trajectories           194 rows
  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)

The missing lines are part of the contract: every table the bundle format defines is either present or declared missing with a reason (here: no profile likelihoods because the example turns them off, no posterior sampling, and tables the network model does not produce).

Step 5: export the fitted model

A finished run is exported in the formats of the SBML ecosystem (phoskintime export):

  • export sbml --run <run> writes the run's SBML model at its fitted parameters (sbml_reactions/ in the run folder by default), rebuilt from the run's model specification, validated with libsbml and checked against the reaction plan in roadrunner;
  • export petab --run <run> --out <folder> writes the run's estimation problem as a PEtab v1 problem (model, observables, measurements, parameters with bounds and priors) that other PEtab tools can read.
rc, out = phoskintime("export", "sbml", "--run", RUN)
print("\n".join(x for x in out if x.startswith(("SBML:", "Reactions:", "Manifest:"))))
rc, out = phoskintime("export", "petab", "--run", RUN, "--out", WORK / "petab")
print(sorted(p.name for p in (WORK / "petab").iterdir()))
SBML: <work>/project/results/sbml_reactions/networkmodel_reactions.xml
Reactions: 36 | Species: 19
Manifest: <work>/project/results/sbml_reactions/networkmodel_sbml_manifest.json
['conditions.tsv', 'measurements.tsv', 'model.xml', 'observables.tsv', 'parameters.tsv', 'phoskintime_reference.json', 'phoskintime_reference.tsv', 'problem.yaml']

What makes the run reproducible

A result can be reproduced only if four things are known: the code, the software environment, the inputs and the settings (including random seeds). The run records each of them.

Code and environment

metadata.json records the version, the git commit of the code that ran (the checkout of the imported library, not the current folder; KNOWN_ISSUES V5), whether that checkout had uncommitted changes (git_dirty), and a sha256 fingerprint of the library's Python files. pixi.lock (tracked in git) pins every package of every pixi environment, so the commit also fixes the environment: pixi install --frozen installs exactly what the lock file lists.

meta = json.loads((RUN / "metadata.json").read_text(encoding="utf-8"))
pd.Series({
    "package_version": meta["package_version"],
    "code.git_commit": meta["code"]["git_commit"],
    "code.git_dirty": meta["code"]["git_dirty"],
    "code.code_fingerprint": meta["code"]["code_fingerprint"][:16] + "…",
    "pixi_environment": meta["pixi_environment"],
    "python_version": meta["python_version"],
    "timestamp": meta["timestamp"],
    "pixi.lock sha256 (now)": sha256(REPO_ROOT / "pixi.lock")[:16] + "…",
}, name="value").to_frame()
value
package_version 0.7.0
code.git_commit b613863688dc3242d2f9a52419eee26580eed509
code.git_dirty False
code.code_fingerprint b98b1195d2a1eb23…
pixi_environment docs
python_version 3.14.10
timestamp 2026-12-03T14:46:45.793083+00:00
pixi.lock sha256 (now) 51028d49b5519db3…

git_dirty = True means the code had uncommitted changes when it ran; such a run cannot be rebuilt from the commit alone, and the fingerprint is then the only record of the code. metadata.json does not store the hash of pixi.lock itself; it is fixed through the commit.

Inputs

Every input file is recorded with its sha256 and size. Recomputing the hashes now shows that the files on disk are still the ones the run read; with your own data, this is how you check that a result belongs to a given dataset.

inputs = pd.DataFrame(meta["inputs"])
inputs["file"] = inputs["path"].map(lambda p: Path(p).name)
inputs["sha256 matches now"] = [sha256(p) == h for p, h in zip(inputs["resolved_path"], inputs["sha256"])]
inputs["sha256"] = inputs["sha256"].str[:16] + "…"
inputs[["file", "size_bytes", "sha256", "sha256 matches now"]]
file size_bytes sha256 sha256 matches now
0 kinase_net.csv 77 a0afd1052adf07b0… True
1 tf_net.csv 39 9bfdd7009f61d752… True
2 ms.csv 2195 24e7eeb0f40c6698… True
3 rna.csv 695 fecc7404667f9444… True
4 kinopt_results.xlsx 6483 f64867a5781f2ecc… True
5 tfopt_results.xlsx 6472 c0cd62c54af42a2e… True

The two workbooks are recorded a second time under external_results, with the tool, the role, the sheets read and the optional Metadata sheet of the workbook (tool version, commit). That is the link back to the KinOpt and TFOpt runs: a real workbook from KinOpt ≥ 0.11.0 or TFOpt ≥ 0.2.0 carries its own provenance, and its sha256 here ties this run to it. A KinOpt workbook written before 0.11.0 has misassigned kinase activities, so every α in it is suspect (KNOWN_ISSUES N38); check the version before using one.

ext = pd.DataFrame(meta["external_results"])
ext["sha256"] = ext["sha256"].str[:16] + "…"
ext[["tool", "role", "status", "sheets_read", "sha256", "metadata"]]
tool role status sheets_read sha256 metadata
0 KinOpt kinase priors (networkmodel) loaded [Alpha Values, Beta Values] f64867a5781f2ecc… None
1 TFOpt TF priors (networkmodel) loaded [Alpha Values, Beta Values] c0cd62c54af42a2e… None

Settings and command

config_resolved.yaml is every setting the run used after the config file and the command-line options were combined, and command.txt is the command. The bundle's manifest stores the sha256 of config_resolved.yaml as config_sha256.

print((RUN / "command.txt").read_text(encoding="utf-8").replace(str(WORK), "<work>").replace(str(REPO_ROOT), "<repo>"))
resolved = (RUN / "config_resolved.yaml").read_text(encoding="utf-8")
keys = ("model:", "fit_engine:", "mechanism:", "n_starts:", "seed:", "cores:", "tf_orphan_policy:", "ck_prior_centre:",
        "profile_likelihood:", "posterior_method:")
print("\n".join(x for x in resolved.splitlines() if x.startswith(keys)))
<repo>/phoskintime/networkmodel/runner.py --conf <work>/project/config.toml

ck_prior_centre: kinopt_beta
cores: 2
fit_engine: sbmlsim
mechanism: ''
model: distributive
n_starts: 2
posterior_method: none
profile_likelihood: false
seed: 42
tf_orphan_policy: data_drive

Seeds and starts

The multistart is seeded. Every start is drawn log-uniformly inside the bounds (a Latin hypercube in ln θ, sbmlsim's LOGUNIFORM_LHS) from seed. The rule is written into metadata.json together with the seed, so the starting points of a run can be regenerated exactly; each start's own record is in optimization/sbmlsim_runs/.

ms = meta["multistart"]
print("seed:", ms["seed"], "| engine:", ms["engine"], "| starts:", ms["n_starts"],
      "| accepted:", ms["accepted_starts"], "| selection:", ms["selection_rule"])
print("start rule:", ms["start_rule"])
summary = pd.read_csv(RUN / "optimization" / "multistart_summary.csv")
summary[["start_id", "seed", "final_objective", "convergence_status", "success", "accepted", "runtime_seconds",
         "selected_best"]]
seed: 42 | engine: sbmlsim | starts: 2 | accepted: 2 | selection: lowest PhosKinTime objective
start rule: log-uniform Latin hypercube in the bounds of ln θ (sbmlsim SamplingType.LOGUNIFORM_LHS), seeded with seed
start_id seed final_objective convergence_status success accepted runtime_seconds selected_best
0 0 42 0.107728 converged True True 3.044779 False
1 1 43 0.078991 converged True True 4.431071 True

Identical starting points do not promise bit-identical results on another machine: floating-point results can differ with the CPU, the number of threads and library builds. This tutorial does not test that; compare objective values and trajectories with a tolerance.

The bundle carries the record

The bundle copies metadata.json, config_resolved.yaml, command.txt, console.log and (up to 50 MB each) the inputs into provenance/, and its manifest lists the sha256 of every file. So a single .pkt.zip is enough to check later which code, settings and inputs produced a result. Inputs that must stay private travel with the bundle too: see the warning on the Run bundle page.

import zipfile

with zipfile.ZipFile(BUNDLE) as zf:
    root = zf.namelist()[0].split("/")[0]
    manifest = json.loads(zf.read(f"{root}/manifest.json"))
    resolved_in_bundle = zf.read(f"{root}/provenance/config_resolved.yaml")
print("config_sha256 in manifest == sha256(provenance/config_resolved.yaml):",
      manifest["config_sha256"] == hashlib.sha256(resolved_in_bundle).hexdigest())
print("producer:", {k: manifest["producer"][k] for k in ("phoskintime_version", "git_commit", "git_dirty")})
pd.DataFrame(manifest["inputs"])[["name", "bytes", "copied", "path"]]
config_sha256 in manifest == sha256(provenance/config_resolved.yaml): True
producer: {'phoskintime_version': '0.7.0', 'git_commit': 'b613863688dc3242d2f9a52419eee26580eed509', 'git_dirty': False}
name bytes copied path
0 kinase_net.csv 77 True provenance/inputs/00_kinase_net.csv
1 tf_net.csv 39 True provenance/inputs/01_tf_net.csv
2 ms.csv 2195 True provenance/inputs/02_ms.csv
3 rna.csv 695 True provenance/inputs/03_rna.csv
4 kinopt_results.xlsx 6483 True provenance/inputs/04_kinopt_results.xlsx
5 tfopt_results.xlsx 6472 True provenance/inputs/05_tfopt_results.xlsx

To reproduce a run elsewhere

  1. Check out the recorded commit (producer.git_commit) and install the locked environment: git checkout <commit> && pixi install --frozen.
  2. Use the same inputs: the copies in the bundle's provenance/inputs/, or your files after checking their sha256 against metadata.json.
  3. Use the same settings: the project's config.toml and the options in command.txt. config_resolved.yaml records what they resolved to; compare it with the new run's.
  4. Run pixi run phoskintime run --conf config.toml, then compare the new bundle with the old one (tutorial 11 reads bundle tables with pandas).

KinOpt and TFOpt record their runs in the same way (see their tutorial 09: KinOpt, TFOpt). A fully reproducible chain records all three: the KinOpt and TFOpt runs that wrote the workbooks, and the PhosKinTime run that read them by sha256.

Next

11. Library API and run bundle: the same pipeline from Python with phoskintime.networkmodel.api, the tables of a run as DataFrames, and the run bundle file by file.