From acfd3a70d4e35016373587fe64e24c1fcdea76ea Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Wed, 18 Nov 2026 20:50:33 -0600 Subject: [PATCH] preprocessing: modern Preprocessor on MNE, agreeing with the director's output Executes a PreprocessPlan with MNE: EDF read and label normalisation, plan bads dropped, line removal on the raw signal (interpolated notch when the line is >= min_db on the kept scalp channels, or ZapLine via meegkit), Raw.filter (IIR Butterworth order 4, zero phase, run by run between BAD_ACQ_SKIP), set_eeg_reference (average of kept scalp / linked ears), EOG/ECG filtered only. Window grid and quality spans from a private copy of the window QC. Within 0.25 uV of legacy.preprocessing on every channel of both default plans away from the filter edges (max(5 s, 3/highpass)). --- pyproject.toml | 1 + src/tea_modulo/preprocessing/__init__.py | 12 +- src/tea_modulo/preprocessing/_channels.py | 76 +++++++++ src/tea_modulo/preprocessing/_qc.py | 69 ++++++++ src/tea_modulo/preprocessing/_signal.py | 192 ++++++++++++++++++++++ src/tea_modulo/preprocessing/api.py | 138 ++++++++++++++++ tests/test_preprocessing.py | 71 ++++++++ 7 files changed, 555 insertions(+), 4 deletions(-) create mode 100644 src/tea_modulo/preprocessing/_channels.py create mode 100644 src/tea_modulo/preprocessing/_qc.py create mode 100644 src/tea_modulo/preprocessing/_signal.py create mode 100644 src/tea_modulo/preprocessing/api.py create mode 100644 tests/test_preprocessing.py diff --git a/pyproject.toml b/pyproject.toml index 0a0ac6c..aaab55f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,7 @@ posterior_rhythm = "tea_modulo.legacy.biomarkers.posterior_rhythm:MODULE" [project.entry-points."tea_modulo.modules"] validation = "tea_modulo.validation:MODULE" +preprocessing = "tea_modulo.preprocessing:MODULE" [project.entry-points."tea_modulo.executors"] legacy = "tea_modulo.legacy.executor:run_serial" diff --git a/src/tea_modulo/preprocessing/__init__.py b/src/tea_modulo/preprocessing/__init__.py index 99162ba..4304b84 100644 --- a/src/tea_modulo/preprocessing/__init__.py +++ b/src/tea_modulo/preprocessing/__init__.py @@ -1,8 +1,12 @@ """ -Preprocessing: PreprocessPlan, the default plans and (later) the modern -Preprocessor built on MNE. +Preprocessing: PreprocessPlan, the default plans and the modern Preprocessor (MNE). + + from tea_modulo.preprocessing import MODULE, DIRECTOR_CLUSTER + plan = MODULE.plan_for(summary, DIRECTOR_CLUSTER.to_dict()) + prep = MODULE.run("study.edf", plan, age_months=27.5) """ +from tea_modulo.preprocessing.api import MODULE, Preprocessing from tea_modulo.preprocessing.defaults import DIRECTOR_CLI, DIRECTOR_CLUSTER, PLANS from tea_modulo.preprocessing.plan import ( GateSettings, @@ -12,5 +16,5 @@ from tea_modulo.preprocessing.plan import ( VariantSpec, ) -__all__ = ["PreprocessPlan", "StepSpec", "VariantSpec", "StateSettings", "GateSettings", - "DIRECTOR_CLUSTER", "DIRECTOR_CLI", "PLANS"] +__all__ = ["MODULE", "Preprocessing", "PreprocessPlan", "StepSpec", "VariantSpec", "StateSettings", + "GateSettings", "DIRECTOR_CLUSTER", "DIRECTOR_CLI", "PLANS"] diff --git a/src/tea_modulo/preprocessing/_channels.py b/src/tea_modulo/preprocessing/_channels.py new file mode 100644 index 0000000..6b72dc6 --- /dev/null +++ b/src/tea_modulo/preprocessing/_channels.py @@ -0,0 +1,76 @@ +""" +Channel labels and classes (private copy; other modules own their own). + +Label sets, classes and 10-20 neighbours are the director's +(preproceso/eeg_io.py EEG_1020 / OREJAS / EOG / CARDIACO / AUXILIAR, +validacion.VECINOS_1020, edf_convert.normalizar_canal) @ 7dfc641. +""" + +from __future__ import annotations + +import re + +EEG_1020 = {"FP1", "FP2", "F3", "F4", "C3", "C4", "P3", "P4", "O1", "O2", "F7", "F8", "T3", "T4", + "T5", "T6", "FZ", "CZ", "PZ", "T7", "T8", "P7", "P8", "FPZ", "OZ"} +EARS = {"A1", "A2", "M1", "M2"} +EOG = {"ROC", "LOC", "EOG", "EOG1", "EOG2", "VEOG", "HEOG", "E1", "E2"} +CARDIAC = {"EKG", "ECG", "EKG1", "EKG2"} +AUX = {"DC", "OSAT", "PR", "SPO2", "RESP", "EMG", "CHIN", "PHOTIC", "TRIG", "PULSE"} + +STANDARD = ("Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2 A1 A2 T7 T8 P7 P8 Oz Fpz").split() +_MAP = {n.upper(): n for n in STANDARD} +_MODERN = {"T7": "T3", "T8": "T4", "P7": "T5", "P8": "T6"} + +NEIGHBOURS_1020 = { + "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"), +} +EAR_NEIGHBOURS = {"A1": ("T3", "T5", "F7"), "A2": ("T4", "T6", "F8")} + + +def normalize(label: str) -> str | None: + """'EEG Fp1-REF' -> 'Fp1'; None if not a recognised channel (edf_convert.normalizar_canal).""" + s = str(label).strip() + if not s or "ANNOT" in s.upper(): + return None + s2 = re.sub(r"^\s*(EEG|ECG|EKG|EOG|EMG|POL)\s+", "", s, flags=re.I) + s2 = re.split(r"[-]", s2)[0].strip() + key = re.sub(r"[^A-Z0-9]", "", s2.upper()) + if key in _MAP: + return _MODERN.get(_MAP[key], _MAP[key]) + up = s.upper() + for aux, dev in (("EKG", "EKG"), ("ECG", "EKG"), ("LOC", "LOC"), ("ROC", "ROC"), ("EOG", "ROC")): + if aux in up: + return dev + return None + + +def classify(names) -> dict[str, str]: + """{name: eeg | orejas | eog | cardiaco | auxiliar | sin_uso | desconocido}.""" + out = {} + for n in names: + u = str(n).strip().upper() + if u in EEG_1020: + out[n] = "eeg" + elif u in EARS: + out[n] = "orejas" + elif u in EOG: + out[n] = "eog" + elif u in CARDIAC: + out[n] = "cardiaco" + elif u in AUX: + out[n] = "auxiliar" + elif u.isdigit() or (u.startswith("CH") and u[2:].isdigit()): + out[n] = "sin_uso" + else: + out[n] = "desconocido" + return out diff --git a/src/tea_modulo/preprocessing/_qc.py b/src/tea_modulo/preprocessing/_qc.py new file mode 100644 index 0000000..11c725d --- /dev/null +++ b/src/tea_modulo/preprocessing/_qc.py @@ -0,0 +1,69 @@ +""" +Window QC for the window table (private copy of the validation's window rules, +lote.qc_estudio), and the window grid / quality spans built from it (same +rules as the legacy adapter: windows_from_qc, spans_from_qc). +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from . import _signal + +P2P_MAX_UV = 800.0 +EMG_MAX = 0.6 +COMMON_MODE_MAX = 0.8 +WINDOW_S = 4.0 + + +def window_qc(y, fs, window_s=WINDOW_S) -> list[dict]: + from mne.time_frequency import psd_array_welch + + n = int(window_s * fs) + lines = _signal.fixed_lines(y, fs, f_max=44.0) + starts = list(range(0, y.shape[0] - n + 1, n)) + segs = [y[a:a + n] for a in starts] + ok = [bool(np.isfinite(s).all()) for s in segs] + emg = {} + if any(ok): + arr = np.stack([s.T for s, g in zip(segs, ok) if g]) + P, f = psd_array_welch(arr, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") + hi = _signal.band_power(f, np.moveaxis(P, -1, 0), 30.0, 45.0, lines) + lo = _signal.band_power(f, np.moveaxis(P, -1, 0), 4.0, 13.0, lines) + emg = dict(zip([a for a, g in zip(starts, ok) if g], np.median(hi / np.maximum(lo, 1e-12), axis=1))) + out = [] + for a, s, good in zip(starts, segs, ok): + row = {"t_ini": a / fs, "t_fin": (a + n) / fs, "montaje": False} + if not good: + out.append({**row, "veredicto": "HUECO"}) + continue + p2p = float(np.max(s.max(axis=0) - s.min(axis=0))) + v_med = float(np.mean(s.var(axis=0))) + mc = float(s.mean(axis=1).var() / v_med) if v_med > 0 else np.nan + e = float(emg[a]) + bad = p2p > P2P_MAX_UV or (np.isfinite(e) and e > EMG_MAX) or (np.isfinite(mc) and mc > COMMON_MODE_MAX) + out.append({**row, "veredicto": "sospechosa" if bad else "limpia", "p2p_uv": p2p, "emg": e, + "common_mode": mc}) + return out + + +def windows_from_qc(qc, duration_s, window_s, step_s) -> pd.DataFrame: + starts = np.arange(0.0, duration_s - window_s + 1e-9, step_s) + q = pd.DataFrame(qc) if qc else pd.DataFrame(columns=["t_ini", "t_fin", "veredicto", "montaje"]) + clean, gap = [], [] + for s in starts: + e = s + window_s + o = q[(q.t_ini < e) & (q.t_fin > s)] if len(q) else q + covered = len(o) > 0 and float(o.t_fin.max()) >= e - 1e-6 and float(o.t_ini.min()) <= s + 1e-6 + clean.append(bool(covered and (o.veredicto == "limpia").all() and not o.montaje.any())) + gap.append(bool(len(o) and (o.veredicto == "HUECO").any())) + return pd.DataFrame({"start_s": starts, "end_s": starts + window_s, + "clean": np.array(clean, bool), "gap": np.array(gap, bool)}) + + +def spans_from_qc(qc) -> pd.DataFrame: + rows = [{"onset_s": float(v["t_ini"]), "duration_s": float(v["t_fin"]) - float(v["t_ini"]), + "reason": str(v["veredicto"])} for v in qc if v["veredicto"] != "limpia" or v["montaje"]] + return pd.DataFrame(rows, columns=["onset_s", "duration_s", "reason"]).astype( + {"onset_s": float, "duration_s": float, "reason": str}) diff --git a/src/tea_modulo/preprocessing/_signal.py b/src/tea_modulo/preprocessing/_signal.py new file mode 100644 index 0000000..1848ab5 --- /dev/null +++ b/src/tea_modulo/preprocessing/_signal.py @@ -0,0 +1,192 @@ +""" +Signal primitives for preprocessing (private copy of the validation one), 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 diff --git a/src/tea_modulo/preprocessing/api.py b/src/tea_modulo/preprocessing/api.py new file mode 100644 index 0000000..7391c03 --- /dev/null +++ b/src/tea_modulo/preprocessing/api.py @@ -0,0 +1,138 @@ +""" +Modern preprocessing: a PreprocessPlan executed with MNE. + +Order (as preproceso.procesar): + read EDF (MNE) -> drop bad channels (plan.bads) -> line removal on the raw signal + (interpolated notch if the line is >= min_db over its neighbourhood, measured on the + kept scalp channels; or ZapLine, meegkit) -> per variant: high-pass + low-pass + (Raw.filter, IIR Butterworth order 4, zero phase, run by run between BAD_ACQ_SKIP) + -> reference (Raw.set_eeg_reference: average of the kept scalp channels, or the + linked ears A1+A2). EOG / ECG are filtered and never re-referenced. + +Windows: the plan's grid (window_s / step_s), flagged from a 4 s back-to-back +window QC (private copy of the validation's rules); quality_spans are the QC +windows that are not clean. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +import numpy as np +import pandas as pd + +from tea_modulo.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of + +from . import _channels, _qc, _signal +from .plan import PreprocessPlan + +GAP = ("BAD_ACQ_SKIP", "edge") +KEEP = ("eeg", "orejas", "eog", "cardiaco") +_TYPE = {"eeg": "eeg", "orejas": "eeg", "eog": "eog", "cardiaco": "ecg"} + + +class Preprocessing: + name = "preprocessing" + version = "0.1.0" + contract_version = CONTRACT_VERSION + impl = "modern" + + def plan_for(self, summary: ValidationSummary, base: Mapping[str, Any]) -> dict: + d = PreprocessPlan.from_dict(base).to_dict() + new = [c for c in summary.bad_channels if c not in d["bads"]] + d["bads"] = list(d["bads"]) + new + d["reasons"] = {**d["reasons"], **{c: summary.bad_channels[c] for c in new}} + if not summary.ears_usable: + d["variants"] = [v for v in d["variants"] if v["reference"] != "linked_ears"] + d["reasons"]["variants"] = "ears not usable: linked-ears variants dropped" + return d + + # ------------------------------------------------------------------ run + def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed: + import mne + + p = PreprocessPlan.from_dict(plan) + raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error") + ren, seen, drop = {}, set(), [] + for c in raw.ch_names: # edf_convert: unknown dropped, first duplicate kept + n = _channels.normalize(c) + if n is None or n in seen: + drop.append(c) + else: + seen.add(n) + ren[c] = n + raw.drop_channels(drop) + raw.rename_channels({c: n for c, n in ren.items() if n != c}) + classes = _channels.classify(raw.ch_names) + keep = [c for c in raw.ch_names if classes[c] in KEEP and c not in p.bads] + raw.pick(keep) + raw.set_channel_types({c: _TYPE[classes[c]] for c in keep}, verbose="error") + fs = float(raw.info["sfreq"]) + scalp = [c for c in keep if classes[c] == "eeg"] + ears = [c for c in keep if classes[c] == "orejas"] + if len(scalp) < p.gates.min_scalp: + raise ValueError(f"only {len(scalp)} scalp electrodes usable (minimum {p.gates.min_scalp})") + + # line removal on the raw signal + x = raw.get_data(reject_by_annotation="NaN", verbose="error").T * 1e6 + idx_scalp = [keep.index(c) for c in scalp] + db_before = float(np.nanmedian(_signal.line_db(x[:, idx_scalp], fs, p.line_hz))) + removal = "none" + notch = p.step("interpolated_notch") + zap = p.step("zapline") + if notch is not None and db_before >= float(notch.params.get("min_db", 6.0)): + x = _signal.notch_interpolated(x, fs, p.line_hz, width=float(notch.params.get("width_hz", 1.5))) + removal = "interpolated_notch" + elif zap is not None: + x = _zapline(x, fs, p.line_hz, int(zap.params.get("nremove", 1))) + removal = "zapline" + gaps = ~np.isfinite(x).all(axis=1) + raw._data[:] = np.nan_to_num(x, nan=0.0).T * 1e-6 + + lp = p.step("lowpass").params["hz"] if p.step("lowpass") else None + iir = {"order": 4, "ftype": "butter"} + variants = {} + for v in p.variants: + r = raw.copy().filter(v.highpass_hz, lp, method="iir", iir_params=iir, phase="zero", + skip_by_annotation=GAP, verbose="error") + if v.reference == "linked_ears": + if len(ears) != 2: + raise ValueError(f"variant {v.name}: linked ears need both A1 and A2 usable") + r.set_eeg_reference(ears, verbose="error") + r.drop_channels(ears) + else: + r.drop_channels(ears) + r.set_eeg_reference("average", verbose="error") + variants[v.name] = r + + # window QC (4 s back-to-back) on the kept scalp channels, notch + 0.5-45 Hz + y = x[:, idx_scalp] + y = _signal.bandpass(y, fs, 0.5, 45.0) + y[gaps] = np.nan + qc = _qc.window_qc(y, fs) + duration = raw.n_times / fs + d = p.to_dict() + d["run"] = {"line_db_before": round(db_before, 1), "line_removal": removal, + "channels": scalp, "aux": [c for c in keep if classes[c] in ("eog", "cardiaco")], + "ears": ears} + return Preprocessed(variants=variants, windows=_qc.windows_from_qc(qc, duration, p.window_s, p.step_s), + age_months=age_months, plan=d, plan_hash=p.content_hash(), + source_sha256=sha256_of(edf_path), quality_spans=_qc.spans_from_qc(qc)) + + +def _zapline(x, fs, f0, nremove): + """ZapLine (meegkit.dss.dss_line) on each gap-free run long enough for its FFT.""" + from meegkit.dss import dss_line + + def f(seg): + import contextlib + import io + with contextlib.redirect_stdout(io.StringIO()): # dss_line prints a summary + out, _ = dss_line(seg, f0, fs, nremove=nremove) + return out + return _signal.by_runs(x, f, minimum=max(int(4 * fs), 1024)) + + +MODULE = Preprocessing() diff --git a/tests/test_preprocessing.py b/tests/test_preprocessing.py new file mode 100644 index 0000000..74c0215 --- /dev/null +++ b/tests/test_preprocessing.py @@ -0,0 +1,71 @@ +"""Modern preprocessing: same plan, MNE operations, agrees with the director's output.""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest + +from synth_edf import make_edf +from tea_modulo.contracts.testing import check_preprocessed +from tea_modulo.legacy.preprocessing import MODULE as LEGACY +from tea_modulo.legacy.validation import MODULE as LVAL +from tea_modulo.preprocessing import DIRECTOR_CLI, DIRECTOR_CLUSTER, MODULE, PreprocessPlan +from tea_modulo.validation import MODULE as VAL + +# MNE pads IIR filter edges differently from sosfiltfilt; the transient lasts longer +# the lower the high-pass: compare from max(5 s, 3 / highpass) on +def edge_s(highpass): + return max(5.0, 3.0 / highpass) + + +@pytest.fixture(scope="module") +def edf(tmp_path_factory): + return make_edf(tmp_path_factory.mktemp("pre") / "s.edf", minutes=5, bad={"bursts": ["P4"]}, line_uv=8) + + +@pytest.mark.parametrize("base", [DIRECTOR_CLUSTER, DIRECTOR_CLI], ids=lambda p: p.name) +def test_agrees_with_legacy(edf, base): + pm = MODULE.run(edf, MODULE.plan_for(VAL.summarize(edf), base.to_dict())) + pl = LEGACY.run(edf, LEGACY.plan_for(LVAL.summarize(edf), base.to_dict())) + check_preprocessed(pm) + assert set(pm.variants) == set(pl.variants) + hp = {v["name"]: v["highpass_hz"] for v in pm.plan["variants"]} + for v in pm.variants: + a, b = pm.variant(v), pl.variant(v) + assert a.ch_names == b.ch_names + e = int(edge_s(hp[v]) * a.info["sfreq"]) + eeg = [c for c, t in zip(a.ch_names, a.get_channel_types()) if t == "eeg"] + d = np.abs(a.get_data(picks=eeg)[:, e:-e] - b.get_data(picks=eeg)[:, e:-e]) * 1e6 + assert d.max() < 0.25, f"{v}: max difference {d.max():.3f} uV" + assert (pm.windows.clean == pl.windows.clean).mean() > 0.95 + + +def test_aux_filtered_not_rereferenced(edf): + pm = MODULE.run(edf, MODULE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict())) + r = pm.variant("hp05_prom") + assert set(r.get_channel_types(picks=["LOC", "ROC", "EKG"])) == {"eog", "ecg"} + assert "P4" not in r.ch_names and "A1" not in r.ch_names + assert abs(r.get_data(picks="eeg").mean(axis=0)).max() < 1e-12 # average reference + + +def test_zapline_step(edf): + d = DIRECTOR_CLUSTER.to_dict() + d["steps"] = [s for s in d["steps"] if s["kind"] != "interpolated_notch"] + \ + [{"kind": "zapline", "params": {"nremove": 1}}] + pm = MODULE.run(edf, MODULE.plan_for(VAL.summarize(edf), PreprocessPlan.from_dict(d).to_dict())) + assert pm.plan["run"]["line_removal"] == "zapline" + from mne.time_frequency import psd_array_welch + P, f = psd_array_welch(pm.variant("hp05_prom").get_data(picks="eeg"), 250.0, n_fft=1000, verbose="error") + at60 = P[:, np.argmin(abs(f - 60))].mean() + near = P[:, (abs(f - 60) > 3) & (abs(f - 60) < 8)].mean() + assert at60 < 3 * near + + +def test_plan_bads_and_gates(edf): + d = MODULE.plan_for(VAL.summarize(edf), DIRECTOR_CLUSTER.to_dict()) + assert "P4" in d["bads"] and "P4" in d["reasons"] + many = {**d, "bads": d["bads"] + ["Fp1", "Fp2", "F3", "F4", "F7", "F8", "Fz"]} + with pytest.raises(ValueError, match="scalp electrodes usable"): + MODULE.run(edf, many)