Files
tea/tests/legacy/test_legacy_state_rhythm.py
T
AlbertoPMDM 441113c7b7 legacy: annotation_mask, sleep_state and posterior_rhythm on the director's code
- contracts: Preprocessed.quality_spans (QC-unclean stretches at the QC's
  own resolution), so the director's state mask can be rebuilt exactly.
- legacy.preprocessing: annotations straight from the EDF (exact onsets, as
  edf_convert), quality_spans from his 4 s QC.
- legacy processes annotation_mask (intervalos_estado, estado_de_ventana) and
  sleep_state (vigilancia.rasgos with senal._mascara_excluir's mask,
  clasificar with the HK1K cut-offs or cohort cut-offs after train()).
- legacy biomarker posterior_rhythm (medidas_director.ritmo on
  ritmo.psd_de_ventanas + pico_dominante) with a private _baseline.py holding
  curvas.py and perfil_alteraciones' age-block z, copied verbatim.
- Each legacy module owns its adapter, which writes the study in the
  director's preprocessed format and opens it with his eeg_io.Estudio.

Identical to the submodule's cluster route on a synthetic study (window
labels and rhythm); contract suites pass.
2026-11-18 20:12:47 -06:00

119 lines
5.2 KiB
Python

"""
Legacy annotation_mask + sleep_state + posterior_rhythm = the cluster route on the
submodule (un_estudio -> senal._mascara_excluir -> vigilancia -> HK1K cut-offs ->
medidas_director.ritmo), exactly.
"""
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.legacy.biomarkers.posterior_rhythm import LegacyPosteriorRhythm
from tea_modulo.legacy.preprocessing import MODULE as PRE
from tea_modulo.legacy.processes.annotation_mask import MODULE as AM
from tea_modulo.legacy.processes.sleep_state import MODULE as SS
from tea_modulo.legacy.validation import MODULE as VAL
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
ROOT = Path(__file__).resolve().parents[2]
BT = ROOT / "biomarcadores-tea"
def _study(edf, age=28.0):
prep = PRE.run(edf, PRE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict()), age_months=age)
s = Study(prep)
s = s.with_labels(AM.predict(s))
return s.with_labels(SS.predict(s))
@pytest.fixture(scope="module")
def edf(tmp_path_factory):
return make_edf(tmp_path_factory.mktemp("legstate") / "s.edf", minutes=8, rhythm_hz=6.5,
annotations=[(5, None, "Paciente despierto"), (240.5, None, "Dormido"),
(100, 20, "Fotica 5 Hz"), (150, None, "llanto")])
def _director(edf_path: Path) -> dict:
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, 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) # senal._mascara_excluir
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
rasgos = vigilancia.rasgos(est, linea_hz=60.0, excluir=m)
d = json.loads(Path({str(BT / 'normas' / 'estado_hk1k.json')!r}).read_text())
t, _ = vigilancia.clasificar(rasgos, d["ref"], [float(d["cortes_A"][0]), float(d["corte_B"])], edad_meses=28.0)
inicios = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "vigilia"]
picos = []
for c in ("O1", "O2", "P3", "P4"):
f, P, n = r.psd_de_ventanas(est.datos(canales=[c])[:, 0], est.fs, inicios, r.VENT_S)
if f is not None:
pico, prom, hay = eeg_io.pico_dominante(f, P)
if hay:
picos.append(float(pico))
val = float(np.median(picos)) if len(picos) >= 2 and len(inicios) >= r.MIN_VENTANAS else float("nan")
print(json.dumps({{"labels": dict(zip([round(float(a), 2) for a in t.t_ini_s], t.vigilancia)),
"ritmo": val, "n_vigilia": len(inicios)}}))
"""
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True,
text=True, check=True)
return json.loads(out.stdout.strip().splitlines()[-1])
@pytest.mark.skipif(not BT.exists(), reason="submodule absent")
def test_legacy_equals_cluster_route(edf):
ref = _director(edf)
s = _study(edf)
w = s.prep.windows
got = dict(zip([str(round(float(a), 2)) for a in w.start_s], s.label("sleep_state").per_window))
for t0, lab in ref["labels"].items():
assert got[str(round(float(t0), 2))] == lab, f"window {t0}"
# every window the director did not label is 'sin_estado' here
assert all(v == "sin_estado" for k, v in got.items() if k not in {str(round(float(a), 2)) for a in ref["labels"]})
m = LegacyPosteriorRhythm().detail(s)
assert m["n_ventanas"] == ref["n_vigilia"]
assert m["ritmo_Hz"] == pytest.approx(ref["ritmo"], abs=0) or (np.isnan(m["ritmo_Hz"]) and np.isnan(ref["ritmo"]))
def test_states_follow_the_signal(edf):
s = _study(edf)
lab, w = s.label("sleep_state").per_window, s.prep.windows
assert (lab[w.start_s < 240] == "vigilia").mean() > 0.6
assert (lab[w.start_s > 250] == "sueno").mean() > 0.6
assert (lab[(w.start_s >= 100) & (w.end_s <= 120)] == "sin_estado").all() # photic excluded
assert LegacyPosteriorRhythm().measure(s)["posterior_rhythm_hz"] == pytest.approx(6.5, abs=0.3)
def test_process_contracts(edf):
s = _study(edf)
check_process(AM, Study(s.prep))
check_process(SS, Study(s.prep).with_labels(AM.predict(Study(s.prep))))
def test_biomarker_contract(tmp_path):
studies = [_study(make_edf(tmp_path / f"s{i}.edf", minutes=4, seed=i, rhythm_hz=6 + i * 0.4), 20 + 4 * i)
for i in range(3)]
check_biomarker(LegacyPosteriorRhythm(baseline="age_blocks"), studies, [20, 24, 28])