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,164 @@
1
+ """
2
+ analysis/group/run.py
3
+ -----------------------
4
+ Runs a group analysis end to end, headless: each recording of the spec is loaded (processed to dF/F,
5
+ its saved splices replayed, its saved markers put on top), its trials cut and measured, the models
6
+ fitted on all of them together (trials.extract_group_trials, stats.fit_group_models), and
7
+ the tables and report written (report.write_group_results). Also reads and writes the group's
8
+ settings file — analysis_settings.json, the spec plus what was in the recordings — which is what makes
9
+ a group analysis repeatable: run_group_analysis(GroupSpec.from_dict(spec_from_that_file)).
10
+
11
+ Recordings are handled one at a time and dropped again, so a large group never has more than one
12
+ recording's signal in memory. Figures are not drawn here (this library has no plotting); a caller that
13
+ wants them passes `extra_writers`.
14
+ """
15
+
16
+ import json
17
+ import os
18
+ from datetime import datetime
19
+
20
+ import pandas as pd
21
+
22
+ from ... import provenance
23
+ from ...markers import group_markers_by_name
24
+ from ...progress import Plan
25
+ from ...recording import load_tdt_recording, normalized_signal
26
+ from . import GroupSpec
27
+ from .report import write_group_results
28
+ from .stats import fit_group_models
29
+ from .trials import TRIAL_COLUMNS, extract_group_trials
30
+
31
+ GROUP_SETTINGS_FILENAME = "analysis_settings.json"
32
+
33
+
34
+ def load_group_recording(folder, regression_method="ols", store_labels=None, progress=None):
35
+ """
36
+ Loads one recording for group analysis exactly the way the single-recording analyses see it,
37
+ without a window: TDT block processed to dF/F, the recording's saved splices replayed (Cut Out
38
+ re-fits the dF/F, as in the app), its saved markers put on top, and the events grouped by name
39
+ with Event PETH's own grouping. The signal handed back is the normalized dF/F, the trace every
40
+ analysis uses.
41
+
42
+ Returns a dict with
43
+ x, y the time axis and the normalized dF/F after any saved splices
44
+ fs sampling rate in Hz
45
+ groups {marker name: sorted event times}, as Event PETH lists them
46
+ n_splices how many saved splices were applied
47
+ warnings saved files that could not be read (the recording is then used without them)
48
+ Raises ValueError if the folder is not a readable TDT block.
49
+ """
50
+ loaded = load_tdt_recording(folder, regression_method=regression_method, progress=progress)
51
+ cache = loaded["cache"]
52
+ _key, _label, y = normalized_signal(cache)
53
+ return {"x": cache["x"], "y": y, "fs": cache["fs"],
54
+ "groups": group_markers_by_name(cache, store_labels),
55
+ "n_splices": len(loaded["splices"]), "warnings": loaded["warnings"]}
56
+
57
+
58
+ def run_group_analysis(spec, out_dir=None, progress=None, load=load_group_recording, extra_writers=()):
59
+ """
60
+ The whole analysis for `spec` (a GroupSpec). If `out_dir` is given the tables and the report are
61
+ written there (write_group_results), then each of `extra_writers` — callables
62
+ f(results, out_dir) -> list of paths written — runs (the app draws and saves its figures this way).
63
+
64
+ `load(folder, regression_method, store_labels, progress)` returns what load_group_recording
65
+ returns; it is a parameter so the analysis can be run on recordings that are not TDT blocks on
66
+ disk (and so the tests can). Raises RuntimeError naming the subject if a recording cannot be
67
+ loaded: leaving one out silently would change the group, so the person is told and can leave it
68
+ out on purpose instead.
69
+
70
+ Returns the GroupResults.
71
+ """
72
+ subjects = list(spec.subjects)
73
+ stages = [(f"rec{i}", 1.0) for i in range(len(subjects))] + [("models", 1.5), ("writing", 0.3)]
74
+ plan = Plan(progress, stages)
75
+
76
+ frames, traces, excluded, notes, grid = [], {}, {m: 0 for m in spec.markers}, [], None
77
+ for i, s in enumerate(subjects):
78
+ name, folder = s["subject"], s["folder"]
79
+ report = plan.sub(f"rec{i}")
80
+
81
+ def relay(fraction, message="", _name=name):
82
+ if report is not None:
83
+ report(fraction, f"{_name}: {message}" if message else _name)
84
+
85
+ plan.begin(f"rec{i}", f"Loading {name} ({i + 1} of {len(subjects)})")
86
+ try:
87
+ data = load(folder, spec.regression_method, spec.store_labels, relay if report is not None else None)
88
+ except Exception as e:
89
+ raise RuntimeError(f"Could not load '{name}' ({folder}): {e}") from e
90
+ out = extract_group_trials(data["x"], data["y"], data["groups"], spec, subject=name, recording=folder)
91
+ frames.append(out["trials"])
92
+ traces[name] = out["traces"]
93
+ grid = out["grid"]
94
+ for marker, n in out["excluded"].items():
95
+ excluded[marker] = excluded.get(marker, 0) + n
96
+ for w in data.get("warnings", []):
97
+ notes.append({"level": "warning", "measure": "", "text": f"{name}: {w}"})
98
+ del data, out # the signal is not needed again: free it before the next one
99
+
100
+ plan.begin("models", "Fitting models")
101
+ trials = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame(columns=TRIAL_COLUMNS)
102
+ results = fit_group_models(trials, spec, progress=plan.sub("models"), traces=traces, trace_grid=grid,
103
+ excluded=excluded)
104
+ results.notes = notes + results.notes
105
+
106
+ if out_dir:
107
+ plan.begin("writing", "Writing the tables and the report")
108
+ results.files = write_group_results(results, out_dir)
109
+ for writer in extra_writers:
110
+ results.files += list(writer(results, out_dir))
111
+ plan.done()
112
+ return results
113
+
114
+
115
+ def write_group_settings(group_dir, spec, scans, app=None):
116
+ """Writes the group's analysis settings (the spec, and a summary of each recording used) to
117
+ <group_dir>/analysis_settings.json, creating the folder; returns the file's path.
118
+
119
+ `app` names the program doing the writing, e.g. {"name": "PyAT", "version": "3.2.0"} — recorded
120
+ with this library's own version, since both decide the numbers. The file is also a provenance record, so
121
+ `reproduce` can run it again; each recording carries the digest of its files at that time."""
122
+ from ... import __version__ as library_version
123
+
124
+ included = {s["folder"] for s in spec.subjects}
125
+ recordings = []
126
+ for sc in scans:
127
+ if sc["folder"] not in included:
128
+ continue
129
+ subject = next(s["subject"] for s in spec.subjects if s["folder"] == sc["folder"])
130
+ recordings.append({
131
+ "subject": subject, "folder": sc["folder"], "block_name": sc["block_name"],
132
+ "start_time": sc["start_time"], "events_per_marker": {m: len(t) for m, t in sc["groups"].items()},
133
+ "saved_splices_applied": sc["n_splices"], "saved_markers": sc["n_saved_markers"],
134
+ })
135
+ for r in recordings:
136
+ r["digest"] = provenance.file_fingerprint(r["folder"]).get("digest")
137
+ doc = {
138
+ "app": {**(app or {"name": "PyATCLI"}), "library_version": library_version},
139
+ "created": datetime.now().isoformat(timespec="seconds"),
140
+ "spec": spec.to_dict(),
141
+ "recordings": recordings,
142
+ # The same file is a provenance record (provenance.py): reproduce.reproduce() and `python -m PyATCLI
143
+ # reproduce` replay it, and the versions it was written with are checked against the ones running.
144
+ "schema": provenance.SCHEMA_VERSION,
145
+ "kind": "group_analysis",
146
+ "software": provenance.software_versions(app),
147
+ "pipeline": provenance.pipeline_parameters(spec.regression_method),
148
+ "analysis": {"type": "group_analysis", "parameters": spec.to_dict()},
149
+ }
150
+ os.makedirs(group_dir, exist_ok=True)
151
+ path = os.path.join(group_dir, GROUP_SETTINGS_FILENAME)
152
+ with open(path, "w", encoding="utf-8") as f:
153
+ json.dump(doc, f, indent=2, ensure_ascii=False)
154
+ return path
155
+
156
+
157
+ def read_group_settings(path):
158
+ """Reads an analysis_settings.json back: returns (GroupSpec, the whole document). `path` may be
159
+ the file or the group's folder."""
160
+ if os.path.isdir(path):
161
+ path = os.path.join(path, GROUP_SETTINGS_FILENAME)
162
+ with open(path, "r", encoding="utf-8") as f:
163
+ doc = json.load(f)
164
+ return GroupSpec.from_dict(doc["spec"]), doc
@@ -0,0 +1,92 @@
1
+ """
2
+ analysis/group/scan.py
3
+ ------------------------
4
+ Finds out what each recording of a group contains — its event markers and how long it is — without
5
+ processing the signal, so a setup step can list the markers the recordings share before anything slow
6
+ happens.
7
+
8
+ A recording's markers are built the way the single-recording analyses build them: the events TDT
9
+ detected (with the recording's saved splices applied, as PyAT does when it restores splice.json) plus
10
+ any markers saved next to it (JSON saves/markers.json), grouped by name with markers.group_markers_by_name.
11
+ No GUI is involved, so this is safe on a worker thread.
12
+ """
13
+
14
+ import os
15
+
16
+ from ...markers import group_markers_by_name
17
+ from ...sources.processing_TDT import scan_tdt_markers, validate_tdt_folder
18
+ from ...progress import Plan
19
+ from ...recording import read_saved_markers, read_saved_splices
20
+
21
+
22
+ def default_subject_names(folders, base_path):
23
+ """One subject name per recording: the recording's own folder name (Synapse's
24
+ Subject-YYMMDD-HHMMSS). Two recordings that share a folder name (in different
25
+ subfolders) get their path from the searched folder on, so names start out unique."""
26
+ names = [os.path.basename(f.rstrip("/\\")) for f in folders]
27
+ out = []
28
+ for f, n in zip(folders, names):
29
+ out.append(n if names.count(n) == 1 else os.path.relpath(f, base_path).replace("\\", "/"))
30
+ return out
31
+
32
+
33
+ def scan_recording(folder, base_path, store_labels=None, progress=None):
34
+ """
35
+ What one recording contains.
36
+
37
+ Returns a dict with
38
+ folder, name (its folder name), label (path from the searched folder),
39
+ groups {marker name: sorted event times} — every event the single-recording
40
+ analyses would offer, under the same names
41
+ t_range (first, last sample time) after any saved splices, or None
42
+ n_events, n_splices (applied), n_splices_saved, n_saved_markers,
43
+ block_name, start_time, warnings (things skipped, in words), error (None, or why the
44
+ recording could not be read at all — then `groups` is empty).
45
+ """
46
+ result = {
47
+ "folder": folder,
48
+ "name": os.path.basename(folder.rstrip("/\\")),
49
+ "label": os.path.relpath(folder, base_path).replace("\\", "/"),
50
+ "groups": {}, "t_range": None, "n_events": 0,
51
+ "n_splices": 0, "n_splices_saved": 0, "n_saved_markers": 0,
52
+ "block_name": None, "start_time": None, "warnings": [], "error": None,
53
+ }
54
+ try:
55
+ valid, message = validate_tdt_folder(folder)
56
+ if not valid:
57
+ raise ValueError(message)
58
+ splices = []
59
+ try:
60
+ splices = read_saved_splices(folder)
61
+ except Exception as e:
62
+ result["warnings"].append(f"Saved splices could not be read ({e}); the recording is used as recorded.")
63
+ result["n_splices_saved"] = len(splices)
64
+
65
+ scan = scan_tdt_markers(folder, splices=splices or None, progress=progress)
66
+
67
+ saved = []
68
+ try:
69
+ saved = read_saved_markers(folder)
70
+ except Exception as e:
71
+ result["warnings"].append(f"Saved markers could not be read ({e}); only the recorded events are used.")
72
+
73
+ groups = group_markers_by_name({"detected_markers": scan["markers"], "markers": saved}, store_labels)
74
+ result.update(groups=groups, t_range=scan["t_range"], n_events=sum(len(t) for t in groups.values()),
75
+ n_splices=scan["n_splices"], n_saved_markers=len(saved),
76
+ block_name=scan["block_name"], start_time=scan["start_time"])
77
+ except Exception as e:
78
+ result["error"] = str(e) or type(e).__name__
79
+ return result
80
+
81
+
82
+ def scan_recordings(folders, base_path, store_labels=None, progress=None):
83
+ """scan_recording for each folder, in order, one step of `progress` per recording. A recording
84
+ that cannot be read comes back with its `error` set instead of stopping the rest."""
85
+ plan = Plan(progress, [(f"rec{i}", 1) for i in range(len(folders))])
86
+ out = []
87
+ for i, folder in enumerate(folders):
88
+ name = os.path.basename(folder.rstrip("/\\"))
89
+ plan.begin(f"rec{i}", f"Scanning {name} ({i + 1} of {len(folders)})")
90
+ out.append(scan_recording(folder, base_path, store_labels))
91
+ plan.done()
92
+ return out