mindmap-synaptome 0.1.0__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 (64) hide show
  1. mindmap_synaptome-0.1.0.dist-info/METADATA +95 -0
  2. mindmap_synaptome-0.1.0.dist-info/RECORD +64 -0
  3. mindmap_synaptome-0.1.0.dist-info/WHEEL +4 -0
  4. mindmap_synaptome-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. synaptome/__init__.py +34 -0
  6. synaptome/_utils.py +126 -0
  7. synaptome/datasets/__init__.py +35 -0
  8. synaptome/datasets/toy.py +983 -0
  9. synaptome/engine/__init__.py +99 -0
  10. synaptome/engine/bootstrap.py +461 -0
  11. synaptome/engine/cluster.py +261 -0
  12. synaptome/engine/correction.py +77 -0
  13. synaptome/engine/effect_sizes.py +368 -0
  14. synaptome/engine/ess.py +67 -0
  15. synaptome/engine/hypothesis.py +485 -0
  16. synaptome/engine/intervals.py +271 -0
  17. synaptome/estimates/__init__.py +10 -0
  18. synaptome/estimates/registry.py +329 -0
  19. synaptome/estimates/requirements.py +119 -0
  20. synaptome/estimates/run.py +412 -0
  21. synaptome/hypotheses/__init__.py +9 -0
  22. synaptome/hypotheses/registry.py +280 -0
  23. synaptome/hypotheses/run.py +559 -0
  24. synaptome/io/__init__.py +8 -0
  25. synaptome/io/_atomic.py +43 -0
  26. synaptome/io/syn.py +416 -0
  27. synaptome/plot/__init__.py +11 -0
  28. synaptome/plot/_data.py +499 -0
  29. synaptome/plot/_draw.py +604 -0
  30. synaptome/plot/accessor.py +932 -0
  31. synaptome/plot/figure.py +66 -0
  32. synaptome/plot/results.py +1051 -0
  33. synaptome/plot/style.py +113 -0
  34. synaptome/py.typed +0 -0
  35. synaptome/questions/__init__.py +25 -0
  36. synaptome/questions/base.py +484 -0
  37. synaptome/questions/compare.py +80 -0
  38. synaptome/questions/compare_along.py +43 -0
  39. synaptome/questions/design.py +137 -0
  40. synaptome/questions/distribution.py +39 -0
  41. synaptome/questions/fingerprint.py +65 -0
  42. synaptome/questions/resolve.py +468 -0
  43. synaptome/results/__init__.py +27 -0
  44. synaptome/results/base.py +396 -0
  45. synaptome/results/cluster.py +170 -0
  46. synaptome/results/correct.py +73 -0
  47. synaptome/results/describe.py +110 -0
  48. synaptome/results/estimate.py +149 -0
  49. synaptome/results/format.py +537 -0
  50. synaptome/results/normality.py +37 -0
  51. synaptome/results/omnibus.py +37 -0
  52. synaptome/results/pairwise.py +159 -0
  53. synaptome/results/run.py +54 -0
  54. synaptome/results/tested.py +72 -0
  55. synaptome/results/timing.py +51 -0
  56. synaptome/study/__init__.py +38 -0
  57. synaptome/study/attachments.py +176 -0
  58. synaptome/study/info.py +169 -0
  59. synaptome/study/protocol.py +368 -0
  60. synaptome/study/reduce.py +213 -0
  61. synaptome/study/study.py +991 -0
  62. synaptome/study/units.py +516 -0
  63. synaptome/study/values.py +117 -0
  64. synaptome/study/variables.py +717 -0
@@ -0,0 +1,983 @@
1
+ """
2
+ Toy studies with planted effects, one per study type of DESIGN.md section 13.
3
+
4
+ Every generator returns a new, fully defined `Study` (no definition is inferred) built from a seeded
5
+ random generator: the same arguments always give the same study. Each plants at least one real effect
6
+ and one null effect, listed in its docstring and stored in `study.info.extra["planted"]`, so tests and
7
+ tutorials can read the truth from the study instead of hard-coding it.
8
+
9
+ A planted entry is a plain dict, shaped like the question that would recover it:
10
+
11
+ - `outcome`, `by`: the variable compared and the factor it is compared across;
12
+ - `contrast`: `[a, b]`, the effect being `a - b`;
13
+ - `statistic`: what `value` measures (`"mean_diff"`: difference of the group means, after `reduce`);
14
+ - `value`: the true value (0.0 for a null effect), or a list with one value per coordinate of `along`;
15
+ - optional: `subset`, `reduce`, `unit`, `along` + `coordinates`, `n` (units with both groups), `note`.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Mapping, Sequence
21
+ from typing import Any
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+
26
+ from ..study import Dim, Study
27
+
28
+ __all__ = [
29
+ "case_control",
30
+ "crossed",
31
+ "crossover",
32
+ "longitudinal",
33
+ "method_comparison",
34
+ "repeated_trials",
35
+ "simulation_benchmark",
36
+ "timepoint_pairing",
37
+ ]
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Helpers.
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def _check_int(name: str, value: Any, minimum: int) -> int:
46
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < minimum:
47
+ raise ValueError(f"`{name}` must be an integer of at least {minimum}, got {value!r}.")
48
+ return int(value)
49
+
50
+
51
+ def _check_float(name: str, value: Any, low: float | None = None, high: float | None = None) -> float:
52
+ if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
53
+ raise ValueError(f"`{name}` must be a number, got {value!r}.")
54
+ value = float(value)
55
+ if not np.isfinite(value) or (low is not None and value < low) or (high is not None and value > high):
56
+ bounds = f"in [{low}, {high}]" if low is not None and high is not None else f"at least {low}"
57
+ raise ValueError(f"`{name}` must be a finite number {bounds}, got {value!r}.")
58
+ return value
59
+
60
+
61
+ def _ids(prefix: str, n: int) -> list[str]:
62
+ width = max(2, len(str(n)))
63
+ return [f"{prefix}{i:0{width}d}" for i in range(1, n + 1)]
64
+
65
+
66
+ def _planted(
67
+ outcome: str,
68
+ by: str,
69
+ contrast: Sequence[str],
70
+ value: float | Sequence[float],
71
+ statistic: str = "mean_diff",
72
+ **optional: Any,
73
+ ) -> dict:
74
+ entry: dict[str, Any] = {
75
+ "outcome": outcome,
76
+ "by": by,
77
+ "contrast": list(contrast),
78
+ "statistic": statistic,
79
+ "value": [float(v) for v in value] if isinstance(value, (list, tuple, np.ndarray)) else float(value),
80
+ }
81
+ entry.update({k: v for k, v in optional.items() if v is not None})
82
+ return entry
83
+
84
+
85
+ def _study(title: str, description: str, generator: str, parameters: Mapping, planted: list[dict]) -> Study:
86
+ study = Study(title, description=description, keywords=["toy study", "synthetic"], status="completed")
87
+ study.info.extra = {
88
+ "generator": {"name": f"synaptome.datasets.{generator}", "parameters": dict(parameters)},
89
+ "planted": planted,
90
+ }
91
+ return study
92
+
93
+
94
+ def _grid(**axes: Sequence) -> pd.DataFrame:
95
+ """Every combination of the given coordinates, as a long table."""
96
+ index = pd.MultiIndex.from_product(list(axes.values()), names=list(axes))
97
+ return index.to_frame(index=False)
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Generators.
102
+ # ---------------------------------------------------------------------------
103
+
104
+
105
+ def case_control(n_per_group: int = 30, effect: float = 10.0, seed: int = 0) -> Study:
106
+ """
107
+ Case-control study: patients and controls, one score each. `compare("score", by="group")` is an
108
+ independent-samples comparison.
109
+
110
+ Units: `subject` (`2 * n_per_group`). Variables at `subject`: `group` (control / patient), `age`
111
+ (years), `sex` (F / M), `score` (points, SD 10 within each group).
112
+
113
+ Planted:
114
+
115
+ - `score`, patient - control: mean difference `effect` (default 10 points, Cohen's d = 1);
116
+ - `age`, patient - control: 0 (null).
117
+
118
+ Parameters
119
+ ----------
120
+ n_per_group: int, optional
121
+ Subjects per group (at least 2).
122
+
123
+ effect: float, optional
124
+ Patients' mean score minus controls'.
125
+
126
+ seed: int, optional
127
+
128
+ Returns
129
+ -------
130
+ Study
131
+ """
132
+ n = _check_int("n_per_group", n_per_group, 2)
133
+ effect = _check_float("effect", effect)
134
+ rng = np.random.default_rng(seed)
135
+
136
+ group = np.repeat(["control", "patient"], n)
137
+ subjects = pd.DataFrame(
138
+ {
139
+ "subject": _ids("s", 2 * n),
140
+ "group": group,
141
+ "age": rng.integers(25, 66, size=2 * n),
142
+ "sex": rng.choice(["F", "M"], size=2 * n),
143
+ }
144
+ )
145
+ score = 50.0 + effect * (group == "patient") + rng.normal(0.0, 10.0, size=2 * n)
146
+
147
+ study = _study(
148
+ "Toy case-control study",
149
+ "Patients and controls with one score each; patients score higher.",
150
+ "case_control",
151
+ {"n_per_group": n, "effect": effect, "seed": seed},
152
+ [
153
+ _planted("score", "group", ["patient", "control"], effect),
154
+ _planted("age", "group", ["patient", "control"], 0.0),
155
+ ],
156
+ )
157
+ v = study.variables
158
+ study.units.add_level("subject", description="Participant")
159
+ v.define("group", "subject", "category", categories=("control", "patient"), scale="nominal")
160
+ v.define("age", "subject", "int", scale="ratio", measurement_unit="years", range=(18, 100))
161
+ v.define("sex", "subject", "category", categories=("F", "M"), scale="nominal")
162
+ v.define(
163
+ "score",
164
+ "subject",
165
+ scale="interval",
166
+ measurement_unit="points",
167
+ description="Symptom score",
168
+ origin="raw",
169
+ )
170
+ study.add_units("subject", subjects)
171
+ study.add("score", pd.DataFrame({"subject": subjects["subject"], "score": score}))
172
+ return study
173
+
174
+
175
+ def crossover(n_subjects: int = 24, effect: float = 5.0, seed: int = 0) -> Study:
176
+ """
177
+ Crossover trial: every subject is measured under placebo and drug. `condition` is a dimension, so
178
+ `compare("score", by="condition")` is paired. Subjects differ much more from each other (SD 15) than
179
+ their two measurements do (SD 3 each), so pairing matters: an independent comparison would miss the
180
+ effect.
181
+
182
+ Units: `subject`. Variables: `sequence` (AB / BA, balanced) at `subject`; `score` (points) and
183
+ `heart_rate` (bpm), both with dimension `condition` (placebo, drug).
184
+
185
+ Planted:
186
+
187
+ - `score`, drug - placebo: mean difference `effect` (default 5 points; d_z about 1.2);
188
+ - `heart_rate`, drug - placebo: 0 (null).
189
+
190
+ Parameters
191
+ ----------
192
+ n_subjects: int, optional
193
+ At least 2.
194
+
195
+ effect: float, optional
196
+
197
+ seed: int, optional
198
+
199
+ Returns
200
+ -------
201
+ Study
202
+ """
203
+ n = _check_int("n_subjects", n_subjects, 2)
204
+ effect = _check_float("effect", effect)
205
+ rng = np.random.default_rng(seed)
206
+
207
+ ids = _ids("s", n)
208
+ conditions = ["placebo", "drug"]
209
+ long = _grid(subject=ids, condition=conditions)
210
+ drug = (long["condition"] == "drug").to_numpy()
211
+ subject_score = np.repeat(rng.normal(100.0, 15.0, size=n), 2)
212
+ subject_rate = np.repeat(rng.normal(70.0, 8.0, size=n), 2)
213
+ long["score"] = subject_score + effect * drug + rng.normal(0.0, 3.0, size=2 * n)
214
+ long["heart_rate"] = subject_rate + rng.normal(0.0, 4.0, size=2 * n)
215
+
216
+ study = _study(
217
+ "Toy crossover trial",
218
+ "Every subject is measured under placebo and drug; the drug raises the score.",
219
+ "crossover",
220
+ {"n_subjects": n, "effect": effect, "seed": seed},
221
+ [
222
+ _planted("score", "condition", ["drug", "placebo"], effect),
223
+ _planted("heart_rate", "condition", ["drug", "placebo"], 0.0),
224
+ ],
225
+ )
226
+ v = study.variables
227
+ study.units.add_level("subject", description="Participant")
228
+ v.define(
229
+ "sequence",
230
+ "subject",
231
+ "category",
232
+ categories=("AB", "BA"),
233
+ scale="nominal",
234
+ kind="manipulated",
235
+ description="Order of the conditions",
236
+ )
237
+ condition = Dim("condition", description="Treatment period")
238
+ v.define("score", "subject", dims=[condition], scale="interval", measurement_unit="points")
239
+ v.define("heart_rate", "subject", dims=[condition], scale="ratio", measurement_unit="bpm")
240
+ study.add_units("subject", pd.DataFrame({"subject": ids, "sequence": np.resize(["AB", "BA"], n)}))
241
+ study.add("score", long[["subject", "condition", "score"]])
242
+ study.add("heart_rate", long[["subject", "condition", "heart_rate"]])
243
+ return study
244
+
245
+
246
+ def longitudinal(
247
+ n_per_group: int = 15,
248
+ n_visits: int = 7,
249
+ slope: float = -1.0,
250
+ onset: float = 4.0,
251
+ missing: float = 0.1,
252
+ seed: int = 0,
253
+ ) -> Study:
254
+ """
255
+ Longitudinal study, two groups: body weight at visits every 2 weeks. Treated subjects start losing
256
+ weight after week `onset`; controls stay stable. Some visits are missing, so subjects have different
257
+ weeks (ragged). Curves: `compare_along("weight", by="group", along="week")`; slopes:
258
+ `compare("weight", by="group", reduce={"week": "slope"})`. Both are independent comparisons.
259
+
260
+ Units: `subject`. Variables: `group` (control / treated) at `subject`; `weight` (kg) with dimension
261
+ `week` (0, 2, ..., `2 * (n_visits - 1)`). Baseline weight SD 5 kg, visit noise SD 1 kg.
262
+
263
+ Planted:
264
+
265
+ - `weight`, treated - control, along `week`: `slope * max(week - onset, 0)` (default: 0 until week 4,
266
+ then -2 kg per visit);
267
+ - `weight` reduced to its slope over weeks, treated - control: the least-squares slope of that curve
268
+ over the full visit schedule (default -0.857 kg/week);
269
+ - `weight` at week 0, treated - control: 0 (null).
270
+
271
+ Parameters
272
+ ----------
273
+ n_per_group: int, optional
274
+ At least 2.
275
+
276
+ n_visits: int, optional
277
+ Visits per subject, every 2 weeks from week 0 (at least 2).
278
+
279
+ slope: float, optional
280
+ Weekly weight change of the treated group after `onset` (kg/week).
281
+
282
+ onset: float, optional
283
+ Week the treatment effect starts.
284
+
285
+ missing: float, optional
286
+ Probability that a visit after week 0 is missing.
287
+
288
+ seed: int, optional
289
+
290
+ Returns
291
+ -------
292
+ Study
293
+ """
294
+ n = _check_int("n_per_group", n_per_group, 2)
295
+ n_visits = _check_int("n_visits", n_visits, 2)
296
+ slope = _check_float("slope", slope)
297
+ onset = _check_float("onset", onset, 0.0)
298
+ missing = _check_float("missing", missing, 0.0, 0.9)
299
+ rng = np.random.default_rng(seed)
300
+
301
+ ids = _ids("s", 2 * n)
302
+ group = np.repeat(["control", "treated"], n)
303
+ weeks = np.arange(n_visits) * 2
304
+ effect_curve = slope * np.maximum(weeks - onset, 0.0) + 0.0 # + 0.0 turns -0.0 into 0.0
305
+ slope_effect = float(np.polyfit(weeks, effect_curve, 1)[0])
306
+
307
+ long = _grid(subject=ids, week=weeks)
308
+ treated = np.repeat(group == "treated", n_visits)
309
+ week = long["week"].to_numpy()
310
+ baseline = np.repeat(rng.normal(80.0, 5.0, size=2 * n), n_visits)
311
+ own_slope = np.repeat(rng.normal(0.0, 0.1, size=2 * n), n_visits)
312
+ long["weight"] = (
313
+ baseline
314
+ + own_slope * week
315
+ + treated * slope * np.maximum(week - onset, 0.0)
316
+ + rng.normal(0.0, 1.0, size=len(long))
317
+ )
318
+ keep = (week == 0) | (rng.random(len(long)) >= missing)
319
+ long = long[keep]
320
+
321
+ study = _study(
322
+ "Toy longitudinal study",
323
+ "Two groups weighed every 2 weeks; the treated group loses weight after the first weeks.",
324
+ "longitudinal",
325
+ {
326
+ "n_per_group": n,
327
+ "n_visits": n_visits,
328
+ "slope": slope,
329
+ "onset": onset,
330
+ "missing": missing,
331
+ "seed": seed,
332
+ },
333
+ [
334
+ _planted(
335
+ "weight",
336
+ "group",
337
+ ["treated", "control"],
338
+ effect_curve,
339
+ along="week",
340
+ coordinates=[int(w) for w in weeks],
341
+ ),
342
+ _planted("weight", "group", ["treated", "control"], slope_effect, reduce={"week": "slope"}),
343
+ _planted("weight", "group", ["treated", "control"], 0.0, subset={"week": 0}),
344
+ ],
345
+ )
346
+ v = study.variables
347
+ study.units.add_level("subject", description="Participant")
348
+ v.define("group", "subject", "category", categories=("control", "treated"), scale="nominal")
349
+ v.define(
350
+ "weight",
351
+ "subject",
352
+ dims=[Dim("week", measurement_unit="week", description="Weeks since inclusion")],
353
+ scale="ratio",
354
+ measurement_unit="kg",
355
+ range=(20, 300),
356
+ )
357
+ study.add_units("subject", pd.DataFrame({"subject": ids, "group": group}))
358
+ study.add("weight", long)
359
+ return study
360
+
361
+
362
+ def simulation_benchmark(
363
+ n_regions: int = 12,
364
+ n_runs: int = 5,
365
+ snrs: Sequence[float] = (0, 5, 10, 20),
366
+ n_boot: int = 100,
367
+ effect: float = 0.03,
368
+ seed: int = 0,
369
+ ) -> Study:
370
+ """
371
+ Simulation benchmark: three methods (`wcset`, `a`, `b`) recover sources in several brain regions, with
372
+ repeated simulation runs per region, at several noise levels. Runs are repetitions (a unit level), so
373
+ `compare("accuracy", by="method", reduce={"run": "mean"}, subset={"snr": 10})` is paired across
374
+ regions. Each run's accuracy also comes with upstream bootstrap draws (`accuracy_boot`).
375
+
376
+ Units: `region > run`. Variables at `run`: `accuracy` (proportion correct) with dimensions `method`
377
+ and `snr` (dB); `accuracy_boot`, its bootstrap draws (`replicates_of="accuracy"`, extra dimension
378
+ `draw` of kind `"replicate"`), as if each run's 200 test items were resampled.
379
+
380
+ Planted (after averaging runs, at every SNR):
381
+
382
+ - `accuracy`, wcset - a: mean difference `effect` (default 0.03);
383
+ - `accuracy`, wcset - b: 0 (null).
384
+
385
+ Parameters
386
+ ----------
387
+ n_regions: int, optional
388
+ At least 2.
389
+
390
+ n_runs: int, optional
391
+ Runs per region (at least 1).
392
+
393
+ snrs: sequence of float, optional
394
+ Signal-to-noise ratios (dB), at least one. Accuracy rises with SNR, from 0.5 to 0.8 for `a`.
395
+
396
+ n_boot: int, optional
397
+ Bootstrap draws per run, method and SNR (at least 2).
398
+
399
+ effect: float, optional
400
+ How much more accurate `wcset` is than `a`.
401
+
402
+ seed: int, optional
403
+
404
+ Returns
405
+ -------
406
+ Study
407
+ """
408
+ n_regions = _check_int("n_regions", n_regions, 2)
409
+ n_runs = _check_int("n_runs", n_runs, 1)
410
+ n_boot = _check_int("n_boot", n_boot, 2)
411
+ effect = _check_float("effect", effect, -0.2, 0.2)
412
+ snrs = [float(s) for s in snrs]
413
+ if not snrs or len(set(snrs)) != len(snrs) or not all(np.isfinite(snrs)):
414
+ raise ValueError(f"`snrs` must be distinct finite numbers, at least one; got {snrs}.")
415
+ rng = np.random.default_rng(seed)
416
+ methods = ["wcset", "a", "b"]
417
+ n_items = 200
418
+
419
+ regions = _ids("r", n_regions)
420
+ runs = _ids("run", n_runs)
421
+ long = _grid(region=regions, run=runs, method=methods, snr=snrs)
422
+ snr = long["snr"].to_numpy()
423
+ snr_span = max(snrs) - min(snrs) or 1.0
424
+ base = 0.5 + 0.3 * (snr - min(snrs)) / snr_span # 0.5 to 0.8: far enough from 1 to not clip
425
+ region_index = long["region"].map({r: i for i, r in enumerate(regions)}).to_numpy()
426
+ method_index = long["method"].map({m: i for i, m in enumerate(methods)}).to_numpy()
427
+ difficulty = rng.normal(0.0, 0.05, size=n_regions)[region_index]
428
+ region_method = rng.normal(0.0, 0.01, size=(n_regions, len(methods)))[region_index, method_index]
429
+ shift = np.where(long["method"].to_numpy() == "a", 0.0, effect)
430
+ accuracy = base + difficulty + region_method + shift + rng.normal(0.0, 0.02, size=len(long))
431
+ long["accuracy"] = np.clip(accuracy, 0.0, 1.0)
432
+
433
+ draws = rng.binomial(n_items, long["accuracy"].to_numpy()[:, None], size=(len(long), n_boot)) / n_items
434
+ boot = long.loc[long.index.repeat(n_boot), ["region", "run", "method", "snr"]].reset_index(drop=True)
435
+ boot["draw"] = np.tile(np.arange(n_boot), len(long))
436
+ boot["accuracy_boot"] = draws.ravel()
437
+
438
+ study = _study(
439
+ "Toy simulation benchmark",
440
+ "Three source-recovery methods over brain regions, repeated runs and noise levels.",
441
+ "simulation_benchmark",
442
+ {
443
+ "n_regions": n_regions,
444
+ "n_runs": n_runs,
445
+ "snrs": snrs,
446
+ "n_boot": n_boot,
447
+ "effect": effect,
448
+ "seed": seed,
449
+ },
450
+ [
451
+ _planted("accuracy", "method", ["wcset", "a"], effect, reduce={"run": "mean"}, subset={"snr": s})
452
+ for s in snrs
453
+ ]
454
+ + [
455
+ _planted("accuracy", "method", ["wcset", "b"], 0.0, reduce={"run": "mean"}, subset={"snr": s})
456
+ for s in snrs
457
+ ],
458
+ )
459
+ study.units.add_level("region", description="Simulated source region")
460
+ study.units.add_level("run", parents="region", description="Simulation run (repetition)")
461
+ dims = [Dim("method"), Dim("snr", measurement_unit="dB", description="Signal-to-noise ratio")]
462
+ v = study.variables
463
+ v.define("accuracy", "run", dims=dims, scale="ratio", measurement_unit="proportion", range=(0, 1))
464
+ v.define(
465
+ "accuracy_boot",
466
+ "run",
467
+ dims=[*dims, Dim("draw", kind="replicate", description="Bootstrap draw over test items")],
468
+ scale="ratio",
469
+ measurement_unit="proportion",
470
+ range=(0, 1),
471
+ replicates_of="accuracy",
472
+ )
473
+ study.add_units("region", regions)
474
+ study.add_units("run", long[["region", "run"]].drop_duplicates())
475
+ study.add("accuracy", long)
476
+ study.add("accuracy_boot", boot)
477
+ return study
478
+
479
+
480
+ def timepoint_pairing(
481
+ n_subjects: int = 3,
482
+ n_times: int = 500,
483
+ effect: float = 0.05,
484
+ rho: float = 0.9,
485
+ seed: int = 0,
486
+ ) -> Study:
487
+ """
488
+ Timepoint pairing within one recording: two methods track a signal over time, scored by their
489
+ correlation with the truth at every time sample. Within one subject, the time samples are the paired
490
+ observations (`compare("correlation", by="method", subset={"subject": "s01"}, unit="time")`). The
491
+ noise is autocorrelated (AR(1), coefficient `rho`), so consecutive samples are not independent and
492
+ the effective sample size is far below `n_times`.
493
+
494
+ Units: `subject`. Variable: `correlation` with dimensions `method` (standard, improved, matched) and
495
+ `time` (s, sampled at 100 Hz).
496
+
497
+ Planted, in every subject:
498
+
499
+ - `correlation`, improved - standard, paired on time: mean difference `effect` (default 0.05);
500
+ - `correlation`, matched - standard, paired on time: 0 (null);
501
+ - serial correlation `rho` of each method's noise (noted in the entries);
502
+ - `correlation`, improved - standard, over subjects after averaging time: `effect` (few subjects).
503
+
504
+ Parameters
505
+ ----------
506
+ n_subjects: int, optional
507
+ At least 1.
508
+
509
+ n_times: int, optional
510
+ Time samples (at least 10).
511
+
512
+ effect: float, optional
513
+
514
+ rho: float, optional
515
+ AR(1) coefficient of the noise, in [0, 0.99].
516
+
517
+ seed: int, optional
518
+
519
+ Returns
520
+ -------
521
+ Study
522
+ """
523
+ n = _check_int("n_subjects", n_subjects, 1)
524
+ n_times = _check_int("n_times", n_times, 10)
525
+ effect = _check_float("effect", effect, -0.5, 0.5)
526
+ rho = _check_float("rho", rho, 0.0, 0.99)
527
+ rng = np.random.default_rng(seed)
528
+
529
+ ids = _ids("s", n)
530
+ methods = ["standard", "improved", "matched"]
531
+ times = np.round(np.arange(n_times) / 100.0, 2)
532
+ innovations = rng.normal(0.0, 0.05 * np.sqrt(1 - rho**2), size=(n, len(methods), n_times))
533
+ noise = np.empty_like(innovations)
534
+ noise[..., 0] = innovations[..., 0] / np.sqrt(1 - rho**2)
535
+ for t in range(1, n_times):
536
+ noise[..., t] = rho * noise[..., t - 1] + innovations[..., t]
537
+ phase = rng.uniform(0, 2 * np.pi, size=(n, 1, 1))
538
+ level = 0.6 + 0.1 * np.sin(2 * np.pi * 0.2 * times[None, None, :] + phase)
539
+ values = level + np.array([0.0, effect, 0.0])[None, :, None] + noise
540
+ long = _grid(subject=ids, method=methods, time=times)
541
+ long["correlation"] = np.clip(values, -1.0, 1.0).ravel()
542
+
543
+ planted = [
544
+ _planted(
545
+ "correlation",
546
+ "method",
547
+ [other, "standard"],
548
+ value,
549
+ subset={"subject": s},
550
+ unit="time",
551
+ note=f"noise is AR(1) with coefficient {rho}",
552
+ )
553
+ for s in ids
554
+ for other, value in (("improved", effect), ("matched", 0.0))
555
+ ]
556
+ planted.append(
557
+ _planted("correlation", "method", ["improved", "standard"], effect, reduce={"time": "mean"})
558
+ )
559
+ study = _study(
560
+ "Toy timepoint pairing",
561
+ "Three methods scored at every time sample of one recording per subject; autocorrelated noise.",
562
+ "timepoint_pairing",
563
+ {"n_subjects": n, "n_times": n_times, "effect": effect, "rho": rho, "seed": seed},
564
+ planted,
565
+ )
566
+ study.units.add_level("subject", description="Recording")
567
+ study.variables.define(
568
+ "correlation",
569
+ "subject",
570
+ dims=[Dim("method"), Dim("time", measurement_unit="s")],
571
+ scale="interval",
572
+ range=(-1, 1),
573
+ description="Correlation of the estimate with the true signal",
574
+ )
575
+ study.add_units("subject", ids)
576
+ study.add("correlation", long)
577
+ return study
578
+
579
+
580
+ def repeated_trials(
581
+ n_per_group: int = 12,
582
+ n_trials: int = 30,
583
+ effect: float = 3.0,
584
+ seed: int = 0,
585
+ ) -> Study:
586
+ """
587
+ Repeated trials (an ERP study): two groups, many trials per subject, a voltage curve per trial. Trials
588
+ are repetitions (a unit level) to average: `compare_along("erp", by="group", along="time",
589
+ reduce={"trial": "mean"})` compares the evoked responses of independent groups.
590
+
591
+ Units: `subject > trial`. Variables: `group` (control / patient) at `subject`; `erp` (µV) at `trial`
592
+ with dimension `time` (ms, -100 to 500 every 10 ms). Every subject shows a component peaking at
593
+ 300 ms (amplitude 5 µV, SD 1 µV across subjects); single trials add white noise (SD 5 µV).
594
+
595
+ Planted:
596
+
597
+ - `erp`, patient - control, along `time`: `effect * exp(-(time - 300)² / (2 * 50²))` µV (default peak
598
+ 3 µV; above half of it between 241 and 359 ms);
599
+ - `erp` averaged over the pre-stimulus window (time < 0), patient - control: 0 (null).
600
+
601
+ Parameters
602
+ ----------
603
+ n_per_group: int, optional
604
+ Subjects per group (at least 2).
605
+
606
+ n_trials: int, optional
607
+ Trials per subject (at least 1).
608
+
609
+ effect: float, optional
610
+ Extra component amplitude of patients (µV).
611
+
612
+ seed: int, optional
613
+
614
+ Returns
615
+ -------
616
+ Study
617
+ """
618
+ n = _check_int("n_per_group", n_per_group, 2)
619
+ n_trials = _check_int("n_trials", n_trials, 1)
620
+ effect = _check_float("effect", effect)
621
+ rng = np.random.default_rng(seed)
622
+
623
+ ids = _ids("s", 2 * n)
624
+ group = np.repeat(["control", "patient"], n)
625
+ times = np.arange(-100, 501, 10)
626
+ shape = np.exp(-((times - 300.0) ** 2) / (2 * 50.0**2))
627
+ amplitude = 5.0 + effect * (group == "patient") + rng.normal(0.0, 1.0, size=2 * n)
628
+ erp = amplitude[:, None, None] * shape[None, None, :] + rng.normal(
629
+ 0.0, 5.0, size=(2 * n, n_trials, len(times))
630
+ )
631
+ long = _grid(subject=ids, trial=range(1, n_trials + 1), time=times)
632
+ long["erp"] = erp.ravel()
633
+
634
+ study = _study(
635
+ "Toy ERP study",
636
+ "Two groups, many trials per subject; patients have a larger component around 300 ms.",
637
+ "repeated_trials",
638
+ {"n_per_group": n, "n_trials": n_trials, "effect": effect, "seed": seed},
639
+ [
640
+ _planted(
641
+ "erp",
642
+ "group",
643
+ ["patient", "control"],
644
+ effect * shape,
645
+ reduce={"trial": "mean"},
646
+ along="time",
647
+ coordinates=[int(t) for t in times],
648
+ ),
649
+ _planted(
650
+ "erp",
651
+ "group",
652
+ ["patient", "control"],
653
+ 0.0,
654
+ subset={"time": [int(t) for t in times if t < 0]},
655
+ reduce={"time": "mean", "trial": "mean"},
656
+ ),
657
+ ],
658
+ )
659
+ study.units.add_level("subject", description="Participant")
660
+ study.units.add_level("trial", parents="subject", description="Stimulus presentation")
661
+ v = study.variables
662
+ v.define("group", "subject", "category", categories=("control", "patient"), scale="nominal")
663
+ v.define(
664
+ "erp",
665
+ "trial",
666
+ dims=[Dim("time", measurement_unit="ms", description="Time from stimulus onset")],
667
+ scale="interval",
668
+ measurement_unit="µV",
669
+ description="Event-related potential at one electrode",
670
+ )
671
+ study.add_units("subject", pd.DataFrame({"subject": ids, "group": group}))
672
+ study.add_units("trial", long[["subject", "trial"]].drop_duplicates())
673
+ study.add("erp", long)
674
+ return study
675
+
676
+
677
+ def crossed(
678
+ n_subjects: int = 20,
679
+ n_stimuli: int = 16,
680
+ n_repeats: int = 2,
681
+ effect: float = 30.0,
682
+ seed: int = 0,
683
+ ) -> Study:
684
+ """
685
+ Crossed subjects x stimuli: every subject sees every stimulus `n_repeats` times; half the stimuli are
686
+ incongruent. A trial belongs to one subject *and* one stimulus (`trial < subject * stimulus`), and the
687
+ condition lives on the stimulus. `compare("rt", by="condition", reduce={"trial": "mean"},
688
+ unit="subject")` is paired across subjects.
689
+
690
+ Units: `subject`, `stimulus`, `trial < subject * stimulus`. Variables: `condition` (congruent /
691
+ incongruent) at `stimulus`; `rt` (ms) and `correct` (bool) at `trial`. Response times: 500 ms, SD 50
692
+ across subjects, SD 20 across stimuli, SD 80 across trials. Stimuli are a sample too: with 16 of
693
+ them, the observed effect varies around `effect` with the stimuli drawn (SD about 10 ms), a variance
694
+ that a by-subject comparison does not see.
695
+
696
+ Planted (trials averaged per subject and condition):
697
+
698
+ - `rt`, incongruent - congruent: mean difference `effect` (default 30 ms);
699
+ - `correct`, incongruent - congruent: 0 (null; 95% correct in both).
700
+
701
+ Parameters
702
+ ----------
703
+ n_subjects: int, optional
704
+ At least 2.
705
+
706
+ n_stimuli: int, optional
707
+ Even, at least 2 (half per condition).
708
+
709
+ n_repeats: int, optional
710
+ Presentations of each stimulus to each subject (at least 1).
711
+
712
+ effect: float, optional
713
+ Slowing on incongruent stimuli (ms).
714
+
715
+ seed: int, optional
716
+
717
+ Returns
718
+ -------
719
+ Study
720
+ """
721
+ n_subjects = _check_int("n_subjects", n_subjects, 2)
722
+ n_stimuli = _check_int("n_stimuli", n_stimuli, 2)
723
+ if n_stimuli % 2:
724
+ raise ValueError(f"`n_stimuli` must be even (half congruent, half incongruent), got {n_stimuli}.")
725
+ n_repeats = _check_int("n_repeats", n_repeats, 1)
726
+ effect = _check_float("effect", effect)
727
+ rng = np.random.default_rng(seed)
728
+
729
+ subjects = _ids("s", n_subjects)
730
+ stimuli = _ids("x", n_stimuli)
731
+ condition = np.resize(["congruent", "incongruent"], n_stimuli)
732
+ long = _grid(subject=subjects, stimulus=stimuli, trial=range(1, n_repeats + 1))
733
+ subject_index = np.repeat(np.arange(n_subjects), n_stimuli * n_repeats)
734
+ stimulus_index = np.tile(np.repeat(np.arange(n_stimuli), n_repeats), n_subjects)
735
+ incongruent = condition[stimulus_index] == "incongruent"
736
+ rt = (
737
+ 500.0
738
+ + rng.normal(0.0, 50.0, size=n_subjects)[subject_index]
739
+ + rng.normal(0.0, 20.0, size=n_stimuli)[stimulus_index]
740
+ + effect * incongruent
741
+ + rng.normal(0.0, 80.0, size=len(long))
742
+ )
743
+ long["rt"] = np.maximum(rt, 150.0)
744
+ long["correct"] = rng.random(len(long)) < 0.95
745
+
746
+ study = _study(
747
+ "Toy crossed design",
748
+ "Every subject sees every stimulus; incongruent stimuli slow responses down.",
749
+ "crossed",
750
+ {
751
+ "n_subjects": n_subjects,
752
+ "n_stimuli": n_stimuli,
753
+ "n_repeats": n_repeats,
754
+ "effect": effect,
755
+ "seed": seed,
756
+ },
757
+ [
758
+ _planted(
759
+ "rt",
760
+ "condition",
761
+ ["incongruent", "congruent"],
762
+ effect,
763
+ reduce={"trial": "mean"},
764
+ unit="subject",
765
+ ),
766
+ _planted(
767
+ "correct",
768
+ "condition",
769
+ ["incongruent", "congruent"],
770
+ 0.0,
771
+ statistic="prop_diff",
772
+ reduce={"trial": "mean"},
773
+ unit="subject",
774
+ ),
775
+ ],
776
+ )
777
+ study.units.define("trial < subject * stimulus")
778
+ v = study.variables
779
+ v.define("condition", "stimulus", "category", categories=("congruent", "incongruent"), scale="nominal")
780
+ v.define(
781
+ "rt", "trial", scale="ratio", measurement_unit="ms", range=(0, None), description="Response time"
782
+ )
783
+ v.define("correct", "trial", "bool", scale="nominal", description="Correct response")
784
+ study.add_units("subject", subjects)
785
+ study.add_units("stimulus", pd.DataFrame({"stimulus": stimuli, "condition": condition}))
786
+ study.add_units("trial", long[["subject", "stimulus", "trial"]])
787
+ study.add("rt", long[["subject", "stimulus", "trial", "rt"]])
788
+ study.add("correct", long[["subject", "stimulus", "trial", "correct"]])
789
+ return study
790
+
791
+
792
+ def method_comparison(
793
+ n_subjects: int = 16,
794
+ n_sources: int = 200,
795
+ n_missing: int = 5,
796
+ n_depth_bins: int = 5,
797
+ effect: float = 0.05,
798
+ seed: int = 0,
799
+ ) -> Study:
800
+ """
801
+ Method comparison against a reference, per source: three methods (`proposed`, `alternative`,
802
+ `baseline`) are scored by their error at every source of every subject, for three sensor types. Every
803
+ factor is a dimension, so every comparison is paired; sources differ in number and identity between
804
+ subjects (ragged); `alternative` failed in `n_missing` subjects and has no values there. Lower error
805
+ is better. Shaped like the mindmap-bem manuscript (TODO.md).
806
+
807
+ `compare("error", by="method", reference="proposed", subset={"sensors": "eeg"},
808
+ reduce={"source": "median"}, higher_is_better=False)` compares per-subject median errors, each pair on
809
+ its complete cases.
810
+
811
+ Units: `subject`. Variables at `subject`:
812
+
813
+ - `error` (dims `method`, `sensors`, `source`): error per source, positive, rising with depth;
814
+ - `bias` (same dims): a signed per-source error, centred on 0 for every method;
815
+ - `depth` (dim `source`, mm): each source's distance to the inner skull;
816
+ - `error_depth` (dims `method`, `sensors`, `depth_bin`): median `error` per depth bin (bin centres in
817
+ mm), as a pipeline would store it;
818
+ - `accepted` (dim `method`, bool): False where `alternative` failed.
819
+
820
+ Planted (on per-subject medians over sources; the differences hold in every depth bin too):
821
+
822
+ - `error`, proposed - baseline: `-effect` for `eeg` and `mag` (default -0.05), 0 for `grad` (null);
823
+ - `error`, alternative - proposed: `2 * effect`, on `n_subjects - n_missing` subjects;
824
+ - `bias`, proposed - baseline: 0 for every sensor type (null).
825
+
826
+ Parameters
827
+ ----------
828
+ n_subjects: int, optional
829
+ At least 3.
830
+
831
+ n_sources: int, optional
832
+ Typical sources per subject (each subject has ±10%, drawn from its own set of ids); at least 10.
833
+
834
+ n_missing: int, optional
835
+ Subjects where `alternative` failed (0 to `n_subjects - 2`).
836
+
837
+ n_depth_bins: int, optional
838
+ Bins of `error_depth` (at least 1).
839
+
840
+ effect: float, optional
841
+ How much lower `proposed`'s error is than `baseline`'s, for EEG and magnetometers.
842
+
843
+ seed: int, optional
844
+
845
+ Returns
846
+ -------
847
+ Study
848
+ """
849
+ n_subjects = _check_int("n_subjects", n_subjects, 3)
850
+ n_sources = _check_int("n_sources", n_sources, 10)
851
+ n_missing = _check_int("n_missing", n_missing, 0)
852
+ if n_missing > n_subjects - 2:
853
+ raise ValueError(f"`n_missing` must be at most n_subjects - 2 = {n_subjects - 2}, got {n_missing}.")
854
+ n_depth_bins = _check_int("n_depth_bins", n_depth_bins, 1)
855
+ effect = _check_float("effect", effect, 0.0, 0.1)
856
+ rng = np.random.default_rng(seed)
857
+
858
+ subjects = _ids("s", n_subjects)
859
+ methods = ["proposed", "alternative", "baseline"]
860
+ sensors = ["eeg", "mag", "grad"]
861
+ base = {("baseline", s): 0.20 for s in sensors} | {
862
+ ("proposed", s): 0.20 - (effect if s != "grad" else 0.0) for s in sensors
863
+ }
864
+ base |= {("alternative", s): base[("proposed", s)] + 2 * effect for s in sensors}
865
+ failed = set(rng.choice(subjects, size=n_missing, replace=False).tolist())
866
+ max_depth = 50.0
867
+ edges = np.linspace(0.0, max_depth, n_depth_bins + 1)
868
+ centres = np.round((edges[:-1] + edges[1:]) / 2, 1)
869
+
870
+ error_parts, bias_parts, depth_parts, binned_parts = [], [], [], []
871
+ for subject in subjects:
872
+ n_src = int(rng.integers(int(0.9 * n_sources), int(1.1 * n_sources) + 1))
873
+ sources = np.sort(rng.choice(int(1.5 * n_sources), size=n_src, replace=False))
874
+ depth = rng.uniform(0.0, max_depth, size=n_src)
875
+ depth_parts.append(pd.DataFrame({"subject": subject, "source": sources, "depth": depth}))
876
+ bins = np.clip(np.digitize(depth, edges[1:-1]), 0, n_depth_bins - 1)
877
+ offset = rng.normal(0.0, 0.01)
878
+ for method in methods:
879
+ if method == "alternative" and subject in failed:
880
+ continue
881
+ for sensor in sensors:
882
+ shift = rng.normal(0.0, 0.01)
883
+ error = base[(method, sensor)] + offset + shift + 0.002 * depth + rng.normal(0.0, 0.03, n_src)
884
+ error = np.maximum(error, 0.0)
885
+ bias = rng.normal(0.0, 0.05, n_src)
886
+ part = {"subject": subject, "method": method, "sensors": sensor, "source": sources}
887
+ error_parts.append(pd.DataFrame({**part, "error": error}))
888
+ bias_parts.append(pd.DataFrame({**part, "bias": bias}))
889
+ medians = pd.Series(error).groupby(bins).median().reindex(range(n_depth_bins))
890
+ binned_parts.append(
891
+ pd.DataFrame(
892
+ {
893
+ "subject": subject,
894
+ "method": method,
895
+ "sensors": sensor,
896
+ "depth_bin": centres,
897
+ "error_depth": medians.to_numpy(),
898
+ }
899
+ )
900
+ )
901
+ accepted = _grid(subject=subjects, method=methods)
902
+ accepted["accepted"] = ~((accepted["method"] == "alternative") & accepted["subject"].isin(failed))
903
+
904
+ complete = n_subjects - n_missing
905
+ planted = [
906
+ _planted(
907
+ "error",
908
+ "method",
909
+ ["proposed", "baseline"],
910
+ -effect if s != "grad" else 0.0,
911
+ subset={"sensors": s},
912
+ reduce={"source": "median"},
913
+ n=n_subjects,
914
+ note="lower is better",
915
+ )
916
+ for s in sensors
917
+ ]
918
+ planted += [
919
+ _planted(
920
+ "error",
921
+ "method",
922
+ ["alternative", "proposed"],
923
+ 2 * effect,
924
+ subset={"sensors": s},
925
+ reduce={"source": "median"},
926
+ n=complete,
927
+ note="lower is better",
928
+ )
929
+ for s in sensors
930
+ ]
931
+ planted += [
932
+ _planted(
933
+ "bias",
934
+ "method",
935
+ ["proposed", "baseline"],
936
+ 0.0,
937
+ subset={"sensors": s},
938
+ reduce={"source": "median"},
939
+ n=n_subjects,
940
+ )
941
+ for s in sensors
942
+ ]
943
+ study = _study(
944
+ "Toy method comparison",
945
+ "Three methods scored per source against a reference, for three sensor types; one method failed "
946
+ "in some subjects. Lower error is better.",
947
+ "method_comparison",
948
+ {
949
+ "n_subjects": n_subjects,
950
+ "n_sources": n_sources,
951
+ "n_missing": n_missing,
952
+ "n_depth_bins": n_depth_bins,
953
+ "effect": effect,
954
+ "seed": seed,
955
+ },
956
+ planted,
957
+ )
958
+ study.units.add_level("subject", description="Participant")
959
+ method, sensor = Dim("method", description="Method compared to the reference"), Dim("sensors")
960
+ source = Dim("source", description="Source id (each subject has its own source space)")
961
+ v = study.variables
962
+ v.define(
963
+ "error", "subject", dims=[method, sensor, source], scale="ratio", range=(0, None), origin="derived"
964
+ )
965
+ v.define("bias", "subject", dims=[method, sensor, source], scale="interval", origin="derived")
966
+ v.define("depth", "subject", dims=[source], scale="ratio", measurement_unit="mm", range=(0, None))
967
+ v.define(
968
+ "error_depth",
969
+ "subject",
970
+ dims=[method, sensor, Dim("depth_bin", measurement_unit="mm", description="Centre of the depth bin")],
971
+ scale="ratio",
972
+ range=(0, None),
973
+ origin="derived",
974
+ description="Median error per depth bin",
975
+ )
976
+ v.define("accepted", "subject", "bool", dims=[method], scale="nominal", description="Method succeeded")
977
+ study.add_units("subject", subjects)
978
+ study.add("error", pd.concat(error_parts, ignore_index=True))
979
+ study.add("bias", pd.concat(bias_parts, ignore_index=True))
980
+ study.add("depth", pd.concat(depth_parts, ignore_index=True))
981
+ study.add("error_depth", pd.concat(binned_parts, ignore_index=True))
982
+ study.add("accepted", accepted)
983
+ return study