From 4deba99c922750bb30b117f23b00753a63699e05 Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Wed, 18 Nov 2026 21:52:22 -0600 Subject: [PATCH] aperiodic and mse, legacy and modern - The cluster route's 2 s window table (ventanas.cortar + estado_director exclusions and labels) rebuilt from the contract, one private copy per module. - legacy: biomarcadores espectro.py, aperiodico.py (FOOOF with Wilkinson's modifications) and complejidad.py copied unchanged; exponent per region and state (NaN under 20 windows or R2 < 0.9); MSE fine / coarse / total. - modern: MNE multitaper + fooof with the same two Wilkinson modifications; antropy sample entropy with Costa's fixed tolerance. Copies byte-identical to the submodule; modern within 2% (exponent) and 1% (MSE) of legacy on the synthetic study; contract suites pass. --- pyproject.toml | 4 + .../biomarkers/aperiodic/__init__.py | 3 + .../biomarkers/aperiodic/_baseline.py | 241 ++++++++++++++++++ .../biomarkers/aperiodic/_windows2s.py | 72 ++++++ src/tea_modulo/biomarkers/aperiodic/api.py | 171 +++++++++++++ src/tea_modulo/biomarkers/mse/__init__.py | 3 + src/tea_modulo/biomarkers/mse/_baseline.py | 241 ++++++++++++++++++ src/tea_modulo/biomarkers/mse/_windows2s.py | 72 ++++++ src/tea_modulo/biomarkers/mse/api.py | 153 +++++++++++ .../legacy/biomarkers/aperiodic/__init__.py | 3 + .../legacy/biomarkers/aperiodic/_baseline.py | 241 ++++++++++++++++++ .../biomarkers/aperiodic/_bio/__init__.py | 1 + .../biomarkers/aperiodic/_bio/aperiodico.py | 92 +++++++ .../biomarkers/aperiodic/_bio/espectro.py | 51 ++++ .../legacy/biomarkers/aperiodic/_windows2s.py | 72 ++++++ .../legacy/biomarkers/aperiodic/api.py | 121 +++++++++ .../legacy/biomarkers/mse/__init__.py | 3 + .../legacy/biomarkers/mse/_baseline.py | 241 ++++++++++++++++++ .../legacy/biomarkers/mse/_bio/__init__.py | 1 + .../legacy/biomarkers/mse/_bio/complejidad.py | 138 ++++++++++ .../legacy/biomarkers/mse/_windows2s.py | 72 ++++++ src/tea_modulo/legacy/biomarkers/mse/api.py | 117 +++++++++ tests/test_aperiodic_mse.py | 52 ++++ tests/test_boundaries.py | 2 +- 24 files changed, 2166 insertions(+), 1 deletion(-) create mode 100644 src/tea_modulo/biomarkers/aperiodic/__init__.py create mode 100644 src/tea_modulo/biomarkers/aperiodic/_baseline.py create mode 100644 src/tea_modulo/biomarkers/aperiodic/_windows2s.py create mode 100644 src/tea_modulo/biomarkers/aperiodic/api.py create mode 100644 src/tea_modulo/biomarkers/mse/__init__.py create mode 100644 src/tea_modulo/biomarkers/mse/_baseline.py create mode 100644 src/tea_modulo/biomarkers/mse/_windows2s.py create mode 100644 src/tea_modulo/biomarkers/mse/api.py create mode 100644 src/tea_modulo/legacy/biomarkers/aperiodic/__init__.py create mode 100644 src/tea_modulo/legacy/biomarkers/aperiodic/_baseline.py create mode 100644 src/tea_modulo/legacy/biomarkers/aperiodic/_bio/__init__.py create mode 100644 src/tea_modulo/legacy/biomarkers/aperiodic/_bio/aperiodico.py create mode 100644 src/tea_modulo/legacy/biomarkers/aperiodic/_bio/espectro.py create mode 100644 src/tea_modulo/legacy/biomarkers/aperiodic/_windows2s.py create mode 100644 src/tea_modulo/legacy/biomarkers/aperiodic/api.py create mode 100644 src/tea_modulo/legacy/biomarkers/mse/__init__.py create mode 100644 src/tea_modulo/legacy/biomarkers/mse/_baseline.py create mode 100644 src/tea_modulo/legacy/biomarkers/mse/_bio/__init__.py create mode 100644 src/tea_modulo/legacy/biomarkers/mse/_bio/complejidad.py create mode 100644 src/tea_modulo/legacy/biomarkers/mse/_windows2s.py create mode 100644 src/tea_modulo/legacy/biomarkers/mse/api.py create mode 100644 tests/test_aperiodic_mse.py diff --git a/pyproject.toml b/pyproject.toml index b52cb15..f11cc84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,8 @@ spindles = "tea_modulo.legacy.biomarkers.spindles:MODULE" gradient = "tea_modulo.legacy.biomarkers.gradient:MODULE" slow_wave_staging = "tea_modulo.legacy.processes.slow_wave_staging:MODULE" slow_waves = "tea_modulo.legacy.biomarkers.slow_waves:MODULE" +aperiodic = "tea_modulo.legacy.biomarkers.aperiodic:MODULE" +mse = "tea_modulo.legacy.biomarkers.mse:MODULE" [project.entry-points."tea_modulo.modules"] validation = "tea_modulo.validation:MODULE" @@ -51,6 +53,8 @@ spindles = "tea_modulo.biomarkers.spindles:MODULE" gradient = "tea_modulo.biomarkers.gradient:MODULE" slow_wave_staging = "tea_modulo.processes.slow_wave_staging:MODULE" slow_waves = "tea_modulo.biomarkers.slow_waves:MODULE" +aperiodic = "tea_modulo.biomarkers.aperiodic:MODULE" +mse = "tea_modulo.biomarkers.mse:MODULE" [project.entry-points."tea_modulo.executors"] legacy = "tea_modulo.legacy.executor:run_serial" diff --git a/src/tea_modulo/biomarkers/aperiodic/__init__.py b/src/tea_modulo/biomarkers/aperiodic/__init__.py new file mode 100644 index 0000000..791cdb1 --- /dev/null +++ b/src/tea_modulo/biomarkers/aperiodic/__init__.py @@ -0,0 +1,3 @@ +from tea_modulo.biomarkers.aperiodic.api import MODULE, Aperiodic + +__all__ = ["MODULE", "Aperiodic"] diff --git a/src/tea_modulo/biomarkers/aperiodic/_baseline.py b/src/tea_modulo/biomarkers/aperiodic/_baseline.py new file mode 100644 index 0000000..167759e --- /dev/null +++ b/src/tea_modulo/biomarkers/aperiodic/_baseline.py @@ -0,0 +1,241 @@ +""" +Baselines, ported as they are (private copy; every legacy 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/aperiodic/_windows2s.py b/src/tea_modulo/biomarkers/aperiodic/_windows2s.py new file mode 100644 index 0000000..91e2fe9 --- /dev/null +++ b/src/tea_modulo/biomarkers/aperiodic/_windows2s.py @@ -0,0 +1,72 @@ +""" +The 2 s window table of the cluster route, rebuilt from the contract (private +copy; aperiodic and mse modules own one each). + +As biomarcadores ventanas.cortar + estado_director.excluir_por_estado / etiquetar +@ 7dfc641: back-to-back 2 s windows; a window is clean if it has no gap, its 4 s QC +window is clean (not in Preprocessed.quality_spans), it is at least `edge_s` from the +start or end of a gap-free run, and its annotated state is not excluded and not +mixed; its state is the sleep_state label of the 4 s window starting at the same +time, or the one starting 2 s before. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + + +def table(study, variant: str, dur_s: float = 2.0, edge_s: float = 2.0) -> pd.DataFrame: + prep = study.prep + raw = prep.variant(variant) + fs = float(raw.info["sfreq"]) + n_t = raw.n_times + gap = np.zeros(n_t, bool) + for a in raw.annotations: + if a["description"].startswith("BAD_ACQ_SKIP"): + gap[int(a["onset"] * fs):int((a["onset"] + a["duration"]) * fs)] = True + unclean = np.zeros(n_t, bool) + for r in prep.quality_spans.itertuples(): + unclean[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True + near = np.zeros(n_t, bool) + b = int(round(edge_s * fs)) + v = np.concatenate([[False], ~gap, [False]]).astype(int) + d = np.diff(v) + for s, e in zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)): + near[s:min(s + b, e)] = True + near[max(e - b, s):e] = True + ev = study.label("annotation_mask").events + excl = set(ev.attrs.get("excluded_states", ())) + ivs = [(r.onset_s, r.onset_s + r.duration_s, r.estado) for r in ev.itertuples()] + lab = study.label("sleep_state").per_window + by_start = dict(zip(prep.windows.start_s.round(2), lab)) + n = int(round(dur_s * fs)) + rows = [] + for k in range(n_t // n): + a0, a1 = k * n, (k + 1) * n + t0, t1 = a0 / fs, a1 / fs + ov = {} + for lo, hi, st in ivs: + o = min(t1, hi) - max(t0, lo) + if o > 0: + ov[st] = ov.get(st, 0) + o + st = max(ov, key=ov.get) if ov else "sin_etiqueta" + mixed = bool(ov) and ov[st] < 0.8 * (t1 - t0) + if gap[a0:a1].any(): + why = "hueco" + elif unclean[a0:a1].any(): + why = "no_limpia_qc" + elif near[a0:a1].any(): + why = "borde_de_tramo" + elif st in excl: + why = f"estado_{st}" + elif mixed: + why = "mixta" + else: + why = "" + state = by_start.get(round(t0, 2), by_start.get(round(t0 - 2.0, 2), "sin_estado")) + rows.append({"t_ini": t0, "t_fin": t1, "i0": a0, "limpia": why == "", "motivo": why, "vigilancia": state}) + t = pd.DataFrame(rows) + for s in ("vigilia", "somnolencia", "sueno"): + t[s] = t.vigilancia.eq(s) if len(t) else pd.Series(dtype=bool) + return t diff --git a/src/tea_modulo/biomarkers/aperiodic/api.py b/src/tea_modulo/biomarkers/aperiodic/api.py new file mode 100644 index 0000000..2708201 --- /dev/null +++ b/src/tea_modulo/biomarkers/aperiodic/api.py @@ -0,0 +1,171 @@ +""" +Modern aperiodic (the cluster route's definitions): + + windows clean 2 s windows of each state (at least 20) + spectrum multitaper per window (mne psd_array_multitaper, half-bandwidth 1 Hz on + 2 s = 3 DPSS tapers), mean over windows, mean over the region's electrodes + fit FOOOF 1.1 (fooof) over 2.5-50 Hz, fixed aperiodic mode, with Wilkinson + 2024's two modifications (shifted robust aperiodic fit at the 10th + percentile; residual below the aperiodic floor set to zero before the + peak search). NaN when R² < 0.9. + +Features: aperiodic__. +""" + +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, _windows2s + +# parametros.toml @ 7dfc641 (the values the cluster route uses) +P = {"ventanas.duracion_s": 2.0, "ventanas.borde_s": 2.0, "ventanas.min_ventanas": 20, "espectro.tapers": 3, + "regiones": {"frontal": ["F3", "Fz", "F4"], "central": ["C3", "Cz", "C4"], + "temporal": ["T3", "T4", "P3", "P4"], "posterior": ["O1", "O2", "Pz"]}, + "aperiodico.rango_hz": [2.5, 50.0], "aperiodico.ancho_picos_hz": [0.5, 18.0], "aperiodico.max_picos": 7, + "aperiodico.umbral_pico": 2.0, "aperiodico.percentil_ap": 10.0, "aperiodico.r2_minimo": 0.9, + "complejidad.m": 2, "complejidad.r": 0.15, "complejidad.escala_max": 20, "complejidad.escala_corte": 5, + "complejidad.segmento_s": 30, "complejidad.max_segmentos": 4} +STATES = ("vigilia", "somnolencia", "sueno") +REGIONS = ('frontal', 'central', 'temporal', 'posterior', 'todo') +FEATURES = tuple(f"aperiodic_{r}_{s}" for s in STATES for r in REGIONS) + + +def wilkinson_fooof(**kw): + import warnings + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + import fooof + from fooof.core.errors import FitError + from fooof.core.funcs import get_ap_func + from fooof.sim.gen import gen_aperiodic + from scipy.optimize import curve_fit + + class FOOOFWilkinson(fooof.FOOOF): + def _robust_ap_fit(self, freqs, spectrum): + popt = self._simple_ap_fit(freqs, spectrum) + flat = spectrum - gen_aperiodic(freqs, popt) + if min(flat) < 0: + flat = flat - min(flat) + mask = flat <= np.percentile(flat, P["aperiodico.percentil_ap"]) + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + params, _ = curve_fit(get_ap_func(self.aperiodic_mode), freqs[mask], spectrum[mask], + p0=popt, maxfev=self._maxfev, bounds=self._ap_bounds) + except (RuntimeError, TypeError) as e: + raise FitError(f"robust aperiodic fit failed: {e}") + return params + + def _fit_peaks(self, flat_iter): + flat_iter = np.array(flat_iter, copy=True) + flat_iter[flat_iter < 0] = 0 + return super()._fit_peaks(flat_iter) + + return FOOOFWilkinson(**kw) + + +def exponent(f, spectrum) -> float: + if spectrum is None or not np.all(np.isfinite(spectrum)) or np.any(spectrum <= 0): + return float("nan") + fm = wilkinson_fooof(peak_width_limits=P["aperiodico.ancho_picos_hz"], max_n_peaks=P["aperiodico.max_picos"], + peak_threshold=P["aperiodico.umbral_pico"], aperiodic_mode="fixed", verbose=False) + fm.fit(np.asarray(f, float), np.asarray(spectrum, float), list(P["aperiodico.rango_hz"])) + if not fm.has_model or fm.r_squared_ < P["aperiodico.r2_minimo"]: + return float("nan") + return float(fm.aperiodic_params_[1]) + + +class Aperiodic: + name = "aperiodic" + version = "0.1.0" + contract_version = CONTRACT_VERSION + requires = ("sleep_state", "annotation_mask") + 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 _reg(self, study): + raw = study.prep.variant(self.variant) + eeg = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg"] + class R: + pass + r = R() + r.datos, r.canales, r.fs = raw.get_data(picks=eeg).T * 1e6, eeg, float(raw.info["sfreq"]) + return r + + def measure(self, study) -> dict: + from mne.time_frequency import psd_array_multitaper + reg = self._reg(study) + tabla = _windows2s.table(study, self.variant, P["ventanas.duracion_s"], P["ventanas.borde_s"]) + n = int(round(P["ventanas.duracion_s"] * reg.fs)) + out = {f: float("nan") for f in FEATURES} + for s in STATES: + sel = tabla[tabla.limpia & tabla[s]] + segs = [reg.datos[i:i + n].T for i in sel.i0 if np.isfinite(reg.datos[i:i + n]).all()] + if len(sel) < P["ventanas.min_ventanas"] or not segs: + continue + Pw, f = psd_array_multitaper(np.stack(segs), reg.fs, bandwidth=2.0, adaptive=False, low_bias=True, + normalization="full", verbose="error") + Pm = Pw.mean(axis=0) # channels x freqs + regions = {**{r: [reg.canales.index(c) for c in cs if c in reg.canales] + for r, cs in P["regiones"].items()}, "todo": list(range(len(reg.canales)))} + for r, idx in regions.items(): + if idx: + out[f"aperiodic_{r}_{s}"] = exponent(f, Pm[idx].mean(axis=0)) + 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 = Aperiodic() diff --git a/src/tea_modulo/biomarkers/mse/__init__.py b/src/tea_modulo/biomarkers/mse/__init__.py new file mode 100644 index 0000000..d88c1a0 --- /dev/null +++ b/src/tea_modulo/biomarkers/mse/__init__.py @@ -0,0 +1,3 @@ +from tea_modulo.biomarkers.mse.api import MODULE, MSE + +__all__ = ["MODULE", "MSE"] diff --git a/src/tea_modulo/biomarkers/mse/_baseline.py b/src/tea_modulo/biomarkers/mse/_baseline.py new file mode 100644 index 0000000..167759e --- /dev/null +++ b/src/tea_modulo/biomarkers/mse/_baseline.py @@ -0,0 +1,241 @@ +""" +Baselines, ported as they are (private copy; every legacy 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/mse/_windows2s.py b/src/tea_modulo/biomarkers/mse/_windows2s.py new file mode 100644 index 0000000..91e2fe9 --- /dev/null +++ b/src/tea_modulo/biomarkers/mse/_windows2s.py @@ -0,0 +1,72 @@ +""" +The 2 s window table of the cluster route, rebuilt from the contract (private +copy; aperiodic and mse modules own one each). + +As biomarcadores ventanas.cortar + estado_director.excluir_por_estado / etiquetar +@ 7dfc641: back-to-back 2 s windows; a window is clean if it has no gap, its 4 s QC +window is clean (not in Preprocessed.quality_spans), it is at least `edge_s` from the +start or end of a gap-free run, and its annotated state is not excluded and not +mixed; its state is the sleep_state label of the 4 s window starting at the same +time, or the one starting 2 s before. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + + +def table(study, variant: str, dur_s: float = 2.0, edge_s: float = 2.0) -> pd.DataFrame: + prep = study.prep + raw = prep.variant(variant) + fs = float(raw.info["sfreq"]) + n_t = raw.n_times + gap = np.zeros(n_t, bool) + for a in raw.annotations: + if a["description"].startswith("BAD_ACQ_SKIP"): + gap[int(a["onset"] * fs):int((a["onset"] + a["duration"]) * fs)] = True + unclean = np.zeros(n_t, bool) + for r in prep.quality_spans.itertuples(): + unclean[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True + near = np.zeros(n_t, bool) + b = int(round(edge_s * fs)) + v = np.concatenate([[False], ~gap, [False]]).astype(int) + d = np.diff(v) + for s, e in zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)): + near[s:min(s + b, e)] = True + near[max(e - b, s):e] = True + ev = study.label("annotation_mask").events + excl = set(ev.attrs.get("excluded_states", ())) + ivs = [(r.onset_s, r.onset_s + r.duration_s, r.estado) for r in ev.itertuples()] + lab = study.label("sleep_state").per_window + by_start = dict(zip(prep.windows.start_s.round(2), lab)) + n = int(round(dur_s * fs)) + rows = [] + for k in range(n_t // n): + a0, a1 = k * n, (k + 1) * n + t0, t1 = a0 / fs, a1 / fs + ov = {} + for lo, hi, st in ivs: + o = min(t1, hi) - max(t0, lo) + if o > 0: + ov[st] = ov.get(st, 0) + o + st = max(ov, key=ov.get) if ov else "sin_etiqueta" + mixed = bool(ov) and ov[st] < 0.8 * (t1 - t0) + if gap[a0:a1].any(): + why = "hueco" + elif unclean[a0:a1].any(): + why = "no_limpia_qc" + elif near[a0:a1].any(): + why = "borde_de_tramo" + elif st in excl: + why = f"estado_{st}" + elif mixed: + why = "mixta" + else: + why = "" + state = by_start.get(round(t0, 2), by_start.get(round(t0 - 2.0, 2), "sin_estado")) + rows.append({"t_ini": t0, "t_fin": t1, "i0": a0, "limpia": why == "", "motivo": why, "vigilancia": state}) + t = pd.DataFrame(rows) + for s in ("vigilia", "somnolencia", "sueno"): + t[s] = t.vigilancia.eq(s) if len(t) else pd.Series(dtype=bool) + return t diff --git a/src/tea_modulo/biomarkers/mse/api.py b/src/tea_modulo/biomarkers/mse/api.py new file mode 100644 index 0000000..3ca2d22 --- /dev/null +++ b/src/tea_modulo/biomarkers/mse/api.py @@ -0,0 +1,153 @@ +""" +Modern mse (the cluster route's definitions): + + runs up to 4 runs of 30 s of consecutive clean 2 s windows of one state, spread + over the recording + entropy per electrode of all regions: sample entropy (antropy, Chebyshev distance, + order 2) of the coarse-grained signal at scales 1-20, tolerance fixed at + 0.15 x the SD of the original run (Costa's MSE) + indices mean curve over runs and electrodes; sums over scales 1-5 (fine), + 6-20 (coarse) and all (total) + +Features: mse__. +""" + +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, _windows2s + +# parametros.toml @ 7dfc641 (the values the cluster route uses) +P = {"ventanas.duracion_s": 2.0, "ventanas.borde_s": 2.0, "ventanas.min_ventanas": 20, "espectro.tapers": 3, + "regiones": {"frontal": ["F3", "Fz", "F4"], "central": ["C3", "Cz", "C4"], + "temporal": ["T3", "T4", "P3", "P4"], "posterior": ["O1", "O2", "Pz"]}, + "aperiodico.rango_hz": [2.5, 50.0], "aperiodico.ancho_picos_hz": [0.5, 18.0], "aperiodico.max_picos": 7, + "aperiodico.umbral_pico": 2.0, "aperiodico.percentil_ap": 10.0, "aperiodico.r2_minimo": 0.9, + "complejidad.m": 2, "complejidad.r": 0.15, "complejidad.escala_max": 20, "complejidad.escala_corte": 5, + "complejidad.segmento_s": 30, "complejidad.max_segmentos": 4} +STATES = ("vigilia", "somnolencia", "sueno") +FEATURES = tuple(f"mse_{k}_{s}" for s in STATES for k in ("fine", "coarse", "total")) + + +def runs(tabla, state) -> list[int]: + per = int(round(P["complejidad.segmento_s"] / P["ventanas.duracion_s"])) + ok = (tabla.limpia & tabla[state]).to_numpy() + starts, k = [], 0 + while k + per <= len(ok): + if ok[k:k + per].all(): + starts.append(int(tabla.i0.iloc[k])) + k += per + else: + k += 1 + mx = P["complejidad.max_segmentos"] + if len(starts) > mx: + starts = [starts[i] for i in np.linspace(0, len(starts) - 1, mx).round().astype(int)] + return starts + + +def mse_curve(x) -> np.ndarray: + import antropy + tol = P["complejidad.r"] * np.std(x) + out = [] + for tau in range(1, P["complejidad.escala_max"] + 1): + n = len(x) // tau + y = np.asarray(x[:n * tau], float).reshape(n, tau).mean(axis=1) + v = antropy.sample_entropy(y, order=P["complejidad.m"], tolerance=tol) if len(y) > 10 else np.nan + out.append(v if np.isfinite(v) else np.nan) + return np.array(out) + + +class MSE: + name = "mse" + version = "0.1.0" + contract_version = CONTRACT_VERSION + requires = ("sleep_state", "annotation_mask") + 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 _reg(self, study): + raw = study.prep.variant(self.variant) + eeg = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg"] + class R: + pass + r = R() + r.datos, r.canales, r.fs = raw.get_data(picks=eeg).T * 1e6, eeg, float(raw.info["sfreq"]) + return r + + def measure(self, study) -> dict: + reg = self._reg(study) + tabla = _windows2s.table(study, self.variant, P["ventanas.duracion_s"], P["ventanas.borde_s"]) + n = int(round(P["complejidad.segmento_s"] * reg.fs)) + chans = sorted({c for cs in P["regiones"].values() for c in cs if c in reg.canales}) + cut = P["complejidad.escala_corte"] + out = {f: float("nan") for f in FEATURES} + for s in STATES: + if (tabla.limpia & tabla[s]).sum() < P["ventanas.min_ventanas"]: + continue + st = runs(tabla, s) + if not st or not chans: + continue + curves = [np.nanmean([mse_curve(reg.datos[i:i + n, reg.canales.index(c)]) for i in st], axis=0) + for c in chans] + curve = np.nanmean(curves, axis=0) + out[f"mse_fine_{s}"] = float(np.nansum(curve[:cut])) + out[f"mse_coarse_{s}"] = float(np.nansum(curve[cut:])) + out[f"mse_total_{s}"] = float(np.nansum(curve)) + 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 = MSE() diff --git a/src/tea_modulo/legacy/biomarkers/aperiodic/__init__.py b/src/tea_modulo/legacy/biomarkers/aperiodic/__init__.py new file mode 100644 index 0000000..ff1de0d --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/aperiodic/__init__.py @@ -0,0 +1,3 @@ +from tea_modulo.legacy.biomarkers.aperiodic.api import MODULE, LegacyAperiodic + +__all__ = ["MODULE", "LegacyAperiodic"] diff --git a/src/tea_modulo/legacy/biomarkers/aperiodic/_baseline.py b/src/tea_modulo/legacy/biomarkers/aperiodic/_baseline.py new file mode 100644 index 0000000..167759e --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/aperiodic/_baseline.py @@ -0,0 +1,241 @@ +""" +Baselines, ported as they are (private copy; every legacy 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/legacy/biomarkers/aperiodic/_bio/__init__.py b/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/__init__.py new file mode 100644 index 0000000..df774e1 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/__init__.py @@ -0,0 +1 @@ +"""biomarcadores-tea/biomarcadores files copied unchanged (see each header).""" diff --git a/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/aperiodico.py b/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/aperiodico.py new file mode 100644 index 0000000..8a22996 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/aperiodico.py @@ -0,0 +1,92 @@ +# Copied unchanged from biomarcadores-tea/biomarcadores/aperiodico.py @ 7dfc641 (sha256 54eaa69cc48ab56af26128f46205e9bba15ff0c2c32d23a1f5eeba44e78278ec) +""" +aperiodico.py — Exponente aperiódico con el ajuste modificado de Wilkinson 2024. + + r = aperiodico.ajustar(f, espectro, p) + r["exponente"], r["offset"], r["r2"], r["picos"] + +El espectro del EEG es una curva que baja con la frecuencia (el «fondo») con jorobas +encima (los ritmos). FOOOF separa las dos cosas: ajusta el fondo como una recta en escala +logarítmica y las jorobas como campanas. El exponente es la inclinación de esa recta. + +Wilkinson cambió dos detalles de FOOOF 1.x para niños pequeños, cuyo espectro tiene picos +anchos que confundían el ajuste del fondo (código en osf.io/u3gp4, cuaderno +01_New_and_Old_FOOOF). Se reproducen tal cual: + 1. En el primer ajuste del fondo, en vez de poner en cero los valores por debajo, sube + toda la curva hasta que no haya negativos, y usa el percentil 10 (no 0.025). + 2. Antes de buscar picos, pone en cero lo que quede por debajo del fondo. +""" + +from __future__ import annotations + +import warnings + +import numpy as np +from scipy.optimize import curve_fit + +with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + import fooof + from fooof.core.errors import FitError + from fooof.core.funcs import get_ap_func + from fooof.sim.gen import gen_aperiodic + + +class FOOOFWilkinson(fooof.FOOOF): + """FOOOF 1.1 con las dos modificaciones de Wilkinson 2024.""" + + def __init__(self, *args, ap_percentil=10.0, **kwargs): + super().__init__(*args, **kwargs) + self._ap_percentile_thresh = ap_percentil + + def _robust_ap_fit(self, freqs, power_spectrum): + popt = self._simple_ap_fit(freqs, power_spectrum) + flatspec = power_spectrum - gen_aperiodic(freqs, popt) + if min(flatspec) < 0: # modificación 1 + flatspec = flatspec - min(flatspec) + perc_mask = flatspec <= np.percentile(flatspec, self._ap_percentile_thresh) + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + params, _ = curve_fit(get_ap_func(self.aperiodic_mode), + freqs[perc_mask], power_spectrum[perc_mask], + p0=popt, maxfev=self._maxfev, bounds=self._ap_bounds) + except (RuntimeError, TypeError) as e: + raise FitError(f"falló el ajuste robusto del fondo: {e}") + return params + + def _fit_peaks(self, flat_iter): + flat_iter = np.array(flat_iter, copy=True) + flat_iter[flat_iter < 0] = 0 # modificación 2 + return super()._fit_peaks(flat_iter) + + +def ajustar(f, espectro, p) -> dict: + """Ajusta un espectro (µV²/Hz, escala lineal). Devuelve exponente, offset, r2, error, picos, ok.""" + fm = FOOOFWilkinson(peak_width_limits=p["aperiodico.ancho_picos_hz"], + max_n_peaks=p["aperiodico.max_picos"], + peak_threshold=p["aperiodico.umbral_pico"], + aperiodic_mode="fixed", verbose=False, + ap_percentil=p["aperiodico.percentil_ap"]) + vacio = {"exponente": np.nan, "offset": np.nan, "r2": np.nan, "error": np.nan, + "picos": [], "ok": False, "modelo": None} + if espectro is None or not np.all(np.isfinite(espectro)) or np.any(espectro <= 0): + return vacio + fm.fit(np.asarray(f, float), np.asarray(espectro, float), list(p["aperiodico.rango_hz"])) + if not fm.has_model: + return vacio + offset, exponente = fm.aperiodic_params_ + r2 = float(fm.r_squared_) + return {"exponente": float(exponente), "offset": float(offset), "r2": r2, + "error": float(fm.error_), + "picos": [tuple(map(float, pk)) for pk in fm.peak_params_], # (frecuencia, potencia, ancho) + "ok": r2 >= p["aperiodico.r2_minimo"], "modelo": fm} + + +def potencia_periodica(resultado: dict, banda) -> float: + """Media del espectro aplanado (espectro − fondo, log10) en una banda. Medida secundaria.""" + fm = resultado.get("modelo") + if fm is None: + return np.nan + sel = (fm.freqs >= banda[0]) & (fm.freqs < banda[1]) + return float(np.mean(fm._spectrum_flat[sel])) if sel.any() else np.nan diff --git a/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/espectro.py b/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/espectro.py new file mode 100644 index 0000000..3510454 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/aperiodic/_bio/espectro.py @@ -0,0 +1,51 @@ +# Copied unchanged from biomarcadores-tea/biomarcadores/espectro.py @ 7dfc641 (sha256 211103b9d1d06ab3f7a19a463dfbb41ebba682862c6d8db6b6be54f7a961693a) +""" +espectro.py — Espectro de potencia por electrodo y por región, como Wilkinson 2024. + + f, P = espectro.multitaper(prep, ventanas_elegidas, p) # P: electrodos × frecuencias + reg = espectro.por_region(P, prep.canales, p) # {"frontal": espectro, ...} + +Cada ventana de 2 s se multiplica por 3 «tapers» (ventanas suaves distintas entre sí), se +calcula su espectro con cada una y se promedian: da un espectro menos ruidoso que con una +sola. Luego se promedian todas las ventanas elegidas. La región es el promedio de los +espectros de sus electrodos (Wilkinson promedia el espectro, no la señal). +""" + +from __future__ import annotations + +import numpy as np +from scipy.signal.windows import dpss + + +def multitaper(prep, tabla_elegida, p): + """Promedio de los espectros de las ventanas elegidas. Devuelve (frecuencias, P) en µV²/Hz.""" + n = int(round(p["ventanas.duracion_s"] * prep.fs)) + k = int(p["espectro.tapers"]) + tapers = dpss(n, NW=(k + 1) / 2, Kmax=k) # k = 2·NW − 1 + f = np.fft.rfftfreq(n, 1 / prep.fs) + acum = np.zeros((prep.datos.shape[1], f.size)) + usadas = 0 + for i0 in tabla_elegida["i0"].to_numpy(): + seg = prep.datos[i0:i0 + n] + if not np.isfinite(seg).all(): + continue + seg = seg - seg.mean(axis=0) + X = np.fft.rfft(tapers[:, :, None] * seg[None, :, :], axis=1) # taper × f × canal + S = (np.abs(X) ** 2).mean(axis=0).T / prep.fs # canal × f + S[:, 1:-1] *= 2 # un solo lado + acum += S + usadas += 1 + if usadas == 0: + return f, None + return f, acum / usadas + + +def por_region(P, canales, p) -> dict: + """{región: espectro promedio de sus electrodos presentes}; omite regiones sin electrodos.""" + out = {} + for region, elec in p["regiones"].items(): + idx = [canales.index(e) for e in elec if e in canales] + if idx: + out[region] = P[idx].mean(axis=0) + out["todo"] = P.mean(axis=0) + return out diff --git a/src/tea_modulo/legacy/biomarkers/aperiodic/_windows2s.py b/src/tea_modulo/legacy/biomarkers/aperiodic/_windows2s.py new file mode 100644 index 0000000..91e2fe9 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/aperiodic/_windows2s.py @@ -0,0 +1,72 @@ +""" +The 2 s window table of the cluster route, rebuilt from the contract (private +copy; aperiodic and mse modules own one each). + +As biomarcadores ventanas.cortar + estado_director.excluir_por_estado / etiquetar +@ 7dfc641: back-to-back 2 s windows; a window is clean if it has no gap, its 4 s QC +window is clean (not in Preprocessed.quality_spans), it is at least `edge_s` from the +start or end of a gap-free run, and its annotated state is not excluded and not +mixed; its state is the sleep_state label of the 4 s window starting at the same +time, or the one starting 2 s before. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + + +def table(study, variant: str, dur_s: float = 2.0, edge_s: float = 2.0) -> pd.DataFrame: + prep = study.prep + raw = prep.variant(variant) + fs = float(raw.info["sfreq"]) + n_t = raw.n_times + gap = np.zeros(n_t, bool) + for a in raw.annotations: + if a["description"].startswith("BAD_ACQ_SKIP"): + gap[int(a["onset"] * fs):int((a["onset"] + a["duration"]) * fs)] = True + unclean = np.zeros(n_t, bool) + for r in prep.quality_spans.itertuples(): + unclean[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True + near = np.zeros(n_t, bool) + b = int(round(edge_s * fs)) + v = np.concatenate([[False], ~gap, [False]]).astype(int) + d = np.diff(v) + for s, e in zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)): + near[s:min(s + b, e)] = True + near[max(e - b, s):e] = True + ev = study.label("annotation_mask").events + excl = set(ev.attrs.get("excluded_states", ())) + ivs = [(r.onset_s, r.onset_s + r.duration_s, r.estado) for r in ev.itertuples()] + lab = study.label("sleep_state").per_window + by_start = dict(zip(prep.windows.start_s.round(2), lab)) + n = int(round(dur_s * fs)) + rows = [] + for k in range(n_t // n): + a0, a1 = k * n, (k + 1) * n + t0, t1 = a0 / fs, a1 / fs + ov = {} + for lo, hi, st in ivs: + o = min(t1, hi) - max(t0, lo) + if o > 0: + ov[st] = ov.get(st, 0) + o + st = max(ov, key=ov.get) if ov else "sin_etiqueta" + mixed = bool(ov) and ov[st] < 0.8 * (t1 - t0) + if gap[a0:a1].any(): + why = "hueco" + elif unclean[a0:a1].any(): + why = "no_limpia_qc" + elif near[a0:a1].any(): + why = "borde_de_tramo" + elif st in excl: + why = f"estado_{st}" + elif mixed: + why = "mixta" + else: + why = "" + state = by_start.get(round(t0, 2), by_start.get(round(t0 - 2.0, 2), "sin_estado")) + rows.append({"t_ini": t0, "t_fin": t1, "i0": a0, "limpia": why == "", "motivo": why, "vigilancia": state}) + t = pd.DataFrame(rows) + for s in ("vigilia", "somnolencia", "sueno"): + t[s] = t.vigilancia.eq(s) if len(t) else pd.Series(dtype=bool) + return t diff --git a/src/tea_modulo/legacy/biomarkers/aperiodic/api.py b/src/tea_modulo/legacy/biomarkers/aperiodic/api.py new file mode 100644 index 0000000..98f3de5 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/aperiodic/api.py @@ -0,0 +1,121 @@ +""" +Legacy aperiodic: the cluster route's aperiodic exponent (pipeline.analizar_director +@ 7dfc641) on biomarcadores' espectro.py and aperiodico.py, copied unchanged: +multitaper spectrum (3 DPSS tapers, 2 s windows) of the clean 2 s windows of each +state, averaged per region (Wilkinson 2024 regions + 'todo'), FOOOF 1.1 with +Wilkinson's two modifications over 2.5-50 Hz. The exponent is NaN with fewer than +20 windows or when the fit's R² < 0.9. + +Features: aperiodic__. +""" + +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, _windows2s +from ._bio import aperiodico, espectro + +# parametros.toml @ 7dfc641 (the values the cluster route uses) +P = {"ventanas.duracion_s": 2.0, "ventanas.borde_s": 2.0, "ventanas.min_ventanas": 20, "espectro.tapers": 3, + "regiones": {"frontal": ["F3", "Fz", "F4"], "central": ["C3", "Cz", "C4"], + "temporal": ["T3", "T4", "P3", "P4"], "posterior": ["O1", "O2", "Pz"]}, + "aperiodico.rango_hz": [2.5, 50.0], "aperiodico.ancho_picos_hz": [0.5, 18.0], "aperiodico.max_picos": 7, + "aperiodico.umbral_pico": 2.0, "aperiodico.percentil_ap": 10.0, "aperiodico.r2_minimo": 0.9, + "complejidad.m": 2, "complejidad.r": 0.15, "complejidad.escala_max": 20, "complejidad.escala_corte": 5, + "complejidad.segmento_s": 30, "complejidad.max_segmentos": 4} +STATES = ("vigilia", "somnolencia", "sueno") +REGIONS = ('frontal', 'central', 'temporal', 'posterior', 'todo') +FEATURES = tuple(f"aperiodic_{r}_{s}" for s in STATES for r in REGIONS) +DIRECTOR_COMMIT = "7dfc641" + + +class LegacyAperiodic: + name = "aperiodic" + version = f"0.1.0+director.{DIRECTOR_COMMIT}" + contract_version = CONTRACT_VERSION + requires = ("sleep_state", "annotation_mask") + 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 _reg(self, study): + raw = study.prep.variant(self.variant) + eeg = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg"] + class R: + pass + r = R() + r.datos, r.canales, r.fs = raw.get_data(picks=eeg).T * 1e6, eeg, float(raw.info["sfreq"]) + return r + + def measure(self, study) -> dict: + reg = self._reg(study) + tabla = _windows2s.table(study, self.variant, P["ventanas.duracion_s"], P["ventanas.borde_s"]) + out = {f: float("nan") for f in FEATURES} + for s in STATES: + elegidas = tabla[tabla.limpia & tabla[s]] + if len(elegidas) < P["ventanas.min_ventanas"]: + continue + f, Pw = espectro.multitaper(reg, elegidas, P) + if Pw is None: + continue + for region, esp in espectro.por_region(Pw, reg.canales, P).items(): + r = aperiodico.ajustar(f, esp, P) + if r["ok"]: + out[f"aperiodic_{region}_{s}"] = float(r["exponente"]) + 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 = LegacyAperiodic() diff --git a/src/tea_modulo/legacy/biomarkers/mse/__init__.py b/src/tea_modulo/legacy/biomarkers/mse/__init__.py new file mode 100644 index 0000000..a2f22c3 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/mse/__init__.py @@ -0,0 +1,3 @@ +from tea_modulo.legacy.biomarkers.mse.api import MODULE, LegacyMSE + +__all__ = ["MODULE", "LegacyMSE"] diff --git a/src/tea_modulo/legacy/biomarkers/mse/_baseline.py b/src/tea_modulo/legacy/biomarkers/mse/_baseline.py new file mode 100644 index 0000000..167759e --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/mse/_baseline.py @@ -0,0 +1,241 @@ +""" +Baselines, ported as they are (private copy; every legacy 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/legacy/biomarkers/mse/_bio/__init__.py b/src/tea_modulo/legacy/biomarkers/mse/_bio/__init__.py new file mode 100644 index 0000000..df774e1 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/mse/_bio/__init__.py @@ -0,0 +1 @@ +"""biomarcadores-tea/biomarcadores files copied unchanged (see each header).""" diff --git a/src/tea_modulo/legacy/biomarkers/mse/_bio/complejidad.py b/src/tea_modulo/legacy/biomarkers/mse/_bio/complejidad.py new file mode 100644 index 0000000..aa6fd90 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/mse/_bio/complejidad.py @@ -0,0 +1,138 @@ +# Copied unchanged from biomarcadores-tea/biomarcadores/complejidad.py @ 7dfc641 (sha256 3808956fa51df831f5cfb83ff905a975bf81153ddc28f7944e37d73fd311fc0c) +""" +complejidad.py — Entropía multiescala (MSE) del EEG. Medida EXPLORATORIA (decisión del 23 oct 2026). + + curva = complejidad.mse(x, m=2, r=0.15, escalas=range(1, 21)) # un tramo, un electrodo + res = complejidad.por_region(reg, tabla_estado, p) # curva por región + +Método de Costa, Goldberger y Peng (2002), con la entropía muestral de Richman y Moorman (2000): + 1. Entropía muestral (SampEn): de todos los pedazos de m puntos que se parecen (diferencia + máxima ≤ r), ¿qué fracción se sigue pareciendo al agregar un punto más? SampEn = −ln(A/B). + Señal repetitiva → los parecidos se mantienen → SampEn baja. + 2. Escala τ: antes de medir, la señal se promedia en bloques de τ puntos seguidos (a 250 Hz, + la escala 1 son 4 ms y la escala 20 son 80 ms). + 3. r se fija UNA vez, como fracción de la desviación estándar del tramo original, y se usa en + todas las escalas (como Costa 2002). Al ser relativa, no depende de la ganancia del equipo. + +Los tramos son de `complejidad.segmento_s` segundos continuos y limpios; se promedia sobre tramos +y luego sobre los electrodos de cada región. + +Comprobaciones de referencia (Costa 2002), en pruebas/: el ruido blanco pierde entropía al +subir la escala; el ruido 1/f la mantiene casi constante. +""" + +from __future__ import annotations + +import numpy as np +from scipy.spatial import cKDTree + + +def _pares(emb: np.ndarray, r: float) -> int: + """Pares distintos (i < j) cuya distancia máxima entre coordenadas es ≤ r.""" + arbol = cKDTree(emb) + total = arbol.count_neighbors(arbol, r, p=np.inf) # pares ordenados, incluye i = j + return int((total - len(emb)) // 2) + + +def sampen(x: np.ndarray, m: int, r: float, valido: np.ndarray | None = None) -> float: + """Entropía muestral de Richman y Moorman; NaN si no hay parecidos suficientes. Con `valido`, + solo cuentan los pedazos cuyos m + 1 puntos son válidos.""" + x = np.asarray(x, dtype=float) + n = len(x) - m # mismos N − m pedazos para m y m + 1 + if n < 10: + return np.nan + emb_m = np.lib.stride_tricks.sliding_window_view(x, m)[:n] + emb_m1 = np.lib.stride_tricks.sliding_window_view(x, m + 1)[:n] + if valido is not None: + ok = np.lib.stride_tricks.sliding_window_view(valido, m + 1).all(axis=1) + if ok.sum() < 10: + return np.nan + emb_m, emb_m1 = emb_m[ok], emb_m1[ok] + b = _pares(emb_m, r) + a = _pares(emb_m1, r) + if a == 0 or b == 0: + return np.nan + return float(-np.log(a / b)) + + +def granulado(x: np.ndarray, tau: int) -> np.ndarray: + """Promedio por bloques de tau puntos seguidos (sin traslape).""" + n = len(x) // tau + return np.asarray(x[:n * tau], dtype=float).reshape(n, tau).mean(axis=1) + + +def mse(x: np.ndarray, m: int, r: float, escalas, excluir: np.ndarray | None = None) -> np.ndarray: + """Curva de entropía por escala de un tramo continuo (sin NaN). `excluir` marca muestras que + no cuentan (p. ej. husos): un bloque de la escala queda fuera si contiene alguna.""" + x = np.asarray(x, dtype=float) + if excluir is None: + tol = r * np.std(x) + return np.array([sampen(granulado(x, t), m, tol) for t in escalas]) + valido = ~np.asarray(excluir, dtype=bool) + tol = r * np.std(x[valido]) + return np.array([sampen(granulado(x, t), m, tol, granulado(valido, t) == 1) for t in escalas]) + + +def tramos_continuos(tabla, columna_estado: str, p) -> list[int]: + """ + Índices de inicio (en muestras) de tramos de `segmento_s` segundos formados por ventanas de + 2 s seguidas, todas limpias y del estado pedido. Como máximo `max_segmentos`, repartidos a lo + largo del registro. + """ + por_tramo = int(round(p["complejidad.segmento_s"] / p["ventanas.duracion_s"])) + ok = (tabla.limpia & tabla[columna_estado]).to_numpy() + inicios, k = [], 0 + while k + por_tramo <= len(ok): + if ok[k:k + por_tramo].all(): + inicios.append(int(tabla.i0.iloc[k])) + k += por_tramo + else: + k += 1 + maximo = p["complejidad.max_segmentos"] + if len(inicios) > maximo: + elegidos = np.linspace(0, len(inicios) - 1, maximo).round().astype(int) + inicios = [inicios[i] for i in elegidos] + return inicios + + +def por_electrodo(reg, tabla, columna_estado: str, p, canales=None) -> dict: + """{electrodo: curva promedio sobre tramos} para un estado, más {"_n_tramos": n}.""" + escalas = range(1, p["complejidad.escala_max"] + 1) + n = int(round(p["complejidad.segmento_s"] * reg.fs)) + inicios = tramos_continuos(tabla, columna_estado, p) + out = {"_n_tramos": len(inicios)} + if not inicios: + return out + for c in (reg.canales if canales is None else canales): + j = reg.canales.index(c) + tramos = [mse(reg.datos[i0:i0 + n, j], p["complejidad.m"], p["complejidad.r"], escalas) + for i0 in inicios] + out[c] = np.nanmean(tramos, axis=0) + return out + + +def por_region(reg, tabla, columna_estado: str, p) -> dict: + """ + {región: curva promedio} para un estado, más {"_n_tramos": n}. Cada curva es el promedio, sobre + tramos y electrodos de la región, de la MSE de cada electrodo. + """ + regiones = dict(p["regiones"]) + regiones["todo"] = sorted({e for v in regiones.values() for e in v}) + canales = sorted({c for v in regiones.values() for c in v if c in reg.canales}) + curvas = por_electrodo(reg, tabla, columna_estado, p, canales) + out = {"_n_tramos": curvas["_n_tramos"]} + if not out["_n_tramos"]: + return out + for region, elec in regiones.items(): + presentes = [curvas[e] for e in elec if e in curvas] + if presentes: + out[region] = np.nanmean(presentes, axis=0) + return out + + +def indices(curva: np.ndarray, p) -> dict: + """Resúmenes de la curva: suma en escalas finas, gruesas y total (índice de complejidad).""" + corte = p["complejidad.escala_corte"] + return {"mse_fina": float(np.nansum(curva[:corte])), + "mse_gruesa": float(np.nansum(curva[corte:])), + "mse_total": float(np.nansum(curva))} diff --git a/src/tea_modulo/legacy/biomarkers/mse/_windows2s.py b/src/tea_modulo/legacy/biomarkers/mse/_windows2s.py new file mode 100644 index 0000000..91e2fe9 --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/mse/_windows2s.py @@ -0,0 +1,72 @@ +""" +The 2 s window table of the cluster route, rebuilt from the contract (private +copy; aperiodic and mse modules own one each). + +As biomarcadores ventanas.cortar + estado_director.excluir_por_estado / etiquetar +@ 7dfc641: back-to-back 2 s windows; a window is clean if it has no gap, its 4 s QC +window is clean (not in Preprocessed.quality_spans), it is at least `edge_s` from the +start or end of a gap-free run, and its annotated state is not excluded and not +mixed; its state is the sleep_state label of the 4 s window starting at the same +time, or the one starting 2 s before. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + + +def table(study, variant: str, dur_s: float = 2.0, edge_s: float = 2.0) -> pd.DataFrame: + prep = study.prep + raw = prep.variant(variant) + fs = float(raw.info["sfreq"]) + n_t = raw.n_times + gap = np.zeros(n_t, bool) + for a in raw.annotations: + if a["description"].startswith("BAD_ACQ_SKIP"): + gap[int(a["onset"] * fs):int((a["onset"] + a["duration"]) * fs)] = True + unclean = np.zeros(n_t, bool) + for r in prep.quality_spans.itertuples(): + unclean[int(r.onset_s * fs):int((r.onset_s + r.duration_s) * fs)] = True + near = np.zeros(n_t, bool) + b = int(round(edge_s * fs)) + v = np.concatenate([[False], ~gap, [False]]).astype(int) + d = np.diff(v) + for s, e in zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)): + near[s:min(s + b, e)] = True + near[max(e - b, s):e] = True + ev = study.label("annotation_mask").events + excl = set(ev.attrs.get("excluded_states", ())) + ivs = [(r.onset_s, r.onset_s + r.duration_s, r.estado) for r in ev.itertuples()] + lab = study.label("sleep_state").per_window + by_start = dict(zip(prep.windows.start_s.round(2), lab)) + n = int(round(dur_s * fs)) + rows = [] + for k in range(n_t // n): + a0, a1 = k * n, (k + 1) * n + t0, t1 = a0 / fs, a1 / fs + ov = {} + for lo, hi, st in ivs: + o = min(t1, hi) - max(t0, lo) + if o > 0: + ov[st] = ov.get(st, 0) + o + st = max(ov, key=ov.get) if ov else "sin_etiqueta" + mixed = bool(ov) and ov[st] < 0.8 * (t1 - t0) + if gap[a0:a1].any(): + why = "hueco" + elif unclean[a0:a1].any(): + why = "no_limpia_qc" + elif near[a0:a1].any(): + why = "borde_de_tramo" + elif st in excl: + why = f"estado_{st}" + elif mixed: + why = "mixta" + else: + why = "" + state = by_start.get(round(t0, 2), by_start.get(round(t0 - 2.0, 2), "sin_estado")) + rows.append({"t_ini": t0, "t_fin": t1, "i0": a0, "limpia": why == "", "motivo": why, "vigilancia": state}) + t = pd.DataFrame(rows) + for s in ("vigilia", "somnolencia", "sueno"): + t[s] = t.vigilancia.eq(s) if len(t) else pd.Series(dtype=bool) + return t diff --git a/src/tea_modulo/legacy/biomarkers/mse/api.py b/src/tea_modulo/legacy/biomarkers/mse/api.py new file mode 100644 index 0000000..68f0dae --- /dev/null +++ b/src/tea_modulo/legacy/biomarkers/mse/api.py @@ -0,0 +1,117 @@ +""" +Legacy mse: the cluster route's multiscale entropy (pipeline.analizar_director @ 7dfc641) +on biomarcadores' complejidad.py, copied unchanged: up to 4 runs of 30 s made of +consecutive clean 2 s windows of one state, sample entropy (m = 2, r = 0.15 SD) of +the coarse-grained signal at scales 1-20 per electrode, averaged over runs and the +electrodes of all regions ('todo'); fine (scales 1-5), coarse (6-20) and total sums. + +Features: mse__. +""" + +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, _windows2s +from ._bio import complejidad + +# parametros.toml @ 7dfc641 (the values the cluster route uses) +P = {"ventanas.duracion_s": 2.0, "ventanas.borde_s": 2.0, "ventanas.min_ventanas": 20, "espectro.tapers": 3, + "regiones": {"frontal": ["F3", "Fz", "F4"], "central": ["C3", "Cz", "C4"], + "temporal": ["T3", "T4", "P3", "P4"], "posterior": ["O1", "O2", "Pz"]}, + "aperiodico.rango_hz": [2.5, 50.0], "aperiodico.ancho_picos_hz": [0.5, 18.0], "aperiodico.max_picos": 7, + "aperiodico.umbral_pico": 2.0, "aperiodico.percentil_ap": 10.0, "aperiodico.r2_minimo": 0.9, + "complejidad.m": 2, "complejidad.r": 0.15, "complejidad.escala_max": 20, "complejidad.escala_corte": 5, + "complejidad.segmento_s": 30, "complejidad.max_segmentos": 4} +STATES = ("vigilia", "somnolencia", "sueno") +FEATURES = tuple(f"mse_{k}_{s}" for s in STATES for k in ("fine", "coarse", "total")) +KEYS = {"fine": "mse_fina", "coarse": "mse_gruesa", "total": "mse_total"} +DIRECTOR_COMMIT = "7dfc641" + + +class LegacyMSE: + name = "mse" + version = f"0.1.0+director.{DIRECTOR_COMMIT}" + contract_version = CONTRACT_VERSION + requires = ("sleep_state", "annotation_mask") + 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 _reg(self, study): + raw = study.prep.variant(self.variant) + eeg = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg"] + class R: + pass + r = R() + r.datos, r.canales, r.fs = raw.get_data(picks=eeg).T * 1e6, eeg, float(raw.info["sfreq"]) + return r + + def measure(self, study) -> dict: + reg = self._reg(study) + tabla = _windows2s.table(study, self.variant, P["ventanas.duracion_s"], P["ventanas.borde_s"]) + out = {f: float("nan") for f in FEATURES} + for s in STATES: + if (tabla.limpia & tabla[s]).sum() < P["ventanas.min_ventanas"]: + continue + res = complejidad.por_region(reg, tabla, s, P) + if res.get("_n_tramos", 0) and "todo" in res: + ind = complejidad.indices(res["todo"], P) + for k, key in KEYS.items(): + out[f"mse_{k}_{s}"] = float(ind[key]) + 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 = LegacyMSE() diff --git a/tests/test_aperiodic_mse.py b/tests/test_aperiodic_mse.py new file mode 100644 index 0000000..97e1c62 --- /dev/null +++ b/tests/test_aperiodic_mse.py @@ -0,0 +1,52 @@ +"""Aperiodic exponent and multiscale entropy: legacy copies unchanged, modern agrees with legacy.""" + +from __future__ import annotations + +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 + +ROOT = Path(__file__).resolve().parents[1] +BIO = ROOT / "biomarcadores-tea" / "biomarcadores" +LEG = ROOT / "src" / "tea_modulo" / "legacy" / "biomarkers" + + +@pytest.mark.skipif(not BIO.exists(), reason="submodule absent") +@pytest.mark.parametrize("copy", ["aperiodic/_bio/aperiodico.py", "aperiodic/_bio/espectro.py", "mse/_bio/complejidad.py"]) +def test_copies_unchanged(copy): + body = (LEG / copy).read_text(encoding="utf-8").split("\n", 1)[1] + assert body == (BIO / Path(copy).name).read_text(encoding="utf-8") + + +@pytest.fixture(scope="module") +def studies(tmp_path_factory): + p = make_edf(tmp_path_factory.mktemp("apmse") / "s.edf", minutes=8) + return (Pipeline.default("modern").study(p, plan=DIRECTOR_CLUSTER, age_months=28), + Pipeline.default("legacy").study(p, plan=DIRECTOR_CLUSTER, age_months=28)) + + +@pytest.mark.parametrize("name,rel", [("aperiodic", 0.02), ("mse", 0.01)]) +def test_modern_agrees_with_legacy(studies, name, rel): + m = Pipeline.default("modern").module(name).measure(studies[0]) + l = Pipeline.default("legacy").module(name).measure(studies[1]) + assert any(np.isfinite(v) for v in l.values()) + for k in m: + if np.isnan(l[k]): + assert np.isnan(m[k]), k + else: + assert m[k] == pytest.approx(l[k], rel=rel), k + + +@pytest.mark.parametrize("name", ["aperiodic", "mse"]) +def test_biomarker_contract(tmp_path, name): + 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)] + mod = type(pipe.module(name))(baseline="age_blocks") + check_biomarker(mod, sts, [20, 24, 28]) diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index 77a3014..876e176 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -17,7 +17,7 @@ SRC = Path(__file__).resolve().parents[1] / "src" / "tea_modulo" # Approved third-party libraries (top-level import names). BASE = {"numpy", "scipy", "pandas", "mne", "sklearn", "antropy", "fooof", "yasa", "meegkit", "edfio"} -LEGACY = {"numpy", "scipy", "pandas", "sklearn"} +LEGACY = {"numpy", "scipy", "pandas", "sklearn", "fooof"} # fooof: biomarcadores-tea dependency EXTRA = { "validation": {"fhir"}, "serving": {"mlflow"},