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

224 lines
9.7 KiB
Python

"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3).
Notes: a note's state is the first whose words its text contains (lower case, accents removed,
ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s;
pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement,
disconnection, photic stimulation and hyperventilation are masked.
State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five
features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma,
muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is standardised by
the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age),
and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no
posterior electrode leaves that feature out of the mean.
Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2
s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least
20 % of the 30 s centred on it, else N2.
"""
import json
import unicodedata
from pathlib import Path
import numpy as np
from models.tea.eeg import signals
from models.tea.eeg.preprocess import WINDOW_S, Prepared
REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text())
NOTE_WORDS = {
"photic": ("fotic", "photic", "flash", "estimulacion luminosa"),
"hyperventilation": ("hv", "hipervent", "hypervent"),
"eyes_open": ("ojos abiertos", "eyes open", "oa"),
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii",
"n1", "n2", "n3"),
"awake": ("despierta", "despierto", "arousal", "vigilia"),
"crying": ("llanto", "llora", "cry"),
"movement": ("movimiento", "movement", "artefacto de movimiento"),
"feeding": ("come", "alimenta", "biberon", "lactancia"),
} # fmt: skip
EXCLUDED = ("crying", "movement", "disconnection")
MASKED = (*EXCLUDED, "photic", "hyperventilation")
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16),
"beta": (16, 30), "high": (20, 40)} # fmt: skip
POSTERIOR = ("O1", "O2", "P3", "P4")
CENTRAL = ("C3", "C4", "Cz")
FRONTAL = ("F3", "F4", "Fz")
def note_state(text: str) -> str | None:
kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1")
plain = "".join(
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
)
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
return next(
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
)
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
"""(onset s, duration s, state) covering the record: the notes' states and `unmarked`."""
notes = sorted(annotations, key=lambda note: note[0])
found = []
for i, (t0, length, text) in enumerate(notes):
state = note_state(text)
if state is None:
continue
if length > 0:
t1 = t0 + length
else:
following = next((n[0] for n in notes[i + 1 :] if note_state(n[2])), None)
t1 = min(t0 + 60.0, following if following else t0 + 60.0)
if t1 - t0 >= 1:
found.append((t0, t1, state))
found.sort(key=lambda piece: piece[0])
full, cursor = [], 0.0
for t0, t1, state in found:
if t0 - cursor >= 1:
full.append((cursor, t0, "unmarked"))
full.append((t0, t1, state))
cursor = max(cursor, t1)
if duration_s - cursor >= 1:
full.append((cursor, duration_s, "unmarked"))
pieces = [(round(t0, 2), round(t1, 2), state) for t0, t1, state in full]
return [(t0, t1 - t0, state) for t0, t1, state in pieces]
def window_note(t0: float, t1: float, intervals) -> tuple[str, bool]:
"""The state covering most of [t0, t1) and whether it covers less than 80 % of it."""
overlap = {}
for onset, length, state in intervals:
lo, hi = max(t0, onset), min(t1, onset + length)
if hi > lo:
overlap[state] = overlap.get(state, 0) + (hi - lo)
if not overlap:
return "unlabelled", False
dominant = max(overlap, key=overlap.get)
return dominant, overlap[dominant] < 0.8 * (t1 - t0)
def mask(prep: Prepared, intervals) -> np.ndarray:
"""Samples of the QC spans and of the masked notes."""
out = np.zeros(len(prep.x), bool)
spans = [*prep.unclean, *((o, d) for o, d, state in intervals if state in MASKED)]
for onset, length in spans:
out[int(onset * prep.fs) : int((onset + length) * prep.fs)] = True
return out
def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, np.ndarray]]:
"""Start samples of the usable windows and their features."""
fs, x, names = prep.fs, prep.x, list(prep.names)
n, step = int(WINDOW_S * fs), int(2 * fs)
starts = [
a
for a in range(0, len(x) - n + 1, step)
if np.isfinite(x[a : a + n]).all() and not masked[a : a + n].any()
]
if not starts:
return [], {}
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names))))
posterior = [names.index(c) for c in POSTERIOR if c in names]
delta_beta = np.median(band["delta"] / np.maximum(band["beta"], 1e-12), axis=1)
features = {
"delta_beta": np.log10(np.clip(delta_beta, 1e-6, None)),
"sigma": np.median((band["sigma"] / total)[:, central], axis=1),
"muscle": np.median(
band["high"] / np.maximum(band["theta"] + band["alpha"], 1e-12), axis=1
),
"alpha": np.median(band["alpha"] / total, axis=1),
}
if posterior:
peaks = [
signals.dominant_peak(f, power[w, posterior].mean(axis=0)) for w in range(len(starts))
]
features["posterior_rhythm"] = np.array([db if found else 0.0 for _, db, found in peaks])
return starts, features
def depth(features: dict[str, np.ndarray], age_months: float | None) -> np.ndarray:
"""The weighted mean of the standardised features, clipped to ±6."""
z, weights = [], []
for name, ref in REFERENCE["features"].items():
if name not in features:
continue
if "slope" in ref and age_months and age_months > 0:
median = ref["slope"] * np.log10(float(age_months)) + ref["intercept"]
else:
median = ref["median"]
z.append(ref["sign"] * (features[name] - median) / max(ref["dispersion"], 1e-9))
weights.append(ref["weight"])
w = np.array(weights, float)
return np.clip((np.column_stack(z) * w).sum(axis=1) / w.sum(), -6, 6)
def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
"""`wake`, `drowsy`, `sleep` or `` (not scored) per grid window."""
starts, features = _features(prep, mask(prep, intervals))
out = np.full(len(prep.starts), "", dtype=object)
if not starts:
return out
labels = STATES[np.digitize(depth(features, age_months), REFERENCE["cuts"])]
by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True))
out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts]
return out
def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
"""(onset s, duration s) of the slow waves of one channel."""
y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
sign = np.sign(y)
sign[sign == 0] = 1
crossings = np.flatnonzero(np.diff(sign) != 0) + 1
waves = []
for j, c0 in enumerate(crossings):
if not y[c0] < 0:
continue
if j + 2 >= len(crossings):
break
c1, c2 = crossings[j + 1], crossings[j + 2]
negative, total = (c1 - c0) / fs, (c2 - c0) / fs
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
continue
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
if 75.0 <= p2p <= 300.0:
waves.append((round(c0 / fs, 3), round(total, 3)))
return waves
def _merged(waves: list[tuple[float, float]]) -> np.ndarray:
if not waves:
return np.empty((0, 2))
a = np.array([onset for onset, _ in waves])
b = a + np.array([length for _, length in waves])
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 np.array(out)
def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray:
"""`N3` or `N2` per sleep window (`` elsewhere)."""
waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
covered = _merged(waves)
out = np.full(len(prep.starts), "", dtype=object)
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
if label != "sleep":
continue
t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
return out