Skip to content

Library API and run bundle

Download the notebook (executed for this page) · source

TFOpt 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, open the run bundle every run writes, and compute the regulatory readout.

The example's TF series are random numbers (generated from a fixed seed) and its targets are computed from known α and β, so the fit recovers them; the values illustrate the file formats, not biology. With your own data, pass input1/input3/input4 (or a config.toml) instead.

import sys
import tempfile
from pathlib import Path

import pandas as pd

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

import tfopt
from tfopt import api
from tfopt.examples import TRUE_ALPHA, TRUE_BETA, write_example

print("TFOpt", tfopt.__version__)
work = Path(tempfile.mkdtemp(prefix="tfopt-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())
TFOpt 0.2.0
['project/config.toml',
 'project/data/input1.csv',
 'project/data/input3.csv',
 'project/data/input4.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). The RNA grid (time_points) and the MS grid (ms_time_points) always come from the configuration: TFOpt has no built-in time grid.

config = api.load_config(config_file, plots=False, fit_analysis=False, prediction_transform="clip")
{k: v for k, v in config.to_dict().items() if k not in ("input1", "input3", "input4", "results_dir", "copy_to_ode_data_dir")}
{'time_points': [4.0, 8.0, 15.0, 30.0, 60.0, 120.0, 240.0, 480.0, 960.0],
 'ms_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': 0,
 'seed': 123,
 'p_random': 0.3,
 'loss_type': 0,
 'lower_bound': -4.0,
 'upper_bound': 4.0,
 'prediction_transform': 'clip',
 'tf_protein_source': 'protein_then_mrna',
 'ms_alignment': 'by_time',
 'out_file': 'tfopt_results.xlsx',
 'maxiter': 20000,
 'tol': 1e-10,
 'n_jobs': 1,
 'threads_per_worker': 1,
 'allow_nonsmooth': False,
 'feasibility_tol': 1e-08,
 'acceptance_tol': 1e-10,
 'plots': False,
 'fit_analysis': False,
 'report': True,
 'bundle': True}

Check the inputs

The checks of tfopt validate and of the GUI's validation step. The example has a TF without any series (TFD): a run drops it with its edge, and the report says so.

report = api.validate_inputs(config.input1, config.input3, config.input4, ms_time_points=config.ms_time_points,
                             time_points=config.time_points, tf_protein_source=config.tf_protein_source,
                             ms_alignment=config.ms_alignment)
print("ok:", report.ok, report.coverage)
display(report.skipped)
report.checks
ok: True {'input1_rows': 6, 'input3_rows': 5, 'input4_rows': 8, 'targets': 4, 'targets_used': 4, 'tfs': 4, 'tfs_protein': 2, 'tfs_mrna': 1, 'tfs_first_site': 0, 'tfs_excluded': 1, 'edges': 8, 'edges_used': 7}
Source Target reason
0 TFD G4 TF has no input1 or input3 series
check status count detail
0 missing columns ok 0
1 time grids ok 0
2 input1 time series values ok 0
3 input3 time series values ok 0
4 duplicated input1 row ok 0
5 input1 Psite neither empty nor S_/T_/Y_ ok 0
6 duplicated input3 row ok 0
7 input4 missing identifiers ok 0
8 TF without series warning 1 1 edges dropped
9 target dropped ok 0
10 targets to fit ok 4
11 coverage ok 4 4 targets, 3 TFs (2 protein, 1 mRNA, 0 first s...

Run

api.run writes the results folder (workbook, multistart files, diagnostics.json, 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 {done}/{total} finished: 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,
      "| success", result.success, "| accepted", result.accepted)
result.multistart
2026-11-30 17:01:40,099 - tfopt.series - WARNING - Edge TFD -> G4 excluded: TF TFD has no input1 or input3 series                                     ⏱ 0.01 sec
start 1/4 finished: objective 2.43062e-11
start 2/4 finished: objective 5.57692e-12
start 3/4 finished: objective 3.01006e-12
start 4/4 finished: objective 2.32642e-12
best objective 2.3264239140816977e-12 selected start 3 | success True | accepted True
start_id fun success constraint_violation nit runtime_s final_error feasible accepted kkt_passed kkt_stationarity kkt_primal_feasibility kkt_dual_feasibility kkt_complementary_slackness seed
0 3 2.326424e-12 True 0.000000e+00 41 0.236821 3.491033e-07 True True True 3.491033e-07 0.000000e+00 -0.0 0.0 126
1 2 3.010058e-12 True 1.110223e-16 44 0.237622 2.772749e-07 True True True 2.772749e-07 1.110223e-16 -0.0 0.0 125
2 1 5.576919e-12 True 2.220446e-16 39 0.325597 2.533826e-07 True True True 2.533826e-07 0.000000e+00 -0.0 0.0 124
3 0 2.430619e-11 True 0.000000e+00 39 1.239393 1.382687e-06 True True True 1.382687e-06 0.000000e+00 -0.0 0.0 123

Read the results

read_results reads a results folder back: every workbook sheet, the multistart summary and the provenance. The Beta Values sheet records in Source which series each TF-level β multiplies (protein, mrna, or site).

results = api.read_results(config.results_dir)
print(list(results.sheets))
results.sheets["Beta Values"]
['Alpha Values', 'Beta Values', 'Residuals', 'Observed', 'Estimated', 'Optimization Results', 'KKT Diagnostics', 'KKT Multipliers', 'Prediction Check']
TF PSite Value Source
0 TFA NaN 0.600000 protein
1 TFA S_10 0.500000 site
2 TFA T_20 -0.100000 site
3 TFB NaN 1.000000 protein
4 TFC NaN 0.700001 mrna
5 TFC S_5 0.200007 site
6 TFC Y_7 0.099991 site
alpha = results.sheets["Alpha Values"]
truth = pd.DataFrame([(g, tf, a) for g, row in TRUE_ALPHA.items() for tf, a in row.items()], columns=["mRNA", "TF", "true"])
alpha.merge(truth, on=["mRNA", "TF"])
mRNA TF Value true
0 G1 TFA 1.000000 1.0
1 G2 TFA 0.300000 0.3
2 G2 TFB 0.700000 0.7
3 G3 TFB 0.400001 0.4
4 G3 TFC 0.599999 0.6
5 G4 TFA 0.500000 0.5
6 G4 TFB 0.500000 0.5

KKT conditions

Stationarity, primal and dual feasibility and complementary slackness of the selected solution (tfopt.optimality.kkt_diagnostics). The same table is the workbook sheet "KKT Diagnostics".

print("source of the multipliers:", result.kkt.source, "| all pass:", result.kkt.passed)
result.kkt.conditions
source of the multipliers: estimated | all pass: True
condition residual tolerance passed
0 stationarity 3.491033e-07 1.000000e-05 True
1 primal feasibility 0.000000e+00 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 the tables, the workbook, the inputs, the resolved configuration and the logs (see the Run bundle page). check_bundle validates it against the published contract and its sha256 hashes.

import zipfile

from tfopt.bundle import check_bundle

check = check_bundle(result.bundle)
print("bundle", result.bundle.name, "valid:", check.ok)
with zipfile.ZipFile(result.bundle) as zf:
    names = zf.namelist()
print(len(names), "files")
sorted(names)[:20]
bundle results.tfopt.zip valid: True
40 files
['results.tfopt/arrays/multistart_params.npy',
 'results.tfopt/manifest.json',
 'results.tfopt/provenance/config_resolved.json',
 'results.tfopt/provenance/diagnostics.json',
 'results.tfopt/provenance/inputs/input1.csv',
 'results.tfopt/provenance/inputs/input3.csv',
 'results.tfopt/provenance/inputs/input4.csv',
 'results.tfopt/provenance/logs/tfopt_20261130.log',
 'results.tfopt/provenance/run_config.json',
 'results.tfopt/provenance/tfopt_results.xlsx',
 'results.tfopt/resim/model.json',
 'results.tfopt/resim/tf_series.parquet',
 'results.tfopt/tables/alpha_summary.parquet',
 'results.tfopt/tables/beta_bound_pressure.parquet',
 'results.tfopt/tables/constraint_checks.parquet',
 'results.tfopt/tables/contributions.parquet',
 'results.tfopt/tables/convergence.parquet',
 'results.tfopt/tables/curve_similarity.parquet',
 'results.tfopt/tables/edge_contributions.parquet',
 'results.tfopt/tables/edge_weights.parquet']

Regulatory readout

tfopt.analysis.network_readout returns the analysis tables of a results folder: signed edge contributions, TF removal (knockout) effects with parameters held fixed, dominance, loads and β bound pressure. tfopt readout writes them as CSV.

from tfopt.analysis import network_readout

tables = network_readout(config.results_dir)
print(sorted(tables))
tables["regulatory_load"]
['alpha_summary', 'beta_bound_pressure', 'edge_contributions', 'fit_quality', 'knockout_effects', 'protein_phosphosite_components', 'regulatory_effect_summary', 'regulatory_load', 'target_dominant_regulators', 'warnings']
TF n_targets n_complete_edges complete total_load_auc_abs known_load_auc_abs activating_auc suppressing_auc frac_beta_at_bound absolute_auc_early absolute_auc_middle absolute_auc_late
0 TFA 3 3 True 1953.821783 1953.821783 1953.821783 0.0 0.0 20.923086 157.461697 1542.901531
1 TFB 3 3 True 1426.677283 1426.677283 1426.677283 0.0 0.0 25.288116 153.875545 1053.256689
2 TFC 1 1 True 726.685987 726.685987 726.685987 0.0 0.0 9.808757 53.913555 594.233193