Files
tea/tests/test_slow_waves.py
T
AlbertoPMDM 4987629e8b slow_wave_staging and slow_waves, legacy and modern
- legacy: ondas_lentas.detectar on F3 F4 Fz over the whole recording,
  union_intervalos + estadificar for the 'sueno' windows (the cluster
  route's fases_sueno), ondas_lentas.resumen for the features; vendored
  unchanged.
- modern: the same zero-crossing detector on an MNE band-pass, the same 20%
  of 30 s N3 rule, the same summary definitions.

Legacy waves equal the submodule's exactly; modern equals legacy on the
synthetic study; contract suites pass.
2026-11-18 21:47:39 -06:00

89 lines
3.6 KiB
Python

"""Slow waves: legacy = the submodule's detector; modern agrees with legacy."""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from synth_edf import make_edf
from tea_modulo.contracts import Study
from tea_modulo.contracts.testing import check_biomarker, check_process
from tea_modulo.pipeline import Pipeline
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
from tea_modulo.processes.slow_wave_staging import api as sws
BT = Path(__file__).resolve().parents[1] / "biomarcadores-tea"
@pytest.fixture(scope="module")
def edf(tmp_path_factory):
return make_edf(tmp_path_factory.mktemp("sw") / "s.edf", minutes=8)
@pytest.fixture(scope="module")
def studies(edf):
return (Pipeline.default("modern").study(edf, plan=DIRECTOR_CLUSTER, age_months=28),
Pipeline.default("legacy").study(edf, plan=DIRECTOR_CLUSTER, age_months=28))
@pytest.mark.skipif(not BT.exists(), reason="submodule absent")
def test_legacy_waves_equal_submodule(edf, studies):
code = f"""
import json, sys, contextlib, io, warnings
from pathlib import Path
sys.path.insert(0, {str(BT / 'preproceso')!r}); warnings.simplefilter("ignore")
import un_estudio, eeg_io, ondas_lentas
with contextlib.redirect_stdout(io.StringIO()), un_estudio.temporal(Path({str(edf)!r}),
linea_hz=60.0, pasa_altas=(0.3, 0.5), pasa_bajas=100.0) as res:
est = eeg_io.Estudio(res["preproc_npz"], preferir="hp05_prom", estricto=True)
out = []
for c in ondas_lentas.CANALES_FRONTAL:
o = ondas_lentas.detectar(est.datos(canales=[c])[:, 0], est.fs)
out += [[c, float(r.t_ini_s), float(r.p2p_uV)] for r in o.itertuples()]
print(json.dumps(out))
"""
r = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True)
assert r.returncode == 0, r.stderr[-1500:]
ref = json.loads(r.stdout.strip().splitlines()[-1])
ev = studies[1].label("slow_wave_staging").events
assert [[c, t, p] for c, t, p in zip(ev.canal, ev.t_ini_s.astype(float), ev.p2p_uV.astype(float))] == ref
def test_modern_agrees_with_legacy(studies):
sm, sl = studies
a, b = sm.label("slow_wave_staging"), sl.label("slow_wave_staging")
assert (a.per_window.values == b.per_window.values).mean() >= 0.95
assert abs(len(a.events) - len(b.events)) <= max(2, 0.1 * len(b.events))
m = Pipeline.default("modern").module("slow_waves").measure(sm)
l = Pipeline.default("legacy").module("slow_waves").measure(sl)
for k in m:
assert (np.isnan(m[k]) and np.isnan(l[k])) or m[k] == pytest.approx(l[k], rel=0.1, abs=0.05), k
def test_n3_rule():
"""20% coverage of the 30 s epoch around the window decides N3."""
iv = np.array([[10.0, 16.5]]) # 6.5 s of slow waves
assert sws.coverage(iv, 0.0, 30.0) == pytest.approx(6.5 / 30)
assert sws.coverage(iv, 0.0, 30.0) >= sws.FRAC_N3
assert sws.coverage(np.array([[10.0, 15.0]]), 0.0, 30.0) < sws.FRAC_N3
def test_contracts(studies):
for impl, s in zip(("modern", "legacy"), studies):
base = Study(s.prep, {k: v for k, v in s.labels.items() if k == "sleep_state" or k == "annotation_mask"})
check_process(Pipeline.default(impl).module("slow_wave_staging"), base)
def test_biomarker_contract(tmp_path):
pipe = Pipeline.default("modern")
sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=6, seed=i), plan=DIRECTOR_CLUSTER,
age_months=20 + 4 * i) for i in range(3)]
from tea_modulo.biomarkers.slow_waves import SlowWaves
check_biomarker(SlowWaves(baseline="age_blocks"), sts, [20, 24, 28])