Skip to content

04. From KinOpt and TFOpt weights to the network

Download the notebook (executed for this page) · source

What this tutorial shows. How PhosKinTime turns the two result workbooks of KinOpt and TFOpt into the two fixed weight matrices of the network model: the kinase→site matrix W and the TF→target matrix. We build the network with phoskintime.networkmodel.PosteriorObjective.build_run_system, the one function that every fit, rebuild and analysis uses, and look at the matrices. Then we change one option at a time: missing_alpha_policy, tf_sign_source, tf_orphan_policy and weight smoothing.

Place in the series. Tutorial 01 built the model from its mechanism file; tutorials 02 and 03 introduced the input files and how they are read. This tutorial covers the network. Tutorial 05 covers the parameters fitted on top of it, and tutorial 06 covers the simulation and the objective.

Data. All numbers come from the synthetic example (phoskintime.networkmodel.example.write_inputs). The curves and weights are invented and describe no biological system. Everything is written to a temporary folder.

Where the weights come from: KinOpt → TFOpt → PhosKinTime

Tool What it fits Dynamics? What PhosKinTime reads
KinOpt α (kinase→phosphosite, sums to 1 per site) and β (a kinase's activity as a signed combination of its own protein and phosphosite series, sums to 1 per kinase) no: one algebraic fit per time point set Alpha Values → W; kinase-level β (rows with an empty Psite) → start value and prior centre of c_k
TFOpt α (TF→target mRNA) and β (a TF's activity from its own protein and sites) no Alpha Values and the TF-level β → TF matrix weight α·β
PhosKinTime the rate constants of a coupled ODE system (mRNA, protein, phosphosites) yes uses W and the TF matrix as fixed weights; α and β are never fitted here

The sibling tutorials show how these weights are produced and laid out: KinOpt 03. Preprocessing and mapping and 04. Parameter layout: alpha and beta; TFOpt 03. Preprocessing and mapping and 04. Parameter layout: alpha and beta. The file contract (sheets, columns, provenance) is on the External tools page, and the model is described in the network model.

# 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 numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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

# Everything this tutorial writes goes into a new temporary folder, never into the repository.
WORK = Path(tempfile.mkdtemp(prefix="phoskintime-tutorial-03-"))
from phoskintime.networkmodel.example import write_example_project

CONF = write_example_project(WORK / "project", n_starts=2, cores=1)  # synthetic inputs + config.toml
DATA = WORK / "project" / "data"
# networkmodel reads its settings when it is first imported, from the file named here.
os.environ["PHOSKINTIME_NETWORKMODEL_CONFIG"] = str(CONF)
print("example project:", CONF.parent)
print(sorted(p.name for p in DATA.iterdir()))
example project: /tmp/phoskintime-tutorial-03-zrs8unx8/project
['kinase_net.csv', 'kinopt_results.xlsx', 'ms.csv', 'rna.csv', 'tf_net.csv', 'tfopt_results.xlsx']

1. The inputs: two networks and two workbooks

The kinase network lists, per phosphosite, the kinases that may phosphorylate it. The TF network lists TF→target edges. KinOpt's and TFOpt's workbooks give a weight to each of these edges.

kin_net = pd.read_csv(DATA / "kinase_net.csv")
tf_net = pd.read_csv(DATA / "tf_net.csv")
display(kin_net)
display(tf_net)
GeneID Psite Kinase
0 A S_1 {K1}
1 A S_2 {K1, K2}
2 B Y_4 {K1, K2}
3 K1 T_3 {K2}
Source Target
0 T1 A
1 T1 B
2 T2 A
3 T3 K1
4 A B
# The two sheets of each workbook that networkmodel reads (phoskintime/common/external_results.py, KINOPT and TFOPT).
kinopt = pd.read_excel(DATA / "kinopt_results.xlsx", sheet_name=["Alpha Values", "Beta Values"])
tfopt = pd.read_excel(DATA / "tfopt_results.xlsx", sheet_name=["Alpha Values", "Beta Values"])
for name, sheets in (("KinOpt", kinopt), ("TFOpt", tfopt)):
    for sheet, df in sheets.items():
        print(f"{name} / {sheet}")
        display(df)
KinOpt / Alpha Values
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
KinOpt / Beta Values
Kinase Psite Beta
0 K1 NaN -0.4
1 K1 T_3 1.4
2 K2 NaN 1.0
TFOpt / Alpha Values
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
TFOpt / Beta Values
TF PSite Value
0 T1 NaN 0.6
1 T1 S_9 0.4
2 T2 NaN 1.0
3 T3 NaN 1.0
4 A NaN -0.7
5 A S_1 1.7

Things to notice in these invented workbooks. Each one shows a case that occurs in real results:

  • KinOpt α of A S_2 ← K2 is 0. KinOpt's simplex constraint gives vertex solutions: some edges get all the weight and the others get exactly 0 (KNOWN_ISSUES N32).
  • KinOpt β. K1 has a protein row (empty Psite, β = −0.4) and a row for its own site T_3 (β = 1.4). The two sum to 1. PhosKinTime reads only the kinase-level row (empty Psite). This β is a share inside KinOpt's activity model, not a rate.
  • TFOpt β of A is negative (−0.7 at TF level, 1.7 on site S_1). Under the default sign reading this negative β makes every edge of A repressive (section 4).
  • T1, T2 and T3 are TFs without phosphosites in the kinase network ("orphan TFs", section 5).

Note (KNOWN_ISSUES N38): KinOpt workbooks written before KinOpt 0.11.0 built kinase activities from other proteins' series. Their α and β are suspect, and so is anything built from them here. The synthetic workbooks are not affected, because they were written by hand.

2. Build the network as a run does

build_run_system loads the data, merges α into the edges (phoskintime.networkmodel.io), applies the orphan-TF policy and the weight smoothing (phoskintime.networkmodel.tf_orphans.prepare_regulators), and builds W (BuildMatrix.build_W_parallel) and the TF matrix (BuildMatrix.build_tf_matrix). The helper below parses the runner's options for the example config, as phoskintime run would, and lets us override single options.

from phoskintime.networkmodel.runner import parse_runtime_args
from phoskintime.networkmodel.PosteriorObjective import build_run_system, live_settings


def build(extra_args=(), quiet=False, **options):
    """Build the network exactly as a run would: parse the runner's options for the example config, then call
    build_run_system. ``options`` override [networkmodel] options (e.g. tf_sign_source="none")."""
    args, _ = parse_runtime_args(["--conf", str(CONF), "--output-dir", str(WORK / "scratch-run"),
                                  *map(str, extra_args)])
    settings = live_settings(args)
    settings["options"] = {**settings["options"], **options}
    if quiet:
        logging.disable(logging.WARNING)
    try:
        net = build_run_system(args, {}, settings)
    finally:
        logging.disable(logging.INFO)
    net.args = args  # kept for later cells
    return net
net = build()  # defaults: missing_alpha_policy "one", tf_sign_source "beta", tf_orphan_policy "data_drive", no smoothing
print("proteins in the model:", net.idx.proteins)
print("kinases:              ", net.idx.kinases)
print("sites per protein:    ", dict(zip(net.idx.proteins, net.idx.sites)))
print("KinOpt kinase-level β:", net.kin_beta_map)
print("TFOpt TF-level β:     ", net.tf_beta_map)
2026-12-03 14:46:32,271 - phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] orphan TF T2 has no mrna data to drive it: fallback its own state (data_drive_fallback)                          ⏱ 0.10 sec
2026-12-03 14:46:32,272 - phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] orphan TF T3 has no mrna data to drive it: fallback its own state (data_drive_fallback)                          ⏱ 0.10 sec
2026-12-03 14:46:32,279 - phoskintime.networkmodel.PosteriorObjective - WARNING - [TF] observations of data-driven TFs ['T1'] are inputs: 9 rows removed from the loss                                  ⏱ 0.11 sec
proteins in the model: ['A', 'B', 'K1', 'T1', 'T2', 'T3']
kinases:               ['K1', 'K2']
sites per protein:     {'A': ['S_1', 'S_2'], 'B': ['Y_4'], 'K1': ['T_3'], 'T1': [], 'T2': [], 'T3': []}
KinOpt kinase-level β: {'K1': -0.4, 'K2': 1.0}
TFOpt TF-level β:      {'T1': 0.6, 'T2': 1.0, 'T3': 1.0, 'A': -0.7}

The warnings above come from the orphan-TF policy (section 5). They are not errors.

Three proteins have phosphosites: A, B and K1. K2 is a kinase only. Its measured protein series drives the phosphorylation of its targets, but K2 itself has no mRNA or protein state in the model. The TFs T1, T2 and T3 are not in the model under the default policy.

3. The kinase→site matrix W

W has one row per phosphosite and one column per kinase. The entry is the KinOpt α of that edge. In the ODE the phosphorylation rate of site j is S_j(t) = Σ_k W_jk · c_k · K_k(t). Here K_k(t) is the kinase's measured protein series, interpolated in time, and c_k is a fitted gain (tutorial 05). KinOpt's own prediction uses the same α in a different way: it maps β-weighted kinase activities algebraically onto the site series, with no dynamics.

def W_table(net):
    """W as a labelled table: rows = '<protein>_<site>', columns = kinases."""
    sites = [f"{p}_{s}" for p, ss in zip(net.idx.proteins, net.idx.sites) for s in ss]
    return pd.DataFrame(net.W_global.toarray(), index=sites, columns=net.idx.kinases)


def TF_table(net):
    """The TF matrix as a labelled table: rows = targets, columns = TFs (both are model proteins)."""
    names = net.idx.proteins
    return pd.DataFrame(net.tf_mat.toarray(), index=pd.Index(names, name="target"), columns=pd.Index(names, name="TF"))


display(net.df_kin)  # the kinase edges with their merged α
W = W_table(net)
W
protein 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
K1 K2
A_S_1 1.0 0.0
A_S_2 1.0 0.0
B_Y_4 0.7 0.3
K1_T_3 0.0 1.0

A_S_2 ← K2 has weight 0. The edge is still in the network, but it contributes nothing, and no warning is given (N32). A_S_1 and A_S_2 are driven by K1 only. K1_T_3 is driven by K2 only.

4. The TF matrix: α·β, and where the sign comes from

The TF matrix has one row per target protein and one column per regulating protein. Under the default tf_sign_source = "beta" the weight of an edge is TFOpt α × the TF-level β of the TF named on the edge. In the model each target's TF input is divided by its row sum Σ|weight| (tf_deg), so only the relative weights of a row matter, and the overall scale is carried by the fitted tf_scale (tutorial 05).

display(net.df_tf_model)  # the TF edges after the orphan policy (section 5), with their α
display(TF_table(net))
print("row sums Σ|w| used for normalisation (tf_deg):", {p: float(d) for p, d in zip(net.idx.proteins, net.tf_deg)})
tf target alpha
0 T1 A 0.6
1 T1 B 0.5
2 T2 A 0.4
3 T3 K1 1.0
4 A B 0.5
TF A B K1 T1 T2 T3
target
A 0.00 0.0 0.0 0.36 0.4 0.0
B -0.35 0.0 0.0 0.30 0.0 0.0
K1 0.00 0.0 0.0 0.00 0.0 1.0
T1 0.00 0.0 0.0 0.00 0.0 0.0
T2 0.00 0.0 0.0 0.00 0.0 0.0
T3 0.00 0.0 0.0 0.00 0.0 0.0
row sums Σ|w| used for normalisation (tf_deg): {'A': 0.76, 'B': 0.6499999999999999, 'K1': 1.0, 'T1': 1.0, 'T2': 1.0, 'T3': 1.0}
fig, axes = plt.subplots(1, 2, figsize=(9, 3.2))
for ax, table, title in ((axes[0], W, "W: kinase → site (KinOpt α)"), (axes[1], TF_table(net), "TF matrix (α·β)")):
    im = ax.imshow(table.values, cmap="coolwarm", vmin=-1, vmax=1)
    ax.set_xticks(range(table.shape[1]), table.columns)
    ax.set_yticks(range(table.shape[0]), table.index)
    ax.set_title(title, fontsize=10)
    for (r, c), v in np.ndenumerate(table.values):
        if v != 0:
            ax.text(c, r, f"{v:.2f}", ha="center", va="center", fontsize=8)
fig.colorbar(im, ax=axes, shrink=0.8, label="weight")
plt.show()

png

What happened to the TF network. The input had five edges: T1→A, T1→B, T2→A, T3→K1 and A→B, and the model keeps all five under their own names, each weighted α·β with its own TF's TF-level β: T1→A 0.36 (0.6 · 0.6), T1→B 0.30 (0.5 · 0.6), T2→A 0.40 (0.4 · 1.0), T3→K1 1.0 and A→B −0.35 (0.5 · −0.7).

  • T1, T2 and T3 are orphan TFs (section 5): T1 is driven by its measured mRNA, T2 and T3 (no mRNA) are their own mRNA and protein states.
  • A's edge to B is negative, because A's TF-level β is negative. Inside TFOpt, β is a share in the TF's activity and not a mode of regulation, so reading its sign as activation or repression is an assumption (External tools page, "Negative weights are not rejected").

tf_sign_source selects where the sign comes from:

  • "beta" (default until the v0.7.0 freeze): weight α·β.
  • "network": the sign of each edge comes from a CollecTRI file (is_stimulation / is_inhibition), and the weight is sign·α·|β|.
  • "none": weight α·|β|, every edge activating.

Below we write a small invented CollecTRI-style file in which T1 represses B and every other edge activates.

collectri = WORK / "collectri_synthetic.csv"  # invented signs, same columns as the CollecTRI file
pd.DataFrame({"source_genesymbol": ["T1", "T1", "T2", "T3", "A"],
              "target_genesymbol": ["A", "B", "A", "K1", "B"],
              "is_stimulation": [1, 0, 1, 1, 1],
              "is_inhibition": [0, 1, 0, 0, 0]}).to_csv(collectri, index=False)

for source in ("beta", "network", "none"):
    n = build(quiet=True, tf_sign_source=source, collectri=str(collectri))
    print(f"tf_sign_source = {source!r}")
    display(TF_table(n))
tf_sign_source = 'beta'
TF A B K1 T1 T2 T3
target
A 0.00 0.0 0.0 0.36 0.4 0.0
B -0.35 0.0 0.0 0.30 0.0 0.0
K1 0.00 0.0 0.0 0.00 0.0 1.0
T1 0.00 0.0 0.0 0.00 0.0 0.0
T2 0.00 0.0 0.0 0.00 0.0 0.0
T3 0.00 0.0 0.0 0.00 0.0 0.0
tf_sign_source = 'network'
TF A B K1 T1 T2 T3
target
A 0.00 0.0 0.0 0.36 0.4 0.0
B 0.35 0.0 0.0 -0.30 0.0 0.0
K1 0.00 0.0 0.0 0.00 0.0 1.0
T1 0.00 0.0 0.0 0.00 0.0 0.0
T2 0.00 0.0 0.0 0.00 0.0 0.0
T3 0.00 0.0 0.0 0.00 0.0 0.0
tf_sign_source = 'none'
TF A B K1 T1 T2 T3
target
A 0.00 0.0 0.0 0.36 0.4 0.0
B 0.35 0.0 0.0 0.30 0.0 0.0
K1 0.00 0.0 0.0 0.00 0.0 1.0
T1 0.00 0.0 0.0 0.00 0.0 0.0
T2 0.00 0.0 0.0 0.00 0.0 0.0
T3 0.00 0.0 0.0 0.00 0.0 0.0

With "network" the B row has T1→B repressing (−0.30) and A→B activating (+0.35): the signs come from the edges themselves, and every TF keeps its own edges.

5. Orphan TFs: tf_orphan_policy

An orphan TF is a TF in the TF network that is not a protein with phosphosites in the kinase network. Since v0.7.0 the only policy is "data_drive" (KNOWN_ISSUES N31; network model page, "tf_orphan_policy"): the orphan's activity is a drive through its own measured data (tf_data_drive_measurement, mRNA by default), and those data become an input, removed from the objective. An orphan without that measurement falls back (data_drive_fallback): "state" (default; it becomes its own mRNA and protein state) or "drop" (its edges are removed). The former policies "proxy" (an orphan replaced by one of its own targets, which created self-feedback that is not in the network), "state" and "drop" were removed.

rows = []
for fallback in ("state", "drop"):
    n = build(quiet=True, data_drive_fallback=fallback)
    info = n.tf_info
    rows.append({"data_drive_fallback": fallback, "model proteins": ", ".join(n.idx.proteins),
                 "driven by data": ", ".join(info["driven"]) or "-", "fell back": info["fallback"] or "-",
                 "dropped edges": len(info["dropped_edges"]), "TF edges in model": int(n.tf_mat.nnz)})
display(pd.DataFrame(rows))
data_drive_fallback model proteins driven by data fell back dropped edges TF edges in model
0 state A, B, K1, T1, T2, T3 T1 {'T2': 'state', 'T3': 'state'} 0 5
1 drop A, B, K1, T1 T1 {'T2': 'drop', 'T3': 'drop'} 2 3

T1 is driven by its mRNA data, and those mRNA data are removed from the objective because they are now an input. T2 (no data) and T3 (protein data only, not mRNA) have no mRNA: with the default fallback "state" they are model proteins without sites (6 proteins, 5 TF edges); with "drop" their edges are removed (4 proteins, 3 TF edges). The driven TF's own rate parameters are fixed and outside the prior term: they have no data influence until interaction data for that TF are part of the network.

6. Missing α: missing_alpha_policy

An edge that is in the network but has no α in the workbook gets α = 1.0 by default ("one"). That is more than any estimated weight (KNOWN_ISSUES N35). "row_mean" uses the mean α of the row's covered edges. "drop" removes the edge. To see this we write a copy of the KinOpt workbook without the B Y_4 ← K2 row.

import phoskintime.networkmodel.io as nm_io

sheets = pd.read_excel(DATA / "kinopt_results.xlsx", sheet_name=None)
alpha = sheets["Alpha Values"]
sheets["Alpha Values"] = alpha[~((alpha["Gene"] == "B") & (alpha["Kinase"] == "K2"))]
kinopt_missing = WORK / "kinopt_missing_edge.xlsx"
with pd.ExcelWriter(kinopt_missing) as writer:
    for name, df in sheets.items():
        df.to_excel(writer, sheet_name=name, index=False)

rows = {}
for policy in ("one", "row_mean", "drop"):
    n = build(["--kinopt", kinopt_missing], quiet=True, missing_alpha_policy=policy)
    rows[policy] = W_table(n).loc["B_Y_4"]
    print(policy, nm_io.INPUT_REPORT["kinase_alpha"])  # the counts a run records in metadata.json inputs_report
pd.DataFrame(rows).T.rename_axis("policy")
one {'edges': 6, 'without_alpha': 1, 'policy': 'one'}
row_mean {'edges': 6, 'without_alpha': 1, 'policy': 'row_mean', 'rows_without_covered_edge': 0, 'edges_kept_at_one': 0}
drop {'edges': 6, 'without_alpha': 1, 'policy': 'drop', 'dropped': 1}
K1 K2
policy
one 0.7 1.0
row_mean 0.7 0.7
drop 0.7 0.0

With "one" the row sum of B_Y_4 becomes 1.7 instead of 1. With "row_mean" the missing edge gets the mean of the covered edge (0.7). With "drop" the edge is gone. A missing TFOpt α is handled in the same way, with the same option.

7. Weight smoothing

weight_smoothing_kin (λ_kin, for W) and weight_smoothing_tf (λ_tf, for the TF matrix) move each row part of the way toward uniform weights, keeping the row sum: w′ = (1 − λ)·w + λ·(row sum / number of edges). This gives zero-weight vertex edges some weight back. Rows with a negative weight are left unsmoothed by default (weight_smoothing_signed = "exclude"), so on this example the TF matrix does not change (A's weights are all negative).

smoothed = build(quiet=True, weight_smoothing_kin=0.5, weight_smoothing_tf=0.5)
pd.concat({"λ = 0": W, "λ_kin = 0.5": W_table(smoothed)}, axis=1)
λ = 0 λ_kin = 0.5
K1 K2 K1 K2
A_S_1 1.0 0.0 1.00 0.00
A_S_2 1.0 0.0 0.75 0.25
B_Y_4 0.7 0.3 0.60 0.40
K1_T_3 0.0 1.0 0.00 1.00

A_S_2 ← K2 now has weight 0.25 and A_S_2 ← K1 has 0.75. B_Y_4 moved from (0.7, 0.3) to (0.6, 0.4). Each row still sums to 1. Smoothing is a modelling choice: it does not recover the information that KinOpt's vertex solution discarded. Its effect on the fit should be checked, for example by comparing runs. weight_smoothing_estimate = true fits λ_kin and λ_tf as two parameters instead.

Summary

  • PhosKinTime reads KinOpt α into W and TFOpt α together with the TF-level β into the TF matrix. Both matrices are fixed during the fit. KinOpt's kinase-level β enters only as the start value and prior centre of c_k (tutorial 05).
  • What a run did is recorded: metadata.json inputs_report (counts, as in nm_io.INPUT_REPORT above), regulators (orphan policy, data-driven TFs, fallbacks, dropped edges, smoothing) and the exported matrices network_W_global.csv and network_tf_mat.csv.
  • Known limitations: zero-weight edges (N32), missing α set to 1.0 (N35), orphan TFs driven by their own data (N31) and KinOpt workbooks before 0.11.0 (N38). See KNOWN_ISSUES.

Next

05. Parameter layout of the network model: the rates fitted on top of these fixed matrices, their bounds, their coordinates and their prior.