06. Simulation, observables and the objective
Download the notebook (executed for this page) · source
What this tutorial shows. How one value of the objective is computed: the kinase drive, one simulation of the
run's SBML model in libroadrunner, the fold-change observables against the baseline time, the data term per
modality, the prior term, and the alternative data term of observation_model = "log_fc_gaussian" (a Gaussian
likelihood of the log fold changes, in nats). Everything comes from api.problem, the problem a run fits
(phoskintime.networkmodel.problem.Problem), so the numbers are those the fit sees at its first start.
Place in the series. Tutorial 01 built the SBML model from its mechanism file, 04 the network weights and 05 the parameter vector θ with its bounds and prior. This tutorial evaluates the objective at a start; tutorial 07 minimises it.
Data. The synthetic example (phoskintime.networkmodel.example), written to a temporary folder. The curves and weights are
invented.
Contrast with KinOpt and TFOpt
KinOpt and TFOpt predict each time point algebraically from the input series at the same time point: no state, no solve (KinOpt 05, TFOpt 05). PhosKinTime's prediction at time t is the state of an ODE system integrated from t = 0, so a parameter acts on every later time point, and on the other layers through the coupling (mRNA → protein → phosphosites).
# 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 logging
import os
import sys
import tempfile
from pathlib import Path
REPO_ROOT = Path.cwd().resolve()
while not ((REPO_ROOT / "configs" / "config.toml").is_file() and (REPO_ROOT / "phoskintime").is_dir()):
if REPO_ROOT.parent == REPO_ROOT:
raise RuntimeError("Start this notebook inside the PhosKinTime repository.")
REPO_ROOT = REPO_ROOT.parent
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
os.chdir(REPO_ROOT)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
pd.set_option("display.width", 140)
pd.set_option("display.max_columns", 20)
logging.disable(logging.INFO) # hide PhosKinTime's INFO log lines; warnings are still shown
from phoskintime.networkmodel import api
# Everything this tutorial writes goes into a new temporary folder, never into the repository.
WORK = Path(tempfile.mkdtemp(prefix="phoskintime-tutorial-06-"))
CONF = api.write_example(WORK / "project", n_starts=2, cores=1) # synthetic inputs + config.toml
prob = api.problem(CONF, work_dir=WORK / "problem") # the problem a run with this config fits
idx, sys_ = prob.idx, prob.sys
theta0 = prob.theta_start
print("model:", sys_.mechanism.name, "| observation model:", prob.observation_model,
"| parameterisation:", prob.parameterisation)
print("data mode:", prob.data_mode.data_mode, "| baseline times (min):", sys_.baseline_times)
print("initial condition policy:", sys_.ic_policy, "| solver grid (min):", prob.solver_times)
[TF] orphan TF T2 has no mrna data to drive it: fallback its own state (data_drive_fallback)
[TF] orphan TF T3 has no mrna data to drive it: fallback its own state (data_drive_fallback)
[TF] observations of data-driven TFs ['T1'] are inputs: 9 rows removed from the loss
model: distributive | observation model: linear_fc_mse | parameterisation: softplus
data mode: mrna+protein+phospho | baseline times (min): {'protein': 0.0, 'phospho': 0.0, 'rna': 4.0}
initial condition policy: data | solver grid (min): [0.0e+00 5.0e-01 7.5e-01 1.0e+00 2.0e+00 4.0e+00 8.0e+00 1.5e+01 1.6e+01
3.0e+01 6.0e+01 1.2e+02 2.4e+02 4.8e+02 9.6e+02]
1. The equations
For protein \(i\) with mRNA \(R_i\), unmodified protein \(P_i\) and the modified form \(X_{ij}\) of each site \(j\), the
distributive model (models/distributive.toml, tutorial 01) is
The site inflow \(S_{ij}(t) = \sum_k W_{ij,k}\, c_k K_k(t)\) carries the kinases. \(K_k(t)\) is the kinase drive:
the measured protein fold change of kinase \(k\), interpolated by a monotone cubic (PCHIP) through the measured times
and held after the last one. The transcription rate \(\text{synth}_i\) is \(A_i\) modulated by the TF input of gene \(i\)
with the TFOpt weights and the gain tf_scale (the full form is on the
Global Network Model page). The drives of the example:
from phoskintime.networkmodel.kinase_drive import KinaseDrive
t_fine = np.unique(np.concatenate([np.linspace(0, float(prob.solver_times[-1]), 481), prob.solver_times]))
kin_in = prob.net.kin_in
K = KinaseDrive(kin_in.grid, kin_in.Kmat).evaluate_many(t_fine) # the PCHIP curve the SBML model encodes exactly
fig, ax = plt.subplots(figsize=(6, 3))
for k, name in enumerate(idx.kinases):
ax.plot(t_fine, K[k], label=f"K(t) of {name}")
ax.plot(kin_in.grid, kin_in.Kmat[k], "o", ms=3, color=ax.lines[-1].get_color())
ax.set_xscale("symlog", linthresh=1.0)
ax.set_xlabel("time (min)")
ax.set_ylabel("fold change")
ax.set_title("Kinase drive (knots = measured kinase protein)", fontsize=10)
ax.legend()
plt.show()

In the SBML model the drive is written as an exact piecewise cubic polynomial with the same knots and slopes, so roadrunner integrates the same curve.
2. The initial state and one solve
trajectory(θ) sets the parameters of θ on the System and integrates the SBML model from the initial state on the
solver grid (the union of the measured times). With the default initial_condition_policy = "data" the initial
state is built from the data at t = 0; "steady_state_all" starts every solve at the rest point of its parameters
instead.
from phoskintime.networkmodel.params import unpack_params
from phoskintime.networkmodel.simulate_sbml import model_of, simulate
objective = prob.numpy_objective()
t_grid, Y_grid = objective.trajectory(theta0) # the solve the objective uses
Y_fine = simulate(sys_, t_fine, y0=sys_.data_y0(), **objective.tol) # the same parameters on a fine grid
states = list(model_of(sys_).state_map) # species ids in PhosKinTime's state order
print("parameters at θ0 (physical):",
{k: np.round(np.atleast_1d(v), 3).tolist() for k, v in unpack_params(theta0[: prob.n_model], prob.slices).items()})
pd.DataFrame({"y0": Y_fine[0], f"y({t_fine[-1]:g} min)": Y_fine[-1]}, index=states).round(4)
SBML written to /tmp/phoskintime_sbml_2e_kumij/model.xml model 'phoskintime_distributive', 0.06 s
parameters at θ0 (physical): {'c_k': [0.01, 1.0], 'A_i': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 'B_i': [0.05, 0.05, 0.05, 0.05, 0.05, 0.05], 'C_i': [0.5, 0.5, 0.5, 0.5, 0.5, 0.5], 'D_i': [0.05, 0.05, 0.05, 0.05, 0.05, 0.05], 'Dp_i': [0.1, 0.1, 0.1, 0.1], 'E_i': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 'tf_scale': [1.0]}
| y0 | y(960 min) | |
|---|---|---|
| R_A | 1.00 | 29.9529 |
| P_A | 0.70 | 284.6761 |
| X_A_S_1 | 0.15 | 2.4754 |
| X_A_S_2 | 0.15 | 2.4754 |
| R_B | 1.00 | 10.0320 |
| P_B | 0.70 | 55.7066 |
| X_B_Y_4 | 0.30 | 14.8712 |
| R_K1 | 1.00 | 29.9751 |
| P_K1 | 0.70 | 83.0634 |
| X_K1_T_3 | 0.30 | 72.2291 |
| R_T1 | 1.00 | 20.0000 |
| P_T1 | 1.00 | 200.0000 |
| R_T2 | 1.00 | 20.0000 |
| P_T2 | 1.00 | 200.0000 |
| R_T3 | 1.00 | 20.0000 |
| P_T3 | 1.00 | 200.0000 |
3. Observables: fold changes against the baseline time
The data are fold changes, so the model is too: each observable is divided by its own value at the baseline time of its modality.
- protein: the total protein \(P_i + \sum_j X_{ij}\), relative to its value at the protein baseline;
- mRNA: \(R_i\) relative to its value at the RNA baseline (the first RNA time, 4 min in the example);
- phosphosite: the modified form \(X_{ij}\) relative to its value at the phospho baseline.
phoskintime.networkmodel.objective_np.predict_observables gives, per modality, the predicted and observed fold changes and the
weights of the rows that enter the data term:
from phoskintime.networkmodel.objective_np import predict_observables
preds = predict_observables(Y_grid, prob.loss_data, prob.data_mode)
pd.DataFrame({m: {"rows": len(pred), "rows with weight > 0": int(np.sum(w > 0)),
"first predictions": np.round(pred[:4], 3).tolist(), "first observations": np.round(obs[:4], 3).tolist()}
for m, (pred, obs, w) in preds.items()}).T
| rows | rows with weight > 0 | first predictions | first observations | |
|---|---|---|---|---|
| protein | 56 | 56 | [1.0, 1.0, 1.0, 1.0] | [1.0, 1.0, 1.0, 1.0] |
| mrna | 27 | 27 | [1.0, 1.0, 1.0, 1.72] | [1.0, 1.0, 1.0, 1.08] |
| phospho | 56 | 56 | [1.0, 1.0, 1.0, 1.0] | [1.0, 1.0, 1.0, 1.0] |
The curves on the fine grid, with the synthetic data. These are the model at the first start, not a fit:
def fold_change_curves(Y, times):
"""Model fold changes on a time grid (distributive layout): {(modality, series): array}."""
base = {m: int(np.argmin(np.abs(times - sys_.baseline_times[m]))) for m in ("protein", "rna", "phospho")}
out = {}
for i, (p, ss) in enumerate(zip(idx.proteins, idx.sites)):
off = int(idx.offset_y[i])
R, total = Y[:, off], Y[:, off + 1: off + 2 + len(ss)].sum(axis=1)
out[("mRNA", p)] = R / R[base["rna"]]
out[("protein", p)] = total / total[base["protein"]]
for j, s in enumerate(ss):
site = Y[:, off + 2 + j]
out[("phospho", f"{p} {s}")] = site / site[base["phospho"]]
return out
curves = fold_change_curves(Y_fine, t_fine)
net = prob.net
observed = {("protein", p): g for p, g in net.df_prot.groupby("protein")}
observed |= {("mRNA", p): g for p, g in net.df_rna.groupby("protein")}
observed |= {("phospho", f"{p} {s}"): g for (p, s), g in net.df_pho.groupby(["protein", "psite"])}
ncol = 5
nrow = int(np.ceil(len(curves) / ncol))
fig, axes = plt.subplots(nrow, ncol, figsize=(14, 2.8 * nrow), sharex=True)
for ax, (key, curve) in zip(axes.ravel(), curves.items()):
ax.plot(t_fine, curve, label="model at θ0")
if key in observed:
ax.plot(observed[key]["time"], observed[key]["fc"], "o", ms=3, color="k", label="synthetic data")
ax.set_title(f"{key[0]}: {key[1]}", fontsize=9)
ax.set_xscale("symlog", linthresh=1.0)
ax.set_yscale("log")
for ax in axes.ravel()[len(curves):]:
ax.set_visible(False)
axes[0, 0].legend(fontsize=8)
fig.suptitle("One forward simulation at the first start (not a fit; invented data)", fontsize=10)
fig.tight_layout()
plt.show()

4. The objective: data term + prior term
With the default observation_model = "linear_fc_mse" the data term is the weighted sum of the mean squared errors
of the fold changes, \(\sum_m \lambda_m\, \mathrm{MSE}_m\) with the weights \(\lambda_m\) of [networkmodel]
lambda_protein, lambda_rna and lambda_phospho. The prior term is the priors file's (tutorial 05). terms gives
both and the breakdown:
t0 = prob.terms(theta0)
parts = {**{f"MSE {m}": v for m, v in t0["breakdown"].items() if m in preds},
"λ": str({k: prob.lambdas[k] for k in ("protein", "rna", "phospho")}),
"data term Σ λ_m MSE_m": t0["data_term"], "prior term": t0["prior_term"], "objective": t0["objective"]}
pd.Series(parts).to_frame("value")
| value | |
|---|---|
| MSE protein | 13367.406476 |
| MSE mrna | 7.362629 |
| MSE phospho | 5668.066827 |
| λ | {'protein': 1.0, 'rna': 1.0, 'phospho': 1.0} |
| data term Σ λ_m MSE_m | 19042.835932 |
| prior term | 0.00499 |
| objective | 19042.840921 |
residual_table lists every row of the data term: the observed and predicted fold change and the residual.
residuals = objective.residual_table(theta0)
residuals["phospho"].head(8)
| series | time_index | obs | pred | residual | in_likelihood | |
|---|---|---|---|---|---|---|
| 0 | 0|0 | 0 | 1.000000 | 1.000000 | 0.000000 | False |
| 1 | 0|1 | 0 | 1.000000 | 1.000000 | 0.000000 | False |
| 2 | 1|0 | 0 | 1.000000 | 1.000000 | 0.000000 | False |
| 3 | 2|0 | 0 | 1.000000 | 1.000000 | 0.000000 | False |
| 4 | 0|0 | 1 | 1.359831 | 0.587127 | -0.772705 | True |
| 5 | 0|1 | 1 | 1.057633 | 0.587127 | -0.470506 | True |
| 6 | 1|0 | 1 | 1.143639 | 0.940579 | -0.203061 | True |
| 7 | 2|0 | 1 | 1.793875 | 1.632650 | -0.161225 | True |
5. The alternative data term: log_fc_gaussian
observation_model = "log_fc_gaussian" models the log fold changes as Gaussian, \(\ln y = \ln \hat y + \varepsilon\),
\(\varepsilon \sim N(0, \sigma_m^2)\) per modality \(m\). The data term is then a negative log-likelihood in nats,
with \(\mathrm{RSS}_m\) the residual sum of squares on the log scale over the \(n_m\) rows after the baseline. By default
(noise_sigma = "estimated") each \(\sigma_m\) is a parameter of the fit, appended to θ with a log-normal prior around
noise_delta_<m>. A likelihood needs a prior in the same units: the priors file must be in mode "likelihood"
(priors_likelihood.toml); PhosKinTime refuses the mixture of nats and objective units (KNOWN_ISSUES V13). This is the
objective the profiles and the posterior of tutorial 09 read as a log-density.
prob_log = api.problem(CONF, ["--observation-model", "log_fc_gaussian",
"--prior-file", REPO_ROOT / "configs" / "priors_likelihood.toml"], work_dir=WORK / "problem-log")
print("θ grows by the σ_m:", prob_log.parameter_names[len(prob.parameter_names):])
t_log = prob_log.terms(prob_log.theta_start)
br = t_log["breakdown"]
table = pd.DataFrame({m: {"n_m": br[f"n_{m}"], "RSS_m (ln scale)": br[f"rss_{m}"], "σ_m at the start": br[f"sigma_{m}"],
"NLL_m (nats)": br[m]} for m in preds if f"n_{m}" in br}).T
print(f"data term {t_log['data_term']:.4f} nats + prior term {t_log['prior_term']:.4f} = {t_log['objective']:.4f}")
table
[TF] orphan TF T2 has no mrna data to drive it: fallback its own state (data_drive_fallback)
[TF] orphan TF T3 has no mrna data to drive it: fallback its own state (data_drive_fallback)
[TF] observations of data-driven TFs ['T1'] are inputs: 9 rows removed from the loss
θ grows by the σ_m: ['sigma[protein]', 'sigma[mrna]', 'sigma[phospho]']
SBML written to /tmp/phoskintime_sbml_vj8s4xuw/model.xml model 'phoskintime_distributive', 0.02 s
data term 55474.0728 nats + prior term 70.4637 = 55544.5364
| n_m | RSS_m (ln scale) | σ_m at the start | NLL_m (nats) | |
|---|---|---|---|---|
| protein | 52.0 | 673.181904 | 0.1 | 33587.145566 |
| mrna | 24.0 | 36.267468 | 0.1 | 1780.165886 |
| phospho | 52.0 | 403.574218 | 0.1 | 20106.761302 |
Summary
- The prediction is a solve of the run's SBML model in libroadrunner at the run's tolerances, from the initial state of the data (or the rest point).
- Observables are fold changes against the baseline time of each modality: total protein, mRNA, and the modified form of each site.
linear_fc_mse: the data term is \(\sum_m \lambda_m \mathrm{MSE}_m\), plus a penalty-mode prior.log_fc_gaussian: a Gaussian likelihood of the log fold changes in nats with estimated \(\sigma_m\), plus a likelihood-mode prior; the objective is then a negative log posterior.api.problem(conf).terms(θ)evaluates exactly what the fit minimises.
Next
07. The fit: the multistart fit in sbmlsim (or AMICI and pyPESTO), the multistart record and the choice of the best start.