Files
tea/src/tea_modulo/legacy/preprocessing/api.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

191 lines
9.1 KiB
Python

"""
Legacy preprocessing: the director's `preproceso.procesar` (vendored unchanged
in `_director/`) behind the `Preprocessor` protocol.
Run order, as in `un_estudio.procesar` step 5:
edf_convert.convertir -> lote.excluidos_para_qc (validation table)
-> lote.qc_estudio (4 s window QC, for the window table)
-> preproceso.procesar(tabla_val, linea_hz, pasa_altas, pasa_bajas, ancho_red)
The plan dict is mapped onto the director's parameters. What his code cannot
do is refused with a message (never silently ignored):
- `zapline`, a notch `min_db` other than his NOTCH_MIN_DB (6 dB);
- manual `bads` (his code decides the channels);
- a variant whose reference he does not write.
His code always writes every high-pass x reference he computes; only the
variants named in the plan are returned.
"""
from __future__ import annotations
import contextlib
import io
import json
import tempfile
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from tea_modulo.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of
DIRECTOR_COMMIT = "7dfc641"
_SUFFIX = {"average": "prom", "linked_ears": "orejas"}
class PlanNotSupported(ValueError):
"""The plan asks for something the director's code cannot do."""
class LegacyPreprocessing:
name = "preprocessing"
version = f"0.1.0+director.{DIRECTOR_COMMIT}"
contract_version = CONTRACT_VERSION
impl = "legacy"
# ---------------------------------------------------------------- plan
def plan_for(self, summary: ValidationSummary, base: Mapping[str, Any]) -> dict:
"""The base plan for this study: the director decides bads and notch at run time,
so only the ear variants are dropped when the ears are not usable."""
plan = json.loads(json.dumps(dict(base)))
if not summary.ears_usable:
plan["variants"] = [v for v in plan["variants"] if v["reference"] != "linked_ears"]
plan.setdefault("reasons", {})["variants"] = "ears not usable: linked-ears variants dropped"
return plan
def director_args(self, plan: Mapping[str, Any]) -> dict:
"""The plan as preproceso.procesar arguments; refuses what it cannot honour."""
from ._director import preproceso
if plan.get("schema") != 1:
raise PlanNotSupported(f"plan schema {plan.get('schema')} is not supported")
steps = {s["kind"]: s.get("params", {}) for s in plan.get("steps", [])}
if "zapline" in steps:
raise PlanNotSupported("the director's code has no zapline step")
notch = steps.get("interpolated_notch")
if notch is None:
raise PlanNotSupported("the director's code always evaluates the interpolated notch")
if float(notch.get("min_db", preproceso.NOTCH_MIN_DB)) != preproceso.NOTCH_MIN_DB:
raise PlanNotSupported(f"notch min_db is fixed at {preproceso.NOTCH_MIN_DB} dB "
f"in the director's code")
if plan.get("bads"):
raise PlanNotSupported("manual bads: the director's code decides the channels")
if "lowpass" not in steps:
raise PlanNotSupported("the director's code always low-passes")
refs = {v["reference"] for v in plan["variants"]}
if not refs <= set(_SUFFIX):
raise PlanNotSupported(f"references {refs - set(_SUFFIX)} are not written by the director")
return {
"linea_hz": float(plan.get("line_hz", 60.0)),
"pasa_altas": tuple(sorted({float(v["highpass_hz"]) for v in plan["variants"]})),
"pasa_bajas": float(steps["lowpass"]["hz"]),
"metodo_red": "interpolacion",
"ancho_red": float(notch.get("width_hz", 1.5)),
}
# ---------------------------------------------------------------- run
def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed:
import mne
from ._director import edf_convert, lote, preproceso
args = self.director_args(plan)
edf_path = Path(edf_path)
nombre = edf_path.stem
with tempfile.TemporaryDirectory(prefix="tea_legacy_pre_") as tmp, \
contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings():
warnings.simplefilter("ignore")
conv, pre = Path(tmp) / "convertidos", Path(tmp) / "preprocesado"
conv.mkdir()
edf_convert.convertir(edf_path, conv)
npz = conv / nombre / f"{nombre}_signals.npz"
meta = conv / nombre / f"{nombre}_metadata.json"
excluir, tabla = lote.excluidos_para_qc(npz, meta, args["linea_hz"])
qc = lote.qc_estudio(npz, meta, linea_hz=args["linea_hz"], nombre_estudio=nombre,
excluir=excluir)
tabla["estudio"] = nombre
fila = preproceso.procesar(conv / nombre, pre, tabla_val=tabla, **args)
with np.load(pre / nombre / f"{nombre}_preproc.npz") as z:
arrays = {k: z[k] for k in z.files}
proc = json.loads(str(arrays["procedencia"]))
fs = float(arrays["fs_hz"])
cuero = [str(c) for c in arrays["canales"]]
aux = [str(c) for c in arrays.get("canales_aux", np.array([]))]
anns = _annotations(edf_path)
variants = {}
for v in plan["variants"]:
etq = f"{float(v['highpass_hz']):g}".replace(".", "")
key = f"signals_hp{etq}_{_SUFFIX[v['reference']]}_uV"
if key not in arrays:
raise PlanNotSupported(f"variant {v['name']}: the director did not write {key} "
f"(ear reference needs both ears usable)")
x = arrays[key].astype(np.float64)
names, types = list(cuero), ["eeg"] * len(cuero)
ak = f"aux_hp{etq}_uV"
if aux and ak in arrays:
x = np.hstack([x, arrays[ak].astype(np.float64)])
names += aux
types += ["ecg" if a == "EKG" else "eog" for a in aux]
info = mne.create_info(names, fs, types)
raw = mne.io.RawArray(x.T * 1e-6, info, verbose="error")
raw.set_annotations(anns)
variants[v["name"]] = raw
n = next(iter(variants.values())).n_times
windows = windows_from_qc(qc.get("_por_ventana", []), n / fs,
float(plan.get("window_s", 4.0)), float(plan.get("step_s", 2.0)))
plan_out = {**dict(plan), "director": {**{k: v for k, v in fila.items() if k != "archivo"},
"args": {**args, "pasa_altas": list(args["pasa_altas"])}}}
return Preprocessed(variants=variants, windows=windows, age_months=age_months,
plan=plan_out, plan_hash=str(plan.get("hash", "")),
source_sha256=sha256_of(edf_path),
quality_spans=spans_from_qc(qc.get("_por_ventana", [])))
def spans_from_qc(qc_windows) -> pd.DataFrame:
"""The director's 4 s QC windows that are not clean: veredicto != 'limpia' or in the
set-up ('montaje'), as in biomarcadores senal._mascara_excluir."""
rows = [{"onset_s": float(v["t_ini"]), "duration_s": float(v["t_fin"]) - float(v["t_ini"]),
"reason": "montaje" if v.get("montaje", False) and v.get("veredicto") == "limpia"
else str(v.get("veredicto"))}
for v in qc_windows if v.get("veredicto") != "limpia" or v.get("montaje", False)]
return pd.DataFrame(rows, columns=["onset_s", "duration_s", "reason"]).astype(
{"onset_s": float, "duration_s": float, "reason": str})
def windows_from_qc(qc_windows, duration_s: float, window_s: float, step_s: float) -> pd.DataFrame:
"""
The analysis window grid (window_s / step_s) with flags from the director's
4 s back-to-back QC: clean if every QC window it overlaps is 'limpia' and
outside the set-up ('montaje'); gap if any overlapped QC window is 'HUECO'.
Windows that reach past the last QC window are not clean.
"""
starts = np.arange(0.0, duration_s - window_s + 1e-9, step_s)
q = pd.DataFrame(qc_windows) if qc_windows else pd.DataFrame(
columns=["t_ini", "t_fin", "veredicto", "montaje"])
clean, gap = [], []
for s in starts:
e = s + window_s
o = q[(q.t_ini < e) & (q.t_fin > s)] if len(q) else q
covered = len(o) > 0 and float(o.t_fin.max()) >= e - 1e-6 and float(o.t_ini.min()) <= s + 1e-6
clean.append(bool(covered and (o.veredicto == "limpia").all()
and not o.get("montaje", pd.Series(False, index=o.index)).any()))
gap.append(bool(len(o) and (o.veredicto == "HUECO").any()))
return pd.DataFrame({"start_s": starts, "end_s": starts + window_s,
"clean": np.array(clean, bool), "gap": np.array(gap, bool)})
def _annotations(edf_path):
"""Every EDF+ annotation with its exact onset and duration, as edf_convert reads them
(the director keeps BAD_ACQ_SKIP among his events too)."""
import mne
a = mne.read_annotations(edf_path)
return mne.Annotations(list(a.onset), list(a.duration), list(a.description))
MODULE = LegacyPreprocessing()