6d0a99e6e5
- every private _signal.bandpass: scipy butter + sosfiltfilt per gap-free run, as eeg_io.pasa_banda (MNE's IIR padded the run edges differently: up to tens of µV) - preprocessing: variants built as preproceso (band-pass per run, nanmean reference); BAD_ACQ_SKIP gaps stay NaN in every variant instead of 0 µV, so no module filters or detects across a gap (the director's EDF reader reads them as signal; his Natus route keeps NaN) - aperiodic: DPSS multitaper on demeaned windows with equal taper weights (espectro.multitaper) instead of MNE's eigenvalue-weighted one without demeaning - gradient: symmetric Hann periodogram of demeaned windows (gradiente.potencias) - tests: preprocessing equal to the director sample by sample (edges included); every biomarker equal to legacy within 1e-4 on gap-free recordings
185 lines
8.3 KiB
Python
185 lines
8.3 KiB
Python
"""
|
|
Modern aperiodic (the cluster route's definitions):
|
|
|
|
windows clean 2 s windows of each state (at least 20)
|
|
spectrum multitaper per demeaned window: 3 DPSS tapers, NW = 2 (scipy.signal.windows.dpss),
|
|
equal weights, one-sided µV²/Hz (as espectro.multitaper); mean over windows,
|
|
mean over the region's electrodes. (MNE's psd_array_multitaper weights the
|
|
tapers by eigenvalue and does not remove the mean: on 2 s windows fitted from
|
|
2.5 Hz the DC leaks into the fit range.)
|
|
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 multitaper(segs, fs, k=3):
|
|
"""Mean multitaper spectrum over windows. segs: (windows, channels, samples) in µV.
|
|
k DPSS tapers with NW = (k + 1) / 2, equal weights, one-sided, µV²/Hz."""
|
|
from scipy.fft import rfft, rfftfreq
|
|
from scipy.signal.windows import dpss
|
|
n = segs.shape[-1]
|
|
tapers = dpss(n, NW=(k + 1) / 2, Kmax=k) # k x n
|
|
x = segs - segs.mean(axis=-1, keepdims=True)
|
|
S = (np.abs(rfft(tapers[None, None] * x[:, :, None], axis=-1)) ** 2).mean(axis=2) / fs
|
|
S[..., 1:-1] *= 2
|
|
return rfftfreq(n, 1 / fs), S.mean(axis=0)
|
|
|
|
|
|
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:
|
|
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
|
|
f, Pm = multitaper(np.stack(segs), reg.fs, int(P["espectro.tapers"])) # 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()
|