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.
Files changed (68) hide show
  1. config_loader.py +38 -0
  2. tfopt/__init__.py +25 -0
  3. tfopt/__main__.py +5 -0
  4. tfopt/_exit.py +66 -0
  5. tfopt/analysis/__init__.py +74 -0
  6. tfopt/analysis/diagrams.py +221 -0
  7. tfopt/api.py +662 -0
  8. tfopt/app/__init__.py +17 -0
  9. tfopt/app/__main__.py +72 -0
  10. tfopt/app/backend.py +593 -0
  11. tfopt/app/server.py +230 -0
  12. tfopt/app/static/app.css +233 -0
  13. tfopt/app/static/app.js +431 -0
  14. tfopt/app/static/index.html +129 -0
  15. tfopt/bundle/__init__.py +13 -0
  16. tfopt/bundle/build.py +566 -0
  17. tfopt/bundle/contract/1.0/manifest.schema.json +316 -0
  18. tfopt/bundle/contract/1.0/tables.json +1186 -0
  19. tfopt/bundle/contract.py +231 -0
  20. tfopt/cli.py +266 -0
  21. tfopt/examples/__init__.py +119 -0
  22. tfopt/fitanalysis/__init__.py +0 -0
  23. tfopt/fitanalysis/__main__.py +12 -0
  24. tfopt/fitanalysis/curves.py +52 -0
  25. tfopt/fitanalysis/figures.py +96 -0
  26. tfopt/fitanalysis/helper.py +2 -0
  27. tfopt/fitanalysis/helpers/__init__.py +1 -0
  28. tfopt/fitanalysis/helpers/plotter.py +372 -0
  29. tfopt/fitanalysis/metrics.py +12 -0
  30. tfopt/fitanalysis/networks.py +46 -0
  31. tfopt/fitanalysis/regulatory.py +237 -0
  32. tfopt/fitanalysis/workbook.py +264 -0
  33. tfopt/local/__init__.py +0 -0
  34. tfopt/local/__main__.py +62 -0
  35. tfopt/local/config/__init__.py +0 -0
  36. tfopt/local/config/constants.py +120 -0
  37. tfopt/local/config/logconf.py +112 -0
  38. tfopt/local/exporter/__init__.py +0 -0
  39. tfopt/local/exporter/latexit.py +13 -0
  40. tfopt/local/exporter/plotout.py +285 -0
  41. tfopt/local/exporter/sheetutils.py +193 -0
  42. tfopt/local/objfn/__init__.py +0 -0
  43. tfopt/local/objfn/minfn.py +67 -0
  44. tfopt/local/opt/__init__.py +0 -0
  45. tfopt/local/opt/optrun.py +279 -0
  46. tfopt/local/opt/slsqp.py +65 -0
  47. tfopt/local/opt/workers.py +81 -0
  48. tfopt/local/optcon/__init__.py +0 -0
  49. tfopt/local/optcon/construct.py +134 -0
  50. tfopt/local/optcon/feasibility.py +116 -0
  51. tfopt/local/optcon/filter.py +101 -0
  52. tfopt/local/utils/__init__.py +0 -0
  53. tfopt/local/utils/iodata.py +238 -0
  54. tfopt/local/utils/params.py +131 -0
  55. tfopt/optimality/KKT.py +14 -0
  56. tfopt/optimality/__init__.py +1 -0
  57. tfopt/optimality/kkt_diagnostics.py +182 -0
  58. tfopt/processing/__init__.py +1 -0
  59. tfopt/processing/cleanup.py +14 -0
  60. tfopt/processing/map.py +14 -0
  61. tfopt/processing/tfseries.py +188 -0
  62. tfopt-0.2.0.dist-info/METADATA +158 -0
  63. tfopt-0.2.0.dist-info/RECORD +68 -0
  64. tfopt-0.2.0.dist-info/WHEEL +5 -0
  65. tfopt-0.2.0.dist-info/entry_points.txt +4 -0
  66. tfopt-0.2.0.dist-info/licenses/LICENSE +28 -0
  67. tfopt-0.2.0.dist-info/licenses/THIRD_PARTY.md +83 -0
  68. tfopt-0.2.0.dist-info/top_level.txt +2 -0
tfopt/api.py ADDED
@@ -0,0 +1,662 @@
1
+ """TFOpt as a library: load a configuration, check the inputs, run the fit, read the results (as kinopt.api).
2
+
3
+ The command line (``tfopt run``, ``tfopt-local``) and the GUI (``tfopt-app``) call these same functions::
4
+
5
+ from tfopt import api
6
+ config = api.load_config("config.toml", n_starts=8) # or api.RunConfig(input1=..., input3=..., ...)
7
+ report = api.validate_inputs(config.input1, config.input3, config.input4)
8
+ result = api.run(config) # writes config.results_dir
9
+ results = api.read_results(config.results_dir)
10
+
11
+ Nothing is read from config.toml at import, and ``run`` takes every path and setting from the ``RunConfig``.
12
+ TFOpt's model (DECISIONS_T6): target mRNA (input3) = Σ_TF α · (β0·X_TF + Σ_s β_s·S_TF,s), with X_TF the TF's input1
13
+ protein row (else its input3 mRNA), S_TF,s its own input1 sites, the TF→target edges from input4.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import dataclasses
18
+ import json
19
+ import os
20
+ import platform
21
+ import shutil
22
+ from dataclasses import dataclass
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ import tomllib # Python >= 3.12 (requires-python)
30
+
31
+ TF_PROTEIN_SOURCES = ('protein_then_mrna', 'mrna', 'legacy_first_site')
32
+ MS_ALIGNMENTS = ('by_time', 'legacy_position')
33
+ LOSS_TYPES = {0: 'MSE', 1: 'MAE', 2: 'soft L1', 3: 'Cauchy', 4: 'arctan', 5: 'elastic net', 6: 'Tikhonov'}
34
+
35
+ _PATH_FIELDS = ('input1', 'input3', 'input4', 'results_dir', 'copy_to_ode_data_dir')
36
+
37
+
38
+ @dataclass
39
+ class RunConfig:
40
+ """Every setting of a TFOpt run. Defaults are those of the shipped config.toml.
41
+
42
+ Attributes:
43
+ input1 (Path): TF protein and phosphosite series (``GeneID, Psite, x1..``; empty Psite = protein row).
44
+ input3 (Path): mRNA series (``GeneID, x1..``): the targets, and the mRNA fallback of a TF.
45
+ input4 (Path): Regulation edges (``Source`` TF, ``Target`` mRNA).
46
+ results_dir (Path): Output folder of the run.
47
+ method (str): ``scipy-slsqp`` (exact constraints) or a JAXopt method (approximate for ill-conditioned fits).
48
+ n_starts (int): Number of multistart starts.
49
+ jitter_scale (float): Jitter of the starting values, as a fraction of each bound's span.
50
+ start_seed (int): Seed of the starting values (α, β) drawn before the multistart.
51
+ seed (int): First seed of the multistart; start i uses ``seed + i``.
52
+ p_random (float): Probability that a start is drawn uniformly within the bounds instead of jittered.
53
+ loss_type (int): 0 MSE, 1 MAE, 2 soft L1, 3 Cauchy, 4 arctan, 5 elastic net, 6 Tikhonov.
54
+ lower_bound (float): Lower bound of β.
55
+ upper_bound (float): Upper bound of β.
56
+ prediction_transform (str): ``clip`` (default), ``none`` or ``softplus``; applied in the objective and in
57
+ Estimated.
58
+ tf_protein_source (str): ``protein_then_mrna`` (default), ``mrna`` or ``legacy_first_site`` (control only).
59
+ ms_alignment (str): ``by_time`` (default) or ``legacy_position`` (control only).
60
+ time_points (list[float]): RNA grid (input3 columns), minutes. Required: TFOpt has no built-in grid.
61
+ ms_time_points (list[float]): MS grid (input1 columns), minutes. Required.
62
+ out_file (str): Name of the results workbook.
63
+ maxiter (int): Solver iteration cap.
64
+ tol (float): Solver tolerance (SLSQP ftol).
65
+ n_jobs (int): Parallel workers of the multistart (-1: all cores; 1: sequential in this process).
66
+ threads_per_worker (int): XLA/OpenMP/BLAS threads of each worker.
67
+ allow_nonsmooth (bool): Allow the quasi-Newton JAXopt methods on the nonsmooth losses 1 and 5.
68
+ feasibility_tol (float): Constraint residual up to which a fit counts as feasible (success).
69
+ acceptance_tol (float): Constraint residual up to which a start is accepted (with success and KKT).
70
+ plots (bool): Draw the per-target, multistart and fit-analysis plots.
71
+ fit_analysis (bool): Write the fit-analysis figures (``tfopt.fitanalysis``).
72
+ report (bool): Group per-target files into folders and write ``report.html`` and the LaTeX tables.
73
+ copy_to_ode_data_dir (Path | None): Also copy the workbook into this folder (never over an existing file).
74
+ bundle (bool): Write the run bundle ``<results_dir>/<results_dir name>.tfopt.zip`` (see ``tfopt.bundle``).
75
+ """
76
+
77
+ input1: Path
78
+ input3: Path
79
+ input4: Path
80
+ results_dir: Path
81
+ time_points: list
82
+ ms_time_points: list
83
+ method: str = 'scipy-slsqp'
84
+ n_starts: int = 64
85
+ jitter_scale: float = 0.10
86
+ start_seed: int = 0
87
+ seed: int = 123
88
+ p_random: float = 0.3
89
+ loss_type: int = 5
90
+ lower_bound: float = -4.0
91
+ upper_bound: float = 4.0
92
+ prediction_transform: str = 'clip'
93
+ tf_protein_source: str = 'protein_then_mrna'
94
+ ms_alignment: str = 'by_time'
95
+ out_file: str = 'tfopt_results.xlsx'
96
+ maxiter: int = 20000
97
+ tol: float = 1e-10
98
+ n_jobs: int = -1
99
+ threads_per_worker: int = 1
100
+ allow_nonsmooth: bool = False
101
+ feasibility_tol: float = 1e-8
102
+ acceptance_tol: float = 1e-10
103
+ plots: bool = True
104
+ fit_analysis: bool = True
105
+ report: bool = True
106
+ copy_to_ode_data_dir: Path | None = None
107
+ bundle: bool = True
108
+
109
+ def __post_init__(self):
110
+ from tfopt.local.objfn.minfn import PREDICTION_TRANSFORMS
111
+ from tfopt.local.opt.optrun import METHODS
112
+ for name in _PATH_FIELDS:
113
+ value = getattr(self, name)
114
+ if value is not None:
115
+ setattr(self, name, Path(value))
116
+ if self.method not in METHODS:
117
+ raise ValueError(f"method {self.method!r} is not supported; choose from {', '.join(METHODS)}")
118
+ if self.prediction_transform not in PREDICTION_TRANSFORMS:
119
+ raise ValueError(f"prediction_transform {self.prediction_transform!r} is not supported; choose from "
120
+ f"{', '.join(PREDICTION_TRANSFORMS)}")
121
+ if self.tf_protein_source not in TF_PROTEIN_SOURCES:
122
+ raise ValueError(f"tf_protein_source {self.tf_protein_source!r} is not supported; choose from "
123
+ f"{', '.join(TF_PROTEIN_SOURCES)}")
124
+ if self.ms_alignment not in MS_ALIGNMENTS:
125
+ raise ValueError(f"ms_alignment {self.ms_alignment!r} is not supported; choose from {', '.join(MS_ALIGNMENTS)}")
126
+ if int(self.loss_type) not in LOSS_TYPES:
127
+ raise ValueError(f"loss_type {self.loss_type!r} is not supported; choose from 0..6")
128
+ if int(self.n_starts) < 1:
129
+ raise ValueError('n_starts must be at least 1')
130
+ if not float(self.lower_bound) <= float(self.upper_bound):
131
+ raise ValueError('lower_bound must not exceed upper_bound')
132
+ self.loss_type = int(self.loss_type)
133
+ self.n_starts = int(self.n_starts)
134
+ self.time_points = [float(t) for t in self.time_points]
135
+ self.ms_time_points = [float(t) for t in self.ms_time_points]
136
+
137
+ @property
138
+ def workbook(self) -> Path:
139
+ """Path of the results workbook."""
140
+ return self.results_dir / self.out_file
141
+
142
+ def to_dict(self) -> dict:
143
+ """Return the configuration as JSON-serializable values (paths as strings)."""
144
+ out = dataclasses.asdict(self)
145
+ for name in _PATH_FIELDS:
146
+ out[name] = None if out[name] is None else str(out[name])
147
+ return out
148
+
149
+ def replace(self, **overrides) -> 'RunConfig':
150
+ """Return a copy with some settings changed (unknown names raise TypeError)."""
151
+ return dataclasses.replace(self, **overrides)
152
+
153
+
154
+ #: Values a config.toml gets for keys it does not set: the settings in effect before those keys existed (the
155
+ #: tfopt-local defaults), as KinOpt keeps 10/0.20 for absent n_starts/jitter_scale. The shipped config.toml sets
156
+ #: every key to the RunConfig defaults.
157
+ LEGACY_DEFAULTS = {'method': 'lbfgsb', 'n_starts': 4, 'jitter_scale': 0.05, 'seed': 0, 'maxiter': 1000, 'tol': 1e-7,
158
+ 'n_jobs': 1}
159
+
160
+
161
+ def load_config(path=None, **overrides) -> RunConfig:
162
+ """Read a RunConfig from a config.toml (``[paths]``, ``[tfopt]`` and ``[tfopt.modes.local]``).
163
+
164
+ Relative paths in ``[paths]`` are resolved against the folder of the config file. Keys the file does not set
165
+ get `LEGACY_DEFAULTS` (the earlier tfopt-local behaviour), then the `RunConfig` defaults. ``jitter_frac`` is
166
+ accepted for ``jitter_scale``.
167
+
168
+ Args:
169
+ path (str | Path | None): The config.toml. If None, the one ``config_loader`` finds (``--conf``,
170
+ ``TFOPT_CONFIG``, else the clone's config.toml).
171
+ **overrides: Settings to change, by `RunConfig` field name.
172
+
173
+ Returns:
174
+ RunConfig: The resolved configuration.
175
+
176
+ Raises:
177
+ TypeError: An override is not a `RunConfig` field.
178
+ ValueError: A setting has an unsupported value, or both jitter_scale and jitter_frac are set.
179
+ """
180
+ if path is None:
181
+ import config_loader
182
+ path = config_loader.config_path()
183
+ path = Path(path).resolve()
184
+ raw = tomllib.loads(path.read_text())
185
+ root = path.parent
186
+ paths = raw.get('paths', {}) or {}
187
+ tf = dict(raw.get('tfopt', {}) or {})
188
+ tf.update((tf.pop('modes', {}) or {}).get('local', {}) or {})
189
+ if 'jitter_frac' in tf:
190
+ if 'jitter_scale' in tf and tf['jitter_scale'] != tf['jitter_frac']:
191
+ raise ValueError('Set either jitter_scale or jitter_frac, not both')
192
+ tf['jitter_scale'] = tf.pop('jitter_frac')
193
+ data_dir = root / paths.get('data_dir', 'data')
194
+ values = {
195
+ 'input1': data_dir / tf.get('input1', 'input1.csv'),
196
+ 'input3': data_dir / tf.get('input3', 'input3.csv'),
197
+ 'input4': data_dir / tf.get('input4', 'input4.csv'),
198
+ 'results_dir': root / paths.get('results_dir', 'results'),
199
+ }
200
+ simple = {f.name for f in dataclasses.fields(RunConfig)} - set(values) - {'copy_to_ode_data_dir'}
201
+ for key in simple:
202
+ if key in tf:
203
+ values[key] = tf[key]
204
+ if tf.get('copy_to_ode_data_dir'):
205
+ values['copy_to_ode_data_dir'] = root / paths.get('ode_data_dir', 'data/ode')
206
+ missing = [k for k in ('time_points', 'ms_time_points') if k not in values and k not in overrides]
207
+ if missing:
208
+ raise ValueError(f"{path}: [tfopt] must set {' and '.join(missing)} (the RNA and MS time grids in minutes); "
209
+ 'TFOpt has no built-in time grid')
210
+ for key, value in LEGACY_DEFAULTS.items():
211
+ values.setdefault(key, value)
212
+ unknown = set(overrides) - {f.name for f in dataclasses.fields(RunConfig)}
213
+ if unknown:
214
+ raise TypeError(f"Unknown settings: {', '.join(sorted(unknown))}")
215
+ values.update(overrides)
216
+ return RunConfig(**values)
217
+
218
+
219
+ # ----------------------------------------------------------------------------------------------- validation
220
+
221
+ @dataclass
222
+ class ValidationReport:
223
+ """Result of `validate_inputs`.
224
+
225
+ Attributes:
226
+ checks (DataFrame): One row per check: 'check', 'status' (``ok``, ``warning``, ``error``), 'count',
227
+ 'detail'.
228
+ coverage (dict): Counts: targets, targets_used, tfs, tfs_protein, tfs_mrna, tfs_first_site, tfs_excluded,
229
+ edges, edges_used, input1_rows, input3_rows, input4_rows.
230
+ skipped (DataFrame): Edges and targets a run would drop (``Source``, ``Target``, ``reason``).
231
+ """
232
+
233
+ checks: pd.DataFrame
234
+ coverage: dict
235
+ skipped: pd.DataFrame
236
+
237
+ @property
238
+ def errors(self) -> pd.DataFrame:
239
+ """The checks with status ``error``."""
240
+ return self.checks[self.checks['status'] == 'error']
241
+
242
+ @property
243
+ def ok(self) -> bool:
244
+ """True if no check failed with an error."""
245
+ return self.errors.empty
246
+
247
+
248
+ def validate_inputs(input1, input3, input4, *, ms_time_points, time_points,
249
+ tf_protein_source='protein_then_mrna', ms_alignment='by_time') -> ValidationReport:
250
+ """Check input1, input3 and input4 before a run: columns, values, duplicates, coverage and what a run drops.
251
+
252
+ The checks mirror what ``tfopt.local`` requires: numeric, finite time series with as many columns as the
253
+ configured grids; unique (GeneID, Psite) rows in input1; TF and target identifiers in input4. A TF without a
254
+ base series (no input1 protein row and no input3 mRNA) is dropped with its edges (warning); a target without
255
+ an input3 row, or without a regulator with a series, is dropped (warning).
256
+
257
+ Args:
258
+ input1, input3, input4 (str | Path | DataFrame): The inputs.
259
+ ms_time_points, time_points (list[float]): MS and RNA grids from the configuration (required).
260
+ tf_protein_source, ms_alignment (str): As the run settings.
261
+
262
+ Returns:
263
+ ValidationReport: Checks, coverage and what a run would skip.
264
+ """
265
+ rows = []
266
+
267
+ def add(check, status, count=0, detail=''):
268
+ rows.append({'check': check, 'status': status, 'count': int(count), 'detail': detail})
269
+
270
+ def read(x, name):
271
+ if isinstance(x, pd.DataFrame):
272
+ return x.copy()
273
+ try:
274
+ return pd.read_csv(x)
275
+ except Exception as exc: # unreadable file
276
+ add(f'{name} readable', 'error', 1, str(exc))
277
+ return None
278
+
279
+ ms, rna = list(ms_time_points), list(time_points)
280
+ d1, d3, d4 = read(input1, 'input1'), read(input3, 'input3'), read(input4, 'input4')
281
+ coverage = {'input1_rows': 0, 'input3_rows': 0, 'input4_rows': 0, 'targets': 0, 'targets_used': 0, 'tfs': 0,
282
+ 'tfs_protein': 0, 'tfs_mrna': 0, 'tfs_first_site': 0, 'tfs_excluded': 0, 'edges': 0, 'edges_used': 0}
283
+ skipped = pd.DataFrame(columns=['Source', 'Target', 'reason'])
284
+ if d1 is None or d3 is None or d4 is None:
285
+ return ValidationReport(pd.DataFrame(rows), coverage, skipped)
286
+
287
+ miss = [f'input1: {c}' for c in ('GeneID', 'Psite') if c not in d1.columns]
288
+ miss += ['input3: GeneID'] if 'GeneID' not in d3.columns else []
289
+ miss += [f'input4: {c}' for c in ('Source', 'Target') if c not in d4.columns]
290
+ if miss:
291
+ add('missing columns', 'error', len(miss), '; '.join(miss))
292
+ return ValidationReport(pd.DataFrame(rows), coverage, skipped)
293
+ add('missing columns', 'ok')
294
+ cols1 = [c for c in d1.columns if c not in ('GeneID', 'Psite')]
295
+ cols3 = [c for c in d3.columns if c != 'GeneID']
296
+ grid_errors = []
297
+ if len(cols1) != len(ms):
298
+ grid_errors.append(f'input1 has {len(cols1)} time columns, the MS grid has {len(ms)}')
299
+ if len(cols3) != len(rna):
300
+ grid_errors.append(f'input3 has {len(cols3)} time columns, the RNA grid has {len(rna)}')
301
+ add('time grids', 'error' if grid_errors else 'ok', len(grid_errors), '; '.join(grid_errors))
302
+ if grid_errors:
303
+ return ValidationReport(pd.DataFrame(rows), coverage, skipped)
304
+
305
+ coverage.update(input1_rows=len(d1), input3_rows=len(d3), input4_rows=len(d4))
306
+ for name, frame, cols, ids in (('input1', d1, cols1, ['GeneID', 'Psite']), ('input3', d3, cols3, ['GeneID'])):
307
+ values = frame[cols].apply(pd.to_numeric, errors='coerce')
308
+ bad = ~np.isfinite(values.to_numpy(dtype=float)).all(axis=1)
309
+ label = frame[ids].astype(str).agg(' '.join, axis=1)
310
+ add(f'{name} time series values', 'error' if bad.any() else 'ok', bad.sum(),
311
+ f"rows with missing or non-numeric values: {', '.join(label[bad].head(10))}" if bad.any() else '')
312
+ d1['Psite'] = d1['Psite'].fillna('').astype(str).str.strip()
313
+ dup1 = d1.duplicated(['GeneID', 'Psite'], keep=False)
314
+ add('duplicated input1 row', 'error' if dup1.any() else 'ok', dup1.sum(),
315
+ ', '.join((d1.loc[dup1, 'GeneID'] + ' ' + d1.loc[dup1, 'Psite']).drop_duplicates().head(10)))
316
+ odd = ~(d1['Psite'].eq('') | d1['Psite'].str.match(r'^[STY]_'))
317
+ add('input1 Psite neither empty nor S_/T_/Y_', 'warning' if odd.any() else 'ok', odd.sum(),
318
+ 'rows ignored: ' + ', '.join((d1.loc[odd, 'GeneID'] + ' ' + d1.loc[odd, 'Psite']).head(10)) if odd.any() else '')
319
+ dup3 = d3['GeneID'].duplicated(keep=False)
320
+ add('duplicated input3 row', 'warning' if dup3.any() else 'ok', dup3.sum(),
321
+ 'the first row of each GeneID is used' if dup3.any() else '')
322
+ empty_ids = d4[['Source', 'Target']].isna().any(axis=1) | d4[['Source', 'Target']].astype(str).apply(
323
+ lambda s: s.str.strip().eq('')).any(axis=1)
324
+ add('input4 missing identifiers', 'error' if empty_ids.any() else 'ok', empty_ids.sum())
325
+ if any(r['status'] == 'error' for r in rows):
326
+ return ValidationReport(pd.DataFrame(rows), coverage, skipped)
327
+
328
+ from tfopt.processing.map import regulation_map
329
+ from tfopt.processing.tfseries import build_tf_series
330
+ series = build_tf_series(d1, d3.drop_duplicates('GeneID'), source=tf_protein_source, ms_time_points=ms,
331
+ rna_time_points=rna, alignment=ms_alignment)
332
+ reg = regulation_map(d4)
333
+ targets_rna = set(d3['GeneID'].astype(str).str.strip())
334
+ edges = [(tf, gene) for gene, tfs in reg.items() for tf in tfs]
335
+ drop = []
336
+ for tf, gene in edges:
337
+ if gene not in targets_rna:
338
+ drop.append((tf, gene, 'target has no input3 row'))
339
+ elif tf not in series.sources:
340
+ drop.append((tf, gene, f"TF has {series.excluded.get(tf, 'no input1 or input3 series')}"))
341
+ dropped_edges = {(tf, g) for tf, g, _ in drop}
342
+ used_edges = [(tf, g) for tf, g in edges if (tf, g) not in dropped_edges]
343
+ targets = sorted({g for _, g in edges})
344
+ targets_used = sorted({g for _, g in used_edges})
345
+ for g in sorted(set(targets) - set(targets_used)):
346
+ if g in targets_rna:
347
+ drop.append(('', g, 'target has no regulator with a series'))
348
+ used_tfs = sorted({tf for tf, _ in used_edges})
349
+ kinds = [series.sources[tf] for tf in used_tfs]
350
+ coverage.update(targets=len(targets), targets_used=len(targets_used), tfs=len({tf for tf, _ in edges}),
351
+ tfs_protein=kinds.count('protein'), tfs_mrna=kinds.count('mrna'),
352
+ tfs_first_site=kinds.count('first_site'),
353
+ tfs_excluded=len({tf for tf, _ in edges} - set(used_tfs)), edges=len(edges),
354
+ edges_used=len(used_edges))
355
+ n_tf_drop = sum(1 for _, _, r in drop if r.startswith('TF '))
356
+ add('TF without series', 'warning' if n_tf_drop else 'ok', coverage['tfs_excluded'],
357
+ f'{n_tf_drop} edges dropped' if n_tf_drop else '')
358
+ n_target_drop = sum(1 for _, _, r in drop if r.startswith('target'))
359
+ add('target dropped', 'warning' if n_target_drop else 'ok', n_target_drop,
360
+ ', '.join(sorted({g for _, g, r in drop if r.startswith('target')})[:10]))
361
+ add('targets to fit', 'error' if not targets_used else 'ok', len(targets_used),
362
+ '' if targets_used else 'no target has a regulator with a series')
363
+ add('coverage', 'ok', coverage['targets_used'],
364
+ f"{coverage['targets_used']} targets, {len(used_tfs)} TFs ({coverage['tfs_protein']} protein, "
365
+ f"{coverage['tfs_mrna']} mRNA, {coverage['tfs_first_site']} first site), {coverage['edges_used']} of "
366
+ f"{coverage['edges']} edges")
367
+ skipped = pd.DataFrame(drop, columns=['Source', 'Target', 'reason'])
368
+ return ValidationReport(pd.DataFrame(rows), coverage, skipped)
369
+
370
+
371
+ # ------------------------------------------------------------------------------------------------------ run
372
+
373
+ @dataclass
374
+ class RunResult:
375
+ """Result of `run`.
376
+
377
+ Attributes:
378
+ config (RunConfig): The configuration used.
379
+ results_dir (Path): Output folder.
380
+ workbook (Path): Results workbook.
381
+ best_objective (float): Objective of the selected fit.
382
+ selected_start (int): Start id of the selected fit.
383
+ success (bool): The selected fit converged and is feasible.
384
+ accepted (bool): Success, constraint residual <= 1e-10 and the KKT verdict.
385
+ multistart (DataFrame): One row per start (multistart_summary.csv).
386
+ kkt: KKT diagnostics of the selected fit (``tfopt.optimality.kkt_diagnostics.KKTReport``).
387
+ diagnostics (dict): The contents of diagnostics.json.
388
+ bundle (Path | None): The run bundle (zip), if written.
389
+ """
390
+
391
+ config: RunConfig
392
+ results_dir: Path
393
+ workbook: Path
394
+ best_objective: float
395
+ selected_start: int
396
+ success: bool
397
+ accepted: bool
398
+ multistart: pd.DataFrame
399
+ kkt: object
400
+ diagnostics: dict
401
+ bundle: Path | None = None
402
+
403
+
404
+ def _git_info():
405
+ """Commit, branch and dirty flag of the code, if it runs from a git clone (else None values)."""
406
+ import subprocess
407
+ root = Path(__file__).resolve().parent.parent
408
+ try:
409
+ def git(*a):
410
+ return subprocess.run(['git', *a], cwd=root, capture_output=True, text=True, timeout=10,
411
+ check=True).stdout.strip()
412
+ if git('rev-parse', '--show-toplevel') != str(root):
413
+ raise RuntimeError
414
+ return {'commit': git('rev-parse', 'HEAD'), 'branch': git('rev-parse', '--abbrev-ref', 'HEAD'),
415
+ 'dirty': bool(git('status', '--porcelain', '--untracked-files=no'))}
416
+ except Exception:
417
+ return {'commit': None, 'branch': None, 'dirty': None}
418
+
419
+
420
+ def _sha256(path) -> str:
421
+ import hashlib
422
+ h = hashlib.sha256()
423
+ with open(path, 'rb') as f:
424
+ for chunk in iter(lambda: f.read(1 << 20), b''):
425
+ h.update(chunk)
426
+ return h.hexdigest()
427
+
428
+
429
+ def run(config: RunConfig, progress=None, quiet=False) -> RunResult:
430
+ """Run the fit with a RunConfig and write the results to ``config.results_dir``.
431
+
432
+ Writes the same outputs as ``tfopt-local``: the workbook (Alpha Values, Beta Values with Source, Residuals,
433
+ Observed, Estimated, Optimization Results, KKT Diagnostics, KKT Multipliers), multistart_summary.csv,
434
+ multistart_params.npz, diagnostics.json and, if enabled, the plots, fit-analysis figures, LaTeX tables and
435
+ report.html; plus ``run_config.json`` (resolved configuration, seeds, versions, git commit, input sha256s,
436
+ selected start, KKT verdict) and the log in ``<results_dir>/logs``.
437
+
438
+ Args:
439
+ config (RunConfig): The run settings.
440
+ progress (callable | None): Called as ``progress(done, total, result)`` each time a start finishes.
441
+ quiet (bool): Show only warnings and errors on the console; the log file is complete either way.
442
+
443
+ Returns:
444
+ RunResult: Summary of the run (also when the selected fit is not accepted; check ``accepted``).
445
+ """
446
+ import logging
447
+ from tfopt import __version__
448
+ from tfopt.local.config.logconf import setup_logger
449
+ from tfopt.local.exporter.plotout import plot_estimated_vs_observed, plot_multistart_summary_runtime_overlay
450
+ from tfopt.local.exporter.sheetutils import (export_multistart_results, export_to_ode_data_dir,
451
+ save_multistart_solutions_npz, save_results_to_excel)
452
+ from tfopt.local.objfn.minfn import compute_predictions, objective_
453
+ from tfopt.local.opt.optrun import multistart_config, run_optimizer, run_optimizer_multistart, \
454
+ _get_constraint_violation
455
+ from tfopt.local.optcon.feasibility import ParameterGeometry
456
+ from tfopt.local.optcon.filter import load_and_filter_data, prepare_data
457
+ from tfopt.local.utils.iodata import create_report
458
+ from tfopt.local.utils.params import get_optimization_parameters, postprocess_results
459
+ from tfopt.optimality.KKT import diagnostics as optimality_diagnostics
460
+ from tfopt.optimality.kkt_diagnostics import kkt_report, summary_columns
461
+ from tfopt.fitanalysis.metrics import fit_metrics
462
+
463
+ c = config
464
+ out_dir = Path(c.results_dir)
465
+ log_dir = out_dir / 'logs'
466
+ log_dir.mkdir(parents=True, exist_ok=True)
467
+ logger = setup_logger(log_dir=log_dir)
468
+ for handler in logger.handlers:
469
+ if isinstance(handler, logging.StreamHandler) and not isinstance(handler, logging.FileHandler):
470
+ handler.setLevel(logging.WARNING if quiet else logging.INFO)
471
+ logger.info('[Local Optimization] mRNA-TF Optimization Problem Started')
472
+ workbook = out_dir / c.out_file
473
+ transform, loss_type = c.prediction_transform, c.loss_type
474
+
475
+ (gene_ids, expr_matrix, expr_time_cols, tf_ids, tf_protein, tf_psite_data, tf_psite_labels, tf_time_cols,
476
+ reg_map, tf_sources) = load_and_filter_data(
477
+ input1=c.input1, input3=c.input3, input4=c.input4, source=c.tf_protein_source, alignment=c.ms_alignment,
478
+ ms_time_points=c.ms_time_points, rna_time_points=c.time_points, with_sources=True)
479
+ fixed_arrays, T_use = prepare_data(gene_ids, expr_matrix, tf_ids, tf_protein, tf_psite_data, tf_psite_labels,
480
+ tf_time_cols, reg_map)
481
+ (expression_matrix, regulators, tf_protein_matrix, psite_tensor, n_reg, _, psite_labels_arr,
482
+ num_psites) = fixed_arrays
483
+ x0, n_alpha, beta_start_indices, bounds, _, n_genes, _, num_psites, lin_cons, T_use = \
484
+ get_optimization_parameters(expression_matrix, tf_protein_matrix, n_reg, T_use, psite_labels_arr,
485
+ num_psites, c.lower_bound, c.upper_bound, regulators=regulators,
486
+ seed=c.start_seed)
487
+ cfg = multistart_config({'method': c.method, 'n_starts': c.n_starts, 'jitter_frac': c.jitter_scale,
488
+ 'seed': c.seed, 'p_random': c.p_random, 'maxiter': c.maxiter, 'tol': c.tol,
489
+ 'n_jobs': c.n_jobs, 'threads_per_worker': c.threads_per_worker,
490
+ 'allow_nonsmooth': c.allow_nonsmooth, 'feasibility_tol': c.feasibility_tol,
491
+ 'acceptance_tol': c.acceptance_tol},
492
+ prediction_transform=transform)
493
+ logger.info(f'[Multistart] method={cfg.method} n_starts={cfg.n_starts} jitter={cfg.jitter_frac} '
494
+ f'seed={cfg.seed} start_seed={c.start_seed} n_jobs={cfg.n_jobs} '
495
+ f'threads_per_worker={cfg.threads_per_worker}')
496
+ result, all_results = run_optimizer_multistart(
497
+ x0, bounds, lin_cons, expression_matrix, regulators, tf_protein_matrix, psite_tensor, n_reg, T_use,
498
+ n_genes, beta_start_indices, num_psites, loss_type, run_optimizer_func=run_optimizer, cfg=cfg, polish=True,
499
+ progress=progress)
500
+ logger.info(f"[Multistart] best fun={result.fun} success={result.success} "
501
+ f"cv={_get_constraint_violation(result)} start_id={getattr(result, 'start_id', None)}")
502
+ summary = export_multistart_results(all_results)
503
+ summary.to_csv(out_dir / 'multistart_summary.csv', index=False)
504
+ save_multistart_solutions_npz(all_results, out_dir / 'multistart_params.npz')
505
+ if c.plots:
506
+ plot_multistart_summary_runtime_overlay(out_dir / 'multistart_summary.csv',
507
+ out_path=out_dir / 'multistart_fun_vs_rank_runtime.png',
508
+ figsize=(8, 8))
509
+
510
+ final_x, final_alpha, final_beta = postprocess_results(result, n_alpha, n_genes, n_reg, beta_start_indices,
511
+ num_psites, reg_map, gene_ids, tf_ids, psite_labels_arr)
512
+
513
+ def objective(x, loss=loss_type):
514
+ return objective_(x, expression_matrix, regulators, tf_protein_matrix, psite_tensor, n_reg, T_use, n_genes,
515
+ beta_start_indices, num_psites, loss, prediction_transform=transform)
516
+
517
+ geom_bounds = [(max(lo, 0.), hi) for lo, hi in bounds] if result.method == 'non-negative' else bounds
518
+ geometry = ParameterGeometry(geom_bounds, regulators, beta_start_indices, num_psites, n_genes, n_reg, lin_cons)
519
+ param_labels = [f"alpha {gene} {tf_ids[regulators[i, j]] if regulators[i, j] >= 0 else 'padding'}"
520
+ for i, gene in enumerate(gene_ids) for j in range(n_reg)]
521
+ param_labels += [f'beta {tf} {label}' for k, tf in enumerate(tf_ids)
522
+ for label in ['TF', *psite_labels_arr[k][:num_psites[k]]]]
523
+ eq_labels = [f'sum alpha {gene}' for gene in gene_ids] + [f'sum beta {tf}' for tf in tf_ids]
524
+ kkt = kkt_report(final_x, objective, geometry, eq_labels=eq_labels, param_labels=param_labels)
525
+ logger.info('KKT diagnostics: ' + '; '.join(f"{r.condition} {r.residual:.3g} ({'pass' if r.passed else 'fail'})"
526
+ for r in kkt.conditions.itertuples()))
527
+
528
+ predictions = np.asarray(compute_predictions(final_x, regulators, tf_protein_matrix, psite_tensor, n_reg, T_use,
529
+ n_genes, beta_start_indices, num_psites, transform))
530
+ from tfopt.local.utils.params import prediction_check
531
+ raw = np.asarray(compute_predictions(final_x, regulators, tf_protein_matrix, psite_tensor, n_reg, T_use, n_genes,
532
+ beta_start_indices, num_psites, 'none')) # before the transform
533
+ pred_check = prediction_check(list(gene_ids), raw, logger=logger)
534
+ negative = {'targets': int(pred_check['negative'].sum()), 'time_points': int(pred_check['negative_points'].sum())}
535
+ if c.plots:
536
+ plot_estimated_vs_observed(predictions, expression_matrix, gene_ids, c.time_points, regulators,
537
+ tf_protein_matrix, tf_ids, num_targets=n_genes, save_path=out_dir)
538
+ save_results_to_excel(gene_ids, tf_ids, final_alpha, final_beta, psite_labels_arr, expression_matrix,
539
+ predictions, result.fun, reg_map, filename=workbook, tf_sources=tf_sources,
540
+ prediction_transform=transform, kkt_report=kkt, method=result.method,
541
+ prediction_check=pred_check)
542
+ if c.fit_analysis and c.plots:
543
+ from tfopt.fitanalysis.helper import Plotter
544
+ plotter = Plotter(workbook, out_dir)
545
+ for name in ('plot_alpha_distribution', 'plot_beta_barplots', 'plot_heatmap_abs_residuals',
546
+ 'plot_goodness_of_fit', 'plot_kld', 'plot_pca', 'plot_boxplot_alpha', 'plot_boxplot_beta',
547
+ 'plot_cdf_alpha', 'plot_cdf_beta', 'plot_time_wise_residuals'):
548
+ getattr(plotter, name)()
549
+
550
+ metrics = fit_metrics(expression_matrix, predictions)
551
+ data_loss = float(objective(final_x, loss_type if loss_type < 5 else 0))
552
+ diagnostics = {'data_fitting_loss': data_loss, 'regularization_loss': result.fun - data_loss,
553
+ 'constraint_penalty': 0., 'total_penalized_objective': result.penalized_fun,
554
+ 'start_seed': c.start_seed, 'prediction_transform': transform, 'n_starts': cfg.n_starts,
555
+ 'jitter_frac': cfg.jitter_frac, 'seed': cfg.seed, 'n_jobs': cfg.n_jobs,
556
+ 'threads_per_worker': cfg.threads_per_worker, 'success': result.success,
557
+ 'accepted': getattr(result, 'accepted', None), 'message': result.message,
558
+ 'constraint_violation': result.constr_violation, 'method': result.method, **metrics}
559
+ diagnostics.update(optimality_diagnostics(final_x, objective, geometry))
560
+ diagnostics.update(final_error=result.final_error, runtime_s=result.runtime_s, nit=result.nit,
561
+ negative_prediction_targets=negative['targets'], **summary_columns(kkt))
562
+ (out_dir / 'diagnostics.json').write_text(json.dumps(diagnostics, indent=2))
563
+ if c.copy_to_ode_data_dir is not None:
564
+ export_to_ode_data_dir(workbook, c.copy_to_ode_data_dir, enabled=True)
565
+
566
+ selected = int(getattr(result, 'start_id', -1))
567
+ provenance = {
568
+ 'tfopt_version': __version__,
569
+ 'git': _git_info(),
570
+ 'created_utc': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
571
+ 'python': platform.python_version(),
572
+ 'config': c.to_dict(),
573
+ 'seeds': {'start_seed': c.start_seed, 'multistart': [int(cfg.seed + i) for i in range(cfg.n_starts)]},
574
+ 'selected_start': selected,
575
+ 'selected': {'objective': float(result.fun), 'success': bool(result.success),
576
+ 'accepted': bool(getattr(result, 'accepted', False)), 'method': result.method},
577
+ 'inputs': [{'name': n, 'path': str(p), 'sha256': _sha256(p), 'bytes': Path(p).stat().st_size}
578
+ for n, p in (('input1', c.input1), ('input3', c.input3), ('input4', c.input4))],
579
+ 'tf_sources': {k: sum(v == k for v in tf_sources.values()) for k in ('protein', 'mrna', 'first_site')},
580
+ 'negative_predictions': negative,
581
+ 'kkt': {'source': kkt.source, 'passed': kkt.passed, 'conditions': kkt.conditions.to_dict(orient='records')},
582
+ }
583
+ (out_dir / 'run_config.json').write_text(json.dumps(provenance, indent=2, default=str))
584
+
585
+ if c.report:
586
+ for gene in gene_ids:
587
+ gene_dir = out_dir / str(gene)
588
+ for path in out_dir.glob(f'{gene}_*'):
589
+ if path.is_file():
590
+ gene_dir.mkdir(exist_ok=True)
591
+ shutil.move(str(path), str(gene_dir / path.name))
592
+ from tfopt.local.exporter import latexit
593
+ latexit.main(out_dir)
594
+ create_report(out_dir)
595
+ bundle_path = None
596
+ if c.bundle:
597
+ from tfopt.bundle import make_bundle
598
+ folder = out_dir / f'{out_dir.name}.tfopt'
599
+ bundle_path = make_bundle(out_dir, out_dir=folder, zip=True)
600
+ shutil.rmtree(folder)
601
+ logger.info(f'Run bundle: {bundle_path}')
602
+ logger.info(f'[Local] Report & Results {out_dir}')
603
+ return RunResult(config=c, results_dir=out_dir, workbook=workbook, best_objective=float(result.fun),
604
+ selected_start=selected, success=bool(result.success),
605
+ accepted=bool(getattr(result, 'accepted', False)), multistart=summary, kkt=kkt,
606
+ diagnostics=diagnostics, bundle=bundle_path)
607
+
608
+
609
+ # ----------------------------------------------------------------------------------------------- results
610
+
611
+ @dataclass
612
+ class Results:
613
+ """A results folder read back by `read_results`.
614
+
615
+ Attributes:
616
+ results_dir (Path): The folder.
617
+ workbook (Path): The results workbook.
618
+ sheets (dict[str, DataFrame]): Every sheet of the workbook.
619
+ multistart (DataFrame): The multistart summary (one row per start).
620
+ run_config (dict | None): ``run_config.json`` if present.
621
+ diagnostics (dict | None): ``diagnostics.json`` if present.
622
+ best_objective (float): The smallest objective over the starts.
623
+ """
624
+
625
+ results_dir: Path
626
+ workbook: Path
627
+ sheets: dict
628
+ multistart: pd.DataFrame
629
+ run_config: dict | None
630
+ diagnostics: dict | None
631
+ best_objective: float
632
+
633
+
634
+ def _find(results_dir: Path, name: str) -> Path:
635
+ for candidate in (results_dir / name, results_dir / 'General' / name):
636
+ if candidate.exists():
637
+ return candidate
638
+ hits = sorted(results_dir.rglob(name))
639
+ if not hits:
640
+ raise FileNotFoundError(f'{name} not found in {results_dir}')
641
+ return hits[0]
642
+
643
+
644
+ def read_results(results_dir, out_file='tfopt_results.xlsx') -> Results:
645
+ """Read a results folder written by `run` (or by ``tfopt-local``).
646
+
647
+ Args:
648
+ results_dir (str | Path): The results folder.
649
+ out_file (str): Name of the workbook.
650
+
651
+ Returns:
652
+ Results: Workbook sheets, multistart summary and provenance.
653
+ """
654
+ results_dir = Path(results_dir)
655
+ workbook = _find(results_dir, out_file)
656
+ sheets = pd.read_excel(workbook, sheet_name=None)
657
+ multistart = pd.read_csv(_find(results_dir, 'multistart_summary.csv'))
658
+ rc, dj = results_dir / 'run_config.json', results_dir / 'diagnostics.json'
659
+ return Results(results_dir, workbook, sheets, multistart,
660
+ json.loads(rc.read_text()) if rc.exists() else None,
661
+ json.loads(dj.read_text()) if dj.exists() else None,
662
+ float(multistart['fun'].min()))