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,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()
|
||||
Reference in New Issue
Block a user