tfopt 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- config_loader.py +38 -0
- tfopt/__init__.py +25 -0
- tfopt/__main__.py +5 -0
- tfopt/_exit.py +66 -0
- tfopt/analysis/__init__.py +74 -0
- tfopt/analysis/diagrams.py +221 -0
- tfopt/api.py +662 -0
- tfopt/app/__init__.py +17 -0
- tfopt/app/__main__.py +72 -0
- tfopt/app/backend.py +593 -0
- tfopt/app/server.py +230 -0
- tfopt/app/static/app.css +233 -0
- tfopt/app/static/app.js +431 -0
- tfopt/app/static/index.html +129 -0
- tfopt/bundle/__init__.py +13 -0
- tfopt/bundle/build.py +566 -0
- tfopt/bundle/contract/1.0/manifest.schema.json +316 -0
- tfopt/bundle/contract/1.0/tables.json +1186 -0
- tfopt/bundle/contract.py +231 -0
- tfopt/cli.py +266 -0
- tfopt/examples/__init__.py +119 -0
- tfopt/fitanalysis/__init__.py +0 -0
- tfopt/fitanalysis/__main__.py +12 -0
- tfopt/fitanalysis/curves.py +52 -0
- tfopt/fitanalysis/figures.py +96 -0
- tfopt/fitanalysis/helper.py +2 -0
- tfopt/fitanalysis/helpers/__init__.py +1 -0
- tfopt/fitanalysis/helpers/plotter.py +372 -0
- tfopt/fitanalysis/metrics.py +12 -0
- tfopt/fitanalysis/networks.py +46 -0
- tfopt/fitanalysis/regulatory.py +237 -0
- tfopt/fitanalysis/workbook.py +264 -0
- tfopt/local/__init__.py +0 -0
- tfopt/local/__main__.py +62 -0
- tfopt/local/config/__init__.py +0 -0
- tfopt/local/config/constants.py +120 -0
- tfopt/local/config/logconf.py +112 -0
- tfopt/local/exporter/__init__.py +0 -0
- tfopt/local/exporter/latexit.py +13 -0
- tfopt/local/exporter/plotout.py +285 -0
- tfopt/local/exporter/sheetutils.py +193 -0
- tfopt/local/objfn/__init__.py +0 -0
- tfopt/local/objfn/minfn.py +67 -0
- tfopt/local/opt/__init__.py +0 -0
- tfopt/local/opt/optrun.py +279 -0
- tfopt/local/opt/slsqp.py +65 -0
- tfopt/local/opt/workers.py +81 -0
- tfopt/local/optcon/__init__.py +0 -0
- tfopt/local/optcon/construct.py +134 -0
- tfopt/local/optcon/feasibility.py +116 -0
- tfopt/local/optcon/filter.py +101 -0
- tfopt/local/utils/__init__.py +0 -0
- tfopt/local/utils/iodata.py +238 -0
- tfopt/local/utils/params.py +131 -0
- tfopt/optimality/KKT.py +14 -0
- tfopt/optimality/__init__.py +1 -0
- tfopt/optimality/kkt_diagnostics.py +182 -0
- tfopt/processing/__init__.py +1 -0
- tfopt/processing/cleanup.py +14 -0
- tfopt/processing/map.py +14 -0
- tfopt/processing/tfseries.py +188 -0
- tfopt-0.2.0.dist-info/METADATA +158 -0
- tfopt-0.2.0.dist-info/RECORD +68 -0
- tfopt-0.2.0.dist-info/WHEEL +5 -0
- tfopt-0.2.0.dist-info/entry_points.txt +4 -0
- tfopt-0.2.0.dist-info/licenses/LICENSE +28 -0
- tfopt-0.2.0.dist-info/licenses/THIRD_PARTY.md +83 -0
- tfopt-0.2.0.dist-info/top_level.txt +2 -0
config_loader.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Independent TOML configuration with KinOpt-style section/mode merging."""
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import tomllib
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
def _project_root():
|
|
8
|
+
return Path(__file__).resolve().parent
|
|
9
|
+
|
|
10
|
+
def _deep_merge(base, override):
|
|
11
|
+
result = dict(base)
|
|
12
|
+
for key, value in override.items():
|
|
13
|
+
result[key] = _deep_merge(result[key], value) if isinstance(value, dict) and isinstance(result.get(key), dict) else value
|
|
14
|
+
return result
|
|
15
|
+
|
|
16
|
+
def config_path():
|
|
17
|
+
args = sys.argv[1:]
|
|
18
|
+
for i, arg in enumerate(args):
|
|
19
|
+
if arg == '--conf' and i + 1 < len(args):
|
|
20
|
+
return Path(args[i+1]).expanduser().resolve()
|
|
21
|
+
if arg.startswith('--conf='):
|
|
22
|
+
return Path(arg.split('=',1)[1]).expanduser().resolve()
|
|
23
|
+
return Path(os.environ.get('TFOPT_CONFIG', _project_root() / 'config.toml')).resolve()
|
|
24
|
+
|
|
25
|
+
def load(mode='local', section='tfopt'):
|
|
26
|
+
path = config_path()
|
|
27
|
+
with path.open('rb') as handle:
|
|
28
|
+
raw = tomllib.load(handle)
|
|
29
|
+
base = raw.get(section, {})
|
|
30
|
+
cfg = _deep_merge(base, base.get('modes', {}).get(mode, {}))
|
|
31
|
+
cfg['_paths'] = raw.get('paths', {})
|
|
32
|
+
cfg['_root'] = str(path.parent)
|
|
33
|
+
return cfg
|
|
34
|
+
|
|
35
|
+
def ensure_dirs():
|
|
36
|
+
cfg = load()
|
|
37
|
+
for value in cfg['_paths'].values():
|
|
38
|
+
(Path(cfg['_root']) / value).mkdir(parents=True, exist_ok=True)
|
tfopt/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""TFOpt: transcription-factor regulatory modeling.
|
|
2
|
+
|
|
3
|
+
Originally developed by Philomina Lillie Normann; extended and refined by Abhinav Mishra.
|
|
4
|
+
"""
|
|
5
|
+
import jax
|
|
6
|
+
jax.config.update("jax_enable_x64", True)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _version():
|
|
10
|
+
"""The version: pyproject.toml in a clone, else the installed package metadata (as kinopt.__version__)."""
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"
|
|
13
|
+
if pyproject.exists():
|
|
14
|
+
import tomllib
|
|
15
|
+
project = tomllib.loads(pyproject.read_text()).get("project", {})
|
|
16
|
+
if project.get("name") == "tfopt":
|
|
17
|
+
return project["version"]
|
|
18
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
19
|
+
try:
|
|
20
|
+
return version("tfopt")
|
|
21
|
+
except PackageNotFoundError: # pragma: no cover
|
|
22
|
+
return "0+unknown"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
__version__ = _version()
|
tfopt/__main__.py
ADDED
tfopt/_exit.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Clean exit for the console entry points (``tfopt``, ``tfopt-local``, ``tfopt-app``).
|
|
2
|
+
|
|
3
|
+
Copied from KinOpt 0.11.0 (kinopt/_exit.py), the same authors and licence. TFOpt writes Parquet with PyArrow (the run
|
|
4
|
+
bundle), so it is exposed to the same abort.
|
|
5
|
+
|
|
6
|
+
A native library can abort the interpreter during its own C++ teardown after all work is done ("terminate called
|
|
7
|
+
without an active exception", exit status 134; KinOpt issue #13). PyArrow (pandas' string storage, the run bundle) keeps
|
|
8
|
+
native threads that are torn down at that point. The entry points therefore end like this: flush the output, run
|
|
9
|
+
Python's exit handlers (logging, joblib/loky and multiprocessing cleanup), then ``os._exit`` with the exit status,
|
|
10
|
+
which skips the native static destructors. Nothing of the run is lost: every file is closed by then.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import atexit
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
import traceback
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _flush():
|
|
21
|
+
for stream in (sys.stdout, sys.stderr):
|
|
22
|
+
try:
|
|
23
|
+
stream.flush()
|
|
24
|
+
except Exception:
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def run_and_exit(main, *args) -> None:
|
|
29
|
+
"""Call ``main(*args)`` and end the process with its exit status, without native teardown.
|
|
30
|
+
|
|
31
|
+
The status is ``main``'s return value if it is an int, else 0; ``SystemExit`` keeps its code (a message is
|
|
32
|
+
printed to stderr and gives 1); any other exception prints its traceback and gives 1; Ctrl+C gives 130.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
main (callable): The command's main function.
|
|
36
|
+
*args: Its arguments.
|
|
37
|
+
"""
|
|
38
|
+
try:
|
|
39
|
+
rc = main(*args)
|
|
40
|
+
code = rc if isinstance(rc, int) and not isinstance(rc, bool) else 0
|
|
41
|
+
except SystemExit as exc:
|
|
42
|
+
if exc.code is None or isinstance(exc.code, int):
|
|
43
|
+
code = exc.code or 0
|
|
44
|
+
else:
|
|
45
|
+
print(exc.code, file=sys.stderr)
|
|
46
|
+
code = 1
|
|
47
|
+
except KeyboardInterrupt:
|
|
48
|
+
code = 130
|
|
49
|
+
except BaseException:
|
|
50
|
+
traceback.print_exc()
|
|
51
|
+
code = 1
|
|
52
|
+
try:
|
|
53
|
+
_flush()
|
|
54
|
+
reusable = sys.modules.get("joblib.externals.loky.reusable_executor")
|
|
55
|
+
executor = getattr(reusable, "_executor", None)
|
|
56
|
+
if executor is not None:
|
|
57
|
+
# Stop joblib's worker processes first, as a normal exit does before the exit handlers run; its handler
|
|
58
|
+
# would otherwise wait for the idle workers. (Only an executor that exists: none is created here.)
|
|
59
|
+
try:
|
|
60
|
+
executor.shutdown(wait=True, kill_workers=True)
|
|
61
|
+
except Exception:
|
|
62
|
+
pass
|
|
63
|
+
atexit._run_exitfuncs() # logging.shutdown, joblib/loky and multiprocessing cleanup, ...
|
|
64
|
+
finally:
|
|
65
|
+
_flush()
|
|
66
|
+
os._exit(code)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Analyses of a TFOpt results folder as library functions returning tidy tables (as kinopt.analysis).
|
|
2
|
+
|
|
3
|
+
``network_readout(results_dir)`` gives the signed regulatory contributions, TF removal (knockout) effects,
|
|
4
|
+
dominance, loads, bound pressure and network edges (``tfopt.fitanalysis.regulatory.analyze``);
|
|
5
|
+
``curve_similarity(observed, estimated, time_points)`` the discrete Fréchet distance per target
|
|
6
|
+
(``tfopt.fitanalysis.curves``). ``load_run(results_dir)`` reads a results folder with the settings its run recorded
|
|
7
|
+
in ``run_config.json`` (inputs, grids, β bounds, alignment).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
from tfopt.fitanalysis.curves import curve_similarity as _curve_similarity
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Run:
|
|
22
|
+
"""A results folder: its workbook (parsed), time grids and recorded settings."""
|
|
23
|
+
|
|
24
|
+
results_dir: Path
|
|
25
|
+
workbook: object
|
|
26
|
+
observed: pd.DataFrame
|
|
27
|
+
estimated: pd.DataFrame
|
|
28
|
+
time_points: list
|
|
29
|
+
config: dict
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def load_run(results_dir, out_file='tfopt_results.xlsx', time_points=None) -> Run:
|
|
33
|
+
"""Read a results folder (workbook and run_config.json). The RNA grid is the one the run recorded in
|
|
34
|
+
run_config.json, else ``time_points`` (required then: TFOpt has no built-in grid)."""
|
|
35
|
+
from tfopt.api import _find
|
|
36
|
+
from tfopt.fitanalysis.workbook import load_workbook
|
|
37
|
+
results_dir = Path(results_dir)
|
|
38
|
+
rc = results_dir / 'run_config.json'
|
|
39
|
+
config = json.loads(rc.read_text()).get('config', {}) if rc.exists() else {}
|
|
40
|
+
times = config.get('time_points', time_points)
|
|
41
|
+
if times is None:
|
|
42
|
+
raise ValueError(f'{results_dir} has no run_config.json with time_points; pass time_points')
|
|
43
|
+
workbook = load_workbook(_find(results_dir, config.get('out_file', out_file)), times)
|
|
44
|
+
return Run(results_dir, workbook, workbook.observed.reset_index(), workbook.estimated.reset_index(),
|
|
45
|
+
list(times), config)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def network_readout(results_dir, input1=None, input3=None, *, bound_tol=1e-6, n_early=3, n_late=3,
|
|
49
|
+
renormalize=False) -> dict:
|
|
50
|
+
"""Every regulatory analysis table of a results folder, as tidy DataFrames (keyed by table name).
|
|
51
|
+
|
|
52
|
+
input1/input3 default to the paths the run recorded (run_config.json); without input1 the signal
|
|
53
|
+
reconstruction and knockouts are unavailable (warnings), the workbook estimates remain.
|
|
54
|
+
"""
|
|
55
|
+
from tfopt.fitanalysis.regulatory import analyze
|
|
56
|
+
run = load_run(results_dir)
|
|
57
|
+
c = run.config
|
|
58
|
+
input1 = input1 if input1 is not None else (c.get('input1') if c.get('input1') and Path(c['input1']).exists() else None)
|
|
59
|
+
input3 = input3 if input3 is not None else (c.get('input3') if c.get('input3') and Path(c['input3']).exists() else None)
|
|
60
|
+
result = analyze(run.workbook, input1, input3, lower_bound=c.get('lower_bound', -4.0),
|
|
61
|
+
upper_bound=c.get('upper_bound', 4.0), bound_tol=bound_tol, n_early=n_early, n_late=n_late,
|
|
62
|
+
renormalize=renormalize, ms_time_points=c.get('ms_time_points'),
|
|
63
|
+
ms_alignment=c.get('ms_alignment', 'by_time'))
|
|
64
|
+
tables = dict(result.tables)
|
|
65
|
+
tables['warnings'] = pd.DataFrame({'warning': result.warnings})
|
|
66
|
+
return tables
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def curve_similarity(observed, estimated, time_points=None, normalize_time=True) -> pd.DataFrame:
|
|
70
|
+
"""Discrete Fréchet distance between observed and estimated series per target (rows), with a summary row set
|
|
71
|
+
in ``DataFrame.attrs['summary']``."""
|
|
72
|
+
rows, summary = _curve_similarity(observed, estimated, time_points, normalize_time)
|
|
73
|
+
rows.attrs['summary'] = summary
|
|
74
|
+
return rows
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Model diagrams of TFOpt's contribution and constraint structure (``tfopt diagram``).
|
|
2
|
+
|
|
3
|
+
Adapted from the two TF-specific functions in KinOpt's former scripts/make_kinopt_diagram.py
|
|
4
|
+
(bibymaths/KinOpt, 78fb06edc2040b8a1716d3917962279c30c7b9c6); formerly TFOpt's scripts/make_tfopt_diagram.py.
|
|
5
|
+
Rendering needs Graphviz and pydot (optional: ``pixi run -e viz``); with ``outfile=None`` the DOT text is returned
|
|
6
|
+
without a renderer.
|
|
7
|
+
"""
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _parameters(tf_psites, n_tfs, lower, upper):
|
|
15
|
+
if lower is None or upper is None:
|
|
16
|
+
raise ValueError('Pass the beta bounds (lower_bound, upper_bound) from the configuration')
|
|
17
|
+
counts = [int(tf_psites)]*n_tfs if isinstance(tf_psites, int) else list(tf_psites)
|
|
18
|
+
if n_tfs < 1 or len(counts) != n_tfs or any(int(n)!=n or n<0 for n in counts):
|
|
19
|
+
raise ValueError('Provide a nonnegative phosphosite count for each TF')
|
|
20
|
+
if not np.isfinite([lower,upper]).all() or lower>upper:
|
|
21
|
+
raise ValueError('Configured beta bounds must be finite and ordered')
|
|
22
|
+
return counts, lower, upper
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _render_dot(dot_str, outfile, *, fmt='png', engine='dot'):
|
|
26
|
+
if fmt not in ('png','svg','pdf'):
|
|
27
|
+
raise ValueError('Diagram format must be png, svg or pdf')
|
|
28
|
+
executable = shutil.which(engine)
|
|
29
|
+
if executable is None:
|
|
30
|
+
raise RuntimeError('Graphviz renderer missing. Use `pixi run -e viz tfopt diagram` or install Graphviz.')
|
|
31
|
+
try:
|
|
32
|
+
import pydot
|
|
33
|
+
except ImportError as exc:
|
|
34
|
+
raise RuntimeError('pydot is missing; use the optional Pixi viz environment') from exc
|
|
35
|
+
graphs = pydot.graph_from_dot_data(dot_str)
|
|
36
|
+
if not graphs:
|
|
37
|
+
raise ValueError('Unable to parse TFOpt DOT diagram')
|
|
38
|
+
path = Path(outfile)
|
|
39
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
subprocess.run([executable, '-T'+fmt, '-o', str(path)], input=dot_str, text=True, check=True, capture_output=True)
|
|
41
|
+
if not path.is_file() or path.stat().st_size == 0:
|
|
42
|
+
raise RuntimeError('Graphviz did not produce a nonempty diagram')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def make_tfopt_diagram_dot(
|
|
46
|
+
outfile: str | None = "tfopt_diagram.png",
|
|
47
|
+
*,
|
|
48
|
+
fmt: str | None = None,
|
|
49
|
+
engine: str = "dot",
|
|
50
|
+
dpi: int = 300,
|
|
51
|
+
rankdir: str = "TB",
|
|
52
|
+
tf_psites: int | list[int] = 1,
|
|
53
|
+
n_tfs: int = 2,
|
|
54
|
+
lower_bound: float | None = None,
|
|
55
|
+
upper_bound: float | None = None,
|
|
56
|
+
):
|
|
57
|
+
"""Adapt the pinned reference make_tfopt_diagram_dot to current TFOpt semantics.
|
|
58
|
+
|
|
59
|
+
Pass outfile=None to obtain DOT without requiring a renderer.
|
|
60
|
+
"""
|
|
61
|
+
import os
|
|
62
|
+
counts, lower_bound, upper_bound = _parameters(tf_psites, n_tfs, lower_bound, upper_bound)
|
|
63
|
+
|
|
64
|
+
if fmt is None:
|
|
65
|
+
_, ext = os.path.splitext(outfile or "diagram.png")
|
|
66
|
+
fmt = ext.lstrip(".").lower() or "png"
|
|
67
|
+
|
|
68
|
+
# Palette
|
|
69
|
+
col_P = "#ffd1d1"
|
|
70
|
+
col_TF = "#94b9ff"
|
|
71
|
+
col_inp = "#d7e8ff"
|
|
72
|
+
col_alpha = "#7cb518"
|
|
73
|
+
col_beta = "#94b9ff"
|
|
74
|
+
|
|
75
|
+
TFs = [f"TF{j}" for j in range(1, n_tfs + 1)]
|
|
76
|
+
|
|
77
|
+
dot = []
|
|
78
|
+
dot.append("digraph TFOPT {")
|
|
79
|
+
dot.append(
|
|
80
|
+
f' graph [rankdir={rankdir}, dpi={dpi}, splines=true, bgcolor="white", nodesep=0.55, ranksep=0.85];'
|
|
81
|
+
)
|
|
82
|
+
dot.append(
|
|
83
|
+
' node [shape=circle, style=filled, fontname="Helvetica", fontsize=16, fontcolor="black", penwidth=2];')
|
|
84
|
+
dot.append(' edge [fontname="Helvetica", fontsize=14, fontcolor="black", penwidth=2, arrowsize=0.9];')
|
|
85
|
+
|
|
86
|
+
dot.append(f' P [label=<mRNA<sub>i</sub><br/>max(0, sum contributions)>, fillcolor="{col_P}", shape=ellipse, width=3.2, fixedsize=false];')
|
|
87
|
+
|
|
88
|
+
dot.append(' subgraph cluster_tfopt {')
|
|
89
|
+
dot.append(' label=""; color="white"; penwidth=0;')
|
|
90
|
+
|
|
91
|
+
for j, tf in enumerate(TFs, start=1):
|
|
92
|
+
dot.append(f' {tf} [label=<TF effect<sub>{j}</sub>>, fillcolor="{col_TF}", shape=ellipse, width=1.8, fixedsize=false];')
|
|
93
|
+
|
|
94
|
+
tf0 = f"{tf}_0"
|
|
95
|
+
dot.append(f' {tf0} [label=<TF<sub>{j}</sub>(t)>, fillcolor="{col_inp}", width=1.35, fixedsize=true];')
|
|
96
|
+
dot.append(f' {tf0} -> {tf} [color="{col_beta}", label=<β<sub>0,{j}</sub>>];')
|
|
97
|
+
|
|
98
|
+
for p in range(1, counts[j-1] + 1):
|
|
99
|
+
ps = f"{tf}_p{p}"
|
|
100
|
+
dot.append(
|
|
101
|
+
f' {ps} [label=<PSite<sub>{p},{j}</sub>(t)>, fillcolor="{col_inp}", width=1.55, fixedsize=true];'
|
|
102
|
+
)
|
|
103
|
+
dot.append(f' {ps} -> {tf} [color="{col_beta}", label=<β<sub>{p},{j}</sub>>];')
|
|
104
|
+
|
|
105
|
+
dot.append(f' {tf} -> P [color="{col_alpha}", label=<α<sub>i,{j}</sub>>];')
|
|
106
|
+
|
|
107
|
+
dot.append(' }')
|
|
108
|
+
dot.append(f' graph [labelloc=b, fontsize=12, label="Alpha: valid regulators only; padded slots fixed to zero.\\nPer-target alpha sum = 1; per-TF beta sum = 1.\\nConfigured beta bounds: [{lower_bound:g}, {upper_bound:g}].\\nNo phosphosites: protein beta = 1.\\nMissing required signals: reconstruction unavailable."];')
|
|
109
|
+
dot.append(f' graph [tooltip="Configured beta bounds: [{lower_bound:g}, {upper_bound:g}]; negative coefficients permitted only within these bounds."];')
|
|
110
|
+
dot.append("}")
|
|
111
|
+
dot_str = "\n".join(dot)
|
|
112
|
+
|
|
113
|
+
if outfile is not None:
|
|
114
|
+
_render_dot(dot_str, outfile, fmt=fmt, engine=engine)
|
|
115
|
+
return dot_str
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def make_tfopt_constraints_graph_dot(
|
|
119
|
+
outfile: str | None = "tfopt_constraints.png",
|
|
120
|
+
*,
|
|
121
|
+
fmt: str | None = None,
|
|
122
|
+
engine: str = "dot",
|
|
123
|
+
dpi: int = 300,
|
|
124
|
+
rankdir: str = "TB",
|
|
125
|
+
tf_psites: int | list[int] = 2,
|
|
126
|
+
n_tfs: int = 2,
|
|
127
|
+
lower_bound: float | None = None,
|
|
128
|
+
upper_bound: float | None = None,
|
|
129
|
+
):
|
|
130
|
+
"""Adapt the pinned reference make_tfopt_constraints_graph_dot to current TFOpt semantics.
|
|
131
|
+
|
|
132
|
+
Pass outfile=None to obtain DOT without requiring a renderer.
|
|
133
|
+
"""
|
|
134
|
+
import os
|
|
135
|
+
counts, lower_bound, upper_bound = _parameters(tf_psites, n_tfs, lower_bound, upper_bound)
|
|
136
|
+
|
|
137
|
+
if fmt is None:
|
|
138
|
+
_, ext = os.path.splitext(outfile or "diagram.png")
|
|
139
|
+
fmt = ext.lstrip(".").lower() or "png"
|
|
140
|
+
|
|
141
|
+
col_P = "#ffd1d1"
|
|
142
|
+
col_TF = "#94b9ff"
|
|
143
|
+
col_inp = "#d7e8ff"
|
|
144
|
+
col_alpha = "#7cb518"
|
|
145
|
+
col_beta = "#94b9ff"
|
|
146
|
+
col_note = "#f2f2f2"
|
|
147
|
+
|
|
148
|
+
TFs = [f"TF{j}" for j in range(1, n_tfs + 1)]
|
|
149
|
+
|
|
150
|
+
dot = []
|
|
151
|
+
dot.append("digraph TFOPT_CONSTRAINTS {")
|
|
152
|
+
dot.append(f' graph [rankdir={rankdir}, dpi={dpi}, splines=true, bgcolor="white", nodesep=0.55, ranksep=0.9];')
|
|
153
|
+
dot.append(
|
|
154
|
+
' node [shape=circle, style=filled, fontname="Helvetica", fontsize=16, fontcolor="black", penwidth=2];')
|
|
155
|
+
dot.append(' edge [fontname="Helvetica", fontsize=12, fontcolor="black", penwidth=2, arrowsize=0.9];')
|
|
156
|
+
|
|
157
|
+
dot.append(f' P [label=<mRNA<sub>i</sub><br/>max(0, sum contributions)>, fillcolor="{col_P}", shape=ellipse, width=3.2, fixedsize=false];')
|
|
158
|
+
|
|
159
|
+
dot.append(
|
|
160
|
+
' C [shape=box, style="rounded,filled", '
|
|
161
|
+
f'fillcolor="{col_note}", fontsize=12, label=<'
|
|
162
|
+
'<b>Constraints</b><br/>'
|
|
163
|
+
'α: 0≤α≤1 and ∑<sub>j</sub>α<sub>i,j</sub>=1 (valid TF→mRNA)<br/>'
|
|
164
|
+
f'β: {lower_bound:g}≤β≤{upper_bound:g} (configured)<br/>'
|
|
165
|
+
'∑<sub>p</sub>β<sub>p,j</sub>=1 (per TF mixture; p=0..K)'
|
|
166
|
+
'>];'
|
|
167
|
+
)
|
|
168
|
+
dot.append(' { rank=source; C; }')
|
|
169
|
+
|
|
170
|
+
# Alpha normalization box (TF-level)
|
|
171
|
+
dot.append(
|
|
172
|
+
f' NA_TF [shape=box, style="rounded,filled", fillcolor="{col_note}", fontsize=12, '
|
|
173
|
+
f'label=<∑<sub>j=1..{n_tfs}</sub> α<sub>i,j</sub> = 1<br/>'
|
|
174
|
+
f'<font point-size="10">α<sub>i,j</sub> ∈ [0,1]</font>>];'
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
for j, tf in enumerate(TFs, start=1):
|
|
178
|
+
dot.append(f' {tf} [label=<TF effect<sub>{j}</sub>>, fillcolor="{col_TF}", shape=ellipse, width=1.8, fixedsize=false];')
|
|
179
|
+
|
|
180
|
+
# Connect alpha-normalization node to each TF (dashed)
|
|
181
|
+
dot.append(f' NA_TF -> {tf} [style=dashed, color="gray50", arrowhead=none];')
|
|
182
|
+
|
|
183
|
+
# α edge TF -> P
|
|
184
|
+
dot.append(
|
|
185
|
+
f' {tf} -> P [color="{col_alpha}", '
|
|
186
|
+
f'label=<α<sub>i,{j}</sub><br/><font point-size="10">[0,1]</font>>];'
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
# β-mixture normalization per TF
|
|
190
|
+
bsum = f"NB_{tf}"
|
|
191
|
+
dot.append(
|
|
192
|
+
f' {bsum} [shape=box, style="rounded,filled", fillcolor="{col_note}", fontsize=12, '
|
|
193
|
+
f'label=<∑<sub>p=0..{counts[j-1]}</sub> β<sub>p,{j}</sub> = 1<br/>'
|
|
194
|
+
f'<font point-size="10">β<sub>p,{j}</sub> ∈ [{lower_bound:g},{upper_bound:g}]</font>>];'
|
|
195
|
+
)
|
|
196
|
+
dot.append(f' {bsum} -> {tf} [style=dashed, color="gray50", arrowhead=none];')
|
|
197
|
+
|
|
198
|
+
# Inputs feeding TF
|
|
199
|
+
tf0 = f"{tf}_0"
|
|
200
|
+
dot.append(f' {tf0} [label=<TF<sub>{j}</sub>(t)>, fillcolor="{col_inp}", width=1.25, fixedsize=true];')
|
|
201
|
+
dot.append(
|
|
202
|
+
f' {tf0} -> {tf} [color="{col_beta}", '
|
|
203
|
+
f'label=<β<sub>0,{j}</sub><br/><font point-size="10">[{lower_bound:g},{upper_bound:g}]</font>>];'
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
for p in range(1, counts[j-1] + 1):
|
|
207
|
+
ps = f"{tf}_p{p}"
|
|
208
|
+
dot.append(
|
|
209
|
+
f' {ps} [label=<PSite<sub>{p},{j}</sub>(t)>, fillcolor="{col_inp}", width=1.45, fixedsize=true];')
|
|
210
|
+
dot.append(
|
|
211
|
+
f' {ps} -> {tf} [color="{col_beta}", '
|
|
212
|
+
f'label=<β<sub>{p},{j}</sub><br/><font point-size="10">[{lower_bound:g},{upper_bound:g}]</font>>];'
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
dot.append(f' graph [labelloc=b, fontsize=12, label="Alpha: valid regulators only; padded slots fixed to zero.\\nPer-target alpha sum = 1; per-TF beta sum = 1.\\nConfigured beta bounds: [{lower_bound:g}, {upper_bound:g}].\\nNo phosphosites: protein beta = 1.\\nMissing required signals: reconstruction unavailable."];')
|
|
216
|
+
dot.append(f' graph [tooltip="Configured beta bounds: [{lower_bound:g}, {upper_bound:g}]; negative coefficients permitted only within these bounds."];')
|
|
217
|
+
dot.append("}")
|
|
218
|
+
dot_str = "\n".join(dot)
|
|
219
|
+
if outfile is not None:
|
|
220
|
+
_render_dot(dot_str, outfile, fmt=fmt, engine=engine)
|
|
221
|
+
return dot_str
|