Files
models/models/tea/eeg/spindles.py
T

182 lines
7.6 KiB
Python

"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the
sigma envelope per electrode.
Detection runs on the frontal, central and parietal electrodes over the windows of the stage
(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median),
from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose
instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose
envelope peaks 3 x over the median.
Density: spindles per minute and searched channel (NaN when none were found); per zone, the
zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are
one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within
the episode ± 0.25 s, over the median envelope in sleep.
"""
from dataclasses import dataclass
import numpy as np
from scipy.signal import hilbert, welch
from models.tea.eeg import signals
from models.tea.eeg.preprocess import WINDOW_S, Prepared
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz")
SIGMA = (11.0, 16.0)
ZONES = {
"frontal_left": ("Fp1", "F3", "F7"),
"frontal_right": ("Fp2", "F4", "F8"),
"frontal_midline": ("Fz",),
"central": ("C3", "Cz", "C4"),
"parietal": ("P3", "Pz", "P4"),
"temporal_left": ("T3", "T5"),
"temporal_right": ("T4", "T6"),
"occipital": ("O1", "O2"),
}
@dataclass(frozen=True)
class Spindles:
events: list[tuple[float, float, str]] # (onset s, duration s, channel)
minutes: float
channels: list[str] # the channels searched (none when under a minute of the stage)
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
y = signals.bandpass(x, fs, *SIGMA)
envelope = np.abs(hilbert(np.nan_to_num(y), axis=0))
k = max(1, int(0.2 * fs))
envelope = np.apply_along_axis(
lambda v: np.convolve(v, np.ones(k) / k, mode="same"), 0, envelope
)
envelope[~np.isfinite(y)] = np.nan
return y, envelope
def _segments(core: np.ndarray, extent: np.ndarray, fs: float) -> list[tuple[int, int]]:
edges = np.diff(extent.astype(np.int8), prepend=0, append=0)
out = []
for a, b in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True):
if not core[a:b].any():
continue
if 0.5 <= (b - a) / fs <= 3.0:
out.append((int(a), int(b)))
elif (b - a) / fs > 3.0:
step = int(3.0 * fs)
for c in range(a, b, step):
e = min(c + step, b)
if 0.5 <= (e - c) / fs <= 3.0 and core[c:e].any():
out.append((int(c), int(e)))
return out
def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
"""Sigma over its flanks, and an instantaneous frequency in band."""
if not np.isfinite(x).all():
return False
nperseg = min(len(x), int(fs))
f, power = welch(x - x.mean(), fs=fs, nperseg=nperseg, nfft=max(1024, nperseg * 4))
inside = (f >= SIGMA[0]) & (f <= SIGMA[1])
flanks = ((f >= 5) & (f < SIGMA[0])) | ((f > SIGMA[1]) & (f <= 30))
if not inside.any() or not flanks.any():
return False
if power[inside].mean() / max(power[flanks].mean(), 1e-30) < 1.5:
return False
frequency = np.diff(np.unwrap(np.angle(hilbert(y)))) * fs / (2 * np.pi)
frequency = frequency[np.isfinite(frequency)]
in_band = frequency[(frequency >= SIGMA[0] - 1) & (frequency <= SIGMA[1] + 1)]
if len(in_band) < 0.5 * max(len(frequency), 1):
return False
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
"""The spindles in the grid windows staged `stage`."""
fs, n = prep.fs, int(WINDOW_S * prep.fs)
asleep = np.zeros(len(prep.x), bool)
for start, s in zip(prep.starts, staged, strict=True):
if s == stage:
a = int(round(float(start) * fs))
asleep[a : a + n] = True
minutes = float(asleep.sum() / fs / 60)
names = prep.columns([c for c in prep.names if c in CHANNELS])
if minutes < 1 or not names:
return Spindles([], minutes, [])
x = prep.data(names)
y, envelope = _envelope(x, fs)
events = []
for i, name in enumerate(names):
in_stage = np.where(asleep, envelope[:, i], np.nan)
values = in_stage[np.isfinite(in_stage)]
if len(values) < fs * 30:
continue
median = float(np.median(values)) or 1e-9
core = max(float(np.percentile(values, 95)), 3 * median)
extent = max(float(np.percentile(values, 70)), 1.6 * median)
finite = np.isfinite(in_stage)
for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs):
if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3:
events.append((round(a / fs, 3), round((b - a) / fs, 3), name))
return Spindles(events, minutes, names)
def density(found: Spindles) -> tuple[float, dict[str, float]]:
"""Spindles per minute and channel (rounded to 3), and per zone; NaN when none."""
zones = dict.fromkeys(ZONES, np.nan)
if not found.events or found.minutes <= 0:
return np.nan, zones
counts = {}
for _, _, channel in found.events:
counts[channel] = counts.get(channel, 0) + 1
for zone, electrodes in ZONES.items():
searched = [e for e in electrodes if e in found.channels]
if searched:
total = sum(counts.get(e, 0) for e in searched)
zones[zone] = total / (found.minutes * len(searched))
per_channel = len(found.events) / found.minutes / max(len(found.channels), 1)
return round(per_channel, 3), zones
def _episodes(events) -> list[list[float]]:
if not events:
return []
a = np.array([onset for onset, _, _ in events], float)
b = a + np.array([length for _, length, _ in events], float)
order = np.argsort(a)
out = [[a[order[0]], b[order[0]]]]
for i in order[1:]:
if a[i] <= out[-1][1]:
out[-1][1] = max(out[-1][1], b[i])
else:
out.append([a[i], b[i]])
return out
def enhancement(prep: Prepared, found: Spindles, states: np.ndarray) -> dict[str, float]:
"""Per spindle electrode, the envelope's median peak over episodes against its sleep median
(NaN for an absent electrode, or without spindles)."""
out = dict.fromkeys(CHANNELS, np.nan)
use = prep.columns(CHANNELS)
episodes = _episodes(found.events)
if not use or not episodes:
return out
fs = prep.fs
y = signals.bandpass(prep.data(use), fs, *SIGMA)
envelope = signals.by_runs(y, lambda run: np.abs(hilbert(run, axis=0)), int(fs))
asleep = np.zeros(len(envelope), bool)
for start, label in zip(prep.starts, states, strict=True):
if label == "sleep":
asleep[int(start * fs) : int((start + WINDOW_S) * fs)] = True
median = np.nanmedian(envelope[asleep] if asleep.sum() > fs * 30 else envelope, axis=0)
peaks = np.full((len(episodes), len(use)), np.nan)
for k, (t0, t1) in enumerate(episodes):
a, b = max(0, int((t0 - 0.25) * fs)), min(len(envelope), int((t1 + 0.25) * fs))
if b - a >= 3:
peaks[k] = np.nanmax(envelope[a:b], axis=0)
for j, name in enumerate(use):
if np.isfinite(median[j]) and median[j] > 0:
out[name] = float(np.nanmedian(peaks[:, j]) / median[j])
return out