modern: the director's filter and spectra, and gaps stay NaN

- every private _signal.bandpass: scipy butter + sosfiltfilt per gap-free run, as
  eeg_io.pasa_banda (MNE's IIR padded the run edges differently: up to tens of µV)
- preprocessing: variants built as preproceso (band-pass per run, nanmean
  reference); BAD_ACQ_SKIP gaps stay NaN in every variant instead of 0 µV, so no
  module filters or detects across a gap (the director's EDF reader reads them as
  signal; his Natus route keeps NaN)
- aperiodic: DPSS multitaper on demeaned windows with equal taper weights
  (espectro.multitaper) instead of MNE's eigenvalue-weighted one without demeaning
- gradient: symmetric Hann periodogram of demeaned windows (gradiente.potencias)
- tests: preprocessing equal to the director sample by sample (edges included);
  every biomarker equal to legacy within 1e-4 on gap-free recordings
This commit is contained in:
AlbertoPMDM
2026-11-19 02:10:15 -06:00
parent 0ee5263419
commit 6d0a99e6e5
13 changed files with 304 additions and 108 deletions
+53
View File
@@ -0,0 +1,53 @@
"""
Modern = legacy on a gap-free recording: since the modern modules use the director's own
filter (scipy sosfiltfilt) and spectra (DPSS multitaper with demeaned windows, symmetric
Hann periodogram), every biomarker agrees with legacy to float32 precision (legacy stores
its variants as float32). With gaps they differ by design: modern keeps gaps as NaN.
"""
from __future__ import annotations
import numpy as np
import pytest
from synth_edf import make_edf
from tea_modulo.pipeline import Pipeline
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
TOL = 1e-4
@pytest.fixture(scope="module")
def tables(tmp_path_factory):
d = tmp_path_factory.mktemp("prec")
st = [("vigilia", 0, 150), ("sueno", 150, 600)]
paths = [make_edf(d / f"p{i}.edf", minutes=10, states=st, seed=i, rhythm_hz=6.5 + i) for i in range(2)]
bios = tuple(Pipeline.default(impl="legacy").biomarker_names())
kw = dict(plan=DIRECTOR_CLUSTER, ages_months=[24, 30], biomarkers=bios)
return (Pipeline.default(impl="legacy").map(paths, **kw),
Pipeline.default(impl="modern").map(paths, cluster="sync", **kw))
def test_every_feature_matches_legacy_without_gaps(tables):
legacy, modern = tables
assert (legacy.error == "").all() and (modern.error == "").all()
skip = {"key", "age_months", "valid", "level", "reasons", "plan_hash", "error", "versions", "seconds",
"clean_fraction", "n_bad_channels"}
feats = [c for c in legacy.columns if c in modern.columns and c not in skip]
assert len(feats) > 60
bad = {}
for f in feats:
a, b = legacy[f].astype(float).to_numpy(), modern[f].astype(float).to_numpy()
if (np.isfinite(a) != np.isfinite(b)).any():
bad[f] = "NaN in one only"
continue
ok = np.isfinite(a)
if ok.any():
tol = TOL * max(1.0, float(np.abs(a[ok]).max()))
if f == "coupling_angle_deg":
d = np.abs((a[ok] - b[ok] + 180) % 360 - 180)
else:
d = np.abs(a[ok] - b[ok])
if d.max() > tol:
bad[f] = float(d.max())
assert not bad, bad
+50 -16
View File
@@ -1,4 +1,5 @@
"""Modern preprocessing: same plan, MNE operations, agrees with the director's output."""
"""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
@@ -14,10 +15,8 @@ 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)
# the director stores variants as float32: compare to float32 precision
TOL_UV = 1e-3
@pytest.fixture(scope="module")
@@ -25,21 +24,56 @@ 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()))
@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)
hp = {v["name"]: v["highpass_hz"] for v in pm.plan["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
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
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):
@@ -47,7 +81,7 @@ def test_aux_filtered_not_rereferenced(edf):
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
assert np.nanmax(abs(r.get_data(picks="eeg").mean(axis=0))) < 1e-12 # average reference
def test_zapline_step(edf):