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/app/backend.py ADDED
@@ -0,0 +1,593 @@
1
+ """The GUI's backend: one session per ``tfopt-app`` start, bound to one working folder (as kinopt.app.backend).
2
+
3
+ Everything the GUI does goes through `Session` and calls the library functions the command line uses
4
+ (``tfopt.api.load_config``, ``tfopt.api.validate_inputs``, ``tfopt.api.run``, ``tfopt.api.read_results``). Files are
5
+ only read from and written to the working folder: uploads go to ``<workdir>/inputs/`` (``input1.csv``,
6
+ ``input3.csv``, ``input4.csv`` and optionally ``config.toml``), the example project to ``<workdir>/example/`` and
7
+ runs to ``<workdir>/runs/<run id>/``; paths from the browser are resolved against the working folder and refused if
8
+ they leave it.
9
+
10
+ TFOpt has no built-in time grid: the RNA grid (``time_points``, input3 columns) and the MS grid
11
+ (``ms_time_points``, input1 columns) come from the user, from an uploaded config.toml or from the example project.
12
+
13
+ A run executes in its own process (its own process group on POSIX), so it can be cancelled with its workers.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import dataclasses
18
+ import math
19
+ import multiprocessing as mp
20
+ import os
21
+ import queue as queue_mod
22
+ import re
23
+ import secrets
24
+ import shutil
25
+ import signal
26
+ import threading
27
+ import time
28
+ import traceback
29
+ from datetime import datetime
30
+ from pathlib import Path
31
+
32
+ #: Roles of the uploaded files and their file name in ``<workdir>/inputs``.
33
+ UPLOAD_ROLES = {"input1": "input1.csv", "input3": "input3.csv", "input4": "input4.csv", "config": "config.toml"}
34
+ #: File type accepted for each role.
35
+ ROLE_SUFFIXES = {"input1": ".csv", "input3": ".csv", "input4": ".csv", "config": ".toml"}
36
+ #: The three data inputs of a run.
37
+ INPUT_ROLES = ("input1", "input3", "input4")
38
+ #: Default upload limit per file (bytes).
39
+ DEFAULT_MAX_UPLOAD_BYTES = 50 * 1024 * 1024
40
+
41
+ #: Settings without a default: TFOpt has no built-in time grid.
42
+ REQUIRED_SETTINGS = ["ms_time_points", "time_points"]
43
+ #: Settings shown first in the configuration step; the others are folded away as advanced options.
44
+ BASIC_SETTINGS = ["ms_time_points", "time_points", "method", "n_starts", "loss_type", "prediction_transform",
45
+ "lower_bound", "upper_bound", "tf_protein_source"]
46
+ #: Settings the browser may not set: they name files or folders (the session chooses them inside the working folder).
47
+ LOCKED_SETTINGS = {"input1", "input3", "input4", "results_dir", "out_file", "copy_to_ode_data_dir", "bundle"}
48
+
49
+ _DEFAULT_INPUTS = {role: f"inputs/{UPLOAD_ROLES[role]}" for role in INPUT_ROLES}
50
+ _ANSI = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
51
+
52
+
53
+ class PathError(ValueError):
54
+ """A path from the browser leaves the working folder or names something not allowed."""
55
+
56
+
57
+ class UploadError(ValueError):
58
+ """An upload is refused; ``status`` is the HTTP status to answer with."""
59
+
60
+ def __init__(self, message, status):
61
+ super().__init__(message)
62
+ self.status = status
63
+
64
+
65
+ def _run_worker(config: dict, events, console: str) -> None:
66
+ """Run ``tfopt.api.run`` in a child process and report progress and the outcome on ``events``."""
67
+ if hasattr(os, "setpgrp"):
68
+ os.setpgrp() # own process group: cancel stops the multistart workers too
69
+ os.environ.setdefault("MPLBACKEND", "Agg")
70
+ try: # the run's console output (LaTeX tables, warnings) goes to the run folder, not to tfopt-app's terminal
71
+ fd = os.open(console, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
72
+ os.dup2(fd, 1)
73
+ os.dup2(fd, 2)
74
+ os.close(fd)
75
+ except OSError:
76
+ pass
77
+ try:
78
+ from tfopt import api
79
+ cfg = api.RunConfig(**config)
80
+ result = api.run(cfg, progress=lambda done, total, o: events.put(
81
+ ("progress", int(done), int(total), float(getattr(o, "fun", math.nan)))), quiet=True)
82
+ events.put(("done", float(result.best_objective), int(result.selected_start), bool(result.success),
83
+ bool(result.accepted), None if result.bundle is None else str(result.bundle)))
84
+ except BaseException: # report every failure to the GUI
85
+ events.put(("failed", traceback.format_exc()))
86
+ finally:
87
+ events.close()
88
+ events.join_thread()
89
+
90
+
91
+ @dataclasses.dataclass
92
+ class _Run:
93
+ run_id: str
94
+ folder: Path
95
+ out_file: str
96
+ process: object
97
+ events: object
98
+ state: str = "running"
99
+ done: int = 0
100
+ total: int = 0
101
+ best: float | None = None
102
+ started: float = dataclasses.field(default_factory=time.time)
103
+ finished: float | None = None
104
+ error: str | None = None
105
+ bundle: str | None = None
106
+ selected_start: int | None = None
107
+ success: bool | None = None
108
+ accepted: bool | None = None
109
+
110
+
111
+ def _settings_of(path, label) -> dict:
112
+ """The settings of a config.toml (``tfopt.api.load_config``) without the paths the GUI chooses itself."""
113
+ from tfopt import api
114
+ try:
115
+ cfg = api.load_config(path)
116
+ except (TypeError, KeyError) as exc:
117
+ raise ValueError(f"{label}: {exc}") from exc
118
+ return {k: v for k, v in cfg.to_dict().items() if k not in LOCKED_SETTINGS}
119
+
120
+
121
+ class Session:
122
+ """State of one GUI session: the working folder, the token, the uploads and the runs.
123
+
124
+ Args:
125
+ workdir (str | Path): The working folder; created if missing. Nothing is written outside it.
126
+ max_upload_bytes (int): Largest accepted upload.
127
+ token (str | None): Session token; a random one by default.
128
+ config (str | Path | None): A config.toml whose settings (time grids included; not its paths) are the GUI's
129
+ defaults and the base of every run (``tfopt-app --config``, as KinOpt 0.11.0).
130
+
131
+ Raises:
132
+ ValueError: ``config`` is not a valid configuration (see ``config_settings``).
133
+ """
134
+
135
+ def __init__(self, workdir, max_upload_bytes=DEFAULT_MAX_UPLOAD_BYTES, token=None, config=None):
136
+ self.workdir = Path(workdir).expanduser().resolve()
137
+ self.workdir.mkdir(parents=True, exist_ok=True)
138
+ self.max_upload_bytes = int(max_upload_bytes)
139
+ self.token = token or secrets.token_urlsafe(32)
140
+ self._runs: dict[str, _Run] = {}
141
+ self._lock = threading.Lock()
142
+ self._ctx = mp.get_context("spawn")
143
+ self.config = None if config is None else Path(config).expanduser().resolve()
144
+ self.preset = {} if self.config is None else _settings_of(self.config, str(self.config))
145
+
146
+ # ------------------------------------------------------------------------------------------ paths
147
+
148
+ def resolve(self, relative) -> Path:
149
+ """Resolve a path given by the browser inside the working folder.
150
+
151
+ Raises:
152
+ PathError: The path is absolute or leaves the working folder (``..``, symlinks).
153
+ """
154
+ rel = str(relative or "")
155
+ if not rel or Path(rel).is_absolute() or "\\" in rel or "\x00" in rel:
156
+ raise PathError(f"not a path inside the working folder: {rel!r}")
157
+ path = (self.workdir / rel).resolve()
158
+ if path != self.workdir and self.workdir not in path.parents:
159
+ raise PathError(f"path leaves the working folder: {rel!r}")
160
+ return path
161
+
162
+ def _rel(self, path: Path) -> str:
163
+ return path.resolve().relative_to(self.workdir).as_posix()
164
+
165
+ # ---------------------------------------------------------------------------------------- uploads
166
+
167
+ def check_upload(self, role: str, filename: str, length: int) -> Path:
168
+ """Check an upload before reading its body and return where it will be stored.
169
+
170
+ Raises:
171
+ UploadError: Unknown role (400), file type not allowed for the role (415) or too large (413).
172
+ """
173
+ if role not in UPLOAD_ROLES:
174
+ raise UploadError(f"unknown upload {role!r}; expected one of {', '.join(UPLOAD_ROLES)}", 400)
175
+ if Path(str(filename)).suffix.lower() != ROLE_SUFFIXES[role]:
176
+ raise UploadError(f"{filename!r}: only {ROLE_SUFFIXES[role]} files are accepted for {role}", 415)
177
+ if length < 0 or length > self.max_upload_bytes:
178
+ raise UploadError(f"upload of {length} bytes exceeds the limit of {self.max_upload_bytes} bytes", 413)
179
+ return self.resolve(f"inputs/{UPLOAD_ROLES[role]}")
180
+
181
+ def save_upload(self, role: str, filename: str, data: bytes) -> str:
182
+ """Store an uploaded file as ``inputs/<role file>`` and return its path relative to the working folder."""
183
+ target = self.check_upload(role, filename, len(data))
184
+ target.parent.mkdir(parents=True, exist_ok=True)
185
+ tmp = target.with_suffix(".part")
186
+ tmp.write_bytes(data)
187
+ tmp.replace(target)
188
+ return self._rel(target)
189
+
190
+ def files(self) -> list:
191
+ """The uploaded files in the working folder's ``inputs/`` (relative paths)."""
192
+ folder = self.workdir / "inputs"
193
+ if not folder.exists():
194
+ return []
195
+ return sorted(self._rel(folder / name) for name in UPLOAD_ROLES.values() if (folder / name).is_file())
196
+
197
+ # ----------------------------------------------------------------------------- config and example
198
+
199
+ def config_settings(self, relative="inputs/config.toml") -> dict:
200
+ """Read the settings of a config.toml of the working folder with ``tfopt.api.load_config``.
201
+
202
+ Its paths are ignored (the GUI chooses them in the working folder); keys the file does not set get the values
203
+ ``load_config`` gives them (as ``tfopt run --config``).
204
+
205
+ Raises:
206
+ ValueError: The file is not valid TOML, lacks a time grid or has an unsupported value.
207
+ """
208
+ path = self.resolve(relative)
209
+ if not path.is_file():
210
+ raise PathError(f"{relative} does not exist")
211
+ return _settings_of(path, relative)
212
+
213
+ def use_example(self) -> dict:
214
+ """Copy the synthetic example (``tfopt.examples``) into ``inputs/`` and return its files and settings.
215
+
216
+ The example project is written once to ``<workdir>/example/`` (``tfopt example``); its data replace the files
217
+ in ``inputs/``. The settings (time grids included) are those of its config.toml.
218
+ """
219
+ from tfopt.examples import write_example
220
+ folder = self.resolve("example")
221
+ if not (folder / "config.toml").exists():
222
+ write_example(folder)
223
+ inputs = self.resolve("inputs")
224
+ inputs.mkdir(parents=True, exist_ok=True)
225
+ files = {}
226
+ for role in INPUT_ROLES:
227
+ target = inputs / UPLOAD_ROLES[role]
228
+ shutil.copyfile(folder / "data" / f"{role}.csv", target)
229
+ files[role] = self._rel(target)
230
+ return {"files": files, "settings": self.config_settings("example/config.toml")}
231
+
232
+ # -------------------------------------------------------------------------------------- settings
233
+
234
+ def defaults(self) -> dict:
235
+ """Default settings (those of ``tfopt.api.RunConfig``), grouped into basic and advanced, with the choices."""
236
+ from tfopt.api import LOSS_TYPES, MS_ALIGNMENTS, TF_PROTEIN_SOURCES, RunConfig
237
+ from tfopt.local.objfn.minfn import PREDICTION_TRANSFORMS
238
+ from tfopt.local.opt.optrun import METHODS
239
+ fields = [f for f in dataclasses.fields(RunConfig) if f.name not in LOCKED_SETTINGS]
240
+ values = {}
241
+ for f in fields:
242
+ if f.default_factory is not dataclasses.MISSING:
243
+ values[f.name] = f.default_factory()
244
+ elif f.default is not dataclasses.MISSING:
245
+ values[f.name] = f.default
246
+ else: # the time grids: no default
247
+ values[f.name] = []
248
+ choices = {"method": list(METHODS), "prediction_transform": list(PREDICTION_TRANSFORMS),
249
+ "loss_type": sorted(LOSS_TYPES), "tf_protein_source": list(TF_PROTEIN_SOURCES),
250
+ "ms_alignment": list(MS_ALIGNMENTS)}
251
+ values.update(self.preset) # tfopt-app --config
252
+ return {"values": values, "required": REQUIRED_SETTINGS, "basic": BASIC_SETTINGS,
253
+ "advanced": [f.name for f in fields if f.name not in BASIC_SETTINGS], "choices": choices,
254
+ "choice_labels": {"loss_type": {str(k): v for k, v in LOSS_TYPES.items()}}}
255
+
256
+ def run_config(self, settings: dict, inputs=None, run_id=None):
257
+ """Build the RunConfig of a run from the browser's settings (paths are chosen here, in the working folder).
258
+
259
+ Args:
260
+ settings (dict): RunConfig fields set by the browser; ``time_points`` and ``ms_time_points`` are required.
261
+ inputs (dict | None): Paths of input1, input3 and input4 relative to the working folder.
262
+ run_id (str | None): Folder name under ``runs/``.
263
+
264
+ Raises:
265
+ ValueError: A setting is locked, unknown, of the wrong type or invalid, or a time grid is missing.
266
+ """
267
+ from tfopt.api import RunConfig
268
+ settings = dict(settings or {})
269
+ locked = LOCKED_SETTINGS & set(settings)
270
+ # The browser sends only what differs from the defaults: the rest comes from --config (if given).
271
+ settings = {**self.preset, **settings}
272
+ if locked:
273
+ raise ValueError(f"settings not allowed from the GUI: {', '.join(sorted(locked))}")
274
+ fields = {f.name: f for f in dataclasses.fields(RunConfig)}
275
+ unknown = set(settings) - set(fields)
276
+ if unknown:
277
+ raise ValueError(f"unknown settings: {', '.join(sorted(unknown))}")
278
+ missing = [k for k in REQUIRED_SETTINGS if not settings.get(k)]
279
+ if missing:
280
+ raise ValueError(f"{' and '.join(missing)} must be set (the MS and RNA time grids in minutes); TFOpt has "
281
+ "no built-in time grid")
282
+ for name, value in list(settings.items()):
283
+ _check_type(name, value, fields[name])
284
+ if isinstance(fields[name].default, float): # JavaScript writes -4.0 as -4: keep the field's type
285
+ settings[name] = float(value)
286
+ paths = {role: self.resolve((inputs or {}).get(role) or _DEFAULT_INPUTS[role]) for role in INPUT_ROLES}
287
+ return RunConfig(**paths, results_dir=self.resolve(f"runs/{run_id or 'check'}"), **settings)
288
+
289
+ # ------------------------------------------------------------------------------------- validation
290
+
291
+ def validate(self, inputs=None, settings=None) -> dict:
292
+ """Run ``tfopt.api.validate_inputs`` on the three inputs of the working folder, with the settings' grids,
293
+ TF protein source and MS alignment."""
294
+ from tfopt import api
295
+ cfg = self.run_config(settings or {}, inputs)
296
+ for p in (cfg.input1, cfg.input3, cfg.input4):
297
+ if not p.is_file():
298
+ raise PathError(f"{self._rel(p)} does not exist")
299
+ report = api.validate_inputs(cfg.input1, cfg.input3, cfg.input4, ms_time_points=cfg.ms_time_points,
300
+ time_points=cfg.time_points, tf_protein_source=cfg.tf_protein_source,
301
+ ms_alignment=cfg.ms_alignment)
302
+ return {"ok": report.ok, "checks": _table(report.checks), "coverage": _jsonable_dict(report.coverage),
303
+ "skipped": _table(report.skipped)}
304
+
305
+ # ------------------------------------------------------------------------------------------- runs
306
+
307
+ def start_run(self, settings: dict, inputs=None) -> str:
308
+ """Validate the inputs, then start a run in a child process; return its id (the folder name under ``runs/``).
309
+
310
+ Raises:
311
+ ValueError: A setting is invalid, or the inputs fail validation with these settings.
312
+ PathError: An input does not exist.
313
+ """
314
+ run_id = datetime.now().strftime("run-%Y%m%d-%H%M%S-") + secrets.token_hex(3)
315
+ cfg = self.run_config(settings, inputs, run_id=run_id)
316
+ report = self.validate(inputs, settings)
317
+ if not report["ok"]:
318
+ errors = [f"{row[0]}: {row[3]}" for row in report["checks"]["rows"] if row[1] == "error"]
319
+ raise ValueError("the inputs fail validation with these settings: " + "; ".join(errors))
320
+ cfg.results_dir.mkdir(parents=True, exist_ok=False)
321
+ (cfg.results_dir / "logs").mkdir(exist_ok=True)
322
+ events = self._ctx.Queue()
323
+ console = str(cfg.results_dir / "logs" / "console.txt")
324
+ proc = self._ctx.Process(target=_run_worker, args=(cfg.to_dict(), events, console), daemon=False)
325
+ proc.start()
326
+ run = _Run(run_id, cfg.results_dir, cfg.out_file, proc, events, total=cfg.n_starts)
327
+ with self._lock:
328
+ self._runs[run_id] = run
329
+ threading.Thread(target=self._watch, args=(run,), daemon=True).start()
330
+ return run_id
331
+
332
+ def _watch(self, run: _Run) -> None:
333
+ while True:
334
+ try:
335
+ ev = run.events.get(timeout=0.25)
336
+ except queue_mod.Empty:
337
+ if not run.process.is_alive():
338
+ try: # events written just before exit
339
+ ev = run.events.get(timeout=1.0)
340
+ except queue_mod.Empty:
341
+ with self._lock:
342
+ if run.state == "running":
343
+ run.state, run.error = "failed", f"the run stopped (exit code {run.process.exitcode})"
344
+ run.finished = run.finished or time.time()
345
+ return
346
+ else:
347
+ continue
348
+ except (OSError, ValueError, EOFError): # the queue was closed by a cancel
349
+ return
350
+ with self._lock:
351
+ if ev[0] == "progress":
352
+ _, run.done, run.total, fun = ev
353
+ if not math.isnan(fun):
354
+ run.best = fun if run.best is None else min(run.best, fun)
355
+ elif ev[0] == "done":
356
+ if run.state == "running":
357
+ run.state = "done"
358
+ run.best, run.selected_start, run.success, run.accepted, run.bundle = ev[1:]
359
+ run.finished = time.time()
360
+ elif ev[0] == "failed":
361
+ if run.state == "running":
362
+ run.state, run.error = "failed", ev[1]
363
+ run.finished = time.time()
364
+ if ev[0] in ("done", "failed"):
365
+ run.process.join(timeout=10)
366
+ return
367
+
368
+ def _get(self, run_id) -> _Run:
369
+ with self._lock:
370
+ run = self._runs.get(str(run_id))
371
+ if run is None:
372
+ raise KeyError(f"no run {run_id!r} in this session")
373
+ return run
374
+
375
+ def run_dir(self, run_id) -> Path:
376
+ """The results folder of a run."""
377
+ return self._get(run_id).folder
378
+
379
+ def is_alive(self, run_id) -> bool:
380
+ """True while the run's process is running."""
381
+ return self._get(run_id).process.is_alive()
382
+
383
+ def status(self, run_id, log_lines=200) -> dict:
384
+ """State, progress, best objective so far and the end of the log of a run."""
385
+ run = self._get(run_id)
386
+ logs = sorted((run.folder / "logs").glob("*.log")) if (run.folder / "logs").exists() else []
387
+ tail = []
388
+ if logs and log_lines:
389
+ text = logs[-1].read_text(errors="replace").splitlines()
390
+ # the working folder as <workdir>: shorter lines, and no local path on screen
391
+ tail = [_ANSI.sub("", line).rstrip().replace(str(self.workdir), "<workdir>")
392
+ for line in text[-log_lines:]]
393
+ with self._lock:
394
+ return {"run": run.run_id, "state": run.state, "done": run.done, "total": run.total,
395
+ "best": _jsonable(run.best), "elapsed_s": round((run.finished or time.time()) - run.started, 1),
396
+ "error": run.error, "selected_start": run.selected_start, "success": run.success,
397
+ "accepted": run.accepted, "log": tail}
398
+
399
+ def cancel(self, run_id) -> None:
400
+ """Stop a running run and its worker processes."""
401
+ run = self._get(run_id)
402
+ with self._lock:
403
+ if run.state != "running":
404
+ return
405
+ run.state, run.finished = "cancelled", time.time()
406
+ pid = run.process.pid
407
+ try:
408
+ if hasattr(os, "killpg"):
409
+ os.killpg(pid, signal.SIGTERM)
410
+ else: # pragma: no cover
411
+ run.process.terminate()
412
+ except ProcessLookupError:
413
+ pass
414
+ run.process.join(timeout=15)
415
+ if run.process.is_alive() and hasattr(os, "killpg"):
416
+ try:
417
+ os.killpg(pid, signal.SIGKILL)
418
+ except ProcessLookupError:
419
+ pass
420
+ run.process.join(timeout=5)
421
+
422
+ def runs(self) -> list:
423
+ """Every run of the session, newest first."""
424
+ with self._lock:
425
+ ids = list(self._runs)
426
+ return [self.status(i, log_lines=0) for i in reversed(ids)]
427
+
428
+ # ---------------------------------------------------------------------------------------- results
429
+
430
+ def bundle_path(self, run_id) -> Path:
431
+ """The run bundle (``<run id>.tfopt.zip``) of a finished run.
432
+
433
+ Raises:
434
+ FileNotFoundError: The run has not finished or wrote no bundle (``tfopt.bundle`` missing).
435
+ """
436
+ run = self._get(run_id)
437
+ if run.state != "done":
438
+ raise FileNotFoundError(f"run {run_id} has not finished")
439
+ path = Path(run.bundle) if run.bundle else run.folder / f"{run.folder.name}.tfopt.zip"
440
+ path = path.resolve()
441
+ if self.workdir not in path.parents:
442
+ raise PathError("bundle outside the working folder")
443
+ if not path.is_file():
444
+ raise FileNotFoundError(f"run {run_id} has no bundle")
445
+ return path
446
+
447
+ def results(self, run_id) -> dict:
448
+ """The results of a finished run, read from its results folder with ``tfopt.api.read_results``.
449
+
450
+ Returns:
451
+ dict: ``summary`` (objective, metrics and verdicts), ``bundle`` (file name or None) and ``tables``:
452
+ metrics, convergence, multistart (starts), constraint_checks, alpha, beta (with Source), tf_sources,
453
+ kkt_conditions and kkt_multipliers.
454
+ """
455
+ import pandas as pd
456
+ from tfopt import api
457
+ run = self._get(run_id)
458
+ if run.state != "done":
459
+ raise FileNotFoundError(f"run {run_id} has not finished")
460
+ res = api.read_results(run.folder, out_file=run.out_file)
461
+ diag = res.diagnostics or {}
462
+ rc = res.run_config or {}
463
+ cfg = rc.get("config", {})
464
+ sheets = res.sheets
465
+ tables = {}
466
+
467
+ metrics = [(k, v) for k, v in diag.items() if isinstance(v, (int, float, str, bool)) or v is None]
468
+ tables["metrics"] = _table(pd.DataFrame(metrics, columns=["Metric", "Value"]))
469
+
470
+ ms = res.multistart.copy()
471
+ if "accepted" in ms:
472
+ ms = ms.sort_values(["accepted", "fun"], ascending=[False, True], kind="mergesort")
473
+ else:
474
+ ms = ms.sort_values("fun", kind="mergesort")
475
+ conv = pd.DataFrame({"rank": range(1, len(ms) + 1), "start": ms["start_id"].to_numpy(),
476
+ "objective": ms["fun"].to_numpy(),
477
+ "distance from best": (ms["fun"] - ms["fun"].min()).to_numpy()})
478
+ for col in ("success", "feasible", "constraint_violation", "kkt_passed", "accepted", "nit", "runtime_s"):
479
+ if col in ms:
480
+ conv[col.replace("_", " ")] = ms[col].to_numpy()
481
+ tables["convergence"] = _table(conv)
482
+ tables["multistart"] = _table(res.multistart)
483
+
484
+ checks = _constraint_checks(sheets, float(cfg.get("lower_bound", -math.inf)),
485
+ float(cfg.get("upper_bound", math.inf)),
486
+ float(cfg.get("feasibility_tol", 1e-8)))
487
+ tables["constraint_checks"] = _table(checks)
488
+ for key, sheet in (("alpha", "Alpha Values"), ("beta", "Beta Values"), ("kkt_conditions", "KKT Diagnostics"),
489
+ ("kkt_multipliers", "KKT Multipliers"), ("prediction_check", "Prediction Check")):
490
+ if sheet in sheets:
491
+ tables[key] = _table(sheets[sheet])
492
+ sources = rc.get("tf_sources") or {}
493
+ if sources:
494
+ tables["tf_sources"] = _table(pd.DataFrame(list(sources.items()), columns=["Source", "TFs"]))
495
+
496
+ kkt = sheets.get("KKT Diagnostics")
497
+ summary = {
498
+ "objective": _jsonable(run.best), "selected_start": run.selected_start, "success": run.success,
499
+ "accepted": run.accepted, "method": diag.get("method"), "loss_type": cfg.get("loss_type"),
500
+ "SSE": _jsonable(diag.get("SSE")), "R^2": _jsonable(diag.get("R^2")),
501
+ "constraint_violation": _jsonable(diag.get("constraint_violation")),
502
+ "starts": len(res.multistart),
503
+ "starts_success": int(res.multistart["success"].sum()) if "success" in res.multistart else None,
504
+ "starts_feasible": int(res.multistart["feasible"].sum()) if "feasible" in res.multistart else None,
505
+ "starts_accepted": int(res.multistart["accepted"].sum()) if "accepted" in res.multistart else None,
506
+ "constraint_checks": len(checks), "constraint_checks_passed": int(checks["passed"].sum()),
507
+ "kkt_conditions": 0 if kkt is None else len(kkt),
508
+ "kkt_passed": None if kkt is None else int(kkt["passed"].astype(bool).sum()),
509
+ "tf_sources": _jsonable_dict(sources),
510
+ "negative_prediction_targets": (rc.get("negative_predictions") or {}).get("targets"),
511
+ }
512
+ try:
513
+ bundle = self.bundle_path(run_id).name
514
+ except (FileNotFoundError, PathError):
515
+ bundle = None
516
+ return {"run": run_id, "summary": summary, "bundle": bundle, "tables": tables}
517
+
518
+
519
+ def _constraint_checks(sheets, lower, upper, tol):
520
+ """Constraints of the selected fit, measured on the workbook: |Σα − 1| per target and α in [0, 1]; |Σβ − 1| per
521
+ TF and β in [lower_bound, upper_bound]. ``passed``: the residual is at most ``tol`` (feasibility_tol)."""
522
+ import pandas as pd
523
+ rows = []
524
+ alpha, beta = sheets.get("Alpha Values"), sheets.get("Beta Values")
525
+ if alpha is not None and len(alpha):
526
+ for target, grp in alpha.groupby("mRNA", sort=False):
527
+ v = grp["Value"].astype(float)
528
+ rows.append(("sum alpha = 1", str(target), abs(float(v.sum()) - 1.0), tol))
529
+ rows.append(("alpha in [0, 1]", str(target), float(max(0.0, -v.min(), v.max() - 1.0)), tol))
530
+ if beta is not None and len(beta):
531
+ for tf, grp in beta.groupby("TF", sort=False):
532
+ v = grp["Value"].astype(float)
533
+ rows.append(("sum beta = 1", str(tf), abs(float(v.sum()) - 1.0), tol))
534
+ rows.append((f"beta in [{lower:g}, {upper:g}]", str(tf),
535
+ float(max(0.0, lower - v.min(), v.max() - upper)), tol))
536
+ out = pd.DataFrame(rows, columns=["check", "item", "residual", "tolerance"])
537
+ out["passed"] = out["residual"] <= out["tolerance"]
538
+ return out
539
+
540
+
541
+ def _check_type(name, value, field) -> None:
542
+ """Refuse a setting whose JSON type does not match its RunConfig field."""
543
+ default = field.default if field.default is not dataclasses.MISSING else None
544
+ if name in REQUIRED_SETTINGS:
545
+ ok = isinstance(value, list) and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in value)
546
+ elif isinstance(default, bool):
547
+ ok = isinstance(value, bool)
548
+ elif isinstance(default, int):
549
+ ok = isinstance(value, int) and not isinstance(value, bool)
550
+ elif isinstance(default, float):
551
+ ok = isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
552
+ elif isinstance(default, str):
553
+ ok = isinstance(value, str)
554
+ else:
555
+ ok = True
556
+ if not ok:
557
+ raise ValueError(f"setting {name}: {value!r} has the wrong type")
558
+
559
+
560
+ def _jsonable(v):
561
+ """A JSON-safe scalar: NaN and NA as None, ±inf as a string, NumPy scalars as Python values."""
562
+ if v is None:
563
+ return None
564
+ if hasattr(v, "item") and not isinstance(v, (str, bytes)):
565
+ try:
566
+ v = v.item()
567
+ except (ValueError, AttributeError):
568
+ pass
569
+ if isinstance(v, float):
570
+ if math.isnan(v):
571
+ return None
572
+ if math.isinf(v):
573
+ return str(v)
574
+ return v
575
+ if isinstance(v, (bool, int, str)):
576
+ return v
577
+ try:
578
+ import pandas as pd
579
+ if pd.isna(v):
580
+ return None
581
+ except (TypeError, ValueError):
582
+ pass
583
+ return str(v)
584
+
585
+
586
+ def _jsonable_dict(d) -> dict:
587
+ return {str(k): _jsonable(v) for k, v in (d or {}).items()}
588
+
589
+
590
+ def _table(df) -> dict:
591
+ """A DataFrame as ``{"columns": [...], "rows": [[...], ...]}`` with JSON-safe values."""
592
+ return {"columns": [str(c) for c in df.columns],
593
+ "rows": [[_jsonable(v) for v in row] for row in df.astype(object).itertuples(index=False)]}