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.
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
from tea_modulo.biomarkers.aperiodic.api import MODULE, Aperiodic
|
||||
|
||||
__all__ = ["MODULE", "Aperiodic"]
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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_<region>_<state>.
|
||||
"""
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,3 @@
|
||||
from tea_modulo.biomarkers.mse.api import MODULE, MSE
|
||||
|
||||
__all__ = ["MODULE", "MSE"]
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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_<fine|coarse|total>_<state>.
|
||||
"""
|
||||
|
||||
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()
|
||||
Reference in New Issue
Block a user