PyATCLI 2026.10.10__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 (71) hide show
  1. PyATCLI/__init__.py +196 -0
  2. PyATCLI/__main__.py +7 -0
  3. PyATCLI/_version.py +47 -0
  4. PyATCLI/analyses.py +640 -0
  5. PyATCLI/analysis/__init__.py +81 -0
  6. PyATCLI/analysis/auc.py +79 -0
  7. PyATCLI/analysis/curve_fit.py +88 -0
  8. PyATCLI/analysis/event_peth.py +263 -0
  9. PyATCLI/analysis/fft.py +99 -0
  10. PyATCLI/analysis/group/__init__.py +318 -0
  11. PyATCLI/analysis/group/rebuild.py +59 -0
  12. PyATCLI/analysis/group/report.py +281 -0
  13. PyATCLI/analysis/group/run.py +164 -0
  14. PyATCLI/analysis/group/scan.py +92 -0
  15. PyATCLI/analysis/group/stats.py +451 -0
  16. PyATCLI/analysis/group/trials.py +188 -0
  17. PyATCLI/analysis/intervals.py +59 -0
  18. PyATCLI/analysis/peak_finder.py +155 -0
  19. PyATCLI/analysis/shared.py +100 -0
  20. PyATCLI/analysis/zscore_peth.py +107 -0
  21. PyATCLI/cli/__init__.py +105 -0
  22. PyATCLI/cli/commands.py +395 -0
  23. PyATCLI/cli/docs.py +246 -0
  24. PyATCLI/cli/parser.py +286 -0
  25. PyATCLI/cli/render.py +130 -0
  26. PyATCLI/engine/__init__.py +0 -0
  27. PyATCLI/engine/contract.py +124 -0
  28. PyATCLI/engine/server.py +169 -0
  29. PyATCLI/engine/session.py +40 -0
  30. PyATCLI/engine/store.py +222 -0
  31. PyATCLI/engine/wire.py +103 -0
  32. PyATCLI/fieldstudy/__init__.py +1 -0
  33. PyATCLI/fieldstudy/study.py +440 -0
  34. PyATCLI/fieldstudy/validation.py +443 -0
  35. PyATCLI/markers.py +71 -0
  36. PyATCLI/models.py +102 -0
  37. PyATCLI/numeric.py +35 -0
  38. PyATCLI/ops/__init__.py +274 -0
  39. PyATCLI/ops/analysis.py +136 -0
  40. PyATCLI/ops/common.py +93 -0
  41. PyATCLI/ops/compute.py +94 -0
  42. PyATCLI/ops/fieldstudy.py +52 -0
  43. PyATCLI/ops/files.py +42 -0
  44. PyATCLI/ops/group.py +144 -0
  45. PyATCLI/ops/recording.py +90 -0
  46. PyATCLI/ops/records.py +63 -0
  47. PyATCLI/ops/results.py +27 -0
  48. PyATCLI/ops/saved.py +98 -0
  49. PyATCLI/ops/system.py +31 -0
  50. PyATCLI/outputs.py +165 -0
  51. PyATCLI/progress.py +227 -0
  52. PyATCLI/provenance.py +336 -0
  53. PyATCLI/recording.py +602 -0
  54. PyATCLI/reproduce.py +278 -0
  55. PyATCLI/results.py +106 -0
  56. PyATCLI/saved_state.py +275 -0
  57. PyATCLI/sources/__init__.py +1 -0
  58. PyATCLI/sources/dataset.py +110 -0
  59. PyATCLI/sources/load.py +169 -0
  60. PyATCLI/sources/processing_TDT.py +810 -0
  61. PyATCLI/sources/processing_oxysoft.py +259 -0
  62. PyATCLI/sources/pt2.py +46 -0
  63. PyATCLI/sources/tables.py +306 -0
  64. PyATCLI/splice.py +196 -0
  65. PyATCLI/viewplan.py +181 -0
  66. pyatcli-2026.10.10.dist-info/METADATA +296 -0
  67. pyatcli-2026.10.10.dist-info/RECORD +71 -0
  68. pyatcli-2026.10.10.dist-info/WHEEL +5 -0
  69. pyatcli-2026.10.10.dist-info/entry_points.txt +2 -0
  70. pyatcli-2026.10.10.dist-info/licenses/LICENSE +661 -0
  71. pyatcli-2026.10.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,274 @@
1
+ """
2
+ ops
3
+ ---
4
+ The operations layer: everything the command line and the engine (`python -m PyATCLI serve`, which PyAT's window talks to) can
5
+ ask of the library, as functions of plain, JSON-ready parameters that return a plain, JSON-ready result.
6
+
7
+ result = ops.call("run", {"kind": "event_peth", "recording": "D:/rats/Rat7", "parameters": {"event": "L1P¹"}, "out": "out"})
8
+
9
+ An operation is the one place that decides what a request means and what comes back. The command line is argparse in front of it and a
10
+ renderer (human text, `--plain` tables, `--json`) behind it; the engine is a JSON-lines transport in front of the same functions, with the
11
+ loaded recordings kept between calls. The two cannot disagree, because neither holds any logic of its own.
12
+
13
+ @operation("run", "run one analysis on a recording")
14
+ def run(ctx, *, kind, recording, parameters=None, ...): ...
15
+
16
+ An operation takes an `OpContext` and its parameters by keyword and returns a dict. While it works it tells the context what is going on —
17
+ `ctx.progress()` (the `progress=` argument of the library's slow functions), `ctx.warn(text)`, `ctx.note(text)` — and the front end shows
18
+ that however it likes (a bar, JSON lines, a toast). It reads recordings through `ctx.load(...)`, which is where the engine's recordings
19
+ live between calls; a one-shot run opens each fresh.
20
+
21
+ Errors are `OpError`s with a stable `code` (`error_info` turns any exception into one), so a caller can tell a mistake it can show (a bad
22
+ parameter) from a bug. Nothing here prints, reads sys.argv, or touches a window.
23
+
24
+ ops.names() every operation, in the order they are documented
25
+ ops.describe() {name: {"summary", "parameters": [...]}} — what `serve`'s `help` method returns
26
+ ops.call(name, params, ctx=None)
27
+
28
+ The result of every operation is JSON-ready (numbers, strings, lists, dicts, None): `to_jsonable` makes it so, with NaN as null.
29
+ """
30
+
31
+ import inspect
32
+ import math
33
+ import os
34
+
35
+ from ..progress import Cancelled
36
+ from ..analyses import AnalysisError, ParameterError
37
+ from ..reproduce import ReproduceError
38
+
39
+ # The engine's protocol: what its callers can count on (the operations and their parameters, the analyses, their tables and the columns that are
40
+ # always there — ENGINE_CONTRACT.json lists them, engine/contract.py explains what counts as breaking). Raise it when something a caller could rely
41
+ # on is removed or renamed; adding is not a reason. tests/test_engine_contract.py fails until the baseline of the new number is added.
42
+ PROTOCOL_VERSION = 1
43
+
44
+ _OPERATIONS = {}
45
+
46
+
47
+ class OpError(Exception):
48
+ """A request that cannot be done, for a reason a person can act on. `code` is stable (see ERROR_CODES), `hint` says what to try."""
49
+
50
+ def __init__(self, message, code="invalid_input", hint=None):
51
+ super().__init__(message)
52
+ self.code = code
53
+ self.hint = hint
54
+
55
+
56
+ ERROR_CODES = {
57
+ "bad_parameter": "a parameter is missing, unknown, or has a value the analysis cannot use",
58
+ "invalid_input": "something in the request is not usable (a file that is not a recording, a value out of range)",
59
+ "not_found": "a file, folder or recording the request names is not there",
60
+ "io_error": "a file could not be read or written",
61
+ "analysis_failed": "the analysis ran and could not give a result",
62
+ "cannot_reproduce": "a provenance record cannot be replayed",
63
+ "unknown_operation": "there is no such operation",
64
+ "no_recording": "the request names a recording the engine has not opened",
65
+ "confirmation_required": "the request would delete or replace something and was not told to go ahead",
66
+ "cancelled": "the request was cancelled before it finished",
67
+ "internal_error": "a bug: something unexpected went wrong",
68
+ }
69
+
70
+
71
+ def error_info(exc):
72
+ """{"code", "message", "hint", "type"} for any exception — the one place an error becomes something a caller can show."""
73
+ if isinstance(exc, Cancelled):
74
+ return {"code": "cancelled", "message": "cancelled", "hint": None, "type": "Cancelled"}
75
+ if isinstance(exc, OpError):
76
+ return {"code": exc.code, "message": str(exc), "hint": exc.hint, "type": type(exc).__name__}
77
+ message = str(exc) or type(exc).__name__
78
+ if isinstance(exc, ParameterError):
79
+ code = "bad_parameter"
80
+ elif isinstance(exc, AnalysisError):
81
+ code = "analysis_failed"
82
+ elif isinstance(exc, ReproduceError):
83
+ code = "cannot_reproduce"
84
+ elif isinstance(exc, FileNotFoundError):
85
+ code = "not_found"
86
+ elif isinstance(exc, KeyError):
87
+ code, message = "invalid_input", f"missing {message}"
88
+ elif isinstance(exc, ValueError):
89
+ code = "invalid_input"
90
+ elif isinstance(exc, OSError):
91
+ code = "io_error"
92
+ else:
93
+ return {"code": "internal_error", "message": f"{type(exc).__name__}: {message}", "type": type(exc).__name__,
94
+ "hint": "this is a bug; it helps to say what was asked (re-run with --debug for the traceback)"}
95
+ return {"code": code, "message": message, "hint": None, "type": type(exc).__name__}
96
+
97
+
98
+ def is_expected(exc):
99
+ """True for the errors a person can act on (everything error_info does not call a bug)."""
100
+ return error_info(exc)["code"] != "internal_error"
101
+
102
+
103
+ def to_jsonable(obj):
104
+ """`obj` as plain JSON values: numpy numbers and arrays, tuples, sets and paths become Python ones, and NaN / infinity become None
105
+ (strict JSON has no such numbers)."""
106
+ import numpy as np
107
+
108
+ if obj is None or isinstance(obj, (bool, str)):
109
+ return obj
110
+ if isinstance(obj, (int,)) and not isinstance(obj, bool):
111
+ return int(obj)
112
+ if isinstance(obj, float):
113
+ return obj if math.isfinite(obj) else None
114
+ if isinstance(obj, np.generic):
115
+ return to_jsonable(obj.item())
116
+ if isinstance(obj, np.ndarray):
117
+ return to_jsonable(obj.tolist())
118
+ if isinstance(obj, dict):
119
+ return {str(k): to_jsonable(v) for k, v in obj.items()}
120
+ if isinstance(obj, (list, tuple, set)):
121
+ return [to_jsonable(v) for v in obj]
122
+ if isinstance(obj, os.PathLike):
123
+ return os.fspath(obj)
124
+ return str(obj)
125
+
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # The context an operation runs in
129
+ # ---------------------------------------------------------------------------
130
+
131
+ class OpContext:
132
+ """What an operation is told about where it runs, and how it tells anyone what it is doing.
133
+
134
+ emit `emit(event, **fields)` — called for "progress" (fraction, message), "warning" (text), "note" (text) and "state" (path: a
135
+ file was written). Default: nobody is listening.
136
+ cancelled `cancelled() -> bool`: True once the caller wants the work stopped; the next progress report raises Cancelled
137
+ loader `loader(path, **options) -> load_recording's dict`; the engine's keeps recordings between calls
138
+ store the engine's recording store (None for a one-shot run): operations that name a recording by id use it
139
+ data_dir where bulk results (arrays, big tables) are written for the caller to map; None: they are not
140
+ app {"name", "version"} of the program asking, written into the provenance records of what is made
141
+ """
142
+
143
+ def __init__(self, emit=None, cancelled=None, loader=None, store=None, data_dir=None, wants_progress=True, app=None):
144
+ self.app = dict(app or {"name": "PyATCLI command line"}) # the program in a provenance record's software section
145
+ self._emit = emit
146
+ self._cancelled = cancelled
147
+ self._loader = loader
148
+ self.store = store
149
+ self.data_dir = data_dir
150
+ self.wants_progress = wants_progress and emit is not None
151
+ self.warnings = []
152
+
153
+ def emit(self, event, **fields):
154
+ if self._emit is not None:
155
+ self._emit(event, **fields)
156
+
157
+ def warn(self, text):
158
+ self.warnings.append(str(text))
159
+ self.emit("warning", text=str(text))
160
+
161
+ def note(self, text):
162
+ self.emit("note", text=str(text))
163
+
164
+ def written(self, path):
165
+ """Tell the caller a file was written (a change of state the user should hear about)."""
166
+ self.emit("state", path=os.fspath(path))
167
+
168
+ def check_cancel(self):
169
+ if self._cancelled is not None and self._cancelled():
170
+ raise Cancelled()
171
+
172
+ def progress(self):
173
+ """The `progress=` argument for the library's slow functions: a callable(fraction, message) that reports through `emit` and
174
+ stops the work (Cancelled) when the caller has cancelled — or None when nobody is listening and nothing can be cancelled."""
175
+ if not self.wants_progress and self._cancelled is None:
176
+ return None
177
+
178
+ def report(fraction, message=""):
179
+ if self.wants_progress:
180
+ self.emit("progress", fraction=float(fraction), message=str(message))
181
+ self.check_cancel()
182
+
183
+ return report
184
+
185
+ def load(self, path, *, progress=None, **options):
186
+ """A recording as load_recording returns it ({"cache", "original_cache", "splices", "warnings"}); `options` are its own
187
+ (regression_method, use_saved, table, x_column, y_columns). Its warnings are passed on (ctx.warn). `progress` is where the
188
+ reading reports, if not the request's own progress (a stage of a longer request: see ops/analysis.py)."""
189
+ progress = progress if progress is not None else self.progress()
190
+ if self._loader is not None:
191
+ loaded = self._loader(path, progress=progress, **options)
192
+ else:
193
+ from ..recording import load_recording
194
+ loaded = load_recording(path, progress=progress, **options)
195
+ for w in loaded.get("warnings", []):
196
+ self.warn(w)
197
+ return loaded
198
+
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # The registry
202
+ # ---------------------------------------------------------------------------
203
+
204
+ class Operation:
205
+ def __init__(self, name, fn, summary, result=()):
206
+ self.name, self.fn, self.summary = name, fn, summary
207
+ self.result = tuple(result) # the keys of the result that are always there (see ENGINE_CONTRACT.json); more may be
208
+ sig = inspect.signature(fn)
209
+ self.parameters = [p for n, p in sig.parameters.items() if n != "ctx"]
210
+
211
+ def describe(self):
212
+ return {"summary": self.summary,
213
+ "parameters": [{"name": p.name, "required": p.default is inspect.Parameter.empty,
214
+ "default": None if p.default is inspect.Parameter.empty else to_jsonable(p.default)}
215
+ for p in self.parameters],
216
+ "result": list(self.result)}
217
+
218
+
219
+ def operation(name, summary, result=()):
220
+ """Registers `fn(ctx, **parameters) -> dict` as the operation `name`. `result` lists the keys of what it returns that are ALWAYS there: a
221
+ caller may count on them (more can be present, and more can be added; removing one is a breaking change, see engine/contract.py)."""
222
+ def register(fn):
223
+ _OPERATIONS[name] = Operation(name, fn, summary, result)
224
+ return fn
225
+ return register
226
+
227
+
228
+ def names():
229
+ _load_all()
230
+ return list(_OPERATIONS)
231
+
232
+
233
+ def describe():
234
+ _load_all()
235
+ return {n: op.describe() for n, op in _OPERATIONS.items()}
236
+
237
+
238
+ def get(name):
239
+ _load_all()
240
+ try:
241
+ return _OPERATIONS[name]
242
+ except KeyError:
243
+ raise OpError(f"there is no operation {name!r}; the operations are: {', '.join(_OPERATIONS)}", "unknown_operation") from None
244
+
245
+
246
+ def call(name, params=None, ctx=None):
247
+ """Runs operation `name` with `params` (a dict of its keyword parameters) and returns its result, made JSON-ready. An unknown or
248
+ missing parameter is a ParameterError naming it."""
249
+ op = get(name)
250
+ params = dict(params or {})
251
+ valid = {p.name for p in op.parameters}
252
+ unknown = sorted(set(params) - valid)
253
+ if unknown:
254
+ raise ParameterError(f"{name}: unknown parameter(s) {', '.join(unknown)}; valid: {', '.join(sorted(valid))}")
255
+ missing = [p.name for p in op.parameters if p.default is inspect.Parameter.empty and p.name not in params]
256
+ if missing:
257
+ raise ParameterError(f"{name}: {', '.join(missing)} {'is' if len(missing) == 1 else 'are'} required")
258
+ result = to_jsonable(op.fn(ctx or OpContext(), **params))
259
+ if os.environ.get("PYATCLI_CHECK_RESULTS", "").strip().lower() not in ("", "0", "false", "no", "off"):
260
+ missing = [k for k in op.result if k not in result]
261
+ if missing: # the tests (and a developer) run like this: a promise broken is loud
262
+ raise AssertionError(f"{name}: the result lacks {', '.join(missing)}, which the operation's contract promises (ops: result=...)")
263
+ return result
264
+
265
+
266
+ _loaded = False
267
+
268
+
269
+ def _load_all():
270
+ """Imports the modules that register operations (done on first use, so `import PyATCLI.ops` stays light)."""
271
+ global _loaded
272
+ if not _loaded:
273
+ from . import analysis, compute, fieldstudy, files, group, records, recording, results, saved, system # noqa: F401,E402 — importing each registers its operations
274
+ _loaded = True
@@ -0,0 +1,136 @@
1
+ """ops/analysis.py — run an analysis, run it again from a record, run many."""
2
+
3
+ import json
4
+ import os
5
+
6
+ from .. import outputs, provenance
7
+ from ..analyses import ParameterError, kinds, normalize_parameters, run_analysis
8
+ from ..progress import Plan
9
+ from ..reproduce import reproduce as reproduce_record
10
+ from ..reproduce import safe_name, write_result
11
+ from . import OpError, operation
12
+ from .common import open_recording, recording_name, recordings_under, tables_wire
13
+
14
+
15
+ def _where(out, output_folder):
16
+ if out and output_folder:
17
+ raise OpError("give --out or --output-folder, not both", "invalid_input")
18
+ return out, output_folder
19
+
20
+
21
+ def _write_result(ctx, result, cache, path, stem, out, output_folder, load, splices):
22
+ """Writes the result's tables and a provenance record: into `out`, or under the Output folder's <data type>/<recording> (Analysis)
23
+ folder, under a name no earlier result has. Returns (files written, the folder)."""
24
+ stem = stem or safe_name(f"{recording_name(path)}_{result.kind}")
25
+ if out is None:
26
+ out = outputs.recording_dir(output_folder, cache.get("source") or "Generic", path)
27
+ stem = outputs.unique_stem(out, stem, [f"_{safe_name(t)}.csv" for t in result.tables] + [".provenance.json"])
28
+ written = write_result(result, out, stem)
29
+ method = (load or {}).get("regression_method") or "ols"
30
+ record = provenance.build_record(
31
+ result.kind, result.parameters, source=provenance.file_fingerprint(path),
32
+ recording=provenance.recording_state(cache, method, splices, signal=result.parameters.get("signal")),
33
+ pipeline=provenance.pipeline_parameters(method), app=ctx.app, outputs=written, notes=result.notes)
34
+ written.append(provenance.write_record(os.path.join(out, f"{stem}.provenance.json"), record))
35
+ for f in written:
36
+ ctx.written(f)
37
+ return written, out
38
+
39
+
40
+ @operation("run", "run one analysis on a recording; writes CSV tables and a provenance record when told where", result=["kind", "recording", "parameters", "summary", "notes", "tables", "files", "directory"])
41
+ def run(ctx, *, kind, recording, parameters=None, load=None, store_labels=None, out=None, output_folder=None, tables="shapes", stem=None):
42
+ out, output_folder = _where(out, output_folder)
43
+ if kind not in kinds():
44
+ raise ParameterError(f"unknown analysis {kind!r}; the analyses are: {', '.join(kinds())}")
45
+ params = dict(parameters or {})
46
+ normalize_parameters(kind, params) # fail on a bad parameter before loading anything slow
47
+ # Opening the recording is most of the work when it is read from a path and none of it when the engine already holds it; the analysis
48
+ # that follows may report nothing of its own (a fit is one call), so it is announced at its start and finished at its end.
49
+ opening, running = "Opening the recording", f"Running {kind.replace('_', ' ')}"
50
+ plan = Plan(ctx.progress(), [(opening, 1 if isinstance(recording, dict) else 4), (running, 3 if isinstance(recording, dict) else 1)])
51
+ plan.begin(opening)
52
+ loaded, path = open_recording(ctx, recording, load, progress=plan.sub(opening))
53
+ cache = loaded["cache"]
54
+ plan.begin(running)
55
+ result = run_analysis(kind, cache, params, store_labels=store_labels, progress=plan.sub(running))
56
+ plan.done("Done")
57
+ written, directory = [], None
58
+ if out or output_folder:
59
+ written, directory = _write_result(ctx, result, cache, path, stem, out, output_folder, load, loaded["splices"])
60
+ return {"kind": result.kind, "recording": path, "parameters": result.parameters, "summary": result.summary, "notes": result.notes,
61
+ "tables": tables_wire(ctx, result.tables, tables, prefix=f"{kind}"), "files": written, "directory": directory}
62
+
63
+
64
+ @operation("reproduce", "run an analysis again from its provenance record and check the numbers against exports")
65
+ def reproduce(ctx, *, record, recording=None, out=None, compare=None, tolerance=1e-4, strict=False, rounded=None, tables="shapes"):
66
+ rep = reproduce_record(record, recording=recording, out_dir=out, compare=compare or (), tolerance=tolerance, strict=strict,
67
+ progress=ctx.progress(), rounded=rounded)
68
+ for w in rep.warnings:
69
+ ctx.warn(w)
70
+ for f in rep.written:
71
+ ctx.written(f)
72
+ return {"ok": rep.ok, "kind": rep.result.kind, "warnings": list(rep.warnings), "comparisons": rep.comparisons, "files": list(rep.written),
73
+ "directory": out, "tables": tables_wire(ctx, rep.result.tables, tables, prefix=f"{rep.result.kind}")}
74
+
75
+
76
+ def _read_jobs(jobs):
77
+ """(jobs list, defaults dict) from a path to a jobs file, or the document itself."""
78
+ if isinstance(jobs, (str, os.PathLike)):
79
+ with open(jobs, "r", encoding="utf-8") as f:
80
+ jobs = json.load(f)
81
+ jobs_list = jobs["jobs"] if isinstance(jobs, dict) else jobs
82
+ defaults = jobs.get("defaults", {}) if isinstance(jobs, dict) else {}
83
+ if not isinstance(jobs_list, list) or not all(isinstance(j, dict) and "kind" in j and "recording" in j for j in jobs_list):
84
+ raise OpError('a jobs file is {"defaults": {...}, "jobs": [{"kind", "recording", "parameters"}, ...]} (or just the list of jobs)',
85
+ "invalid_input")
86
+ return jobs_list, defaults
87
+
88
+
89
+ @operation("batch", "run many analyses over many recordings (a folder of TDT blocks counts as many)")
90
+ def batch(ctx, *, jobs, out=None, output_folder=None, load=None):
91
+ import pandas as pd
92
+
93
+ out, output_folder = _where(out, output_folder)
94
+ if not (out or output_folder):
95
+ raise OpError("say where the results go: --out DIR, or --output-folder DIR", "invalid_input")
96
+ jobs_list, defaults = _read_jobs(jobs)
97
+ load = dict(load or {})
98
+ if "regression_method" in defaults:
99
+ load["regression_method"] = defaults["regression_method"]
100
+ if "use_saved" in defaults:
101
+ load["use_saved"] = bool(defaults["use_saved"])
102
+ for n, job in enumerate(jobs_list, 1): # a bad parameter anywhere fails before the first slow load
103
+ normalize_parameters(job["kind"], {**defaults.get("parameters", {}), **job.get("parameters", {})})
104
+ summary, failed, combined_files = [], [], []
105
+ for n, job in enumerate(jobs_list, 1):
106
+ kind = job["kind"]
107
+ parameters = {**defaults.get("parameters", {}), **job.get("parameters", {})}
108
+ job_dir = os.path.join(output_folder, "Batch", f"{n:02d}_{kind}") if output_folder else os.path.join(out, f"{n:02d}_{kind}")
109
+ combined, files, names = {}, [], []
110
+ for path in recordings_under(job["recording"]):
111
+ ctx.check_cancel()
112
+ name = safe_name(recording_name(path))
113
+ try:
114
+ loaded, _ = open_recording(ctx, path, load)
115
+ result = run_analysis(kind, loaded["cache"], parameters, progress=ctx.progress())
116
+ written, _dir = _write_result(ctx, result, loaded["cache"], path, f"{name}_{kind}", None if output_folder else os.path.join(job_dir, name),
117
+ output_folder, load, loaded["splices"])
118
+ except Exception as e: # noqa: BLE001 — one recording failing must not stop the rest
119
+ from . import is_expected, error_info
120
+ if not is_expected(e):
121
+ raise
122
+ failed.append({"job": n, "kind": kind, "recording": name, "error": error_info(e)["message"]})
123
+ continue
124
+ files += written
125
+ names.append(name)
126
+ ctx.note(f"job {n} {kind}: {name}: {len(written)} files")
127
+ for tname, table in result.tables.items():
128
+ combined.setdefault(tname, []).append(table.assign(recording=name))
129
+ for tname, frames in combined.items():
130
+ path = os.path.join(job_dir, f"{kind}_{safe_name(tname)}_all.csv")
131
+ os.makedirs(job_dir, exist_ok=True)
132
+ pd.concat(frames, ignore_index=True).to_csv(path, index=False, encoding="utf-8")
133
+ combined_files.append(path)
134
+ ctx.written(path)
135
+ summary.append({"job": n, "kind": kind, "recordings": names, "files": files})
136
+ return {"jobs": summary, "failed": failed, "combined": combined_files, "ok": not failed}
PyATCLI/ops/common.py ADDED
@@ -0,0 +1,93 @@
1
+ """
2
+ ops/common.py
3
+ -------------
4
+ What the operations share: how a request names a recording and its load options, how tables travel in a result, and the small
5
+ checks every operation makes before it does anything slow.
6
+ """
7
+
8
+ import os
9
+
10
+ from ..analyses import ParameterError
11
+ from . import OpError
12
+
13
+ LOAD_KEYS = ("regression_method", "use_saved", "table", "x_column", "y_columns")
14
+
15
+
16
+ def load_options(load):
17
+ """The keyword arguments of load_recording from a request's `load` dict ({} -> its defaults). An unknown key is a ParameterError."""
18
+ load = dict(load or {})
19
+ unknown = sorted(set(load) - set(LOAD_KEYS))
20
+ if unknown:
21
+ raise ParameterError(f"unknown load option(s) {', '.join(unknown)}; valid: {', '.join(LOAD_KEYS)}")
22
+ return {k: v for k, v in load.items() if v is not None}
23
+
24
+
25
+ def recording_name(path):
26
+ """A recording's own name: its folder's or file's basename."""
27
+ return os.path.basename(os.fspath(path).rstrip("/" + chr(92)))
28
+
29
+
30
+ def require_exists(path):
31
+ path = os.fspath(path)
32
+ if not os.path.exists(path):
33
+ raise OpError(f"{path} does not exist", "not_found")
34
+ return path
35
+
36
+
37
+ def open_recording(ctx, recording, load=None, progress=None):
38
+ """({"cache", "original_cache", "splices", "warnings"}, path) for the recording a request names: a path (the file as it is on disk now,
39
+ opened fresh) or a reference {"id", "splices"?, "markers"?, "signal_labels"?, ...} to a recording the engine has open (engine/store.py).
40
+ `progress` is where opening reports, if not the request's own."""
41
+ if isinstance(recording, dict):
42
+ if "id" not in recording:
43
+ raise OpError("a recording is a path, or {\"id\": ...} for one the engine has open", "invalid_input")
44
+ if ctx.store is None:
45
+ raise OpError("recordings are only kept open by the engine (python -m PyATCLI serve); give a path", "no_recording")
46
+ entry = ctx.store.get(recording["id"])
47
+ return entry.resolve(recording, progress if progress is not None else ctx.progress()), entry.path
48
+ path = require_exists(recording)
49
+ return ctx.load(path, progress=progress, **load_options(load)), path
50
+
51
+
52
+ def recordings_under(path):
53
+ """[path] if it is a recording itself, else every TDT block found under it."""
54
+ from ..sources.processing_TDT import validate_tdt_folder
55
+ from ..recording import find_tdt_recordings
56
+
57
+ path = require_exists(path)
58
+ if os.path.isdir(path) and not validate_tdt_folder(path)[0]:
59
+ found = find_tdt_recordings(path)
60
+ if not found:
61
+ raise OpError(f"no TDT recordings found under {path}", "invalid_input")
62
+ return found
63
+ return [path]
64
+
65
+
66
+ def table_summary(table, name=None):
67
+ return {"columns": [str(c) for c in table.columns], "rows": int(len(table))}
68
+
69
+
70
+ def tables_wire(ctx, tables, mode="shapes", prefix="table"):
71
+ """How a result's tables (DataFrames) travel: "shapes" says each one's columns and number of rows; "inline" adds the values as
72
+ {column: [values]} (small tables); "files" writes each as a CSV in ctx.data_dir and gives its path (a table too big for a message)."""
73
+ if mode not in ("shapes", "inline", "files"):
74
+ raise ParameterError(f"tables must be shapes, inline or files, not {mode!r}")
75
+ out = {}
76
+ for name, table in tables.items():
77
+ entry = table_summary(table, name)
78
+ if mode == "inline":
79
+ entry["data"] = {str(c): table[c].tolist() for c in table.columns}
80
+ elif mode == "files":
81
+ if ctx.data_dir is None:
82
+ raise OpError("tables='files' needs somewhere to put them (the engine's data folder)", "invalid_input")
83
+ os.makedirs(ctx.data_dir, exist_ok=True)
84
+ path = os.path.join(ctx.data_dir, f"{prefix}_{_safe(name)}.csv")
85
+ table.to_csv(path, index=False, encoding="utf-8")
86
+ entry["path"] = path
87
+ out[str(name)] = entry
88
+ return out
89
+
90
+
91
+ def _safe(text):
92
+ import re
93
+ return re.sub(r'[<>:"/\\|?*\s]+', "_", str(text)).strip("_") or "table"
PyATCLI/ops/compute.py ADDED
@@ -0,0 +1,94 @@
1
+ """
2
+ ops/compute.py — the building blocks a window draws from, where `run` (analysis.py) gives the tables an export writes.
3
+
4
+ compute.event_peth every occurrence of one event aligned into a trial x time matrix of z-scores (the Event PETH window's data)
5
+ compute.peaks Peak Finder: significant peaks of the whole recording, or the one nearest each of some events
6
+
7
+ Both work on the recording's normalized signal (the corrected dF/F for TDT), smoothed, exactly as the app's windows do, and name the
8
+ recording as `run` does ({"id": ...} for one the engine holds, or a path). Arrays come back as .npy files to map (engine/wire.py): a
9
+ trial matrix is a result to look at and change the checked rows of, not text.
10
+ """
11
+
12
+ import tempfile
13
+
14
+ from ..analyses import ParameterError
15
+ from ..analysis.event_peth import compute_event_zscore_peth
16
+ from ..analysis.peak_finder import find_peak_near_events, find_significant_peaks
17
+ from ..analysis.shared import smooth_signal
18
+ from ..progress import Plan
19
+ from ..recording import normalized_signal
20
+ from . import OpError, operation
21
+ from .common import open_recording
22
+
23
+
24
+ def arrays_wire(ctx, obj, prefix):
25
+ """`obj` (dicts, lists, numbers and arrays) with its arrays written as .npy files in a new folder of the engine's data folder:
26
+ {"directory": ..., "data": the structure with each array replaced by a reference} (decode with engine.wire.decode)."""
27
+ from ..engine.wire import ArrayFiles, encode
28
+
29
+ if ctx.data_dir is None:
30
+ raise OpError("arrays need somewhere to go (the engine's data folder); this operation is for the engine", "invalid_input")
31
+ directory = tempfile.mkdtemp(prefix=f"{prefix}-", dir=ctx.data_dir)
32
+ return {"directory": directory, "data": encode(obj, ArrayFiles(directory), prefix)}
33
+
34
+
35
+ def _times(values, what):
36
+ try:
37
+ return [float(t) for t in values]
38
+ except (TypeError, ValueError):
39
+ raise ParameterError(f"{what} is a list of times in seconds") from None
40
+
41
+
42
+ def _window(pre, post):
43
+ pre, post = float(pre), float(post)
44
+ if pre <= 0 or post <= 0:
45
+ raise ParameterError("pre and post are positive numbers of seconds")
46
+ return pre, post
47
+
48
+
49
+ @operation("compute.event_peth", "z-score and align every occurrence of an event into a trial x time matrix (the Event PETH window's data)", result=["signal", "label", "result"])
50
+ def event_peth(ctx, *, recording, event_times, pre, post, num_bins=300, load=None):
51
+ times = _times(event_times, "event_times")
52
+ pre, post = _window(pre, post)
53
+ loaded, _ = open_recording(ctx, recording, load)
54
+ cache = loaded["cache"]
55
+ key, label, y = normalized_signal(cache)
56
+ plan = Plan(ctx.progress(), [("Smoothing the signal", 10), ("Aligning trials", 90)])
57
+ plan.begin("Smoothing the signal")
58
+ clean = smooth_signal(y, cache["fs"])
59
+ result = compute_event_zscore_peth(cache["x"], clean, times, pre, post, num_bins=int(num_bins), progress=plan.sub("Aligning trials"))
60
+ return {"signal": key, "label": label, "result": arrays_wire(ctx, result, "event_peth")}
61
+
62
+
63
+ @operation("compute.peaks", "Peak Finder: significant peaks of the whole recording (scope whole), or the peak nearest each event (scope events)", result=["signal", "label"])
64
+ def peaks(ctx, *, recording, scope, z_threshold, include_troughs=False, min_distance_s=1.0, events=None, pre=None, post=None, load=None):
65
+ if scope not in ("whole", "events"):
66
+ raise ParameterError(f"scope must be 'whole' or 'events', not {scope!r}")
67
+ z_threshold = float(z_threshold)
68
+ if scope == "events":
69
+ if not isinstance(events, dict) or not events:
70
+ raise ParameterError("events is {event name: [times]} for scope 'events'")
71
+ groups = {str(name): _times(times, f"events[{name!r}]") for name, times in events.items()}
72
+ if pre is None or post is None:
73
+ raise ParameterError("pre and post (seconds around each event) are needed for scope 'events'")
74
+ pre, post = _window(pre, post)
75
+ loaded, _ = open_recording(ctx, recording, load)
76
+ cache = loaded["cache"]
77
+ key, label, y = normalized_signal(cache)
78
+ plan = Plan(ctx.progress(), [("Smoothing the signal", 10), ("Searching for peaks", 90)])
79
+ plan.begin("Smoothing the signal")
80
+ clean = smooth_signal(y, cache["fs"])
81
+ plan.begin("Searching for peaks")
82
+ if scope == "whole":
83
+ found = find_significant_peaks(cache["x"], clean, z_threshold=z_threshold, min_distance_sec=float(min_distance_s),
84
+ include_troughs=bool(include_troughs))
85
+ plan.done()
86
+ return {"signal": key, "label": label, "peaks": found}
87
+ if len(groups) == 1: # one event type: the progress follows its events
88
+ (name, times), = groups.items()
89
+ results = {name: find_peak_near_events(cache["x"], clean, times, pre, post, z_threshold=z_threshold,
90
+ include_troughs=bool(include_troughs), progress=plan.sub("Searching for peaks"))}
91
+ else: # several: one tick per event type
92
+ results = {name: find_peak_near_events(cache["x"], clean, times, pre, post, z_threshold=z_threshold, include_troughs=bool(include_troughs))
93
+ for name, times in plan.track("Searching for peaks", groups.items())}
94
+ return {"signal": key, "label": label, "groups": results}
@@ -0,0 +1,52 @@
1
+ """
2
+ ops/fieldstudy.py — text field studies (a folder of per-participant JSON files whose free-text answers are embedded and compared).
3
+
4
+ fieldstudy.fields the field names in a study folder's files (for choosing which to compare)
5
+ fieldstudy.run the whole pipeline: load, flag short answers, embed, similarity of each pair of fields, permutation tests
6
+ fieldstudy.validate the statistical validation of the pairs (permutation p-values with FDR, Cohen's d, bootstrap CI, leave-one-out)
7
+
8
+ Both pipelines load a language model and embed every answer — a lot to import and hold, and the reason they run in the engine rather than
9
+ in a window. The tables come back as the shapes of what they hold, or (tables="files") as CSV files to read.
10
+ """
11
+
12
+ from ..analyses import ParameterError
13
+ from ..fieldstudy.validation import run_validation_pipeline
14
+ from ..fieldstudy.study import peek_fields, run_field_study_pipeline
15
+ from . import operation
16
+ from .common import require_exists, tables_wire
17
+
18
+
19
+ def _pairs(paired_fields):
20
+ """[(field_a, field_b, name), ...] from lists as JSON carries them."""
21
+ try:
22
+ return [(str(a), str(b), str(name)) for a, b, name in (paired_fields or [])]
23
+ except (TypeError, ValueError):
24
+ raise ParameterError("paired_fields is a list of [field_a, field_b, name]") from None
25
+
26
+
27
+ @operation("fieldstudy.fields", "the field names found in the first participant file of a study folder", result=["folder", "fields"])
28
+ def fields(ctx, *, folder, file_glob="P-*.json"):
29
+ return {"folder": require_exists(folder), "fields": peek_fields(require_exists(folder), file_glob)}
30
+
31
+
32
+ @operation("fieldstudy.run", "run a text field study: one row per participant, with the similarity of each pair of fields and its tests", result=["folder", "rows", "tables"])
33
+ def run(ctx, *, folder, text_fields, paired_fields=None, delta_pair=None, file_glob="P-*.json", min_words=5, tables="shapes"):
34
+ if not text_fields:
35
+ raise ParameterError("text_fields: name the fields to load")
36
+ delta = tuple(str(f) for f in delta_pair) if delta_pair else None
37
+ if delta is not None and len(delta) != 2:
38
+ raise ParameterError("delta_pair is [field_from, field_to]")
39
+ df = run_field_study_pipeline(require_exists(folder), text_fields=[str(f) for f in text_fields], delta_pair=delta,
40
+ paired_fields=_pairs(paired_fields) or None, file_glob=file_glob, min_words=int(min_words),
41
+ progress=ctx.progress())
42
+ return {"folder": folder, "rows": int(len(df)), "tables": tables_wire(ctx, {"study": df}, tables, prefix="fieldstudy")}
43
+
44
+
45
+ @operation("fieldstudy.validate", "statistical validation of a study's field pairs: one row per pair", result=["folder", "rows", "tables"])
46
+ def validate(ctx, *, folder, text_fields, paired_fields, file_glob="P-*.json", tables="shapes"):
47
+ pairs = _pairs(paired_fields)
48
+ if not pairs:
49
+ raise ParameterError("paired_fields: give at least one [field_a, field_b, name] to validate")
50
+ df = run_validation_pipeline(require_exists(folder), text_fields=[str(f) for f in text_fields], paired_fields=pairs, file_glob=file_glob,
51
+ progress=ctx.progress())
52
+ return {"folder": folder, "rows": int(len(df)), "tables": tables_wire(ctx, {"validation": df}, tables, prefix="validation")}