API Reference
Generated from the docstrings of every module in the repository's Python packages. Each section lists a package and
all its submodules. The top-level processing package of a clone is an alias of tfopt.processing and is documented
there.
The public entry points:
| Task | Module |
|---|---|
| Load a configuration, check inputs, run, read results | tfopt.api (load_config, RunConfig, validate_inputs, run, read_results) |
| Write or check a run bundle | tfopt.bundle (make_bundle, check_bundle, load_contract) |
| Regulatory readout and curve similarity | tfopt.analysis (network_readout, load_run, curve_similarity) |
| Feasibility and KKT diagnostics | tfopt.optimality.KKT, tfopt.optimality.kkt_diagnostics |
| The model and the solvers | tfopt.local.objfn.minfn, tfopt.local.opt.optrun, tfopt.local.opt.slsqp |
| TF base series and time alignment | tfopt.processing.tfseries |
| The synthetic example | tfopt.examples (write_example, example_inputs, example_tables) |
| The command line and the GUI | tfopt.cli, tfopt.local.__main__, tfopt.app |
tfopt
tfopt
TFOpt: transcription-factor regulatory modeling.
Originally developed by Philomina Lillie Normann; extended and refined by Abhinav Mishra.
_version
_version()
The version: pyproject.toml in a clone, else the installed package metadata (as kinopt.version).
_exit
Clean exit for the console entry points (tfopt, tfopt-local, tfopt-app).
Copied from KinOpt 0.11.0 (kinopt/_exit.py), the same authors and licence. TFOpt writes Parquet with PyArrow (the run bundle), so it is exposed to the same abort.
A native library can abort the interpreter during its own C++ teardown after all work is done ("terminate called
without an active exception", exit status 134; KinOpt issue #13). PyArrow (pandas' string storage, the run bundle) keeps
native threads that are torn down at that point. The entry points therefore end like this: flush the output, run
Python's exit handlers (logging, joblib/loky and multiprocessing cleanup), then os._exit with the exit status,
which skips the native static destructors. Nothing of the run is lost: every file is closed by then.
run_and_exit
run_and_exit(main, *args) -> None
Call main(*args) and end the process with its exit status, without native teardown.
The status is main's return value if it is an int, else 0; SystemExit keeps its code (a message is
printed to stderr and gives 1); any other exception prints its traceback and gives 1; Ctrl+C gives 130.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
main
|
callable
|
The command's main function. |
required |
*args
|
Its arguments. |
()
|
analysis
Analyses of a TFOpt results folder as library functions returning tidy tables (as kinopt.analysis).
network_readout(results_dir) gives the signed regulatory contributions, TF removal (knockout) effects,
dominance, loads, bound pressure and network edges (tfopt.fitanalysis.regulatory.analyze);
curve_similarity(observed, estimated, time_points) the discrete Fréchet distance per target
(tfopt.fitanalysis.curves). load_run(results_dir) reads a results folder with the settings its run recorded
in run_config.json (inputs, grids, β bounds, alignment).
Run
dataclass
A results folder: its workbook (parsed), time grids and recorded settings.
load_run
load_run(results_dir, out_file='tfopt_results.xlsx', time_points=None) -> Run
Read a results folder (workbook and run_config.json). The RNA grid is the one the run recorded in
run_config.json, else time_points (required then: TFOpt has no built-in grid).
network_readout
network_readout(results_dir, input1=None, input3=None, *, bound_tol=1e-06, n_early=3, n_late=3, renormalize=False) -> dict
Every regulatory analysis table of a results folder, as tidy DataFrames (keyed by table name).
input1/input3 default to the paths the run recorded (run_config.json); without input1 the signal reconstruction and knockouts are unavailable (warnings), the workbook estimates remain.
curve_similarity
curve_similarity(observed, estimated, time_points=None, normalize_time=True) -> pd.DataFrame
Discrete Fréchet distance between observed and estimated series per target (rows), with a summary row set
in DataFrame.attrs['summary'].
diagrams
Model diagrams of TFOpt's contribution and constraint structure (tfopt diagram).
Adapted from the two TF-specific functions in KinOpt's former scripts/make_kinopt_diagram.py
(bibymaths/KinOpt, 78fb06edc2040b8a1716d3917962279c30c7b9c6); formerly TFOpt's scripts/make_tfopt_diagram.py.
Rendering needs Graphviz and pydot (optional: pixi run -e viz); with outfile=None the DOT text is returned
without a renderer.
make_tfopt_diagram_dot
make_tfopt_diagram_dot(outfile: str | None = 'tfopt_diagram.png', *, fmt: str | None = None, engine: str = 'dot', dpi: int = 300, rankdir: str = 'TB', tf_psites: int | list[int] = 1, n_tfs: int = 2, lower_bound: float | None = None, upper_bound: float | None = None)
Adapt the pinned reference make_tfopt_diagram_dot to current TFOpt semantics.
Pass outfile=None to obtain DOT without requiring a renderer.
make_tfopt_constraints_graph_dot
make_tfopt_constraints_graph_dot(outfile: str | None = 'tfopt_constraints.png', *, fmt: str | None = None, engine: str = 'dot', dpi: int = 300, rankdir: str = 'TB', tf_psites: int | list[int] = 2, n_tfs: int = 2, lower_bound: float | None = None, upper_bound: float | None = None)
Adapt the pinned reference make_tfopt_constraints_graph_dot to current TFOpt semantics.
Pass outfile=None to obtain DOT without requiring a renderer.
api
TFOpt as a library: load a configuration, check the inputs, run the fit, read the results (as kinopt.api).
The command line (tfopt run, tfopt-local) and the GUI (tfopt-app) call these same functions::
from tfopt import api
config = api.load_config("config.toml", n_starts=8) # or api.RunConfig(input1=..., input3=..., ...)
report = api.validate_inputs(config.input1, config.input3, config.input4)
result = api.run(config) # writes config.results_dir
results = api.read_results(config.results_dir)
Nothing is read from config.toml at import, and run takes every path and setting from the RunConfig.
TFOpt's model (DECISIONS_T6): target mRNA (input3) = Σ_TF α · (β0·X_TF + Σ_s β_s·S_TF,s), with X_TF the TF's input1
protein row (else its input3 mRNA), S_TF,s its own input1 sites, the TF→target edges from input4.
RunConfig
dataclass
Every setting of a TFOpt run. Defaults are those of the shipped config.toml.
Attributes:
| Name | Type | Description |
|---|---|---|
input1 |
Path
|
TF protein and phosphosite series ( |
input3 |
Path
|
mRNA series ( |
input4 |
Path
|
Regulation edges ( |
results_dir |
Path
|
Output folder of the run. |
method |
str
|
|
n_starts |
int
|
Number of multistart starts. |
jitter_scale |
float
|
Jitter of the starting values, as a fraction of each bound's span. |
start_seed |
int
|
Seed of the starting values (α, β) drawn before the multistart. |
seed |
int
|
First seed of the multistart; start i uses |
p_random |
float
|
Probability that a start is drawn uniformly within the bounds instead of jittered. |
loss_type |
int
|
0 MSE, 1 MAE, 2 soft L1, 3 Cauchy, 4 arctan, 5 elastic net, 6 Tikhonov. |
lower_bound |
float
|
Lower bound of β. |
upper_bound |
float
|
Upper bound of β. |
prediction_transform |
str
|
|
tf_protein_source |
str
|
|
ms_alignment |
str
|
|
time_points |
list[float]
|
RNA grid (input3 columns), minutes. Required: TFOpt has no built-in grid. |
ms_time_points |
list[float]
|
MS grid (input1 columns), minutes. Required. |
out_file |
str
|
Name of the results workbook. |
maxiter |
int
|
Solver iteration cap. |
tol |
float
|
Solver tolerance (SLSQP ftol). |
n_jobs |
int
|
Parallel workers of the multistart (-1: all cores; 1: sequential in this process). |
threads_per_worker |
int
|
XLA/OpenMP/BLAS threads of each worker. |
allow_nonsmooth |
bool
|
Allow the quasi-Newton JAXopt methods on the nonsmooth losses 1 and 5. |
feasibility_tol |
float
|
Constraint residual up to which a fit counts as feasible (success). |
acceptance_tol |
float
|
Constraint residual up to which a start is accepted (with success and KKT). |
plots |
bool
|
Draw the per-target, multistart and fit-analysis plots. |
fit_analysis |
bool
|
Write the fit-analysis figures ( |
report |
bool
|
Group per-target files into folders and write |
copy_to_ode_data_dir |
Path | None
|
Also copy the workbook into this folder (never over an existing file). |
bundle |
bool
|
Write the run bundle |
workbook
property
workbook: Path
Path of the results workbook.
to_dict
to_dict() -> dict
Return the configuration as JSON-serializable values (paths as strings).
replace
replace(**overrides) -> 'RunConfig'
Return a copy with some settings changed (unknown names raise TypeError).
ValidationReport
dataclass
Result of validate_inputs.
Attributes:
| Name | Type | Description |
|---|---|---|
checks |
DataFrame
|
One row per check: 'check', 'status' ( |
coverage |
dict
|
Counts: targets, targets_used, tfs, tfs_protein, tfs_mrna, tfs_first_site, tfs_excluded, edges, edges_used, input1_rows, input3_rows, input4_rows. |
skipped |
DataFrame
|
Edges and targets a run would drop ( |
errors
property
errors: DataFrame
The checks with status error.
ok
property
ok: bool
True if no check failed with an error.
RunResult
dataclass
Result of run.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
RunConfig
|
The configuration used. |
results_dir |
Path
|
Output folder. |
workbook |
Path
|
Results workbook. |
best_objective |
float
|
Objective of the selected fit. |
selected_start |
int
|
Start id of the selected fit. |
success |
bool
|
The selected fit converged and is feasible. |
accepted |
bool
|
Success, constraint residual <= 1e-10 and the KKT verdict. |
multistart |
DataFrame
|
One row per start (multistart_summary.csv). |
kkt |
object
|
KKT diagnostics of the selected fit ( |
diagnostics |
dict
|
The contents of diagnostics.json. |
bundle |
Path | None
|
The run bundle (zip), if written. |
Results
dataclass
A results folder read back by read_results.
Attributes:
| Name | Type | Description |
|---|---|---|
results_dir |
Path
|
The folder. |
workbook |
Path
|
The results workbook. |
sheets |
dict[str, DataFrame]
|
Every sheet of the workbook. |
multistart |
DataFrame
|
The multistart summary (one row per start). |
run_config |
dict | None
|
|
diagnostics |
dict | None
|
|
best_objective |
float
|
The smallest objective over the starts. |
load_config
load_config(path=None, **overrides) -> RunConfig
Read a RunConfig from a config.toml ([paths], [tfopt] and [tfopt.modes.local]).
Relative paths in [paths] are resolved against the folder of the config file. Keys the file does not set
get LEGACY_DEFAULTS (the earlier tfopt-local behaviour), then the RunConfig defaults. jitter_frac is
accepted for jitter_scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | None
|
The config.toml. If None, the one |
None
|
**overrides
|
Settings to change, by |
{}
|
Returns:
| Type | Description |
|---|---|
RunConfig
|
The resolved configuration. |
Raises:
| Type | Description |
|---|---|
TypeError
|
An override is not a |
ValueError
|
A setting has an unsupported value, or both jitter_scale and jitter_frac are set. |
validate_inputs
validate_inputs(input1, input3, input4, *, ms_time_points, time_points, tf_protein_source='protein_then_mrna', ms_alignment='by_time') -> ValidationReport
Check input1, input3 and input4 before a run: columns, values, duplicates, coverage and what a run drops.
The checks mirror what tfopt.local requires: numeric, finite time series with as many columns as the
configured grids; unique (GeneID, Psite) rows in input1; TF and target identifiers in input4. A TF without a
base series (no input1 protein row and no input3 mRNA) is dropped with its edges (warning); a target without
an input3 row, or without a regulator with a series, is dropped (warning).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input1, input3, input4
|
str | Path | DataFrame
|
The inputs. |
required |
ms_time_points, time_points
|
list[float]
|
MS and RNA grids from the configuration (required). |
required |
tf_protein_source, ms_alignment
|
str
|
As the run settings. |
required |
Returns:
| Type | Description |
|---|---|
ValidationReport
|
Checks, coverage and what a run would skip. |
_git_info
_git_info()
Commit, branch and dirty flag of the code, if it runs from a git clone (else None values).
run
run(config: RunConfig, progress=None, quiet=False) -> RunResult
Run the fit with a RunConfig and write the results to config.results_dir.
Writes the same outputs as tfopt-local: the workbook (Alpha Values, Beta Values with Source, Residuals,
Observed, Estimated, Optimization Results, KKT Diagnostics, KKT Multipliers), multistart_summary.csv,
multistart_params.npz, diagnostics.json and, if enabled, the plots, fit-analysis figures, LaTeX tables and
report.html; plus run_config.json (resolved configuration, seeds, versions, git commit, input sha256s,
selected start, KKT verdict) and the log in <results_dir>/logs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RunConfig
|
The run settings. |
required |
progress
|
callable | None
|
Called as |
None
|
quiet
|
bool
|
Show only warnings and errors on the console; the log file is complete either way. |
False
|
Returns:
| Type | Description |
|---|---|
RunResult
|
Summary of the run (also when the selected fit is not accepted; check |
read_results
read_results(results_dir, out_file='tfopt_results.xlsx') -> Results
Read a results folder written by run (or by tfopt-local).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_dir
|
str | Path
|
The results folder. |
required |
out_file
|
str
|
Name of the workbook. |
'tfopt_results.xlsx'
|
Returns:
| Type | Description |
|---|---|
Results
|
Workbook sheets, multistart summary and provenance. |
app
tfopt-app: a guided GUI for TFOpt in the browser (as KinOpt's kinopt-app).
Steps: inputs (input1, input3, input4 or the example; the time grids) → validation → configuration → run → results
(tables and the run bundle). The server is the Python standard library, the page is plain HTML/JS/CSS shipped in the
package; it calls the same library functions as the command line (tfopt.api). See tfopt.app.server for the
security measures.
Session
State of one GUI session: the working folder, the token, the uploads and the runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workdir
|
str | Path
|
The working folder; created if missing. Nothing is written outside it. |
required |
max_upload_bytes
|
int
|
Largest accepted upload. |
DEFAULT_MAX_UPLOAD_BYTES
|
token
|
str | None
|
Session token; a random one by default. |
None
|
config
|
str | Path | None
|
A config.toml whose settings (time grids included; not its paths) are the GUI's
defaults and the base of every run ( |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
resolve
resolve(relative) -> Path
Resolve a path given by the browser inside the working folder.
Raises:
| Type | Description |
|---|---|
PathError
|
The path is absolute or leaves the working folder ( |
check_upload
check_upload(role: str, filename: str, length: int) -> Path
Check an upload before reading its body and return where it will be stored.
Raises:
| Type | Description |
|---|---|
UploadError
|
Unknown role (400), file type not allowed for the role (415) or too large (413). |
save_upload
save_upload(role: str, filename: str, data: bytes) -> str
Store an uploaded file as inputs/<role file> and return its path relative to the working folder.
files
files() -> list
The uploaded files in the working folder's inputs/ (relative paths).
config_settings
config_settings(relative='inputs/config.toml') -> dict
Read the settings of a config.toml of the working folder with tfopt.api.load_config.
Its paths are ignored (the GUI chooses them in the working folder); keys the file does not set get the values
load_config gives them (as tfopt run --config).
Raises:
| Type | Description |
|---|---|
ValueError
|
The file is not valid TOML, lacks a time grid or has an unsupported value. |
use_example
use_example() -> dict
Copy the synthetic example (tfopt.examples) into inputs/ and return its files and settings.
The example project is written once to <workdir>/example/ (tfopt example); its data replace the files
in inputs/. The settings (time grids included) are those of its config.toml.
defaults
defaults() -> dict
Default settings (those of tfopt.api.RunConfig), grouped into basic and advanced, with the choices.
run_config
run_config(settings: dict, inputs=None, run_id=None)
Build the RunConfig of a run from the browser's settings (paths are chosen here, in the working folder).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
dict
|
RunConfig fields set by the browser; |
required |
inputs
|
dict | None
|
Paths of input1, input3 and input4 relative to the working folder. |
None
|
run_id
|
str | None
|
Folder name under |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
A setting is locked, unknown, of the wrong type or invalid, or a time grid is missing. |
validate
validate(inputs=None, settings=None) -> dict
Run tfopt.api.validate_inputs on the three inputs of the working folder, with the settings' grids,
TF protein source and MS alignment.
start_run
start_run(settings: dict, inputs=None) -> str
Validate the inputs, then start a run in a child process; return its id (the folder name under runs/).
Raises:
| Type | Description |
|---|---|
ValueError
|
A setting is invalid, or the inputs fail validation with these settings. |
PathError
|
An input does not exist. |
run_dir
run_dir(run_id) -> Path
The results folder of a run.
is_alive
is_alive(run_id) -> bool
True while the run's process is running.
status
status(run_id, log_lines=200) -> dict
State, progress, best objective so far and the end of the log of a run.
cancel
cancel(run_id) -> None
Stop a running run and its worker processes.
runs
runs() -> list
Every run of the session, newest first.
bundle_path
bundle_path(run_id) -> Path
The run bundle (<run id>.tfopt.zip) of a finished run.
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The run has not finished or wrote no bundle ( |
results
results(run_id) -> dict
The results of a finished run, read from its results folder with tfopt.api.read_results.
Returns:
| Type | Description |
|---|---|
dict
|
|
make_server
make_server(session: Session, port: int = 0) -> ThreadingHTTPServer
Create the GUI server for a session, bound to 127.0.0.1 (port 0: a free port chosen by the system).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The session (working folder, token, limits). |
required |
port
|
int
|
Port; 0 picks a free one. |
0
|
Returns:
| Type | Description |
|---|---|
ThreadingHTTPServer
|
Call |
url
url(httpd: ThreadingHTTPServer, session: Session) -> str
The URL to open, with the session token.
main
main(argv=None) -> int
Entry point of tfopt-app: start the server, print the URL with the token, open the browser.
backend
The GUI's backend: one session per tfopt-app start, bound to one working folder (as kinopt.app.backend).
Everything the GUI does goes through Session and calls the library functions the command line uses
(tfopt.api.load_config, tfopt.api.validate_inputs, tfopt.api.run, tfopt.api.read_results). Files are
only read from and written to the working folder: uploads go to <workdir>/inputs/ (input1.csv,
input3.csv, input4.csv and optionally config.toml), the example project to <workdir>/example/ and
runs to <workdir>/runs/<run id>/; paths from the browser are resolved against the working folder and refused if
they leave it.
TFOpt has no built-in time grid: the RNA grid (time_points, input3 columns) and the MS grid
(ms_time_points, input1 columns) come from the user, from an uploaded config.toml or from the example project.
A run executes in its own process (its own process group on POSIX), so it can be cancelled with its workers.
PathError
Bases: ValueError
A path from the browser leaves the working folder or names something not allowed.
UploadError
Bases: ValueError
An upload is refused; status is the HTTP status to answer with.
Session
State of one GUI session: the working folder, the token, the uploads and the runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workdir
|
str | Path
|
The working folder; created if missing. Nothing is written outside it. |
required |
max_upload_bytes
|
int
|
Largest accepted upload. |
DEFAULT_MAX_UPLOAD_BYTES
|
token
|
str | None
|
Session token; a random one by default. |
None
|
config
|
str | Path | None
|
A config.toml whose settings (time grids included; not its paths) are the GUI's
defaults and the base of every run ( |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
resolve
resolve(relative) -> Path
Resolve a path given by the browser inside the working folder.
Raises:
| Type | Description |
|---|---|
PathError
|
The path is absolute or leaves the working folder ( |
check_upload
check_upload(role: str, filename: str, length: int) -> Path
Check an upload before reading its body and return where it will be stored.
Raises:
| Type | Description |
|---|---|
UploadError
|
Unknown role (400), file type not allowed for the role (415) or too large (413). |
save_upload
save_upload(role: str, filename: str, data: bytes) -> str
Store an uploaded file as inputs/<role file> and return its path relative to the working folder.
files
files() -> list
The uploaded files in the working folder's inputs/ (relative paths).
config_settings
config_settings(relative='inputs/config.toml') -> dict
Read the settings of a config.toml of the working folder with tfopt.api.load_config.
Its paths are ignored (the GUI chooses them in the working folder); keys the file does not set get the values
load_config gives them (as tfopt run --config).
Raises:
| Type | Description |
|---|---|
ValueError
|
The file is not valid TOML, lacks a time grid or has an unsupported value. |
use_example
use_example() -> dict
Copy the synthetic example (tfopt.examples) into inputs/ and return its files and settings.
The example project is written once to <workdir>/example/ (tfopt example); its data replace the files
in inputs/. The settings (time grids included) are those of its config.toml.
defaults
defaults() -> dict
Default settings (those of tfopt.api.RunConfig), grouped into basic and advanced, with the choices.
run_config
run_config(settings: dict, inputs=None, run_id=None)
Build the RunConfig of a run from the browser's settings (paths are chosen here, in the working folder).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
dict
|
RunConfig fields set by the browser; |
required |
inputs
|
dict | None
|
Paths of input1, input3 and input4 relative to the working folder. |
None
|
run_id
|
str | None
|
Folder name under |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
A setting is locked, unknown, of the wrong type or invalid, or a time grid is missing. |
validate
validate(inputs=None, settings=None) -> dict
Run tfopt.api.validate_inputs on the three inputs of the working folder, with the settings' grids,
TF protein source and MS alignment.
start_run
start_run(settings: dict, inputs=None) -> str
Validate the inputs, then start a run in a child process; return its id (the folder name under runs/).
Raises:
| Type | Description |
|---|---|
ValueError
|
A setting is invalid, or the inputs fail validation with these settings. |
PathError
|
An input does not exist. |
run_dir
run_dir(run_id) -> Path
The results folder of a run.
is_alive
is_alive(run_id) -> bool
True while the run's process is running.
status
status(run_id, log_lines=200) -> dict
State, progress, best objective so far and the end of the log of a run.
cancel
cancel(run_id) -> None
Stop a running run and its worker processes.
runs
runs() -> list
Every run of the session, newest first.
bundle_path
bundle_path(run_id) -> Path
The run bundle (<run id>.tfopt.zip) of a finished run.
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The run has not finished or wrote no bundle ( |
results
results(run_id) -> dict
The results of a finished run, read from its results folder with tfopt.api.read_results.
Returns:
| Type | Description |
|---|---|
dict
|
|
_run_worker
_run_worker(config: dict, events, console: str) -> None
Run tfopt.api.run in a child process and report progress and the outcome on events.
_settings_of
_settings_of(path, label) -> dict
The settings of a config.toml (tfopt.api.load_config) without the paths the GUI chooses itself.
_constraint_checks
_constraint_checks(sheets, lower, upper, tol)
Constraints of the selected fit, measured on the workbook: |Σα − 1| per target and α in [0, 1]; |Σβ − 1| per
TF and β in [lower_bound, upper_bound]. passed: the residual is at most tol (feasibility_tol).
_check_type
_check_type(name, value, field) -> None
Refuse a setting whose JSON type does not match its RunConfig field.
_jsonable
_jsonable(v)
A JSON-safe scalar: NaN and NA as None, ±inf as a string, NumPy scalars as Python values.
_table
_table(df) -> dict
A DataFrame as {"columns": [...], "rows": [[...], ...]} with JSON-safe values.
server
The GUI's HTTP server: Python standard library only, loopback only, one random token per session (as kinopt-app).
Security (the machine may be shared with other users):
- binds 127.0.0.1 on a free port chosen by the system;
- every request must carry the session token, in the URL (
?token=) or theX-TFOpt-Tokenheader; it is compared in constant time and requests without it get 403; - the
Hostheader must name the loopback address (against DNS rebinding); - uploads: only the roles input1, input3, input4 (
.csv) and config (.toml), at mostSession.max_upload_bytes(checked from Content-Length before the body is read); - paths from the browser are resolved inside the working folder and refused if they leave it; settings that name files or folders cannot be set from the browser;
- responses carry
Referrer-Policy: no-referrer(the token is in the URL),X-Content-Type-Options: nosniff,X-Frame-Options: DENYand a Content-Security-Policy that allows only the app's own files.
_inputs
_inputs(body) -> dict
The input paths of a request body ({"inputs": {"input1": ..., ...}}); missing ones take the defaults.
make_server
make_server(session: Session, port: int = 0) -> ThreadingHTTPServer
Create the GUI server for a session, bound to 127.0.0.1 (port 0: a free port chosen by the system).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The session (working folder, token, limits). |
required |
port
|
int
|
Port; 0 picks a free one. |
0
|
Returns:
| Type | Description |
|---|---|
ThreadingHTTPServer
|
Call |
url
url(httpd: ThreadingHTTPServer, session: Session) -> str
The URL to open, with the session token.
bundle
TFOpt run bundles: one self-contained folder (or zip) per run, with its tables, inputs and provenance.
make_bundle(results_dir) writes <run>.tfopt/ (and optionally <run>.tfopt.zip) from a results folder;
check_bundle(path) validates a bundle against the contract (contracts/tfopt/1.0) and its manifest hashes.
The command line is tfopt bundle <results_dir> and tfopt bundle --check <bundle>. TFOpt's counterpart of
kinopt.bundle, for the TF model (mRNA targets, TF weights α, TF-component weights β with their Source).
BundleCheck
dataclass
Result of check_bundle.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True if there are no errors. |
errors |
list[str]
|
What is wrong (schema, hashes, files, tables). |
warnings |
list[str]
|
Things to note (e.g. inputs referenced, not copied). |
manifest |
dict | None
|
The parsed manifest. |
build_tables
build_tables(results_dir) -> tuple[dict, dict]
Assemble every bundle table from a results folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_dir
|
str | Path
|
A results folder written by |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The folder has no run_config.json (a run written before the library API). |
make_bundle
make_bundle(results_dir, out_dir=None, zip=False, max_input_bytes=DEFAULT_MAX_INPUT_BYTES) -> Path
Write a run bundle for a results folder (the folder's own files are not changed).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_dir
|
str | Path
|
A results folder written by |
required |
out_dir
|
str | Path | None
|
Bundle folder to write; default |
None
|
zip
|
bool
|
Also write |
False
|
max_input_bytes
|
int
|
Inputs larger than this are referenced by sha256 instead of copied. |
DEFAULT_MAX_INPUT_BYTES
|
Returns:
| Type | Description |
|---|---|
Path
|
The bundle folder, or the zip file with |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
The bundle folder already exists. |
check_bundle
check_bundle(path) -> BundleCheck
Check a run bundle (folder or .zip) against the contract and its manifest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The bundle folder (with manifest.json) or zip. |
required |
Returns:
| Type | Description |
|---|---|
BundleCheck
|
|
load_contract
load_contract() -> dict
Load the packaged contract.
Returns:
| Type | Description |
|---|---|
dict
|
|
validate_manifest
validate_manifest(manifest, schema, _root=None, _path='manifest') -> list[str]
Validate a manifest against the contract's JSON Schema, in plain Python.
Supports the keywords the contract uses: type, required, properties, additionalProperties
(boolean), items, enum, const, pattern, minimum, minItems and local $ref.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
The parsed manifest (or a part of it, recursively). |
required | |
schema
|
dict
|
The schema (or sub-schema). |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Error messages; empty if the manifest is valid. |
build
Build a TFOpt run bundle from a results folder (as kinopt.bundle.build, for TFOpt's model and outputs).
A run bundle follows phoskintime-vis's bundle conventions: a folder <run>.tfopt/ (optionally zipped to
<run>.tfopt.zip) with manifest.json at the root and the files under provenance/, tables/ (Parquet),
arrays/ (.npy) and resim/. The tables and their columns are defined by the contract
contracts/tfopt/1.0/tables.json; every table is written with the contract's dtypes, and null means missing
(never 0). TFOpt's model: mRNA_i(t) = transform(Σ_TF α_i,TF · (β_TF,0 · X_TF(t) + Σ_s β_TF,s · S_TF,s(t))).
_quiet
_quiet()
Suppress logging and stdout while the bundle re-runs analyses on a finished run.
_site
_site(value)
Phosphosite label, or None for a TF-level row (empty or NaN PSite).
_parameter_labels
_parameter_labels(observed, alpha, beta, n_params)
Labels of the parameter vector (as tfopt.api.run's KKT labels) and the rows of multistart_parameters.
α: per mRNA (Observed order) one slot per TF, padded to the widest mRNA; then β per TF (TF-level, then sites).
Returns (labels, rows) with rows (index, parameter, mrna, tf, component), or (None, None) if the
vector does not have that shape.
_analysis_table
_analysis_table(name, df: DataFrame) -> pd.DataFrame
An analysis table of tfopt.analysis with the contract's lowercase column names (PSite '' → null).
_verified_inputs
_verified_inputs(run_config) -> dict
Input name → path, for the inputs that still exist with the sha256 the run recorded.
_signals
_signals(run_config, workbook, inputs)
The series the model used for every β row, on the RNA grid: {(tf, site or ''): values} and their source.
_signal_tables
_signal_tables(run_config, results_dir, inputs) -> tuple[dict, pd.DataFrame]
tf_activity, contributions and reconstruction (TFOpt's model, in NumPy), and the resim tf_series.
_network_tables
_network_tables(edges: DataFrame, knockout: DataFrame) -> dict
network_edges and network_nodes from tfopt.fitanalysis.networks.build_network (contribution mode).
build_tables
build_tables(results_dir) -> tuple[dict, dict]
Assemble every bundle table from a results folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_dir
|
str | Path
|
A results folder written by |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The folder has no run_config.json (a run written before the library API). |
_typed_table
_typed_table(name: str, df: DataFrame, spec: dict) -> pa.Table
Cast a DataFrame to the contract's columns and dtypes (extra columns are kept as inferred).
make_bundle
make_bundle(results_dir, out_dir=None, zip=False, max_input_bytes=DEFAULT_MAX_INPUT_BYTES) -> Path
Write a run bundle for a results folder (the folder's own files are not changed).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_dir
|
str | Path
|
A results folder written by |
required |
out_dir
|
str | Path | None
|
Bundle folder to write; default |
None
|
zip
|
bool
|
Also write |
False
|
max_input_bytes
|
int
|
Inputs larger than this are referenced by sha256 instead of copied. |
DEFAULT_MAX_INPUT_BYTES
|
Returns:
| Type | Description |
|---|---|
Path
|
The bundle folder, or the zip file with |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
The bundle folder already exists. |
contract
The run-bundle contract (contracts/tfopt/1.0) and the bundle check (as kinopt.bundle.contract).
The contract has the format of phoskintime-vis's contracts/<producer>/<version>/: manifest.schema.json
(JSON Schema 2020-12 for manifest.json) and tables.json (tables, columns, dtypes, nullability, units). The
check validates a bundle (folder or .zip) in plain Python: the manifest against the schema (the subset of JSON
Schema the contract uses), every listed file's sha256 and size, no unlisted files, every contract table present or
listed in manifest.missing, and every table against tables.json (required columns present with their dtypes;
non-nullable columns without nulls; extra columns are allowed within a minor version).
BundleCheck
dataclass
Result of check_bundle.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True if there are no errors. |
errors |
list[str]
|
What is wrong (schema, hashes, files, tables). |
warnings |
list[str]
|
Things to note (e.g. inputs referenced, not copied). |
manifest |
dict | None
|
The parsed manifest. |
_Source
Read the files of a bundle folder or zip by their path relative to the bundle root.
load_contract
load_contract() -> dict
Load the packaged contract.
Returns:
| Type | Description |
|---|---|
dict
|
|
validate_manifest
validate_manifest(manifest, schema, _root=None, _path='manifest') -> list[str]
Validate a manifest against the contract's JSON Schema, in plain Python.
Supports the keywords the contract uses: type, required, properties, additionalProperties
(boolean), items, enum, const, pattern, minimum, minItems and local $ref.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
The parsed manifest (or a part of it, recursively). |
required | |
schema
|
dict
|
The schema (or sub-schema). |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Error messages; empty if the manifest is valid. |
check_bundle
check_bundle(path) -> BundleCheck
Check a run bundle (folder or .zip) against the contract and its manifest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The bundle folder (with manifest.json) or zip. |
required |
Returns:
| Type | Description |
|---|---|
BundleCheck
|
|
cli
The tfopt command: subcommands for running, checking and post-processing TFOpt (as the kinopt command).
tfopt run fits the model (the same as tfopt-local), tfopt validate checks the inputs. Every subcommand
calls the library functions of tfopt.api (and the other tfopt modules); see tfopt <subcommand> --help.
build_parser
build_parser() -> argparse.ArgumentParser
Return the argument parser of the tfopt command.
main
main(argv=None) -> int
Entry point of the tfopt command; returns the exit status.
console_main
console_main() -> None
Console script tfopt: main with a clean exit (tfopt._exit.run_and_exit).
examples
A small synthetic example project, shipped with TFOpt, for trying the command line, the library and the GUI.
write_example(folder) (or tfopt example <folder>) writes data/input1.csv (TF protein and phosphosite
series on the 14-point MS grid), data/input3.csv (mRNA series on the 9-point RNA grid) and data/input4.csv
(TF → target edges), with a config.toml using few starts, so a full run takes seconds. It shows every case of
TFOpt's model: a TF with a protein row and sites (TFA), with a protein row only (TFB), with sites but no protein row
(TFC: its mRNA is used, logged), and a TF with no series (TFD: excluded with its edge, logged). The targets G1–G4 are
computed from known α and β by the model itself, so a run can recover them. Values are generated from a fixed
seed; they illustrate the file formats, not biology. No data file is shipped.
example_grids
example_grids()
(ms_time_points, time_points) of the example project: read from its config.toml text (one source).
example_tables
example_tables()
Generate the example's input tables (input1, input3, input4) from a fixed seed.
Returns:
| Type | Description |
|---|---|
tuple[DataFrame, DataFrame, DataFrame]
|
input1 (uniform in [0.5, 2] on the MS grid), input3 (the targets G1–G4 from TRUE_ALPHA/TRUE_BETA at the RNA times, plus TFC's mRNA) and input4. |
example_inputs
example_inputs(folder) -> dict
Write input1.csv, input3.csv and input4.csv into folder; returns their paths.
write_example
write_example(folder, n_starts=4) -> Path
Write the example project (config.toml and data/) into folder; returns the config path.
Raises:
| Type | Description |
|---|---|
FileExistsError
|
|
fitanalysis
curves
Discrete Fréchet diagnostics, independent of fitting objectives.
discrete_frechet
discrete_frechet(first, second)
Euclidean discrete Fréchet distance with O(len(second)) working memory.
curve_similarity
curve_similarity(observed, estimated, time_points=None, normalize_time=True)
Align by mRNA; flag incomplete rows without imputation or finite ranks.
Time coordinates are normalized to [0,1] by default, preserving irregular spacing. Amplitudes are unchanged. Raw minutes can be requested explicitly.
figures
Publication-quality TF-specific readout figures, without optimizer imports.
helper
Compatibility import for the original fit-analysis API.
helpers
plotter
Plotter
A class to plot various analysis results from an Excel file.
load_data()
Loads data from the specified Excel file. Args: filepath (str): Path to the Excel file. savepath (str): Directory where the plots will be saved.
plot_alpha_distribution()
Plots the distribution of alpha parameter values grouped by transcription factors (TFs) using a strip plot.
plot_beta_barplots()
Processes the beta values DataFrame and creates a separate bar plot for each unique transcription factor (TF).
plot_heatmap_abs_residuals()
Plots a heatmap of the absolute values of the residuals.
plot_goodness_of_fit()
Creates a scatter plot comparing observed vs. estimated values, fits a linear regression model, plots the 95% confidence interval, and labels points outside the confidence interval.
plot_kld()
Plots the Kullback-Leibler Divergence (KLD) for each mRNA. The KLD is calculated between the observed and estimated distributions of the mRNA expression levels.
plot_pca()
Plots a PCA (Principal Component Analysis) of the observed and estimated values.
plot_boxplot_alpha()
Plots a boxplot of the alpha values.
plot_boxplot_beta()
Plots a boxplot of the beta values.
plot_cdf_alpha()
Plots the cumulative distribution function (CDF) of the alpha values.
plot_cdf_beta()
Plots the cumulative distribution function (CDF) of the beta values.
plot_time_wise_residuals()
Plots the residuals over time for each mRNA.
metrics
Fit statistics, distinct from normalized and regularized optimizer losses.
networks
Directed TF-to-mRNA graphs; signs describe contributions, not alpha signs.
render_gravis
render_gravis(graph, node_size=12, edge_scale=1.0, edge_labels=False)
Return self-contained interactive HTML; unavailable signals remain labelled.
regulatory
TF-specific post-fit signal-flow analysis shared by dashboard and scripts.
The original model is attributed to Philomina Lillie Normann; subsequent implementation and architectural improvements are attributed to Abhinav Mishra.
windows
windows(n_time, n_early=3, n_late=3)
Non-overlapping, index-defined windows on the actual RNA grid.
_transform
_transform(values, transform)
The workbook's prediction transform (I2), in NumPy: clip | none | softplus.
remove_regulator
remove_regulator(contributions, alpha, index, renormalize=False, transform='clip')
Fixed-parameter removal, not refitting; the final transform follows TFOpt (default clip).
analyze
analyze(workbook, input1=None, input3=None, *, lower_bound=-4.0, upper_bound=4.0, bound_tol=1e-06, n_early=3, n_late=3, renormalize=False, ms_time_points=None, ms_alignment='by_time')
Decompose signed signals; withhold reconstruction/KO for incomplete targets.
AUCs use actual minutes. Dominance uses integrated absolute contributions,
never signed cancellation; an all-zero signal has no dominant regulator.
Delta AUC means baseline minus removal, after clipping in both cases.
Signals follow the workbook's Beta "Source" column when present (T6; input1 series on ms_time_points,
default: the configured grid); older workbooks use the legacy loader rules.
workbook
Read-only TFOpt workbook, time-grid and legacy raw-signal interpretation.
analysis_config
analysis_config(conf=None)
Read the same base/local fields as the optimizer, without changing globals.
time_grid
time_grid(frame, configured=None)
Resolve xN ordinal columns against RNA times, or validate literal time headers.
aligned_series
aligned_series(observed, estimated, configured=None)
Outer-align rows by mRNA; preserve missing rows/values as NaN, never zero.
load_workbook
load_workbook(source, time_points=None)
Parse the exporter's exact TFOpt schema; target Psite columns are not used.
workbook_signals
workbook_signals(input1, beta, observed, rna_times, input3=None, ms_time_points=None, alignment='by_time')
Signals named by a workbook's Beta "Source" column (T6): the series the optimizer actually used.
Source "protein": the TF's input1 protein row (empty Psite); "mrna": its input3 row (the Observed row when no input3 is given); "first_site": its first S_/T_/Y_ input1 row (legacy control); site rows: their own input1 row. input1 series are taken at the RNA times by actual time (processing.tfseries.align_to_rna). Missing vectors stay unavailable; without input1 nothing is reconstructed.
legacy_signals
legacy_signals(input1, observed, n_time, input3=None)
Reproduce first-accepted-row protein proxy, five-column drop and RNA fallback.
Used only for workbooks without a Beta "Source" column (written before T6, e.g. the shipped workbook), which
were fitted with this loader (KNOWN_ISSUES T6/T6c). Newer workbooks use workbook_signals.
No input1 means source selection is unknown: even a matching observed mRNA cannot then be assumed to be the original TF signal. Missing vectors remain unavailable. Protein keys use blank PSite, matching the fitted workbook.
local
config
constants
Settings of a tfopt.local run, read from the configuration on first use (never at import).
Every name below (OUT_DIR, INPUT1, TIME_POINTS, ...) is computed from config_loader.load("local",
"tfopt") the first time it is accessed (PEP 562 module __getattr__), so importing TFOpt needs no config.toml
(as KinOpt 0.11). Library code takes explicit paths (tfopt.api); these names serve the tfopt-local command
and its defaults. reload() forgets the cached values (for a new --conf).
reload
reload()
Forget the cached settings; the next access reads the configuration again.
ensure_output_dirs
ensure_output_dirs()
Create the results and log folders. Called when a run starts, never on import (I3; as KinOpt 0bffd08).
The data folder is only read, and the ODE folder is created only when the workbook copy is requested
(export_to_ode_data_dir).
parse_args
parse_args(return_all=False)
tfopt.local CLI: bounds, loss and prediction transform.
Defaults come from config.toml. Returns (lower_bound, upper_bound, loss_type); with return_all a dict that
also holds prediction_transform.
logconf
LazyLogger
Logger set up on first use, so that importing a module creates no log folder or file (I3).
Forwards every attribute to setup_logger(**kwargs), called once per instance. A logger that already has
handlers (set up by another module) is reused instead of being set up again.
exporter
latexit
Standalone LaTeX summary of TFOpt workbooks and plots; no TeX runtime required.
plotout
plot_estimated_vs_observed
plot_estimated_vs_observed(predictions, expression_matrix, gene_ids, time_points, regulators, tf_protein_matrix, tf_ids, num_targets, save_path=None)
Plots the estimated vs observed values for a given set of genes and their corresponding TFs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
|
ndarray
|
Predicted expression levels. |
required |
expression_matrix
|
ndarray
|
Observed expression levels. |
required |
gene_ids
|
list
|
List of gene identifiers. |
required |
time_points
|
ndarray
|
The configured RNA time grid in minutes (the plot's x values). |
required |
regulators
|
ndarray
|
Matrix of regulators for each gene. |
required |
tf_protein_matrix
|
ndarray
|
Matrix of TF protein levels. |
required |
tf_ids
|
list
|
List of TF identifiers. |
required |
num_targets
|
int
|
Number of target genes to plot. |
required |
save_path
|
str
|
Directory to save the plots. |
None
|
plot_multistart_summary_runtime_overlay
plot_multistart_summary_runtime_overlay(summary_csv, out_path=None, figsize=(8, 8), x_col='rank', y_col='fun', c_col='runtime_s', success_col='success', cv_col='constr_violation', annotate_best=True)
Creates a scatter plot visualizing multi-start optimization results with runtime overlay.
This function reads a CSV summary of multiple optimization runs and generates a scatter plot showing the relationship between run rank and final objective value, with runtime (or iterations) represented as color intensity. Successful and feasible runs are emphasized while unsuccessful or infeasible runs are shown with reduced opacity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
summary_csv
|
str or Path
|
Path to the CSV file containing multi-start optimization results. |
required |
out_path
|
str or Path
|
Path to save the output figure. If None, figure is not saved. Defaults to None. |
None
|
figsize
|
tuple
|
Figure size as (width, height) in inches. Defaults to (8, 8). |
(8, 8)
|
x_col
|
str
|
Column name for x-axis (run rank). If missing, will be created from y_col ranking. Defaults to "rank". |
'rank'
|
y_col
|
str
|
Column name for y-axis (final objective value). Defaults to "fun". |
'fun'
|
c_col
|
str
|
Column name for color mapping (typically runtime). Falls back to "nit" (iterations) if not found. Defaults to "runtime_s". |
'runtime_s'
|
success_col
|
str
|
Column name indicating optimization success status. Defaults to "success". |
'success'
|
cv_col
|
str
|
Column name for constraint violation values. Falls back to common alternatives if not found. Defaults to "constr_violation". |
'constr_violation'
|
annotate_best
|
bool
|
Whether to annotate the best (rank 1) point on the plot. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - fig (matplotlib.figure.Figure): The generated figure object. - ax (matplotlib.axes.Axes): The axes object of the plot. - df (pd.DataFrame): The processed DataFrame with sorted results. |
Notes
- Points are considered feasible if constraint violation <= 1e-8
- Infeasible or unsuccessful runs are plotted with reduced opacity (0.25)
- If rank column is missing, it's automatically generated from objective values
- If runtime column is missing, falls back to iteration count or constant color
sheetutils
save_results_to_excel
save_results_to_excel(gene_ids, tf_ids, final_alpha, final_beta, psite_labels_arr, expression_matrix, predictions, objective_value, reg_map, filename=None, tf_sources=None, prediction_transform='clip', kkt_report=None, method=None, prediction_check=None)
Save the optimization results to an Excel file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gene_ids
|
list
|
List of gene identifiers. |
required |
tf_ids
|
list
|
List of TF identifiers. |
required |
final_alpha
|
ndarray
|
Final alpha values. |
required |
final_beta
|
ndarray
|
Final beta values. |
required |
psite_labels_arr
|
list
|
List of phosphorylation site labels. |
required |
expression_matrix
|
ndarray
|
Observed expression levels. |
required |
predictions
|
ndarray
|
Predicted expression levels. |
required |
objective_value
|
float
|
Objective value from optimization. |
required |
reg_map
|
dict
|
Mapping of genes to regulators. |
required |
filename
|
str
|
Path to the output Excel file. |
None
|
tf_sources
|
dict
|
TF -> series behind its TF-level beta ("protein" | "mrna" | "first_site"). When given, the Beta sheet gets a "Source" column: that value on the TF-level row, "site" on site rows. |
None
|
prediction_check
|
DataFrame
|
|
None
|
export_to_ode_data_dir
export_to_ode_data_dir(out_file, ode_data_dir, enabled=False)
Copy the results workbook into ode_data_dir only when explicitly enabled, never over an existing file.
ode_data_dir may hold the input data of a downstream model (e.g. PhosKinTime's data/tfopt_results.xlsx), so the
copy is opt-in (copy_to_ode_data_dir) and an existing file there is left untouched. Returns the new path, or
None when nothing was copied.
export_multistart_results
export_multistart_results(results)
Export multiple multistart optimization results to an Excel file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
list
|
List of optimization results, each containing attributes like 'start_id', 'fun', 'success', etc. |
required |
Returns:
| Type | Description |
|---|---|
|
None |
save_multistart_solutions_npz
save_multistart_solutions_npz(all_results, out_path)
Saves multistart optimization solutions to a compressed .npz file format.
This function aggregates optimization results into a structured format and saves them in a compressed NumPy .npz file. It processes the solutions, extracting relevant attributes such as optimization variables, function values, success status, and starting IDs, before saving them for later use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_results
|
list
A list of optimization result objects. Each result object must have
the attributes |
required | |
out_path
|
str or Path The file path where the compressed .npz file will be saved. The path will be converted into a pathlib Path object if it is not already one. |
required |
objfn
minfn
Differentiable transcription-factor model.
Originally implemented by Philomina Lillie Normann. This version has been modified and optimized for consistency & speed in submodules by Abhinav Mishra.
The standalone implementation uses JAX float64 and one prediction transform shared by the objective and the Estimated sheet (default "clip", the behaviour so far).
apply_prediction_transform
apply_prediction_transform(pred, transform='clip')
Apply the prediction transform to the summed prediction (see PREDICTION_TRANSFORMS).
opt
optrun
Local solvers with explicit feasibility and convergence reporting.
scipy-slsqp (default; SciPy SLSQP driver, exact constraints, analytic JAX gradients; tfopt.local.opt.slsqp) and the JAXopt methods (lbfgsb, projected-gradient, non-negative, unconstrained), which are approximate for the shipped problem: it is ill-conditioned (condition number about 6.5e5 on the feasible directions) and they do not converge at tol 1e-7.
_is_accepted
_is_accepted(res, acceptance_tol=ACCEPTANCE_TOL)
Accepted start: success = True, measured constraint residual <= acceptance_tol, and the KKT verdict passes when it was computed (DECISIONS_T6, fourth and seventh blocks).
_result_sort_key
_result_sort_key(res, acceptance_tol=ACCEPTANCE_TOL)
Accepted starts first, ranked by objective; then the rest (feasible first, success, quality).
multistart_config
multistart_config(settings, **overrides)
MultiStartConfig from configuration settings. jitter_scale (KinOpt's name) is accepted for jitter_frac;
giving both is ambiguous and rejected.
run_optimizer_multistart
run_optimizer_multistart(x0, bounds, lin_cons, expression_matrix, regulators, tf_protein_matrix, psite_tensor, n_reg, T_use, n_genes, beta_start_indices, num_psites, loss_type, run_optimizer_func=run_optimizer, cfg=None, polish=True, progress=None)
Multistart over cfg.n_starts starting points (see MultiStartConfig); progress(done, total, result) is
called after each start (not for the polish run).
slsqp
SciPy SLSQP driver with exact constraints and analytic JAX gradients ("scipy-slsqp"; as KinOpt).
Approved in DECISIONS_T6 (seventh block, item 1; AGENTS.md): JAX evaluates the objective and its gradient; SciPy
SLSQP is the optimisation driver for exact constraints. Finite-difference gradients are not allowed. The objective
gradient comes from jax.value_and_grad (jitted), and the equality constraints are linear (Σα = 1 per target over
its real edges, Σβ = 1 per TF), so their Jacobian is the constant matrix A.
Only the coefficients that belong to a constraint group are optimised. Padded α slots and other fixed coordinates
keep the geometry's fixed values. The bounds are the geometry's effective bounds. This is the only TFOpt module that
imports scipy.optimize (architecture test).
group_variables
group_variables(geometry)
Indices of the coefficients in constraint groups, and (A, b) of the groups over those indices.
run_scipy_slsqp
run_scipy_slsqp(fun, geometry, x0, tol=1e-10, maxiter=SLSQP_MAXITER)
Minimise fun (a JAX function of the full parameter vector) with SLSQP under TFOpt's exact constraints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fun
|
callable
|
JAX-traceable objective of the full parameter vector. |
required |
geometry
|
ParameterGeometry
|
Groups, fixed values and effective bounds. |
required |
x0
|
array
|
Starting point (full vector); only the grouped coordinates are used. |
required |
tol
|
float
|
SLSQP |
1e-10
|
maxiter
|
int
|
SLSQP iteration cap. |
SLSQP_MAXITER
|
Returns:
| Type | Description |
|---|---|
dict
|
|
workers
Parallel multistart workers (DECISIONS_T6, seventh block, item 2).
Starts run in separate processes (spawn). The parent sets thread limits in the environment while the pool starts, so
every worker starts with XLA, OpenMP and BLAS limited to threads threads and the workers do not oversubscribe the
cores. Each worker builds the solver engine once from the problem payload and solves the starting points it is given;
each start keeps its own seed (its starting point is fixed by the parent). This module imports nothing heavy at import
time.
thread_limited_env
thread_limited_env(threads=1)
Temporarily set the thread-limit environment (inherited by spawned workers).
resolve_jobs
resolve_jobs(n_jobs)
Worker count: -1 means all cores; otherwise at least 1.
solve_parallel
solve_parallel(payload, x0s, n_jobs, threads=1, progress=None)
Solve each starting point in a pool of n_jobs spawned workers; results keep the input order.
progress(done, total, result) is called in the parent each time a start finishes (in finishing order).
optcon
construct
build_fixed_arrays
build_fixed_arrays(gene_ids, expression_matrix, tf_ids, tf_protein, tf_psite_data, tf_psite_labels, reg_map)
Build expression, padded regulators, protein and site arrays.
Gene and TF identifiers determine stable array order. The returned tuple also includes regulator width, maximum site count, padded labels and actual counts.
constraint_alpha_func
constraint_alpha_func(x, n_genes, n_reg) -> np.ndarray
For each gene, the sum of its alpha parameters must equal 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Decision vector. |
required |
n_genes
|
int
|
Number of genes. |
required |
n_reg
|
int
|
Number of regulators. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of constraints. |
constraint_beta_func
constraint_beta_func(x, n_alpha, n_TF, beta_start_indices, num_psites, no_psite_tf) -> np.ndarray
For each TF, the sum of its beta parameters must equal 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Decision vector. |
required |
n_alpha
|
int
|
Number of alpha parameters. |
required |
n_TF
|
int
|
Number of transcription factors. |
required |
beta_start_indices
|
list
|
List of starting indices for beta parameters. |
required |
num_psites
|
list
|
List of number of phosphorylation sites for each TF. |
required |
no_psite_tf
|
list
|
List indicating if a TF has no phosphorylation site. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of constraints. |
build_linear_constraints
build_linear_constraints(n_genes, n_TF, n_reg, n_alpha, beta_start_indices, num_psites, no_psite_tf, regulators=None)
Return TF-specific affine groups, independent of SciPy.
Optional regulators exclude padded slots. The optimizer also derives the mask from its required regulator matrix for legacy callers that omit this argument.
feasibility
Bounded affine alpha/beta geometry, permitting signed beta coefficients.
ParameterGeometry
decode(z)
Sequential bounded stick allocation: a box maps exactly into group sums.
project(x, hyperparams=None)
Euclidean projection on disjoint bounded affine-sum groups.
Compiled once per geometry (I1): called eagerly, the per-group loops were traced and compiled again on
every call (745 s for 64 starting points on the shipped problem). Same operations as _project_impl.
_project_impl(x)
The projection itself: per group, bisection (80 steps) for the shift that meets the sum in the box.
filter
load_and_filter_data
load_and_filter_data(*, input1=None, input3=None, input4=None, source=None, ms_time_points=None, rna_time_points=None, alignment=None, with_sources=False)
Load and filter data for the optimization problem.
Keyword arguments override the configured inputs and series settings (processing/tfseries.py). TFs without a
base series are dropped with their edges, and every mRNA fallback and dropped edge is logged (T6).
With with_sources a tenth element is returned: TF -> "protein" | "mrna" | "first_site".
Returns:
| Type | Description |
|---|---|
- gene_ids (list
|
List of gene IDs. - expr_matrix (np.ndarray): Gene expression matrix. - expr_time_cols (list): Time columns for expression data. - tf_ids (list): List of transcription factor IDs. - tf_protein (dict): Dictionary mapping TF IDs to their protein data. - tf_psite_data (dict): Dictionary mapping TF IDs to their phosphorylation site data. - tf_psite_labels (dict): Dictionary mapping TF IDs to their phosphorylation site labels. - tf_time_cols (list): Time columns for TF data. - reg_map (dict): Regulation map, mapping gene IDs to their regulators. |
prepare_data
prepare_data(gene_ids, expr_matrix, tf_ids, tf_protein, tf_psite_data, tf_psite_labels, tf_time_cols, reg_map)
Prepares the data for optimization by filtering the expression matrix to match the number of time points and building fixed arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gene_ids
|
list
|
List of gene IDs. |
required |
expr_matrix
|
ndarray
|
Gene expression matrix. |
required |
tf_ids
|
list
|
List of transcription factor IDs. |
required |
tf_protein
|
dict
|
Dictionary mapping TF IDs to their protein data. |
required |
tf_psite_data
|
dict
|
Dictionary mapping TF IDs to their phosphorylation site data. |
required |
tf_psite_labels
|
dict
|
Dictionary mapping TF IDs to their phosphorylation site labels. |
required |
tf_time_cols
|
list
|
Time columns for TF data. |
required |
reg_map
|
dict
|
Regulation map, mapping gene IDs to their regulators. |
required |
Returns: fixed_arrays (tuple): Tuple containing the fixed arrays: - expression_matrix: array of shape (n_genes, T) - regulators: array of shape (n_genes, n_reg) with indices into tf_ids. - tf_protein_matrix: array of shape (n_TF, T) - psite_tensor: array of shape (n_TF, n_psite_max, T), padded with zeros. - n_reg: maximum number of regulators per gene. - n_psite_max: maximum number of PSites among TFs. - psite_labels_arr: list (length n_TF) of lists of PSite names (padded with empty strings). - num_psites: array of length n_TF with the actual number of PSites for each TF. T_use (int): Number of time points used in the expression matrix.
utils
iodata
min_max_normalize
min_max_normalize(df, custom_max=None)
Row-wise (per-sample) min-max normalize time-series columns starting with 'x'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame with time-series columns (x1-xN). |
required |
custom_max
|
float
|
If given, used as max for all rows. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Normalized DataFrame with same shape. |
load_expression_data
load_expression_data(filename=None)
Loads gene expression (mRNA) data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the CSV file containing mRNA data. |
None
|
Returns:
| Type | Description |
|---|---|
-gene_ids
|
List of gene identifiers (strings). - expression_matrix: Matrix of gene expression data (numpy array). - time_cols: List of time columns (excluding "GeneID"). |
load_tf_protein_data
load_tf_protein_data(filename=None, *, expression_file=None, source=None, ms_time_points=None, rna_time_points=None, alignment=None, return_series=False)
Loads the TF base series X_i and the TF's own phosphosite series (KNOWN_ISSUES T6, T6c).
X_i is the TF's input1 protein row (empty Psite) or, without one, its input3 mRNA ("protein_then_mrna");
see processing/tfseries.py for the other source settings. All input1 series are taken at the RNA times by
actual time (alignment "by_time"). Defaults come from the configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the CSV file containing TF protein and phosphosite data (input1). |
None
|
expression_file
|
str
|
input3 path for the mRNA fallback (default: configured input3). |
None
|
source, ms_time_points, rna_time_points, alignment
|
override the configured settings. |
required | |
return_series
|
bool
|
return the processing.tfseries.TFSeries (with sources) instead of the tuple. |
False
|
Returns: - tf_ids: List of TF identifiers (strings). - tf_protein: Dictionary mapping TF identifiers to their base series X_i (numpy array). - tf_psite_data: Dictionary mapping TF identifiers to their phosphorylation site data (list of numpy arrays). - tf_psite_labels: Dictionary mapping TF identifiers to their phosphorylation site labels (list of strings). - time_cols: List of the RNA time columns the series are aligned to.
load_regulation
load_regulation(filename=None)
Returns a mapping from target gene to its source transcription factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the CSV file containing regulation data. |
None
|
Returns: - reg_map: Dictionary mapping gene identifiers to lists of TF identifiers.
summarize_stats
summarize_stats(input3=None, input1=None, input4=None)
Summarizes statistics for the expression data (input3) and TF protein data (input1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input3
|
str
|
Path to the expression data CSV file. |
None
|
input1
|
str
|
Path to the TF protein data CSV file. |
None
|
input4
|
str
|
Path to the mapping file CSV. |
None
|
create_report
create_report(results_dir: str, output_file: str = 'report.html')
Aggregate TF-specific and general plots and workbook tables locally.
organize_output_files
organize_output_files(*directories)
Function to organize output files into protein-specific folders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directories
|
str
|
List of directories to organize. |
()
|
params
get_optimization_parameters
get_optimization_parameters(expression_matrix, tf_protein_matrix, n_reg, T_use, psite_labels_arr, num_psites, lb, ub, *, regulators=None, seed=0)
Prepare the optimization parameters for the optimization problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression_matrix
|
ndarray
|
Gene expression matrix. |
required |
tf_protein_matrix
|
ndarray
|
TF protein matrix. |
required |
n_reg
|
int
|
Number of regulators. |
required |
T_use
|
int
|
Number of time points to use. |
required |
psite_labels_arr
|
list
|
List of phosphorylation site labels for each TF. |
required |
num_psites
|
ndarray
|
Array containing the number of phosphorylation sites for each TF. |
required |
lb
|
float
|
Lower bound for beta parameters. |
required |
ub
|
float
|
Upper bound for beta parameters. |
required |
Returns: x0 (np.ndarray): Initial guess for the optimization variables. n_alpha (int): Number of alpha parameters. beta_start_indices (np.ndarray): Starting indices for beta parameters. bounds (list): List of bounds for the optimization variables. no_psite_tf (np.ndarray): Array indicating whether each TF has no phosphorylation sites. n_genes (int): Number of genes. n_TF (int): Number of transcription factors.
postprocess_results
postprocess_results(result, n_alpha, n_genes, n_reg, beta_start_indices, num_psites, reg_map, gene_ids, tf_ids, psite_labels_arr)
Post-process the optimization results to extract the final alpha and beta parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
OptimizeResult
|
The result of the optimization. |
required |
n_alpha
|
int
|
Number of alpha parameters. |
required |
n_genes
|
int
|
Number of genes. |
required |
n_reg
|
int
|
Number of regulators. |
required |
beta_start_indices
|
ndarray
|
Starting indices for beta parameters. |
required |
num_psites
|
ndarray
|
Array containing the number of phosphorylation sites for each TF. |
required |
reg_map
|
dict
|
Regulation map, mapping gene IDs to their regulators. |
required |
gene_ids
|
list
|
List of gene IDs. |
required |
tf_ids
|
list
|
List of transcription factor IDs. |
required |
psite_labels_arr
|
list
|
List of lists containing phosphorylation site labels. |
required |
Returns:
| Type | Description |
|---|---|
final_x (np.ndarray
|
Final optimization result. final_alpha (np.ndarray): Final alpha parameters reshaped into a matrix. final_beta (np.ndarray): Final beta parameters reshaped into a matrix. |
prediction_check
prediction_check(targets, raw, logger=None)
Flag the targets whose summed prediction is negative at any RNA time point (KinOpt 0.11.0's check, TF form).
raw is the summed prediction sum_k alpha_ik * activity_k(t) before the prediction transform. With the
default transform "clip" its negative values are 0 in Estimated; with "none" it is the fitted prediction
itself. An mRNA level cannot be negative, so a flagged target should be inspected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
list of str
|
The target mRNA (GeneID) of each row of |
required |
raw
|
array
|
Summed prediction, shape (n_targets, n_time). |
required |
logger
|
Logger | None
|
If given, a warning names the flagged targets. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per target: |
optimality
KKT
TF-specific feasibility and first-order projected stationarity diagnostics.
kkt_diagnostics
KKT diagnostics for TFOpt's constrained fit: Lagrange multipliers and the four KKT residuals (issue #13, I5).
Same names, report and tolerances as KinOpt 0.11 (kinopt.optimality.kkt_diagnostics). TFOpt solves min f(x)
subject to linear equalities A x = b (Σα = 1 per target over its real edges, Σβ = 1 per TF) and bounds
l <= x <= u. At a KKT point there are multipliers λ (free sign) and μ_l, μ_u >= 0 with
- stationarity:
∇f(x) + Aᵀλ - μ_l + μ_u = 0; - primal feasibility:
A x = bandl <= x <= u; - dual feasibility:
μ_l >= 0andμ_u >= 0; - complementary slackness:
μ_l · (x - l) = 0andμ_u · (u - x) = 0.
λ and μ are estimated by least squares on the stationarity equation, with μ >= 0 on the active bounds only, as in
KinOpt. KinOpt solves that with scipy.optimize.lsq_linear. TFOpt's equality rows are disjoint (every parameter
belongs to at most one group), so the problem separates into one convex, piecewise-quadratic problem in λ per group,
solved here exactly by bisection on its monotone derivative. No scipy.optimize is used (TFOpt's architecture
test). Each residual is compared with a tolerance and gets a pass/fail verdict.
KKTReport
dataclass
Result of kkt_diagnostics.
Attributes:
| Name | Type | Description |
|---|---|---|
conditions |
DataFrame
|
One row per condition: 'condition', 'residual', 'tolerance', 'passed'. |
multipliers |
DataFrame
|
One row per multiplier: 'kind' ('equality', 'lower', 'upper'), 'index' (row of
|
source |
str
|
'solver' if λ came from the solver, 'estimated' otherwise. |
passed |
bool
|
True if every condition passed. |
details |
dict
|
Further numbers: gradient norm, active-bound counts, active-set tolerance. |
constraint_matrix
constraint_matrix(groups, n_params)
Build A and b from TFOpt's sum constraints, [(indices, target), ...] (ParameterGeometry.groups).
Returns:
| Type | Description |
|---|---|
tuple
|
|
_group_lambda
_group_lambda(g, lower_only, upper_only, free, iters=200)
λ minimising Σ_free (g+λ)² + Σ_lower min(0, g+λ)² + Σ_upper max(0, g+λ)² (convex, monotone derivative).
kkt_diagnostics
kkt_diagnostics(grad, x, A, b, lower, upper, solver_multipliers=None, tolerances=None, active_tol=1e-10, eq_labels=None, param_labels=None)
Compute KKT multipliers and residuals at a point (same signature and report as KinOpt 0.11).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grad
|
array
|
Gradient of the objective at |
required |
x
|
array
|
Point to check, shape (n,). |
required |
A
|
array
|
Equality constraint matrix, shape (m, n); its rows must be disjoint (TFOpt's groups). |
required |
b
|
array
|
Equality right-hand side, shape (m,). |
required |
lower, upper
|
array
|
Bounds, shape (n,). For fixed parameters |
required |
solver_multipliers
|
array | None
|
Equality multipliers from a solver (convention ∇f = Σ m_i ∇h_i + bound terms, as SciPy SLSQP). TFOpt's JAXopt solvers report none, so λ is estimated. |
None
|
tolerances
|
dict | None
|
Overrides of |
None
|
active_tol
|
float
|
A bound is active when |
1e-10
|
eq_labels, param_labels
|
list[str] | None
|
Labels of the constraints and parameters. |
required |
Returns:
| Type | Description |
|---|---|
KKTReport
|
Conditions with verdicts, multipliers and details. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The equality rows overlap (a parameter in more than one group). |
kkt_report
kkt_report(x, objective, geometry, tolerances=None, eq_labels=None, param_labels=None)
KKT diagnostics of objective at x for a ParameterGeometry (its groups and effective bounds).
summary_columns
summary_columns(report)
Per-start summary fields: kkt_passed and one residual per condition.
processing
TF-specific input validation and regulatory mapping.
cleanup
Validate numerical time-series tables without altering scientific scaling.
map
TF Source -> mRNA Target mappings, preserving input regulator order.
tfseries
TF base series X_i, site series S_is and their time alignment (KNOWN_ISSUES T6, T6c; DECISIONS_T6).
Approved model (DECISIONS_T6 1). Only the regulator base series X_i is selected here:
X_i(t) = P_i(t) if TF i has an input1 protein row (empty Psite) source "protein"
= R_i(t) otherwise, if TF i has input3 mRNA source "mrna" (logged)
(no series -> the TF and its edges are excluded, logged)
A_i(t) = beta_i0 * X_i(t) + sum_s beta_is * S_is(t) (S_is: the TF's own input1 sites)
A TF acts as a protein, so its activity is built from its protein and its own sites, as KinOpt builds a kinase's activity; the TF's own mRNA is a fallback proxy only.
Settings (tf_protein_source):
"protein_then_mrna" the approved default above;
"mrna" X_i = input3 mRNA for every TF (TFs without mRNA are excluded);
"legacy_first_site" the shipped behaviour (former iodata.py:93-100): rows whose Psite does not start with
S_/T_/Y_ (including protein rows) are skipped and the TF's first remaining row is X_i, labelled
"first_site"; TFs without such rows use their mRNA. For the control run only.
Time alignment (ms_alignment, T6c). input1 is on the MS grid, input3 on the RNA grid. Every input1 series is
taken at the RNA times, matched by actual time from the configured grids:
"by_time" the value itself where the MS grid has the RNA time, otherwise PCHIP over the full MS grid;
"legacy_position" the last len(RNA) columns, the shipped behaviour (pairs RNA 15 min with MS 16 min).
ms_rna_pairing
ms_rna_pairing(ms_time_points, rna_time_points)
Positional pairing of the last len(RNA) MS columns with the RNA columns, flagged where times differ.
align_to_rna
align_to_rna(values, ms_time_points, rna_time_points, alignment='by_time')
input1 series on the MS grid (last axis) at the RNA times; values at shared times are copied unchanged.
build_tf_series
build_tf_series(input1, input3, *, source='protein_then_mrna', ms_time_points=None, rna_time_points=None, alignment='by_time')
Select X_i and S_is per TF from input1 (GeneID, Psite, MS columns) and input3 (GeneID, RNA columns).
Every gene of input1/input3 is a candidate TF; log_tf_sources reports the sources of the TFs that regulate.
log_tf_sources
log_tf_sources(series, reg_map, logger=log)
Log the mRNA fallbacks and exclusions of the TFs that have edges; returns the dropped edges.
config
config
Standalone CLI and logging configuration.
cli
CLI shortcuts matching the twin repository workflow.
config_loader
config_loader
Independent TOML configuration with KinOpt-style section/mode merging.