03. Load and validate data
Download the notebook (executed for this page) · source
What this tutorial shows. phoskintime.networkmodel.api.validate_inputs on the example project: what it checks, the
inputs_report counts it returns (what was read, dropped or defaulted), and what happens with a workbook that breaks
the KinOpt/TFOpt file contract, a missing workbook, and an MS file with too many time columns. Fourth tutorial of the
series (after 02. Toy dataset format).
The data are the invented curves of the synthetic example, written to a temporary folder.
Counterparts: KinOpt 02 and TFOpt 02 validate the raw time series and build each tool's arrays. PhosKinTime validates the same inputs plus the two tools' result workbooks, and builds the network.
import os
import sys
from pathlib import Path
# Find the repository root (the folder with pixi.toml and phoskintime/networkmodel/), put it first on sys.path and work from
# there. A Jupyter kernel started outside pixi does not get pixi's PYTHONPATH.
REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
if (p / "pixi.toml").is_file() and (p / "phoskintime" / "networkmodel").is_dir())
sys.path.insert(0, str(REPO_ROOT))
os.chdir(REPO_ROOT)
import json
import logging
import tempfile
import pandas as pd
import phoskintime.networkmodel.io
import phoskintime.networkmodel.PosteriorObjective
from phoskintime.config.constants import LOG_DIR
from phoskintime.config.logconf import redirect_file_logs
from phoskintime.networkmodel import api, options
from phoskintime.networkmodel.config import RESULTS_DIR
pd.set_option("display.max_colwidth", None) # show table cells in full
WORK = Path(tempfile.mkdtemp(prefix="phoskintime-tutorial-02-")) # never inside the repository
# Logging: write log files into the temporary folder (not the config's output folder), hide INFO lines, and print
# warnings without the terminal colour codes.
redirect_file_logs(WORK / "logs", [RESULTS_DIR, LOG_DIR])
logging.disable(logging.INFO)
for lg in logging.Logger.manager.loggerDict.values():
for h in getattr(lg, "handlers", []):
if type(h) is logging.StreamHandler:
h.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
conf = api.write_example(WORK / "project", n_starts=2, cores=1)
data = conf.parent / "data"
print(conf)
/tmp/phoskintime-tutorial-02-axxcgz4v/project/config.toml
The settings that decide how inputs are read
options.parse_config returns every registered [networkmodel] option of the config, with defaults where the file
has none. These are the ones that change how the inputs become the network:
cfg = api.load_config(conf)
opts = options.parse_config(cfg)
keys = ["missing_alpha_policy", "tf_sign_source", "tf_orphan_policy", "kinopt_alpha_source", "ck_prior_centre"]
pd.DataFrame({"value": [opts[k] for k in keys],
"meaning": [options.BY_KEY[k].help.split(". ")[0] for k in keys]}, index=keys)
| value | meaning | |
|---|---|---|
| missing_alpha_policy | one | Network edges without a KinOpt/TFOpt α: one (legacy, α = 1.0, N35) | row_mean (mean α of the row's covered edges: a site's kinase edges, a target's TF edges) | drop (edge removed). |
| tf_sign_source | beta | Sign of a TF edge: beta (legacy; the sign of TFOpt's TF-level β) | network (CollecTRI mode of regulation, is_stimulation / is_inhibition) | none (every edge activating) |
| tf_orphan_policy | data_drive | TFs that are not proteins with phosphosites: data_drive (driven by the TF's own measurement, tf_data_drive_measurement; the only policy since v0.7.0: proxy, state and drop were removed, N31). |
| kinopt_alpha_source | workbook | KinOpt α: workbook (the selected start, legacy) | ensemble_mean (mean α over the accepted KinOpt starts within kinopt_ensemble_tol of the best; needs kinopt_run_dir) | ensemble_member (one start, kinopt_ensemble_member; the ensemble driver script runs every member). |
| ck_prior_centre | kinopt_beta | Centre of the c_k prior and c_k's starting value: kinopt_beta (legacy; KinOpt's kinase-level β, a share inside KinOpt's activity mixture, not a scale; N38) | design (geometric middle of the c_k design box). |
What validate_inputs checks
It reads everything a run would read and builds the network, without fitting:
- the runner options parse (from the config, plus
extra_argsthat override it, as on the command line); - the input files exist:
kinase_net,tf_net,ms(required),rna(if given); - each KinOpt/TFOpt workbook meets the file contract (
phoskintime.common.external_results); a missing workbook is a warning, a workbook that breaks the contract is an error; - the network can be built with the function every run uses,
phoskintime.networkmodel.PosteriorObjective.build_run_system: data loading andfc_startscaling, the time columns against the time grids, the mechanistic site filter, the orphan-TF policy, W and the TF matrix, the kinase drives and the initial conditions.
It returns a ValidationReport(ok, errors, warnings, counts). The command line equivalent is
pixi run phoskintime validate --conf configs/config.toml --verbose.
report = api.validate_inputs(conf)
print("ok:", report.ok)
print("errors:", report.errors)
print("warnings:", report.warnings)
WARNING phoskintime.networkmodel.PosteriorObjective: [TF] orphan TF T2 has no mrna data to drive it: fallback its own state (data_drive_fallback)
WARNING phoskintime.networkmodel.PosteriorObjective: [TF] orphan TF T3 has no mrna data to drive it: fallback its own state (data_drive_fallback)
WARNING phoskintime.networkmodel.PosteriorObjective: [TF] observations of data-driven TFs ['T1'] are inputs: 9 rows removed from the loss
ok: True
errors: []
warnings: []
The three [TF] orphan TF ... lines above are log warnings of the network build, not entries of report.warnings:
T1, T2 and T3 are orphan TFs and the default policy replaces each by one of its targets (KNOWN_ISSUES N31). A run
records the same in metadata.json regulators.
The inputs report
report.counts is the run's inputs_report (also written to metadata.json): what was read, dropped or defaulted.
Nothing is changed silently; everything that is dropped is counted (KNOWN_ISSUES N37).
rows = []
for section, values in report.counts.items():
for key, value in values.items():
if key not in ("path", "workbook", "sha256", "note"):
rows.append({"section": section, "count": key, "value": value})
pd.DataFrame(rows).set_index(["section", "count"])
| value | ||
|---|---|---|
| section | count | |
| kinase_network | rows | 4 |
| rows_with_empty_cell_dropped | 0 | |
| edges | 6 | |
| duplicate_edges_removed | 0 | |
| kinopt | alpha_rows | 6 |
| kinase_level_beta | 2 | |
| site_level_beta_rows_not_used | 1 | |
| kinase_alpha | edges | 6 |
| without_alpha | 0 | |
| policy | one | |
| tf_network | rows | 5 |
| rows_with_empty_cell_dropped | 0 | |
| duplicate_edges_removed | 0 | |
| tf_sign_source | beta | |
| tfopt | alpha_rows | 5 |
| tf_level_beta | 4 | |
| site_level_beta_rows_not_used | 2 | |
| negative_tf_level_beta | 1 | |
| tf_alpha | edges | 5 |
| without_alpha | 0 | |
| policy | one | |
| ms | rows | 10 |
| time_columns | 14 | |
| missing_values_dropped | 0 | |
| values_after_scaling | 140 | |
| non_finite_after_scaling_dropped | 0 | |
| protein_values | 70 | |
| phospho_values | 70 | |
| rna | rows | 4 |
| time_columns | 9 | |
| missing_values_dropped | 0 | |
| values_after_scaling | 36 | |
| non_finite_after_scaling_dropped | 0 | |
| phospho_site_filter | rows_before | 70 |
| rows_after | 56 | |
| observations_in_model | protein | [70, 56] |
| rna | [27, 27] | |
| phospho | [56, 56] | |
| phospho_rows_of_sites_not_in_the_model | 0 |
How to read it, on this example:
- kinase_network: 4 rows become 6 edges (
{K1, K2}cells split). kinase_alpha: all 6 edges found an α in the KinOpt workbook (without_alpha0), somissing_alpha_policydid not apply. - kinopt: 6 α rows, 2 kinase-level β (K1, K2); 1 site-level β row (K1 T_3) is not used by PhosKinTime.
- tfopt: 4 TF-level β, one of them negative (A); 2 site-level β rows are not used.
- ms: 10 rows × 14 time columns = 140 values: 70 protein values (5 protein rows) and 70 phosphosite values (5 site rows). rna: 4 rows × 9 = 36 values.
- phospho_site_filter 70 → 56: the mechanistic site filter drops phosphosite rows without a kinase edge, here T1 S_9 (14 values).
- observations_in_model
[before, after]: protein 70 → 42 and RNA 36 → 27 keep the model proteins A, B and K1 only. K2's protein row is not a model observation, but it is still read as K2's kinase drive; T3's protein row and T1's mRNA row are not used (both are orphan TFs).
The file paths and SHA-256 checksums are in the same report (report.counts["kinopt"]["sha256"]) and, for a run, in
metadata.json external_results, so a result can be traced to the exact KinOpt and TFOpt workbooks.
print(json.dumps({k: report.counts[k] for k in ("kinopt", "tfopt")}, indent=1)[:900])
{
"kinopt": {
"workbook": "/tmp/phoskintime-tutorial-02-axxcgz4v/project/data/kinopt_results.xlsx",
"sha256": "490c11814eab9aa96c8913e04ffd17182d94d9f6c32451196a9bda8f326b8db6",
"alpha_rows": 6,
"kinase_level_beta": 2,
"site_level_beta_rows_not_used": 1
},
"tfopt": {
"workbook": "/tmp/phoskintime-tutorial-02-axxcgz4v/project/data/tfopt_results.xlsx",
"sha256": "59f959e9fc4a58c0b5307f8f7b68fbb163bb85df199a2a2241db04a4bca479b3",
"alpha_rows": 5,
"tf_level_beta": 4,
"site_level_beta_rows_not_used": 2,
"negative_tf_level_beta": 1
}
}
A workbook that breaks the contract
The contract lists, per tool, the sheets and columns PhosKinTime reads (External tools). Extra sheets and columns are allowed; missing ones are an error.
from phoskintime.common.external_results import KINOPT, TFOPT, ExternalResultsError, read_external_results
pd.DataFrame([{"tool": c.tool, "sheet": s, "required columns": ", ".join(cols)}
for c in (KINOPT, TFOPT) for s, cols in c.sheets.items()])
| tool | sheet | required columns | |
|---|---|---|---|
| 0 | KinOpt | Alpha Values | Gene, Psite, Kinase, Alpha |
| 1 | KinOpt | Beta Values | Kinase, Psite, Beta |
| 2 | KinOpt | Estimated | Gene, Psite |
| 3 | TFOpt | Alpha Values | mRNA, TF, Value |
| 4 | TFOpt | Beta Values | TF, PSite, Value |
| 5 | TFOpt | Estimated | mRNA |
Break a copy of the KinOpt workbook: rename the column Alpha of Alpha Values to Weight. The copy goes into the
temporary folder; the project's own workbook is unchanged. extra_args points the check at it, exactly like
--kinopt on the command line.
broken = WORK / "broken_kinopt_results.xlsx"
sheets = pd.read_excel(data / "kinopt_results.xlsx", sheet_name=None)
sheets["Alpha Values"] = sheets["Alpha Values"].rename(columns={"Alpha": "Weight"})
with pd.ExcelWriter(broken) as writer:
for name, df in sheets.items():
df.to_excel(writer, sheet_name=name, index=False)
bad = api.validate_inputs(conf, extra_args=["--kinopt", broken])
print("ok:", bad.ok)
for err in bad.errors:
print("error:", err)
ok: False
error: kinopt: KinOpt result file /tmp/phoskintime-tutorial-02-axxcgz4v/broken_kinopt_results.xlsx, sheet 'Alpha Values': missing required column(s) ['Alpha']; found columns ['Gene', 'Psite', 'Kinase', 'Weight']. See the 'External tools' page of the PhosKinTime documentation (docs/Documentation/external_tools.md) for the file contract.
The check stops before the network build. Underneath, the contract raises ExternalResultsError (a ValueError);
its message names the file, the sheet and the missing column:
try:
read_external_results(broken, KINOPT, sheets=("Alpha Values", "Beta Values"))
except ExternalResultsError as exc:
print(type(exc).__name__, "->", exc)
ExternalResultsError -> KinOpt result file /tmp/phoskintime-tutorial-02-axxcgz4v/broken_kinopt_results.xlsx, sheet 'Alpha Values': missing required column(s) ['Alpha']; found columns ['Gene', 'Psite', 'Kinase', 'Weight']. See the 'External tools' page of the PhosKinTime documentation (docs/Documentation/external_tools.md) for the file contract.
A missing workbook is a warning
Without a TFOpt workbook a run still starts: every TF edge gets α = 1.0, no TF-level β is used, and the provenance
records priors: none. validate_inputs reports it as a warning and ok stays true.
no_tfopt = api.validate_inputs(conf, extra_args=["--tfopt", WORK / "no_such_tfopt_results.xlsx"])
print("ok:", no_tfopt.ok)
for w in no_tfopt.warnings:
print("warning:", w)
print("tfopt:", no_tfopt.counts["tfopt"], "| tf_alpha:", no_tfopt.counts["tf_alpha"])
WARNING phoskintime.networkmodel.io: [Data] TFOpt results not found ('/tmp/phoskintime-tutorial-02-axxcgz4v/no_such_tfopt_results.xlsx'): using alpha = 1.0 for all TF edges and no TF priors (priors: none). See the 'External tools' docs page.
WARNING phoskintime.networkmodel.PosteriorObjective: [TF] orphan TF T2 has no mrna data to drive it: fallback its own state (data_drive_fallback)
WARNING phoskintime.networkmodel.PosteriorObjective: [TF] orphan TF T3 has no mrna data to drive it: fallback its own state (data_drive_fallback)
WARNING phoskintime.networkmodel.PosteriorObjective: [TF] observations of data-driven TFs ['T1'] are inputs: 9 rows removed from the loss
ok: True
warning: tfopt: TFOpt result file not found: '/tmp/phoskintime-tutorial-02-axxcgz4v/no_such_tfopt_results.xlsx'. Expected a workbook such as 'tfopt_results.xlsx'. See the 'External tools' page of the PhosKinTime documentation (docs/Documentation/external_tools.md) for the file contract. (a run uses alpha = 1.0 and no priors for these edges)
tfopt: {'workbook': 'absent'} | tf_alpha: {'edges': 5, 'without_alpha': 5, 'policy': 'no workbook: 1.0'}
All 5 TF edges are now without_alpha and get the policy's value (missing_alpha_policy = "one": α = 1.0,
KNOWN_ISSUES N35). Such a run is not the same model as one with TFOpt weights; check the warnings before fitting.
An MS file with more time columns than the time grid
Before v0.7.0 surplus time columns were dropped silently; now they are an error (KNOWN_ISSUES N37). Add a column x15
to a copy of the MS table:
ms_extra = WORK / "ms_with_x15.csv"
pd.read_csv(data / "ms.csv").assign(x15=1.0).to_csv(ms_extra, index=False)
too_many = api.validate_inputs(conf, extra_args=["--ms", ms_extra])
print("ok:", too_many.ok)
for err in too_many.errors:
print("error:", err)
ok: False
error: the network cannot be built: MS file /tmp/phoskintime-tutorial-02-axxcgz4v/ms_with_x15.csv: 15 time columns (x1..x15) but the MS time grid has 14 points; set the grid in [networkmodel.timepoints] (surplus columns were dropped silently before v0.7.0, N37).
What validation does not check
validate_inputs checks files, columns and that the network can be built. It does not check whether the KinOpt and
TFOpt weights are right: a workbook of KinOpt before 0.11.0 passes the contract although its α and β are suspect
(KNOWN_ISSUES N38), and vertex solutions with zero weights pass as well (N32). Record the tools'
versions (an optional Metadata sheet with tool, version, git_commit is copied into the run's provenance).
Whether the KinOpt and TFOpt fits themselves are feasible and converged is checked in those tools:
KinOpt 08, TFOpt 08.
Next
04. From KinOpt and TFOpt weights to the network: how the validated inputs become the model's proteins, kinases, W and TF matrix, and what the orphan-TF policy does to the example's T1, T2 and T3.