From 1f8793aacba34762a325cd2b0a7d8fdaf7f17dae Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Wed, 18 Nov 2026 20:53:52 -0600 Subject: [PATCH] modern annotation_mask, sleep_state and posterior_rhythm - processes.annotation_mask: the director's state words and interval rules on the EDF+ annotations (MNE), window dominant state and 'mixta'. - processes.sleep_state: vigilancia's features from batched Hann periodograms (mne psd_array_welch), depth index, HK1K cut-offs or cohort reference + KMeans (scikit-learn) after train(). - biomarkers.posterior_rhythm: Welch of the wake windows (MNE), 1/f-fitted dominant peak, median of O1 O2 P3 P4; private copy of the baselines. - Registered as the modern modules; Pipeline.default("modern") now runs the full slice. On a synthetic study: annotation states and sleep-state labels identical to legacy, rhythm equal (6.5 Hz); contract suites and cohort cut-offs tested. --- pyproject.toml | 3 + src/tea_modulo/biomarkers/__init__.py | 1 + .../biomarkers/posterior_rhythm/__init__.py | 3 + .../biomarkers/posterior_rhythm/_baseline.py | 241 +++++++++++++++++ .../biomarkers/posterior_rhythm/api.py | 140 ++++++++++ src/tea_modulo/processes/__init__.py | 1 + .../processes/annotation_mask/__init__.py | 3 + .../processes/annotation_mask/api.py | 136 ++++++++++ .../processes/sleep_state/__init__.py | 3 + src/tea_modulo/processes/sleep_state/api.py | 242 ++++++++++++++++++ .../sleep_state/data/estado_hk1k.json | 47 ++++ tests/test_modern_slice.py | 65 +++++ 12 files changed, 885 insertions(+) create mode 100644 src/tea_modulo/biomarkers/__init__.py create mode 100644 src/tea_modulo/biomarkers/posterior_rhythm/__init__.py create mode 100644 src/tea_modulo/biomarkers/posterior_rhythm/_baseline.py create mode 100644 src/tea_modulo/biomarkers/posterior_rhythm/api.py create mode 100644 src/tea_modulo/processes/__init__.py create mode 100644 src/tea_modulo/processes/annotation_mask/__init__.py create mode 100644 src/tea_modulo/processes/annotation_mask/api.py create mode 100644 src/tea_modulo/processes/sleep_state/__init__.py create mode 100644 src/tea_modulo/processes/sleep_state/api.py create mode 100644 src/tea_modulo/processes/sleep_state/data/estado_hk1k.json create mode 100644 tests/test_modern_slice.py diff --git a/pyproject.toml b/pyproject.toml index aaab55f..e1a5200 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,9 @@ posterior_rhythm = "tea_modulo.legacy.biomarkers.posterior_rhythm:MODULE" [project.entry-points."tea_modulo.modules"] validation = "tea_modulo.validation:MODULE" preprocessing = "tea_modulo.preprocessing:MODULE" +annotation_mask = "tea_modulo.processes.annotation_mask:MODULE" +sleep_state = "tea_modulo.processes.sleep_state:MODULE" +posterior_rhythm = "tea_modulo.biomarkers.posterior_rhythm:MODULE" [project.entry-points."tea_modulo.executors"] legacy = "tea_modulo.legacy.executor:run_serial" diff --git a/src/tea_modulo/biomarkers/__init__.py b/src/tea_modulo/biomarkers/__init__.py new file mode 100644 index 0000000..192657a --- /dev/null +++ b/src/tea_modulo/biomarkers/__init__.py @@ -0,0 +1 @@ +"""biomarkers: one independent module each.""" diff --git a/src/tea_modulo/biomarkers/posterior_rhythm/__init__.py b/src/tea_modulo/biomarkers/posterior_rhythm/__init__.py new file mode 100644 index 0000000..55136de --- /dev/null +++ b/src/tea_modulo/biomarkers/posterior_rhythm/__init__.py @@ -0,0 +1,3 @@ +from tea_modulo.biomarkers.posterior_rhythm.api import MODULE, PosteriorRhythm + +__all__ = ["MODULE", "PosteriorRhythm"] diff --git a/src/tea_modulo/biomarkers/posterior_rhythm/_baseline.py b/src/tea_modulo/biomarkers/posterior_rhythm/_baseline.py new file mode 100644 index 0000000..f70c368 --- /dev/null +++ b/src/tea_modulo/biomarkers/posterior_rhythm/_baseline.py @@ -0,0 +1,241 @@ +""" +Baselines, ported as they are (private copy; every biomarker owns one). + +Functions copied verbatim: + - biomarcadores-tea/biomarcadores/curvas.py @ 7dfc641: CUANTILES, rejilla, + cuantil_ponderado, ajustar, en_edad, z_y_posicion + - codigo/perfil_alteraciones.py @ c7a4736: MIN_CONTROLES_BLOQUE, bordes_edad, + z_por_bloques, marcar_fuera (the cut-offs = p5/p95 of the controls' own z, + as in construir_perfil.mete), with BLOQUES from codigo/curva_desarrollo.py + +Two classes wrap them with fit / deviation / to_dict / from_dict: + CentileCurves outside: below p5 or above p95 of the age curve; z = z_robusto + AgeBlockZ outside: z beyond the controls' z p5 / p95; z = (x - median) / MAD +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +# ------------------------------------------------------------------ curvas.py (verbatim) +CUANTILES = {"p5": 0.05, "p25": 0.25, "mediana": 0.5, "p75": 0.75, "p95": 0.95} + + +def rejilla(edad_min=1.0, edad_max=216.0, puntos=120) -> np.ndarray: + """Edades (meses) espaciadas en escala log.""" + return np.exp(np.linspace(np.log(edad_min), np.log(edad_max), puntos)) + + +def cuantil_ponderado(x: np.ndarray, w: np.ndarray, q: float) -> float: + """Cuantil con pesos (interpolando entre los puntos medios de cada peso acumulado).""" + o = np.argsort(x) + x, w = x[o], w[o] + c = (np.cumsum(w) - 0.5 * w) / w.sum() + return float(np.interp(q, c, x)) + + +def ajustar(valores, edades_meses, ancho_log=0.2, n_min=30, edades=None) -> pd.DataFrame: + """Curva de percentiles: una fila por edad de la rejilla (edad_meses, n_efectivo, p5…p95).""" + v = np.asarray(valores, dtype=float) + e = np.asarray(edades_meses, dtype=float) + ok = np.isfinite(v) & np.isfinite(e) & (e > 0) + v, le = v[ok], np.log(e[ok]) + edades = rejilla() if edades is None else np.asarray(edades, dtype=float) + filas = [] + for a in edades: + w = np.exp(-0.5 * ((le - np.log(a)) / ancho_log) ** 2) + n_ef = w.sum() ** 2 / (w ** 2).sum() if w.sum() > 0 else 0.0 + fila = {"edad_meses": round(float(a), 3), "n_efectivo": round(float(n_ef), 1)} + dentro = len(le) and le.min() <= np.log(a) <= le.max() + for nom, q in CUANTILES.items(): + fila[nom] = (round(cuantil_ponderado(v, w, q), 4) if n_ef >= n_min and dentro + else np.nan) + filas.append(fila) + return pd.DataFrame(filas) + + +def en_edad(edad_meses: float, curva: pd.DataFrame) -> dict | None: + """p5…p95 a una edad exacta (interpolados en log(edad)); None si la curva no la cubre.""" + c = curva.dropna(subset=list(CUANTILES)) + if not len(c) or not np.isfinite(edad_meses) or edad_meses <= 0: + return None + la, lx = np.log(edad_meses), np.log(c.edad_meses.to_numpy()) + if la < lx.min() or la > lx.max(): + return None + return {nom: float(np.interp(la, lx, c[nom].to_numpy())) for nom in CUANTILES} + + +def z_y_posicion(valores, edades_meses, curva: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]: + """`z_robusto` y `posicion` de muchos valores a la vez (mismo resultado, sin bucle por fila).""" + v = np.asarray(valores, dtype=float) + e = np.asarray(edades_meses, dtype=float) + z = np.full(v.shape, np.nan) + pos = np.full(v.shape, "sin referencia", dtype=object) + c = curva.dropna(subset=list(CUANTILES)) + if not len(c): + return z, pos + lx = np.log(c.edad_meses.to_numpy()) + with np.errstate(divide="ignore", invalid="ignore"): + la = np.where(e > 0, np.log(np.where(e > 0, e, 1.0)), np.nan) + ok = np.isfinite(v) & np.isfinite(la) & (la >= lx.min()) & (la <= lx.max()) + q = {k: np.interp(la, lx, c[k].to_numpy()) for k in CUANTILES} + lado = np.where(v < q["mediana"], q["mediana"] - q["p5"], q["p95"] - q["mediana"]) + zz = (v - q["mediana"]) / (lado / 1.645) + z[ok] = np.where(lado[ok] > 0, zz[ok], np.nan) + pos[ok] = np.where(v[ok] < q["p5"][ok], "bajo p5", + np.where(v[ok] > q["p95"][ok], "sobre p95", "dentro")) + return z, pos + + +# ------------------------------------------------------------------ perfil_alteraciones.py (verbatim) +BLOQUES = (2, 4, 6, 9, 12, 18, 24, 36, 48, 60, 84, 120, 192) # curva_desarrollo.BLOQUES +MIN_CONTROLES_BLOQUE = 12 + + +def bordes_edad(edad_min, edad_max): + """Bloques de la curva de desarrollo recortados al rango pedido.""" + b = [x for x in BLOQUES if edad_min < x < edad_max] + return [edad_min] + b + [edad_max] + + +def z_por_bloques(xT, edadT, xC, edadC, bordes): + """ + z de cada caso contra la mediana y el MAD de los controles de su bloque + de edad, y el z de los propios controles para sacar los cortes. + + Un bloque con menos de MIN_CONTROLES_BLOQUE controles usa la normativa + del rango completo, y se avisa: una banda de 8 controles es una línea + firme dibujada sobre nada. + """ + xT = np.asarray(xT, dtype=float) + xC = np.asarray(xC, dtype=float) + bT = np.digitize(np.asarray(edadT, dtype=float), bordes[1:-1]) + bC = np.digitize(np.asarray(edadC, dtype=float), bordes[1:-1]) + okC = np.isfinite(xC) + med_g = float(np.nanmedian(xC)) + mad_g = float(1.4826 * np.nanmedian(np.abs(xC - med_g))) or np.nan + + zT = np.full(len(xT), np.nan) + zC = np.full(len(xC), np.nan) + for b in range(len(bordes) - 1): + enC = okC & (bC == b) + if enC.sum() >= MIN_CONTROLES_BLOQUE: + med = float(np.median(xC[enC])) + mad = float(1.4826 * np.median(np.abs(xC[enC] - med))) + else: + med, mad = med_g, mad_g + if not np.isfinite(mad) or mad == 0: + continue + zT[bT == b] = (xT[bT == b] - med) / mad + zC[enC] = (xC[enC] - med) / mad + return zT, zC + + +def marcar_fuera(P, cortes): + F = pd.DataFrame(0, index=P.index, + columns=[f"fuera_{c}" for c in P.columns]) + for c in P.columns: + lo, hi = cortes[c] + F.loc[P[c] < lo, f"fuera_{c}"] = -1 + F.loc[P[c] > hi, f"fuera_{c}"] = 1 + return F + + +# ------------------------------------------------------------------ wrappers +class CentileCurves: + name = "curves" + + def __init__(self, ancho_log=0.2, n_min=30, curva=None): + self.ancho_log = ancho_log + self.n_min = n_min + self.curva = curva + + def fit(self, values, ages_months): + self.curva = ajustar(values, ages_months, ancho_log=self.ancho_log, n_min=self.n_min) + return self + + def deviation(self, values, ages_months): + z, pos = z_y_posicion(values, ages_months, self.curva) + outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0)) + return outside.astype(int), z + + def to_dict(self): + return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min, + "curva": self.curva.replace({np.nan: None}).to_dict("list")} + + @classmethod + def from_dict(cls, d): + curva = pd.DataFrame(d["curva"]).astype(float) + return cls(d["ancho_log"], d["n_min"], curva) + + +class AgeBlockZ: + name = "age_blocks" + + def __init__(self, edad_min=12.0, edad_max=60.0, state=None): + self.edad_min = edad_min + self.edad_max = edad_max + self.state = state + + def fit(self, values, ages_months): + v = np.asarray(values, float) + e = np.asarray(ages_months, float) + keep = (e >= self.edad_min) & (e <= self.edad_max) # perfil_alteraciones.filtra + v, e = v[keep], e[keep] + bordes = bordes_edad(self.edad_min, self.edad_max) + _, zC = z_por_bloques(v, e, v, e, bordes) + zC = zC[np.isfinite(zC)] + blocks = [] + bC = np.digitize(e, bordes[1:-1]) + ok = np.isfinite(v) + med_g = float(np.nanmedian(v)) + mad_g = float(1.4826 * np.nanmedian(np.abs(v - med_g))) or np.nan + for b in range(len(bordes) - 1): + en = ok & (bC == b) + if en.sum() >= MIN_CONTROLES_BLOQUE: + med = float(np.median(v[en])) + blocks.append({"median": med, "mad": float(1.4826 * np.median(np.abs(v[en] - med))), + "n": int(en.sum())}) + else: + blocks.append({"median": med_g, "mad": mad_g, "n": int(en.sum()), "fallback": True}) + self.state = {"bordes": bordes, "blocks": blocks, + "cortes": [float(np.percentile(zC, 5)), float(np.percentile(zC, 95))] + if len(zC) else [np.nan, np.nan], "n": int(len(v))} + return self + + def deviation(self, values, ages_months): + v = np.asarray(values, float) + e = np.asarray(ages_months, float) + bordes = self.state["bordes"] + b = np.digitize(e, bordes[1:-1]) + z = np.full(len(v), np.nan) + for i, (x, k) in enumerate(zip(v, b)): + blk = self.state["blocks"][k] + if np.isfinite(blk["mad"]) and blk["mad"] != 0: + z[i] = (x - blk["median"]) / blk["mad"] + P = pd.DataFrame({"m": z}) + F = marcar_fuera(P, {"m": tuple(self.state["cortes"])}) + return F["fuera_m"].to_numpy().astype(int), z + + def to_dict(self): + return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max, + "state": self.state} + + @classmethod + def from_dict(cls, d): + return cls(d["edad_min"], d["edad_max"], d["state"]) + + +BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ} + + +def make(name, **params): + try: + return BASELINES[name](**params) + except KeyError: + raise ValueError(f"unknown baseline {name!r}; one of {', '.join(BASELINES)}") from None + + +def from_dict(d): + return BASELINES[d["name"]].from_dict(d) diff --git a/src/tea_modulo/biomarkers/posterior_rhythm/api.py b/src/tea_modulo/biomarkers/posterior_rhythm/api.py new file mode 100644 index 0000000..b8c1f4e --- /dev/null +++ b/src/tea_modulo/biomarkers/posterior_rhythm/api.py @@ -0,0 +1,140 @@ +""" +Modern posterior_rhythm (the cluster route's measure, medidas_director.ritmo): + + windows 4 s windows labelled 'vigilia' by sleep_state, gap-free (at least 15) + PSD mean Hann periodogram of those windows per channel (mne psd_array_welch, + one segment per window, mean removed) — ritmo.psd_de_ventanas + peak largest peak 3-14 Hz over a 1/f line fitted on 1.5-45 Hz without 4-16 Hz, + at least 1.5 dB and not at the band edge — eeg_io.pico_dominante + value median over O1 O2 P3 P4 with a peak, if at least 2 of them +""" + +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 + +POSTERIOR = ("O1", "O2", "P3", "P4") +MIN_WINDOWS = 15 +MIN_CHANNELS = 2 +WINDOW_S = 4.0 + + +def dominant_peak(f, P, band=(3.0, 14.0), fit=(1.5, 45.0), exclude=(4.0, 16.0), min_db=1.5): + val = (f >= fit[0]) & (f <= fit[1]) & (P > 0) + bg = val & ~((f >= exclude[0]) & (f <= exclude[1])) + if bg.sum() < 5: + return np.nan, np.nan, False + coef = np.polyfit(np.log10(f[bg]), np.log10(P[bg]), 1) + resid = 10 * (np.log10(P[val]) - np.polyval(coef, np.log10(f[val]))) + fv = f[val] + sel = (fv >= band[0]) & (fv <= band[1]) + if not sel.any(): + return np.nan, np.nan, False + i = int(np.argmax(resid[sel])) + peak, prom = float(fv[sel][i]), float(resid[sel][i]) + found = bool(prom >= min_db and 0 < i < int(sel.sum()) - 1) + return (peak if found else np.nan), prom, found + + +def rhythm(raw, starts, min_windows=MIN_WINDOWS) -> dict: + from mne.time_frequency import psd_array_welch + + out = {"rhythm_hz": np.nan, "n_channels": 0, "prominence_db": np.nan, "n_windows": len(starts), + "reason": ""} + if len(starts) < min_windows: + out["reason"] = "too few wake windows" + return out + fs = float(raw.info["sfreq"]) + chans = [c for c in POSTERIOR if c in raw.ch_names] + n = int(round(WINDOW_S * fs)) + x = raw.get_data(picks=chans).T * 1e6 if chans else np.empty((raw.n_times, 0)) + segs = [] + for t0 in starts: + a = int(round(float(t0) * fs)) + if a >= 0 and a + n <= len(x) and np.isfinite(x[a:a + n]).all(): + segs.append(x[a:a + n].T) + peaks, proms = [], [] + if segs and chans: + P, f = psd_array_welch(np.stack(segs), fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") + for k in range(len(chans)): + pk, pr, ok = dominant_peak(f, P[:, k].mean(axis=0)) + if ok: + peaks.append(pk) + proms.append(pr) + out["n_channels"] = len(peaks) + if len(peaks) >= MIN_CHANNELS: + out["rhythm_hz"], out["prominence_db"] = float(np.median(peaks)), float(np.median(proms)) + else: + out["reason"] = "no peak in two posterior channels" + return out + + +class PosteriorRhythm: + name = "posterior_rhythm" + version = "0.1.0" + contract_version = CONTRACT_VERSION + requires = ("sleep_state",) + features = ("posterior_rhythm_hz",) + impl = "modern" + + def __init__(self, variant="hp05_prom", state="vigilia", baseline="curves", baseline_params=None, + fitted=None): + self.variant = variant + self.state = state + self.baseline_name = baseline + self.baseline_params = dict(baseline_params or {}) + self.baseline = _baseline.from_dict(fitted) if fitted else _baseline.make(baseline, **self.baseline_params) + self._fitted = fitted is not None + + def detail(self, study) -> dict: + lab, w = study.label("sleep_state").per_window, study.prep.windows + return rhythm(study.prep.variant(self.variant), [float(s) for s, e in zip(w.start_s, lab) if e == self.state]) + + def measure(self, study) -> dict: + return {"posterior_rhythm_hz": float(self.detail(study)["rhythm_hz"])} + + 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] + self.baseline.fit(t["posterior_rhythm_hz"].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] + v, a = t["posterior_rhythm_hz"].to_numpy(float), t["age_months"].to_numpy(float) + outside, z = self.baseline.deviation(v, a) + return pd.DataFrame({"feature": "posterior_rhythm_hz", "value": v, "age_months": a, "outside": outside, + "z": z, "baseline": self.baseline.name}, columns=list(DEVIATION_COLUMNS)) + + def save(self, path): + Path(path, "params.json").write_text(json.dumps( + {"variant": self.variant, "state": self.state, "baseline": self.baseline_name, + "baseline_params": self.baseline_params})) + Path(path, "baseline.json").write_text(json.dumps(self.baseline.to_dict() 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 = PosteriorRhythm() diff --git a/src/tea_modulo/processes/__init__.py b/src/tea_modulo/processes/__init__.py new file mode 100644 index 0000000..b299e07 --- /dev/null +++ b/src/tea_modulo/processes/__init__.py @@ -0,0 +1 @@ +"""processes: one independent module each.""" diff --git a/src/tea_modulo/processes/annotation_mask/__init__.py b/src/tea_modulo/processes/annotation_mask/__init__.py new file mode 100644 index 0000000..39c30f5 --- /dev/null +++ b/src/tea_modulo/processes/annotation_mask/__init__.py @@ -0,0 +1,3 @@ +from tea_modulo.processes.annotation_mask.api import MODULE, AnnotationMask + +__all__ = ["MODULE", "AnnotationMask"] diff --git a/src/tea_modulo/processes/annotation_mask/api.py b/src/tea_modulo/processes/annotation_mask/api.py new file mode 100644 index 0000000..da8d54f --- /dev/null +++ b/src/tea_modulo/processes/annotation_mask/api.py @@ -0,0 +1,136 @@ +""" +Modern annotation_mask: annotated states from the EDF+ annotations (MNE). + +Rules ported from the director (eeg_io._PALABRAS_ESTADO, _estado_de_texto, +intervalos_estado; seleccion.estado_de_ventana, EXCLUIDOS, PROVOCACION): + - a note's state is the first state whose words appear in its text + (lower case, accents removed, ñ kept), as substrings, like the director; + - a note lasts until its end if it has a duration, otherwise 60 s or until + the next note with a state, whichever comes first; pieces under 1 s are dropped; + - gaps between notes are 'no_marcado'; + - each window takes its dominant state; it is 'mixta' when the dominant one + covers less than 80% of the window. +""" + +from __future__ import annotations + +import json +import unicodedata +from pathlib import Path + +import pandas as pd + +from tea_modulo.contracts import CONTRACT_VERSION, Labels + +WORDS = [ + ("fotica", ("fotic", "photic", "flash", "estimulacion luminosa")), + ("HV", ("hv", "hipervent", "hypervent")), + ("ojos_abiertos", ("ojos abiertos", "eyes open", "oa")), + ("ojos_cerrados", ("ojos cerrados", "eyes closed", "oc")), + ("sueno", ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii", "n1", "n2", "n3")), + ("despertar", ("despierta", "despierto", "arousal", "vigilia")), + ("llanto", ("llanto", "llora", "cry")), + ("movimiento", ("movimiento", "movement", "artefacto de movimiento")), + ("alimentacion", ("come", "alimenta", "biberon", "lactancia")), +] +EXCLUDED = ("llanto", "movimiento", "desconexion") +PROVOCATION = ("fotica", "HV") +NOTE_S = 60.0 +MIN_S = 1.0 + + +def normalize(s: str) -> str: + s = str(s or "").replace("ñ", "\x00").replace("Ñ", "\x01") + s = "".join(c for c in unicodedata.normalize("NFD", s) if unicodedata.category(c) != "Mn") + return s.replace("\x00", "ñ").replace("\x01", "Ñ").lower().strip() + + +def state_of(text: str) -> str | None: + t = normalize(text) + for state, words in WORDS: + if any(w in t for w in words): + return state + return None + + +def intervals(annotations, duration_s: float) -> list[dict]: + notes = sorted([(float(a["onset"]), float(a["duration"]), a["description"]) for a in annotations], + key=lambda n: n[0]) + iv = [] + for i, (t0, dur, text) in enumerate(notes): + st = state_of(text) + if st is None: + continue + if dur > 0: + t1 = t0 + dur + else: + nxt = next((n[0] for n in notes[i + 1:] if state_of(n[2])), None) + t1 = min(t0 + NOTE_S, nxt if nxt else t0 + NOTE_S) + if t1 - t0 >= MIN_S: + iv.append({"t_ini": t0, "t_fin": t1, "estado": st, "fuente": "edf"}) + iv.sort(key=lambda d: d["t_ini"]) + kept = [d for d in iv if d["t_fin"] - d["t_ini"] >= MIN_S] + full, cursor = [], 0.0 + for d in kept: + if d["t_ini"] - cursor >= MIN_S: + full.append({"t_ini": cursor, "t_fin": d["t_ini"], "estado": "no_marcado", "fuente": "-"}) + full.append(d) + cursor = max(cursor, d["t_fin"]) + if duration_s - cursor >= MIN_S: + full.append({"t_ini": cursor, "t_fin": duration_s, "estado": "no_marcado", "fuente": "-"}) + for d in full: + d["t_ini"], d["t_fin"] = round(d["t_ini"], 2), round(d["t_fin"], 2) + return full + + +def window_state(a: float, b: float, ivs) -> tuple[str, bool]: + overlap = {} + for d in ivs: + lo, hi = max(a, d["t_ini"]), min(b, d["t_fin"]) + if hi > lo: + overlap[d["estado"]] = overlap.get(d["estado"], 0) + (hi - lo) + if not overlap: + return "sin_etiqueta", False + dom = max(overlap, key=overlap.get) + return dom, overlap[dom] < 0.8 * (b - a) + + +class AnnotationMask: + name = "annotation_mask" + version = "0.1.0" + contract_version = CONTRACT_VERSION + requires: tuple[str, ...] = () + impl = "modern" + + def __init__(self, variant: str = "hp05_prom"): + self.variant = variant + + def train(self, studies): + return self + + def predict(self, study) -> Labels: + prep = study.prep + raw = prep.variant(self.variant) if self.variant in prep.variants else next(iter(prep.variants.values())) + ivs = intervals(raw.annotations, raw.n_times / raw.info["sfreq"]) + states, mixed = [], [] + for r in prep.windows.itertuples(): + s, m = window_state(r.start_s, r.end_s, ivs) + states.append(s) + mixed.append(m) + ev = pd.DataFrame([{"onset_s": float(d["t_ini"]), "duration_s": float(d["t_fin"] - d["t_ini"]), + "estado": d["estado"], "fuente": d["fuente"]} for d in ivs], + columns=["onset_s", "duration_s", "estado", "fuente"]) + ev.attrs["mixed_windows"] = [int(i) for i, m in zip(prep.windows.index, mixed) if m] + ev.attrs["excluded_states"] = list(EXCLUDED) + list(PROVOCATION) + return Labels(self.name, per_window=pd.Series(states, index=prep.windows.index, name="estado"), + events=ev) + + def save(self, path): + Path(path, "params.json").write_text(json.dumps({"variant": self.variant})) + + @classmethod + def load(cls, path): + return cls(**json.loads(Path(path, "params.json").read_text())) + + +MODULE = AnnotationMask() diff --git a/src/tea_modulo/processes/sleep_state/__init__.py b/src/tea_modulo/processes/sleep_state/__init__.py new file mode 100644 index 0000000..f85a3ab --- /dev/null +++ b/src/tea_modulo/processes/sleep_state/__init__.py @@ -0,0 +1,3 @@ +from tea_modulo.processes.sleep_state.api import MODULE, SleepState, hk1k_cut + +__all__ = ["MODULE", "SleepState", "hk1k_cut"] diff --git a/src/tea_modulo/processes/sleep_state/api.py b/src/tea_modulo/processes/sleep_state/api.py new file mode 100644 index 0000000..80b1ba3 --- /dev/null +++ b/src/tea_modulo/processes/sleep_state/api.py @@ -0,0 +1,242 @@ +""" +Modern sleep_state: the director's vigilancia on MNE/scikit-learn. + +Per 4 s window (2 s step) of the variant, skipping windows that touch the mask +(QC-unclean spans + annotated EXCLUIDOS/PROVOCACION) or a gap: + features delta/beta, relative delta and alpha, central sigma, EMG + (20-40 / theta+alpha), posterior rhythm prominence (1/f-fitted peak) + from one Hann periodogram per window (mne psd_array_welch, batched) + depth weighted sum of the features standardised by the reference + (cohort or age-adjusted line), clipped to ±6 (vigilancia.indice_profundidad) + label vigilia / somnolencia / sueno by the cut-offs: HK1K (estado_hk1k.json, + E13) by default, or the cohort's KMeans after train(cutoffs="cohort") +""" + +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, Labels + +HK1K = Path(__file__).with_name("data") / "estado_hk1k.json" +POSTERIOR = ("O1", "O2", "P3", "P4") +CENTRAL = ("C3", "C4", "Cz") +BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alfa": (8, 13), "sigma": (11, 16), "beta": (16, 30), + "alto": (20, 40)} +SIGN = {"delta_beta": +1, "ritmo_post": -1, "sigma_rel": +1, "emg": -1, "rel_alfa": -1} +WEIGHT = {"delta_beta": 1.0, "ritmo_post": 1.0, "sigma_rel": 0.7, "emg": 0.7, "rel_alfa": 0.6} +FEATURES = tuple(SIGN) + + +def hk1k_cut(path=HK1K) -> dict: + d = json.loads(Path(path).read_text(encoding="utf-8")) + low, b = float(d["cortes_A"][0]), float(d["corte_B"]) + if not low < b: + raise ValueError(f"inconsistent HK1K cut-offs: wake {low} >= sleep {b}") + return {"ref": d["ref"], "cuts": [low, b], "n_studies": d.get("n_estudios_ref"), "origin": "hk1k"} + + +def dominant_peak(f, P, band=(3.0, 14.0), fit=(1.5, 45.0), exclude=(4.0, 16.0), min_db=1.5): + val = (f >= fit[0]) & (f <= fit[1]) & (P > 0) + bg = val & ~((f >= exclude[0]) & (f <= exclude[1])) + if bg.sum() < 5: + return np.nan, False + coef = np.polyfit(np.log10(f[bg]), np.log10(P[bg]), 1) + resid = 10 * (np.log10(P[val]) - np.polyval(coef, np.log10(f[val]))) + sel = (f[val] >= band[0]) & (f[val] <= band[1]) + if not sel.any(): + return np.nan, False + i = int(np.argmax(resid[sel])) + prom = float(resid[sel][i]) + return prom, bool(prom >= min_db and 0 < i < int(sel.sum()) - 1) + + +def features(raw, mask, window_s=4.0, step_s=2.0) -> pd.DataFrame: + from mne.time_frequency import psd_array_welch + + fs = float(raw.info["sfreq"]) + eeg = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg"] + x = raw.get_data(picks=eeg).T * 1e6 + n, k = int(window_s * fs), int(step_s * fs) + starts = [a for a in range(0, len(x) - n + 1, k) + if np.isfinite(x[a:a + n]).all() and (mask is None or not mask[a:a + n].any())] + cols = ["t_ini_s", *FEATURES, "rel_delta"] + if not starts: + return pd.DataFrame(columns=cols) + seg = np.stack([x[a:a + n].T for a in starts]) # (win, ch, n) + P, f = psd_array_welch(seg, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") + pot = {b: P[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()} + tot = np.maximum(pot["delta"] + pot["theta"] + pot["alfa"] + pot["beta"], 1e-12) + i_post = [eeg.index(c) for c in POSTERIOR if c in eeg] + i_cent = [eeg.index(c) for c in CENTRAL if c in eeg] or list(range(min(3, len(eeg)))) + out = pd.DataFrame({"t_ini_s": np.round(np.array(starts) / fs, 2)}) + out["delta_beta"] = np.median(pot["delta"] / np.maximum(pot["beta"], 1e-12), axis=1) + out["rel_delta"] = np.median(pot["delta"] / tot, axis=1) + out["rel_alfa"] = np.median(pot["alfa"] / tot, axis=1) + out["sigma_rel"] = np.median((pot["sigma"] / tot)[:, i_cent], axis=1) + out["emg"] = np.median(pot["alto"] / np.maximum(pot["theta"] + pot["alfa"], 1e-12), axis=1) + if i_post: + prom = [dominant_peak(f, P[w, i_post].mean(axis=0)) for w in range(len(starts))] + out["ritmo_post"] = [p if ok else 0.0 for p, ok in prom] + else: + out["ritmo_post"] = np.nan + return out + + +def depth(t: pd.DataFrame, ref=None, age_months=None) -> np.ndarray: + z = pd.DataFrame(index=t.index) + for c, sg in SIGN.items(): + if c not in t or not t[c].notna().any(): + continue + v = t[c].astype(float) + if c == "delta_beta": + v = np.log10(v.clip(lower=1e-6)) + r = (ref or {}).get(c) + if r is None: + med = float(v.median()) + disp = float(1.4826 * np.median(np.abs(v - med))) or 1.0 + elif "pend" in r and age_months and age_months > 0: + med, disp = r["pend"] * np.log10(float(age_months)) + r["orden"], r["disp"] + else: + med, disp = r["med"], r["disp"] + z[c] = sg * (v - med) / max(disp, 1e-9) + if not len(z.columns): + return np.zeros(len(t)) + w = np.array([WEIGHT[c] for c in z.columns], float) + return np.clip((z.values * w).sum(axis=1) / w.sum(), -6, 6) + + +def label(depths, cuts) -> np.ndarray: + names = (["vigilia", "sueno"] if len(cuts) == 1 + else ["vigilia"] + ["somnolencia"] * (len(cuts) - 1) + ["sueno"]) + return np.array(names, dtype=object)[np.digitize(depths, cuts)] + + +def cohort_reference(tables, ages=None, r_min=0.30) -> dict: + """vigilancia.referencia_cohorte: median / MAD per feature, age line where |r| >= r_min.""" + allw = pd.concat(tables, ignore_index=True) + ref = {} + for c in FEATURES: + if c not in allw or not allw[c].notna().any(): + continue + v = allw[c].astype(float) + v = np.log10(v.clip(lower=1e-6)) if c == "delta_beta" else v + med = float(v.median()) + ref[c] = {"med": med, "disp": float(1.4826 * np.median(np.abs(v.dropna() - med))) or 1.0} + rows = [] + for i, t in enumerate(tables): + a = (ages or {}).get(i) + if not a or a <= 0: + continue + r = {"log_age": np.log10(a)} + for c in FEATURES: + if c in t and t[c].notna().any(): + v = t[c].astype(float) + r[c] = float(np.log10(v.clip(lower=1e-6)).median() if c == "delta_beta" else v.median()) + rows.append(r) + if len(rows) < 10: + return ref + d = pd.DataFrame(rows) + for c in FEATURES: + if c not in d or d[c].notna().sum() < 10: + continue + m = d[c].notna() + rr = float(np.corrcoef(d.log_age[m], d[c][m])[0, 1]) + if not np.isfinite(rr) or abs(rr) < r_min: + continue + pend, orden = np.polyfit(d.log_age[m], d[c][m], 1) + res = d[c][m] - (pend * d.log_age[m] + orden) + ref[c] = {"pend": float(pend), "orden": float(orden), "med": float(d[c][m].median()), + "disp": float(1.4826 * np.median(np.abs(res - res.median()))) or 1.0} + return ref + + +def cohort_cuts(tables, ref, n_groups=3, seed=0, ages=None) -> list[float]: + from sklearn.cluster import KMeans + idx = np.concatenate([depth(t, ref, (ages or {}).get(i)) for i, t in enumerate(tables)]) + idx = idx[np.isfinite(idx)] + if len(idx) > 200000: + idx = np.random.default_rng(seed).choice(idx, 200000, replace=False) + km = KMeans(n_clusters=max(2, n_groups), n_init=10, random_state=seed).fit(idx.reshape(-1, 1)) + c = np.sort(km.cluster_centers_.ravel()) + return [float((c[i] + c[i + 1]) / 2) for i in range(len(c) - 1)] + + +class SleepState: + name = "sleep_state" + version = "0.1.0" + contract_version = CONTRACT_VERSION + requires = ("annotation_mask",) + impl = "modern" + + def __init__(self, variant="hp05_prom", cutoffs="hk1k", age_range=(16, 36), n_groups=3, cut=None): + self.variant = variant + self.cutoffs = cutoffs + self.age_range = tuple(age_range) + self.n_groups = n_groups + self.cut = cut if cut is not None else (hk1k_cut() if cutoffs == "hk1k" else None) + + def mask(self, study, n, fs): + prep = study.prep + if not prep.plan.get("state", {}).get("mask", True): + return None + m = np.zeros(n, bool) + for r in prep.quality_spans.itertuples(): + m[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True + ev = study.label("annotation_mask").events + excl = set(ev.attrs.get("excluded_states", ())) + for r in ev.itertuples(): + if r.estado in excl: + m[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True + return m + + def features(self, study) -> pd.DataFrame: + raw = study.prep.variant(self.variant) + return features(raw, self.mask(study, raw.n_times, float(raw.info["sfreq"]))) + + def train(self, studies): + if self.cutoffs != "cohort": + return self + tables, ages = [], {} + for s in studies: + t = self.features(s) + if len(t) >= 30: + if s.prep.age_months: + ages[len(tables)] = float(s.prep.age_months) + tables.append(t) + lo, hi = self.age_range + in_range = [i for i in range(len(tables)) if lo <= ages.get(i, -1) <= hi] + use = in_range if len(in_range) >= 10 else list(range(len(tables))) + sub, sub_ages = [tables[i] for i in use], {k: ages[i] for k, i in enumerate(use) if i in ages} + ref = cohort_reference(sub, sub_ages or None) + self.cut = {"ref": ref, "cuts": cohort_cuts(sub, ref, self.n_groups, ages=sub_ages or None), + "n_studies": len(sub), "origin": "cohort"} + return self + + def predict(self, study) -> Labels: + if self.cut is None: + raise ValueError("sleep_state with cutoffs='cohort' must be trained first") + w = study.prep.windows + t = self.features(study) + per = pd.Series("sin_estado", index=w.index, name="vigilancia", dtype=object) + if len(t): + lab = label(depth(t, self.cut["ref"], study.prep.age_months), self.cut["cuts"]) + by_start = dict(zip(t.t_ini_s.round(2), lab)) + per[:] = [by_start.get(round(float(s), 2), "sin_estado") for s in w.start_s] + return Labels(self.name, per_window=per) + + def save(self, path): + Path(path, "params.json").write_text(json.dumps( + {"variant": self.variant, "cutoffs": self.cutoffs, "age_range": list(self.age_range), + "n_groups": self.n_groups, "cut": self.cut}, default=float)) + + @classmethod + def load(cls, path): + return cls(**json.loads(Path(path, "params.json").read_text())) + + +MODULE = SleepState() diff --git a/src/tea_modulo/processes/sleep_state/data/estado_hk1k.json b/src/tea_modulo/processes/sleep_state/data/estado_hk1k.json new file mode 100644 index 0000000..bd49204 --- /dev/null +++ b/src/tea_modulo/processes/sleep_state/data/estado_hk1k.json @@ -0,0 +1,47 @@ +{ + "ref": { + "delta_beta": { + "med": 1.6117037688126001, + "disp": 0.3097998485854789 + }, + "ritmo_post": { + "pend": 4.934510806157707, + "orden": 0.999676072265559, + "disp": 1.021788597296859, + "med": 7.765061458878031 + }, + "sigma_rel": { + "med": 0.019957376774209706, + "disp": 0.012167857665235331 + }, + "emg": { + "med": 0.0742822337558628, + "disp": 0.056777351044491706 + }, + "rel_alfa": { + "med": 0.03498707283228359, + "disp": 0.016352123389996105 + } + }, + "cortes_A": [ + -1.2326590642152986, + 0.243030749000992 + ], + "corte_B": -0.3031551001049524, + "youden_B": 0.5286948181809392, + "validacion_cruzada": { + "cv1_corte": -0.307, + "cv1_sueno_n2_pct_mediana": 85.3, + "cv1_sueno_pre_pct_mediana": 26.8, + "cv2_corte": -0.299, + "cv2_sueno_n2_pct_mediana": 85.9, + "cv2_sueno_pre_pct_mediana": 23.0 + }, + "edad_meses": [ + 16, + 36 + ], + "n_estudios_ref": 223, + "version": "0.2.0", + "fuente": "E13, HK1K (Zenodo 17138539); vigilancia.py del director, rasgos solo en ventanas limpias; corte B por Youden (0–300 s frente a 360–900 s)" +} \ No newline at end of file diff --git a/tests/test_modern_slice.py b/tests/test_modern_slice.py new file mode 100644 index 0000000..be98797 --- /dev/null +++ b/tests/test_modern_slice.py @@ -0,0 +1,65 @@ +"""Modern annotation_mask + sleep_state + posterior_rhythm agree with the legacy (director) ones.""" + +from __future__ import annotations + +import pytest + +from synth_edf import make_edf +from tea_modulo.contracts import Study +from tea_modulo.contracts.testing import check_biomarker, check_process +from tea_modulo.pipeline import Pipeline +from tea_modulo.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER +from tea_modulo.processes.sleep_state import SleepState + +ANN = [(5, None, "Paciente despierto"), (240.5, None, "Dormido"), (100, 20, "Fotica 5 Hz"), (150, None, "llanto")] + + +@pytest.fixture(scope="module") +def studies(tmp_path_factory): + p = make_edf(tmp_path_factory.mktemp("slice") / "s.edf", minutes=8, rhythm_hz=6.5, annotations=ANN) + return (Pipeline.default("modern").study(p, plan=DIRECTOR_CLUSTER, age_months=28), + Pipeline.default("legacy").study(p, plan=DIRECTOR_CLUSTER, age_months=28)) + + +def test_annotation_states_equal(studies): + m, l = studies + assert (m.label("annotation_mask").per_window.values == l.label("annotation_mask").per_window.values).all() + + +def test_sleep_state_agrees(studies): + m, l = studies + a, b = m.label("sleep_state").per_window, l.label("sleep_state").per_window + assert (a.values == b.values).mean() >= 0.95 + + +def test_rhythm_agrees(studies): + m, l = studies + rm = Pipeline.default("modern").module("posterior_rhythm").measure(m)["posterior_rhythm_hz"] + rl = Pipeline.default("legacy").module("posterior_rhythm").measure(l)["posterior_rhythm_hz"] + assert rm == pytest.approx(rl, abs=0.25) and rm == pytest.approx(6.5, abs=0.3) + + +def test_contracts(studies): + m, _ = studies + pm = Pipeline.default("modern") + check_process(pm.module("annotation_mask"), Study(m.prep)) + check_process(pm.module("sleep_state"), Study(m.prep).with_labels(pm.module("annotation_mask").predict(Study(m.prep)))) + + +def test_biomarker_contract(tmp_path): + pipe = Pipeline.default("modern") + sts = [pipe.study(make_edf(tmp_path / f"s{i}.edf", minutes=4, seed=i, rhythm_hz=6 + 0.4 * i), + plan=DIRECTOR_CLUSTER, age_months=20 + 4 * i) for i in range(3)] + from tea_modulo.biomarkers.posterior_rhythm import PosteriorRhythm + check_biomarker(PosteriorRhythm(baseline="age_blocks"), sts, [20, 24, 28]) + + +def test_cohort_cutoffs_train(tmp_path): + """DIRECTOR_CLI route: KMeans cut-offs on the cohort (cutoffs='cohort').""" + pipe = Pipeline.default("modern") + sts = [pipe.study(make_edf(tmp_path / f"c{i}.edf", minutes=6, seed=10 + i), plan=DIRECTOR_CLI, + age_months=24, processes=["annotation_mask"]) for i in range(2)] + ss = SleepState(cutoffs="cohort").train(sts) + assert ss.cut["origin"] == "cohort" and len(ss.cut["cuts"]) == 2 + lab = ss.predict(sts[0]).per_window + assert {"vigilia", "sueno"} <= set(lab)