modern annotation_mask, sleep_state and posterior_rhythm
- processes.annotation_mask: the director's state words and interval rules
on the EDF+ annotations (MNE), window dominant state and 'mixta'.
- processes.sleep_state: vigilancia's features from batched Hann
periodograms (mne psd_array_welch), depth index, HK1K cut-offs or cohort
reference + KMeans (scikit-learn) after train().
- biomarkers.posterior_rhythm: Welch of the wake windows (MNE), 1/f-fitted
dominant peak, median of O1 O2 P3 P4; private copy of the baselines.
- Registered as the modern modules; Pipeline.default("modern") now runs
the full slice.
On a synthetic study: annotation states and sleep-state labels identical to
legacy, rhythm equal (6.5 Hz); contract suites and cohort cut-offs tested.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""biomarkers: one independent module each."""
|
||||
@@ -0,0 +1,3 @@
|
||||
from tea_modulo.biomarkers.posterior_rhythm.api import MODULE, PosteriorRhythm
|
||||
|
||||
__all__ = ["MODULE", "PosteriorRhythm"]
|
||||
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
Baselines, ported as they are (private copy; every biomarker owns one).
|
||||
|
||||
Functions copied verbatim:
|
||||
- biomarcadores-tea/biomarcadores/curvas.py @ 7dfc641: CUANTILES, rejilla,
|
||||
cuantil_ponderado, ajustar, en_edad, z_y_posicion
|
||||
- codigo/perfil_alteraciones.py @ c7a4736: MIN_CONTROLES_BLOQUE, bordes_edad,
|
||||
z_por_bloques, marcar_fuera (the cut-offs = p5/p95 of the controls' own z,
|
||||
as in construir_perfil.mete), with BLOQUES from codigo/curva_desarrollo.py
|
||||
|
||||
Two classes wrap them with fit / deviation / to_dict / from_dict:
|
||||
CentileCurves outside: below p5 or above p95 of the age curve; z = z_robusto
|
||||
AgeBlockZ outside: z beyond the controls' z p5 / p95; z = (x - median) / MAD
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
# ------------------------------------------------------------------ curvas.py (verbatim)
|
||||
CUANTILES = {"p5": 0.05, "p25": 0.25, "mediana": 0.5, "p75": 0.75, "p95": 0.95}
|
||||
|
||||
|
||||
def rejilla(edad_min=1.0, edad_max=216.0, puntos=120) -> np.ndarray:
|
||||
"""Edades (meses) espaciadas en escala log."""
|
||||
return np.exp(np.linspace(np.log(edad_min), np.log(edad_max), puntos))
|
||||
|
||||
|
||||
def cuantil_ponderado(x: np.ndarray, w: np.ndarray, q: float) -> float:
|
||||
"""Cuantil con pesos (interpolando entre los puntos medios de cada peso acumulado)."""
|
||||
o = np.argsort(x)
|
||||
x, w = x[o], w[o]
|
||||
c = (np.cumsum(w) - 0.5 * w) / w.sum()
|
||||
return float(np.interp(q, c, x))
|
||||
|
||||
|
||||
def ajustar(valores, edades_meses, ancho_log=0.2, n_min=30, edades=None) -> pd.DataFrame:
|
||||
"""Curva de percentiles: una fila por edad de la rejilla (edad_meses, n_efectivo, p5…p95)."""
|
||||
v = np.asarray(valores, dtype=float)
|
||||
e = np.asarray(edades_meses, dtype=float)
|
||||
ok = np.isfinite(v) & np.isfinite(e) & (e > 0)
|
||||
v, le = v[ok], np.log(e[ok])
|
||||
edades = rejilla() if edades is None else np.asarray(edades, dtype=float)
|
||||
filas = []
|
||||
for a in edades:
|
||||
w = np.exp(-0.5 * ((le - np.log(a)) / ancho_log) ** 2)
|
||||
n_ef = w.sum() ** 2 / (w ** 2).sum() if w.sum() > 0 else 0.0
|
||||
fila = {"edad_meses": round(float(a), 3), "n_efectivo": round(float(n_ef), 1)}
|
||||
dentro = len(le) and le.min() <= np.log(a) <= le.max()
|
||||
for nom, q in CUANTILES.items():
|
||||
fila[nom] = (round(cuantil_ponderado(v, w, q), 4) if n_ef >= n_min and dentro
|
||||
else np.nan)
|
||||
filas.append(fila)
|
||||
return pd.DataFrame(filas)
|
||||
|
||||
|
||||
def en_edad(edad_meses: float, curva: pd.DataFrame) -> dict | None:
|
||||
"""p5…p95 a una edad exacta (interpolados en log(edad)); None si la curva no la cubre."""
|
||||
c = curva.dropna(subset=list(CUANTILES))
|
||||
if not len(c) or not np.isfinite(edad_meses) or edad_meses <= 0:
|
||||
return None
|
||||
la, lx = np.log(edad_meses), np.log(c.edad_meses.to_numpy())
|
||||
if la < lx.min() or la > lx.max():
|
||||
return None
|
||||
return {nom: float(np.interp(la, lx, c[nom].to_numpy())) for nom in CUANTILES}
|
||||
|
||||
|
||||
def z_y_posicion(valores, edades_meses, curva: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""`z_robusto` y `posicion` de muchos valores a la vez (mismo resultado, sin bucle por fila)."""
|
||||
v = np.asarray(valores, dtype=float)
|
||||
e = np.asarray(edades_meses, dtype=float)
|
||||
z = np.full(v.shape, np.nan)
|
||||
pos = np.full(v.shape, "sin referencia", dtype=object)
|
||||
c = curva.dropna(subset=list(CUANTILES))
|
||||
if not len(c):
|
||||
return z, pos
|
||||
lx = np.log(c.edad_meses.to_numpy())
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
la = np.where(e > 0, np.log(np.where(e > 0, e, 1.0)), np.nan)
|
||||
ok = np.isfinite(v) & np.isfinite(la) & (la >= lx.min()) & (la <= lx.max())
|
||||
q = {k: np.interp(la, lx, c[k].to_numpy()) for k in CUANTILES}
|
||||
lado = np.where(v < q["mediana"], q["mediana"] - q["p5"], q["p95"] - q["mediana"])
|
||||
zz = (v - q["mediana"]) / (lado / 1.645)
|
||||
z[ok] = np.where(lado[ok] > 0, zz[ok], np.nan)
|
||||
pos[ok] = np.where(v[ok] < q["p5"][ok], "bajo p5",
|
||||
np.where(v[ok] > q["p95"][ok], "sobre p95", "dentro"))
|
||||
return z, pos
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ perfil_alteraciones.py (verbatim)
|
||||
BLOQUES = (2, 4, 6, 9, 12, 18, 24, 36, 48, 60, 84, 120, 192) # curva_desarrollo.BLOQUES
|
||||
MIN_CONTROLES_BLOQUE = 12
|
||||
|
||||
|
||||
def bordes_edad(edad_min, edad_max):
|
||||
"""Bloques de la curva de desarrollo recortados al rango pedido."""
|
||||
b = [x for x in BLOQUES if edad_min < x < edad_max]
|
||||
return [edad_min] + b + [edad_max]
|
||||
|
||||
|
||||
def z_por_bloques(xT, edadT, xC, edadC, bordes):
|
||||
"""
|
||||
z de cada caso contra la mediana y el MAD de los controles de su bloque
|
||||
de edad, y el z de los propios controles para sacar los cortes.
|
||||
|
||||
Un bloque con menos de MIN_CONTROLES_BLOQUE controles usa la normativa
|
||||
del rango completo, y se avisa: una banda de 8 controles es una línea
|
||||
firme dibujada sobre nada.
|
||||
"""
|
||||
xT = np.asarray(xT, dtype=float)
|
||||
xC = np.asarray(xC, dtype=float)
|
||||
bT = np.digitize(np.asarray(edadT, dtype=float), bordes[1:-1])
|
||||
bC = np.digitize(np.asarray(edadC, dtype=float), bordes[1:-1])
|
||||
okC = np.isfinite(xC)
|
||||
med_g = float(np.nanmedian(xC))
|
||||
mad_g = float(1.4826 * np.nanmedian(np.abs(xC - med_g))) or np.nan
|
||||
|
||||
zT = np.full(len(xT), np.nan)
|
||||
zC = np.full(len(xC), np.nan)
|
||||
for b in range(len(bordes) - 1):
|
||||
enC = okC & (bC == b)
|
||||
if enC.sum() >= MIN_CONTROLES_BLOQUE:
|
||||
med = float(np.median(xC[enC]))
|
||||
mad = float(1.4826 * np.median(np.abs(xC[enC] - med)))
|
||||
else:
|
||||
med, mad = med_g, mad_g
|
||||
if not np.isfinite(mad) or mad == 0:
|
||||
continue
|
||||
zT[bT == b] = (xT[bT == b] - med) / mad
|
||||
zC[enC] = (xC[enC] - med) / mad
|
||||
return zT, zC
|
||||
|
||||
|
||||
def marcar_fuera(P, cortes):
|
||||
F = pd.DataFrame(0, index=P.index,
|
||||
columns=[f"fuera_{c}" for c in P.columns])
|
||||
for c in P.columns:
|
||||
lo, hi = cortes[c]
|
||||
F.loc[P[c] < lo, f"fuera_{c}"] = -1
|
||||
F.loc[P[c] > hi, f"fuera_{c}"] = 1
|
||||
return F
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ wrappers
|
||||
class CentileCurves:
|
||||
name = "curves"
|
||||
|
||||
def __init__(self, ancho_log=0.2, n_min=30, curva=None):
|
||||
self.ancho_log = ancho_log
|
||||
self.n_min = n_min
|
||||
self.curva = curva
|
||||
|
||||
def fit(self, values, ages_months):
|
||||
self.curva = ajustar(values, ages_months, ancho_log=self.ancho_log, n_min=self.n_min)
|
||||
return self
|
||||
|
||||
def deviation(self, values, ages_months):
|
||||
z, pos = z_y_posicion(values, ages_months, self.curva)
|
||||
outside = np.where(pos == "bajo p5", -1, np.where(pos == "sobre p95", 1, 0))
|
||||
return outside.astype(int), z
|
||||
|
||||
def to_dict(self):
|
||||
return {"name": self.name, "ancho_log": self.ancho_log, "n_min": self.n_min,
|
||||
"curva": self.curva.replace({np.nan: None}).to_dict("list")}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d):
|
||||
curva = pd.DataFrame(d["curva"]).astype(float)
|
||||
return cls(d["ancho_log"], d["n_min"], curva)
|
||||
|
||||
|
||||
class AgeBlockZ:
|
||||
name = "age_blocks"
|
||||
|
||||
def __init__(self, edad_min=12.0, edad_max=60.0, state=None):
|
||||
self.edad_min = edad_min
|
||||
self.edad_max = edad_max
|
||||
self.state = state
|
||||
|
||||
def fit(self, values, ages_months):
|
||||
v = np.asarray(values, float)
|
||||
e = np.asarray(ages_months, float)
|
||||
keep = (e >= self.edad_min) & (e <= self.edad_max) # perfil_alteraciones.filtra
|
||||
v, e = v[keep], e[keep]
|
||||
bordes = bordes_edad(self.edad_min, self.edad_max)
|
||||
_, zC = z_por_bloques(v, e, v, e, bordes)
|
||||
zC = zC[np.isfinite(zC)]
|
||||
blocks = []
|
||||
bC = np.digitize(e, bordes[1:-1])
|
||||
ok = np.isfinite(v)
|
||||
med_g = float(np.nanmedian(v))
|
||||
mad_g = float(1.4826 * np.nanmedian(np.abs(v - med_g))) or np.nan
|
||||
for b in range(len(bordes) - 1):
|
||||
en = ok & (bC == b)
|
||||
if en.sum() >= MIN_CONTROLES_BLOQUE:
|
||||
med = float(np.median(v[en]))
|
||||
blocks.append({"median": med, "mad": float(1.4826 * np.median(np.abs(v[en] - med))),
|
||||
"n": int(en.sum())})
|
||||
else:
|
||||
blocks.append({"median": med_g, "mad": mad_g, "n": int(en.sum()), "fallback": True})
|
||||
self.state = {"bordes": bordes, "blocks": blocks,
|
||||
"cortes": [float(np.percentile(zC, 5)), float(np.percentile(zC, 95))]
|
||||
if len(zC) else [np.nan, np.nan], "n": int(len(v))}
|
||||
return self
|
||||
|
||||
def deviation(self, values, ages_months):
|
||||
v = np.asarray(values, float)
|
||||
e = np.asarray(ages_months, float)
|
||||
bordes = self.state["bordes"]
|
||||
b = np.digitize(e, bordes[1:-1])
|
||||
z = np.full(len(v), np.nan)
|
||||
for i, (x, k) in enumerate(zip(v, b)):
|
||||
blk = self.state["blocks"][k]
|
||||
if np.isfinite(blk["mad"]) and blk["mad"] != 0:
|
||||
z[i] = (x - blk["median"]) / blk["mad"]
|
||||
P = pd.DataFrame({"m": z})
|
||||
F = marcar_fuera(P, {"m": tuple(self.state["cortes"])})
|
||||
return F["fuera_m"].to_numpy().astype(int), z
|
||||
|
||||
def to_dict(self):
|
||||
return {"name": self.name, "edad_min": self.edad_min, "edad_max": self.edad_max,
|
||||
"state": self.state}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d):
|
||||
return cls(d["edad_min"], d["edad_max"], d["state"])
|
||||
|
||||
|
||||
BASELINES = {"curves": CentileCurves, "age_blocks": AgeBlockZ}
|
||||
|
||||
|
||||
def make(name, **params):
|
||||
try:
|
||||
return BASELINES[name](**params)
|
||||
except KeyError:
|
||||
raise ValueError(f"unknown baseline {name!r}; one of {', '.join(BASELINES)}") from None
|
||||
|
||||
|
||||
def from_dict(d):
|
||||
return BASELINES[d["name"]].from_dict(d)
|
||||
@@ -0,0 +1,140 @@
|
||||
"""
|
||||
Modern posterior_rhythm (the cluster route's measure, medidas_director.ritmo):
|
||||
|
||||
windows 4 s windows labelled 'vigilia' by sleep_state, gap-free (at least 15)
|
||||
PSD mean Hann periodogram of those windows per channel (mne psd_array_welch,
|
||||
one segment per window, mean removed) — ritmo.psd_de_ventanas
|
||||
peak largest peak 3-14 Hz over a 1/f line fitted on 1.5-45 Hz without 4-16 Hz,
|
||||
at least 1.5 dB and not at the band edge — eeg_io.pico_dominante
|
||||
value median over O1 O2 P3 P4 with a peak, if at least 2 of them
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from tea_modulo.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS
|
||||
|
||||
from . import _baseline
|
||||
|
||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||
MIN_WINDOWS = 15
|
||||
MIN_CHANNELS = 2
|
||||
WINDOW_S = 4.0
|
||||
|
||||
|
||||
def dominant_peak(f, P, band=(3.0, 14.0), fit=(1.5, 45.0), exclude=(4.0, 16.0), min_db=1.5):
|
||||
val = (f >= fit[0]) & (f <= fit[1]) & (P > 0)
|
||||
bg = val & ~((f >= exclude[0]) & (f <= exclude[1]))
|
||||
if bg.sum() < 5:
|
||||
return np.nan, np.nan, False
|
||||
coef = np.polyfit(np.log10(f[bg]), np.log10(P[bg]), 1)
|
||||
resid = 10 * (np.log10(P[val]) - np.polyval(coef, np.log10(f[val])))
|
||||
fv = f[val]
|
||||
sel = (fv >= band[0]) & (fv <= band[1])
|
||||
if not sel.any():
|
||||
return np.nan, np.nan, False
|
||||
i = int(np.argmax(resid[sel]))
|
||||
peak, prom = float(fv[sel][i]), float(resid[sel][i])
|
||||
found = bool(prom >= min_db and 0 < i < int(sel.sum()) - 1)
|
||||
return (peak if found else np.nan), prom, found
|
||||
|
||||
|
||||
def rhythm(raw, starts, min_windows=MIN_WINDOWS) -> dict:
|
||||
from mne.time_frequency import psd_array_welch
|
||||
|
||||
out = {"rhythm_hz": np.nan, "n_channels": 0, "prominence_db": np.nan, "n_windows": len(starts),
|
||||
"reason": ""}
|
||||
if len(starts) < min_windows:
|
||||
out["reason"] = "too few wake windows"
|
||||
return out
|
||||
fs = float(raw.info["sfreq"])
|
||||
chans = [c for c in POSTERIOR if c in raw.ch_names]
|
||||
n = int(round(WINDOW_S * fs))
|
||||
x = raw.get_data(picks=chans).T * 1e6 if chans else np.empty((raw.n_times, 0))
|
||||
segs = []
|
||||
for t0 in starts:
|
||||
a = int(round(float(t0) * fs))
|
||||
if a >= 0 and a + n <= len(x) and np.isfinite(x[a:a + n]).all():
|
||||
segs.append(x[a:a + n].T)
|
||||
peaks, proms = [], []
|
||||
if segs and chans:
|
||||
P, f = psd_array_welch(np.stack(segs), fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
|
||||
for k in range(len(chans)):
|
||||
pk, pr, ok = dominant_peak(f, P[:, k].mean(axis=0))
|
||||
if ok:
|
||||
peaks.append(pk)
|
||||
proms.append(pr)
|
||||
out["n_channels"] = len(peaks)
|
||||
if len(peaks) >= MIN_CHANNELS:
|
||||
out["rhythm_hz"], out["prominence_db"] = float(np.median(peaks)), float(np.median(proms))
|
||||
else:
|
||||
out["reason"] = "no peak in two posterior channels"
|
||||
return out
|
||||
|
||||
|
||||
class PosteriorRhythm:
|
||||
name = "posterior_rhythm"
|
||||
version = "0.1.0"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("sleep_state",)
|
||||
features = ("posterior_rhythm_hz",)
|
||||
impl = "modern"
|
||||
|
||||
def __init__(self, variant="hp05_prom", state="vigilia", baseline="curves", baseline_params=None,
|
||||
fitted=None):
|
||||
self.variant = variant
|
||||
self.state = state
|
||||
self.baseline_name = baseline
|
||||
self.baseline_params = dict(baseline_params or {})
|
||||
self.baseline = _baseline.from_dict(fitted) if fitted else _baseline.make(baseline, **self.baseline_params)
|
||||
self._fitted = fitted is not None
|
||||
|
||||
def detail(self, study) -> dict:
|
||||
lab, w = study.label("sleep_state").per_window, study.prep.windows
|
||||
return rhythm(study.prep.variant(self.variant), [float(s) for s, e in zip(w.start_s, lab) if e == self.state])
|
||||
|
||||
def measure(self, study) -> dict:
|
||||
return {"posterior_rhythm_hz": float(self.detail(study)["rhythm_hz"])}
|
||||
|
||||
def train(self, data, ages_months=None):
|
||||
if isinstance(data, pd.DataFrame):
|
||||
t = data
|
||||
else:
|
||||
t = pd.DataFrame([self.measure(s) for s in data])
|
||||
t["age_months"] = list(ages_months) if ages_months is not None else [s.prep.age_months for s in data]
|
||||
self.baseline.fit(t["posterior_rhythm_hz"].to_numpy(float), t["age_months"].to_numpy(float))
|
||||
self._fitted = True
|
||||
return self
|
||||
|
||||
def predict(self, data, age_months=None) -> pd.DataFrame:
|
||||
if not self._fitted:
|
||||
raise ValueError(f"{self.name}: train() before predict()")
|
||||
if isinstance(data, pd.DataFrame):
|
||||
t = data
|
||||
else:
|
||||
t = pd.DataFrame([self.measure(data)])
|
||||
t["age_months"] = [age_months if age_months is not None else data.prep.age_months]
|
||||
v, a = t["posterior_rhythm_hz"].to_numpy(float), t["age_months"].to_numpy(float)
|
||||
outside, z = self.baseline.deviation(v, a)
|
||||
return pd.DataFrame({"feature": "posterior_rhythm_hz", "value": v, "age_months": a, "outside": outside,
|
||||
"z": z, "baseline": self.baseline.name}, columns=list(DEVIATION_COLUMNS))
|
||||
|
||||
def save(self, path):
|
||||
Path(path, "params.json").write_text(json.dumps(
|
||||
{"variant": self.variant, "state": self.state, "baseline": self.baseline_name,
|
||||
"baseline_params": self.baseline_params}))
|
||||
Path(path, "baseline.json").write_text(json.dumps(self.baseline.to_dict() if self._fitted else None,
|
||||
default=float))
|
||||
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
p = json.loads(Path(path, "params.json").read_text())
|
||||
return cls(**p, fitted=json.loads(Path(path, "baseline.json").read_text()))
|
||||
|
||||
|
||||
MODULE = PosteriorRhythm()
|
||||
Reference in New Issue
Block a user