spindle_detection and spindles, legacy and modern
- legacy: husos.detectar / husos.resumen vendored unchanged, run on the 'sueno' windows as medidas_director does; the wake rhythm that sets the 'rhythm near sigma' flag is computed inside the process (no biomarker dependency). - modern: the same detector on MNE (sigma band-pass) and SciPy (Hilbert, Welch narrowness, phase stability); summary with the director's definitions; one baseline per feature. - privacy.group_size understands per-feature baseline dicts. Legacy equals the submodule's cluster route exactly (spindle count and the six summary measures); modern equals legacy on the synthetic study.
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
"""Spindles: legacy = the cluster route on the submodule; modern agrees with legacy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
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
|
||||
|
||||
BT = Path(__file__).resolve().parents[1] / "biomarcadores-tea"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("spin") / "s.edf", minutes=8, rhythm_hz=6.5)
|
||||
|
||||
|
||||
@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))
|
||||
|
||||
|
||||
def _director(edf_path):
|
||||
code = f"""
|
||||
import json, sys, contextlib, io, warnings
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
sys.path.insert(0, {str(BT / 'preproceso')!r}); warnings.simplefilter("ignore")
|
||||
import un_estudio, eeg_io, vigilancia, seleccion, husos, ritmo as r
|
||||
with contextlib.redirect_stdout(io.StringIO()), un_estudio.temporal(Path({str(edf_path)!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)
|
||||
ivs = [{{k: d[k] for k in ("t_ini", "t_fin", "estado", "fuente")}} for d in eeg_io.intervalos_estado(est)]
|
||||
m = np.zeros(est.n, dtype=bool)
|
||||
for v in res["ventanas_qc"]:
|
||||
if v.get("veredicto") != "limpia" or v.get("montaje", False):
|
||||
m[int(v["t_ini"] * est.fs):int(v["t_fin"] * est.fs)] = True
|
||||
for d in ivs:
|
||||
if d["estado"] in seleccion.EXCLUIDOS + seleccion.PROVOCACION:
|
||||
m[int(d["t_ini"] * est.fs):int(d["t_fin"] * est.fs)] = True
|
||||
d = json.loads(Path({str(BT / 'normas' / 'estado_hk1k.json')!r}).read_text())
|
||||
t, _ = vigilancia.clasificar(vigilancia.rasgos(est, linea_hz=60.0, excluir=m), d["ref"],
|
||||
[float(d["cortes_A"][0]), float(d["corte_B"])], edad_meses=28.0)
|
||||
vig = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "vigilia"]
|
||||
sue = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "sueno"]
|
||||
picos = []
|
||||
for c in ("O1", "O2", "P3", "P4"):
|
||||
f, P, n = r.psd_de_ventanas(est.datos(canales=[c])[:, 0], est.fs, vig, r.VENT_S)
|
||||
if f is not None:
|
||||
pk, pr, hay = eeg_io.pico_dominante(f, P)
|
||||
if hay: picos.append(float(pk))
|
||||
rh = float(np.median(picos)) if len(picos) >= 2 and len(vig) >= r.MIN_VENTANAS else float("nan")
|
||||
ev, minutos, nombres, cont = husos.detectar(est, sue, ritmo_posterior=rh)
|
||||
res_ = husos.resumen(ev, minutos, nombres, estudio="")
|
||||
print(json.dumps({{k: v for k, v in res_.items() if k != "estudio"}}, default=float))
|
||||
"""
|
||||
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True)
|
||||
assert out.returncode == 0, out.stderr[-1500:]
|
||||
return json.loads(out.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
@pytest.mark.skipif(not BT.exists(), reason="submodule absent")
|
||||
def test_legacy_equals_cluster_route(edf, studies):
|
||||
ref = _director(edf)
|
||||
_, sl = studies
|
||||
got = Pipeline.default("legacy").module("spindles").summary(sl)
|
||||
for k in ("n_husos", "densidad_por_min_canal", "frecuencia_mediana_Hz", "pct_rapidos",
|
||||
"duracion_mediana_s", "densidad_lento", "densidad_rapido"):
|
||||
assert got[k] == ref[k], k
|
||||
|
||||
|
||||
def test_modern_agrees_with_legacy(studies):
|
||||
sm, sl = studies
|
||||
m = Pipeline.default("modern").module("spindles").measure(sm)
|
||||
l = Pipeline.default("legacy").module("spindles").measure(sl)
|
||||
for k in m:
|
||||
assert m[k] == pytest.approx(l[k], rel=0.05, abs=0.05), k
|
||||
assert m["spindle_frequency_hz"] == pytest.approx(13.0, abs=0.3)
|
||||
|
||||
|
||||
def test_contracts(studies):
|
||||
for impl, s in zip(("modern", "legacy"), studies):
|
||||
pipe = Pipeline.default(impl)
|
||||
base = Study(s.prep, {k: v for k, v in s.labels.items() if k != "spindle_detection"})
|
||||
check_process(pipe.module("spindle_detection"), 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.spindles import Spindles
|
||||
check_biomarker(Spindles(baseline="age_blocks"), sts, [20, 24, 28])
|
||||
Reference in New Issue
Block a user