Skip to content

12. Build your own model, from files to the SBML ecosystem

Download the notebook (executed for this page) · source

What this tutorial shows. How to go from nothing to a model of your own and use it: which files a model is made of, how to write a config.toml, how to define new reaction kinetics in a mechanism file, how to check that everything works without any measured data (we make the data ourselves from known parameters), how to fit and read the result, and what you can then do with the SBML model: inspect it, print its equations, simulate it with libroadrunner and sbmlsim, scan parameters, run in-silico experiments, rank sensitivities, and export it in community standards.

Who it is for. A bachelor or master student with some Python. Background: Learn. Tutorials 01 to 11 go through single parts in more detail.

Place in the series. The last tutorial. It puts the parts together for a model that is new from the first file.

Data. There is none. The network (kinases KIN1, KIN2; a transcription factor TFX; its targets GENEY and SUBZ) is invented, and the "observations" are simulated by us with added noise. Nothing here describes a real protein. This is the standard way to test a modelling workflow: if you know the truth, you can see what a fit can and cannot recover.

Run time. About four minutes, most of it the fit and its profile likelihoods.

Setup

The notebook works with a clone of the repository and with an installed package (pip install phoskintime). In a clone the setup cell puts the repository root on sys.path, because a Jupyter kernel started outside pixi does not get pixi's environment; with an installed package there is nothing to add. Everything is written into a new temporary folder.

PhosKinTime reads some settings (the time grids, the model family, the solver tolerances) from a config file once per Python process, when its model modules are first imported. We therefore name our config file in the environment variable PHOSKINTIME_NETWORKMODEL_CONFIG right away, before we write it. Rule: one model configuration per kernel; restart the kernel after changing time points, family or tolerances.

import contextlib
import logging
import os
import sys
import tempfile
import time
from pathlib import Path

# In a clone: put the repository root on sys.path. With an installed package there is no clone and nothing to add.
REPO_ROOT = next((p for p in [Path.cwd(), *Path.cwd().parents]
                  if (p / "pixi.toml").is_file() and (p / "phoskintime" / "networkmodel").is_dir()), None)
if REPO_ROOT is not None and str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

WORK = Path(tempfile.mkdtemp(prefix="phoskintime-tutorial-12-"))  # everything this tutorial writes
PROJECT = WORK / "project"
DATA = PROJECT / "data"
DATA.mkdir(parents=True)
CONF = PROJECT / "config.toml"
os.environ["PHOSKINTIME_NETWORKMODEL_CONFIG"] = str(CONF)  # one model configuration per kernel
os.chdir(WORK)
CORES = min(4, os.cpu_count() or 1)

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import Markdown, display
from IPython.utils.capture import capture_output

%matplotlib inline
pd.set_option("display.width", 140)
pd.set_option("display.max_colwidth", 90)
logging.disable(logging.INFO)  # hide PhosKinTime's INFO log lines; warnings are still shown

# colours used in every figure
BLUE, ORANGE, AQUA, VIOLET, GREY = "#257de0", "#f47230", "#00b894", "#6a4ce2", "#777777"


@contextlib.contextmanager
def quiet():
    """Hide repeated log and console messages of a call (we show what matters ourselves)."""
    level = logging.root.manager.disable
    logging.disable(logging.WARNING)
    try:
        with capture_output():  # printed and displayed messages
            yield
    finally:
        logging.disable(level)


from phoskintime.config_loader import shipped_file  # default files, in a clone or an installed package
from phoskintime.networkmodel import mechanism as mech

print("temporary project folder created")
temporary project folder created

1. What the files are

A PhosKinTime model is not written as one big file of equations. It is built from a few small files:

file what it says who writes it
config.toml which files to read, the time points, and how to fit you (start from the shipped one)
mechanism file (*.toml) per protein: which reactions happen and with which rate law shipped with PhosKinTime, or yours
kinase network CSV which kinase acts on which site you (columns GeneID, Psite, Kinase)
TF network CSV which transcription factor regulates which gene you (columns Source, Target)
MS CSV protein and phosphosite time series; the kinases' protein series drive the model your measurements
RNA CSV mRNA time series your measurements
priors file (priors_*.toml) what you believe about parameter values before seeing data shipped with PhosKinTime
KinOpt / TFOpt workbooks (optional) edge weights fitted by the two external tools External tools

From these PhosKinTime writes one SBML model (SBML is the standard file format for models in systems biology), and every simulation, fit and export runs on it.

2. Mechanism files: the reactions

A mechanism file (format phoskintime-mechanism/1) lists the reactions of one protein; PhosKinTime repeats them for every protein and site of your network. It has a header (format, [mechanism] with a name and a family, [ptm] naming the modification) and one [[reactions]] block per reaction. PhosKinTime ships four families and one example of another post-translational modification (PTM):

files = sorted(mech.MODELS_DIR.glob("*.toml")) + sorted((mech.MODELS_DIR / "examples").glob("*.toml"))
rows = []
for f in files:
    m = mech.load(f)
    rows.append({"file": f.name, "family": m.family, "PTM": m.ptm["name"], "reactions": len(m.reactions),
                 "description": m.doc})
pd.DataFrame(rows)
file family PTM reactions description
0 combinatorial.toml combinatorial phosphorylation 6 mRNA -> protein -> one form per modification pattern (combinatorial)
1 distributive.toml distributive phosphorylation 7 mRNA -> protein -> one form per modified site (distributive)
2 saturation.toml saturation phosphorylation 7 as distributive, with saturating translation C·R/(1+R) and modification S·P/(1+P)
3 sequential.toml sequential phosphorylation 7 mRNA -> protein -> modification chain in residue order (sequential)
4 acetylation_mm.toml distributive acetylation 7 mRNA -> protein -> one acetylated form per site; saturating deacetylation

Here is the header and one reaction of the distributive file, the simplest family: each site is modified from the unmodified protein P into its own form X, and back.

distributive = (mech.MODELS_DIR / "distributive.toml").read_text(encoding="utf-8")
header = distributive[distributive.index("format ="):distributive.index("[[reactions]]")]
block = next(b for b in distributive.split("[[reactions]]") if 'kind = "phosphorylation"' in b)
print(header + "[[reactions]]" + block)
format = "phoskintime-mechanism/1"

[mechanism]
name = "distributive"
family = "distributive"   # state layout: distributive | sequential | combinatorial | saturation
doc = "mRNA -> protein -> one form per modified site (distributive)"

[ptm]
name = "phosphorylation"
modification = "phosphorylation"       # reaction kind of the modification step
demodification = "dephosphorylation"   # reaction kind of the reverse step

[[reactions]]
kind = "phosphorylation"
per = "site"
reactants = ["P"]
products = ["X"]
modifiers = "site_kinases"
rate = "{S} * {P}"
reversible_if_signed_drive = true
sbo = "SBO:0000216"
go = "GO:0006468"
key meaning
kind a name for the reaction (the SBML reaction becomes rx_<kind>_<label>)
per repeat the reaction once per protein or per site (combinatorial files: state, state_site)
reactants, products species consumed and produced: R mRNA, P unmodified protein, X modified form
modifiers who influences the reaction without being consumed: "site_kinases", "regulators" or species
rate the rate law, a formula with {symbols}
sbo, go annotations: what kind of reaction this is, in standard vocabularies (SBO, Gene Ontology)

Each scope offers fixed symbols. You can use them, but you cannot invent new species or parameters in the file:

pd.DataFrame({"scope": list(mech.SYMBOLS),
              "symbols you may use": [", ".join(sorted(s)) for s in mech.SYMBOLS.values()]})
scope symbols you may use
0 protein A, B, C, D, E, M0, P, R, gene, synth
1 site A, B, C, D, Dp, E, P, R, S, X, gene, prev, site, synth
2 state A, B, C, D, D_state, E, M, M0, R, gene, m, synth
3 state_site A, B, C, D, D_state, Dp, E, M, M0, M_to, R, S, gene, m, site, synth

3. Define new dynamics

The built-in distributive law says phosphorylation is proportional to the unmodified protein: rate = S · P (S is the activity of the site's kinases). A real enzyme can saturate: when there is much substrate, the rate stops growing. The textbook form is Michaelis-Menten, S · P / (Km + P). We write it so that it equals the linear law at P = 1:

\[v = S \cdot P \cdot \frac{1 + K_m}{K_m + P}, \qquad K_m = 0.5\]

Km is a fixed number written into the rate law (a mechanism file cannot add a fitted parameter). Making our file means copying the closest built-in one and changing the name and one rate:

text = distributive.replace('name = "distributive"\n', 'name = "saturating_phosphorylation"\n', 1)
text = text.replace('doc = "mRNA -> protein -> one form per modified site (distributive)"',
                    'doc = "distributive, with Michaelis-Menten (Km = 0.5) phosphorylation"')
text = text.replace('rate = "{S} * {P}"', 'rate = "{S} * {P} * 1.5 / (0.5 + {P})"')
MECHANISM = PROJECT / "saturating_phosphorylation.toml"
MECHANISM.write_text(text, encoding="utf-8")

mine = mech.load(MECHANISM)  # loading checks the whole file
print(mine.name, "| family:", mine.family, "| model code:", mine.model_code)
mech.for_run(str(MECHANISM), mine.model_code)  # the family must be the run's model family
pd.DataFrame([{"kind": r.kind, "per": r.per, "rate law": r.rate} for r in mine.reactions])
saturating_phosphorylation | family: distributive | model code: 0
kind per rate law
0 transcription protein {synth}
1 mrna_decay protein {B} * {R}
2 translation protein {C} * {R}
3 protein_decay protein {D} * {P}
4 phosphorylation site {S} * {P} * 1.5 / (0.5 + {P})
5 dephosphorylation site {E} * {X}
6 phospho_decay site ({D} + {Dp}) * {X}
P = np.linspace(0, 3, 200)
fig, ax = plt.subplots(figsize=(5.5, 3.2))
ax.plot(P, P, color=GREY, ls="--", lw=2, label="built in: S · P")
ax.plot(P, P * 1.5 / (0.5 + P), color=BLUE, lw=2, label="ours: S · P · 1.5 / (0.5 + P)")
ax.axvline(1, color=GREY, lw=0.5)
ax.set_xlabel("unmodified protein P")
ax.set_ylabel("phosphorylation rate / S")
ax.legend(frameon=False)
ax.set_title("A new rate law")
plt.show()

png

Validation. The loader refuses a file that cannot work, and the message names the problem. Three typical mistakes:

mistakes = {
    "a new parameter Km": text.replace("(0.5 + {P})", "({Km} + {P})"),
    "a species that the reaction does not list": text.replace('rate = "{B} * {R}"', 'rate = "{B} * {R} * {P}"'),
    "kinases do not drive the modification": text.replace('modifiers = "site_kinases"', "modifiers = []"),
}
for what, bad_text in mistakes.items():
    bad = WORK / "bad.toml"
    bad.write_text(bad_text, encoding="utf-8")
    try:
        mech.load(bad)
    except mech.MechanismError as exc:
        print(f"{what}:\n   {str(exc).replace(str(WORK), '<work>')}\n")
a new parameter Km:
   <work>/bad.toml: [[reactions]] #5 (phosphorylation): unknown symbol(s) ['Km'] in rate; allowed ['A', 'B', 'C', 'D', 'Dp', 'E', 'P', 'R', 'S', 'X', 'gene', 'prev', 'site', 'synth']

a species that the reaction does not list:
   <work>/bad.toml: [[reactions]] #2 (mrna_decay): the rate uses species ['P'] that the reaction does not list as reactant, product or modifier

kinases do not drive the modification:
   <work>/bad.toml: no reaction of the modification kind 'phosphorylation' with modifiers 'site_kinases' (the kinases' inflow S must drive the modification)

Another modification. The same format describes other PTMs: [ptm] names them, and the reactions get their own kinds. The shipped example is lysine acetylation with saturating deacetylation. Its site data would be acetyl-site fold changes and its "kinases" the acetyltransferases:

acetylation = mech.load(mech.MODELS_DIR / "examples" / "acetylation_mm.toml")
print("PTM:", acetylation.ptm)
pd.DataFrame([{"kind": r.kind, "per": r.per, "rate law": r.rate} for r in acetylation.scope("site")])
PTM: {'name': 'acetylation', 'modification': 'acetylation', 'demodification': 'deacetylation'}
kind per rate law
0 acetylation site {S} * {P}
1 deacetylation site {E} * {X} / (1 + {X})
2 acetyl_decay site ({D} + {Dp}) * {X}

4. A small invented network

Two kinases act on four sites of three proteins, and the transcription factor TFX regulates the genes of the other two proteins. We write the two network files:

kinase_net = pd.DataFrame({"GeneID": ["TFX", "GENEY", "GENEY", "SUBZ"], "Psite": ["S_10", "S_20", "T_35", "Y_5"],
                           "Kinase": ["{KIN1}", "{KIN1, KIN2}", "{KIN2}", "{KIN2}"]})
tf_net = pd.DataFrame({"Source": ["TFX", "TFX"], "Target": ["GENEY", "SUBZ"]})
kinase_net.to_csv(DATA / "kinase_net.csv", index=False)
tf_net.to_csv(DATA / "tf_net.csv", index=False)
display(kinase_net)
tf_net
GeneID Psite Kinase
0 TFX S_10 {KIN1}
1 GENEY S_20 {KIN1, KIN2}
2 GENEY T_35 {KIN2}
3 SUBZ Y_5 {KIN2}
Source Target
0 TFX GENEY
1 TFX SUBZ
positions = {"KIN1": (0, 2), "KIN2": (0, 0), "TFX S_10": (1, 2.6), "GENEY S_20": (1, 1.5), "GENEY T_35": (1, 0.7),
             "SUBZ Y_5": (1, -0.3), "TFX": (2, 2.6), "GENEY": (2, 1.1), "SUBZ": (2, -0.3)}
fig, ax = plt.subplots(figsize=(7.5, 4))
boxes = {}
for name, (x, y) in positions.items():
    color = BLUE if name.startswith("KIN") else GREY if " " in name else ORANGE
    boxes[name] = ax.text(x, y, name, ha="center", va="center", fontsize=9, zorder=3,
                          bbox=dict(boxstyle="round,pad=0.5", fc="white", ec=color, lw=1.5))
fig.canvas.draw()  # the boxes get their size, so the arrows can stop at their edges


def arrow(a, b, color, style="-", bend=0.0):
    ax.annotate("", xy=positions[b], xytext=positions[a],
                arrowprops=dict(arrowstyle="-|>", color=color, ls=style, lw=1.5, patchA=boxes[a].get_bbox_patch(),
                                patchB=boxes[b].get_bbox_patch(), connectionstyle=f"arc3,rad={bend}"))


for _, r in kinase_net.iterrows():
    for k in r["Kinase"].strip("{}").split(","):
        arrow(k.strip(), f"{r.GeneID} {r.Psite}", BLUE)
for gene, site in zip(kinase_net.GeneID, kinase_net.Psite):
    arrow(f"{gene} {site}", gene, GREY, ":")
for _, r in tf_net.iterrows():
    arrow(r.Source, r.Target, ORANGE, bend=-0.5)
ax.set_title("kinases (blue) -> sites -> proteins; TFX regulates two genes (orange)", fontsize=10)
ax.set_xlim(-0.35, 2.9)
ax.set_ylim(-0.8, 3.1)
ax.axis("off")
plt.show()

png

The stimulus. The model is driven from outside by the kinases' measured protein time series (as fold changes). We invent them: after a stimulus at time 0, KIN1 rises quickly and falls again, KIN2 rises slowly and stays high. Times are in minutes.

T_PROTEIN = [0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0, 240.0]
T_RNA = [15.0, 30.0, 60.0, 120.0, 240.0]
t = np.array(T_PROTEIN)
drive = {"KIN1": 1 + 3 * (t / 10) * np.exp(1 - t / 10), "KIN2": 1 + 1.5 * (1 - np.exp(-t / 45))}

fig, ax = plt.subplots(figsize=(6, 3))
for (name, v), color in zip(drive.items(), (BLUE, ORANGE)):
    ax.plot(t, v, "o-", color=color, lw=2, label=name)
ax.set_xscale("symlog", linthresh=1)
ax.set_xlabel("time (min)")
ax.set_ylabel("protein fold change")
ax.legend(frameon=False)
ax.set_title("The invented stimulus: the kinase drives")
plt.show()

png

5. Write config.toml

TOML is a simple format: key = value, grouped in [tables]. The shipped file (configs/config.toml) explains every key in comments. Here is a short one with the keys that matter for us:

config_toml = f"""
[networkmodel]
# --- inputs
kinase_net = "{(DATA / 'kinase_net.csv').as_posix()}"
tf_net     = "{(DATA / 'tf_net.csv').as_posix()}"
ms         = "{(DATA / 'ms.csv').as_posix()}"
rna        = "{(DATA / 'rna.csv').as_posix()}"
kinopt     = ""                      # no KinOpt/TFOpt results: every edge gets weight 1
tfopt      = ""
mechanism  = "saturating_phosphorylation.toml"   # relative to this file's folder

# --- run
output_dir = "{(WORK / 'results').as_posix()}"
cores      = {CORES}
seed       = 1
n_starts   = 6                       # fit 6 times from different start values

# --- how data are compared with the model
scaling_method           = "fc_start"        # each series divided by its first value (fold change)
initial_condition_policy = "data"            # start state built from the data at the first time
observation_model        = "log_fc_gaussian" # likelihood: ln(fold change) with Gaussian noise
parameterisation         = "log"             # the optimiser works on ln(parameter)

# --- prior knowledge
prior_file      = "priors_likelihood.toml"   # relative to this file's folder
ck_prior_centre = "design"                   # without KinOpt: centre the kinase gains on the allowed range
lambda_prior    = 0.1

# --- identifiability (switched on in section 8)
profile_likelihood = false
profile_indices    = ""
profile_restarts   = 2

[networkmodel.models]
default_model = "distributive"       # the family of the mechanism file

[networkmodel.timepoints]            # minutes; the x1, x2, ... columns of the CSVs
protein         = {T_PROTEIN}
phospho_protein = {T_PROTEIN}
rna             = {T_RNA}

[networkmodel.solver]
absolute_tolerance = 1e-8
relative_tolerance = 1e-8
"""
CONF.write_text(config_toml, encoding="utf-8")
(PROJECT / "priors_likelihood.toml").write_bytes(shipped_file("priors_likelihood.toml").read_bytes())
print(config_toml.replace(WORK.as_posix(), "<work>"))
[networkmodel]
# --- inputs
kinase_net = "<work>/project/data/kinase_net.csv"
tf_net     = "<work>/project/data/tf_net.csv"
ms         = "<work>/project/data/ms.csv"
rna        = "<work>/project/data/rna.csv"
kinopt     = ""                      # no KinOpt/TFOpt results: every edge gets weight 1
tfopt      = ""
mechanism  = "saturating_phosphorylation.toml"   # relative to this file's folder

# --- run
output_dir = "<work>/results"
cores      = 4
seed       = 1
n_starts   = 6                       # fit 6 times from different start values

# --- how data are compared with the model
scaling_method           = "fc_start"        # each series divided by its first value (fold change)
initial_condition_policy = "data"            # start state built from the data at the first time
observation_model        = "log_fc_gaussian" # likelihood: ln(fold change) with Gaussian noise
parameterisation         = "log"             # the optimiser works on ln(parameter)

# --- prior knowledge
prior_file      = "priors_likelihood.toml"   # relative to this file's folder
ck_prior_centre = "design"                   # without KinOpt: centre the kinase gains on the allowed range
lambda_prior    = 0.1

# --- identifiability (switched on in section 8)
profile_likelihood = false
profile_indices    = ""
profile_restarts   = 2

[networkmodel.models]
default_model = "distributive"       # the family of the mechanism file

[networkmodel.timepoints]            # minutes; the x1, x2, ... columns of the CSVs
protein         = [0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0, 240.0]
phospho_protein = [0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0, 240.0]
rna             = [15.0, 30.0, 60.0, 120.0, 240.0]

[networkmodel.solver]
absolute_tolerance = 1e-8
relative_tolerance = 1e-8
key why it matters
kinase_net, tf_net, ms, rna the inputs; relative paths are read from the working directory, so we write full paths
mechanism, default_model your reactions; the file's family must equal default_model
[networkmodel.timepoints] must match the data columns; they also set which rate constants the data can resolve
scaling_method fc_start turns each series into a fold change relative to its first time
initial_condition_policy data (from the first observations) or steady_state_all (rest before the stimulus)
observation_model, prior_file the data term and the prior must use the same units: log_fc_gaussian with priors_likelihood.toml, linear_fc_mse with priors_lognormal.toml
n_starts, seed more starts make it more likely to find the best fit; the seed makes the run repeatable
profile_likelihood, profile_indices which parameters get an identifiability check
output_dir one folder per run

A key that is missing takes the default of the code, which is not always the value in the shipped file (for example the model family). So for real work, copy the shipped file and change it:

from phoskintime.networkmodel.example import config_text

shipped = shipped_file("config.toml").read_text(encoding="utf-8")
from_shipped = config_text(shipped, {"mechanism": "saturating_phosphorylation.toml", "n_starts": 6,
                                     "observation_model": "log_fc_gaussian", "prior_file": "priors_likelihood.toml"})
changed = [(a, b) for a, b in zip(shipped.splitlines(), from_shipped.splitlines()) if a != b]
print(f"{len(shipped.splitlines())} lines in the shipped file, {len(changed)} changed:")
pd.DataFrame(changed, columns=["shipped", "mine"])
618 lines in the shipped file, 4 changed:
shipped mine
0 mechanism = "" mechanism = "saturating_phosphorylation.toml"
1 observation_model = "linear_fc_mse" observation_model = "log_fc_gaussian"
2 prior_file = "priors_lognormal.toml" prior_file = "priors_likelihood.toml"
3 n_starts = 20 n_starts = 6

(config_text replaces the first line that starts with each key. You can of course edit the copy in a text editor. The full reference is the Configuration reference.)

6. Build the model, then make synthetic data

We have no measurements, but the loader needs data files to build the network. So we first write a draft with every value 1 ("nothing changes"), except for the kinase drives, which are real inputs of our model.

GENES = ["GENEY", "SUBZ", "TFX"]
SITES = list(zip(kinase_net.GeneID, kinase_net.Psite))


def write_data(protein, phospho, rna):
    """Write ms.csv and rna.csv from {gene: values}, {(gene, site): values} and {gene: values}."""
    def row(gene, site, values):
        return {"GeneID": gene, "Psite": site, **{f"x{i + 1}": v for i, v in enumerate(values)}}

    rows = [row(k, "", v) for k, v in drive.items()]            # kinase protein series: the drives
    rows += [row(g, "", protein[g]) for g in GENES]             # protein observations: Psite empty
    rows += [row(g, s, phospho[g, s]) for g, s in SITES]        # phosphosite observations
    pd.DataFrame(rows).to_csv(DATA / "ms.csv", index=False)
    pd.DataFrame([{"GeneID": g, **{f"x{i + 1}": v for i, v in enumerate(rna[g])}}
                  for g in GENES]).to_csv(DATA / "rna.csv", index=False)


ones, ones_rna = np.ones(len(T_PROTEIN)), np.ones(len(T_RNA))
write_data({g: ones for g in GENES}, {s: ones for s in SITES}, {g: ones_rna for g in GENES})

api.validate_inputs (the command phoskintime validate) reads everything a run would read, without fitting. The two warnings are expected: we gave no KinOpt and TFOpt workbooks.

from phoskintime.networkmodel import api

with quiet():
    report = api.validate_inputs(CONF)
print("ok:", report.ok, "| errors:", report.errors)
for w in report.warnings:
    print("warning:", w.split(". Expected")[0])
pd.DataFrame(report.counts["observations_in_model"], index=["in the files", "in the model"])[["protein", "rna",
                                                                                           "phospho"]]
ok: True | errors: []
warning: kinopt: KinOpt result file not found: ''
warning: tfopt: TFOpt result file not found: ''
protein rna phospho
in the files 50 15 40
in the model 30 15 40

api.problem builds the model and the objective, still without fitting. It tells us every parameter and the bounds PhosKinTime derives from the data and the sampling times:

name meaning
A_i, B_i mRNA synthesis and decay of a gene
C_i, D_i translation and protein decay
E_i dephosphorylation (one rate per protein)
Dp_i extra decay of a phosphorylated site
c_k gain of a kinase: how strongly its protein level phosphorylates
tf_scale strength of transcriptional regulation
sigma[...] the noise level of each data type (estimated too)
from phoskintime.networkmodel import parameterisation as P_
from phoskintime.networkmodel.simulate_sbml import model_of

with quiet():
    draft = api.problem(CONF, work_dir=WORK / "draft")
    states = list(model_of(draft.sys).state_map)  # model_of: the problem's SBML model
print("mechanism:", draft.sys.mechanism.name, "| proteins:", draft.idx.proteins, "| kinases:", draft.idx.kinases)
print("states:", states)
mechanism: saturating_phosphorylation | proteins: ['GENEY', 'SUBZ', 'TFX'] | kinases: ['KIN1', 'KIN2']
states: ['R_GENEY', 'P_GENEY', 'X_GENEY_S_20', 'X_GENEY_T_35', 'R_SUBZ', 'P_SUBZ', 'X_SUBZ_Y_5', 'R_TFX', 'P_TFX', 'X_TFX_S_10']

The truth. We now choose the parameter values that "nature" uses, all in 1/min except tf_scale and the noise levels:

TRUE = {"A_i[TFX]": 0.03, "A_i[GENEY]": 0.03, "A_i[SUBZ]": 0.03,
        "B_i[TFX]": 0.03, "B_i[GENEY]": 0.04, "B_i[SUBZ]": 0.03,
        "C_i[TFX]": 0.04, "C_i[GENEY]": 0.04, "C_i[SUBZ]": 0.04,
        "D_i[TFX]": 0.03, "D_i[GENEY]": 0.04, "D_i[SUBZ]": 0.03,
        "E_i[TFX]": 0.10, "E_i[GENEY]": 0.10, "E_i[SUBZ]": 0.08,
        "c_k[KIN1]": 0.06, "c_k[KIN2]": 0.03, "tf_scale": 4.0,
        "Dp_i[TFX_S_10]": 0.30, "Dp_i[GENEY_S_20]": 0.05, "Dp_i[GENEY_T_35]": 0.02, "Dp_i[SUBZ_Y_5]": 0.04,
        "sigma[protein]": 0.05, "sigma[mrna]": 0.05, "sigma[phospho]": 0.08}


def theta_of(problem, values):
    """The problem's parameter vector for named physical values (the optimiser works on transformed values)."""
    return P_.to_raw_np(np.array([values[n] for n in problem.parameter_names]))


with quiet():
    objective = draft.numpy_objective()
    t_solve, Y = objective.trajectory(theta_of(draft, TRUE))  # simulate the SBML model at the truth
Y = pd.DataFrame(Y, index=t_solve, columns=states)
Y.loc[[0.0, 10.0, 60.0, 240.0]].round(3)
R_GENEY P_GENEY X_GENEY_S_20 X_GENEY_T_35 R_SUBZ P_SUBZ X_SUBZ_Y_5 R_TFX P_TFX X_TFX_S_10
0.0 1.000 0.700 0.150 0.150 1.000 0.700 0.300 1.0 0.700 0.300
10.0 1.192 0.162 0.552 0.120 1.289 0.822 0.236 1.0 0.143 0.236
60.0 1.285 0.228 0.323 0.175 1.627 1.031 0.409 1.0 0.277 0.083
240.0 1.462 0.266 0.369 0.243 1.947 1.324 0.543 1.0 0.364 0.088

The simulation gives amounts of species. A measurement is not a species: a proteomics experiment sees the total of a protein, with or without phosphate, relative to the start. For the distributive family the three observables are:

  • protein = P + all modified forms X,
  • phosphosite = its form X,
  • mRNA = R,

each divided by its value at the first time of its data. Then we add multiplicative noise, as in real fold-change data (the first protein time stays exactly 1, since fc_start divides by it).

def observables(Y):
    """The noise-free fold changes of a simulated trajectory (distributive layout)."""
    fold = lambda series, times: (series.loc[times] / series.loc[times[0]]).to_numpy()
    protein = {g: fold(Y[[c for c in Y if c == f"P_{g}" or c.startswith(f"X_{g}_")]].sum(axis=1), T_PROTEIN)
               for g in GENES}
    phospho = {(g, s): fold(Y[f"X_{g}_{s}"], T_PROTEIN) for g, s in SITES}
    rna = {g: fold(Y[f"R_{g}"], T_RNA) for g in GENES}
    return protein, phospho, rna


rng = np.random.default_rng(12)


def noisy(values, sd):
    factor = np.exp(rng.normal(0.0, sd, len(values)))
    factor[0] = 1.0
    return values * factor


protein, phospho, rna = observables(Y)
protein_obs = {k: noisy(v, TRUE["sigma[protein]"]) for k, v in protein.items()}
phospho_obs = {k: noisy(v, TRUE["sigma[phospho]"]) for k, v in phospho.items()}
rna_obs = {k: noisy(v, TRUE["sigma[mrna]"]) for k, v in rna.items()}
write_data(protein_obs, phospho_obs, rna_obs)

fig, axes = plt.subplots(1, 3, figsize=(12, 3.2))
for ax, (title, clean, seen, times) in zip(axes, [("phosphosites", phospho, phospho_obs, T_PROTEIN),
                                                  ("proteins", protein, protein_obs, T_PROTEIN),
                                                  ("mRNA", rna, rna_obs, T_RNA)]):
    for key, color in zip(clean, (BLUE, ORANGE, AQUA, VIOLET)):
        label = " ".join(key) if isinstance(key, tuple) else key
        ax.plot(times, clean[key], color=color, lw=2, label=label)
        ax.plot(times, seen[key], "o", color=color, ms=4)
    ax.set_title(f"{title}: truth (lines), synthetic data (dots)", fontsize=9)
    ax.set_xscale("symlog", linthresh=1)
    ax.set_xlabel("time (min)")
    ax.legend(frameon=False, fontsize=8)
axes[0].set_ylabel("fold change")
fig.tight_layout()
plt.show()

png

7. Check the problem before fitting

We rebuild the problem with the synthetic data. Two checks: the true values must lie inside the bounds (which depend on the data), and at the truth the residuals must be about as large as the noise we added.

with quiet():
    report = api.validate_inputs(CONF)
    prob = api.problem(CONF, work_dir=WORK / "problem")
theta_true = theta_of(prob, TRUE)
print("inputs ok:", report.ok)
print("truth inside the bounds:", bool(np.all((theta_true >= prob.lower) & (theta_true <= prob.upper))))

with quiet():
    residuals = prob.numpy_objective().residual_table(theta_true)
    at_truth, at_start = prob.terms(theta_true), prob.terms(prob.theta_start)
print({m: f"residual sd {d.residual[d.in_likelihood].std():.3f}" for m, d in residuals.items()})
pd.DataFrame({"at the truth": at_truth, "at the first start value": at_start}).drop(index="breakdown").round(1)
inputs ok: True
truth inside the bounds: True
{'protein': 'residual sd 0.048', 'mrna': 'residual sd 0.038', 'phospho': 'residual sd 0.083'}
at the truth at the first start value
objective -62.4506 26569.502895
data_term -104.373289 26518.173356
prior_term 41.922688 51.329539
pd.DataFrame({"parameter": prob.parameter_names, "lower bound": P_.to_physical_np(prob.lower),
              "upper bound": P_.to_physical_np(prob.upper),
              "truth": [TRUE[n] for n in prob.parameter_names]}).set_index("parameter")
lower bound upper bound truth
parameter
A_i[GENEY] 0.000088 2.012041 0.03
A_i[SUBZ] 0.000088 2.012041 0.03
A_i[TFX] 0.000088 2.012041 0.03
B_i[GENEY] 0.000468 0.153506 0.04
B_i[SUBZ] 0.000468 0.153506 0.03
B_i[TFX] 0.000468 0.153506 0.03
C_i[GENEY] 0.000028 20.155159 0.04
C_i[SUBZ] 0.000028 20.155159 0.04
C_i[TFX] 0.000028 20.155159 0.04
D_i[GENEY] 0.000439 2.302585 0.04
D_i[SUBZ] 0.000439 2.302585 0.03
D_i[TFX] 0.000439 2.302585 0.03
E_i[GENEY] 0.000439 2.302585 0.10
E_i[SUBZ] 0.000439 2.302585 0.08
E_i[TFX] 0.000439 2.302585 0.10
c_k[KIN1] 0.000439 5.000000 0.06
c_k[KIN2] 0.000439 5.000000 0.03
tf_scale 0.500000 5.000000 4.00
Dp_i[GENEY_S_20] 0.000439 2.302585 0.05
Dp_i[GENEY_T_35] 0.000439 2.302585 0.02
Dp_i[SUBZ_Y_5] 0.000439 2.302585 0.04
Dp_i[TFX_S_10] 0.000439 2.302585 0.30
sigma[protein] 0.000674 14.841316 0.05
sigma[mrna] 0.000674 14.841316 0.05
sigma[phospho] 0.000674 14.841316 0.08

The objective is a negative log likelihood plus a negative log prior: smaller is better, and it can be negative. At the first start value it is huge; at the truth it is low.

8. Fit, with identifiability checks

A fit always returns a number for every parameter. Whether the data actually determine that number is a separate question. A profile likelihood answers it: fix one parameter at a range of values, re-fit all others each time, and see how fast the fit gets worse. Profiles cost many fits, so we choose four parameters of interest:

PROFILED = ["c_k[KIN1]", "E_i[TFX]", "Dp_i[SUBZ_Y_5]", "tf_scale"]
indices = ",".join(str(prob.parameter_names.index(p)) for p in PROFILED)
CONF.write_text(config_text(CONF.read_text(encoding="utf-8"),
                            {"profile_likelihood": True, "profile_indices": indices}), encoding="utf-8")
print("profile_indices =", indices)
profile_indices = 15,14,20,17

api.run runs the fit exactly as the command phoskintime run --conf config.toml does, in its own process. The fit itself takes seconds; the profiles take a minute or two.

t0 = time.time()
RUN = api.run(CONF, log=WORK / "run.log")
print(f"run finished in {time.time() - t0:.0f} s; run folder <work>/{RUN.name}")
run finished in 172 s; run folder <work>/results

9. Read the results

Did the starts agree? Each row is one fit from its own start values. The best accepted one is selected. If only one start reaches the best objective, use more starts. A start marked failed did not report convergence and is not used.

results = api.read_results(RUN)
results["multistart"][["start", "objective", "convergence_status", "selected"]]
start objective convergence_status selected
0 0 -90.492261 converged False
1 1 -90.490988 converged False
2 2 -90.494746 converged False
3 3 -90.491431 converged False
4 4 -90.494794 converged False
5 5 -90.495005 converged True

Does the model follow the data? We load the fitted SBML model (<run>/model/model.xml) with phoskintime.networkmodel.sim and simulate it on a fine time grid. For comparison we make a second copy of the model that carries the true parameters.

import libsbml

from phoskintime.networkmodel import sim

fitted = sim.load(RUN)
status = pd.read_csv(RUN / "parameter_status.csv").set_index("parameter")


def sbml_name(parameter):
    """The SBML id of a PhosKinTime parameter name: "c_k[KIN1]" -> "ck_KIN1", "A_i[TFX]" -> "A_TFX"."""
    if parameter == "tf_scale":
        return parameter
    group, entity = parameter.rstrip("]").split("[")
    return {"c_k": "ck", "Dp_i": "Dp"}.get(group, group[0]) + "_" + entity


doc = libsbml.readSBMLFromString(fitted.sbml)
for name, value in TRUE.items():
    if not name.startswith("sigma"):
        doc.getModel().getParameter(sbml_name(name)).setValue(value)
truth = sim.FittedModel.from_sbml(libsbml.writeSBMLToString(doc), "truth")

DENSE = tuple(np.unique(np.concatenate([np.linspace(0, 240, 241), T_PROTEIN, T_RNA])))


def run_experiment(model, experiment):
    """{scenario: DataFrame(time x variable) of amounts} of an experiment."""
    tr = sim.simulate(model, experiment).trajectories
    return {s: d.pivot(index="time", columns="variable", values="value") for s, d in tr.groupby("scenario", sort=False)}


baseline = sim.Experiment("sustained", times=DENSE)
fit_Y = run_experiment(fitted, baseline)["sustained"]
true_Y = run_experiment(truth, baseline)["sustained"]


def fold_change(Y, kind, key):
    if kind == "phosphosite":
        series, base = Y[f"X_{key[0]}_{key[1]}"], 0.0
    elif kind == "protein":
        series, base = Y[f"Ptotal_{key}"], 0.0
    else:
        series, base = Y[f"R_{key}"], T_RNA[0]
    series = series / series.loc[base]
    return series[series.index >= base]


panels = ([("phosphosite", k, phospho_obs[k], T_PROTEIN) for k in SITES]
          + [("protein", g, protein_obs[g], T_PROTEIN) for g in GENES]
          + [("mRNA", g, rna_obs[g], T_RNA) for g in GENES])
fig, axes = plt.subplots(2, 5, figsize=(14, 5.6), sharex=True)
for ax, (kind, key, seen, times) in zip(axes.flat, panels):
    ax.plot(times, seen, "o", color=GREY, ms=4, label="synthetic data")
    ax.plot(fold_change(true_Y, kind, key), color=ORANGE, ls="--", lw=2, label="truth")
    ax.plot(fold_change(fit_Y, kind, key), color=BLUE, lw=2, label="fitted model")
    ax.set_title(f"{kind} {' '.join(key) if isinstance(key, tuple) else key}", fontsize=9)
    ax.set_xscale("symlog", linthresh=1)
for ax in axes[1]:
    ax.set_xlabel("time (min)")
axes[0, 0].legend(frameon=False, fontsize=8)
axes[0, 0].set_ylabel("fold change")
axes[1, 0].set_ylabel("fold change")
fig.tight_layout()
plt.show()

png

A quick consistency check: the exported SBML model, simulated outside the fit, reproduces the model values the run wrote to model_trajectories.csv.

written = pd.read_csv(RUN / "model_trajectories.csv")
kinds = {"Phosphorylation": "phosphosite", "Protein": "protein", "RNA": "mRNA"}
difference = max(
    abs(fold_change(fit_Y, kinds[r.type], (r.protein, r.psite) if r.type == "Phosphorylation" else r.protein)
        .loc[r.time] - r.fc_pred)
    for r in written.itertuples())
print(f"largest difference over {len(written)} points: {difference:.1e}")
largest difference over 85 points: 2.5e-07
metrics = results["metrics"]
metrics[metrics.protein.isna() & metrics.metric.isin(["rmse", "n_obs"])].fillna({"layer": "all"}).pivot(
    index="layer", columns="metric", values="value").round(4)
metric n_obs rmse
layer
all 85.0 0.0528
phospho 40.0 0.0712
protein 30.0 0.0296
rna 15.0 0.0228

Which numbers may you believe? parameter_status.csv gives every parameter a label:

label meaning
estimate (two-sided) the profile rises on both sides: the data give a value with an interval
upper limit only / lower limit only the data exclude large (or small) values only
not identifiable (flat) the data say nothing about it
not assessed no profile was computed; do not quote the value as a result
at ... bound, below/above resolvable rate the fit ran into a limit
table = status.loc[:, ["value", "profile_lower", "profile_upper", "label"]].copy()
table.insert(0, "truth", [TRUE[n] for n in table.index])
table.loc[PROFILED]
truth value profile_lower profile_upper label
parameter
c_k[KIN1] 0.06 0.063184 0.055113 0.074594 estimate (two-sided)
E_i[TFX] 0.10 0.121073 0.078750 0.228820 estimate (two-sided)
Dp_i[SUBZ_Y_5] 0.04 0.105460 0.000439 0.155948 upper limit only
tf_scale 4.00 4.999070 1.251545 5.000000 at optimizer bound (upper; not a design bound)
import json

points = pd.read_csv(RUN / "profiles" / "profile_likelihood_summary.csv")
reference = json.loads((RUN / "profiles" / "profile_reference.json").read_text())
fig, axes = plt.subplots(1, len(PROFILED), figsize=(14, 3.2), sharey=True)
for ax, name in zip(axes, PROFILED):
    d = points[(points.parameter_name == name) & np.isfinite(points.objective_value)]
    x = np.append(d.grid_value_physical, status.loc[name, "value_data_only"])
    y = np.append(d.objective_value - reference["f_ref"], 0.0)
    order = np.argsort(x)
    ax.plot(x[order], y[order], "o-", color=BLUE, ms=3, lw=1.5, label="profile")
    ax.axhline(reference["threshold"], color=GREY, ls=":", label="95 % threshold")
    ax.axvline(TRUE[name], color=ORANGE, ls="--", label="truth")
    ax.set_xscale("log")
    ax.set_ylim(-0.1, 3 * reference["threshold"])
    ax.set_title(f"{name}\n{status.loc[name, 'label']}", fontsize=9)
    ax.set_xlabel("parameter value")
axes[0].set_ylabel("loss of fit (data only)")
axes[0].legend(frameon=False, fontsize=8)
fig.tight_layout()
plt.show()

png

How to read a panel: parameter values whose curve stays below the dotted line are compatible with the data. A curve that crosses the line on both sides of its minimum gives a two-sided interval; a curve that stays below the line up to the edge of the allowed range leaves that side open. In our run the two kinase-related parameters come out two-sided, the extra decay of phospho-SUBZ only has an upper limit, and the best tf_scale sits at the upper end of its allowed range: the data exclude small values, but do not say how large it is. Compare each with the dashed truth.

Recovery against the truth. For all parameters, fitted value divided by true value (1 is perfect):

ratio = pd.Series({n: status.loc[n, "value"] / TRUE[n] for n in status.index})
fig, ax = plt.subplots(figsize=(7, 6.5))
y = np.arange(len(ratio))
is_profiled = ratio.index.isin(PROFILED)
ax.axvline(1, color=GREY, lw=1)
ax.plot(ratio[~is_profiled], y[~is_profiled], "o", color=GREY, label="not profiled")
ax.plot(ratio[is_profiled], y[is_profiled], "D", color=BLUE, label="profiled")
for name in PROFILED:
    lo, hi = status.loc[name, ["profile_lower", "profile_upper"]].astype(float) / TRUE[name]
    ax.plot([lo, hi], [list(ratio.index).index(name)] * 2, color=BLUE, lw=2, alpha=0.5)
ax.set_yticks(y, ratio.index, fontsize=8)
ax.invert_yaxis()
ax.set_xscale("log")
ax.set_xlim(0.02, 30)
ax.set_xlabel("fitted / true (lines: profile interval / true)")
ax.legend(frameon=False)
ax.set_title("Recovery of the known parameters")
plt.show()

png

The lesson of this figure: a good fit does not mean good parameters. The curves above follow the data closely, yet several rates are off by a factor of two or more: other parameters compensate. The noise levels sigma come out below the truth, because a fit with many parameters absorbs part of the noise. Only the profiled parameters come with a statement of how far the data pin them down. To learn more about the others you would need more informative data (more time points, perturbations, several conditions) or more prior knowledge.

10. The SBML ecosystem on your model

The run wrote model/model.xml, an SBML file. From here on you are not tied to PhosKinTime: every tool below reads that file.

10.1 Inspect it: libSBML and sbmlutils

libSBML is the reference library to read SBML; sbmlutils builds and reports on SBML models (PhosKinTime writes its models with it).

from sbmlutils.report.sbmlinfo import SBMLDocumentInfo

from phoskintime.networkmodel.exchange.sbml_model import validate_sbml

XML = RUN / "model" / "model.xml"
with quiet():
    check = validate_sbml(XML)  # libSBML's consistency checks, every category, units included
    info = SBMLDocumentInfo.from_sbml(XML).info["model"]
print("SBML errors:", check["errors"], "| warnings:", check["warnings"])
pd.Series({k: len(info[k]) for k in ("compartments", "species", "parameters", "assignmentRules", "reactions",
                                     "unitDefinitions")}, name="number in the model").to_frame()
SBML errors: 0 | warnings: 0
number in the model
compartments 1
species 12
parameters 40
assignmentRules 20
reactions 24
unitDefinitions 2
model = libsbml.readSBMLFromFile(str(XML)).getModel()
pd.DataFrame([{
    "reaction": r.getId(),
    "from": " + ".join(s.getSpecies() for s in r.getListOfReactants()),
    "to": " + ".join(s.getSpecies() for s in r.getListOfProducts()),
    "modifiers": ", ".join(s.getSpecies() for s in r.getListOfModifiers()),
    "rate law": libsbml.formulaToL3String(r.getKineticLaw().getMath()).replace(" dimensionless", ""),
    "SBO": r.getSBOTermID(),
} for r in model.getListOfReactions() if "TFX" in r.getId()])
reaction from to modifiers rate law SBO
0 rx_transcription_TFX R_TFX synth_TFX SBO:0000183
1 rx_mrna_decay_TFX R_TFX B_TFX * R_TFX SBO:0000179
2 rx_translation_TFX P_TFX R_TFX C_TFX * R_TFX SBO:0000184
3 rx_protein_decay_TFX P_TFX D_TFX * P_TFX SBO:0000179
4 rx_phosphorylation_TFX_S_10 P_TFX X_TFX_S_10 K_KIN1 S_TFX_S_10 * P_TFX * 1.5 / (0.5 + P_TFX) SBO:0000216
5 rx_dephosphorylation_TFX_S_10 X_TFX_S_10 P_TFX E_TFX * X_TFX_S_10 SBO:0000330
6 rx_phospho_decay_TFX_S_10 X_TFX_S_10 (D_TFX + Dp_TFX_S_10) * X_TFX_S_10 SBO:0000179

Our saturating rate law is in the model, for every site.

10.2 The equations: sbmlode

sbmlode turns any SBML model into its differential equations (Markdown, LaTeX, Python, Julia, R and more). Here are the rates and equations of TFX, cut out of the Markdown document:

from sbmlode import OdeSystem

equations = OdeSystem.from_sbml(str(XML)).render("markdown")
(WORK / "equations.md").write_text(equations, encoding="utf-8")
lines = [l.replace(r"\\[1ex]", "").rstrip(" \\") for l in equations.splitlines()
         if "TFX" in l and (l.startswith(r"v_{") or l.startswith(r"\frac{\mathrm{d}"))]
lines = list(dict.fromkeys(lines))
display(Markdown("$$\n\\begin{aligned}\n" + " \\\\[1ex]\n".join(lines) + "\n\\end{aligned}\n$$"))
\[ \begin{aligned} v_{\mathrm{rx\_transcription\_TFX}} &= \mathrm{synth}_{\mathrm{TFX}} \\[1ex] v_{\mathrm{rx\_mrna\_decay\_TFX}} &= B_{\mathrm{TFX}} \cdot R_{\mathrm{TFX}} \\[1ex] v_{\mathrm{rx\_translation\_TFX}} &= C_{\mathrm{TFX}} \cdot R_{\mathrm{TFX}} \\[1ex] v_{\mathrm{rx\_protein\_decay\_TFX}} &= D_{\mathrm{TFX}} \cdot P_{\mathrm{TFX}} \\[1ex] v_{\mathrm{rx\_phosphorylation\_TFX\_S\_10}} &= \frac{S_{\mathrm{TFX\_S\_10}} \cdot P_{\mathrm{TFX}} \cdot 1.5}{0.5 + P_{\mathrm{TFX}}} \\[1ex] v_{\mathrm{rx\_dephosphorylation\_TFX\_S\_10}} &= E_{\mathrm{TFX}} \cdot X_{\mathrm{TFX\_S\_10}} \\[1ex] v_{\mathrm{rx\_phospho\_decay\_TFX\_S\_10}} &= \mathopen{}\left(D_{\mathrm{TFX}} + \mathrm{Dp}_{\mathrm{TFX\_S\_10}}\right) \cdot X_{\mathrm{TFX\_S\_10}} \\[1ex] \frac{\mathrm{d} R_{\mathrm{TFX}}}{\mathrm{d} t} &= v_{\mathrm{rx\_transcription\_TFX}} - v_{\mathrm{rx\_mrna\_decay\_TFX}} \\[1ex] \frac{\mathrm{d} P_{\mathrm{TFX}}}{\mathrm{d} t} &= v_{\mathrm{rx\_translation\_TFX}} - v_{\mathrm{rx\_protein\_decay\_TFX}} - v_{\mathrm{rx\_phosphorylation\_TFX\_S\_10}} + v_{\mathrm{rx\_dephosphorylation\_TFX\_S\_10}} \\[1ex] \frac{\mathrm{d} X_{\mathrm{TFX\_S\_10}}}{\mathrm{d} t} &= v_{\mathrm{rx\_phosphorylation\_TFX\_S\_10}} - v_{\mathrm{rx\_dephosphorylation\_TFX\_S\_10}} - v_{\mathrm{rx\_phospho\_decay\_TFX\_S\_10}} \end{aligned} \]

10.3 Simulate: libroadrunner and sbmlsim

libroadrunner is a fast SBML simulator. Three lines are enough:

import roadrunner

rr = roadrunner.RoadRunner(str(XML))
rr.integrator.relative_tolerance = 1e-10
rr.integrator.absolute_tolerance = 1e-12
out = rr.simulate(0, 240, 241, ["time", "X_TFX_S_10", "P_TFX", "R_GENEY"])

fig, ax = plt.subplots(figsize=(7, 3.2))
for k, (name, color) in enumerate([("X_TFX_S_10", BLUE), ("P_TFX", ORANGE), ("R_GENEY", AQUA)], start=1):
    ax.plot(out[:, 0], out[:, k], color=color, lw=2, label=name)
ax.set_xlabel("time (min)")
ax.set_ylabel("amount")
ax.legend(frameon=False)
ax.set_title("libroadrunner: the fitted model")
plt.show()

png

sbmlsim describes simulations as objects: how long, which parameter changes, and when. Here an inhibitor of KIN1 (its gain set to zero) is added at 10 minutes and washed out at 60:

from sbmlsim.simulation import Change, Dimension, Scan, Simulation
from sbmlsim.simulation.observables import Formula
from sbmlsim.simulator import Simulator

simulator = Simulator()
simulator.set_integrator_settings(relative_tolerance=1e-10, absolute_tolerance=1e-12)
ck1, ck2 = fitted.parameters["ck_KIN1"], fitted.parameters["ck_KIN2"]
grid = [float(x) for x in np.linspace(0, 240, 481)]
washout = Simulation(end=240.0, times=grid, changes=[Change(10.0, {"ck_KIN1": 0.0}), Change(60.0, {"ck_KIN1": ck1})])

fig, ax = plt.subplots(figsize=(7, 3.2))
for label, simulation, color in [("no inhibitor", Simulation(end=240.0, times=grid), GREY),
                                 ("inhibitor from 10 to 60 min", washout, BLUE)]:
    res = simulator.simulate(XML, simulation)
    values = pd.DataFrame(np.asarray(res.values, dtype=float), columns=list(res.columns))
    ax.plot(values["time"], values["X_TFX_S_10"], color=color, lw=2, label=label)
ax.axvspan(10, 60, color=GREY, alpha=0.12)
ax.set_xlabel("time (min)")
ax.set_ylabel("X_TFX_S_10")
ax.legend(frameon=False)
ax.set_title("sbmlsim: a timed intervention")
plt.show()

png

10.4 Parameter scans in one and two dimensions

A scan repeats a simulation while parameters change. sbmlsim does this with Dimensions. First one dimension: the gain of KIN1 from zero to twice the fitted value.

factors = np.linspace(0.0, 2.0, 21)
observed = [Formula(id="tfx_site", formula="X_TFX_S_10"), Formula(id="geney_mrna", formula="R_GENEY")]
times = [float(x) for x in np.linspace(0, 240, 121)]
scan1 = simulator.run(XML, Scan(Simulation(end=240.0, times=times),
                                (Dimension("kin1", values={"ck_KIN1": ck1 * factors}),)), observed)

fig, axes = plt.subplots(1, 2, figsize=(10, 3.4))
colors = plt.cm.Blues(np.linspace(0.3, 1.0, len(factors)))
for i, color in enumerate(colors):
    axes[0].plot(times, scan1["tfx_site"].values[i], color=color, lw=1)
axes[0].set_title("phospho-TFX over time; darker = more KIN1 gain", fontsize=9)
axes[0].set_xlabel("time (min)")
axes[0].set_ylabel("X_TFX_S_10")
final = scan1["geney_mrna"].values[:, -1]
axes[1].plot(factors, final, "o-", color=BLUE, lw=2)
axes[1].axvline(1, color=GREY, ls=":")
axes[1].set_title("GENEY mRNA at 240 min", fontsize=9)
axes[1].set_xlabel("KIN1 gain / fitted gain")
axes[1].set_ylabel("R_GENEY")
fig.tight_layout()
plt.show()

png

Two dimensions give a map. Here both kinase gains are varied together (21 × 21 = 441 simulations):

scan2 = simulator.run(XML, Scan(Simulation(end=240.0, times=times),
                                (Dimension("kin1", values={"ck_KIN1": ck1 * factors}),
                                 Dimension("kin2", values={"ck_KIN2": ck2 * factors}))),
                      [Formula(id="geney_mrna", formula="R_GENEY"), Formula(id="geney_site", formula="X_GENEY_S_20")])

fig, axes = plt.subplots(1, 2, figsize=(10.5, 4))
maps = [("GENEY mRNA at 240 min", scan2["geney_mrna"].values[:, :, -1]),
        ("largest GENEY S_20 form (0-240 min)", scan2["geney_site"].values.max(axis=2))]
for ax, (title, z) in zip(axes, maps):
    im = ax.pcolormesh(factors, factors, z.T, cmap="Blues", shading="nearest")
    ax.plot(1, 1, "o", color=ORANGE, ms=7)
    ax.set_title(title, fontsize=9)
    ax.set_xlabel("KIN1 gain / fitted")
    ax.set_ylabel("KIN2 gain / fitted")
    fig.colorbar(im, ax=ax, label="amount")
fig.tight_layout()
plt.show()

png

(The orange dot is the fitted model.)

10.5 In-silico experiments: phoskintime.networkmodel.sim

PhosKinTime names the common biological interventions, so you do not have to know parameter ids: inhibit and knockout of a kinase, knockdown of a gene, remove_edge, pulse (the stimulus is withdrawn) and dose responses. See In-silico experiments.

Because we know the truth, we can do what is impossible with real data: ask whether the fitted model predicts experiments it has never seen.

experiments = [
    sim.Experiment("knockout KIN1", (sim.Perturbation("knockout", "KIN1"),), DENSE),
    sim.Experiment("inhibit KIN2 80 %", (sim.Perturbation("inhibit", "KIN2", fraction=0.8),), DENSE),
    sim.Experiment("knockdown TFX 70 %", (sim.Perturbation("knockdown", "TFX", fraction=0.7),), DENSE),
    sim.Experiment("remove KIN1 -> GENEY S_20", (sim.Perturbation("remove_edge", kinase="KIN1", site="GENEY_S_20"),),
                   DENSE),
    sim.Experiment("stimulus KIN2 withdrawn at 30 min", (sim.Perturbation("pulse", "KIN2", t_off=30.0, tau=15.0),),
                   DENSE),
]
shown = ["X_TFX_S_10", "X_GENEY_S_20", "X_SUBZ_Y_5", "R_GENEY"]
fig, axes = plt.subplots(len(experiments), len(shown), figsize=(13, 11), sharex=True)
for row, experiment in zip(axes, experiments):
    predicted = run_experiment(fitted, experiment)[experiment.name]
    real = run_experiment(truth, experiment)[experiment.name]
    for ax, variable in zip(row, shown):
        ax.plot(fit_Y[variable], color=GREY, lw=1, label="fitted, unperturbed")
        ax.plot(real[variable], color=ORANGE, ls="--", lw=2, label="truth, perturbed")
        ax.plot(predicted[variable], color=BLUE, lw=2, label="fitted, perturbed")
        ax.set_title(variable, fontsize=9)
    row[0].set_ylabel(experiment.name.replace(" -> ", "\n-> ").replace(" withdrawn", "\nwithdrawn"), fontsize=8)
for ax in axes[-1]:
    ax.set_xlabel("time (min)")
axes[0, 0].legend(frameon=False, fontsize=7)
fig.tight_layout()
plt.show()

png

Compare the dashed (truth) and blue (prediction) lines. Where they differ, the training data did not contain the information needed for that prediction. With real data you cannot see the dashed line, so treat predictions as hypotheses to test.

A dose response is one preset. api.simulate also writes an experiment bundle: the specification, the model and the results, with checksums.

with quiet():
    dose = api.simulate(fitted, preset="dose_response", target="KIN1", times=T_PROTEIN,
                        out=WORK / "dose_KIN1.pke.zip")
tr = dose.trajectories
tr = tr[(tr.time == T_PROTEIN[-1]) & tr.variable.isin(["X_TFX_S_10", "X_GENEY_S_20", "R_GENEY"])].copy()
tr["inhibition"] = tr.scenario.str.extract(r"\[(.+)\]", expand=False).astype(float)
final = tr.pivot(index="inhibition", columns="variable", values="fold_change")

fig, ax = plt.subplots(figsize=(6, 3.4))
for name, color in zip(final.columns, (BLUE, ORANGE, AQUA)):
    ax.plot(100 * final.index, final[name], "o-", color=color, lw=2, label=name)
ax.set_xlabel("KIN1 inhibition (%)")
ax.set_ylabel("fold change at 240 min")
ax.legend(frameon=False, fontsize=8)
ax.set_title("Dose response of an inhibitor of KIN1")
plt.show()

png

10.6 Global sensitivity

Which parameters matter for an output? The Morris method changes all rate parameters over a range (here ±50 %) and measures the average effect of each (mu_star; larger means more influential). PhosKinTime runs it with sbmlsim's sensitivity tools:

from phoskintime.networkmodel.exchange.experiments import global_sensitivity
from phoskintime.networkmodel.exchange.standards import kinetic_parameters

with quiet():
    sensitivity, design = global_sensitivity(XML, kinetic_parameters(XML), T_PROTEIN, method="morris", n=20,
                                             observables=["X_GENEY_S_20", "R_GENEY", "R_SUBZ"], seed=1)
effect = sensitivity[sensitivity["index"] == "mu_star"].groupby(["observable", "parameter"]).value.max()

fig, axes = plt.subplots(1, 3, figsize=(12, 3.4))
for ax, name in zip(axes, ["X_GENEY_S_20", "R_GENEY", "R_SUBZ"]):
    top = effect[name].sort_values().tail(8)
    ax.barh(top.index, top.values, color=BLUE, height=0.6)
    ax.set_title(name, fontsize=10)
    ax.set_xlabel("largest mu_star over time")
fig.tight_layout()
plt.show()

png

10.7 Standards archive, PEtab, SBGN, CellML

To give your model to someone else, export the run as a COMBINE archive (.omex, the command is phoskintime export standards --run <run> --out <folder>). It holds the SBML model, its equations, SBGN diagrams, a CellML version, sbmlsim simulations and the fitting problem in PEtab, and checks all of them:

from phoskintime.networkmodel.exchange import standards

with quiet():
    archive = standards.export(RUN, WORK / "standards", sensitivity="none")
print("archive:", Path(archive["archive"]).name, "| all checks passed:", archive["ok"])
pd.Series({name: c.get("ok") for name, c in archive["checks"].items()}, name="passed").to_frame()
archive: phoskintime_model.omex | all checks passed: True
passed
sbml True
annotations True
sbgn True
cellml True
omex True
experiments_from_archive True
petab_from_archive True
import zipfile

with zipfile.ZipFile(archive["archive"]) as zf:
    for name in sorted(zf.namelist()):
        print(name)
README.md
cellml/model.cellml
cellml/model.rdf
diagrams/model_af.sbgn
diagrams/model_pd.sbgn
equations.md
experiments/d5_A_GENEY.json
experiments/d5_A_SUBZ.json
experiments/d5_A_TFX.json
experiments/d5_ck_KIN1.json
experiments/d5_ck_KIN2.json
experiments/timecourse.json
manifest.xml
model.xml
petab/measurements.tsv
petab/model.xml
petab/observables.tsv
petab/parameters.tsv
petab/problem.yaml

PEtab describes a parameter estimation problem as tables, so that other fitting tools can read it. Here are the first rows of its parameter and measurement tables:

petab_dir = WORK / "standards" / "phoskintime_model" / "petab"
display(pd.read_csv(petab_dir / "parameters.tsv", sep="\t").head())
pd.read_csv(petab_dir / "measurements.tsv", sep="\t").head()
parameterId parameterName lowerBound upperBound estimate priorDistribution priorParameters nominalValue
0 A_GENEY A_i[GENEY] 0.000088 2.012041 True log-normal -4.317969103074447;2.508559311526579 0.013944
1 A_SUBZ A_i[SUBZ] 0.000088 2.012041 True log-normal -4.317969103074447;2.508559311526579 0.020804
2 A_TFX A_i[TFX] 0.000088 2.012041 True log-normal -4.317969103074447;2.508559311526579 0.022328
3 B_GENEY B_i[GENEY] 0.000468 0.153506 True log-normal -4.77024274268556;1.4481124934156528 0.020996
4 B_SUBZ B_i[SUBZ] 0.000468 0.153506 True log-normal -4.77024274268556;1.4481124934156528 0.025101
experimentId observableId time measurement
0 NaN obs_protein_GENEY 1.0 1.041906
1 NaN obs_protein_SUBZ 1.0 1.024236
2 NaN obs_protein_TFX 1.0 0.913428
3 NaN obs_protein_GENEY 2.0 1.012491
4 NaN obs_protein_SUBZ 2.0 0.909265

The simulations in the archive run with sbmlsim alone, without PhosKinTime:

from sbmlsim.simulation import Simulation

root = WORK / "standards" / "phoskintime_model"
saved = Simulation.from_dict(json.loads((root / "experiments" / "timecourse.json").read_text()))
again = simulator.simulate(root / "model.xml", saved)
print(f"{len(again.columns)} columns, {np.asarray(again.values).shape[0]} time points")
90 columns, 207 time points

SBGN is the standard notation for biological network diagrams. The archive holds an Activity Flow map (who influences whom) and a Process Description map (every reaction). Dedicated editors draw them; here we read the Activity Flow file with libsbgnpy and draw its boxes and arrows from the coordinates in the file:

from libsbgnpy import read_sbgn_from_file

sbgn = read_sbgn_from_file(root / "diagrams" / "model_af.sbgn")
maps = sbgn.map if isinstance(sbgn.map, list) else [sbgn.map]
glyphs = {g.id: g for g in maps[0].glyph}

fig, ax = plt.subplots(figsize=(11, 7))
patches = {}
for key, g in glyphs.items():
    b = g.bbox
    patches[key] = ax.add_patch(plt.Rectangle((b.x, b.y), b.w, b.h, fc="white", ec=GREY, zorder=3))
    unit = next((u.label.text for u in g.glyph if u.label), "")
    ax.text(b.x + b.w / 2, b.y + b.h / 2, f"{g.label.text}\n{unit}", ha="center", va="center", fontsize=8, zorder=4)
ax.autoscale_view()
ax.margins(0.08)
ax.invert_yaxis()
ax.axis("off")
fig.canvas.draw()
centre = lambda g: (g.bbox.x + g.bbox.w / 2, g.bbox.y + g.bbox.h / 2)
for arc in maps[0].arc:
    color = ORANGE if "negative" in arc.class_value.value else BLUE
    ax.annotate("", xy=centre(glyphs[arc.target]), xytext=centre(glyphs[arc.source]),
                arrowprops=dict(arrowstyle="-|>", color=color, lw=1.2, patchA=patches[arc.source],
                                patchB=patches[arc.target], connectionstyle="arc3,rad=0.25"))
ax.set_title("SBGN Activity Flow map of the model")
plt.show()

png

11. Save and share

Everything of this tutorial is in a temporary folder. For your own project use a permanent folder, and keep:

keep why
the project folder: config.toml, mechanism file, priors file, input CSVs enough to rebuild and rerun
the run folder all results, and the exact settings used (config_resolved.yaml, metadata.json)
the run bundle results.pkt.zip one file with results, provenance and checksums; PhosKinTime-Vis reads it
the COMBINE archive .omex the model for other SBML tools

The run wrote the bundle already; check it before you send it:

bundle = api.bundle_path(RUN)
if bundle.is_file():
    checked = api.check_bundle(bundle)
    print(bundle.name, "| valid:", checked.ok, "| errors:", checked.errors)
else:
    print("no run bundle: a bundle records the git commit of the code, see the run log")
sorted(p.name for p in WORK.iterdir())
results.pkt.zip | valid: True | errors: []
['bad.toml',
 'dose_KIN1.pke.zip',
 'draft',
 'equations.md',
 'problem',
 'project',
 'results',
 'run.log',
 'standards']

Before sharing: bundles and PEtab folders contain your measurements (here invented ones). Export with --no-petab for a model without data, and share unpublished data only when you may.

The same steps on the command line:

phoskintime validate --conf project/config.toml
phoskintime run --conf project/config.toml
phoskintime simulate run --model results --preset knockout --target KIN1 --out ko.pke.zip
phoskintime export standards --run results --out standards
phoskintime bundle inspect results/results.pkt.zip

(In a clone, write pixi run phoskintime ....)

Your turn

  1. Change the rate law (for example a Hill law {S} * {P} * {P} / (0.25 + {P} * {P})), load it, and run again in a new kernel. Compare the objectives of the two mechanisms on the same data.
  2. Add a site or a kinase to the network.
  3. Remove time points from the data and watch the profile labels change.
  4. Start from models/combinatorial.toml for a protein with two sites (set default_model to its family).

Where to learn more

topic link
PhosKinTime for beginners Learn
mechanism files, all rules Mechanism files
the model's equations Global network model
every config key Configuration reference
SBML sbml.org, libSBML
building and describing models sbmlutils, sbmlode
simulating libroadrunner, sbmlsim
fitting problems PEtab
diagrams and archives SBGN, COMBINE archive, CellML
published models BioModels

Summary

  • A model is built from a config file, a mechanism file, two networks and the data.
  • A new rate law is a copy of a mechanism file with one line changed; the loader checks it.
  • Synthetic data from known parameters test the whole workflow without measurements, and show what a fit can recover.
  • A close fit is not enough: read the identifiability labels.
  • The result is a standard SBML model: libSBML, sbmlutils, sbmlode, libroadrunner, sbmlsim, PEtab, SBGN, CellML and COMBINE all work with it.

Next

This is the last tutorial. Back to 00. Overview, or continue with the Learn pages and the Library reference.