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,451 @@
1
+ """
2
+ analysis/group/stats.py
3
+ -----------------------
4
+ The statistics of group analysis, on the trial table trials.extract_group_trials builds:
5
+ descriptives, linear mixed-effects models, and pairwise comparisons between markers.
6
+
7
+ For each measure, twice:
8
+
9
+ basis "trials" every trial is a row. Two or more markers: measure ~ marker with a random
10
+ intercept for subject and one for each subject x marker cell (statsmodels
11
+ MixedLM, REML). One marker: measure ~ 1 with a random intercept for subject.
12
+ basis "means" one row per subject x marker (the mean of that cell's trials): measure ~ marker
13
+ with a random intercept for subject, which for a balanced design is the classical
14
+ repeated-measures analysis. It does not rely on trials being independent, so it is
15
+ the check on the first.
16
+
17
+ Why the subject x marker term: trials of one subject and marker share an effect of their own, and
18
+ neighbouring trials share signal when their windows overlap. A model without that term counts every
19
+ trial as independent evidence about a difference between markers. Simulated cohorts (three markers, 40
20
+ trials per subject and marker, 6, 10 and 20 subjects; 18 settings of 300 runs each, with and without a
21
+ subject x marker effect and with trials autocorrelated at 0.8) with no true difference between markers:
22
+ a random-intercept-only model called it significant in 65-93% of runs whenever trials were correlated
23
+ within a cell (4-8% when they were not), at a nominal 5%; the model used here in 1-8% of runs (4.8% on
24
+ average), as did repeated-measures ANOVA on the cell means (5.2%). With true differences (0, 0.5 and 1.0
25
+ residual SDs) and 10 subjects it found them in 95% of runs.
26
+
27
+ p-values. statsmodels gives Wald z tests, which assume many subjects. Alongside them (p_z) every test
28
+ also gets a small-sample version (p_t) that uses degrees of freedom from the subjects, not the trials:
29
+ n - 1 for a contrast between two markers (subjects that have both), like a paired test; n - 1 for a
30
+ mean against zero; and, for the omnibus test of a marker effect, an F with (k - 1, (k - 1)(n - 1)) as in
31
+ repeated-measures ANOVA. For balanced data these equal the paired t-test on the cell means. p_t is what
32
+ the pairwise comparisons are corrected on and what is flagged as significant.
33
+
34
+ One marker: there is nothing to compare it with. AUC and mean amplitude are tested against zero (a
35
+ baseline-corrected trace has mean zero when there is no response). The peak (the extreme of a noisy
36
+ window is never zero without a response), latency and decay time have no zero to test against, so they
37
+ are reported as estimates with 95% intervals only.
38
+ """
39
+
40
+ import itertools
41
+ import math
42
+ import re
43
+ import warnings
44
+ from dataclasses import dataclass, field
45
+
46
+ import numpy as np
47
+ import pandas as pd
48
+ import scipy
49
+ import scipy.stats as st
50
+ import statsmodels
51
+ import statsmodels.formula.api as smf
52
+ from statsmodels.stats.multitest import multipletests
53
+
54
+ from ...progress import Plan
55
+ from . import METRIC_LABELS
56
+
57
+ TESTABLE_AGAINST_ZERO = ("auc", "mean")
58
+
59
+ FRAME_NAMES = ("descriptives", "subject_means", "models", "fixed_effects", "omnibus", "variance",
60
+ "estimated_means", "pairwise", "diagnostics", "random_effects")
61
+
62
+
63
+ @dataclass
64
+ class GroupResults:
65
+ """Everything a group analysis produced. The DataFrames are the tables; `notes` are the things worth
66
+ knowing (dropped markers, boundary fits, undefined measures) as {"level", "measure", "text"}."""
67
+
68
+ spec: object
69
+ trials: pd.DataFrame
70
+ traces: dict = field(default_factory=dict)
71
+ trace_grid: object = None
72
+ excluded: dict = field(default_factory=dict)
73
+ descriptives: pd.DataFrame = None
74
+ subject_means: pd.DataFrame = None
75
+ models: pd.DataFrame = None
76
+ fixed_effects: pd.DataFrame = None
77
+ omnibus: pd.DataFrame = None
78
+ variance: pd.DataFrame = None
79
+ estimated_means: pd.DataFrame = None
80
+ pairwise: pd.DataFrame = None
81
+ diagnostics: pd.DataFrame = None
82
+ random_effects: pd.DataFrame = None
83
+ notes: list = field(default_factory=list)
84
+ software: dict = field(default_factory=dict)
85
+ files: list = field(default_factory=list) # paths written by report.write_group_results
86
+
87
+ def frames(self):
88
+ """{name: DataFrame} of every table, the trial table first."""
89
+ out = {"trials": self.trials}
90
+ for name in FRAME_NAMES:
91
+ out[name] = getattr(self, name)
92
+ return out
93
+
94
+
95
+ # ---- descriptives -------------------------------------------------------------------------------
96
+ def subject_means(trials, measures, markers):
97
+ """Mean of each measure over the valid trials of every subject x marker cell (empty values skipped;
98
+ the decay time, for one, can be empty). Long format: subject, marker, measure, n, mean."""
99
+ valid = trials[trials["valid"].astype(bool)] if len(trials) else trials
100
+ rows = []
101
+ for measure in measures:
102
+ if not len(valid):
103
+ continue
104
+ sub = valid[valid[measure].notna()]
105
+ for (subject, marker), vals in sub.groupby(["subject", "marker"], sort=False)[measure]:
106
+ rows.append((subject, marker, measure, int(len(vals)), float(vals.mean())))
107
+ out = pd.DataFrame(rows, columns=["subject", "marker", "measure", "n", "mean"])
108
+ return _sorted(out, measures, markers)
109
+
110
+
111
+ def _sorted(df, measures=None, markers=None):
112
+ """Rows ordered by measure, marker (both in the order given), then subject; the helper keys are dropped again."""
113
+ if not len(df):
114
+ return df
115
+ out, keys = df.copy(), []
116
+ if measures is not None and "measure" in out:
117
+ out["_m"] = out["measure"].map({m: i for i, m in enumerate(measures)})
118
+ keys.append("_m")
119
+ if markers is not None and "marker" in out:
120
+ out["_k"] = out["marker"].map({m: i for i, m in enumerate(markers)})
121
+ keys.append("_k")
122
+ if "subject" in out:
123
+ out["_s"] = out["subject"].astype(str)
124
+ keys.append("_s")
125
+ return out.sort_values(keys, kind="stable").drop(columns=keys).reset_index(drop=True)
126
+
127
+
128
+ def descriptives(trials, means, measures, markers):
129
+ """Per measure and marker: how many subjects and trials, the mean and spread of the subject means (with the
130
+ standard error and a 95% interval across subjects), and the mean and SD over all trials."""
131
+ rows = []
132
+ valid = trials[trials["valid"].astype(bool)] if len(trials) else trials
133
+ for measure in measures:
134
+ for marker in markers:
135
+ cell = means[(means["measure"] == measure) & (means["marker"] == marker)]
136
+ if not len(cell):
137
+ continue
138
+ vals = cell["mean"].to_numpy(float)
139
+ n = len(vals)
140
+ sd = float(vals.std(ddof=1)) if n > 1 else float("nan")
141
+ sem = sd / math.sqrt(n) if n > 1 else float("nan")
142
+ half = st.t.ppf(0.975, n - 1) * sem if n > 1 else float("nan")
143
+ tr = valid[(valid["marker"] == marker)][measure].dropna().to_numpy(float)
144
+ rows.append({"measure": measure, "marker": marker, "n_subjects": n, "n_trials": int(cell["n"].sum()),
145
+ "mean_of_subject_means": float(vals.mean()), "sd_of_subject_means": sd, "sem": sem,
146
+ "ci_low": float(vals.mean() - half), "ci_high": float(vals.mean() + half),
147
+ "median_of_subject_means": float(np.median(vals)),
148
+ "trial_mean": float(tr.mean()) if len(tr) else float("nan"),
149
+ "trial_sd": float(tr.std(ddof=1)) if len(tr) > 1 else float("nan")})
150
+ return pd.DataFrame(rows)
151
+
152
+
153
+ # ---- one model ----------------------------------------------------------------------------------
154
+ # statsmodels' default optimizers (BFGS, L-BFGS, CG) often stop short of the REML optimum when a variance is
155
+ # near zero: on simulated cohorts they reported non-convergence in up to 62% of fits, and landed at a worse
156
+ # likelihood, which changes the standard errors. Powell's method (derivative-free) converged every time and
157
+ # reached the best likelihood found (300 fits), at about 50 ms a fit. It has no bounds, though, and with an
158
+ # unbalanced design (a subject without one of the markers) it can step onto a singular covariance and raise;
159
+ # the bounded gradient methods are the fallback for that.
160
+ OPTIMIZERS = (["powell", "nm"], ["lbfgs", "bfgs", "cg"])
161
+
162
+
163
+ def _fit_mixed(d, markers, cell_effect):
164
+ """Fit the mixed model to d (columns y, subject, marker). Returns (result, None), or (None, reason) if it could
165
+ not be fitted. statsmodels' own warnings (a variance at the boundary, an optimizer retrying) are swallowed: what
166
+ they mean for the person is reported from the fitted variances instead."""
167
+ k = len(markers)
168
+ kwargs = {"groups": "subject"}
169
+ if k >= 2 and cell_effect:
170
+ kwargs.update(re_formula="1", vc_formula={"cell": "0 + C(marker)"})
171
+ formula = "y ~ 1" if k == 1 else "y ~ C(marker)"
172
+ problem = "the model did not converge"
173
+ for methods in OPTIMIZERS:
174
+ with warnings.catch_warnings(record=True):
175
+ warnings.simplefilter("always")
176
+ try:
177
+ res = smf.mixedlm(formula, d, **kwargs).fit(reml=True, method=methods)
178
+ except Exception as e: # singular matrices, non-finite likelihoods, ...
179
+ problem = f"{type(e).__name__}: {e}"
180
+ continue
181
+ se = np.sqrt(np.diag(res.cov_params().loc[res.fe_params.index, res.fe_params.index].to_numpy(float)))
182
+ if not res.converged or not np.all(np.isfinite(se)) or not np.all(np.isfinite(res.fe_params.to_numpy(float))):
183
+ problem = "the model did not converge"
184
+ continue
185
+ return res, None
186
+ return None, problem
187
+
188
+
189
+ def _contrast(res, row_a, row_b=None):
190
+ """Estimate and standard error of a linear combination of the fixed effects (row_a, or row_a - row_b)."""
191
+ beta = res.fe_params.to_numpy(float)
192
+ cov = res.cov_params().loc[res.fe_params.index, res.fe_params.index].to_numpy(float)
193
+ L = np.asarray(row_a, float) - (np.asarray(row_b, float) if row_b is not None else 0.0)
194
+ return float(L @ beta), float(math.sqrt(max(L @ cov @ L, 0.0)))
195
+
196
+
197
+ def _tests(est, se, df):
198
+ """z and t statistics with their two-sided p-values and the 95% interval from t (df may be NaN)."""
199
+ z = est / se if se > 0 else (0.0 if est == 0 else math.copysign(math.inf, est))
200
+ p_z = float(2 * st.norm.sf(abs(z)))
201
+ if df is None or not np.isfinite(df) or df < 1:
202
+ return {"z": z, "p_z": p_z, "df": float("nan"), "t": float("nan"), "p_t": float("nan"),
203
+ "ci_low": float("nan"), "ci_high": float("nan")}
204
+ p_t = float(2 * st.t.sf(abs(z), df))
205
+ half = st.t.ppf(0.975, df) * se
206
+ return {"z": z, "p_z": p_z, "df": float(df), "t": z, "p_t": p_t, "ci_low": est - half, "ci_high": est + half}
207
+
208
+
209
+ def _design_rows(res, markers):
210
+ """
211
+ The fixed-effects design row for each marker, aligned with res.fe_params. Built directly from the
212
+ treatment-coded `C(marker)[T.<level>]` column names rather than re-deriving them through the formula
213
+ engine's own design-matrix machinery (statsmodels' formula backend switched from patsy to formulaic in
214
+ 0.15, which dropped the patsy-specific `design_info` this used to read; the `C(marker)[T....]` naming
215
+ convention itself is unchanged across both).
216
+ """
217
+ if len(markers) == 1:
218
+ return {markers[0]: np.ones(1)}
219
+ names = list(res.fe_params.index)
220
+ col_for_marker = {}
221
+ for name in names:
222
+ match = re.fullmatch(r"C\(marker\)\[T\.(.*)\]", name)
223
+ if match:
224
+ col_for_marker[match.group(1)] = name
225
+ rows = {}
226
+ for m in markers:
227
+ row = np.zeros(len(names))
228
+ row[names.index("Intercept")] = 1.0
229
+ col = col_for_marker.get(m)
230
+ if col is not None:
231
+ row[names.index(col)] = 1.0
232
+ rows[m] = row
233
+ return rows
234
+
235
+
236
+ def _variances(res, k, cell_effect):
237
+ out = [("subject", float(res.cov_re.iloc[0, 0]))]
238
+ if k >= 2 and cell_effect:
239
+ out.append(("subject x marker", float(np.atleast_1d(res.vcomp)[0])))
240
+ out.append(("residual", float(res.scale)))
241
+ return out
242
+
243
+
244
+ def analyse_measure(d, measure, markers, basis, correction="holm", alpha=0.05):
245
+ """
246
+ One measure on one basis. `d` has columns y, subject, marker (markers not in `markers`, and NaN, already gone).
247
+ Returns a dict of small DataFrames (fixed_effects, omnibus, variance, estimated_means, pairwise, diagnostics,
248
+ random_effects), a `model` dict describing the fit, and `notes`; or model["status"] != "fitted" when it could
249
+ not be fitted, with the reason in notes.
250
+ """
251
+ label = METRIC_LABELS.get(measure, measure)
252
+ notes = []
253
+ empty = {"fixed_effects": [], "omnibus": [], "variance": [], "estimated_means": [], "pairwise": [],
254
+ "diagnostics": pd.DataFrame(), "random_effects": []}
255
+
256
+ def failed(text, level="warning"):
257
+ notes.append({"level": level, "measure": measure, "text": f"{label} ({basis}): {text}"})
258
+ return {**empty, "model": {"measure": measure, "basis": basis, "status": "not fitted"}, "notes": notes}
259
+
260
+ counts = d.groupby("marker", observed=True)["subject"].nunique()
261
+ kept = [m for m in markers if counts.get(m, 0) >= 2]
262
+ for m in markers:
263
+ if m not in kept:
264
+ notes.append({"level": "warning", "measure": measure,
265
+ "text": f"{label} ({basis}): '{m}' has values for fewer than 2 subjects and was left out."})
266
+ if not kept:
267
+ return failed("no marker has values for two or more subjects.")
268
+ d = d[d["marker"].isin(kept)].copy()
269
+ d["marker"] = pd.Categorical(d["marker"], categories=kept)
270
+ d["subject"] = d["subject"].astype(str)
271
+ if d["y"].nunique() < 2:
272
+ return failed("every value is identical, so there is nothing to model.")
273
+ k = len(kept)
274
+ n_subjects = int(d["subject"].nunique())
275
+ cell_effect = basis == "trials"
276
+
277
+ res, problem = _fit_mixed(d, kept, cell_effect)
278
+ if res is None:
279
+ return failed(problem + ("; the subject-means analysis does not depend on it." if basis == "trials" else "."))
280
+
281
+ rows = _design_rows(res, kept)
282
+ per_subject = {m: set(d.loc[d["marker"] == m, "subject"]) for m in kept}
283
+ variances = _variances(res, k, cell_effect)
284
+ total_var = sum(v for _, v in variances)
285
+ total_sd = math.sqrt(total_var)
286
+ at_zero = [name for name, v in variances if name != "residual" and v <= 1e-6 * total_var]
287
+ if at_zero:
288
+ notes.append({"level": "info", "measure": measure,
289
+ "text": f"{label} ({basis}): the {' and '.join(at_zero)} variance was estimated at zero (the data show "
290
+ "none beyond the residual), so the model reduces to a simpler one."})
291
+
292
+ fixed, omnibus, emm, pair = [], [], [], []
293
+ tested = k >= 2 or measure in TESTABLE_AGAINST_ZERO
294
+ if k == 1:
295
+ est, se = _contrast(res, rows[kept[0]])
296
+ df = n_subjects - 1
297
+ t = _tests(est, se, df)
298
+ if not tested:
299
+ t.update(z=float("nan"), p_z=float("nan"), t=float("nan"), p_t=float("nan"))
300
+ fixed.append({"term": f"mean of '{kept[0]}'" + ("" if tested else " (estimate only)"), "estimate": est, "se": se, **t})
301
+ emm.append({"marker": kept[0], "mean": est, "se": se, "df": t["df"], "ci_low": t["ci_low"], "ci_high": t["ci_high"]})
302
+ else:
303
+ ref = kept[0]
304
+ names = [f"mean of '{ref}'"] + [f"'{m}' minus '{ref}'" for m in kept[1:]]
305
+ beta_rows = [rows[ref]] + [rows[m] - rows[ref] for m in kept[1:]]
306
+ for name, L, m in zip(names, beta_rows, [ref] + kept[1:]):
307
+ est, se = _contrast(res, L)
308
+ n_pair = len(per_subject[ref]) if m == ref else len(per_subject[ref] & per_subject[m])
309
+ fixed.append({"term": name, "estimate": est, "se": se, **_tests(est, se, n_pair - 1)})
310
+ for m in kept:
311
+ est, se = _contrast(res, rows[m])
312
+ t = _tests(est, se, len(per_subject[m]) - 1)
313
+ emm.append({"marker": m, "mean": est, "se": se, "df": t["df"], "ci_low": t["ci_low"], "ci_high": t["ci_high"]})
314
+
315
+ # Wald test that every marker coefficient is zero (the Intercept is the first fixed effect).
316
+ beta = res.fe_params.to_numpy(float)[1:]
317
+ cov = res.cov_params().loc[res.fe_params.index, res.fe_params.index].to_numpy(float)[1:, 1:]
318
+ chi2 = float(beta @ np.linalg.solve(cov, beta))
319
+ complete = set.intersection(*per_subject.values())
320
+ df2 = (k - 1) * (len(complete) - 1) if len(complete) >= 2 else float("nan")
321
+ omnibus.append({"test": "effect of marker", "chi2": chi2, "df1": k - 1, "p_chi2": float(st.chi2.sf(chi2, k - 1)),
322
+ "F": chi2 / (k - 1), "df2": df2,
323
+ "p_F": float(st.f.sf(chi2 / (k - 1), k - 1, df2)) if np.isfinite(df2) else float("nan"),
324
+ "n_subjects_with_all_markers": len(complete)})
325
+
326
+ for a, b in itertools.combinations(kept, 2):
327
+ est, se = _contrast(res, rows[a], rows[b])
328
+ n_pair = len(per_subject[a] & per_subject[b])
329
+ t = _tests(est, se, n_pair - 1)
330
+ pair.append({"marker_a": a, "marker_b": b, "difference": est, "se": se, **t,
331
+ "std_difference": est / total_sd if total_sd > 0 else float("nan"),
332
+ "n_subjects_with_both": n_pair})
333
+ if pair:
334
+ p = np.array([r["p_t"] for r in pair], float)
335
+ adj = np.full(len(p), np.nan)
336
+ ok = np.isfinite(p)
337
+ if ok.any():
338
+ adj[ok] = multipletests(p[ok], alpha=alpha, method=correction)[1]
339
+ for r, a_ in zip(pair, adj):
340
+ r["p_adjusted"] = float(a_)
341
+ r["significant"] = bool(a_ < alpha) if np.isfinite(a_) else False
342
+
343
+ var_rows = [{"component": name, "variance": v, "sd": math.sqrt(v),
344
+ "share_of_total": v / sum(x for _, x in variances) if sum(x for _, x in variances) > 0 else float("nan")}
345
+ for name, v in variances]
346
+ resid = pd.DataFrame({"subject": d["subject"].to_numpy(), "marker": d["marker"].astype(str).to_numpy(),
347
+ "observed": d["y"].to_numpy(float), "fitted": np.asarray(res.fittedvalues, float),
348
+ "resid": np.asarray(res.resid, float)}) if basis == "trials" else pd.DataFrame()
349
+ blups = [{"subject": str(s), "effect": float(np.asarray(v, float).ravel()[0])} for s, v in res.random_effects.items()]
350
+ model = {"measure": measure, "basis": basis, "status": "fitted",
351
+ "formula": "measure ~ 1" if k == 1 else "measure ~ marker",
352
+ "random_effects": "subject" + (" + subject x marker" if k >= 2 and cell_effect else ""),
353
+ "n_observations": int(len(d)), "n_subjects": n_subjects, "n_markers": k, "markers": "; ".join(kept),
354
+ "tested_against_zero": bool(k == 1 and tested), "converged": bool(res.converged)}
355
+ return {"model": model, "fixed_effects": fixed, "omnibus": omnibus, "variance": var_rows,
356
+ "estimated_means": emm, "pairwise": pair, "diagnostics": resid, "random_effects": blups, "notes": notes}
357
+
358
+
359
+ # ---- the whole analysis -------------------------------------------------------------------------
360
+ def fit_group_models(trials, spec, progress=None, traces=None, trace_grid=None, excluded=None):
361
+ """
362
+ Descriptives, mixed models and pairwise comparisons for every measure in spec.metrics, on both bases.
363
+
364
+ Parameters
365
+ ----------
366
+ trials : DataFrame
367
+ The trial table (trials.TRIAL_COLUMNS), all subjects together.
368
+ spec : GroupSpec
369
+ Uses markers, metrics, correction and alpha.
370
+ progress : None, True or callable(fraction, message)
371
+ Progress reporting (see PyATCLI.progress), one step per measure.
372
+ traces, trace_grid, excluded
373
+ Carried into the result unchanged (mean traces per subject and marker, their time axis, and the
374
+ events left out for not having a full window) for the plots and the report.
375
+
376
+ Returns
377
+ -------
378
+ GroupResults
379
+ """
380
+ markers = list(spec.markers)
381
+ measures = list(spec.metrics)
382
+ means = subject_means(trials, measures, markers)
383
+ plan = Plan(progress, [(m, 1) for m in measures])
384
+ notes, models, fixed, omni, var, emm, pair, diag, blup = [], [], [], [], [], [], [], [], []
385
+ valid = trials[trials["valid"].astype(bool)] if len(trials) else trials
386
+
387
+ for measure in measures:
388
+ plan.begin(measure, f"Fitting models: {METRIC_LABELS.get(measure, measure)}")
389
+ n_missing = int(valid[measure].isna().sum()) if len(valid) else 0
390
+ if n_missing:
391
+ notes.append({"level": "info", "measure": measure,
392
+ "text": f"{METRIC_LABELS.get(measure, measure)}: {n_missing} of {len(valid)} valid trials have "
393
+ "no value (the trace never fell to the decay level, or there was no peak to fall from) "
394
+ "and are left out of its models."})
395
+ for basis in ("trials", "means"):
396
+ if basis == "trials":
397
+ d = valid[valid[measure].notna() & valid["marker"].isin(markers)][["subject", "marker", measure]] if len(valid) else pd.DataFrame(columns=["subject", "marker", "y"])
398
+ d = d.rename(columns={measure: "y"}).reset_index(drop=True)
399
+ else:
400
+ cell = means[means["measure"] == measure]
401
+ d = cell.rename(columns={"mean": "y"})[["subject", "marker", "y"]].reset_index(drop=True)
402
+ out = analyse_measure(d, measure, markers, basis, spec.correction, spec.alpha)
403
+ notes.extend(out["notes"])
404
+ models.append(out["model"])
405
+ for store, key in ((fixed, "fixed_effects"), (omni, "omnibus"), (var, "variance"), (emm, "estimated_means"),
406
+ (pair, "pairwise"), (blup, "random_effects")):
407
+ store.extend({"measure": measure, "basis": basis, **r} for r in out[key])
408
+ if len(out["diagnostics"]):
409
+ diag.append(out["diagnostics"].assign(measure=measure))
410
+ plan.done()
411
+ for measure in measures:
412
+ label = METRIC_LABELS.get(measure, measure)
413
+ p = {}
414
+ for r in omni:
415
+ if r["measure"] == measure and np.isfinite(r["p_F"]):
416
+ p[r["basis"]] = r["p_F"]
417
+ if not p: # one marker: the test against zero instead
418
+ for r in fixed:
419
+ if r["measure"] == measure and np.isfinite(r["p_t"]):
420
+ p[r["basis"]] = r["p_t"]
421
+ if len(p) == 2 and (p["trials"] < spec.alpha) != (p["means"] < spec.alpha):
422
+ notes.append({"level": "warning", "measure": measure,
423
+ "text": f"{label}: the trial-level model (p = {p['trials']:.3g}) and the check on subject means "
424
+ f"(p = {p['means']:.3g}) fall on different sides of {spec.alpha:g}. Trials from one subject "
425
+ "are not independent evidence and subjects are what the tests count, so look at the "
426
+ "subject means (subject_means.csv); the more cautious of the two is the safer one to report."})
427
+ if len(trials) and len(valid) < len(trials):
428
+ notes.append({"level": "warning", "measure": "",
429
+ "text": f"{len(trials) - len(valid)} of {len(trials)} trials could not be measured and are left out "
430
+ "(see the 'reason' column of the trial table)."})
431
+
432
+ def frame(rows, cols=None):
433
+ df = pd.DataFrame(rows)
434
+ return df[[c for c in cols if c in df.columns] + [c for c in df.columns if c not in cols]] if cols and len(df) else df
435
+
436
+ results = GroupResults(
437
+ spec=spec, trials=trials, traces=traces or {}, trace_grid=trace_grid, excluded=excluded or {},
438
+ descriptives=descriptives(trials, means, measures, markers), subject_means=means,
439
+ models=frame(models, ["measure", "basis", "status"]),
440
+ fixed_effects=frame(fixed, ["measure", "basis", "term"]),
441
+ omnibus=frame(omni, ["measure", "basis", "test"]),
442
+ variance=frame(var, ["measure", "basis", "component"]),
443
+ estimated_means=frame(emm, ["measure", "basis", "marker"]),
444
+ pairwise=frame(pair, ["measure", "basis", "marker_a", "marker_b"]),
445
+ diagnostics=pd.concat(diag, ignore_index=True) if diag else pd.DataFrame(),
446
+ random_effects=frame(blup, ["measure", "basis", "subject"]),
447
+ notes=notes,
448
+ software={"statsmodels": statsmodels.__version__, "scipy": scipy.__version__,
449
+ "numpy": np.__version__, "pandas": pd.__version__},
450
+ )
451
+ return results
@@ -0,0 +1,188 @@
1
+ """
2
+ analysis/group/trials.py
3
+ ------------------------
4
+ Trials for group analysis: the window around every event of a marker, baseline-corrected
5
+ and reduced to the five measures (what each one is: see __init__.py). It works on plain
6
+ arrays (the time axis, the dF/F, and the event times of each marker), so it does not care
7
+ how a recording was loaded.
8
+
9
+ A trial is *usable* if its whole window, [event - pre, event + post], lies inside the
10
+ recording. Every usable trial becomes one row, in time order; a trial that cannot be
11
+ measured (a flat baseline for the z-score, non-finite samples, an empty window) stays in
12
+ the table with valid = False and the reason, so nothing disappears silently.
13
+ """
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ from ...numeric import as_float64
19
+ from ..auc import compute_auc_from_trace
20
+ from ..shared import estimate_sample_rate, smooth_signal
21
+ from ..zscore_peth import _baseline_mean_std
22
+
23
+ MEASURE_COLUMNS = ("auc", "peak", "mean", "latency", "decay")
24
+ TRIAL_COLUMNS = ["group", "subject", "recording", "marker", "trial", "event_time", "valid", "reason",
25
+ *MEASURE_COLUMNS, "baseline_mean", "baseline_sd", "n_samples", "overlap"]
26
+ TRACE_STEP = 0.04 # seconds between points of the mean traces (the dF/F is low-passed at 5 Hz, far below this rate)
27
+
28
+
29
+ def decay_time(t, y, peak_index, fraction):
30
+ """
31
+ Seconds from the peak until the trace has fallen to `fraction` of the peak, measured by linear
32
+ interpolation between the two samples either side of the crossing. NaN if the trace never falls that
33
+ far after the peak, or if there is no peak to fall from (a peak of exactly zero).
34
+
35
+ A positive peak has fallen when the trace is at or below fraction * peak; a negative peak (a dip)
36
+ when it is at or above it, i.e. when it has climbed back that far.
37
+
38
+ Parameters
39
+ ----------
40
+ t, y : arrays
41
+ Time (seconds from the event) and the baseline-corrected trace, the whole trial.
42
+ peak_index : int
43
+ Index of the peak in t / y.
44
+ fraction : float
45
+ Between 0 and 1 (0.5 = half-decay time).
46
+ """
47
+ peak = y[peak_index]
48
+ if not np.isfinite(peak) or peak == 0:
49
+ return float("nan")
50
+ target = fraction * peak
51
+ tail = y[peak_index:]
52
+ hits = np.flatnonzero(tail <= target if peak > 0 else tail >= target)
53
+ if hits.size == 0:
54
+ return float("nan")
55
+ j = int(hits[0]) # >= 1: the peak itself is beyond the target for any fraction below 1
56
+ t0, t1 = t[peak_index + j - 1], t[peak_index + j]
57
+ y0, y1 = tail[j - 1], tail[j]
58
+ frac = (target - y0) / (y1 - y0) if y1 != y0 else 1.0
59
+ return float(t0 + frac * (t1 - t0) - t[peak_index])
60
+
61
+
62
+ def measures_for_trial(rel_t, y, spec):
63
+ """
64
+ The five measures of one baseline-corrected trial.
65
+
66
+ Parameters
67
+ ----------
68
+ rel_t : array
69
+ Time in seconds relative to the event.
70
+ y : array
71
+ The baseline-corrected trace (dF/F minus the baseline mean, or the z-score, per spec.signal).
72
+ spec : GroupSpec
73
+ Uses response, peak_direction and decay_fraction.
74
+
75
+ Returns
76
+ -------
77
+ dict with auc, peak, mean, latency, decay — or None if the response window holds fewer than 2 samples.
78
+ """
79
+ r0, r1 = spec.response
80
+ idx = np.flatnonzero((rel_t >= r0) & (rel_t <= r1))
81
+ if idx.size < 2:
82
+ return None
83
+ rt, ry = rel_t[idx], y[idx]
84
+ if spec.peak_direction == "positive":
85
+ k = int(np.argmax(ry))
86
+ elif spec.peak_direction == "negative":
87
+ k = int(np.argmin(ry))
88
+ else:
89
+ k = int(np.argmax(np.abs(ry)))
90
+ return {
91
+ "auc": float(compute_auc_from_trace(rt, ry)["total_auc"]),
92
+ "peak": float(ry[k]),
93
+ "mean": float(ry.mean()),
94
+ "latency": float(rt[k]),
95
+ "decay": decay_time(rel_t, y, int(idx[k]), spec.decay_fraction),
96
+ }
97
+
98
+
99
+ def extract_group_trials(x, y, events, spec, subject, recording="", trace_step=TRACE_STEP):
100
+ """
101
+ Slice one recording into trials and measure each.
102
+
103
+ Parameters
104
+ ----------
105
+ x : array
106
+ Time axis of the recording in seconds (uniformly sampled; need not start at 0).
107
+ y : array
108
+ The dF/F, same length as x. Smoothed here with spec.smooth_seconds (0 = not at all).
109
+ events : dict {marker name: sequence of event times}
110
+ Only the markers in spec.markers are used; one with no events gives no trials.
111
+ spec : GroupSpec
112
+ Uses group_name, markers, pre, post, baseline, response, signal, smooth_seconds,
113
+ peak_direction and decay_fraction.
114
+ subject, recording : str
115
+ Filled into every row.
116
+ trace_step : float
117
+ Spacing in seconds of the mean traces returned alongside.
118
+
119
+ Returns
120
+ -------
121
+ dict with
122
+ trials : DataFrame with TRIAL_COLUMNS, one row per usable trial ordered by marker (as in
123
+ spec.markers) then time. `trial` counts within the marker; `overlap` is True when the
124
+ window shares samples with the neighbouring trial's (events less than pre + post apart).
125
+ traces : {marker: {"n": valid trials, "mean": mean baseline-corrected trace on `grid`}}
126
+ grid : the common time axis of the traces, -pre to +post
127
+ excluded : {marker: events whose window is not fully inside the recording}
128
+ """
129
+ x = as_float64(x)
130
+ y = as_float64(y)
131
+ fs = estimate_sample_rate(x)
132
+ ys = smooth_signal(y, fs, spec.smooth_seconds) if spec.smooth_seconds > 0 else y
133
+ pre, post = spec.pre, spec.post
134
+ b0, b1 = spec.baseline
135
+ grid = np.arange(-pre, post + trace_step / 2, trace_step)
136
+
137
+ rows, traces, excluded = [], {}, {}
138
+ for marker in spec.markers:
139
+ times = np.sort(np.asarray(events.get(marker, []), dtype=float))
140
+ inside = (times - pre >= x[0]) & (times + post <= x[-1])
141
+ usable = times[inside]
142
+ excluded[marker] = int(len(times) - len(usable))
143
+
144
+ overlap = np.zeros(len(usable), dtype=bool)
145
+ if len(usable) > 1:
146
+ close = np.diff(usable) < pre + post
147
+ overlap[:-1] |= close
148
+ overlap[1:] |= close
149
+
150
+ total, n_valid = np.zeros(len(grid)), 0
151
+ for number, t in enumerate(usable, start=1):
152
+ i0 = int(np.searchsorted(x, t - pre, side="left"))
153
+ i1 = int(np.searchsorted(x, t + post, side="right"))
154
+ rel, seg = x[i0:i1] - t, ys[i0:i1]
155
+ row = {"group": spec.group_name, "subject": subject, "recording": recording, "marker": marker,
156
+ "trial": number, "event_time": float(t), "valid": False, "reason": "",
157
+ "baseline_mean": np.nan, "baseline_sd": np.nan, "n_samples": int(len(seg)),
158
+ "overlap": bool(overlap[number - 1]), **{c: np.nan for c in MEASURE_COLUMNS}}
159
+ base = seg[(rel >= b0) & (rel <= b1)]
160
+ if base.size == 0:
161
+ row["reason"] = "no samples in the baseline window"
162
+ elif not np.isfinite(seg).all():
163
+ row["reason"] = "non-finite samples in the window"
164
+ else:
165
+ mu, sd = _baseline_mean_std(base)
166
+ row["baseline_mean"], row["baseline_sd"] = float(mu), float(sd)
167
+ corrected = None
168
+ if spec.signal == "zscore":
169
+ if sd == 0 or sd <= 1e-12 * np.max(np.abs(base)):
170
+ row["reason"] = "flat baseline (no spread to z-score by)"
171
+ else:
172
+ corrected = (seg - mu) / sd
173
+ else:
174
+ corrected = seg - mu
175
+ if corrected is not None:
176
+ measured = measures_for_trial(rel, corrected, spec)
177
+ if measured is None:
178
+ row["reason"] = "fewer than 2 samples in the response window"
179
+ else:
180
+ row.update(measured)
181
+ row["valid"] = True
182
+ total += np.interp(grid, rel, corrected)
183
+ n_valid += 1
184
+ rows.append(row)
185
+ traces[marker] = {"n": n_valid, "mean": total / n_valid if n_valid else np.full(len(grid), np.nan)}
186
+
187
+ trials = pd.DataFrame(rows, columns=TRIAL_COLUMNS)
188
+ return {"trials": trials, "traces": traces, "grid": grid, "excluded": excluded}