Skip to content

TFOpt Documentation

TFOpt: TF effects on mRNA expression TFOpt: TF effects on mRNA expression

TFOpt estimates the contributions of transcription factors (TFs) to time-resolved mRNA expression. For every target mRNA it fits how much each of its TFs contributes (α), and for every TF how its protein series and its own phosphosite series combine into its activity (β). This documentation covers the Python modules in this repository:

  • tfopt/
  • processing/ (an alias of tfopt.processing)
  • config/
  • config_loader.py

TFOpt was originally developed by Philomina Lillie Normann and subsequently extended and refined by Abhinav Mishra, with improvements to computational performance, code consistency, and software architecture. TFOpt and KinOpt are architectural twins with distinct scientific formulations; both come from PhosKinTime. Cite TFOpt as doi:10.5281/zenodo.24690567 (all versions); release 0.2.0 is doi:10.5281/zenodo.24690568. The metadata are in CITATION.cff.


Overview

TFOpt is organized around a TF-regulation optimization workflow:

  1. Prepare and check the input tables with tfopt.processing (or tfopt validate).
  2. Fit the TF weights (α) and the TF protein and phosphosite weights (β) with tfopt.local (tfopt run).
  3. Review fitted outputs with tfopt.fitanalysis and the regulatory readout of tfopt.analysis.
  4. Inspect feasibility and the KKT conditions with tfopt.optimality.
  5. Load runtime settings from a config.toml through config_loader.py and tfopt.api.load_config.

The model, the constraints and the solver options are described in TF Optimization; the choice of each TF's base series and the time alignment in TF Base Series.


Package Areas

tfopt

  • tfopt.api is the library: load_config, RunConfig, validate_inputs, run, read_results. The command line and the GUI call it.
  • tfopt.local runs the constrained optimization. The default method is SciPy SLSQP with the sum-to-one constraints and the bounds as exact constraints and analytic JAX gradients (scipy-slsqp), with 64 starts. The JAXopt methods are approximate options for this problem.
  • tfopt.fitanalysis contains the post-fit figures and the workbook, regulatory, curve and network helpers.
  • tfopt.analysis returns the regulatory readout and the curve similarity of a results folder as tables.
  • tfopt.optimality checks feasibility and the KKT conditions of a fit.
  • tfopt.bundle writes and checks the run bundle; tfopt.examples writes the synthetic example project; tfopt.cli is the tfopt command; tfopt.app is the GUI.

No evolutionary optimization is part of TFOpt.

processing

tfopt.processing checks the input tables and maps TF → target edges; processing at the repository root is an alias kept for scripts in a clone. See Processing & Mapping.

config and config_loader.py

config.logconf sets up logging; config.cli is a small command wrapper. config_loader.py finds and loads the config.toml of a run (--config, TFOPT_CONFIG, else the clone's) and merges mode-specific overrides.


Installing TFOpt

pixi install            # in a clone; `pip install tfopt` once a release is published

Use cases

Each path below runs on the synthetic example that ships with TFOpt: tfopt example <folder> writes a config.toml and three small input files generated from a fixed seed (four TFs, four targets: a TF with a protein row and sites, one with a protein row only, one with sites but no protein row, whose mRNA is used, and one with no series, which is dropped). The targets are computed from known α and β, so a fit recovers them; the values are not biology. All three are run by the test suite exactly as shown here.

1. The command line

# Write the synthetic example project (config.toml, data/input1.csv, data/input3.csv, data/input4.csv)
tfopt example my-project
cd my-project

# Check the inputs against the configured time grids, then fit (64 starts by default; the example's config.toml uses 4)
tfopt validate --config config.toml
tfopt run --config config.toml --prediction-transform clip

# The same fit with tfopt-local (its options use underscores, as in earlier versions)
tfopt-local --config config.toml --prediction_transform clip

# Every run writes a run bundle; check it against the contract and its hashes
tfopt bundle --check results/results.tfopt.zip

# Regulatory readout tables and curve similarity as CSV
tfopt readout results --out results/readout
tfopt similarity results --out results/curve_similarity.csv

tfopt run and tfopt-local read a config.toml (the one given with --config, else TFOPT_CONFIG, else the clone's) and accept overrides on the command line. See the Command line page for every subcommand and option.

2. As a library

from tfopt import api
from tfopt.bundle import check_bundle
from tfopt.examples import write_example

# 1. Inputs: the synthetic example (or your own config.toml / input1.csv / input3.csv / input4.csv)
config_file = write_example("my-project")

# 2. Configure: config.toml plus overrides (or build api.RunConfig(input1=..., input3=..., input4=..., results_dir=...,
#    time_points=..., ms_time_points=...); the time grids have no default)
config = api.load_config(config_file, n_starts=4, prediction_transform="clip", plots=False)

# 3. Check the inputs
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(report.checks[["check", "status", "count"]])
if not report.ok:
    raise SystemExit("fix the inputs first")

# 4. Run (writes config.results_dir and the run bundle)
result = api.run(config, progress=lambda done, total, outcome: print(f"start {done}/{total}: {outcome.fun:.6g}"))
print("best objective", result.best_objective, "selected start", result.selected_start, "accepted", result.accepted)
print(result.kkt.conditions)

# 5. Read the results
results = api.read_results(config.results_dir)
alpha = results.sheets["Alpha Values"]  # mRNA, TF, Value
beta = results.sheets["Beta Values"]  # TF, PSite, Value, Source
print(alpha.head())
print("bundle ok:", check_bundle(result.bundle).ok)

api.run writes the same outputs as the command line, including the run bundle; see the API Reference and the Run bundle schema.

3. A complete script

run_tfopt.py (download) fits three CSV files without a config.toml, writes the results, the run bundle and the regulatory readout tables, and checks the bundle:

#!/usr/bin/env python3
"""Fit TFOpt to three CSV files and write the results, a run bundle and the regulatory readout.

Usage:
    python run_tfopt.py                                     # the synthetic example shipped with TFOpt
    python run_tfopt.py --input1 input1.csv --input3 input3.csv --input4 input4.csv --out results \\
        --time-points 4 8 15 30 60 120 240 480 960 --ms-time-points 0 0.5 0.75 1 2 4 8 16 30 60 120 240 480 960

The two time grids (minutes of input3's and input1's columns) are required with your own files: TFOpt has no built-in
time grid. Every other setting not given here has the default of ``tfopt.api.RunConfig``; no config.toml is needed.
"""
import argparse
from pathlib import Path

from tfopt import api
from tfopt.analysis import network_readout
from tfopt.bundle import check_bundle
from tfopt.examples import example_grids, example_inputs


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--input1", type=Path, default=None, help="TF protein and phosphosite series CSV")
    p.add_argument("--input3", type=Path, default=None, help="mRNA series CSV")
    p.add_argument("--input4", type=Path, default=None, help="TF -> target edges CSV (Source, Target)")
    p.add_argument("--time-points", type=float, nargs="+", default=None, help="RNA times of input3's columns (min)")
    p.add_argument("--ms-time-points", type=float, nargs="+", default=None, help="MS times of input1's columns (min)")
    p.add_argument("--out", type=Path, default=Path("tfopt_results"), help="results folder")
    p.add_argument("--n-starts", type=int, default=4, help="multistart starts (TFOpt's default is 64)")
    p.add_argument("--prediction-transform", choices=["clip", "none", "softplus"], default="clip")
    p.add_argument("--plots", action="store_true", help="also draw the per-target and fit-analysis plots")
    args = p.parse_args()
    inputs = (args.input1, args.input3, args.input4)
    if all(x is None for x in inputs):
        example = example_inputs(args.out / "example_inputs")  # generated, not real data
        args.input1, args.input3, args.input4 = example["input1"], example["input3"], example["input4"]
        args.ms_time_points, args.time_points = example_grids()
    elif any(x is None for x in inputs) or args.time_points is None or args.ms_time_points is None:
        p.error("give --input1, --input3, --input4, --time-points and --ms-time-points (or none, for the example)")

    config = api.RunConfig(input1=args.input1, input3=args.input3, input4=args.input4, results_dir=args.out,
                           time_points=args.time_points, ms_time_points=args.ms_time_points,
                           n_starts=args.n_starts, prediction_transform=args.prediction_transform,
                           plots=args.plots, fit_analysis=args.plots)

    report = api.validate_inputs(config.input1, config.input3, config.input4, ms_time_points=config.ms_time_points,
                                 time_points=config.time_points)
    for row in report.checks.itertuples():
        print(f"[{row.status}] {row.check} {row.detail}")
    if not report.ok:
        raise SystemExit("the inputs do not pass the checks")

    result = api.run(config, progress=lambda done, total, o: print(f"  start {done}/{total} finished"))
    print(f"best objective {result.best_objective:.8g} (start {result.selected_start}; "
          f"{'accepted' if result.accepted else 'NOT accepted'})")
    print(result.kkt.conditions.to_string(index=False))

    readout = args.out / "readout"
    readout.mkdir(exist_ok=True)
    for name, table in network_readout(args.out).items():
        table.to_csv(readout / f"{name}.csv", index=False)

    check = check_bundle(result.bundle)
    print(f"workbook {result.workbook}")
    print(f"run bundle {result.bundle} ({'valid' if check.ok else 'INVALID'})")
    print(f"readout tables in {readout}")


if __name__ == "__main__":
    main()
python run_tfopt.py                                          # the synthetic example
python run_tfopt.py --input1 input1.csv --input3 input3.csv --input4 input4.csv --out results \
    --time-points 4 8 15 30 60 120 240 480 960 --ms-time-points 0 0.5 0.75 1 2 4 8 16 30 60 120 240 480 960

With your own files the two time grids must be given: TFOpt has no built-in time grid.

4. The guided GUI

tfopt-app opens a step-by-step GUI in the browser (inputs, validation, configuration, run, results); see The TFOpt app.

5. Tutorials

Jupyter notebooks, executed when this site is built: from the input format, the parameter layout and the objective to a full run, its diagnostics and KKT conditions, and the library API with the run bundle; see Tutorials.

See the Configuration Reference for every setting.