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
PyATCLI/provenance.py ADDED
@@ -0,0 +1,336 @@
1
+ """
2
+ provenance.py
3
+ -------------
4
+ How a result was produced, as data: the software that ran (versions of this library, Python, the
5
+ numerical packages), what the pipeline did that no caller chose (the filter, the bleaching model, the
6
+ z-score baseline rule), which recording went in and in what state (splices, markers, the motion-correction
7
+ method), and the parameters of the analysis itself. Written next to every export as
8
+ <export name>.provenance.json, and enough — with the recording — to run the analysis again
9
+ (PyATCLI.reproduce, and the `python -m PyATCLI` command line).
10
+
11
+ A record is a plain JSON-able dict:
12
+
13
+ schema SCHEMA_VERSION of this layout
14
+ kind what was produced ("event_peth", "zscore_window", "group_analysis", "figure", ...)
15
+ created ISO date-time
16
+ software software_versions(): this library, Python, platform, the numerical packages, the app
17
+ source file_fingerprint() of the recording's folder / file: names, sizes, hashes
18
+ recording recording_state(): its type, length, splices, markers, motion-correction method
19
+ pipeline pipeline_parameters(): the processing no caller chose, from the constants the code uses
20
+ analysis {"type": kind, "parameters": {...}} — what was asked of that analysis
21
+ outputs the files written, each with its size and hash
22
+ notes anything worth saying in words
23
+
24
+ Nothing in a record is recording *data*: no samples, no trace values. A record holds names, counts,
25
+ times of events, parameters and hashes. File paths are included (they are what lets the analysis be run
26
+ again) and can be left out with `portable=True` in file_fingerprint.
27
+ """
28
+
29
+ import hashlib
30
+ import json
31
+ import os
32
+ import platform
33
+ import re
34
+ import sys
35
+ from datetime import datetime
36
+
37
+ from ._version import resolve_version
38
+
39
+ SCHEMA_VERSION = 1
40
+ SIDECAR_SUFFIX = ".provenance.json"
41
+
42
+ # A file larger than this is identified by its name, size and date rather than hashed: a TDT block's
43
+ # .tev can be gigabytes, and its small index/header files already say whether it is the same block.
44
+ HASH_LIMIT_BYTES = 16 * 2 ** 20
45
+
46
+ # Distributions whose versions can change a number (or how a figure looks); reported when installed.
47
+ PACKAGES = ("numpy", "scipy", "pandas", "statsmodels", "scikit-learn", "tdt", "openpyxl", "tqdm",
48
+ "PyQt6", "pyqtgraph")
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Software
53
+ # ---------------------------------------------------------------------------
54
+
55
+ def library_version():
56
+ """This library's running version (see _version.py for why that is not always the installed one)."""
57
+ return resolve_version()
58
+
59
+
60
+ def software_versions(app=None, packages=PACKAGES):
61
+ """What is running: Python, the OS, this library, the numerical packages that are installed, and the
62
+ program using it (`app`, e.g. {"name": "PyAT", "version": "3.2.0"}). Never raises."""
63
+ from importlib import metadata
64
+
65
+ pkgs = {}
66
+ for name in packages:
67
+ try:
68
+ pkgs[name] = metadata.version(name)
69
+ except Exception: # noqa: BLE001 - not installed / unreadable: just absent
70
+ pass
71
+ try:
72
+ plat = platform.platform()
73
+ except Exception: # noqa: BLE001
74
+ plat = sys.platform
75
+ out = {
76
+ "python": platform.python_version(),
77
+ "implementation": platform.python_implementation(),
78
+ "bits": 64 if sys.maxsize > 2 ** 32 else 32,
79
+ "platform": plat,
80
+ "frozen": bool(getattr(sys, "frozen", False)),
81
+ "library": library_version(),
82
+ "packages": pkgs,
83
+ }
84
+ if app:
85
+ out["app"] = dict(app)
86
+ return out
87
+
88
+
89
+ def check_environment(record, packages=("numpy", "scipy", "pandas", "statsmodels", "scikit-learn")):
90
+ """Differences between the software a record was produced with and the software running now that
91
+ could matter, as plain sentences ([] = none worth mentioning). Library version differences and a
92
+ different Python minor version are named, and so is a different major.minor of a numerical package:
93
+ results can differ in the last digits across those, rarely more."""
94
+ then = record.get("software", {})
95
+ now = software_versions()
96
+ out = []
97
+ if then.get("library") and then["library"] != now["library"]:
98
+ out.append(f"PyATCLI was {then['library']} when this was produced; this is {now['library']}.")
99
+
100
+ def minor(v):
101
+ return ".".join(str(v).split(".")[:2])
102
+
103
+ if then.get("python") and minor(then["python"]) != minor(now["python"]):
104
+ out.append(f"Python was {then['python']} when this was produced; this is {now['python']}.")
105
+ for name in packages:
106
+ a, b = then.get("packages", {}).get(name), now["packages"].get(name)
107
+ if a and b and minor(a) != minor(b):
108
+ out.append(f"{name} was {a} when this was produced; this is {b} — numbers can differ in the last digits.")
109
+ return out
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # What the pipeline does that no caller chose
114
+ # ---------------------------------------------------------------------------
115
+
116
+ def pipeline_parameters(regression_method="ols"):
117
+ """The processing a TDT recording goes through and the analysis conventions, read from the constants
118
+ the code itself uses (so this cannot drift from what ran)."""
119
+ from .sources import processing_TDT as P
120
+ from .analysis import shared, zscore_peth
121
+
122
+ if regression_method not in P.REGRESSION_METHODS:
123
+ raise ValueError(f"Unknown regression method {regression_method!r}; expected one of {P.REGRESSION_METHODS}")
124
+ return {
125
+ "dtype": "float64",
126
+ "motion_correction": {
127
+ "method": regression_method,
128
+ "signal_stream": "the stream whose name contains '465'",
129
+ "reference_stream": "the stream whose name contains '415' (none: no motion correction)",
130
+ "fit": "linear regression of the 415 reference onto the 465 signal; the fitted 415 is subtracted",
131
+ "ransac": {"residual_threshold": "3 x robust noise (MAD of an OLS fit's residuals / 0.6745)", "random_state": 0},
132
+ "huber": {"epsilon": 1.35, "fitted on median/MAD-standardised data": True},
133
+ },
134
+ "photobleaching": {
135
+ "model": "double exponential fitted to the 465 stream",
136
+ "fit": "scipy.optimize.curve_fit on the samples above the stream's median, in units of its own maximum",
137
+ "fallback": "log-linear trend if the fit fails",
138
+ },
139
+ "dff": {
140
+ "with_reference": "motion-corrected residual / bleaching baseline",
141
+ "without_reference": "(465 - bleaching baseline) / bleaching baseline",
142
+ },
143
+ "denoise": {
144
+ "filter": "Butterworth low-pass, zero-phase (scipy filtfilt)",
145
+ "cutoff_hz": P.DENOISE_CUTOFF_HZ,
146
+ "order": P.DENOISE_ORDER,
147
+ },
148
+ "smoothing": {
149
+ "method": "moving average (applied before event-locked analyses)",
150
+ "window_s": shared.SMOOTH_WINDOW_SEC,
151
+ },
152
+ "zscore": {
153
+ "baseline": "the samples before the event (t < event time)",
154
+ "baseline_artifact_guard": f"samples beyond {zscore_peth.BASELINE_ROBUST_SD:g} robust SDs (1.4826 x MAD) "
155
+ "of the baseline median are pulled in before its mean and SD are taken",
156
+ "robust_sd_limit": zscore_peth.BASELINE_ROBUST_SD,
157
+ },
158
+ }
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # The recording
163
+ # ---------------------------------------------------------------------------
164
+
165
+ def _sha256_file(path, limit=None):
166
+ limit = HASH_LIMIT_BYTES if limit is None else limit # looked up now, so changing the constant takes effect
167
+ try:
168
+ if os.path.getsize(path) > limit:
169
+ return None
170
+ h = hashlib.sha256()
171
+ with open(path, "rb") as f:
172
+ for chunk in iter(lambda: f.read(1 << 20), b""):
173
+ h.update(chunk)
174
+ return h.hexdigest()
175
+ except OSError:
176
+ return None
177
+
178
+
179
+ def _iso(ts):
180
+ return datetime.fromtimestamp(ts).isoformat(timespec="seconds")
181
+
182
+
183
+ def file_fingerprint(path, max_files=200, portable=False):
184
+ """Identifies a recording's folder or file without reading gigabytes: for a folder, every file
185
+ directly inside it (not its JSON saves/ or other subfolders) with its size and, if small enough, its
186
+ SHA-256; for a file, the same for it. `digest` condenses the list, so two records can be compared
187
+ at a glance.
188
+
189
+ `portable=True` leaves the absolute path out (the name stays), for a record that will leave the
190
+ machine; running the analysis again then needs the recording's location given explicitly."""
191
+ full = os.path.abspath(path)
192
+ out = {"name": os.path.basename(full.rstrip("/\\"))}
193
+ if not portable:
194
+ out["path"] = full
195
+ if os.path.isdir(full):
196
+ files, total, newest = [], 0, 0.0
197
+ for name in sorted(os.listdir(full)):
198
+ p = os.path.join(full, name)
199
+ if not os.path.isfile(p) or len(files) >= max_files:
200
+ continue
201
+ size = os.path.getsize(p)
202
+ total += size
203
+ newest = max(newest, os.path.getmtime(p))
204
+ files.append({"name": name, "size": size, "sha256": _sha256_file(p)})
205
+ out.update(kind="folder", n_files=len(files), size_bytes=total, files=files)
206
+ if newest:
207
+ out["modified"] = _iso(newest)
208
+ elif os.path.isfile(full):
209
+ size = os.path.getsize(full)
210
+ files = [{"name": out["name"], "size": size, "sha256": _sha256_file(full)}]
211
+ out.update(kind="file", n_files=1, size_bytes=size, files=files, modified=_iso(os.path.getmtime(full)))
212
+ else:
213
+ out.update(kind="missing", n_files=0, size_bytes=0, files=[])
214
+ return out
215
+ lines = "\n".join(f"{f['name']}|{f['size']}|{f['sha256'] or '-'}" for f in files)
216
+ out["digest"] = hashlib.sha256(lines.encode("utf-8")).hexdigest()
217
+ return out
218
+
219
+
220
+ def markers_summary(markers, detected_markers=None):
221
+ """How many markers there are and a digest of them (time to the microsecond, label, store, phase;
222
+ order does not matter), so a record can say which markers an analysis saw without holding them."""
223
+ def digest(ms):
224
+ keys = sorted((round(float(m["time"]), 6), str(m.get("label", "")), str(m.get("store", "")),
225
+ str(m.get("phase", ""))) for m in ms)
226
+ return hashlib.sha256(json.dumps(keys).encode("utf-8")).hexdigest()[:16]
227
+
228
+ out = {"n_user": len(markers), "user_digest": digest(markers)}
229
+ if detected_markers is not None:
230
+ out.update(n_detected=len(detected_markers), detected_digest=digest(detected_markers))
231
+ return out
232
+
233
+
234
+ def recording_state(cache, regression_method=None, splices=(), store_labels=None, signal=None):
235
+ """The state of a loaded recording that decides what an analysis sees: its type, length and sampling
236
+ rate, the motion-correction method, every splice applied (in order), the markers (counts and
237
+ digests, see markers_summary), the store renames in effect, and which signal was analysed. `cache` is
238
+ the dict of recording.py."""
239
+ x = cache["x"]
240
+ store = cache.get("store")
241
+ base_store = re.sub(r" \[(?:cut|kept) [^\]]*\]$", "", store) if isinstance(store, str) else store
242
+ out = {
243
+ "source_type": cache.get("source"),
244
+ "store": store,
245
+ "base_store": base_store,
246
+ "n_samples": int(len(x)),
247
+ "fs": float(cache["fs"]) if cache.get("fs") is not None else None,
248
+ "duration_s": float(x[-1] - x[0]) if len(x) else 0.0,
249
+ "splices": [dict(s) for s in splices],
250
+ "markers": markers_summary(cache.get("markers", []), cache.get("detected_markers")),
251
+ }
252
+ if cache.get("source") == "Generic":
253
+ # which table and columns of the file were opened — the choice a person makes in the loader's dialog
254
+ out["generic"] = {"table": base_store, "x_column": cache.get("x_label"), "y_columns": list(cache.get("y_columns", {}))}
255
+ if cache.get("signals"):
256
+ out["signal_labels"] = {k: sig["label"] for k, sig in cache["signals"].items()}
257
+ if regression_method is not None:
258
+ out["regression_method"] = regression_method
259
+ if store_labels:
260
+ out["store_labels"] = dict(store_labels)
261
+ if signal is not None:
262
+ out["signal"] = signal
263
+ return out
264
+
265
+
266
+ # ---------------------------------------------------------------------------
267
+ # Records
268
+ # ---------------------------------------------------------------------------
269
+
270
+ def output_entry(path):
271
+ """One entry of a record's `outputs`: the file's name, size and (if small enough) SHA-256."""
272
+ return {"name": os.path.basename(path), "size": os.path.getsize(path), "sha256": _sha256_file(path)}
273
+
274
+
275
+ def build_record(kind, parameters=None, *, source=None, recording=None, pipeline=None, app=None,
276
+ outputs=None, notes=None, now=None):
277
+ """Assembles a provenance record (see the module docstring). `source` is a path (fingerprinted here)
278
+ or an already-built fingerprint dict; `outputs` a list of file paths or entries; empty sections are left out."""
279
+ rec = {
280
+ "schema": SCHEMA_VERSION,
281
+ "kind": kind,
282
+ "created": (now or datetime.now()).isoformat(timespec="seconds"),
283
+ "software": software_versions(app),
284
+ }
285
+ if source is not None:
286
+ rec["source"] = source if isinstance(source, dict) else file_fingerprint(source)
287
+ if recording:
288
+ rec["recording"] = recording
289
+ if pipeline:
290
+ rec["pipeline"] = pipeline
291
+ rec["analysis"] = {"type": kind, "parameters": dict(parameters or {})}
292
+ if outputs:
293
+ rec["outputs"] = [o if isinstance(o, dict) else output_entry(o) for o in outputs]
294
+ if notes:
295
+ rec["notes"] = list(notes)
296
+ return rec
297
+
298
+
299
+ def sidecar_path_for(export_path):
300
+ """Where the record for an export goes: beside it, same name, `.provenance.json` in place of its
301
+ extension — `Event PETH.png` -> `Event PETH.provenance.json`."""
302
+ return os.path.splitext(export_path)[0] + SIDECAR_SUFFIX
303
+
304
+
305
+ def json_default(o):
306
+ import numpy as np
307
+ if isinstance(o, np.generic):
308
+ return o.item()
309
+ if isinstance(o, np.ndarray):
310
+ return o.tolist()
311
+ if isinstance(o, (set, tuple)):
312
+ return list(o)
313
+ raise TypeError(f"{type(o).__name__} is not JSON serialisable")
314
+
315
+
316
+ def write_record(path, record):
317
+ """Writes a record as indented UTF-8 JSON (NumPy numbers and arrays are converted); returns `path`."""
318
+ parent = os.path.dirname(path)
319
+ if parent:
320
+ os.makedirs(parent, exist_ok=True)
321
+ with open(path, "w", encoding="utf-8") as f:
322
+ json.dump(record, f, indent=2, ensure_ascii=False, default=json_default)
323
+ return path
324
+
325
+
326
+ def read_record(path):
327
+ """Reads a record back. Raises ValueError if it is not one (no `schema` / `kind`) or is from a newer
328
+ layout than this library understands."""
329
+ with open(path, "r", encoding="utf-8") as f:
330
+ rec = json.load(f)
331
+ if not isinstance(rec, dict) or "schema" not in rec or "kind" not in rec:
332
+ raise ValueError(f"{os.path.basename(path)} is not a provenance record")
333
+ if rec["schema"] > SCHEMA_VERSION:
334
+ raise ValueError(f"{os.path.basename(path)} uses provenance layout {rec['schema']}; this library reads "
335
+ f"up to {SCHEMA_VERSION} — update PyATCLI")
336
+ return rec