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.
This commit is contained in:
@@ -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:<commit>` 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.
|
||||||
|
|||||||
@@ -54,8 +54,20 @@ class LegacySpindleDetection:
|
|||||||
requires = ("sleep_state",)
|
requires = ("sleep_state",)
|
||||||
impl = "legacy"
|
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.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):
|
def train(self, studies):
|
||||||
return self
|
return self
|
||||||
@@ -65,7 +77,7 @@ class LegacySpindleDetection:
|
|||||||
from ._director import ritmo as r
|
from ._director import ritmo as r
|
||||||
|
|
||||||
lab, w = study.label("sleep_state").per_window, study.prep.windows
|
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"]
|
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:
|
with _adapter.estudio(study.prep, self.variant, eeg_io) as est:
|
||||||
rh = wake_rhythm(est, vigilia, r, eeg_io)
|
rh = wake_rhythm(est, vigilia, r, eeg_io)
|
||||||
@@ -80,7 +92,7 @@ class LegacySpindleDetection:
|
|||||||
return Labels(self.name, events=out.reset_index(drop=True))
|
return Labels(self.name, events=out.reset_index(drop=True))
|
||||||
|
|
||||||
def save(self, path):
|
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
|
@classmethod
|
||||||
def load(cls, path):
|
def load(cls, path):
|
||||||
|
|||||||
@@ -140,8 +140,20 @@ class SpindleDetection:
|
|||||||
requires = ("sleep_state",)
|
requires = ("sleep_state",)
|
||||||
impl = "modern"
|
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.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):
|
def train(self, studies):
|
||||||
return self
|
return self
|
||||||
@@ -154,8 +166,8 @@ class SpindleDetection:
|
|||||||
x = raw.get_data(picks=names).T * 1e6
|
x = raw.get_data(picks=names).T * 1e6
|
||||||
asleep = np.zeros(len(x), bool)
|
asleep = np.zeros(len(x), bool)
|
||||||
n = int(4 * fs)
|
n = int(4 * fs)
|
||||||
for s, e in zip(w.start_s, lab):
|
for s, ok in zip(w.start_s, self._sleep(study, lab)):
|
||||||
if e == "sueno":
|
if ok:
|
||||||
a = int(round(float(s) * fs))
|
a = int(round(float(s) * fs))
|
||||||
asleep[a:a + n] = True
|
asleep[a:a + n] = True
|
||||||
minutes = float(asleep.sum() / fs / 60)
|
minutes = float(asleep.sum() / fs / 60)
|
||||||
@@ -166,7 +178,7 @@ class SpindleDetection:
|
|||||||
return Labels(self.name, events=ev)
|
return Labels(self.name, events=ev)
|
||||||
|
|
||||||
def save(self, path):
|
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
|
@classmethod
|
||||||
def load(cls, path):
|
def load(cls, path):
|
||||||
|
|||||||
@@ -43,9 +43,13 @@ def test_order_is_topological():
|
|||||||
|
|
||||||
|
|
||||||
def test_legacy_pipeline_is_registered():
|
def test_legacy_pipeline_is_registered():
|
||||||
pipe = Pipeline.default(impl="legacy")
|
for impl in ("legacy", "modern"):
|
||||||
assert {"validation", "preprocessing", "annotation_mask", "sleep_state", "posterior_rhythm"} <= set(pipe.modules)
|
pipe = Pipeline.default(impl=impl)
|
||||||
assert pipe.biomarker_names() == ["posterior_rhythm"]
|
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):
|
def test_legacy_loop_rows_and_errors(edfs):
|
||||||
|
|||||||
@@ -101,3 +101,19 @@ def test_biomarker_contract(tmp_path):
|
|||||||
age_months=20 + 4 * i) for i in range(3)]
|
age_months=20 + 4 * i) for i in range(3)]
|
||||||
from tea_modulo.biomarkers.spindles import Spindles
|
from tea_modulo.biomarkers.spindles import Spindles
|
||||||
check_biomarker(Spindles(baseline="age_blocks"), sts, [20, 24, 28])
|
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")
|
||||||
|
|||||||
Reference in New Issue
Block a user