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,318 @@
1
+ """
2
+ analysis/group.py
3
+ -----------------
4
+ Group analysis across recordings ("Hypothesis Testing" in PyAT): the same
5
+ event-locked responses measured in every recording of a group, reduced to a few
6
+ numbers per trial, and compared with a linear mixed-effects model.
7
+
8
+ What is analysed
9
+ Every recording in the group is one subject. The variables are event markers
10
+ (lever presses, notes, ...); a trial is one occurrence of a marker, taken from
11
+ the recording exactly as the single-recording Event PETH takes it. Each trial
12
+ is a window around its event: [-pre, +post] seconds. Inside it, a baseline
13
+ window and a response window (both in seconds relative to the event) define
14
+ the numbers computed per trial:
15
+
16
+ auc area under the baseline-corrected trace across the response window
17
+ peak baseline-corrected value at the peak in the response window
18
+ (peak_direction: "positive", "negative", or "absolute" = the largest
19
+ deflection either way, signed, as the single-recording Event PETH does)
20
+ mean mean of the baseline-corrected trace across the response window
21
+ latency seconds from the event to the peak
22
+ decay seconds from the peak until the trace has fallen to
23
+ `decay_fraction` of the peak (0.5 = half-decay time); looked for from
24
+ the peak to the end of the trial window, empty if it never falls that far
25
+
26
+ "Baseline-corrected" is set by `signal`: "dff" subtracts the baseline window's
27
+ mean from the trial's dF/F; "zscore" also divides by the baseline's SD. The signal is
28
+ first smoothed with a moving average of `smooth_seconds`, as Event PETH does.
29
+
30
+ How it is analysed (stats.py)
31
+ Each measure is analysed on its own. With two or more markers: a linear mixed-effects
32
+ model, measure ~ marker, with a random intercept for subject and a random intercept for
33
+ each subject x marker cell. The cell term matters: trials of one subject and marker
34
+ share a cell-level effect (and neighbouring trials share signal), and without it the
35
+ test treats every trial as independent evidence about the marker difference, which gives
36
+ false positives far above the nominal rate (65-93% of runs at a nominal 5% in the simulations
37
+ described in stats.py).
38
+ p-values use t / F with subject-based degrees of freedom (n_subjects - 1 for a contrast,
39
+ like a paired test), then all pairwise comparisons between markers are corrected for
40
+ multiple comparisons. With one marker there is nothing to compare it with: AUC and mean
41
+ amplitude are tested against zero (the baseline-corrected trace has mean zero without a
42
+ response); the peak, latency and decay time, which are extreme-value or timing statistics
43
+ with no zero to compare against, are reported as estimates with intervals only. Every
44
+ analysis is repeated on subject x marker means as a check that does not rely on trials
45
+ being independent.
46
+
47
+ This file has the parts needed before any signal is loaded: the settings object
48
+ (GroupSpec), and checks on the design (which markers the recordings share, how many
49
+ trials each subject would contribute, whether trials overlap). trials.py slices the
50
+ trials and computes the measures; stats.py fits the models.
51
+
52
+ Defaults
53
+ There is no formal standard for the window. The closest thing to a reference is
54
+ TDT's own fiber photometry epoch-averaging example, which uses TRANGE = [-10, 20]
55
+ (start, then window *duration*: -10 s to +10 s around the event) and a baseline of
56
+ -10 to -6 s, z-scoring each trial against it. GuPPy and pMAT leave the window and
57
+ baseline to the user. These defaults follow TDT's example; the response window is
58
+ the whole post-event half.
59
+ """
60
+
61
+ import math
62
+ from dataclasses import dataclass, field, fields
63
+
64
+ import numpy as np
65
+
66
+ from ...sources.processing_TDT import REGRESSION_METHODS
67
+
68
+ METRICS = ("auc", "peak", "mean", "latency", "decay")
69
+ METRIC_LABELS = {
70
+ "auc": "AUC",
71
+ "peak": "Peak amplitude",
72
+ "mean": "Mean amplitude",
73
+ "latency": "Latency to peak",
74
+ "decay": "Decay time",
75
+ }
76
+ SIGNALS = ("dff", "zscore")
77
+ PEAK_DIRECTIONS = ("positive", "negative", "absolute")
78
+ CORRECTIONS = ("holm", "bonferroni", "fdr_bh")
79
+ CORRECTION_LABELS = {"holm": "Holm", "bonferroni": "Bonferroni", "fdr_bh": "Benjamini-Hochberg (FDR)"}
80
+
81
+ DEFAULT_PRE = 10.0
82
+ DEFAULT_POST = 10.0
83
+ DEFAULT_BASELINE = (-10.0, -6.0)
84
+ DEFAULT_RESPONSE = (0.0, 10.0)
85
+
86
+ # Below this many subjects a mixed model's estimate of how much subjects differ is unreliable;
87
+ # below the second, its Wald z p-values (no small-sample degrees of freedom) run optimistic.
88
+ MIN_SUBJECTS_RELIABLE = 6
89
+ MIN_SUBJECTS_APPROXIMATE_P = 20
90
+
91
+
92
+ @dataclass
93
+ class GroupSpec:
94
+ """Everything the user decides for one group analysis; saved as JSON next to the results."""
95
+
96
+ group_name: str = ""
97
+ # [{"subject": name, "folder": path}, ...] — one entry per recording, subject names unique.
98
+ subjects: list = field(default_factory=list)
99
+ # Marker names as PyAT lists them: a store's name plus a superscript 1 (onset) or 0 (offset),
100
+ # or a note's own text.
101
+ markers: list = field(default_factory=list)
102
+ # Store renames in effect when the markers were listed ({store id: shown name}); a marker name
103
+ # only means something together with the renames that produced it.
104
+ store_labels: dict = field(default_factory=dict)
105
+ pre: float = DEFAULT_PRE
106
+ post: float = DEFAULT_POST
107
+ baseline: tuple = DEFAULT_BASELINE
108
+ response: tuple = DEFAULT_RESPONSE
109
+ signal: str = "dff"
110
+ # Moving-average smoothing of the dF/F before slicing, in seconds (0 = none); 0.5 is what the
111
+ # single-recording Event PETH applies.
112
+ smooth_seconds: float = 0.5
113
+ metrics: list = field(default_factory=lambda: list(METRICS))
114
+ peak_direction: str = "absolute"
115
+ decay_fraction: float = 0.5
116
+ # Multiple-comparison correction across the pairwise comparisons of one measure, and the level.
117
+ correction: str = "holm"
118
+ alpha: float = 0.05
119
+ # The dF/F is recomputed for every recording with this motion-correction method.
120
+ regression_method: str = "ols"
121
+
122
+ def to_dict(self):
123
+ d = {f.name: getattr(self, f.name) for f in fields(self)}
124
+ d["baseline"] = list(self.baseline)
125
+ d["response"] = list(self.response)
126
+ return d
127
+
128
+ @classmethod
129
+ def from_dict(cls, d):
130
+ """Rebuilds a spec from to_dict()'s output (a JSON round trip); unknown keys are ignored."""
131
+ known = {f.name for f in fields(cls)}
132
+ spec = cls(**{k: v for k, v in d.items() if k in known})
133
+ spec.baseline = tuple(spec.baseline)
134
+ spec.response = tuple(spec.response)
135
+ return spec
136
+
137
+ def window_problems(self):
138
+ """Just the rules for the window around the event, its baseline and its response window."""
139
+ out = []
140
+ if not (_finite(self.pre) and self.pre > 0 and _finite(self.post) and self.post > 0):
141
+ out.append("The window needs a positive number of seconds before and after the event.")
142
+ return out
143
+ b0, b1 = self.baseline
144
+ if not (_finite(b0) and _finite(b1) and b0 < b1):
145
+ out.append("The baseline window must run from an earlier to a later time.")
146
+ elif b0 < -self.pre or b1 > 0:
147
+ out.append(f"The baseline window must lie between -{self.pre:g} s and 0 s "
148
+ "(before the event, inside the window).")
149
+ r0, r1 = self.response
150
+ if not (_finite(r0) and _finite(r1) and r0 < r1):
151
+ out.append("The response window must run from an earlier to a later time.")
152
+ elif r0 < 0 or r1 > self.post:
153
+ out.append(f"The response window must lie between 0 s and {self.post:g} s "
154
+ "(after the event, inside the window).")
155
+ return out
156
+
157
+ def problems(self):
158
+ """Everything that makes this spec unusable, as plain sentences (empty list = fine)."""
159
+ out = []
160
+ names = [s.get("subject", "") for s in self.subjects]
161
+ if len(self.subjects) < 2:
162
+ out.append("Pick at least two recordings: a group comparison needs more than one subject.")
163
+ if any(not str(n).strip() for n in names):
164
+ out.append("Every subject needs a name.")
165
+ elif len(set(names)) != len(names):
166
+ dupes = sorted({n for n in names if names.count(n) > 1})
167
+ out.append("Subject names must be unique (repeated: " + ", ".join(dupes) + ").")
168
+
169
+ if not self.markers:
170
+ out.append("Pick at least one marker.")
171
+ elif len(set(self.markers)) != len(self.markers):
172
+ out.append("Each marker can only be picked once.")
173
+
174
+ out.extend(self.window_problems())
175
+
176
+ if not self.metrics:
177
+ out.append("Pick at least one measure (AUC, peak, ...).")
178
+ elif any(m not in METRICS for m in self.metrics):
179
+ out.append("Unknown measure: " + ", ".join(m for m in self.metrics if m not in METRICS) + ".")
180
+ if self.signal not in SIGNALS:
181
+ out.append(f"Signal must be one of {', '.join(SIGNALS)}.")
182
+ if self.peak_direction not in PEAK_DIRECTIONS:
183
+ out.append(f"Peak direction must be one of {', '.join(PEAK_DIRECTIONS)}.")
184
+ if not (_finite(self.decay_fraction) and 0 < self.decay_fraction < 1):
185
+ out.append("The decay level must be between 0 and 100% of the peak.")
186
+ if not (_finite(self.smooth_seconds) and self.smooth_seconds >= 0):
187
+ out.append("The smoothing window must be zero (none) or a positive number of seconds.")
188
+ if self.correction not in CORRECTIONS:
189
+ out.append(f"Correction must be one of {', '.join(CORRECTIONS)}.")
190
+ if not (_finite(self.alpha) and 0 < self.alpha < 1):
191
+ out.append("The significance level must be between 0 and 1.")
192
+ if self.regression_method not in REGRESSION_METHODS:
193
+ out.append(f"Regression method must be one of {', '.join(REGRESSION_METHODS)}.")
194
+ return out
195
+
196
+
197
+ def _finite(v):
198
+ return isinstance(v, (int, float, np.floating, np.integer)) and math.isfinite(v)
199
+
200
+
201
+ def marker_index(scans):
202
+ """
203
+ Which markers the recordings have, and how many events of each.
204
+
205
+ Parameters
206
+ ----------
207
+ scans : list of {"subject": str, "groups": {marker name: [event times]}, ...}
208
+
209
+ Returns
210
+ -------
211
+ {marker: {"recordings": how many recordings have it, "events": total events,
212
+ "per_subject": {subject: events}}} — only recordings that have at least one
213
+ event of a marker are counted for it.
214
+ """
215
+ index = {}
216
+ for sc in scans:
217
+ for name, times in sc["groups"].items():
218
+ if len(times) == 0:
219
+ continue
220
+ entry = index.setdefault(name, {"recordings": 0, "events": 0, "per_subject": {}})
221
+ entry["recordings"] += 1
222
+ entry["events"] += len(times)
223
+ entry["per_subject"][sc["subject"]] = len(times)
224
+ return index
225
+
226
+
227
+ def common_markers(scans):
228
+ """Marker names present (at least one event) in every one of the recordings, sorted."""
229
+ n = len(scans)
230
+ return sorted(name for name, e in marker_index(scans).items() if n and e["recordings"] == n)
231
+
232
+
233
+ def design_summary(scans, markers, pre, post):
234
+ """
235
+ How many trials each subject would contribute per marker, worked out from the event
236
+ times alone (no signal is loaded), plus the problems worth knowing about first.
237
+
238
+ A trial is *usable* if its whole window, [event - pre, event + post], lies inside the
239
+ recording. Trials *overlap* when their windows share samples (events less than
240
+ pre + post seconds apart): the same stretch of signal then enters more than one trial,
241
+ so trials of one subject are not independent of each other.
242
+
243
+ Parameters
244
+ ----------
245
+ scans : list of {"subject", "groups": {marker: [event times]}, "t_range": (first, last)
246
+ sample time, or None if unknown}
247
+ markers : list of marker names to summarise
248
+ pre, post : float
249
+ Seconds before and after each event.
250
+
251
+ Returns
252
+ -------
253
+ dict with
254
+ cells : {subject: {marker: {"events", "usable", "overlapping"}}} ("overlapping"
255
+ counts usable trials whose window shares samples with another usable trial's)
256
+ markers : {marker: {"events", "usable", "overlapping", "subjects_with_trials",
257
+ "min_usable", "max_usable"}} (min/max across subjects, zeros included)
258
+ n_subjects : number of subjects
259
+ warnings : list of {"level": "warning" | "info", "text": str}
260
+ """
261
+ span = pre + post
262
+ cells = {}
263
+ for sc in scans:
264
+ t0, t1 = sc.get("t_range") or (-math.inf, math.inf)
265
+ row = {}
266
+ for m in markers:
267
+ times = np.sort(np.asarray(sc["groups"].get(m, []), dtype=float))
268
+ usable = times[(times - pre >= t0) & (times + post <= t1)]
269
+ overlap = np.zeros(len(usable), dtype=bool)
270
+ if len(usable) > 1:
271
+ close = np.diff(usable) < span
272
+ overlap[:-1] |= close
273
+ overlap[1:] |= close
274
+ row[m] = {"events": int(len(times)), "usable": int(len(usable)), "overlapping": int(overlap.sum())}
275
+ cells[sc["subject"]] = row
276
+
277
+ per_marker = {}
278
+ for m in markers:
279
+ usable = [cells[s][m]["usable"] for s in cells]
280
+ per_marker[m] = {
281
+ "events": sum(cells[s][m]["events"] for s in cells),
282
+ "usable": sum(usable),
283
+ "overlapping": sum(cells[s][m]["overlapping"] for s in cells),
284
+ "subjects_with_trials": sum(1 for u in usable if u > 0),
285
+ "min_usable": min(usable) if usable else 0,
286
+ "max_usable": max(usable) if usable else 0,
287
+ }
288
+
289
+ warnings = []
290
+ n_subjects = len(scans)
291
+ for m in markers:
292
+ info = per_marker[m]
293
+ missing = [s for s in cells if cells[s][m]["usable"] == 0]
294
+ if info["usable"] == 0:
295
+ warnings.append({"level": "warning", "text": f"'{m}' has no usable trials in any recording."})
296
+ elif missing:
297
+ shown = ", ".join(missing[:4]) + (f" and {len(missing) - 4} more" if len(missing) > 4 else "")
298
+ warnings.append({"level": "warning",
299
+ "text": f"'{m}': {len(missing)} of {n_subjects} subjects have no usable trials "
300
+ f"({shown}); they will not contribute to it."})
301
+ if info["usable"]:
302
+ share = info["overlapping"] / info["usable"]
303
+ if share >= 0.5:
304
+ warnings.append({"level": "warning",
305
+ "text": f"'{m}': {share:.0%} of trials share samples with another trial's window, "
306
+ "so trials are not independent of each other. A shorter window reduces this."})
307
+ elif share > 0:
308
+ warnings.append({"level": "info",
309
+ "text": f"'{m}': {share:.0%} of trials share samples with another trial's window."})
310
+ if n_subjects < MIN_SUBJECTS_RELIABLE:
311
+ warnings.append({"level": "warning",
312
+ "text": f"Only {n_subjects} subjects: a mixed model cannot estimate how much subjects "
313
+ "differ reliably with so few."})
314
+ elif n_subjects < MIN_SUBJECTS_APPROXIMATE_P:
315
+ warnings.append({"level": "info",
316
+ "text": f"With {n_subjects} subjects the mixed model's p-values (Wald z tests, no small-sample "
317
+ "correction) are approximate and lean optimistic."})
318
+ return {"cells": cells, "markers": per_marker, "n_subjects": n_subjects, "warnings": warnings}
@@ -0,0 +1,59 @@
1
+ """
2
+ analysis/group/rebuild.py
3
+ -------------------------
4
+ A group analysis's GroupResults put back together from its tables: the ones `run_analysis` / run_group_analysis return, or the CSVs written to the
5
+ group's folder read back (results.open_results). What a viewer needs to show a result that is no longer in memory: the report is written from
6
+ a GroupResults (report.report_text), and so are the figures.
7
+ """
8
+
9
+ import os
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from . import GroupSpec
15
+ from .report import CSV_NAMES
16
+ from .stats import FRAME_NAMES, GroupResults
17
+
18
+ _FRAME_BY_STEM = {os.path.splitext(filename)[0]: frame for frame, filename in CSV_NAMES.items()}
19
+
20
+
21
+ def _frames(tables):
22
+ """{frame name: DataFrame} from tables keyed either by frame name (a result in memory) or by the stem of the CSV file it was written to
23
+ (a folder read back)."""
24
+ return {_FRAME_BY_STEM.get(key, key): table for key, table in tables.items()}
25
+
26
+
27
+ def _ordered(values):
28
+ return list(dict.fromkeys(values))
29
+
30
+
31
+ def results_from_tables(tables, parameters=None, notes=None, software=None):
32
+ """A GroupResults rebuilt from a group analysis's tables. `parameters` is the analysis's GroupSpec as a dict (its settings file holds it);
33
+ without it the spec is inferred from the tables (the markers, subjects and measures in them, default windows). `notes` ([{"level",
34
+ "measure", "text"}, ...]) and `software` are what the analysis said and ran on, which no table holds: given, the report of the rebuilt
35
+ results reads as the original's. None if these are not a group analysis's tables (no mean traces and no subject means)."""
36
+ frames = _frames(tables)
37
+ traces_table = frames.get("mean_traces")
38
+ means = frames.get("subject_means")
39
+ if traces_table is None and means is None:
40
+ return None
41
+ if parameters and parameters.get("markers"):
42
+ spec = GroupSpec.from_dict(parameters)
43
+ else:
44
+ source = traces_table if traces_table is not None else means
45
+ spec = GroupSpec(group_name="Group analysis", subjects=[{"subject": s, "folder": ""} for s in _ordered(source["subject"])],
46
+ markers=_ordered(source["marker"]), metrics=_ordered(means["measure"]) if means is not None else ["auc"])
47
+ traces, grid = {}, None
48
+ if traces_table is not None and len(traces_table):
49
+ grid = np.sort(traces_table["time"].astype(float).unique())
50
+ for (subject, marker), g in traces_table.groupby(["subject", "marker"], sort=False):
51
+ g = g.sort_values("time")
52
+ traces.setdefault(subject, {})[marker] = {"n": int(g["n_trials"].iloc[0]), "mean": g["value"].to_numpy(float)}
53
+ extra = {name: frames.get(name, pd.DataFrame()) for name in FRAME_NAMES}
54
+ results = GroupResults(spec=spec, trials=frames.get("trials", pd.DataFrame()), traces=traces, trace_grid=grid, **extra)
55
+ if notes is not None:
56
+ results.notes = [dict(n) for n in notes]
57
+ if software is not None:
58
+ results.software = dict(software)
59
+ return results
@@ -0,0 +1,281 @@
1
+ """
2
+ analysis/group/report.py
3
+ ------------------------
4
+ A group analysis written down: every table as a CSV file, and a plain-text report (design, results per
5
+ measure, notes, and a methods paragraph to adapt). Files are UTF-8 with a byte-order mark so Excel reads the
6
+ superscript 1 / 0 in marker names correctly.
7
+ """
8
+
9
+ import json
10
+ import math
11
+ import os
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from . import CORRECTION_LABELS, METRIC_LABELS
17
+
18
+ REPORT_FILENAME = "analysis_report.txt"
19
+ NOTES_FILENAME = "analysis_notes.json" # what the analysis said (notes) and ran on (software): no table holds them, a folder read back needs them
20
+
21
+ _SIGNAL_TEXT = {"dff": "dF/F minus the baseline mean", "zscore": "z-score against the baseline"}
22
+ _DIRECTION_TEXT = {"positive": "the largest positive value", "negative": "the largest negative value",
23
+ "absolute": "the largest deflection in either direction (signed)"}
24
+
25
+ CSV_NAMES = {
26
+ "trials": "trials_long.csv",
27
+ "subject_means": "subject_means.csv",
28
+ "descriptives": "descriptives.csv",
29
+ "models": "models.csv",
30
+ "fixed_effects": "model_fixed_effects.csv",
31
+ "omnibus": "model_omnibus_tests.csv",
32
+ "variance": "model_variance_components.csv",
33
+ "estimated_means": "estimated_means.csv",
34
+ "pairwise": "posthoc_pairwise_comparisons.csv",
35
+ "diagnostics": "model_residuals.csv",
36
+ "random_effects": "model_random_effects.csv",
37
+ }
38
+
39
+ # Where each table of a group analysis goes in its folder (the CSVs above, and the mean traces), and the columns of each that are ALWAYS there — a
40
+ # program that reads a group's folder (PyAT's Open Results) may ask for them by name. A table can have more columns, and more tables can appear;
41
+ # removing or renaming a listed table, file or column is a breaking change (engine/contract.py, ops.PROTOCOL_VERSION). Tables with no rows are not written.
42
+ TABLE_FILES = {**CSV_NAMES, "mean_traces": "mean_traces.csv"}
43
+
44
+ GROUP_TABLES = {
45
+ "trials": ["subject", "marker", "trial", "event_time", "valid", "auc", "peak", "mean", "latency", "decay"],
46
+ "subject_means": ["subject", "marker", "measure", "n", "mean"],
47
+ "descriptives": ["measure", "marker", "n_subjects", "n_trials", "mean_of_subject_means", "sd_of_subject_means", "sem", "ci_low", "ci_high"],
48
+ "models": ["measure", "basis", "status", "formula", "n_observations", "n_subjects", "converged"],
49
+ "fixed_effects": ["measure", "basis", "term", "estimate", "se", "ci_low", "ci_high"],
50
+ "omnibus": ["measure", "basis", "test"],
51
+ "variance": ["measure", "basis", "component", "variance"],
52
+ "estimated_means": ["measure", "basis", "marker", "mean", "se", "ci_low", "ci_high"],
53
+ "pairwise": ["measure", "basis", "marker_a", "marker_b", "difference", "se", "p_adjusted", "significant"],
54
+ "diagnostics": ["subject", "marker", "measure", "observed", "fitted", "resid"],
55
+ "random_effects": ["measure", "basis", "subject", "effect"],
56
+ "mean_traces": ["marker", "subject", "n_trials", "time", "value"],
57
+ }
58
+
59
+
60
+ def measure_units(measure, signal):
61
+ """Units of a measure, as text: the trace's own unit for amplitudes, its unit x seconds for the AUC."""
62
+ trace = "dF/F" if signal == "dff" else "z"
63
+ return {"auc": f"{trace} x s", "peak": trace, "mean": trace, "latency": "s", "decay": "s"}[measure]
64
+
65
+
66
+ def trace_frame(results):
67
+ """The mean traces in long format: marker, subject, n_trials, time, value."""
68
+ grid = results.trace_grid
69
+ rows = []
70
+ for subject, by_marker in results.traces.items():
71
+ for marker, tr in by_marker.items():
72
+ if tr["n"] == 0:
73
+ continue
74
+ rows.append(pd.DataFrame({"marker": marker, "subject": subject, "n_trials": tr["n"],
75
+ "time": grid, "value": tr["mean"]}))
76
+ return pd.concat(rows, ignore_index=True) if rows else pd.DataFrame(
77
+ columns=["marker", "subject", "n_trials", "time", "value"])
78
+
79
+
80
+ def write_group_results(results, directory):
81
+ """Write every table as CSV and the text report into `directory` (created if needed). Returns the paths."""
82
+ os.makedirs(directory, exist_ok=True)
83
+ paths = []
84
+ frames = results.frames()
85
+ for name, filename in CSV_NAMES.items():
86
+ df = frames.get(name)
87
+ if df is None or not len(df):
88
+ continue
89
+ path = os.path.join(directory, filename)
90
+ df.to_csv(path, index=False, encoding="utf-8-sig")
91
+ paths.append(path)
92
+ traces = trace_frame(results)
93
+ if len(traces):
94
+ path = os.path.join(directory, "mean_traces.csv")
95
+ traces.to_csv(path, index=False, encoding="utf-8-sig")
96
+ paths.append(path)
97
+ path = os.path.join(directory, REPORT_FILENAME)
98
+ with open(path, "w", encoding="utf-8-sig") as f:
99
+ f.write(report_text(results))
100
+ paths.append(path)
101
+ path = os.path.join(directory, NOTES_FILENAME)
102
+ with open(path, "w", encoding="utf-8") as f:
103
+ json.dump({"notes": [dict(n) for n in results.notes], "software": dict(results.software)}, f, indent=2, ensure_ascii=False)
104
+ paths.append(path)
105
+ return paths
106
+
107
+
108
+ def read_group_notes(directory):
109
+ """(notes, software) a group's folder holds — what the analysis said and ran on, as write_group_results saved them; ([], {}) for a folder
110
+ from before they were saved or one that cannot be read."""
111
+ try:
112
+ with open(os.path.join(directory, NOTES_FILENAME), "r", encoding="utf-8") as f:
113
+ doc = json.load(f)
114
+ return [dict(n) for n in doc.get("notes") or []], dict(doc.get("software") or {})
115
+ except (OSError, ValueError, TypeError):
116
+ return [], {}
117
+
118
+
119
+ def _num(v, digits=4):
120
+ if v is None or (isinstance(v, float) and not math.isfinite(v)):
121
+ return "-"
122
+ if isinstance(v, (int, np.integer)):
123
+ return f"{int(v):,}"
124
+ return f"{v:.{digits}g}"
125
+
126
+
127
+ def _p(v):
128
+ if v is None or not np.isfinite(v):
129
+ return "-"
130
+ return "<0.0001" if v < 1e-4 else f"{v:.4f}"
131
+
132
+
133
+ def _peq(v):
134
+ """'p = 0.0123' or 'p < 0.0001'."""
135
+ text = _p(v)
136
+ return f"p {text}" if text.startswith("<") else f"p = {text}"
137
+
138
+
139
+ def _table(df, columns, headers, indent=6):
140
+ if not len(df):
141
+ return " " * indent + "(none)\n"
142
+ shown = pd.DataFrame({h: df[c] for c, h in zip(columns, headers)})
143
+ return "\n".join(" " * indent + line for line in shown.to_string(index=False, justify="left").splitlines()) + "\n"
144
+
145
+
146
+ def report_text(results):
147
+ """The plain-text report."""
148
+ spec = results.spec
149
+ out = []
150
+ add = out.append
151
+ subjects = [s["subject"] for s in spec.subjects]
152
+ add(f"GROUP ANALYSIS: {spec.group_name}")
153
+ add("=" * (16 + len(spec.group_name)))
154
+ add(f"Subjects ({len(subjects)}): " + ", ".join(subjects))
155
+ add(f"Markers ({len(spec.markers)}): " + ", ".join(spec.markers))
156
+ add(f"Window: {spec.pre:g} s before to {spec.post:g} s after each event; baseline {spec.baseline[0]:g} to "
157
+ f"{spec.baseline[1]:g} s; response {spec.response[0]:g} to {spec.response[1]:g} s")
158
+ add(f"Signal: {_SIGNAL_TEXT.get(spec.signal, spec.signal)}"
159
+ + (f"; smoothed with a {spec.smooth_seconds:g} s moving average" if spec.smooth_seconds > 0 else "; not smoothed")
160
+ + f"; motion correction {spec.regression_method.upper()}")
161
+ add("Measures: " + ", ".join(f"{METRIC_LABELS[m]} ({measure_units(m, spec.signal)})" for m in spec.metrics)
162
+ + f"; peak = {_DIRECTION_TEXT[spec.peak_direction]}; decay = time to fall to {spec.decay_fraction:.0%} of the peak")
163
+ add("")
164
+
165
+ trials = results.trials
166
+ add("TRIALS")
167
+ if len(trials):
168
+ table = trials.pivot_table(index="subject", columns="marker", values="trial", aggfunc="count", fill_value=0)
169
+ table = table.reindex(index=[s for s in subjects if s in table.index],
170
+ columns=[m for m in spec.markers if m in table.columns])
171
+ overlap = trials.groupby("marker")["overlap"].mean()
172
+ add(" Trials per subject (all with a full window inside the recording):")
173
+ add("\n".join(" " + line for line in table.to_string().splitlines()))
174
+ add(" Share of trials whose window shares samples with a neighbouring trial's: "
175
+ + ", ".join(f"{m} {overlap[m]:.0%}" for m in spec.markers if m in overlap.index))
176
+ skipped = {m: n for m, n in results.excluded.items() if n}
177
+ if skipped:
178
+ add(" Events left out because their window is not fully inside the recording: "
179
+ + ", ".join(f"{m} {n}" for m, n in skipped.items()))
180
+ else:
181
+ add(" No trials.")
182
+ add("")
183
+
184
+ add("RESULTS")
185
+ for measure in spec.metrics:
186
+ label = METRIC_LABELS[measure]
187
+ add("")
188
+ add(f"{label} ({measure_units(measure, spec.signal)})")
189
+ add("-" * (len(label) + len(measure_units(measure, spec.signal)) + 3))
190
+ d = results.descriptives
191
+ d = d[d["measure"] == measure] if len(d) else d
192
+ add(" Mean of the subject means, by marker:")
193
+ if len(d):
194
+ d = d.assign(**{c: [_num(v) for v in d[c]] for c in ("mean_of_subject_means", "sem", "ci_low", "ci_high")})
195
+ add(_table(d, ["marker", "n_subjects", "n_trials", "mean_of_subject_means", "sem", "ci_low", "ci_high"],
196
+ ["marker", "subjects", "trials", "mean", "SEM", "95% CI low", "95% CI high"], indent=4).rstrip("\n"))
197
+ for basis, title in (("trials", "Trial-level mixed model"), ("means", "Check on subject means")):
198
+ m = results.models[(results.models["measure"] == measure) & (results.models["basis"] == basis)] if len(results.models) else results.models
199
+ add("")
200
+ if not len(m) or m.iloc[0]["status"] != "fitted":
201
+ add(f" {title}: not fitted (see the notes below).")
202
+ continue
203
+ info = m.iloc[0]
204
+ add(f" {title}: {info['formula']}, random effects: {info['random_effects']}; "
205
+ f"{int(info['n_observations']):,} values from {int(info['n_subjects'])} subjects")
206
+ om = results.omnibus[(results.omnibus["measure"] == measure) & (results.omnibus["basis"] == basis)] if len(results.omnibus) else results.omnibus
207
+ if len(om):
208
+ o = om.iloc[0]
209
+ text = f" Effect of marker: F({int(o['df1'])}, {_num(o['df2'])}) = {_num(o['F'])}, {_peq(o['p_F'])}"
210
+ add(text + f" (Wald chi2({int(o['df1'])}) = {_num(o['chi2'])}, {_peq(o['p_chi2'])})")
211
+ fe = results.fixed_effects[(results.fixed_effects["measure"] == measure) & (results.fixed_effects["basis"] == basis)] if len(results.fixed_effects) else results.fixed_effects
212
+ if int(info["n_markers"]) == 1 and len(fe):
213
+ r = fe.iloc[0]
214
+ if np.isfinite(r["p_t"]):
215
+ add(f" {r['term']} against zero: estimate {_num(r['estimate'])}, 95% CI [{_num(r['ci_low'])}, "
216
+ f"{_num(r['ci_high'])}], t({_num(r['df'])}) = {_num(r['t'])}, {_peq(r['p_t'])}")
217
+ else:
218
+ add(f" {r['term']}: {_num(r['estimate'])}, 95% CI [{_num(r['ci_low'])}, {_num(r['ci_high'])}] "
219
+ "(not tested against zero: there is no null value for this measure)")
220
+ pw = results.pairwise[(results.pairwise["measure"] == measure) & (results.pairwise["basis"] == basis)] if len(results.pairwise) else results.pairwise
221
+ if len(pw):
222
+ add(f" Pairwise comparisons, p adjusted by {CORRECTION_LABELS.get(spec.correction, spec.correction)}"
223
+ f" (significant at {spec.alpha:g}: marked *):")
224
+ shown = pw.assign(pair=pw["marker_a"] + " - " + pw["marker_b"],
225
+ flag=np.where(pw["significant"], "*", ""),
226
+ ci=[f"[{_num(a)}, {_num(b)}]" for a, b in zip(pw["ci_low"], pw["ci_high"])],
227
+ tt=[f"t({_num(df)}) = {_num(t)}" for df, t in zip(pw["df"], pw["t"])],
228
+ p=[_p(v) for v in pw["p_t"]], padj=[_p(v) for v in pw["p_adjusted"]],
229
+ diff=[_num(v) for v in pw["difference"]])
230
+ add(_table(shown, ["pair", "diff", "ci", "tt", "p", "padj", "flag"],
231
+ ["comparison", "difference", "95% CI", "statistic", "p", "p adjusted", ""]).rstrip("\n"))
232
+ var = results.variance[(results.variance["measure"] == measure) & (results.variance["basis"] == basis)] if len(results.variance) else results.variance
233
+ if len(var):
234
+ add(" Variance: " + "; ".join(f"{r['component']} {_num(r['variance'])} ({r['share_of_total']:.0%})"
235
+ for _, r in var.iterrows()))
236
+ add("")
237
+ if results.notes:
238
+ add("NOTES")
239
+ for n in results.notes:
240
+ add(f" [{n['level']}] {n['text']}")
241
+ add("")
242
+ add("METHODS (a starting point to adapt)")
243
+ add(_methods(results))
244
+ return "\n".join(out) + "\n"
245
+
246
+
247
+ def _methods(results):
248
+ spec = results.spec
249
+ sw = results.software
250
+ k = len(spec.markers)
251
+ text = [
252
+ f"Photometry recordings from {len(spec.subjects)} subjects were processed as dF/F (the isosbestic channel "
253
+ f"regressed out of the signal channel by {spec.regression_method.upper()} regression, photobleaching removed with a "
254
+ "double-exponential baseline, low-pass filtered at 5 Hz)"
255
+ + (f" and smoothed with a {spec.smooth_seconds:g} s moving average." if spec.smooth_seconds > 0 else "."),
256
+ f"For every occurrence of each marker ({', '.join(spec.markers)}) a window from {spec.pre:g} s before to "
257
+ f"{spec.post:g} s after the event was taken; events whose window extended beyond the recording were excluded. "
258
+ f"Each trial was baseline-corrected with the mean of {spec.baseline[0]:g} to {spec.baseline[1]:g} s"
259
+ + (" and divided by the baseline SD" if spec.signal == "zscore" else "")
260
+ + " (baseline statistics winsorised at 5 robust SDs).",
261
+ f"In the response window ({spec.response[0]:g} to {spec.response[1]:g} s) the following were computed per trial: "
262
+ + ", ".join(METRIC_LABELS[m] if METRIC_LABELS[m].isupper() else METRIC_LABELS[m].lower() for m in spec.metrics)
263
+ + f" (AUC by the trapezoidal rule; peak = {_DIRECTION_TEXT[spec.peak_direction]}; "
264
+ f"decay time = time from the peak to {spec.decay_fraction:.0%} of it, by linear interpolation).",
265
+ ]
266
+ if k >= 2:
267
+ text.append(
268
+ "Each measure was analysed with a linear mixed-effects model (statsmodels "
269
+ f"{sw.get('statsmodels', '')} MixedLM, restricted maximum likelihood) with marker as a fixed effect and random "
270
+ "intercepts for subject and for subject x marker. Tests use subject-based degrees of freedom (n - 1 for "
271
+ "a contrast between two markers, (k - 1)(n - 1) for the omnibus F test of marker). All pairwise comparisons "
272
+ f"between markers were corrected with {CORRECTION_LABELS.get(spec.correction, spec.correction)} "
273
+ f"(alpha = {spec.alpha:g}). As a check that does not assume independent trials, each analysis was repeated on "
274
+ "subject x marker means with subject as a random effect.")
275
+ else:
276
+ text.append(
277
+ "Each measure was summarised with a linear mixed-effects model with a random intercept for subject "
278
+ f"(statsmodels {sw.get('statsmodels', '')} MixedLM, REML). The AUC and mean amplitude were tested against zero "
279
+ "with t tests on the model's intercept using n - 1 subject-based degrees of freedom; the peak, latency and decay "
280
+ "time have no null value to test against and are reported as estimates with 95% intervals.")
281
+ return "\n".join(" " + line for line in "\n\n".join(text).splitlines())