Files
tea/tests/test_preprocessing.py
T
AlbertoPMDM acfd3a70d4 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)).
2026-11-18 20:50:33 -06:00

72 lines
3.1 KiB
Python

"""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)