gradient, legacy and modern
- legacy: medidas_director.gradiente on gradiente.analizar (vendored), in the 'sueno' and 'somnolencia' windows as analizar_director does. - modern: Hann periodograms per window (MNE), median band power, Theil-Sen slope (scipy.stats.theilslopes) on the director's front-back coordinates. - 8 features gradient_<band>_<state>, one baseline each. Legacy equals the submodule's cluster route exactly; modern within 0.01 of legacy on the synthetic study.
This commit is contained in:
@@ -1 +1,3 @@
|
||||
"""Modern gradient: API pending."""
|
||||
from tea_modulo.biomarkers.gradient.api import MODULE, Gradient
|
||||
|
||||
__all__ = ["MODULE", "Gradient"]
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
Modern gradient (gradiente.analizar's definitions on MNE/SciPy):
|
||||
|
||||
windows 4 s windows of each state ('sueno', 'somnolencia'), gap-free, at least 15
|
||||
power per channel and band, the median over windows of the band power of a
|
||||
Hann periodogram (mne psd_array_welch, one segment per window)
|
||||
slope Theil-Sen slope (scipy.stats.theilslopes) of log10 power against the
|
||||
electrode's front-back coordinate (the director's 2D positions, +1 frontal)
|
||||
|
||||
Features: gradient_<band>_<state> for delta, theta, alpha (8-13) and beta (13-30).
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
POS_Y = {"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
|
||||
"T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53, "Pz": -0.50,
|
||||
"P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95} # gradiente.POS (y)
|
||||
BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alfa": (8, 13), "beta": (13, 30)}
|
||||
STATES = ("sueno", "somnolencia")
|
||||
MIN_WINDOWS = 15
|
||||
FEATURES = tuple(f"gradient_{b}_{s}" for s in STATES for b in BANDS)
|
||||
|
||||
|
||||
def slopes(raw, starts, window_s=4.0) -> dict:
|
||||
from mne.time_frequency import psd_array_welch
|
||||
from scipy.stats import theilslopes
|
||||
|
||||
out = {b: np.nan for b in BANDS}
|
||||
if len(starts) < MIN_WINDOWS:
|
||||
return out
|
||||
fs = float(raw.info["sfreq"])
|
||||
chans = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg" and c in POS_Y]
|
||||
n = int(window_s * fs)
|
||||
x = raw.get_data(picks=chans).T * 1e6
|
||||
segs = [x[a:a + n].T for a in (int(round(t * fs)) for t in starts)
|
||||
if a + n <= len(x) and np.isfinite(x[a:a + n]).all()]
|
||||
if not segs:
|
||||
return out
|
||||
P, f = psd_array_welch(np.stack(segs), fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
|
||||
y = np.array([POS_Y[c] for c in chans])
|
||||
for b, (lo, hi) in BANDS.items():
|
||||
pw = np.median(P[..., (f >= lo) & (f < hi)].sum(axis=-1), axis=0)
|
||||
v = np.log10(np.maximum(pw, 1e-30))
|
||||
ok = np.isfinite(v)
|
||||
if ok.sum() >= 6:
|
||||
out[b] = float(theilslopes(v[ok], y[ok])[0])
|
||||
return out
|
||||
|
||||
|
||||
class Gradient:
|
||||
name = "gradient"
|
||||
version = "0.1.0"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("sleep_state",)
|
||||
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 measure(self, study) -> dict:
|
||||
lab, w = study.label("sleep_state").per_window, study.prep.windows
|
||||
raw = study.prep.variant(self.variant)
|
||||
out = {}
|
||||
for s in STATES:
|
||||
sl = slopes(raw, [float(t) for t, e in zip(w.start_s, lab) if e == s])
|
||||
out.update({f"gradient_{b}_{s}": float(v) for b, v in sl.items()})
|
||||
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 = Gradient()
|
||||
@@ -1 +1,3 @@
|
||||
"""Legacy gradient: director code vendored; API pending."""
|
||||
from tea_modulo.legacy.biomarkers.gradient.api import MODULE, LegacyGradient
|
||||
|
||||
__all__ = ["MODULE", "LegacyGradient"]
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""
|
||||
Legacy gradient: the cluster route's anteroposterior gradient (medidas_director.gradiente
|
||||
on gradiente.analizar, vendored unchanged) in the windows labelled 'sueno' and
|
||||
'somnolencia' (pipeline.analizar_director @ 7dfc641).
|
||||
|
||||
Features: the Theil-Sen slope of log10 band power against the electrode's
|
||||
front-back coordinate (gradiente.POS, +1 frontal, -1 occipital) for delta,
|
||||
theta, alpha and beta, in each state: gradient_<band>_<state>. NaN with fewer
|
||||
than 15 windows of that state.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from tea_modulo.contracts import CONTRACT_VERSION, DEVIATION_COLUMNS
|
||||
|
||||
from . import _adapter, _baseline
|
||||
|
||||
DIRECTOR_COMMIT = "7dfc641"
|
||||
BANDS = ("delta", "theta", "alfa", "beta") # pipeline.BANDAS_GRADIENTE
|
||||
STATES = ("sueno", "somnolencia")
|
||||
MIN_WINDOWS = 15
|
||||
FEATURES = tuple(f"gradient_{b}_{s}" for s in STATES for b in BANDS)
|
||||
|
||||
|
||||
def gradiente(est, inicios, g, min_ventanas=MIN_WINDOWS) -> dict:
|
||||
"""medidas_director.gradiente (verbatim but for `est`)."""
|
||||
if len(inicios) < min_ventanas:
|
||||
return {"n_ventanas": len(inicios), "motivo": "pocas ventanas"}
|
||||
fila, _, n = g.analizar(est, inicios)
|
||||
if fila is None:
|
||||
return {"n_ventanas": n, "motivo": "sin potencias"}
|
||||
return {**fila, "motivo": ""}
|
||||
|
||||
|
||||
class LegacyGradient:
|
||||
name = "gradient"
|
||||
version = f"0.1.0+director.{DIRECTOR_COMMIT}"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("sleep_state",)
|
||||
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 detail(self, study) -> dict:
|
||||
from ._director import eeg_io
|
||||
from ._director import gradiente as g
|
||||
|
||||
lab, w = study.label("sleep_state").per_window, study.prep.windows
|
||||
out = {}
|
||||
with _adapter.estudio(study.prep, self.variant, eeg_io) as est:
|
||||
for s in STATES:
|
||||
out[s] = gradiente(est, [float(t) for t, e in zip(w.start_s, lab) if e == s], g)
|
||||
return out
|
||||
|
||||
def measure(self, study) -> dict:
|
||||
d = self.detail(study)
|
||||
return {f"gradient_{b}_{s}": float(d[s].get(f"pendiente_{b}", float("nan")))
|
||||
for s in STATES for b in BANDS}
|
||||
|
||||
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 = LegacyGradient()
|
||||
Reference in New Issue
Block a user