From 6d0a99e6e5fd14546dec4830c5fd2bcdc41b4d8d Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Thu, 19 Nov 2026 02:10:15 -0600 Subject: [PATCH] modern: the director's filter and spectra, and gaps stay NaN MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- src/tea_modulo/biomarkers/aperiodic/api.py | 25 +++++-- src/tea_modulo/biomarkers/coupling/_signal.py | 25 ++++--- src/tea_modulo/biomarkers/gradient/api.py | 21 ++++-- src/tea_modulo/biomarkers/spikes/_signal.py | 25 ++++--- .../biomarkers/spindle_topography/_signal.py | 25 ++++--- src/tea_modulo/preprocessing/_signal.py | 25 ++++--- src/tea_modulo/preprocessing/api.py | 47 ++++++++----- .../processes/slow_wave_staging/_signal.py | 25 ++++--- .../processes/spindle_detection/_signal.py | 25 ++++--- .../processes/window_selection/_signal.py | 25 ++++--- src/tea_modulo/validation/_signal.py | 25 ++++--- tests/test_modern_precision.py | 53 +++++++++++++++ tests/test_preprocessing.py | 66 ++++++++++++++----- 13 files changed, 304 insertions(+), 108 deletions(-) create mode 100644 tests/test_modern_precision.py diff --git a/src/tea_modulo/biomarkers/aperiodic/api.py b/src/tea_modulo/biomarkers/aperiodic/api.py index 2708201..7e14d47 100644 --- a/src/tea_modulo/biomarkers/aperiodic/api.py +++ b/src/tea_modulo/biomarkers/aperiodic/api.py @@ -2,8 +2,11 @@ Modern aperiodic (the cluster route's definitions): windows clean 2 s windows of each state (at least 20) - spectrum multitaper per window (mne psd_array_multitaper, half-bandwidth 1 Hz on - 2 s = 3 DPSS tapers), mean over windows, mean over the region's electrodes + spectrum multitaper per demeaned window: 3 DPSS tapers, NW = 2 (scipy.signal.windows.dpss), + equal weights, one-sided µV²/Hz (as espectro.multitaper); mean over windows, + mean over the region's electrodes. (MNE's psd_array_multitaper weights the + tapers by eigenvalue and does not remove the mean: on 2 s windows fitted from + 2.5 Hz the DC leaks into the fit range.) fit FOOOF 1.1 (fooof) over 2.5-50 Hz, fixed aperiodic mode, with Wilkinson 2024's two modifications (shifted robust aperiodic fit at the 10th percentile; residual below the aperiodic floor set to zero before the @@ -71,6 +74,19 @@ def wilkinson_fooof(**kw): return FOOOFWilkinson(**kw) +def multitaper(segs, fs, k=3): + """Mean multitaper spectrum over windows. segs: (windows, channels, samples) in µV. + k DPSS tapers with NW = (k + 1) / 2, equal weights, one-sided, µV²/Hz.""" + from scipy.fft import rfft, rfftfreq + from scipy.signal.windows import dpss + n = segs.shape[-1] + tapers = dpss(n, NW=(k + 1) / 2, Kmax=k) # k x n + x = segs - segs.mean(axis=-1, keepdims=True) + S = (np.abs(rfft(tapers[None, None] * x[:, :, None], axis=-1)) ** 2).mean(axis=2) / fs + S[..., 1:-1] *= 2 + return rfftfreq(n, 1 / fs), S.mean(axis=0) + + def exponent(f, spectrum) -> float: if spectrum is None or not np.all(np.isfinite(spectrum)) or np.any(spectrum <= 0): return float("nan") @@ -108,7 +124,6 @@ class Aperiodic: return r def measure(self, study) -> dict: - from mne.time_frequency import psd_array_multitaper reg = self._reg(study) tabla = _windows2s.table(study, self.variant, P["ventanas.duracion_s"], P["ventanas.borde_s"]) n = int(round(P["ventanas.duracion_s"] * reg.fs)) @@ -118,9 +133,7 @@ class Aperiodic: segs = [reg.datos[i:i + n].T for i in sel.i0 if np.isfinite(reg.datos[i:i + n]).all()] if len(sel) < P["ventanas.min_ventanas"] or not segs: continue - Pw, f = psd_array_multitaper(np.stack(segs), reg.fs, bandwidth=2.0, adaptive=False, low_bias=True, - normalization="full", verbose="error") - Pm = Pw.mean(axis=0) # channels x freqs + f, Pm = multitaper(np.stack(segs), reg.fs, int(P["espectro.tapers"])) # channels x freqs regions = {**{r: [reg.canales.index(c) for c in cs if c in reg.canales] for r, cs in P["regiones"].items()}, "todo": list(range(len(reg.canales)))} for r, idx in regions.items(): diff --git a/src/tea_modulo/biomarkers/coupling/_signal.py b/src/tea_modulo/biomarkers/coupling/_signal.py index 8acc92d..c207990 100644 --- a/src/tea_modulo/biomarkers/coupling/_signal.py +++ b/src/tea_modulo/biomarkers/coupling/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/src/tea_modulo/biomarkers/gradient/api.py b/src/tea_modulo/biomarkers/gradient/api.py index 9804fa9..0ffde16 100644 --- a/src/tea_modulo/biomarkers/gradient/api.py +++ b/src/tea_modulo/biomarkers/gradient/api.py @@ -3,7 +3,7 @@ Modern gradient (gradiente.analizar's definitions on MNE/SciPy): windows 4 s windows of each state ('sueno', 'somnolencia'), gap-free, at least 15 power per channel and band, the median over windows of the band power of a - Hann periodogram (mne psd_array_welch, one segment per window) + Hann periodogram of each demeaned window (symmetric Hann, scipy; as the director) slope Theil-Sen slope (scipy.stats.theilslopes) of log10 power against the electrode's front-back coordinate (the director's 2D positions, +1 frontal) @@ -31,8 +31,19 @@ MIN_WINDOWS = 15 FEATURES = tuple(f"gradient_{b}_{s}" for s in STATES for b in BANDS) +def band_powers(segs, fs, bands): + """Band power per window and channel: |rfft|² of the demeaned window under a symmetric + Hann taper (scipy.signal.windows.hann(sym=True), as gradiente.potencias' np.hanning), + summed over the band's bins. segs: (windows, channels, samples).""" + from scipy.fft import rfft, rfftfreq + from scipy.signal.windows import hann + n = segs.shape[-1] + f = rfftfreq(n, 1.0 / fs) + S = np.abs(rfft((segs - segs.mean(axis=-1, keepdims=True)) * hann(n, sym=True), axis=-1)) ** 2 + return {b: S[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in bands.items()} + + def slopes(raw, starts, window_s=4.0) -> dict: - from mne.time_frequency import psd_array_welch from scipy.stats import theilslopes out = {b: np.nan for b in BANDS} @@ -48,10 +59,10 @@ def slopes(raw, starts, window_s=4.0) -> dict: if a + n <= len(x) and np.isfinite(x[a:a + n]).all()] if not segs: return out - P, f = psd_array_welch(np.stack(segs), fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") + powers = band_powers(np.stack(segs), fs, BANDS) y = np.array([POS_Y[c] for c in chans]) - for b, (lo, hi) in BANDS.items(): - pw = np.median(P[..., (f >= lo) & (f < hi)].sum(axis=-1), axis=0) + for b in BANDS: + pw = np.median(powers[b], axis=0) v = np.log10(np.maximum(pw, 1e-30)) ok = np.isfinite(v) if ok.sum() >= 6: diff --git a/src/tea_modulo/biomarkers/spikes/_signal.py b/src/tea_modulo/biomarkers/spikes/_signal.py index 84f7f02..bc4fb5f 100644 --- a/src/tea_modulo/biomarkers/spikes/_signal.py +++ b/src/tea_modulo/biomarkers/spikes/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/src/tea_modulo/biomarkers/spindle_topography/_signal.py b/src/tea_modulo/biomarkers/spindle_topography/_signal.py index 8acc92d..c207990 100644 --- a/src/tea_modulo/biomarkers/spindle_topography/_signal.py +++ b/src/tea_modulo/biomarkers/spindle_topography/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/src/tea_modulo/preprocessing/_signal.py b/src/tea_modulo/preprocessing/_signal.py index 1848ab5..d776122 100644 --- a/src/tea_modulo/preprocessing/_signal.py +++ b/src/tea_modulo/preprocessing/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/src/tea_modulo/preprocessing/api.py b/src/tea_modulo/preprocessing/api.py index 7391c03..614e321 100644 --- a/src/tea_modulo/preprocessing/api.py +++ b/src/tea_modulo/preprocessing/api.py @@ -4,10 +4,11 @@ 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. + kept scalp channels; or ZapLine, meegkit) -> per variant: one Butterworth band-pass + (order 4, zero phase: scipy sosfiltfilt, as eeg_io.pasa_banda) on each gap-free run + -> reference (nanmean of the kept scalp channels, or of the linked ears A1+A2). + EOG / ECG are filtered and never re-referenced. Gaps (BAD_ACQ_SKIP) stay NaN in + every variant, as in the director's npz: modules see a gap as NaN, never as 0 µV. 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 @@ -17,6 +18,7 @@ windows that are not clean. from __future__ import annotations import json +import warnings from collections.abc import Mapping from typing import Any @@ -28,7 +30,6 @@ from tea_modulo.contracts import CONTRACT_VERSION, Preprocessed, ValidationSumma 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"} @@ -89,22 +90,34 @@ class Preprocessing: 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 + # variants as the director builds them: one Butterworth band-pass per gap-free run + # (NaN stays NaN), then the reference with nanmean, so a gap is still a gap (NaN) in + # every variant and no module filters across it lp = p.step("lowpass").params["hz"] if p.step("lowpass") else None - iir = {"order": 4, "ftype": "butter"} + idx_ears = [keep.index(c) for c in ears] + others = [i for i, c in enumerate(keep) if c not in ears] + aux_idx = [i for i in others if i not in idx_scalp] + base_raw = raw.copy().drop_channels(ears) 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") + y = _signal.bandpass(x, fs, v.highpass_hz, lp) + cue = y[:, idx_scalp] + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) # nanmean of a gap row + if v.reference == "linked_ears": + if len(ears) != 2: + raise ValueError(f"variant {v.name}: linked ears need both A1 and A2 usable") + ref = np.nanmean(y[:, idx_ears], axis=1, keepdims=True) + else: + ref = np.nanmean(cue, axis=1, keepdims=True) + out = np.empty((len(y), len(others))) + pos = {i: k for k, i in enumerate(others)} + out[:, [pos[i] for i in idx_scalp]] = cue - ref + if aux_idx: + out[:, [pos[i] for i in aux_idx]] = y[:, aux_idx] # EOG/EKG: not re-referenced + r = base_raw.copy() + r._data = out.T * 1e-6 variants[v.name] = r # window QC (4 s back-to-back) on the kept scalp channels, notch + 0.5-45 Hz diff --git a/src/tea_modulo/processes/slow_wave_staging/_signal.py b/src/tea_modulo/processes/slow_wave_staging/_signal.py index ead1b61..d34b3a1 100644 --- a/src/tea_modulo/processes/slow_wave_staging/_signal.py +++ b/src/tea_modulo/processes/slow_wave_staging/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/src/tea_modulo/processes/spindle_detection/_signal.py b/src/tea_modulo/processes/spindle_detection/_signal.py index 8acc92d..c207990 100644 --- a/src/tea_modulo/processes/spindle_detection/_signal.py +++ b/src/tea_modulo/processes/spindle_detection/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/src/tea_modulo/processes/window_selection/_signal.py b/src/tea_modulo/processes/window_selection/_signal.py index 84f7f02..bc4fb5f 100644 --- a/src/tea_modulo/processes/window_selection/_signal.py +++ b/src/tea_modulo/processes/window_selection/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/src/tea_modulo/validation/_signal.py b/src/tea_modulo/validation/_signal.py index 385d75c..f125324 100644 --- a/src/tea_modulo/validation/_signal.py +++ b/src/tea_modulo/validation/_signal.py @@ -28,14 +28,23 @@ def by_runs(x, fn, minimum: int): 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))) + """Butterworth, zero phase, run by run: scipy.signal.butter + sosfiltfilt with SciPy's + default edge padding, as the director's eeg_io.pasa_banda. (MNE's IIR filter gives the + same output inside each run but pads the edges differently: up to tens of µV in the + first and last seconds, enough to move a 75 µV slow-wave threshold. Neither is closer + to the true signal there, so the reference wins.)""" + from scipy import signal + ny = fs / 2 + if lo and hi: + sos = signal.butter(order, [lo / ny, hi / ny], btype="band", output="sos") + elif lo: + sos = signal.butter(order, lo / ny, btype="high", output="sos") + elif hi: + sos = signal.butter(order, hi / ny, btype="low", output="sos") + else: + raise ValueError("give lo, hi or both") + return by_runs(x, lambda seg: signal.sosfiltfilt(sos, seg, axis=0), + minimum=max(3 * (sos.shape[0] * 2 + 1), int(fs))) def notch_interpolated(x, fs, f0=60.0, width=1.5, harmonics=True): diff --git a/tests/test_modern_precision.py b/tests/test_modern_precision.py new file mode 100644 index 0000000..df598a0 --- /dev/null +++ b/tests/test_modern_precision.py @@ -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 diff --git a/tests/test_preprocessing.py b/tests/test_preprocessing.py index 74c0215..ff60a5c 100644 --- a/tests/test_preprocessing.py +++ b/tests/test_preprocessing.py @@ -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):