Skip to content

Library API and run bundle

Download the notebook (executed for this page) ยท source

KinOpt 0.11 is a library with a command line and a GUI around it. This notebook uses the library directly, as a script or another program would: write the synthetic example, configure, check the inputs, run, read the results, check the KKT conditions, and open the run bundle every run writes.

The example's values are random numbers (generated from a fixed seed), so the fit itself means nothing; with your own data, pass input1/input2 (or a config.toml) instead.

import sys
import tempfile
from pathlib import Path

import pandas as pd

# In a clone, use the repository's KinOpt (run from anywhere inside it); otherwise the installed one.
for folder in [Path.cwd(), *Path.cwd().parents]:
    if (folder / "kinopt" / "__init__.py").is_file():
        sys.path.insert(0, str(folder))
        break

import kinopt
from kinopt import api
from kinopt.examples import write_example

print("KinOpt", kinopt.__version__)
work = Path(tempfile.mkdtemp(prefix="kinopt-tutorial-"))
config_file = write_example(work / "project", n_starts=4)
sorted(p.relative_to(work).as_posix() for p in (work / "project").rglob("*") if p.is_file())
KinOpt 0.11.0
['project/config.toml', 'project/data/input1.csv', 'project/data/input2.csv']

Configure

load_config reads a config.toml and applies overrides by name; every setting is a field of api.RunConfig (which can also be built directly, without a file).

config = api.load_config(config_file, plots=False, fit_analysis=False)
{k: v for k, v in config.to_dict().items() if k not in ("input1", "input2", "results_dir", "copy_to_ode_data_dir")}
{'time_points': [0.0,
  0.5,
  0.75,
  1.0,
  2.0,
  4.0,
  8.0,
  16.0,
  30.0,
  60.0,
  120.0,
  240.0,
  480.0,
  960.0],
 'method': 'scipy-slsqp',
 'n_starts': 4,
 'jitter_scale': 0.1,
 'start_seed': 20260115,
 'base_seed': 20260115,
 'loss_type': 'weighted',
 'lower_bound': -4,
 'upper_bound': 4,
 'estimate_missing_kinases': True,
 'scaling_method': 'none',
 'split_point': 9,
 'segment_points': [0, 3, 6, 9, 14],
 'prediction_transform': 'none',
 'out_file': 'kinopt_results.xlsx',
 'n_jobs': -1,
 'init_strategy': 'hybrid',
 'plots': False,
 'fit_analysis': False,
 'report': True,
 'bundle': True}

Check the inputs

The checks of kinopt validate and of the GUI's validation step.

report = api.validate_inputs(config.input1, config.input2)
print("ok:", report.ok, report.coverage)
report.checks
ok: True {'input1_rows': 9, 'input2_rows': 4, 'sites': 4, 'kinases': 3, 'kinases_with_series': 3, 'sites_with_series': 4, 'edges': 7}
check status count detail
0 missing columns ok 0
1 time series values ok 0
2 duplicated input1 row ok 0
3 duplicated site ok 0
4 site without input1 row ok 0
5 site without kinases ok 0
6 kinase without series ok 0
7 coverage ok 4 4 sites, 3 kinases (3 with input1 series), 7 k...

Run

api.run writes the results folder (workbook, multistart files, run_config.json, logs) and the run bundle. The progress callback is called each time a start finishes; quiet=True keeps the console to warnings.

def progress(done, total, outcome):
    print(f"start {outcome.start_id} finished ({done}/{total}): objective {outcome.fun:.6g}")

result = api.run(config, progress=progress, quiet=True)  # the full log is in results/logs
print("best objective", result.best_objective, "selected start", result.selected_start)
result.multistart
start 1 finished (1/4): objective 0.165203
start 2 finished (2/4): objective 0.165203
start 3 finished (3/4): objective 0.165203
start 0 finished (4/4): objective 0.165203
best objective 0.16520268632791024 selected start 2
start_id seed fun success constr_violation runtime_s
0 0 20260115 0.165203 True 0.000000e+00 1.395725
1 1 20260116 0.165203 True 4.930381e-32 1.252537
2 2 20260117 0.165203 True 1.232595e-32 1.321294
3 3 20260118 0.165203 True 9.860761e-32 1.260229

Read the results

read_results reads a results folder back: every workbook sheet, the multistart summary and the provenance.

results = api.read_results(config.results_dir)
print(list(results.sheets))
results.sheets["Alpha Values"]
['Alpha Values', 'Beta Values', 'Summary', 'Observed', 'Estimated', 'Residuals', 'KKT', 'KKT Multipliers', 'Prediction Check']
Gene Psite Kinase Alpha
0 SUB1 S_10 ZK 0.571028
1 SUB1 S_10 AK 0.428972
2 SUB2 S_20 MK 1.000000
3 SUB3 T_30 AK 0.418461
4 SUB3 T_30 MK 0.496539
5 SUB3 T_30 ZK 0.085000
6 ZK S_1 MK 1.000000
results.sheets["Summary"]
Metric Value
0 Success Success
1 Message Optimization terminated successfully
2 Iterations 55
3 Function Evaluations 61
4 Objective (weighted) 0.165203
5 SSE 13.842706
6 MSE 0.247191
7 RMSE 0.497183
8 MAE 0.388391
9 MAPE 40.030674
10 R-squared -0.271114
11 Prediction transform none
12 Method scipy-slsqp
13 Sites with a negative prediction 0

KKT conditions

Stationarity, primal and dual feasibility and complementary slackness of the selected solution, with SLSQP's multipliers (kinopt.optimality.kkt_diagnostics). The same table is the workbook sheet "KKT".

print("source of the multipliers:", result.kkt.source, "| all pass:", result.kkt.passed)
result.kkt.conditions
source of the multipliers: solver | all pass: True
condition residual tolerance passed
0 stationarity 5.782623e-08 1.000000e-05 True
1 primal feasibility 2.220446e-16 1.000000e-10 True
2 dual feasibility 0.000000e+00 1.000000e-10 True
3 complementary slackness 0.000000e+00 1.000000e-08 True

The run bundle

One zip per run with every table in Parquet, the workbook, the inputs, the resolved configuration and the logs; it is the input of kinopt-vis. check_bundle validates it against the published contract and its sha256 hashes.

import io
import json
import zipfile

from kinopt.bundle import check_bundle

check = check_bundle(result.bundle)
print("bundle", result.bundle.name, "valid:", check.ok)
manifest = check.manifest
print("schema", manifest["bundle_schema"], "| producer", manifest["producer"]["kinopt_version"],
      "| tables", sum(f["kind"] == "table" for f in manifest["files"]))
pd.DataFrame([f for f in manifest["files"] if f["kind"] == "table"])[["path", "rows", "bytes"]]
bundle results.kinopt.zip valid: True
schema 1.0 | producer 0.11.0 | tables 29
path rows bytes
0 tables/bound_pressure.parquet 3 2030
1 tables/constraint_checks.parquet 7 1486
2 tables/contributions.parquet 98 2393
3 tables/control_dag.parquet 0 1524
4 tables/convergence.parquet 4 2638
5 tables/curve_similarity.parquet 4 2161
6 tables/edge_load.parquet 7 1957
7 tables/edge_weights.parquet 7 1260
8 tables/estimated.parquet 56 1746
9 tables/kinase_activity.parquet 42 1456
10 tables/kinase_activity_summary.parquet 3 2957
11 tables/kinase_load.parquet 3 2404
12 tables/kinase_site_detail.parquet 6 2476
13 tables/kkt_conditions.parquet 4 1600
14 tables/kkt_multipliers.parquet 9 1478
15 tables/knockout_matrix.parquet 12 2383
16 tables/knockouts.parquet 7 4261
17 tables/metrics.parquet 14 1418
18 tables/multistart.parquet 4 2509
19 tables/multistart_parameters.parquet 52 2445
20 tables/network_edges.parquet 7 2727
21 tables/network_nodes.parquet 7 1733
22 tables/observed.parquet 56 1858
23 tables/observed_vs_reconstructed.parquet 4 2677
24 tables/prediction_check.parquet 4 1546
25 tables/reconstruction.parquet 4 1507
26 tables/regulator_weights.parquet 6 1559
27 tables/target_dominance.parquet 16 2240
28 tables/target_fragility.parquet 4 3230
with zipfile.ZipFile(result.bundle) as zf:
    name = next(n for n in zf.namelist() if n.endswith("tables/knockouts.parquet"))
    knockouts = pd.read_parquet(io.BytesIO(zf.read(name)))
knockouts[["protein", "psite", "kinase", "delta_auc_abs"]].sort_values("delta_auc_abs", ascending=False)
protein psite kinase delta_auc_abs
2 SUB2 S_20 MK 1.242791
6 ZK S_1 MK 1.242791
3 SUB3 T_30 MK 0.137336
0 SUB1 S_10 ZK 0.108849
4 SUB3 T_30 ZK 0.001960
1 SUB1 S_10 AK -0.081770
5 SUB3 T_30 AK -0.121981

Network readout

kinopt.analysis.network_readout returns the same analysis tables from a results folder (kinopt readout writes them as CSV).

from kinopt.analysis import network_readout

tables = network_readout(config.results_dir)
print(sorted(tables))
tables["kinase_load"]
['bound_pressure', 'contributions', 'control_dag', 'curve_similarity', 'edge_load', 'kinase_activity', 'kinase_activity_summary', 'kinase_load', 'kinase_site_detail', 'knockout_matrix', 'knockouts', 'network_edges', 'network_nodes', 'observed_vs_reconstructed', 'target_dominance', 'target_fragility']
kinase n_targets total_load_auc_abs frac_beta_at_bound n_beta_at_bound latent_auc_abs latent_peak_abs
0 MK 3 3.102676 0.0 0 1.242791 1.899253
1 AK 2 0.791521 0.0 0 0.934022 1.807009
2 ZK 2 0.737796 0.0 0 1.124641 2.119775