coupling, legacy and modern
- legacy: acoplamiento.fases_de_estudio + resumen (vendored unchanged); spindle and slow-wave events read through the contract columns, so either detector can feed it; in_slow_wave = --solo-en-onda. - modern: slow-oscillation phase (MNE 0.5-2 Hz, scipy Hilbert, per run) at the sigma-envelope peak of each spindle; R from 200 subsamples of 30, excess over the chance floor, preferred angle, raw R. Modern within 0.03 of legacy; phase-locked synthetic spindles give R > 0.8 at the trough in both; contract suite passes.
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
Modern coupling (acoplamiento's definitions on MNE/SciPy): slow-oscillation phase
|
||||
(0.5-2 Hz MNE band-pass, scipy Hilbert, per gap-free run) at the maximum of the
|
||||
sigma envelope (11-16 Hz band-pass, |Hilbert|) within each spindle, on the
|
||||
spindle's own channel. R = median resultant length over 200 subsamples of 30
|
||||
spindles (seed 7); R over the chance floor sqrt(pi)/(2 sqrt(30)); preferred angle
|
||||
(circular mean of the subsample angles); raw R. NaN with fewer than 30 spindles.
|
||||
"""
|
||||
|
||||
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, _signal
|
||||
|
||||
SO = (0.5, 2.0)
|
||||
SIGMA = (11.0, 16.0)
|
||||
N_SUB, REPS, SEED = 30, 200, 7
|
||||
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz", "T3", "T4", "T5",
|
||||
"T6", "O1", "O2")
|
||||
FEATURES = ("coupling_r", "coupling_r_over_floor", "coupling_angle_deg", "coupling_r_raw")
|
||||
|
||||
|
||||
def resultant(ph):
|
||||
if ph is None or not len(ph):
|
||||
return np.nan, np.nan
|
||||
m = np.exp(1j * np.asarray(ph, float)).mean()
|
||||
return float(np.abs(m)), float(np.angle(m))
|
||||
|
||||
|
||||
def phases(raw, sp, slow=None):
|
||||
from scipy.signal import hilbert
|
||||
fs = float(raw.info["sfreq"])
|
||||
names = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg" and c in CHANNELS]
|
||||
x = raw.get_data(picks=names).T * 1e6
|
||||
lo = _signal.bandpass(x, fs, *SO)
|
||||
ph = _signal.by_runs(lo, lambda s: np.angle(hilbert(s, axis=0)), minimum=int(fs))
|
||||
env = _signal.by_runs(_signal.bandpass(x, fs, *SIGMA), lambda s: np.abs(hilbert(s, axis=0)), minimum=int(fs))
|
||||
idx = {c: i for i, c in enumerate(names)}
|
||||
out = []
|
||||
for r in sp.itertuples():
|
||||
if r.channel not in idx:
|
||||
continue
|
||||
a = max(int(round(float(r.onset_s) * fs)), 0)
|
||||
b = min(a + int(round(float(r.duration_s) * fs)), len(x))
|
||||
if b - a < 2:
|
||||
continue
|
||||
j = idx[r.channel]
|
||||
k = a + int(np.nanargmax(env[a:b, j])) if np.isfinite(env[a:b, j]).any() else a
|
||||
v = float(ph[k, j])
|
||||
if not np.isfinite(v):
|
||||
continue
|
||||
inside = True
|
||||
if slow is not None and len(slow):
|
||||
s = slow[slow.channel == r.channel] if (slow.channel == r.channel).any() else slow
|
||||
t = k / fs
|
||||
inside = bool(np.any((t >= s.onset_s.to_numpy(float)) &
|
||||
(t <= s.onset_s.to_numpy(float) + s.duration_s.to_numpy(float))))
|
||||
out.append((v, inside))
|
||||
return out
|
||||
|
||||
|
||||
class Coupling:
|
||||
name = "coupling"
|
||||
version = "0.1.0"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("spindle_detection",)
|
||||
features = FEATURES
|
||||
impl = "modern"
|
||||
|
||||
def __init__(self, variant="hp05_prom", in_slow_wave=False, baseline="curves", baseline_params=None,
|
||||
fitted=None):
|
||||
self.variant = variant
|
||||
self.in_slow_wave = bool(in_slow_wave)
|
||||
self.requires = ("spindle_detection", "slow_wave_staging") if self.in_slow_wave else ("spindle_detection",)
|
||||
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:
|
||||
nan = {f: float("nan") for f in FEATURES}
|
||||
sp = study.label("spindle_detection").events
|
||||
if not len(sp):
|
||||
return nan
|
||||
slow = study.label("slow_wave_staging").events if self.in_slow_wave else None
|
||||
res = phases(study.prep.variant(self.variant), sp, slow)
|
||||
ph = np.array([v for v, ok in res if ok or not self.in_slow_wave])
|
||||
if not len(ph):
|
||||
return nan
|
||||
raw_r, _ = resultant(ph)
|
||||
if len(ph) < N_SUB:
|
||||
return {**nan, "coupling_r_raw": raw_r}
|
||||
rng = np.random.default_rng(SEED)
|
||||
rs, angs = [], []
|
||||
for _ in range(REPS):
|
||||
r, a = resultant(rng.choice(ph, size=N_SUB, replace=False))
|
||||
rs.append(r)
|
||||
angs.append(a)
|
||||
R = float(np.median(rs))
|
||||
floor = float(np.sqrt(np.pi) / (2 * np.sqrt(N_SUB)))
|
||||
return {"coupling_r": R, "coupling_r_over_floor": (R - floor) / (1 - floor),
|
||||
"coupling_angle_deg": float(np.degrees(resultant(np.array(angs))[1])), "coupling_r_raw": raw_r}
|
||||
|
||||
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, "in_slow_wave": self.in_slow_wave, "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 = Coupling()
|
||||
Reference in New Issue
Block a user