From 5da1921c6926a6b3cb5f14f01d8ba1d17f8b9519 Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Wed, 18 Nov 2026 22:12:02 -0600 Subject: [PATCH] spindle phases (N2/N3), README, registry test for the full module set - spindle_detection (legacy and modern): phase='N2'|'N3' searches only the sleep windows of that stage (husos --fase); requires slow_wave_staging then. - README: modules, requirements, use, tests and cluster verification. - test_pipeline: both implementations register the same 5 processes and 9 biomarkers. --- README.md | 71 +++++++++++++++++++ .../legacy/processes/spindle_detection/api.py | 18 ++++- .../processes/spindle_detection/api.py | 20 ++++-- tests/test_pipeline.py | 10 ++- tests/test_spindles.py | 16 +++++ 5 files changed, 125 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index e69de29..1e75384 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,71 @@ +# tea_modulo + +EEG library for the TEA project: EDF in; validation, preprocessing, processes +and biomarkers out. Every biomarker and every process is its own module, and +modules talk only through `tea_modulo.contracts`, so any module can be replaced +without touching the others. Architecture plan: +https://claude.ai/artifact/H9Rh19Lv79dVeikeVD9KFZ + +## Two implementations + +| | `tea_modulo` (modern) | `tea_modulo.legacy` | +|---|---|---| +| Code | the director's methods on MNE, SciPy, scikit-learn, antropy, fooof, meegkit | the director's code (biomarcadores-tea @ 7dfc641, codigo @ c7a4736) copied unchanged except imports | +| Batches | Dask (`cluster="auto"/"remote"/"local"/"sync"`) | plain single-threaded loop | +| Checked against | legacy, on synthetic EDFs | the submodule's own scripts, exactly | + +## Modules + +| kind | name | requires | +|---|---|---| +| validator | `validation` | — | +| preprocessor | `preprocessing` | — | +| process | `annotation_mask` | — | +| process | `window_selection` | annotation_mask | +| process | `sleep_state` | annotation_mask | +| process | `slow_wave_staging` | sleep_state | +| process | `spindle_detection` | sleep_state (+ slow_wave_staging with `phase`) | +| biomarker | `posterior_rhythm` | sleep_state | +| biomarker | `spindles` | spindle_detection | +| biomarker | `gradient` | sleep_state | +| biomarker | `slow_waves` | slow_wave_staging | +| biomarker | `aperiodic`, `mse` | sleep_state, annotation_mask | +| biomarker | `coupling` | spindle_detection (+ slow_wave_staging with `in_slow_wave`) | +| biomarker | `spindle_topography` | spindle_detection, sleep_state | +| biomarker | `spikes` | sleep_state (modern: + annotation_mask) | + +## Use + +```python +from tea_modulo.validation import validate +bundle, valid = validate("study.edf") # R4B FHIR Bundle, 1 valid / 0 not valid + +from tea_modulo.pipeline import Pipeline +from tea_modulo.preprocessing import DIRECTOR_CLUSTER +pipe = Pipeline.default() # or Pipeline.default(impl="legacy") +study = pipe.study("study.edf", plan=DIRECTOR_CLUSTER, age_months=27.5) +pipe.biomarker("posterior_rhythm").measure(study) + +table = pipe.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, + biomarkers=("posterior_rhythm", "spindles")) # Dask: cluster or LocalCluster +rhythm = pipe.biomarker("posterior_rhythm").train(table) # baseline: curves or age_blocks +rhythm.predict(table.iloc[[0]]) # outside -1/0/+1, z + +from tea_modulo.serving import log_plan, log_biomarker # MLflow models, privacy guard +``` + +Replace a module: `pipe.replace("spindle_detection", MyDetector())`, or register +it under the same name in the `tea_modulo.modules` entry-point group. Check it +with `tea_modulo.contracts.testing`. + +## Tests and cluster verification + +- `uv run pytest` (synthetic EDFs only; no patient data). +- `deploy/verify.sh` builds `tea-verify:` from this checkout, runs the + test suite and the HK1K check (`python -m tea_modulo.verify hk1k`) in a + `DaskJob` of its own; `deploy/verify.sh --logs`, `--delete`. +- `python tools/vendor_legacy.py --check` confirms the legacy copies are + unchanged. + +Patient data (ISSSTELEÓN) is never read by these tests; the HK1K check reads +only `raw/eeg-helsinki/` and writes group summaries only. diff --git a/src/tea_modulo/legacy/processes/spindle_detection/api.py b/src/tea_modulo/legacy/processes/spindle_detection/api.py index 3a392e6..4642bdd 100644 --- a/src/tea_modulo/legacy/processes/spindle_detection/api.py +++ b/src/tea_modulo/legacy/processes/spindle_detection/api.py @@ -54,8 +54,20 @@ class LegacySpindleDetection: requires = ("sleep_state",) impl = "legacy" - def __init__(self, variant: str = "hp05_prom"): + def __init__(self, variant: str = "hp05_prom", phase: str | None = None): + """`phase` 'N2' or 'N3': search only the sleep windows of that stage (husos --fase, + the CLI route with N2/N3 on); the thresholds then come from that stage alone.""" + if phase not in (None, "N2", "N3"): + raise ValueError(f"phase must be None, 'N2' or 'N3', not {phase!r}") self.variant = variant + self.phase = phase + self.requires = ("sleep_state", "slow_wave_staging") if phase else ("sleep_state",) + + def _sleep(self, study, lab): + if not self.phase: + return [e == "sueno" for e in lab] + st = study.label("slow_wave_staging").per_window + return [e == "sueno" and f == self.phase for e, f in zip(lab, st)] def train(self, studies): return self @@ -65,7 +77,7 @@ class LegacySpindleDetection: from ._director import ritmo as r lab, w = study.label("sleep_state").per_window, study.prep.windows - sueno = [float(s) for s, e in zip(w.start_s, lab) if e == "sueno"] + sueno = [float(s) for s, ok in zip(w.start_s, self._sleep(study, lab)) if ok] vigilia = [float(s) for s, e in zip(w.start_s, lab) if e == "vigilia"] with _adapter.estudio(study.prep, self.variant, eeg_io) as est: rh = wake_rhythm(est, vigilia, r, eeg_io) @@ -80,7 +92,7 @@ class LegacySpindleDetection: return Labels(self.name, events=out.reset_index(drop=True)) def save(self, path): - Path(path, "params.json").write_text(json.dumps({"variant": self.variant})) + Path(path, "params.json").write_text(json.dumps({"variant": self.variant, "phase": self.phase})) @classmethod def load(cls, path): diff --git a/src/tea_modulo/processes/spindle_detection/api.py b/src/tea_modulo/processes/spindle_detection/api.py index d3e99a3..dcff182 100644 --- a/src/tea_modulo/processes/spindle_detection/api.py +++ b/src/tea_modulo/processes/spindle_detection/api.py @@ -140,8 +140,20 @@ class SpindleDetection: requires = ("sleep_state",) impl = "modern" - def __init__(self, variant: str = "hp05_prom"): + def __init__(self, variant: str = "hp05_prom", phase: str | None = None): + """`phase` 'N2' or 'N3': search only the sleep windows of that stage (husos --fase, + the CLI route with N2/N3 on); the thresholds then come from that stage alone.""" + if phase not in (None, "N2", "N3"): + raise ValueError(f"phase must be None, 'N2' or 'N3', not {phase!r}") self.variant = variant + self.phase = phase + self.requires = ("sleep_state", "slow_wave_staging") if phase else ("sleep_state",) + + def _sleep(self, study, lab): + if not self.phase: + return [e == "sueno" for e in lab] + st = study.label("slow_wave_staging").per_window + return [e == "sueno" and f == self.phase for e, f in zip(lab, st)] def train(self, studies): return self @@ -154,8 +166,8 @@ class SpindleDetection: x = raw.get_data(picks=names).T * 1e6 asleep = np.zeros(len(x), bool) n = int(4 * fs) - for s, e in zip(w.start_s, lab): - if e == "sueno": + for s, ok in zip(w.start_s, self._sleep(study, lab)): + if ok: a = int(round(float(s) * fs)) asleep[a:a + n] = True minutes = float(asleep.sum() / fs / 60) @@ -166,7 +178,7 @@ class SpindleDetection: return Labels(self.name, events=ev) def save(self, path): - Path(path, "params.json").write_text(json.dumps({"variant": self.variant})) + Path(path, "params.json").write_text(json.dumps({"variant": self.variant, "phase": self.phase})) @classmethod def load(cls, path): diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index b3eee46..db31b6f 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -43,9 +43,13 @@ def test_order_is_topological(): def test_legacy_pipeline_is_registered(): - pipe = Pipeline.default(impl="legacy") - assert {"validation", "preprocessing", "annotation_mask", "sleep_state", "posterior_rhythm"} <= set(pipe.modules) - assert pipe.biomarker_names() == ["posterior_rhythm"] + for impl in ("legacy", "modern"): + pipe = Pipeline.default(impl=impl) + assert set(pipe.process_names()) == {"annotation_mask", "window_selection", "sleep_state", + "slow_wave_staging", "spindle_detection"}, impl + assert set(pipe.biomarker_names()) == {"posterior_rhythm", "spindles", "gradient", "slow_waves", + "aperiodic", "mse", "coupling", "spindle_topography", + "spikes"}, impl def test_legacy_loop_rows_and_errors(edfs): diff --git a/tests/test_spindles.py b/tests/test_spindles.py index 2abea37..7a8cd5b 100644 --- a/tests/test_spindles.py +++ b/tests/test_spindles.py @@ -101,3 +101,19 @@ def test_biomarker_contract(tmp_path): age_months=20 + 4 * i) for i in range(3)] from tea_modulo.biomarkers.spindles import Spindles check_biomarker(Spindles(baseline="age_blocks"), sts, [20, 24, 28]) + + +@pytest.mark.parametrize("impl", ["modern", "legacy"]) +def test_phase_restricts_the_search(studies, impl): + """phase='N3' searches only N3 sleep windows (none in this study: no spindles, no minutes).""" + s = studies[0] if impl == "modern" else studies[1] + pipe = Pipeline.default(impl) + det = type(pipe.module("spindle_detection"))(phase="N3") + assert det.requires == ("sleep_state", "slow_wave_staging") + ev = det.predict(s).events + n3 = (s.label("slow_wave_staging").per_window == "N3").sum() + assert n3 == 0 and len(ev) == 0 and ev.attrs["minutes"] == 0 + det2 = type(pipe.module("spindle_detection"))(phase="N2") + assert len(det2.predict(s).events) == len(s.label("spindle_detection").events) # all sleep is N2 here + with pytest.raises(ValueError, match="phase"): + type(pipe.module("spindle_detection"))(phase="REM")