"""Whether an EEG can be analysed: channel rules, 4 s window QC, triage level and gates. Channel rules flag a channel bad (each reason is one check): dead (< 10 finite samples or SD < 0.5 µV, which skips the rest), frozen, saturated, infinite values, gaps of its own; after the mains notch and a 0.5-45 Hz band-pass, an amplitude over 4 x the scalp median, intermittent contact (10 s blocks far below the montage) or bursts (far above it); on 1-40 Hz, a bridge with a contiguous electrode or an ear that does not follow its neighbours; EOG/ECG out of range. Window QC splits the kept scalp channels (notch, 0.5-45 Hz) into back-to-back 4 s windows: a gap, or a window over 800 µV peak to peak, with muscle (30-45 / 4-13 Hz power, fixed lines out, over 0.6) or common mode over 0.8, is not clean. Triage sets the level from coverage, bad scalp electrodes and clean minutes; the gates make the EEG not valid when the level is `not_analyzable`, fewer than 60 % of windows are clean or fewer than 12 scalp electrodes are usable. """ from dataclasses import dataclass, field import numpy as np from models.tea.eeg import signals from models.tea.eeg.read import Recording NEIGHBOURS = { "Fp1": ("Fp2", "F3", "F7"), "Fp2": ("Fp1", "F4", "F8"), "F7": ("Fp1", "F3", "T3"), "F8": ("Fp2", "F4", "T4"), "F3": ("Fp1", "F7", "Fz", "C3"), "F4": ("Fp2", "F8", "Fz", "C4"), "Fz": ("F3", "F4", "Cz"), "T3": ("F7", "C3", "T5"), "T4": ("F8", "C4", "T6"), "C3": ("F3", "T3", "Cz", "P3"), "C4": ("F4", "T4", "Cz", "P4"), "Cz": ("Fz", "C3", "C4", "Pz"), "T5": ("T3", "P3", "O1"), "T6": ("T4", "P4", "O2"), "P3": ("C3", "T5", "Pz", "O1"), "P4": ("C4", "T6", "Pz", "O2"), "Pz": ("Cz", "P3", "P4"), "O1": ("T5", "P3", "O2"), "O2": ("T6", "P4", "O1"), } # fmt: skip EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")} MIN_CLEAN_PCT = 60.0 MIN_COVERAGE = 0.90 MAX_BAD_SCALP = 2 MIN_SCALP = 12 MAX_LINE_DB = 45.0 NOT_ANALYZABLE = "not_analyzable" @dataclass(frozen=True) class Validation: valid: bool level: str bad: dict[str, list[str]] # channel -> reasons, every kind of channel clean_pct: float line_db: float checks: list[dict] = field(default_factory=list) @property def ears_usable(self) -> bool: return all(ear not in self.bad for ear in ("A1", "A2")) def check( code, *, electrode=None, value=None, text=None, unit=None, low=None, high=None, decisive=False, abnormal=False, ) -> dict: return dict( code=code, electrode=electrode, value=value, text=text, unit=unit, low=low, high=high, decisive=decisive, abnormal=abnormal, ) def file_not_valid(reason: str) -> Validation: rows = [check("file", text=reason, decisive=True, abnormal=True)] return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows) def _filtered(x, fs, mains_hz, lo, hi): return signals.bandpass(signals.notch(x, fs, mains_hz), fs, lo, hi) def _temporal(v: np.ndarray) -> list[tuple[str, str]]: """Rules on a channel's raw samples: (code, reason).""" finite = v[np.isfinite(v)] if len(finite) < 10 or np.std(finite) < 0.5: return [("dead-channel", "dead channel")] out = [] if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5: out.append(("frozen", "frozen")) if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001: out.append(("saturated", "saturated")) if np.isinf(v).any(): out.append(("inf-values", "Inf values")) return out def _contact(y: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: """Per channel, the fraction of 10 s blocks silent against the montage and bursting above it (NaN with fewer than 6 blocks).""" size = int(10 * fs) blocks = len(y) // size low, high = np.full(y.shape[1], np.nan), np.full(y.shape[1], np.nan) if blocks < 6: return low, high sd = np.full((blocks, y.shape[1]), np.nan) for b in range(blocks): block = y[b * size : (b + 1) * size] if np.isfinite(block).all(): sd[b] = block.std(axis=0) with np.errstate(all="ignore"): relative = sd / np.maximum(np.nanmedian(sd, axis=1, keepdims=True), 1e-12) for i in range(y.shape[1]): v = relative[:, i] v = v[np.isfinite(v) & (v > 0)] if len(v) >= 6: low[i] = np.mean((v < 0.25 * max(float(np.percentile(v, 75)), 1e-12)) & (v < 0.35)) high[i] = np.mean(v > 4.0) return low, high def _bridges(y: np.ndarray, names: list[str], scalp: list[int]) -> dict[str, str]: """Scalp channels correlating over 0.99 with a contiguous electrode and with no far one.""" finite = np.isfinite(y).all(axis=1) if finite.sum() < 200 or len(scalp) < 2: return {} r = np.abs(np.corrcoef(y[finite][:, scalp].T)) index = {names[i]: k for k, i in enumerate(scalp)} out = {} for name, k in index.items(): near = [index[n] for n in NEIGHBOURS.get(name, ()) if n in index] far = [j for j in index.values() if j != k and j not in near] if not near: continue best = max(near, key=lambda j: r[k, j]) if r[k, best] > 0.99 and not (far and max(r[k, j] for j in far) > 0.99): out[name] = next(n for n, j in index.items() if j == best) return out def _ears(y: np.ndarray, fs: float, names: list[str]) -> dict[str, tuple[float, float]]: """Per ear: its best |r| with its neighbours, and the neighbours' median |r| between them.""" out = {} for ear, around in EAR_NEIGHBOURS.items(): present = [n for n in around if n in names] if ear not in names or len(present) < 2: continue cols = [names.index(ear)] + [names.index(n) for n in present] rows = np.isfinite(y[:, cols]).all(axis=1) if rows.sum() < fs * 30: continue r = np.abs(np.corrcoef(y[rows][:, cols].T)) between = [r[a, b] for a in range(1, len(cols)) for b in range(a + 1, len(cols))] out[ear] = (float(np.nanmax(r[0, 1:])), float(np.nanmedian(between))) return out def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, str]]]: """Channel -> [(code, reason)] of every channel some rule flags.""" x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds() reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)} dead = { name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")] } notched = signals.notch(x, fs, mains_hz) y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9)) y40 = signals.bandpass(notched, fs, 1.0, 40.0) scalp = [i for i, name in enumerate(names) if kinds[name] == "eeg"] rms = np.nanstd(y45, axis=0) median = float(np.nanmedian(rms[scalp])) if scalp else np.nan ratio = rms / median if np.isfinite(median) and median > 0 else np.full(len(names), np.nan) low, burst = _contact(y45, fs) bridges = _bridges(y40, names, scalp) ears = _ears(y40, fs, names) missing = 1 - np.isfinite(x).mean(axis=0) for i, name in enumerate(names): found, k = reasons[name], kinds[name] if missing[i] > missing.min() + 0.02: excess = 100 * (missing[i] - missing.min()) found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)")) if name in dead: continue if k == "eeg" and name in bridges: found.append(("bridge", f"bridge with {bridges[name]}")) if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0: found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median")) if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]: c, e = ears[name] found.append( ( "does-not-correlate", f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})", ) ) if np.isfinite(low[i]) and low[i] > 0.10: found.append( ( "intermittent-contact", f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)", ) ) if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05: found.append( ( "intermittent-bursts", f"intermittent contact by bursts " f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)", ) ) if k in ("eog", "ecg"): v = x[:, i][np.isfinite(x[:, i])] if np.sqrt(np.mean(v**2)) > 20000: found.append( ( "aux-amplitude", f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, " f"out of range even for {k.upper()}", ) ) return {name: found for name, found in reasons.items() if found} def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]: """Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the verdict `gap`, `suspect` or `clean`.""" n = int(4 * fs) lines = signals.fixed_lines(y, fs, f_max=44.0) starts = list(range(0, len(y) - n + 1, n)) segments = [y[a : a + n] for a in starts] whole = [bool(np.isfinite(s).all()) for s in segments] emg = {} if any(whole): stack = np.stack([s.T for s, ok in zip(segments, whole, strict=True) if ok]) f, power = signals.periodograms(stack, fs) power = np.moveaxis(power, -1, 0) high = signals.band_power(f, power, 30.0, 45.0, lines) low = signals.band_power(f, power, 4.0, 13.0, lines) ratio = np.median(high / np.maximum(low, 1e-12), axis=1) emg = dict(zip([a for a, ok in zip(starts, whole, strict=True) if ok], ratio, strict=True)) out = [] for a, s, ok in zip(starts, segments, whole, strict=True): if not ok: out.append((a / fs, (a + n) / fs, "gap")) continue p2p = float(np.max(s.max(axis=0) - s.min(axis=0))) variance = float(np.mean(s.var(axis=0))) common = float(s.mean(axis=1).var() / variance) if variance > 0 else np.nan muscle = float(emg[a]) suspect = p2p > 800 or (np.isfinite(muscle) and muscle > 0.6) or common > 0.8 out.append((a / fs, (a + n) / fs, "suspect" if suspect else "clean")) return out def _triage(rec: Recording, mains_hz: float, bad: dict, clean_pct: float, coverage: float): """(level, bad scalp electrodes by the triage rule).""" x, fs, kinds = rec.x, rec.fs, rec.kinds() columns = [i for i, name in enumerate(rec.names) if kinds[name] in ("eeg", "ear")] y = _filtered(x[:, columns], fs, mains_hz, 0.5, 45.0) rms, flat = {}, {} for k, i in enumerate(columns): v = y[:, k][np.isfinite(y[:, k])] rms[rec.names[i]] = float(np.nanstd(y[:, k])) if len(v) else np.nan flat[rec.names[i]] = float(np.mean(np.abs(np.diff(v)) < 1e-9)) if len(v) > 1 else 1.0 scalp = rec.of("eeg") median = float(np.nanmedian([rms[n] for n in scalp])) if scalp else np.nan triaged = [n for n in scalp if rms[n] > max(5 * median, 300.0) or rms[n] < 0.5 or flat[n] > 0.5] minutes = rec.duration_s * clean_pct / 100 / 60 base = coverage >= MIN_COVERAGE and len(triaged) <= MAX_BAD_SCALP if not (base and clean_pct >= 30 and minutes >= 3): level = NOT_ANALYZABLE elif not (clean_pct >= 50 and minutes >= 3): level = "partial" elif {"A1", "A2"} & {n for n in bad if kinds[n] == "ear"}: level = "no_ear_reference" else: level = "complete" return level, triaged def validate(rec: Recording, mains_hz: float) -> Validation: flagged = bad_channels(rec, mains_hz) scalp = rec.of("eeg") usable = [n for n in scalp if n not in flagged] qc = usable if len(usable) >= 2 else scalp y = _filtered(rec.x[:, [rec.names.index(n) for n in qc]], rec.fs, mains_hz, 0.5, 45.0) windows = window_qc(y, rec.fs) clean_pct = 100.0 * sum(v == "clean" for *_, v in windows) / max(len(windows), 1) coverage = float(np.isfinite(rec.x).all(axis=1).mean()) columns = [rec.names.index(n) for n in scalp] if scalp else slice(None) db = signals.line_db(rec.x[:, columns], rec.fs, mains_hz) line = float(np.nanmedian(db)) if np.isfinite(db).any() else np.nan level, triaged = _triage(rec, mains_hz, flagged, clean_pct, coverage) rows = [ check(code, electrode=name, text=reason, abnormal=True) for name, found in flagged.items() for code, reason in found ] rows += [ check( "clean-windows", value=clean_pct, unit="%", low=MIN_CLEAN_PCT, abnormal=clean_pct < MIN_CLEAN_PCT, decisive=True, ), check( "internal-coverage", value=coverage, unit="fraction", low=MIN_COVERAGE, abnormal=coverage < MIN_COVERAGE, decisive=True, ), check( "bad-scalp-triage", value=float(len(triaged)), unit="electrodes", high=float(MAX_BAD_SCALP), abnormal=len(triaged) > MAX_BAD_SCALP, decisive=True, ), check( "usable-scalp", value=float(len(usable)), unit="electrodes", low=float(MIN_SCALP), abnormal=len(usable) < MIN_SCALP, decisive=True, ), check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True), ] if np.isfinite(line): rows.append( check( "line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB ) ) valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP bad = {name: [reason for _, reason in found] for name, found in flagged.items()} return Validation(valid, level, bad, clean_pct, line, rows)