TFOpt Optimization Package
The tfopt package contains the transcription-factor regulation optimization workflow.
Model
For each target mRNA j in input3 with TFs $i \in \mathcal{T}_j$ from input4:
$$ \hat R_j(t) = \max\Big(0,\ \sum_{i\in\mathcal{T}j} \alpha\, A_i(t)\Big), \qquad A_i(t) = \beta_{i0}\, X_i(t) + \sum_{s\in\mathcal{S}i} \beta(t) $$}\, S_{is
- $X_i(t)$ is the base series of TF i: its
input1protein row (empty Psite) or, without one, itsinput3mRNA (logged). A TF with neither is excluded with its edges (logged). $S_{is}(t)$ are the TF's owninput1phosphosite rows (S_/T_/Y_). input1 series are taken at the RNA times by actual time. See TF Base Series for the choice of $X_i$ and the time alignment (T6/T6c). - Constraints: $0 \le \alpha_{ji} \le 1$ with $\sum_i \alpha_{ji} = 1$ for every target, over its real edges only
(padded regulator slots are fixed to zero and never absorb α); $\beta$ between
lower_boundandupper_boundwith $\beta_{i0} + \sum_s \beta_{is} = 1$ for every TF. β may be negative. A TF without sites has a single β fixed at 1. - The objective is the loss between the observed target series and $\hat R_j(t)$ at the RNA times; the default is
loss_type5 (MSE plus an elastic-net penalty on β, see Metrics). The clip at zero (the defaultprediction_transform) is the same function in the objective and in the Estimated sheet.
The parameter vector is α (target-major, padded to the largest regulator count) followed by β (TF-major: the TF-level term first, then its sites).
This is a local nonconvex problem. A feasible converged fit is not a proof of a unique or global optimum.
Package Structure
tfopt/
├── __init__.py # enables JAX float64; __version__
├── api.py # the library: RunConfig, load_config, validate_inputs, run, read_results
├── cli.py # the `tfopt` command
├── analysis/ # regulatory readout, curve similarity, model diagrams (tables from a results folder)
├── app/ # the GUI (`tfopt-app`)
├── bundle/ # run bundles: make_bundle, check_bundle, the contract
├── examples/ # the synthetic example project (generated, no data shipped)
├── fitanalysis/
│ ├── __main__.py
│ ├── helpers/ # fit-analysis figures (Plotter)
│ ├── workbook.py, regulatory.py, curves.py, networks.py, figures.py, metrics.py
├── local/
│ ├── __main__.py # `tfopt-local`
│ ├── config/
│ ├── exporter/
│ ├── objfn/
│ ├── opt/ # optrun.py (multistart, JAXopt methods), slsqp.py (scipy-slsqp), workers.py
│ ├── optcon/ # filter.py (load and filter), construct.py, feasibility.py (ParameterGeometry)
│ └── utils/
├── optimality/
│ ├── KKT.py # feasibility and projected stationarity
│ └── kkt_diagnostics.py
└── processing/ # cleanup.py, map.py, tfseries.py
tfopt.local
tfopt.local runs the constrained optimization. It contains:
- The objective and the prediction (JAX,
jax.numpy, float64) inobjfn:objective_,objective_wrapper,compute_predictions, with the seven losses. - Loading, filtering and the fixed arrays in
optconandutils, and the parameter geometry (ParameterGeometry: groups, bounds, projection, violation) inoptcon.feasibility. - The solvers and the multistart in
opt(see Solvers). - Export helpers in
exporter: workbook, plots, LaTeX tables andreport.html.
Run it with:
pixi run tfopt run --config config.toml # or: tfopt-local --config config.toml
Outputs (in paths.results_dir)
| Path | Content |
|---|---|
tfopt_results.xlsx |
Sheets Alpha Values (mRNA, TF, Value), Beta Values (TF, PSite, Value, Source), Residuals, Observed, Estimated (mRNA, x1 … xN), Optimization Results (Metric, Value), KKT Diagnostics, KKT Multipliers, Prediction Check (mRNA, min_prediction, negative_points, negative) |
multistart_summary.csv |
Objective, success, constraint residual, acceptance, seed label and KKT residuals of every start |
multistart_params.npz |
Parameter vector of every start |
diagnostics.json |
Data loss, regularization, constraint penalty and total objective as separate fields; feasibility, stationarity, KKT and solver status of the selected start |
run_config.json |
Resolved configuration, seeds, versions, git commit, input sha256s, selected start, KKT verdict |
multistart_fun_vs_rank_runtime.png, per-target folders, fit-analysis figures |
Plots (see Plotting) |
report.html, tfopt_model_latex.tex |
Report of all plots and tables; LaTeX tables and figure references (no TeX compiler needed) |
logs/ |
Run log |
<results folder name>.tfopt.zip |
The run bundle |
In Beta Values, a blank PSite is the TF-level row; its Source gives the series that β multiplies (protein,
mrna, or first_site in the legacy control); site rows read site. The workbook is copied into
paths.ode_data_dir only with copy_to_ode_data_dir.
Solvers
The default scipy-slsqp runs SciPy SLSQP with the exact equality constraints (Σα = 1 per target over its real edges,
Σβ = 1 per TF) and the bounds, with the objective gradient from JAX and the exact Jacobian of the linear constraints;
finite differences are not used. Starts run in parallel worker processes (n_jobs, threads_per_worker); each start
keeps its draw, and parallel results are identical to sequential ones.
The JAXopt methods remain available and are approximate for the production problem. At a projected-gradient iterate on
the shipped inputs, the Hessian restricted to the feasible directions has eigenvalues from 1.8e-6 to 1.16 (condition
number about 6.5e5, one slightly negative eigenvalue); projected-gradient, accelerated projected-gradient and
L-BFGS-B did not converge at tol 1e-7, while scipy-slsqp converged with the KKT conditions verified (record of
DECISIONS_T6, diagnostics_t6/T6_SOLVER_REPORT.md).
lbfgsboptimizes box variables through a sequential bounded allocation, which keeps the groups exact. Success requires solver convergence and an original-parameter projected-gradient infinity norm ≤tol, with finite gradients and feasible parameters. If the box solver converges at a collapsed stick while the original problem is not stationary, an explicit ProjectedGradient refinement runs on the original groups with its ownmaxiterbudget; the result recordsrefinement_method,refinement_nit,solver_errorandprojected_gradient_inf. Failed or nonstationary refinement cannot report success.projected-gradientprojects each bounded affine-sum group;non-negativerestricts β to ≥ 0;unconstraineduses LBFGS and reports any resulting infeasibility.- MAE, the L1 part of the elastic net and the clip at zero are nonsmooth; they are not silently smoothed. The
quasi-Newton methods on losses 1 and 5 need
allow_nonsmooth = true.
Multistart selection prefers accepted starts (success, constraint residual ≤ 1e-10, KKT verdict), then feasibility and success; within a class the objective precedes sub-tolerance constraint residuals, and infeasible results are ranked by their violation first. See Configuration.
tfopt.api
The library behind the command line and the GUI: load_config (a config.toml plus overrides → RunConfig),
validate_inputs (the checks of tfopt validate, returning a ValidationReport with checks, coverage and the
edges and targets a run would drop), run (writes a results folder and returns a RunResult with the objective, the
selected start, success, accepted, the multistart table, the KKT report and the bundle path) and read_results.
See the API Reference and tutorial 10.
tfopt.fitanalysis
tfopt.fitanalysis draws the fit-analysis figures (α distributions, β bar plots, absolute residual heatmap, goodness
of fit, KLD, PCA, box plots, CDFs, time-wise residuals). It runs at the end of a run on that run's workbook; to run it
again on an existing results folder use python -m tfopt.fitanalysis --conf config.toml or
pixi run tfopt-fitanalysis. Its modules workbook, regulatory, curves, networks and figures hold the
calculations of the regulatory readout below.
tfopt.analysis: regulatory readout
tfopt.analysis.network_readout(results_dir) (tfopt readout) returns the regulatory analysis of a fitted results
folder as tables; it never refits the model.
Signals and reconstruction. A TF's effective signal is $A_i(t)$ above: its base series times the TF-level β plus
each phosphosite series times its signed β. A target contribution is $\alpha_{ji} A_i(t)$; the target prediction is
the clip of the sum of these signed contributions. Individual TF effects and contributions are not clipped, and a
negative site term need not make the whole TF repressive. Raw input1 signals follow the workbook's Beta Source
column: protein is the TF's empty-Psite input1 row, mrna its input3 row, first_site its first S_/T_/Y_
row (legacy control); site rows use their own input1 row. input1 series are taken at the RNA times as the run took
them (ms_time_points, ms_alignment from run_config.json). Workbooks without a Source column (written before
T6) are read with the legacy rules. The inputs default to the paths the run recorded; without input1, signal
reconstruction and removal effects are unavailable (reported as warnings) while the workbook tables remain.
A missing, too-short or non-finite required signal makes that TF incomplete: the affected reconstructions, removal effects and total load are NaN, never zero. Only a zero coefficient permits a zero term without its series. Complete coverage is reported separately from agreement with the workbook estimate (reconstruction mismatch).
Time, load and dominance. Workbook columns x1 … xN are placed on the run's RNA grid (time_points of
run_config.json, or passed explicitly: there is no built-in grid). AUCs use actual minutes. Signed AUC keeps
activation and repression apart; absolute contribution AUC measures load without cancellation. TF load sums the
absolute edge AUC over its targets; breadth counts targets with positive α. β bound pressure checks each configured
lower and upper bound separately. Dominance is a TF's share of the integrated absolute contributions to a target;
early, middle and late windows use non-overlapping sample indices (--early, --late); a window with too few
samples is empty, and a single-sample window uses the absolute sample value for dominance. Window AUCs integrate only
within each window, so they need not sum to the full-series AUC. An all-zero signal has no dominant TF.
TF removal with fixed parameters. Removal sets one TF's contribution to zero and recomputes the clipped
prediction with all parameters held fixed (not a refit). α renormalization is off by default (--renormalize-alpha).
Delta AUC is baseline clipped AUC minus removal clipped AUC: positive means removal lowers the predicted expression.
These are computational sensitivity measures, not experimental evidence of causality.
tfopt.analysis.curve_similarity gives the discrete Fréchet distance per target (see
Metrics); tfopt.analysis.diagrams draws the model and constraint diagrams
(tfopt diagram).
tfopt.optimality
tfopt.optimality.KKT.diagnostics measures the constraint violation and the projected-gradient infinity norm on the
actual bounded affine groups (a first-order stationarity measure). tfopt.optimality.kkt_diagnostics estimates the
Lagrange multipliers and reports the four KKT residuals with tolerances and verdicts; see
Metrics. Neither is a second-order or global optimality certificate.