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.
- PyATCLI/__init__.py +196 -0
- PyATCLI/__main__.py +7 -0
- PyATCLI/_version.py +47 -0
- PyATCLI/analyses.py +640 -0
- PyATCLI/analysis/__init__.py +81 -0
- PyATCLI/analysis/auc.py +79 -0
- PyATCLI/analysis/curve_fit.py +88 -0
- PyATCLI/analysis/event_peth.py +263 -0
- PyATCLI/analysis/fft.py +99 -0
- PyATCLI/analysis/group/__init__.py +318 -0
- PyATCLI/analysis/group/rebuild.py +59 -0
- PyATCLI/analysis/group/report.py +281 -0
- PyATCLI/analysis/group/run.py +164 -0
- PyATCLI/analysis/group/scan.py +92 -0
- PyATCLI/analysis/group/stats.py +451 -0
- PyATCLI/analysis/group/trials.py +188 -0
- PyATCLI/analysis/intervals.py +59 -0
- PyATCLI/analysis/peak_finder.py +155 -0
- PyATCLI/analysis/shared.py +100 -0
- PyATCLI/analysis/zscore_peth.py +107 -0
- PyATCLI/cli/__init__.py +105 -0
- PyATCLI/cli/commands.py +395 -0
- PyATCLI/cli/docs.py +246 -0
- PyATCLI/cli/parser.py +286 -0
- PyATCLI/cli/render.py +130 -0
- PyATCLI/engine/__init__.py +0 -0
- PyATCLI/engine/contract.py +124 -0
- PyATCLI/engine/server.py +169 -0
- PyATCLI/engine/session.py +40 -0
- PyATCLI/engine/store.py +222 -0
- PyATCLI/engine/wire.py +103 -0
- PyATCLI/fieldstudy/__init__.py +1 -0
- PyATCLI/fieldstudy/study.py +440 -0
- PyATCLI/fieldstudy/validation.py +443 -0
- PyATCLI/markers.py +71 -0
- PyATCLI/models.py +102 -0
- PyATCLI/numeric.py +35 -0
- PyATCLI/ops/__init__.py +274 -0
- PyATCLI/ops/analysis.py +136 -0
- PyATCLI/ops/common.py +93 -0
- PyATCLI/ops/compute.py +94 -0
- PyATCLI/ops/fieldstudy.py +52 -0
- PyATCLI/ops/files.py +42 -0
- PyATCLI/ops/group.py +144 -0
- PyATCLI/ops/recording.py +90 -0
- PyATCLI/ops/records.py +63 -0
- PyATCLI/ops/results.py +27 -0
- PyATCLI/ops/saved.py +98 -0
- PyATCLI/ops/system.py +31 -0
- PyATCLI/outputs.py +165 -0
- PyATCLI/progress.py +227 -0
- PyATCLI/provenance.py +336 -0
- PyATCLI/recording.py +602 -0
- PyATCLI/reproduce.py +278 -0
- PyATCLI/results.py +106 -0
- PyATCLI/saved_state.py +275 -0
- PyATCLI/sources/__init__.py +1 -0
- PyATCLI/sources/dataset.py +110 -0
- PyATCLI/sources/load.py +169 -0
- PyATCLI/sources/processing_TDT.py +810 -0
- PyATCLI/sources/processing_oxysoft.py +259 -0
- PyATCLI/sources/pt2.py +46 -0
- PyATCLI/sources/tables.py +306 -0
- PyATCLI/splice.py +196 -0
- PyATCLI/viewplan.py +181 -0
- pyatcli-2026.10.10.dist-info/METADATA +296 -0
- pyatcli-2026.10.10.dist-info/RECORD +71 -0
- pyatcli-2026.10.10.dist-info/WHEEL +5 -0
- pyatcli-2026.10.10.dist-info/entry_points.txt +2 -0
- pyatcli-2026.10.10.dist-info/licenses/LICENSE +661 -0
- pyatcli-2026.10.10.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
"""
|
|
2
|
+
fieldstudy/validation.py
|
|
3
|
+
---------------------------
|
|
4
|
+
Statistical validation for the paired-similarity metric computed by
|
|
5
|
+
study.py: for each field pair, is the same-subject
|
|
6
|
+
similarity meaningfully higher than chance, how big is that effect, is
|
|
7
|
+
it just a word-count artifact, how precise is the estimate, and how
|
|
8
|
+
much does it depend on any one subject?
|
|
9
|
+
|
|
10
|
+
run_validation_pipeline() is the single entry point (load -> embed ->
|
|
11
|
+
compute similarity -> validate, self-contained so it can run as its own
|
|
12
|
+
follow-up analysis without needing anything cached from a prior
|
|
13
|
+
run_field_study_pipeline() call); the stage functions below are also
|
|
14
|
+
exposed separately. Every function's docstring explains what the
|
|
15
|
+
statistic actually means, for interpreting/writing up results — not
|
|
16
|
+
just how to call it.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
from ..progress import Plan
|
|
23
|
+
from .study import load_field_study_folder, embed_text_fields, compute_paired_similarity, permutation_test_similarity
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cohens_d(group1, group2):
|
|
27
|
+
"""
|
|
28
|
+
Cohen's d: how far apart two distributions' means are, in units of
|
|
29
|
+
their pooled standard deviation. Unlike a p-value (which just says
|
|
30
|
+
"probably not the same"), this says how *big* the difference is —
|
|
31
|
+
the conventional rough guide is ~0.2 small, ~0.5 medium, ~0.8 large,
|
|
32
|
+
but those thresholds are a loose convention, not a hard rule.
|
|
33
|
+
|
|
34
|
+
Here: group1 is typically the same-subject similarity values (one
|
|
35
|
+
per subject), group2 the pooled null (chance-pairing) similarity
|
|
36
|
+
values — d tells you how far the "real" pairing sits from chance
|
|
37
|
+
pairing, in a way that doesn't depend on sample size the way a
|
|
38
|
+
p-value does.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
group1, group2 : array-like
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
float
|
|
47
|
+
"""
|
|
48
|
+
group1 = np.asarray(group1, dtype=float)
|
|
49
|
+
group2 = np.asarray(group2, dtype=float)
|
|
50
|
+
n1, n2 = len(group1), len(group2)
|
|
51
|
+
if n1 < 2 or n2 < 2:
|
|
52
|
+
# A standard deviation isn't defined from a single value — not
|
|
53
|
+
# enough subjects/null draws yet for this to mean anything.
|
|
54
|
+
return float("nan")
|
|
55
|
+
var1, var2 = group1.var(ddof=1), group2.var(ddof=1)
|
|
56
|
+
pooled_std = np.sqrt(((n1 - 1) * var1 + (n2 - 1) * var2) / (n1 + n2 - 2))
|
|
57
|
+
if pooled_std == 0:
|
|
58
|
+
return float("nan")
|
|
59
|
+
return float((group1.mean() - group2.mean()) / pooled_std)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def benjamini_hochberg(p_values):
|
|
63
|
+
"""
|
|
64
|
+
Benjamini-Hochberg false discovery rate correction. Running several
|
|
65
|
+
hypothesis tests (here: one permutation test per field pair) inflates
|
|
66
|
+
the chance that at least one comes back "significant" by luck alone —
|
|
67
|
+
this adjusts each p-value upward to control the *expected proportion*
|
|
68
|
+
of false positives among the tests you call significant, which is
|
|
69
|
+
less conservative (more power) than a stricter correction like
|
|
70
|
+
Bonferroni while still accounting for doing multiple tests.
|
|
71
|
+
|
|
72
|
+
The output is often called a "q-value": if you use q < 0.05 as your
|
|
73
|
+
cutoff, you're accepting that on average 5% of the pairs you call
|
|
74
|
+
significant across repeated studies like this one would be false
|
|
75
|
+
positives — not that any individual result has a 5% chance of being
|
|
76
|
+
wrong.
|
|
77
|
+
|
|
78
|
+
Parameters
|
|
79
|
+
----------
|
|
80
|
+
p_values : array-like
|
|
81
|
+
|
|
82
|
+
Returns
|
|
83
|
+
-------
|
|
84
|
+
ndarray
|
|
85
|
+
Corrected p-values (q-values), same order as the input.
|
|
86
|
+
"""
|
|
87
|
+
p_values = np.asarray(p_values, dtype=float)
|
|
88
|
+
n = len(p_values)
|
|
89
|
+
order = np.argsort(p_values)
|
|
90
|
+
ranked = p_values[order]
|
|
91
|
+
corrected = ranked * n / np.arange(1, n + 1)
|
|
92
|
+
# Enforce monotonicity (a lower-ranked p-value's correction can never
|
|
93
|
+
# end up smaller than a higher-ranked one's) via a reverse cumulative
|
|
94
|
+
# minimum — the standard BH step-up procedure.
|
|
95
|
+
corrected = np.minimum.accumulate(corrected[::-1])[::-1]
|
|
96
|
+
corrected = np.clip(corrected, 0, 1)
|
|
97
|
+
out = np.empty(n)
|
|
98
|
+
out[order] = corrected
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def wordcount_controlled_regression(df, field_a, field_b, sim_col):
|
|
103
|
+
"""
|
|
104
|
+
OLS regression: same-subject similarity ~ wordcount_<field_a> +
|
|
105
|
+
wordcount_<field_b>. Tests whether verbosity in either field predicts
|
|
106
|
+
similarity, controlling for the other. If a word-count coefficient
|
|
107
|
+
comes back significant (small p-value), that field's length is
|
|
108
|
+
predicting similarity independent of actual content overlap — a
|
|
109
|
+
"longer answers just look more similar" confound that would weaken a
|
|
110
|
+
claim based on the similarity metric alone. If neither is
|
|
111
|
+
significant, the observed similarity isn't just a length artifact.
|
|
112
|
+
|
|
113
|
+
Requires the `statsmodels` package.
|
|
114
|
+
|
|
115
|
+
Parameters
|
|
116
|
+
----------
|
|
117
|
+
df : pandas.DataFrame
|
|
118
|
+
Must have wordcount_<field_a>, wordcount_<field_b>, and sim_col
|
|
119
|
+
columns (i.e. called on the output of run_field_study_pipeline,
|
|
120
|
+
or with those columns present some other way).
|
|
121
|
+
field_a, field_b : str
|
|
122
|
+
sim_col : str
|
|
123
|
+
The similarity column to use as the outcome, e.g. 'sim_<name>'.
|
|
124
|
+
|
|
125
|
+
Returns
|
|
126
|
+
-------
|
|
127
|
+
dict
|
|
128
|
+
r_squared : float
|
|
129
|
+
Proportion of variance in similarity explained by both word
|
|
130
|
+
counts together — small values mean word count barely
|
|
131
|
+
matters, which is the reassuring result for the confound
|
|
132
|
+
check.
|
|
133
|
+
coef_const, coef_wordcount_<field_a>, coef_wordcount_<field_b> : float
|
|
134
|
+
Regression coefficients (the intercept, and how much
|
|
135
|
+
similarity is predicted to change per additional word in
|
|
136
|
+
each field).
|
|
137
|
+
pvalue_const, pvalue_wordcount_<field_a>, pvalue_wordcount_<field_b> : float
|
|
138
|
+
Whether each coefficient is distinguishable from zero.
|
|
139
|
+
model : statsmodels RegressionResults
|
|
140
|
+
The full fitted model, for anyone who wants more than the
|
|
141
|
+
summary numbers above (e.g. confidence intervals, residual
|
|
142
|
+
diagnostics).
|
|
143
|
+
"""
|
|
144
|
+
import statsmodels.api as sm
|
|
145
|
+
|
|
146
|
+
x = df[[f"wordcount_{field_a}", f"wordcount_{field_b}"]].astype(float)
|
|
147
|
+
x = sm.add_constant(x)
|
|
148
|
+
y = df[sim_col].astype(float)
|
|
149
|
+
|
|
150
|
+
# 3 parameters (intercept + 2 word-count covariates) need at least 3
|
|
151
|
+
# subjects to not be a singular/degenerate fit — with fewer, there's
|
|
152
|
+
# no unique answer, so return NaNs instead of letting statsmodels
|
|
153
|
+
# produce a nonsensical or all-NaN result silently.
|
|
154
|
+
if len(df) < x.shape[1]:
|
|
155
|
+
result = {"r_squared": float("nan"), "model": None}
|
|
156
|
+
for name in x.columns:
|
|
157
|
+
result[f"coef_{name}"] = float("nan")
|
|
158
|
+
result[f"pvalue_{name}"] = float("nan")
|
|
159
|
+
return result
|
|
160
|
+
|
|
161
|
+
model = sm.OLS(y, x).fit()
|
|
162
|
+
|
|
163
|
+
result = {"r_squared": float(model.rsquared), "model": model}
|
|
164
|
+
for name in x.columns:
|
|
165
|
+
result[f"coef_{name}"] = float(model.params[name])
|
|
166
|
+
result[f"pvalue_{name}"] = float(model.pvalues[name])
|
|
167
|
+
return result
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def bootstrap_mean_ci(values, n_boot=1000, ci=0.95, rng_seed=None):
|
|
171
|
+
"""
|
|
172
|
+
Bootstrap confidence interval on the mean: resample the subjects
|
|
173
|
+
(with replacement, same sample size) n_boot times, take the mean
|
|
174
|
+
each time, and report the [lower, upper] percentiles of that
|
|
175
|
+
distribution of means. This doesn't assume the underlying similarity
|
|
176
|
+
values are normally distributed (unlike a textbook mean ± 1.96*SE
|
|
177
|
+
interval) — it just asks "how much would my estimate of the mean
|
|
178
|
+
wobble if I'd happened to sample a slightly different set of
|
|
179
|
+
subjects from the same population."
|
|
180
|
+
|
|
181
|
+
A narrow interval means the estimate is precise (more subjects, or
|
|
182
|
+
less subject-to-subject variability); a wide one means treat the
|
|
183
|
+
point estimate cautiously — you don't have enough subjects yet to
|
|
184
|
+
pin it down tightly.
|
|
185
|
+
|
|
186
|
+
Parameters
|
|
187
|
+
----------
|
|
188
|
+
values : array-like
|
|
189
|
+
Per-subject values (e.g. same-subject similarity for one pair).
|
|
190
|
+
n_boot : int
|
|
191
|
+
Number of resamples.
|
|
192
|
+
ci : float
|
|
193
|
+
Confidence level, e.g. 0.95 for a 95% interval.
|
|
194
|
+
rng_seed : int or None
|
|
195
|
+
|
|
196
|
+
Returns
|
|
197
|
+
-------
|
|
198
|
+
dict
|
|
199
|
+
mean, ci_lower, ci_upper, boot_means (the full resampled-means
|
|
200
|
+
array, for anyone who wants to plot its distribution).
|
|
201
|
+
"""
|
|
202
|
+
values = np.asarray(values, dtype=float)
|
|
203
|
+
rng = np.random.default_rng(rng_seed)
|
|
204
|
+
n = len(values)
|
|
205
|
+
boot_means = np.empty(n_boot)
|
|
206
|
+
for i in range(n_boot):
|
|
207
|
+
boot_means[i] = rng.choice(values, size=n, replace=True).mean()
|
|
208
|
+
|
|
209
|
+
alpha = 1 - ci
|
|
210
|
+
lower = np.percentile(boot_means, 100 * alpha / 2)
|
|
211
|
+
upper = np.percentile(boot_means, 100 * (1 - alpha / 2))
|
|
212
|
+
return {
|
|
213
|
+
"mean": float(values.mean()),
|
|
214
|
+
"ci_lower": float(lower),
|
|
215
|
+
"ci_upper": float(upper),
|
|
216
|
+
"boot_means": boot_means,
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def leave_one_out_sensitivity(values, ids=None):
|
|
221
|
+
"""
|
|
222
|
+
Leave-one-out sensitivity check: recompute the mean with each subject
|
|
223
|
+
dropped, one at a time, and flag any subject whose removal shifts the
|
|
224
|
+
mean by more than one standard deviation of the resulting
|
|
225
|
+
(n_subjects-long) distribution of leave-one-out means.
|
|
226
|
+
|
|
227
|
+
This catches a single unusual subject quietly dominating your
|
|
228
|
+
result — e.g. one participant with an oddly high or low similarity
|
|
229
|
+
score dragging the whole-group mean toward it. A flagged subject
|
|
230
|
+
isn't necessarily wrong or worth excluding — it's worth looking at
|
|
231
|
+
that subject's actual data and deciding, not an automatic exclusion
|
|
232
|
+
rule.
|
|
233
|
+
|
|
234
|
+
Parameters
|
|
235
|
+
----------
|
|
236
|
+
values : array-like
|
|
237
|
+
Per-subject values (e.g. same-subject similarity for one pair).
|
|
238
|
+
ids : array-like or None
|
|
239
|
+
Subject identifiers matching values' order, for readable output.
|
|
240
|
+
Defaults to positional indices if not given.
|
|
241
|
+
|
|
242
|
+
Returns
|
|
243
|
+
-------
|
|
244
|
+
dict
|
|
245
|
+
full_mean : float
|
|
246
|
+
loo_means : ndarray
|
|
247
|
+
The mean with each subject left out, in input order.
|
|
248
|
+
shifts : ndarray
|
|
249
|
+
full_mean minus each loo_means entry — how far removing that
|
|
250
|
+
subject moved the mean.
|
|
251
|
+
threshold : float
|
|
252
|
+
One standard deviation of loo_means — the cutoff used to flag.
|
|
253
|
+
flagged_ids : list
|
|
254
|
+
Subject ids whose |shift| exceeds threshold.
|
|
255
|
+
"""
|
|
256
|
+
values = np.asarray(values, dtype=float)
|
|
257
|
+
n = len(values)
|
|
258
|
+
if ids is None:
|
|
259
|
+
ids = list(range(n))
|
|
260
|
+
else:
|
|
261
|
+
ids = list(ids)
|
|
262
|
+
|
|
263
|
+
full_mean = float(values.mean()) if n > 0 else float("nan")
|
|
264
|
+
if n < 2:
|
|
265
|
+
# Nothing to leave out-and-compare with fewer than 2 subjects —
|
|
266
|
+
# "does removing one subject change the mean" isn't meaningful
|
|
267
|
+
# when there's only one (or zero) to begin with.
|
|
268
|
+
return {
|
|
269
|
+
"full_mean": full_mean,
|
|
270
|
+
"loo_means": np.array([]),
|
|
271
|
+
"shifts": np.array([]),
|
|
272
|
+
"threshold": 0.0,
|
|
273
|
+
"flagged_ids": [],
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
loo_means = np.array([np.delete(values, i).mean() for i in range(n)])
|
|
277
|
+
shifts = full_mean - loo_means
|
|
278
|
+
threshold = float(loo_means.std(ddof=1))
|
|
279
|
+
flagged_mask = np.abs(shifts) > threshold
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
"full_mean": full_mean,
|
|
283
|
+
"loo_means": loo_means,
|
|
284
|
+
"shifts": shifts,
|
|
285
|
+
"threshold": threshold,
|
|
286
|
+
"flagged_ids": [ids[i] for i in range(n) if flagged_mask[i]],
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def build_validation_summary(df, paired_fields, similarity_results, id_field="participant_id", n_boot=1000, rng_seed=None,
|
|
291
|
+
progress=None):
|
|
292
|
+
"""
|
|
293
|
+
Folds every check above into one summary table, one row per field
|
|
294
|
+
pair — see each column's meaning below (and the stage functions'
|
|
295
|
+
own docstrings for the full explanation of each statistic).
|
|
296
|
+
|
|
297
|
+
Parameters
|
|
298
|
+
----------
|
|
299
|
+
df : pandas.DataFrame
|
|
300
|
+
Needs wordcount_<field> columns for every field in paired_fields,
|
|
301
|
+
and id_field if you want subject ids (not positional indices) in
|
|
302
|
+
flagged_participant_ids.
|
|
303
|
+
paired_fields : list of (field_a, field_b, pair_name)
|
|
304
|
+
similarity_results : dict
|
|
305
|
+
As returned by compute_paired_similarity, computed with these
|
|
306
|
+
same paired_fields — reused rather than recomputed here, since
|
|
307
|
+
recomputing similarity means recomputing the (expensive)
|
|
308
|
+
embeddings.
|
|
309
|
+
id_field : str
|
|
310
|
+
n_boot : int
|
|
311
|
+
rng_seed : int or None
|
|
312
|
+
progress : None, True or callable(fraction, message)
|
|
313
|
+
Progress reporting, one tick per pair; see PyATCLI.progress.
|
|
314
|
+
|
|
315
|
+
Returns
|
|
316
|
+
-------
|
|
317
|
+
pandas.DataFrame
|
|
318
|
+
One row per pair:
|
|
319
|
+
- pair, field_a, field_b : which fields this row covers
|
|
320
|
+
- observed_mean_similarity : mean same-subject similarity
|
|
321
|
+
- p_value : permutation-test p-value (is the observed mean
|
|
322
|
+
higher than chance-pairing, one-tailed)
|
|
323
|
+
- p_value_fdr : p_value after Benjamini-Hochberg correction
|
|
324
|
+
across all pairs in this table — use this one, not the raw
|
|
325
|
+
p_value, once you're looking at more than one pair
|
|
326
|
+
- cohens_d : effect size (same-subject similarity vs. the pooled
|
|
327
|
+
chance-pairing null), pooled-std units
|
|
328
|
+
- wc_coef_a/wc_pvalue_a, wc_coef_b/wc_pvalue_b : word-count
|
|
329
|
+
regression coefficient/p-value for field_a's and field_b's
|
|
330
|
+
word count respectively, controlling for each other
|
|
331
|
+
(wordcount_controlled_regression) — a significant coefficient
|
|
332
|
+
here means part of the similarity effect may just be verbosity
|
|
333
|
+
- regression_r_squared : how much of the similarity variance
|
|
334
|
+
both word counts together explain (low = reassuring)
|
|
335
|
+
- ci_lower, ci_upper : bootstrap 95% CI on observed_mean_similarity
|
|
336
|
+
- n_flagged_loo : how many subjects were flagged by the
|
|
337
|
+
leave-one-out check (0 is the reassuring result)
|
|
338
|
+
- flagged_participant_ids : which ones, comma-separated
|
|
339
|
+
"""
|
|
340
|
+
rows = []
|
|
341
|
+
p_values = []
|
|
342
|
+
for field_a, field_b, name in Plan(progress, [("Validating field pairs", 1)]).track(
|
|
343
|
+
"Validating field pairs", paired_fields):
|
|
344
|
+
result = similarity_results[name]
|
|
345
|
+
same = result["same_subject_similarity"]
|
|
346
|
+
null_values = result["null_values"]
|
|
347
|
+
null_shuffle_means = result["null_shuffle_means"]
|
|
348
|
+
|
|
349
|
+
perm = permutation_test_similarity(same, null_shuffle_means)
|
|
350
|
+
d = cohens_d(same, null_values)
|
|
351
|
+
reg = wordcount_controlled_regression(df, field_a, field_b, f"sim_{name}")
|
|
352
|
+
ci = bootstrap_mean_ci(same, n_boot=n_boot, rng_seed=rng_seed)
|
|
353
|
+
ids = df[id_field].tolist() if id_field in df.columns else None
|
|
354
|
+
loo = leave_one_out_sensitivity(same, ids=ids)
|
|
355
|
+
|
|
356
|
+
rows.append({
|
|
357
|
+
"pair": name,
|
|
358
|
+
"field_a": field_a,
|
|
359
|
+
"field_b": field_b,
|
|
360
|
+
"observed_mean_similarity": perm["observed_mean_similarity"],
|
|
361
|
+
"p_value": perm["p_value"],
|
|
362
|
+
"cohens_d": d,
|
|
363
|
+
"wc_coef_a": reg[f"coef_wordcount_{field_a}"],
|
|
364
|
+
"wc_pvalue_a": reg[f"pvalue_wordcount_{field_a}"],
|
|
365
|
+
"wc_coef_b": reg[f"coef_wordcount_{field_b}"],
|
|
366
|
+
"wc_pvalue_b": reg[f"pvalue_wordcount_{field_b}"],
|
|
367
|
+
"regression_r_squared": reg["r_squared"],
|
|
368
|
+
"ci_lower": ci["ci_lower"],
|
|
369
|
+
"ci_upper": ci["ci_upper"],
|
|
370
|
+
"n_flagged_loo": len(loo["flagged_ids"]),
|
|
371
|
+
"flagged_participant_ids": ",".join(str(x) for x in loo["flagged_ids"]),
|
|
372
|
+
})
|
|
373
|
+
p_values.append(perm["p_value"])
|
|
374
|
+
|
|
375
|
+
p_fdr = benjamini_hochberg(np.array(p_values))
|
|
376
|
+
for row, q in zip(rows, p_fdr):
|
|
377
|
+
row["p_value_fdr"] = float(q)
|
|
378
|
+
|
|
379
|
+
return pd.DataFrame(rows)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def run_validation_pipeline(folder_path, text_fields, paired_fields,
|
|
383
|
+
model_name="all-MiniLM-L6-v2", n_null=200,
|
|
384
|
+
n_boot=1000, rng_seed=None, file_glob="P-*.json",
|
|
385
|
+
id_field="participant_id", progress=None):
|
|
386
|
+
"""
|
|
387
|
+
Full validation pipeline: load -> embed -> compute paired similarity
|
|
388
|
+
-> build the validation summary table (see build_validation_summary
|
|
389
|
+
for what each column means). Self-contained — recomputes embeddings
|
|
390
|
+
rather than reusing a prior run_field_study_pipeline() call, so this
|
|
391
|
+
can run as its own follow-up analysis.
|
|
392
|
+
|
|
393
|
+
Parameters
|
|
394
|
+
----------
|
|
395
|
+
folder_path : str
|
|
396
|
+
text_fields : list of str
|
|
397
|
+
Same meaning as in run_field_study_pipeline.
|
|
398
|
+
paired_fields : list of (field_a, field_b, pair_name)
|
|
399
|
+
Which fields to compare. Required here (unlike
|
|
400
|
+
run_field_study_pipeline, where it's optional) — there's nothing
|
|
401
|
+
to validate without at least one pair.
|
|
402
|
+
model_name : str
|
|
403
|
+
n_null : int
|
|
404
|
+
Permutation shuffles for the null distribution.
|
|
405
|
+
n_boot : int
|
|
406
|
+
Bootstrap resamples for the confidence interval.
|
|
407
|
+
rng_seed : int or None
|
|
408
|
+
file_glob : str
|
|
409
|
+
id_field : str
|
|
410
|
+
Column to use as subject identifiers in the leave-one-out flags.
|
|
411
|
+
progress : None, True or callable(fraction, message)
|
|
412
|
+
Progress reporting; see PyATCLI.progress. Loading the
|
|
413
|
+
embedding model (a download the first time) and embedding the
|
|
414
|
+
responses are the longest steps.
|
|
415
|
+
|
|
416
|
+
Returns
|
|
417
|
+
-------
|
|
418
|
+
pandas.DataFrame
|
|
419
|
+
See build_validation_summary.
|
|
420
|
+
"""
|
|
421
|
+
if not paired_fields:
|
|
422
|
+
raise ValueError("paired_fields is required — nothing to validate without at least one pair.")
|
|
423
|
+
|
|
424
|
+
plan = Plan(progress, [("Reading study files", 5), ("Embedding responses", 70),
|
|
425
|
+
("Comparing field pairs", 5), ("Validating field pairs", 20)])
|
|
426
|
+
df = load_field_study_folder(folder_path, text_fields, file_glob=file_glob,
|
|
427
|
+
progress=plan.sub("Reading study files"))
|
|
428
|
+
fields_to_embed = sorted({f for field_a, field_b, _ in paired_fields for f in (field_a, field_b)})
|
|
429
|
+
embeddings = embed_text_fields(df, fields_to_embed, model_name=model_name,
|
|
430
|
+
progress=plan.sub("Embedding responses"))
|
|
431
|
+
similarity_results = compute_paired_similarity(embeddings, paired_fields, n_null=n_null, rng_seed=rng_seed,
|
|
432
|
+
progress=plan.sub("Comparing field pairs"))
|
|
433
|
+
|
|
434
|
+
# build_validation_summary's regression step needs sim_<name> columns
|
|
435
|
+
# on df, same as run_field_study_pipeline adds them.
|
|
436
|
+
for field_a, field_b, name in paired_fields:
|
|
437
|
+
df[f"sim_{name}"] = similarity_results[name]["same_subject_similarity"]
|
|
438
|
+
|
|
439
|
+
return build_validation_summary(
|
|
440
|
+
df, paired_fields, similarity_results,
|
|
441
|
+
id_field=id_field, n_boot=n_boot, rng_seed=rng_seed,
|
|
442
|
+
progress=plan.sub("Validating field pairs"),
|
|
443
|
+
)
|
PyATCLI/markers.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""
|
|
2
|
+
markers.py
|
|
3
|
+
----------
|
|
4
|
+
How an event marker is named and how markers are grouped by name — shared by every analysis that
|
|
5
|
+
works "per event" (Event PETH, the peak finder, group analysis) so they all agree on what a marker is
|
|
6
|
+
called. A marker is a dict with at least a 'time' (seconds) and a 'label'; the ones TDT detected also
|
|
7
|
+
carry 'store' (the epoc store's id, e.g. 'PP1_') and, for onset/offset pairs, 'phase' ('high'/'low') —
|
|
8
|
+
see processing_TDT.get_event_markers.
|
|
9
|
+
|
|
10
|
+
The raw store id stays the internal identifier everywhere; only how it is *shown* can be renamed
|
|
11
|
+
(`store_labels`, {store id: shown name}). Group analysis saves the renames it was run with, because a
|
|
12
|
+
marker name only means something together with them.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
PHASE_SUFFIX = {'high': '¹', 'low': '⁰'} # superscript 1 / 0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def store_display_name(store_id, store_labels=None):
|
|
19
|
+
"""The name shown for a store id — the renamed name if one has been set in `store_labels`,
|
|
20
|
+
otherwise the raw store id unchanged."""
|
|
21
|
+
if store_id is None:
|
|
22
|
+
return store_id
|
|
23
|
+
return (store_labels or {}).get(store_id, store_id)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def marker_display_label(marker, store_labels=None):
|
|
27
|
+
"""Full text to show for a marker: its store's renamed display name, plus a superscript ¹/⁰ if
|
|
28
|
+
it's a high/low phase marker.
|
|
29
|
+
|
|
30
|
+
Only markers with a 'phase' key get the store-name substitution — those are exactly the
|
|
31
|
+
auto-generated onset/offset markers whose label IS the store name by convention (see
|
|
32
|
+
processing_TDT.get_event_markers). Everything else (Note markers, whose label is the actual note
|
|
33
|
+
text like 'Clap' even though they share store == 'Note'; manually-placed markers) keeps its own
|
|
34
|
+
label untouched — renaming a store must not clobber a marker whose label was never derived from
|
|
35
|
+
that store name."""
|
|
36
|
+
if marker.get('phase') is not None:
|
|
37
|
+
label = store_display_name(marker['store'], store_labels)
|
|
38
|
+
else:
|
|
39
|
+
label = marker['label']
|
|
40
|
+
return f"{label}{PHASE_SUFFIX.get(marker.get('phase'), '')}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def group_markers_by_name(cache, store_labels=None):
|
|
44
|
+
"""{display_name: [sorted event times]} across every event TDT actually detected in this
|
|
45
|
+
recording (cache['detected_markers']), plus anything manually placed or already added to the plot
|
|
46
|
+
(cache['markers']) — deduped by (name, time) so a marker that's both detected and already plotted
|
|
47
|
+
doesn't get double-counted. This intentionally does NOT require an event to already be on the
|
|
48
|
+
plot: the whole point is finding out which event types are worth plotting in the first place.
|
|
49
|
+
High/low phase markers count as separate event names (their display label already differs by the
|
|
50
|
+
¹/⁰ suffix).
|
|
51
|
+
|
|
52
|
+
Parameters
|
|
53
|
+
----------
|
|
54
|
+
cache : dict
|
|
55
|
+
A recording as PyAT holds it (see recording.py): only 'detected_markers' (optional) and
|
|
56
|
+
'markers' are read.
|
|
57
|
+
store_labels : dict, optional
|
|
58
|
+
{store id: shown name} renames in effect.
|
|
59
|
+
"""
|
|
60
|
+
groups = {}
|
|
61
|
+
seen = set()
|
|
62
|
+
for m in cache.get('detected_markers', []) + cache['markers']:
|
|
63
|
+
name = marker_display_label(m, store_labels)
|
|
64
|
+
key = (name, m['time'])
|
|
65
|
+
if key in seen:
|
|
66
|
+
continue
|
|
67
|
+
seen.add(key)
|
|
68
|
+
groups.setdefault(name, []).append(m['time'])
|
|
69
|
+
for name in groups:
|
|
70
|
+
groups[name].sort()
|
|
71
|
+
return groups
|
PyATCLI/models.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""
|
|
2
|
+
models.py
|
|
3
|
+
---------
|
|
4
|
+
Parametric model functions for curve fitting via scipy.optimize.curve_fit.
|
|
5
|
+
|
|
6
|
+
Each function follows the signature f(x, *params) -> y so they can be
|
|
7
|
+
passed directly to fit_model_to_segment (analysis/curve_fit.py). CURVE_FIT_MODELS,
|
|
8
|
+
at the bottom, is the registry the app's Curve Fit tool (and scripts) pick from.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def visibility_model(beta, a, v, beta_c, period):
|
|
15
|
+
"""
|
|
16
|
+
Photon-entanglement visibility model.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
beta : array Polarizer angle (degrees or radians)
|
|
21
|
+
a : float Amplitude of the sinusoid
|
|
22
|
+
v : float Visibility (0–1)
|
|
23
|
+
beta_c : float Angular offset / centre
|
|
24
|
+
period : float Period of the oscillation
|
|
25
|
+
|
|
26
|
+
Returns
|
|
27
|
+
-------
|
|
28
|
+
array
|
|
29
|
+
"""
|
|
30
|
+
return (a / 2) * (1 - v * np.sin((beta - beta_c) / period))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def double_exponential_model(x, a, b, c, d, k):
|
|
34
|
+
"""
|
|
35
|
+
Physical model of fluorophore bleaching.
|
|
36
|
+
y = a*exp(-b*x) + c*exp(-d*x) + k
|
|
37
|
+
"""
|
|
38
|
+
return a * np.exp(-b * x) + c * np.exp(-d * x) + k
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def linear_model(x, m, b):
|
|
42
|
+
"""y = mx + b"""
|
|
43
|
+
return m * x + b
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def single_exponential_model(x, a, b, c):
|
|
47
|
+
"""y = a * exp(-b*x) + c"""
|
|
48
|
+
return a * np.exp(-b * x) + c
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def exponential_rise_model(x, a, b, c):
|
|
52
|
+
"""y = a * (1 - exp(-b*x)) + c — rising exponential (e.g. venous occlusion)"""
|
|
53
|
+
return a * (1 - np.exp(-b * x)) + c
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def gaussian_model(x, a, mu, sigma):
|
|
57
|
+
"""y = a * exp(-(x-mu)^2 / (2*sigma^2))"""
|
|
58
|
+
return a * np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def sinusoidal_model(x, a, f, phi, c):
|
|
62
|
+
"""y = a * sin(2*pi*f*x + phi) + c"""
|
|
63
|
+
return a * np.sin(2 * np.pi * f * x + phi) + c
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# Curve-fit registry: "Display Name": (model_fn, p0_fn, [param names]) where
|
|
67
|
+
# model_fn - f(x, *params) -> y
|
|
68
|
+
# p0_fn - f(x_seg, y_seg) -> list of initial guesses
|
|
69
|
+
# param list- human-readable name for every parameter, in order
|
|
70
|
+
# To add a model, add an entry here — the app's Curve Fit dialog and the scripting API both read it.
|
|
71
|
+
CURVE_FIT_MODELS = {
|
|
72
|
+
"Linear (y = mx + b)": (
|
|
73
|
+
linear_model,
|
|
74
|
+
lambda x, y: [(y[-1] - y[0]) / (x[-1] - x[0]) if (x[-1] - x[0]) != 0 else 0, y[0]],
|
|
75
|
+
["m (slope)", "b (intercept)"],
|
|
76
|
+
),
|
|
77
|
+
"Exponential Decay (a*e^(-bx) + c)": (
|
|
78
|
+
single_exponential_model,
|
|
79
|
+
lambda x, y: [y.max() - y.min(), 0.1, y.min()],
|
|
80
|
+
["a (amplitude)", "b (decay rate)", "c (offset)"],
|
|
81
|
+
),
|
|
82
|
+
"Exponential Rise (a*(1-e^(-bx)) + c)": (
|
|
83
|
+
exponential_rise_model,
|
|
84
|
+
lambda x, y: [y.max() - y.min(), 0.1, y.min()],
|
|
85
|
+
["a (amplitude)", "b (rise rate)", "c (offset)"],
|
|
86
|
+
),
|
|
87
|
+
"Gaussian (a*exp(-(x-u)^2/2s^2))": (
|
|
88
|
+
gaussian_model,
|
|
89
|
+
lambda x, y: [y.max(), x[y.argmax()], (x[-1] - x[0]) / 4],
|
|
90
|
+
["a (amplitude)", "u (centre)", "s (width)"],
|
|
91
|
+
),
|
|
92
|
+
"Sinusoidal (a*sin(2*pi*f*x + phi) + c)": (
|
|
93
|
+
sinusoidal_model,
|
|
94
|
+
lambda x, y: [(y.max() - y.min()) / 2, 1.0, 0.0, y.mean()],
|
|
95
|
+
["a (amplitude)", "f (frequency Hz)", "phi (phase)", "c (offset)"],
|
|
96
|
+
),
|
|
97
|
+
"Double Exponential (a*e^(-bx) + c*e^(-dx) + k)": (
|
|
98
|
+
double_exponential_model,
|
|
99
|
+
lambda x, y: [y.max() * 0.6, 0.05, y.max() * 0.4, 0.001, y.min()],
|
|
100
|
+
["a", "b (fast rate)", "c", "d (slow rate)", "k (offset)"],
|
|
101
|
+
),
|
|
102
|
+
}
|
PyATCLI/numeric.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""
|
|
2
|
+
numeric.py
|
|
3
|
+
----------
|
|
4
|
+
The library's one numeric-precision rule: signals, time axes and images are float64, always.
|
|
5
|
+
|
|
6
|
+
Why it is a rule and not a per-function judgement call: TDT hands its streams over as float32, and
|
|
7
|
+
numpy functions are not safe on single-precision data of a realistic length. np.polyfit on a float32
|
|
8
|
+
regressor silently drops the slope term once n * float32-eps exceeds the ratio of the regressor's
|
|
9
|
+
spread to its mean (~200,000 samples, ~3 minutes at 1 kHz, for a channel of 25 +/- 1), returning a line
|
|
10
|
+
at roughly half the true slope with only a RankWarning; sums, means and FFTs lose digits the same way,
|
|
11
|
+
just less visibly. Nothing here relies on a caller remembering to widen first.
|
|
12
|
+
|
|
13
|
+
Where it is enforced
|
|
14
|
+
- Every file load: get_tdt_struct / get_plot_data (TDT), the Oxysoft parser, the generic table
|
|
15
|
+
parser (GenericTable), the .pt2 image parser, and the Dataset container every loader returns.
|
|
16
|
+
Whatever a load hands back is float64, whatever the file stores.
|
|
17
|
+
- Every public function that takes a signal, a time axis or a trial matrix (smoothing, z-scoring,
|
|
18
|
+
FFT, AUC, curve fits, peak finding, PETH, splicing, motion correction, ...), so arrays that did
|
|
19
|
+
not come through a loader — straight from the tdt SDK, or from a script's own pipeline — are
|
|
20
|
+
widened on the way in too.
|
|
21
|
+
|
|
22
|
+
as_float64 is a no-op (returns the same object, no copy) for an array that is already float64, so the
|
|
23
|
+
rule costs nothing on the normal path, and widening float32 to float64 is exact: the values do not change,
|
|
24
|
+
only what is computed from them stops losing precision.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
|
|
29
|
+
FLOAT = np.float64
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def as_float64(a):
|
|
33
|
+
"""`a` as a float64 ndarray: the same object if it already is one (no copy), otherwise a widened
|
|
34
|
+
copy (float32 / float16 / integer arrays, lists, ...). NaN and inf are kept as they are."""
|
|
35
|
+
return np.asarray(a, dtype=np.float64)
|