ae92ae8b17
- legacy: medidas_director.gradiente on gradiente.analizar (vendored), in the 'sueno' and 'somnolencia' windows as analizar_director does. - modern: Hann periodograms per window (MNE), median band power, Theil-Sen slope (scipy.stats.theilslopes) on the director's front-back coordinates. - 8 features gradient_<band>_<state>, one baseline each. Legacy equals the submodule's cluster route exactly; modern within 0.01 of legacy on the synthetic study.
87 lines
3.5 KiB
Python
87 lines
3.5 KiB
Python
"""Gradient: 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.testing import check_biomarker
|
|
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("grad") / "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))
|
|
|
|
|
|
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, gradiente as g
|
|
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)
|
|
sue = [float(a) for a, e in zip(t.t_ini_s, t.vigilancia) if e == "sueno"]
|
|
fila, _, n = g.analizar(est, sue)
|
|
print(json.dumps({{k: fila.get(f"pendiente_{{k}}") for k in ("delta", "theta", "alfa", "beta")}}, 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)
|
|
got = Pipeline.default("legacy").module("gradient").measure(studies[1])
|
|
for b, v in ref.items():
|
|
assert got[f"gradient_{b}_sueno"] == v, b
|
|
|
|
|
|
def test_modern_agrees_with_legacy(studies):
|
|
sm, sl = studies
|
|
m = Pipeline.default("modern").module("gradient").measure(sm)
|
|
l = Pipeline.default("legacy").module("gradient").measure(sl)
|
|
for k in m:
|
|
if np.isnan(l[k]):
|
|
assert np.isnan(m[k]), k
|
|
else:
|
|
assert m[k] == pytest.approx(l[k], abs=0.01), k
|
|
|
|
|
|
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.gradient import Gradient
|
|
check_biomarker(Gradient(baseline="age_blocks"), sts, [20, 24, 28])
|