PreprocessPlan, default plans and legacy.preprocessing
preprocessing.plan: frozen PreprocessPlan (steps, variants, state, gates, bads, reasons) with checks, to_dict/from_dict (schema 1, unknown keys refused) and a content hash; defaults DIRECTOR_CLUSTER and DIRECTOR_CLI turn the route differences into data. legacy.preprocessing maps the plan dict onto the director's preproceso.procesar (vendored unchanged), refuses what his code cannot do (zapline, other notch threshold, manual bads), returns MNE Raw variants and the window grid flagged from his 4 s QC. Identical to the submodule for both default plans.
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
"""Legacy preprocessing = the director's preproceso.procesar, exactly."""
|
||||
|
||||
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_preprocessed
|
||||
from tea_modulo.legacy.preprocessing import MODULE, PlanNotSupported, windows_from_qc
|
||||
from tea_modulo.legacy.validation import MODULE as VAL
|
||||
from tea_modulo.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PREPROCESO = ROOT / "biomarcadores-tea" / "preproceso"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def edf(tmp_path_factory):
|
||||
return make_edf(tmp_path_factory.mktemp("legpre") / "s.edf", minutes=5, bad={"bursts": ["P4"]})
|
||||
|
||||
|
||||
def _director_preproc(edf_path: Path, out: Path, args: dict):
|
||||
code = f"""
|
||||
import sys, tempfile, contextlib, io
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, {str(PREPROCESO)!r})
|
||||
import edf_convert, lote, preproceso
|
||||
p = Path({str(edf_path)!r}); nombre = p.stem
|
||||
with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()):
|
||||
conv = Path(tmp) / "c"; conv.mkdir()
|
||||
edf_convert.convertir(p, conv)
|
||||
npz = conv / nombre / f"{{nombre}}_signals.npz"; meta = conv / nombre / f"{{nombre}}_metadata.json"
|
||||
_, tabla = lote.excluidos_para_qc(npz, meta, {args['linea_hz']})
|
||||
tabla["estudio"] = nombre
|
||||
preproceso.procesar(conv / nombre, Path({str(out)!r}), tabla_val=tabla,
|
||||
linea_hz={args['linea_hz']}, pasa_altas={tuple(args['pasa_altas'])!r},
|
||||
pasa_bajas={args['pasa_bajas']}, metodo_red="interpolacion",
|
||||
ancho_red={args['ancho_red']})
|
||||
"""
|
||||
subprocess.run([sys.executable, "-W", "ignore", "-c", code], check=True, capture_output=True)
|
||||
with np.load(out / edf_path.stem / f"{edf_path.stem}_preproc.npz") as z:
|
||||
return {k: z[k] for k in z.files}
|
||||
|
||||
|
||||
@pytest.mark.skipif(not PREPROCESO.exists(), reason="submodule absent")
|
||||
@pytest.mark.parametrize("base", [DIRECTOR_CLUSTER, DIRECTOR_CLI], ids=lambda p: p.name)
|
||||
def test_legacy_equals_submodule(edf, tmp_path, base):
|
||||
plan = MODULE.plan_for(VAL.summarize(edf), base.to_dict())
|
||||
prep = MODULE.run(edf, plan)
|
||||
ref = _director_preproc(edf, tmp_path, MODULE.director_args(plan))
|
||||
cuero = [str(c) for c in ref["canales"]]
|
||||
for v in plan["variants"]:
|
||||
etq = f"{v['highpass_hz']:g}".replace(".", "")
|
||||
suf = {"average": "prom", "linked_ears": "orejas"}[v["reference"]]
|
||||
got = prep.variant(v["name"]).get_data(picks=cuero) * 1e6
|
||||
want = ref[f"signals_hp{etq}_{suf}_uV"].astype(np.float64).T
|
||||
np.testing.assert_allclose(got, want, rtol=1e-9, atol=1e-9)
|
||||
|
||||
|
||||
def test_contract_and_variants(edf):
|
||||
prep = MODULE.run(edf, MODULE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict()))
|
||||
check_preprocessed(prep)
|
||||
raw = prep.variant("hp05_prom")
|
||||
assert "P4" not in raw.ch_names # bursting electrode dropped
|
||||
assert set(raw.get_channel_types(picks=["LOC", "EKG"])) == {"eog", "ecg"}
|
||||
assert prep.plan["director"]["fs_hz"] == 250.0
|
||||
assert prep.windows.clean.mean() > 0.9
|
||||
|
||||
|
||||
def test_refuses_what_the_director_cannot_do():
|
||||
base = DIRECTOR_CLUSTER.to_dict()
|
||||
for change, msg in [
|
||||
(lambda d: d["steps"].__setitem__(1, {"kind": "zapline", "params": {}}), "zapline"),
|
||||
(lambda d: d["steps"][1]["params"].__setitem__("min_db", 3.0), "min_db"),
|
||||
(lambda d: d.__setitem__("bads", ["Fz"]), "manual bads"),
|
||||
]:
|
||||
d = json.loads(json.dumps(base))
|
||||
change(d)
|
||||
with pytest.raises(PlanNotSupported, match=msg):
|
||||
MODULE.director_args(d)
|
||||
|
||||
|
||||
def test_windows_from_qc():
|
||||
qc = [{"t_ini": 0.0, "t_fin": 4.0, "veredicto": "limpia", "montaje": True},
|
||||
{"t_ini": 4.0, "t_fin": 8.0, "veredicto": "limpia", "montaje": False},
|
||||
{"t_ini": 8.0, "t_fin": 12.0, "veredicto": "sospechosa", "montaje": False},
|
||||
{"t_ini": 12.0, "t_fin": 16.0, "veredicto": "HUECO", "montaje": False}]
|
||||
w = windows_from_qc(qc, 16.0, 4.0, 2.0)
|
||||
assert list(w.start_s) == [0, 2, 4, 6, 8, 10, 12]
|
||||
assert list(w.clean) == [False, False, True, False, False, False, False]
|
||||
assert list(w.gap) == [False, False, False, False, False, True, True]
|
||||
@@ -0,0 +1,52 @@
|
||||
"""PreprocessPlan: checks, round trip, hash."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from tea_modulo.preprocessing import (
|
||||
DIRECTOR_CLI,
|
||||
DIRECTOR_CLUSTER,
|
||||
PreprocessPlan,
|
||||
StepSpec,
|
||||
VariantSpec,
|
||||
)
|
||||
|
||||
|
||||
def test_round_trip_through_json():
|
||||
for plan in (DIRECTOR_CLUSTER, DIRECTOR_CLI):
|
||||
d = json.loads(json.dumps(plan.to_dict()))
|
||||
again = PreprocessPlan.from_dict(d)
|
||||
assert again == plan
|
||||
assert again.content_hash() == plan.content_hash() == d["hash"]
|
||||
|
||||
|
||||
def test_hash_ignores_reasons_and_bads_but_not_parameters():
|
||||
p = DIRECTOR_CLUSTER
|
||||
assert p.without("Fz", reason="test").content_hash() == p.content_hash()
|
||||
assert p.with_step("lowpass", hz=70).content_hash() != p.content_hash()
|
||||
|
||||
|
||||
def test_checks():
|
||||
with pytest.raises(ValueError, match="unknown step"):
|
||||
StepSpec("wavelet")
|
||||
with pytest.raises(ValueError, match="reference"):
|
||||
VariantSpec("x", 0.5, "ipsilateral")
|
||||
with pytest.raises(ValueError, match="below the lowpass"):
|
||||
DIRECTOR_CLUSTER.with_step("lowpass", hz=0.4)
|
||||
with pytest.raises(ValueError, match="one line-removal"):
|
||||
DIRECTOR_CLUSTER.with_step("zapline")
|
||||
with pytest.raises(ValueError, match="unknown plan keys"):
|
||||
PreprocessPlan.from_dict({**DIRECTOR_CLUSTER.to_dict(), "lowpas": 3})
|
||||
with pytest.raises(ValueError, match="reason"):
|
||||
DIRECTOR_CLUSTER.without("Fz", reason=" ")
|
||||
|
||||
|
||||
def test_route_differences_are_data():
|
||||
c, l = DIRECTOR_CLUSTER, DIRECTOR_CLI
|
||||
assert c.step("lowpass").params["hz"] == 100 and l.step("lowpass").params["hz"] == 45
|
||||
assert c.state.cutoffs == "hk1k" and l.state.cutoffs == "cohort"
|
||||
assert c.state.mask and not l.state.mask
|
||||
assert l.state.use_n3 and not c.state.use_n3
|
||||
Reference in New Issue
Block a user