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

67 lines
2.7 KiB
Python

"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average
reference, and the 4 s / 2 s window grid with the stretches QC judged not clean.
The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp
channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given:
the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so.
The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp
channels at 0.5-45 Hz.
"""
import warnings
from dataclasses import dataclass
import numpy as np
from models.tea.eeg import signals
from models.tea.eeg.checks import window_qc
from models.tea.eeg.read import Recording
NOTCH_HZ = 60.0
NOTCH_MIN_DB = 6.0
WINDOW_S = 4.0
STEP_S = 2.0
@dataclass(frozen=True)
class Prepared:
x: np.ndarray # (samples, scalp channels) µV, average reference
names: tuple[str, ...] # the kept scalp channels
fs: float
starts: np.ndarray # window grid starts, s
unclean: tuple[tuple[float, float], ...] # (onset s, duration s) of QC windows not clean
annotations: tuple[tuple[float, float, str], ...]
@property
def duration_s(self) -> float:
return len(self.x) / self.fs
def columns(self, wanted) -> list[str]:
"""The kept channels among `wanted`, in `wanted`'s order."""
return [name for name in wanted if name in self.names]
def data(self, names) -> np.ndarray:
return self.x[:, [self.names.index(name) for name in names]]
def prepare(rec: Recording, bad) -> Prepared:
scalp = [name for name in rec.of("eeg") if name not in bad]
x = rec.x[:, [rec.names.index(name) for name in scalp]]
if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB:
x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5)
gaps = ~np.isfinite(x).all(axis=1)
y = signals.bandpass(x, rec.fs, 0.5, 100.0)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row
referenced = y - np.nanmean(y, axis=1, keepdims=True)
# Kept as the reference analysis read it from MNE: through volts and back, column-major in
# memory (the layout decides the order of float sums along time).
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
qc[gaps] = np.nan
unclean = tuple(
(float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean"
)
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S)
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)