25dd95a8ad
The director's scripts (biomarcadores-tea/preproceso @ 7dfc641) are vendored unchanged except imports by tools/vendor_legacy.py, one copy per legacy module; --check re-derives them from the pinned submodule. LegacyValidation runs steps 1-4 of un_estudio.procesar for an EDF (edf_convert, lote.excluidos_para_qc + qc_estudio + veredicto, triaje.triar, 60% clean windows) plus preproceso.MIN_CUERO, and returns an R4B FHIR Bundle and 0/1. Tests: identical to the submodule on a synthetic EDF, contract suite, not-valid case, vendor check.
122 lines
4.8 KiB
Python
122 lines
4.8 KiB
Python
"""
|
|
Legacy validation = the director's code, exactly.
|
|
|
|
The submodule's own scripts (biomarcadores-tea/preproceso via sys.path) and
|
|
tea_modulo.legacy.validation run on the same synthetic EDF must give identical
|
|
results: channel table, dropped channels, window QC and triage.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pytest
|
|
|
|
from synth_edf import SCALP, make_edf
|
|
from tea_modulo.contracts.testing import check_validation
|
|
from tea_modulo.legacy.validation import MODULE
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
PREPROCESO = ROOT / "biomarcadores-tea" / "preproceso"
|
|
needs_submodule = pytest.mark.skipif(not PREPROCESO.exists(), reason="submodule absent")
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def edf(tmp_path_factory):
|
|
d = tmp_path_factory.mktemp("legval")
|
|
return make_edf(d / "s.edf", minutes=6, gaps=[(100.0, 4.0)],
|
|
bad={"flat": ["P3"], "bursts": ["P4"], "bridge": [("F3", "C3")]})
|
|
|
|
|
|
def _director_run(edf_path: Path, line_hz=60.0) -> dict:
|
|
"""Steps 1-4 of un_estudio.procesar, run on the submodule itself in a subprocess."""
|
|
code = f"""
|
|
import json, sys, tempfile, contextlib, io
|
|
from pathlib import Path
|
|
sys.path.insert(0, {str(PREPROCESO)!r})
|
|
import edf_convert, lote, triaje, preproceso, eeg_io
|
|
import pandas as pd
|
|
p = Path({str(edf_path)!r}); nombre = p.stem
|
|
with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()):
|
|
conv = Path(tmp)
|
|
edf_convert.convertir(p, conv)
|
|
npz = conv / nombre / f"{{nombre}}_signals.npz"; meta = conv / nombre / f"{{nombre}}_metadata.json"
|
|
excluir, tabla = lote.excluidos_para_qc(npz, meta, {line_hz})
|
|
reg = {{"estudio": nombre, **lote.qc_estudio(npz, meta, linea_hz={line_hz}, nombre_estudio=nombre, excluir=excluir)}}
|
|
reg["veredicto"], reg["motivo"] = lote.veredicto(reg)
|
|
est = eeg_io.Estudio(npz, meta)
|
|
todos = eeg_io.canales_de(est.canales, "eeg", "orejas", "eog", "cardiaco")
|
|
malos, motivo = preproceso.canales_malos(est, todos, tabla)
|
|
pub = {{k: v for k, v in reg.items() if not k.startswith("_")}}
|
|
qc_df = pd.DataFrame([pub]).rename(columns=lote.UNIDADES)
|
|
can_df = pd.DataFrame([dict(estudio=nombre, **c) for c in reg.get("_por_canal", [])])
|
|
tri = triaje.triar(qc_df, can_df if len(can_df) else None).iloc[0]
|
|
print(json.dumps({{"qc": pub, "ventanas": reg["_por_ventana"], "tabla": tabla.to_dict("records"),
|
|
"malos": {{n: motivo.get(n, "") for n in sorted(malos)}}, "excluir": excluir,
|
|
"nivel": tri.nivel, "accion": tri.accion}}, default=str))
|
|
"""
|
|
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True,
|
|
text=True, check=True, cwd=str(edf_path.parent))
|
|
return json.loads(out.stdout.strip().splitlines()[-1])
|
|
|
|
|
|
def _norm(x):
|
|
return json.loads(json.dumps(x, default=str))
|
|
|
|
|
|
@needs_submodule
|
|
def test_legacy_equals_submodule(edf):
|
|
ref = _director_run(edf)
|
|
r = MODULE.run(edf)
|
|
assert r["malos"] == ref["malos"]
|
|
assert r["excluidos_qc"] == ref["excluir"]
|
|
assert _norm(r["qc"]) == ref["qc"]
|
|
assert _norm(r["ventanas"]) == ref["ventanas"]
|
|
assert _norm(r["tabla"].to_dict("records")) == ref["tabla"]
|
|
assert r["triaje"]["nivel"] == ref["nivel"] and r["triaje"]["accion"] == ref["accion"]
|
|
|
|
|
|
def test_finds_the_faults_and_passes(edf):
|
|
r = MODULE.run(edf)
|
|
assert {"P3", "P4", "F3", "C3"} <= set(r["malos"])
|
|
assert "puente" in r["malos"]["F3"]
|
|
assert r["valid"] == 1 and r["triaje"]["nivel"] == "completo"
|
|
|
|
|
|
def test_validate_contract_and_fhir(edf):
|
|
bundle, valid = MODULE.validate(edf)
|
|
summary = MODULE.summarize(edf)
|
|
check_validation(bundle, valid, summary)
|
|
from fhir.resources.R4B.bundle import Bundle
|
|
Bundle.model_validate(bundle)
|
|
obs = [e["resource"] for e in bundle["entry"] if e["resource"]["resourceType"] == "Observation"]
|
|
electrodes = {c.get("valueString") for o in obs for c in o.get("component", [])
|
|
if c["code"]["text"] == "electrode"}
|
|
assert {"P3", "P4"} <= electrodes
|
|
assert not any("subject" in e["resource"] for e in bundle["entry"])
|
|
|
|
|
|
def test_too_few_scalp_electrodes_is_not_valid(tmp_path):
|
|
flat = SCALP[:8] # 8 dead -> 11 usable < 12
|
|
p = make_edf(tmp_path / "bad.edf", minutes=4, bad={"flat": flat})
|
|
bundle, valid = MODULE.validate(p)
|
|
assert valid == 0
|
|
r = MODULE.run(p)
|
|
assert any("electrodos de cuero" in x for x in r["razones"])
|
|
check_validation(bundle, valid)
|
|
|
|
|
|
def test_vendored_copies_are_unchanged():
|
|
out = subprocess.run([sys.executable, str(ROOT / "tools" / "vendor_legacy.py"), "--check"],
|
|
capture_output=True, text=True)
|
|
if out.returncode == 2:
|
|
pytest.skip(out.stderr.strip())
|
|
assert out.returncode == 0, out.stdout
|