"""Modern preprocessing: same plan, same filter as the director (scipy sosfiltfilt per gap-free run), agrees with the director's output sample by sample, edges and gaps included.""" 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 # the director stores variants as float32: compare to float32 precision TOL_UV = 1e-3 @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.fixture(scope="module") def edf_gaps(tmp_path_factory): return make_edf(tmp_path_factory.mktemp("pregap") / "g.edf", minutes=5, line_uv=8, gaps=((40.0, 6.0), (130.5, 2.0), (200.0, 12.0))) def _both(path, base): pm = MODULE.run(path, MODULE.plan_for(VAL.summarize(path), base.to_dict())) pl = LEGACY.run(path, LEGACY.plan_for(LVAL.summarize(path), base.to_dict())) check_preprocessed(pm) assert set(pm.variants) == set(pl.variants) return pm, pl @pytest.mark.parametrize("base", [DIRECTOR_CLUSTER, DIRECTOR_CLI], ids=lambda p: p.name) def test_agrees_with_legacy_sample_by_sample(edf, base): """No gaps: the same numbers as the director, edges included (float32 precision).""" pm, pl = _both(edf, base) for v in pm.variants: a, b = pm.variant(v), pl.variant(v) assert a.ch_names == b.ch_names xa, xb = a.get_data() * 1e6, b.get_data() * 1e6 assert np.isfinite(xa).all() and np.isfinite(xb).all() d = np.abs(xa - xb).max() assert d < TOL_UV * max(1.0, np.abs(xb).max() / 100), f"{v}: max difference {d:.4f} uV" assert (pm.windows.clean == pl.windows.clean).all() GAPS = ((40.0, 6.0), (130.5, 2.0), (200.0, 12.0)) def test_gaps_stay_gaps(edf_gaps): """BAD_ACQ_SKIP: NaN in every variant and channel (the director's EDF reader reads the zeros as signal and filters across them; his Natus route keeps NaN, as here). Away from the gaps the numbers stay close to the director's.""" pm, pl = _both(edf_gaps, DIRECTOR_CLUSTER) for v in pm.variants: a, b = pm.variant(v).get_data() * 1e6, pl.variant(v).get_data() * 1e6 fs = pm.variant(v).info["sfreq"] t = np.arange(a.shape[1]) / fs in_gap = np.zeros(len(t), bool) near = np.zeros(len(t), bool) for g0, d in GAPS: in_gap |= (t >= g0) & (t < g0 + d) near |= (t >= g0 - 20) & (t < g0 + d + 20) assert np.isnan(a[:, in_gap]).all(), v assert np.isfinite(a[:, ~in_gap]).all(), v far = ~near # the notch is an FFT over each gap-free run: runs d = np.abs(a[:, far] - b[:, far]) # split differently change it a little everywhere assert np.median(d) < 0.5 and np.corrcoef(a[:, far].ravel(), b[:, far].ravel())[0, 1] > 0.999, v 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 np.nanmax(abs(r.get_data(picks="eeg").mean(axis=0))) < 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)