spindle_detection and spindles, legacy and modern
- legacy: husos.detectar / husos.resumen vendored unchanged, run on the 'sueno' windows as medidas_director does; the wake rhythm that sets the 'rhythm near sigma' flag is computed inside the process (no biomarker dependency). - modern: the same detector on MNE (sigma band-pass) and SciPy (Hilbert, Welch narrowness, phase stability); summary with the director's definitions; one baseline per feature. - privacy.group_size understands per-feature baseline dicts. Legacy equals the submodule's cluster route exactly (spindle count and the six summary measures); modern equals legacy on the synthetic study.
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
from tea_modulo.processes.spindle_detection.api import MODULE, SpindleDetection
|
||||
|
||||
__all__ = ["MODULE", "SpindleDetection"]
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
Signal primitives for spindle detection (private copy), on MNE and SciPy.
|
||||
|
||||
Arrays are (samples, channels) in µV with NaN in gaps. Filters run on each
|
||||
gap-free run separately (runs shorter than the filter's minimum become NaN,
|
||||
as the director's por_tramos does).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def runs(valid: np.ndarray) -> list[tuple[int, int]]:
|
||||
"""[(start, stop)] of the True runs of a boolean vector."""
|
||||
v = np.concatenate([[False], np.asarray(valid, bool), [False]])
|
||||
d = np.diff(v.astype(int))
|
||||
return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)))
|
||||
|
||||
|
||||
def by_runs(x, fn, minimum: int):
|
||||
x = np.asarray(x, float)
|
||||
out = np.full_like(x, np.nan)
|
||||
for a, b in runs(np.isfinite(x).all(axis=1)):
|
||||
if b - a >= minimum:
|
||||
out[a:b] = fn(x[a:b])
|
||||
return out
|
||||
|
||||
|
||||
def bandpass(x, fs, lo=None, hi=None, order=4):
|
||||
"""Butterworth, zero phase (mne.filter.filter_data, IIR), run by run."""
|
||||
import mne
|
||||
iir = {"order": order, "ftype": "butter"}
|
||||
|
||||
def f(seg):
|
||||
return mne.filter.filter_data(seg.T, fs, lo, hi, method="iir", iir_params=iir,
|
||||
phase="zero", verbose="error").T
|
||||
return by_runs(x, f, minimum=max(3 * (2 * order + 1), int(fs)))
|
||||
|
||||
|
||||
def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True):
|
||||
"""Spectrum interpolation around f0 and harmonics (port of eeg_io.notch_interpolado).
|
||||
No library implements this method; MNE's notch filters change the signal differently."""
|
||||
freqs = [f0]
|
||||
if harmonics:
|
||||
k = 2
|
||||
while k * f0 < fs / 2 * 0.98:
|
||||
freqs.append(k * f0)
|
||||
k += 1
|
||||
|
||||
def f(seg):
|
||||
n = seg.shape[0]
|
||||
fr = np.fft.rfftfreq(n, 1.0 / fs)
|
||||
F = np.fft.rfft(seg, axis=0)
|
||||
for c in freqs:
|
||||
inside = (fr >= c - width) & (fr <= c + width)
|
||||
left = (fr >= c - 3 * width) & (fr < c - width)
|
||||
right = (fr > c + width) & (fr <= c + 3 * width)
|
||||
if not (inside.any() and left.any() and right.any()):
|
||||
continue
|
||||
ml, mr = np.abs(F[left]).mean(axis=0), np.abs(F[right]).mean(axis=0)
|
||||
k_ = np.linspace(0, 1, int(inside.sum()))[:, None]
|
||||
target = ml[None, :] * (1 - k_) + mr[None, :] * k_
|
||||
cur = F[inside]
|
||||
mag = np.abs(cur)
|
||||
F[inside] = target * np.where(mag > 0, cur / np.maximum(mag, 1e-30), 1.0)
|
||||
return np.fft.irfft(F, n=n, axis=0)
|
||||
return by_runs(x, f, minimum=max(int(2 * fs), 256))
|
||||
|
||||
|
||||
def welch(x, fs, seg_s=4.0, overlap=0.5):
|
||||
"""Welch PSD (Hann) per channel over the gap-free runs (mne psd_array_welch), µV²/Hz."""
|
||||
from mne.time_frequency import psd_array_welch
|
||||
x = np.asarray(x, float)
|
||||
x = x[:, None] if x.ndim == 1 else x
|
||||
n = int(round(seg_s * fs))
|
||||
acc, w = None, 0
|
||||
for a, b in runs(np.isfinite(x).all(axis=1)):
|
||||
if b - a < n:
|
||||
continue
|
||||
P, f = psd_array_welch(x[a:b].T, fs, n_fft=n, n_per_seg=n, n_overlap=int(n * overlap),
|
||||
window="hann", average="mean", verbose="error")
|
||||
k = (b - a - n) // int(n * (1 - overlap)) + 1
|
||||
acc = P * k if acc is None else acc + P * k
|
||||
w += k
|
||||
if acc is None:
|
||||
return None, None
|
||||
return f, (acc / w).T # (freqs, channels)
|
||||
|
||||
|
||||
def line_db(x, fs, f0=60.0, width=0.6, neighbourhood=(2, 6)):
|
||||
"""dB of the mains peak over its neighbourhood on the samples valid in all channels
|
||||
(eeg_io.nivel_de_red)."""
|
||||
x = np.atleast_2d(np.asarray(x, float).T).T
|
||||
fin = np.isfinite(x).all(axis=1)
|
||||
if not fin.any():
|
||||
return np.full(x.shape[1], np.nan)
|
||||
seg = x[fin] - x[fin].mean(axis=0)
|
||||
fr = np.fft.rfftfreq(len(seg), 1.0 / fs)
|
||||
P = np.abs(np.fft.rfft(seg * np.hanning(len(seg))[:, None], axis=0)) ** 2
|
||||
lo, hi = neighbourhood
|
||||
peak = P[(fr >= f0 - width) & (fr <= f0 + width)].mean(axis=0)
|
||||
nb = P[((fr >= f0 - hi) & (fr <= f0 - lo)) | ((fr >= f0 + lo) & (fr <= f0 + hi))].mean(axis=0)
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
return 10 * np.log10(np.where(nb > 0, peak / nb, np.nan))
|
||||
|
||||
|
||||
def dominant_peak(f, P, band=(3.0, 14.0), fit=(1.5, 45.0), exclude=(4.0, 16.0), min_db=1.5):
|
||||
"""Peak over the 1/f fit (eeg_io.pico_dominante): (Hz, prominence dB, found)."""
|
||||
f, P = np.asarray(f, float), np.asarray(P, float)
|
||||
val = (f >= fit[0]) & (f <= fit[1]) & (P > 0)
|
||||
bg = val & ~((f >= exclude[0]) & (f <= exclude[1]))
|
||||
if bg.sum() < 5:
|
||||
return np.nan, np.nan, False
|
||||
coef = np.polyfit(np.log10(f[bg]), np.log10(P[bg]), 1)
|
||||
resid = 10 * (np.log10(P[val]) - np.polyval(coef, np.log10(f[val])))
|
||||
fv = f[val]
|
||||
sel = (fv >= band[0]) & (fv <= band[1])
|
||||
if not sel.any():
|
||||
return np.nan, np.nan, False
|
||||
i = int(np.argmax(resid[sel]))
|
||||
peak, prom = float(fv[sel][i]), float(resid[sel][i])
|
||||
edge = i == 0 or i == int(sel.sum()) - 1
|
||||
found = bool(prom >= min_db and not edge)
|
||||
return (peak if found else np.nan), prom, found
|
||||
|
||||
|
||||
def fixed_lines(x, fs, f_min=1.0, f_max=None, min_db=6.0, max_width=0.5, bg_hz=2.0, seg_s=8.0):
|
||||
"""Fixed-frequency lines of the recording (lineas.lineas_fijas): [(Hz, dB, width)]."""
|
||||
from scipy.ndimage import median_filter
|
||||
x = np.asarray(x, float)
|
||||
x = x[:, None] if x.ndim == 1 else x
|
||||
n = int(round(seg_s * fs))
|
||||
f = np.fft.rfftfreq(n, 1.0 / fs)
|
||||
win = np.hanning(n)[:, None]
|
||||
acc, k = None, 0
|
||||
for a in range(0, len(x) - n + 1, n):
|
||||
seg = x[a:a + n]
|
||||
if not np.isfinite(seg).all():
|
||||
continue
|
||||
S = np.abs(np.fft.rfft((seg - seg.mean(axis=0)) * win, axis=0)) ** 2
|
||||
acc = S if acc is None else acc + S
|
||||
k += 1
|
||||
if not k:
|
||||
return []
|
||||
P = np.median(acc / k, axis=1)
|
||||
df = float(f[1] - f[0])
|
||||
lp = 10 * np.log10(np.maximum(P, 1e-30))
|
||||
kk = max(1, int(round(bg_hz / df)))
|
||||
prom = lp - median_filter(lp, size=2 * kk + 1, mode="nearest")
|
||||
f_max = min(f_max or fs / 2, fs / 2 - bg_hz)
|
||||
cand = []
|
||||
for i in range(1, len(f) - 1):
|
||||
if not (f_min <= f[i] <= f_max) or prom[i] < min_db:
|
||||
continue
|
||||
if prom[i] < prom[i - 1] or prom[i] < prom[i + 1]:
|
||||
continue
|
||||
u = prom[i] - 3.0
|
||||
a = i
|
||||
while a > 0 and prom[a - 1] >= u:
|
||||
a -= 1
|
||||
b = i
|
||||
while b < len(f) - 1 and prom[b + 1] >= u:
|
||||
b += 1
|
||||
if (b - a + 1) * df <= max_width:
|
||||
cand.append((round(float(f[i]), 3), round(float(prom[i]), 1), round((b - a + 1) * df, 3)))
|
||||
cand.sort(key=lambda c: -c[1])
|
||||
out = []
|
||||
for c in cand:
|
||||
if all(abs(c[0] - o[0]) > 0.5 for o in out):
|
||||
out.append(c)
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def band_power(f, P, lo, hi, lines=(), margin=1.0):
|
||||
"""Power of [lo, hi) without ±margin around fixed lines, rescaled (lineas.potencia_banda)."""
|
||||
f, P = np.asarray(f, float), np.asarray(P, float)
|
||||
band = (f >= lo) & (f < hi)
|
||||
clean = band.copy()
|
||||
for li in lines or ():
|
||||
clean &= np.abs(f - float(li[0])) > margin
|
||||
if not clean.any():
|
||||
return np.full(P.shape[1:], np.nan) if P.ndim > 1 else np.nan
|
||||
return P[clean].sum(axis=0) * (band.sum() / clean.sum())
|
||||
|
||||
|
||||
def hurst(x):
|
||||
"""Hurst exponent by detrended fluctuation analysis (antropy)."""
|
||||
import antropy
|
||||
v = np.asarray(x, float)
|
||||
v = v[np.isfinite(v)]
|
||||
return float(antropy.detrended_fluctuation(v)) if len(v) > 4096 else np.nan
|
||||
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
Modern spindle_detection: the director's detector (husos.detectar) on MNE/SciPy.
|
||||
|
||||
In the windows labelled 'sueno', on the spindle channels (frontal, central,
|
||||
parietal; no occipitals):
|
||||
envelope 11-16 Hz band-pass (MNE IIR, zero phase) -> |Hilbert| -> 0.2 s moving mean
|
||||
thresholds per channel, from the child's own sleep: core > max(p95, 3 x median),
|
||||
extent > max(p70, 1.6 x median)
|
||||
segments extent stretches with a core, 0.5-3 s (longer ones cut in 3 s pieces)
|
||||
keep sigma power at least 1.5 x the 5-30 Hz flanks (scipy Welch), stable
|
||||
Hilbert phase in band for half the samples, peak 11-16 Hz,
|
||||
enhancement >= 3 x median
|
||||
|
||||
The wake rhythm only sets the 'rhythm near sigma' flag (as in the cluster
|
||||
route); it is computed here (private copy of the rhythm code).
|
||||
"""
|
||||
|
||||
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, Labels
|
||||
|
||||
from . import _signal
|
||||
|
||||
SIGMA = (11.0, 16.0)
|
||||
FAST = 13.0
|
||||
SPINDLE_CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz")
|
||||
DUR_MIN, DUR_MAX = 0.5, 3.0
|
||||
COLUMNS = ["onset_s", "duration_s", "channel", "frequency_hz", "enhancement", "amplitude_uv", "narrowness",
|
||||
"symmetry", "kind"]
|
||||
|
||||
|
||||
def segments(core, extent, fs, dmin=DUR_MIN, dmax=DUR_MAX):
|
||||
d = np.diff(extent.astype(np.int8), prepend=0, append=0)
|
||||
out = []
|
||||
for a, b in zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)):
|
||||
if not core[a:b].any():
|
||||
continue
|
||||
dur = (b - a) / fs
|
||||
if dmin <= dur <= dmax:
|
||||
out.append((int(a), int(b)))
|
||||
elif dur > dmax:
|
||||
step = int(dmax * fs)
|
||||
for c in range(a, b, step):
|
||||
e = min(c + step, b)
|
||||
if dmin <= (e - c) / fs <= dmax and core[c:e].any():
|
||||
out.append((int(c), int(e)))
|
||||
return out
|
||||
|
||||
|
||||
def detect(x, fs, names, asleep, pct=95.0, min_narrow=1.5, min_enh=3.0):
|
||||
from scipy.signal import hilbert, welch
|
||||
|
||||
y = _signal.bandpass(x, fs, *SIGMA)
|
||||
env = np.abs(hilbert(np.nan_to_num(y), axis=0))
|
||||
k = max(1, int(0.2 * fs))
|
||||
env = np.apply_along_axis(lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, env)
|
||||
env[~np.isfinite(y)] = np.nan
|
||||
rows = []
|
||||
for i, nm in enumerate(names):
|
||||
e = env[:, i].copy()
|
||||
e[~asleep] = np.nan
|
||||
val = e[np.isfinite(e)]
|
||||
if len(val) < fs * 30:
|
||||
continue
|
||||
med = float(np.median(val)) or 1e-9
|
||||
hi = max(float(np.percentile(val, pct)), min_enh * med)
|
||||
lo = max(float(np.percentile(val, max(50.0, pct - 25))), 1.6 * med)
|
||||
for a, b in segments(np.isfinite(e) & (e > hi), np.isfinite(e) & (e > lo), fs):
|
||||
seg = x[a:b, i]
|
||||
if not np.isfinite(seg).all():
|
||||
continue
|
||||
nper = min(len(seg), int(fs))
|
||||
f, P = welch(seg - seg.mean(), fs=fs, nperseg=nper, nfft=max(1024, nper * 4))
|
||||
ins = (f >= SIGMA[0]) & (f <= SIGMA[1])
|
||||
out_ = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30))
|
||||
if not ins.any() or not out_.any():
|
||||
continue
|
||||
narrow = float(P[ins].mean() / max(P[out_].mean(), 1e-30))
|
||||
if narrow < min_narrow:
|
||||
continue
|
||||
inst = np.diff(np.unwrap(np.angle(hilbert(y[a:b, i])))) * fs / (2 * np.pi)
|
||||
inst = inst[np.isfinite(inst)]
|
||||
inband = inst[(inst >= SIGMA[0] - 1) & (inst <= SIGMA[1] + 1)]
|
||||
if len(inband) < 0.5 * max(len(inst), 1):
|
||||
continue
|
||||
peak = float(np.median(inband))
|
||||
if not SIGMA[0] <= peak <= SIGMA[1]:
|
||||
continue
|
||||
ev = env[a:b, i]
|
||||
enh = float(np.nanmax(ev)) / med
|
||||
if enh < min_enh:
|
||||
continue
|
||||
top = int(np.argmax(ev))
|
||||
rows.append({"onset_s": round(a / fs, 3), "duration_s": round((b - a) / fs, 3), "channel": nm,
|
||||
"frequency_hz": round(peak, 2), "enhancement": round(enh, 2),
|
||||
"amplitude_uv": round(float(np.ptp(y[a:b, i])), 1), "narrowness": round(narrow, 2),
|
||||
"symmetry": round(min(top, len(ev) - top) / max(len(ev) / 2, 1), 2),
|
||||
"kind": "slow" if peak < FAST else "fast"})
|
||||
return pd.DataFrame(rows, columns=COLUMNS)
|
||||
|
||||
|
||||
def wake_rhythm(raw, starts) -> float:
|
||||
"""Median 3-14 Hz peak of O1 O2 P3 P4 over the wake windows (>= 15, >= 2 channels)."""
|
||||
from mne.time_frequency import psd_array_welch
|
||||
if len(starts) < 15:
|
||||
return np.nan
|
||||
fs = float(raw.info["sfreq"])
|
||||
chans = [c for c in ("O1", "O2", "P3", "P4") if c in raw.ch_names]
|
||||
n = int(4 * fs)
|
||||
x = raw.get_data(picks=chans).T * 1e6
|
||||
segs = [x[int(round(t * fs)):int(round(t * fs)) + n].T for t in starts
|
||||
if int(round(t * fs)) + n <= len(x) and np.isfinite(x[int(round(t * fs)):int(round(t * fs)) + n]).all()]
|
||||
if not segs or not chans:
|
||||
return np.nan
|
||||
P, f = psd_array_welch(np.stack(segs), fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
|
||||
peaks = []
|
||||
for k in range(len(chans)):
|
||||
Pm = P[:, k].mean(axis=0)
|
||||
val = (f >= 1.5) & (f <= 45) & (Pm > 0)
|
||||
bg = val & ~((f >= 4) & (f <= 16))
|
||||
coef = np.polyfit(np.log10(f[bg]), np.log10(Pm[bg]), 1)
|
||||
res = 10 * (np.log10(Pm[val]) - np.polyval(coef, np.log10(f[val])))
|
||||
sel = (f[val] >= 3) & (f[val] <= 14)
|
||||
i = int(np.argmax(res[sel]))
|
||||
if res[sel][i] >= 1.5 and 0 < i < int(sel.sum()) - 1:
|
||||
peaks.append(float(f[val][sel][i]))
|
||||
return float(np.median(peaks)) if len(peaks) >= 2 else np.nan
|
||||
|
||||
|
||||
class SpindleDetection:
|
||||
name = "spindle_detection"
|
||||
version = "0.1.0"
|
||||
contract_version = CONTRACT_VERSION
|
||||
requires = ("sleep_state",)
|
||||
impl = "modern"
|
||||
|
||||
def __init__(self, variant: str = "hp05_prom"):
|
||||
self.variant = variant
|
||||
|
||||
def train(self, studies):
|
||||
return self
|
||||
|
||||
def predict(self, study) -> Labels:
|
||||
raw = study.prep.variant(self.variant)
|
||||
fs = float(raw.info["sfreq"])
|
||||
lab, w = study.label("sleep_state").per_window, study.prep.windows
|
||||
names = [c for c, t in zip(raw.ch_names, raw.get_channel_types()) if t == "eeg" and c in SPINDLE_CHANNELS]
|
||||
x = raw.get_data(picks=names).T * 1e6
|
||||
asleep = np.zeros(len(x), bool)
|
||||
n = int(4 * fs)
|
||||
for s, e in zip(w.start_s, lab):
|
||||
if e == "sueno":
|
||||
a = int(round(float(s) * fs))
|
||||
asleep[a:a + n] = True
|
||||
minutes = float(asleep.sum() / fs / 60)
|
||||
ev = detect(x, fs, names, asleep) if minutes >= 1 else pd.DataFrame(columns=COLUMNS)
|
||||
rh = wake_rhythm(raw, [float(s) for s, e in zip(w.start_s, lab) if e == "vigilia"])
|
||||
ev.attrs.update({"minutes": minutes, "channels": names, "searched": minutes >= 1,
|
||||
"rhythm_near_sigma": bool(rh == rh and rh > SIGMA[0] - 1.5)})
|
||||
return Labels(self.name, events=ev)
|
||||
|
||||
def save(self, path):
|
||||
Path(path, "params.json").write_text(json.dumps({"variant": self.variant}))
|
||||
|
||||
@classmethod
|
||||
def load(cls, path):
|
||||
return cls(**json.loads(Path(path, "params.json").read_text()))
|
||||
|
||||
|
||||
MODULE = SpindleDetection()
|
||||
Reference in New Issue
Block a user