From ae92ae8b17dea1c6bd47e20090a72b7935ea3ac8 Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Wed, 18 Nov 2026 21:44:52 -0600 Subject: [PATCH] gradient, legacy and modern - 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__, one baseline each. Legacy equals the submodule's cluster route exactly; modern within 0.01 of legacy on the synthetic study. --- pyproject.toml | 2 + .../biomarkers/gradient/__init__.py | 4 +- src/tea_modulo/biomarkers/gradient/api.py | 125 ++++++++++++++++++ .../legacy/biomarkers/gradient/__init__.py | 4 +- .../legacy/biomarkers/gradient/api.py | 112 ++++++++++++++++ tests/test_gradient.py | 86 ++++++++++++ 6 files changed, 331 insertions(+), 2 deletions(-) create mode 100644 src/tea_modulo/biomarkers/gradient/api.py create mode 100644 src/tea_modulo/legacy/biomarkers/gradient/api.py create mode 100644 tests/test_gradient.py diff --git a/pyproject.toml b/pyproject.toml index b3f4d74..584b6f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,7 @@ sleep_state = "tea_modulo.legacy.processes.sleep_state:MODULE" posterior_rhythm = "tea_modulo.legacy.biomarkers.posterior_rhythm:MODULE" spindle_detection = "tea_modulo.legacy.processes.spindle_detection:MODULE" spindles = "tea_modulo.legacy.biomarkers.spindles:MODULE" +gradient = "tea_modulo.legacy.biomarkers.gradient:MODULE" [project.entry-points."tea_modulo.modules"] validation = "tea_modulo.validation:MODULE" @@ -45,6 +46,7 @@ sleep_state = "tea_modulo.processes.sleep_state:MODULE" posterior_rhythm = "tea_modulo.biomarkers.posterior_rhythm:MODULE" spindle_detection = "tea_modulo.processes.spindle_detection:MODULE" spindles = "tea_modulo.biomarkers.spindles:MODULE" +gradient = "tea_modulo.biomarkers.gradient:MODULE" [project.entry-points."tea_modulo.executors"] legacy = "tea_modulo.legacy.executor:run_serial" diff --git a/src/tea_modulo/biomarkers/gradient/__init__.py b/src/tea_modulo/biomarkers/gradient/__init__.py index 10dd6a6..f6fa680 100644 --- a/src/tea_modulo/biomarkers/gradient/__init__.py +++ b/src/tea_modulo/biomarkers/gradient/__init__.py @@ -1 +1,3 @@ -"""Modern gradient: API pending.""" +from tea_modulo.biomarkers.gradient.api import MODULE, Gradient + +__all__ = ["MODULE", "Gradient"] diff --git a/src/tea_modulo/biomarkers/gradient/api.py b/src/tea_modulo/biomarkers/gradient/api.py new file mode 100644 index 0000000..a2468f3 --- /dev/null +++ b/src/tea_modulo/biomarkers/gradient/api.py @@ -0,0 +1,125 @@ +""" +Modern gradient (gradiente.analizar's definitions on MNE/SciPy): + + windows 4 s windows of each state ('sueno', 'somnolencia'), gap-free, at least 15 + power per channel and band, the median over windows of the band power of a + Hann periodogram (mne psd_array_welch, one segment per window) + slope Theil-Sen slope (scipy.stats.theilslopes) of log10 power against the + electrode's front-back coordinate (the director's 2D positions, +1 frontal) + +Features: gradient__ for delta, theta, alpha (8-13) and beta (13-30). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pandas as pd + +from tea_modulo.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS + +from . import _baseline + +POS_Y = {"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59, + "T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53, "Pz": -0.50, + "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95} # gradiente.POS (y) +BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alfa": (8, 13), "beta": (13, 30)} +STATES = ("sueno", "somnolencia") +MIN_WINDOWS = 15 +FEATURES = tuple(f"gradient_{b}_{s}" for s in STATES for b in BANDS) + + +def slopes(raw, starts, window_s=4.0) -> dict: + from mne.time_frequency import psd_array_welch + from scipy.stats import theilslopes + + out = {b: np.nan for b in BANDS} + if len(starts) < MIN_WINDOWS: + return out + fs = float(raw.info["sfreq"]) + chans = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg" and c in POS_Y] + n = int(window_s * fs) + x = raw.get_data(picks=chans).T * 1e6 + segs = [x[a:a + n].T for a in (int(round(t * fs)) for t in starts) + if a + n <= len(x) and np.isfinite(x[a:a + n]).all()] + if not segs: + return out + P, f = psd_array_welch(np.stack(segs), fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") + y = np.array([POS_Y[c] for c in chans]) + for b, (lo, hi) in BANDS.items(): + pw = np.median(P[..., (f >= lo) & (f < hi)].sum(axis=-1), axis=0) + v = np.log10(np.maximum(pw, 1e-30)) + ok = np.isfinite(v) + if ok.sum() >= 6: + out[b] = float(theilslopes(v[ok], y[ok])[0]) + return out + + +class Gradient: + name = "gradient" + version = "0.1.0" + contract_version = CONTRACT_VERSION + requires = ("sleep_state",) + features = FEATURES + impl = "modern" + + def __init__(self, variant="hp05_prom", baseline="curves", baseline_params=None, fitted=None): + self.variant = variant + self.baseline_name = baseline + self.baseline_params = dict(baseline_params or {}) + self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted + else {f: _baseline.make(baseline, **self.baseline_params) for f in FEATURES}) + self._fitted = fitted is not None + + def measure(self, study) -> dict: + lab, w = study.label("sleep_state").per_window, study.prep.windows + raw = study.prep.variant(self.variant) + out = {} + for s in STATES: + sl = slopes(raw, [float(t) for t, e in zip(w.start_s, lab) if e == s]) + out.update({f"gradient_{b}_{s}": float(v) for b, v in sl.items()}) + return out + + def train(self, data, ages_months=None): + if isinstance(data, pd.DataFrame): + t = data + else: + t = pd.DataFrame([self.measure(s) for s in data]) + t["age_months"] = list(ages_months) if ages_months is not None else [s.prep.age_months for s in data] + for f, b in self.baselines.items(): + b.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + self._fitted = True + return self + + def predict(self, data, age_months=None) -> pd.DataFrame: + if not self._fitted: + raise ValueError(f"{self.name}: train() before predict()") + if isinstance(data, pd.DataFrame): + t = data + else: + t = pd.DataFrame([self.measure(data)]) + t["age_months"] = [age_months if age_months is not None else data.prep.age_months] + a = t["age_months"].to_numpy(float) + parts = [] + for f, b in self.baselines.items(): + v = t[f].to_numpy(float) + outside, z = b.deviation(v, a) + parts.append(pd.DataFrame({"feature": f, "value": v, "age_months": a, "outside": outside, "z": z, + "baseline": b.name}, columns=list(DEVIATION_COLUMNS))) + return pd.concat(parts, ignore_index=True) + + def save(self, path): + Path(path, "params.json").write_text(json.dumps({"variant": self.variant, "baseline": self.baseline_name, + "baseline_params": self.baseline_params})) + Path(path, "baseline.json").write_text(json.dumps( + {f: b.to_dict() for f, b in self.baselines.items()} if self._fitted else None, default=float)) + + @classmethod + def load(cls, path): + p = json.loads(Path(path, "params.json").read_text()) + return cls(**p, fitted=json.loads(Path(path, "baseline.json").read_text())) + + +MODULE = Gradient() diff --git a/src/tea_modulo/legacy/biomarkers/gradient/__init__.py b/src/tea_modulo/legacy/biomarkers/gradient/__init__.py index cfb7558..c2e52d1 100644 --- a/src/tea_modulo/legacy/biomarkers/gradient/__init__.py +++ b/src/tea_modulo/legacy/biomarkers/gradient/__init__.py @@ -1 +1,3 @@ -"""Legacy gradient: director code vendored; API pending.""" +from tea_modulo.legacy.biomarkers.gradient.api import MODULE, LegacyGradient + +__all__ = ["MODULE", "LegacyGradient"] diff --git a/src/tea_modulo/legacy/biomarkers/gradient/api.py b/src/tea_modulo/legacy/biomarkers/gradient/api.py new file mode 100644 index 0000000..2622461 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/gradient/api.py @@ -0,0 +1,112 @@ +""" +Legacy gradient: the cluster route's anteroposterior gradient (medidas_director.gradiente +on gradiente.analizar, vendored unchanged) in the windows labelled 'sueno' and +'somnolencia' (pipeline.analizar_director @ 7dfc641). + +Features: the Theil-Sen slope of log10 band power against the electrode's +front-back coordinate (gradiente.POS, +1 frontal, -1 occipital) for delta, +theta, alpha and beta, in each state: gradient__. NaN with fewer +than 15 windows of that state. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pandas as pd + +from tea_modulo.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS + +from . import _adapter, _baseline + +DIRECTOR_COMMIT = "7dfc641" +BANDS = ("delta", "theta", "alfa", "beta") # pipeline.BANDAS_GRADIENTE +STATES = ("sueno", "somnolencia") +MIN_WINDOWS = 15 +FEATURES = tuple(f"gradient_{b}_{s}" for s in STATES for b in BANDS) + + +def gradiente(est, inicios, g, min_ventanas=MIN_WINDOWS) -> dict: + """medidas_director.gradiente (verbatim but for `est`).""" + if len(inicios) < min_ventanas: + return {"n_ventanas": len(inicios), "motivo": "pocas ventanas"} + fila, _, n = g.analizar(est, inicios) + if fila is None: + return {"n_ventanas": n, "motivo": "sin potencias"} + return {**fila, "motivo": ""} + + +class LegacyGradient: + name = "gradient" + version = f"0.1.0+director.{DIRECTOR_COMMIT}" + contract_version = CONTRACT_VERSION + requires = ("sleep_state",) + features = FEATURES + impl = "legacy" + + def __init__(self, variant="hp05_prom", baseline="curves", baseline_params=None, fitted=None): + self.variant = variant + self.baseline_name = baseline + self.baseline_params = dict(baseline_params or {}) + self.baselines = ({f: _baseline.from_dict(d) for f, d in fitted.items()} if fitted + else {f: _baseline.make(baseline, **self.baseline_params) for f in FEATURES}) + self._fitted = fitted is not None + + def detail(self, study) -> dict: + from ._director import eeg_io + from ._director import gradiente as g + + lab, w = study.label("sleep_state").per_window, study.prep.windows + out = {} + with _adapter.estudio(study.prep, self.variant, eeg_io) as est: + for s in STATES: + out[s] = gradiente(est, [float(t) for t, e in zip(w.start_s, lab) if e == s], g) + return out + + def measure(self, study) -> dict: + d = self.detail(study) + return {f"gradient_{b}_{s}": float(d[s].get(f"pendiente_{b}", float("nan"))) + for s in STATES for b in BANDS} + + def train(self, data, ages_months=None): + if isinstance(data, pd.DataFrame): + t = data + else: + t = pd.DataFrame([self.measure(s) for s in data]) + t["age_months"] = list(ages_months) if ages_months is not None else [s.prep.age_months for s in data] + for f, b in self.baselines.items(): + b.fit(t[f].to_numpy(float), t["age_months"].to_numpy(float)) + self._fitted = True + return self + + def predict(self, data, age_months=None) -> pd.DataFrame: + if not self._fitted: + raise ValueError(f"{self.name}: train() before predict()") + if isinstance(data, pd.DataFrame): + t = data + else: + t = pd.DataFrame([self.measure(data)]) + t["age_months"] = [age_months if age_months is not None else data.prep.age_months] + a = t["age_months"].to_numpy(float) + parts = [] + for f, b in self.baselines.items(): + v = t[f].to_numpy(float) + outside, z = b.deviation(v, a) + parts.append(pd.DataFrame({"feature": f, "value": v, "age_months": a, "outside": outside, "z": z, + "baseline": b.name}, columns=list(DEVIATION_COLUMNS))) + return pd.concat(parts, ignore_index=True) + + def save(self, path): + Path(path, "params.json").write_text(json.dumps({"variant": self.variant, "baseline": self.baseline_name, + "baseline_params": self.baseline_params})) + Path(path, "baseline.json").write_text(json.dumps( + {f: b.to_dict() for f, b in self.baselines.items()} if self._fitted else None, default=float)) + + @classmethod + def load(cls, path): + p = json.loads(Path(path, "params.json").read_text()) + return cls(**p, fitted=json.loads(Path(path, "baseline.json").read_text())) + + +MODULE = LegacyGradient() diff --git a/tests/test_gradient.py b/tests/test_gradient.py new file mode 100644 index 0000000..2aca267 --- /dev/null +++ b/tests/test_gradient.py @@ -0,0 +1,86 @@ +"""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])