diff --git a/models/tea/eeg/analysis.py b/models/tea/eeg/analysis.py index f4cd34e..b2b4e1a 100644 --- a/models/tea/eeg/analysis.py +++ b/models/tea/eeg/analysis.py @@ -63,6 +63,7 @@ def analyze( *, age_months: float | None = None, mains_hz: float = MAINS_HZ, + keep_flat=False, ) -> Analysis: out = dict( valid=None, @@ -114,10 +115,11 @@ def analyze( ) if not verdict.valid: return _result(out, biomarkers.invalid()) - prep = preprocess.prepare(rec, verdict.bad) + prep = preprocess.prepare(rec, verdict.bad, mains_hz, keep_flat=keep_flat) notes = sleep.note_intervals(prep.annotations, prep.duration_s) states = sleep.states(prep, notes, age) measured = biomarkers.measure(prep, states, notes) + measured.rejected["start_s"] = preprocess.stable_start(rec) return _result(out, measured, sleep=bool((states == "sleep").any())) except Exception as exc: # noqa: BLE001 return Analysis(**out | dict(error=_error(exc))) diff --git a/models/tea/eeg/checks.py b/models/tea/eeg/checks.py index 87a16d9..684a5d3 100644 --- a/models/tea/eeg/checks.py +++ b/models/tea/eeg/checks.py @@ -204,9 +204,11 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s return {name: found for name, found in reasons.items() if found} -def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]: +def window_qc(y: np.ndarray, fs: float, start_s=0.0) -> list[tuple[float, float, str]]: n = int(4 * fs) - lines = signals.fixed_lines(y, fs, f_max=44.0) + start = int(start_s * fs) + after_start = y[start:] if len(y) - start > 30 * fs else y + lines = signals.fixed_lines(after_start, fs, f_max=44.0) starts = list(range(0, len(y) - n + 1, n)) segments = [y[a : a + n] for a in starts] whole = [bool(np.isfinite(s).all()) for s in segments] diff --git a/models/tea/eeg/preprocess.py b/models/tea/eeg/preprocess.py index c3dac42..51eb4b1 100644 --- a/models/tea/eeg/preprocess.py +++ b/models/tea/eeg/preprocess.py @@ -1,16 +1,26 @@ +import unicodedata import warnings from dataclasses import dataclass import numpy as np +from scipy import signal from models.tea.eeg import signals from models.tea.eeg.checks import window_qc from models.tea.eeg.read import Recording -NOTCH_HZ = 60.0 NOTCH_MIN_DB = 6.0 WINDOW_S = 4.0 STEP_S = 2.0 +_START_MARKS = ( + "start record", + "inicio", + "comienzo", + "begin record", + "recording on", + "start of record", +) +_SETUP_MARKS = ("impedanc", "montaje", "montage", "electrod", "calibrac", "colocac", "prueba") @dataclass(frozen=True) @@ -33,21 +43,67 @@ class Prepared: return self.x[:, [self.names.index(name) for name in names]] -def prepare(rec: Recording, bad) -> Prepared: - scalp = [name for name in rec.of("eeg") if name not in bad] +def stable_start(rec: Recording) -> float: + x = rec.x[:, [rec.names.index(name) for name in rec.of("eeg")]] + n = int(10 * rec.fs) + rms = np.array( + [ + np.median(np.std(x[a : a + n], axis=0)) if np.isfinite(x[a : a + n]).all() else np.nan + for a in range(0, len(x) - n + 1, n) + ] + ) + finite = np.isfinite(rms) + if finite.sum() < 12: + return 0.0 + limit = 2.0 * np.median(rms[finite][finite.sum() // 2 :]) + start = 0.0 + for i in range(len(rms)): + if not np.isfinite(rms[i]): + continue + rest = rms[i:][np.isfinite(rms[i:])] + if len(rest) >= 6 and np.mean(rest <= limit) >= 0.9: + start = i * n / rec.fs + break + mark = None + for onset, _, text in sorted(rec.annotations, key=lambda a: a[0]): + plain = "".join( + c for c in unicodedata.normalize("NFD", str(text)) if unicodedata.category(c) != "Mn" + ).lower() + if any(m in plain for m in _START_MARKS): + mark = onset + break + if any(m in plain for m in _SETUP_MARKS): + mark = onset + return float(mark) if mark is not None and mark >= start else start + + +def _iir_notch(x: np.ndarray, fs: float, mains_hz: float) -> np.ndarray: + frequencies = [mains_hz] + [k * mains_hz for k in range(2, 100) if k * mains_hz < fs / 2 * 0.98] + sos = np.vstack([np.hstack(signal.iirnotch(f, 30.0, fs)).reshape(1, 6) for f in frequencies]) + minimum = max(3 * (len(sos) * 2 + 1), int(fs)) + return signals.by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum) + + +def prepare(rec: Recording, bad, mains_hz: float, keep_flat=False) -> Prepared: + flat = [name for name in rec.of("eeg") if not np.nanstd(rec.x[:, rec.names.index(name)]) > 0.5] + keep = flat if keep_flat and len(flat) == 1 else [] + scalp = [name for name in rec.of("eeg") if name not in bad or name in keep] x = rec.x[:, [rec.names.index(name) for name in scalp]] - if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB: - x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5) - gaps = ~np.isfinite(x).all(axis=1) + if np.nanmedian(signals.line_db(x, rec.fs, mains_hz)) >= NOTCH_MIN_DB: + x = signals.notch(x, rec.fs, mains_hz, width=1.5) y = signals.bandpass(x, rec.fs, 0.5, 100.0) with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) referenced = y - np.nanmean(y, axis=1, keepdims=True) referenced = np.asfortranarray(referenced * 1e-6 * 1e6) - qc = signals.bandpass(x, rec.fs, 0.5, 45.0) - qc[gaps] = np.nan + qc_names = [name for name in scalp if name not in keep] + raw_qc = rec.x[:, [rec.names.index(name) for name in qc_names]] + qc = signals.bandpass(_iir_notch(raw_qc, rec.fs, mains_hz), rec.fs, 0.5, 45.0) + start_s = stable_start(rec) unclean = tuple( - (float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean" + (float(t0), float(t1) - float(t0)) + for t0, t1, v in window_qc(qc, rec.fs, start_s) + if v != "clean" or t0 < start_s ) starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S) return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations) diff --git a/models/tea/eeg/reference.py b/models/tea/eeg/reference.py index 396a7fb..3ebade4 100644 --- a/models/tea/eeg/reference.py +++ b/models/tea/eeg/reference.py @@ -22,7 +22,7 @@ def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, def _one(study: tuple[str, Path, float, float]) -> dict: key, path, age, mains_hz = study - a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz) + a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz, keep_flat=True) return { "key": key, "age_months": age, diff --git a/models/tea/eeg/signals.py b/models/tea/eeg/signals.py index 587c854..34179f8 100644 --- a/models/tea/eeg/signals.py +++ b/models/tea/eeg/signals.py @@ -1,5 +1,4 @@ import numpy as np -from mne.time_frequency import psd_array_welch from scipy import signal from scipy.ndimage import median_filter @@ -66,8 +65,11 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray: def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]: n = segments.shape[-1] - power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error") - return f, power + window = np.hanning(n) + y = (segments - segments.mean(axis=-1, keepdims=True)) * window + power = np.abs(np.fft.rfft(y, axis=-1)) ** 2 / (fs * (window**2).sum()) + power[..., 1 : -1 if n % 2 == 0 else None] *= 2 + return np.fft.rfftfreq(n, 1 / fs), power def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]: diff --git a/models/tea/eeg/sleep.py b/models/tea/eeg/sleep.py index fd1338c..583e255 100644 --- a/models/tea/eeg/sleep.py +++ b/models/tea/eeg/sleep.py @@ -143,6 +143,7 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str, if not starts: return [], {} f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs) + power *= fs * (np.hanning(n) ** 2).sum() / 2 band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()} total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12) central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names)))) diff --git a/tests/test_eeg.py b/tests/test_eeg.py index f58ac19..0663aaf 100644 --- a/tests/test_eeg.py +++ b/tests/test_eeg.py @@ -1,8 +1,23 @@ +from dataclasses import replace +from types import SimpleNamespace + import numpy as np import pandas as pd import pytest +from scipy import signal -from models.tea.eeg import curves, signals +from core.tea.reasons import REJECTED_MINUTES +from models.tea.eeg import ( + analysis, + biomarkers, + checks, + curves, + preprocess, + reference, + signals, + sleep, +) +from models.tea.eeg.read import Recording def test_score_without_value_or_coverage(): @@ -26,3 +41,184 @@ def test_band_power_excludes_line_noise_and_rescales_clean_bins(): frequencies = np.arange(7.0, 14.0) power = np.array([100.0, 2.0, 30.0, 40.0, 30.0, 4.0, 100.0]) assert signals.band_power(frequencies, power, 8, 13, lines=(10,)) == 15 + + +def _recording(seconds=180, fs=256): + names = ("C3", "Cz", "C4", "O1") + x = np.random.default_rng(7).normal(0, 10, (seconds * fs, len(names))) + return Recording(x, fs, names, (), None, None) + + +@pytest.mark.parametrize(("flat_count", "keep_flat"), [(1, False), (1, True), (2, True)]) +def test_prepare_keeps_only_one_flat_channel_when_requested(monkeypatch, flat_count, keep_flat): + rec = _recording(seconds=20) + rec.x[:, 1 : flat_count + 1] = 0 + bad = dict.fromkeys(rec.names[1 : flat_count + 1]) + seen = [] + + def qc(y, fs, start_s): + seen.append(y) + return [] + + monkeypatch.setattr(preprocess, "window_qc", qc) + prep = preprocess.prepare(rec, bad, 60, keep_flat=keep_flat) + kept = keep_flat and flat_count == 1 + names = rec.names if kept else tuple(name for name in rec.names if name not in bad) + assert prep.names == names + assert seen[0].shape[1] == len(rec.names) - flat_count + raw = rec.x[:, [rec.names.index(name) for name in names]] + filtered = signals.bandpass(raw, rec.fs, 0.5, 100) + np.testing.assert_allclose(prep.x, filtered - filtered.mean(axis=1, keepdims=True)) + if kept: + assert np.std(prep.data(["Cz"])) > 0.5 + + +@pytest.mark.parametrize("n", [255, 256]) +def test_periodograms_match_symmetric_hann_density(n): + fs = 256 + segments = np.random.default_rng(1).normal(3, 2, (2, 3, n)) + window = np.hanning(n) + transformed = np.fft.rfft((segments - segments.mean(axis=-1, keepdims=True)) * window) + expected = np.abs(transformed) ** 2 / (fs * np.sum(window**2)) + for k in range(1, expected.shape[-1]): + if 2 * k != n: + expected[..., k] *= 2 + frequencies, power = signals.periodograms(segments, fs) + np.testing.assert_array_equal(frequencies, np.fft.rfftfreq(n, 1 / fs)) + np.testing.assert_allclose(power, expected, rtol=1e-14) + + +def test_prepare_uses_50_hz_mains_and_raw_iir_qc(monkeypatch): + rec = _recording(seconds=40) + t = np.arange(len(rec.x)) / rec.fs + rec.x[:] += np.sin(2 * np.pi * 50 * t)[:, None] * np.array([100, 40, 20, 10]) + rec.x[:, 0] += 100 * np.sin(2 * np.pi * 60 * t) + rec.x[:, 0] += 100 * np.sin(2 * np.pi * 100 * t) + seen = [] + + def qc(y, fs, start_s): + seen.append(y) + return [] + + monkeypatch.setattr(preprocess, "window_qc", qc) + prep = preprocess.prepare(rec, {}, 50) + f = np.fft.rfftfreq(len(t), 1 / rec.fs) + before = np.abs(np.fft.rfft(rec.x[:, 0])) + after = np.abs(np.fft.rfft(prep.x[:, 0])) + assert after[f == 50] < before[f == 50] * 0.01 + assert after[f == 60] > before[f == 60] * 0.5 + sos = np.vstack([np.r_[signal.iirnotch(hz, 30, rec.fs)] for hz in (50, 100)]) + expected = signal.sosfiltfilt(sos, rec.x, axis=0) + expected = signals.bandpass(expected, rec.fs, 0.5, 45) + np.testing.assert_allclose(seen[0], expected) + + +def test_stable_start_finds_a_noisy_setup_prefix(): + rec = _recording() + rec.x[: 60 * rec.fs] *= 20 + assert preprocess.stable_start(rec) == 50.0 + + +def test_stable_start_returns_zero_for_a_clean_record(): + assert preprocess.stable_start(_recording()) == 0.0 + + +@pytest.mark.parametrize( + ("annotations", "expected"), + [ + (((75.0, 0.0, "INÍCIO"),), 75.0), + (((30.0, 0.0, "electrodos"), (65.0, 0.0, "impedancias")), 65.0), + (((90.0, 0.0, "montaje"), (55.0, 0.0, "start recording")), 55.0), + (((20.0, 0.0, "inicio"),), 50.0), + ], +) +def test_stable_start_honours_annotations_and_keeps_the_later_start(annotations, expected): + rec = _recording() + rec.x[: 60 * rec.fs] *= 20 + assert preprocess.stable_start(replace(rec, annotations=annotations)) == expected + + +def test_stable_start_returns_zero_with_fewer_than_twelve_finite_windows(): + rec = _recording(seconds=120) + rec.x[: 10 * rec.fs] = np.nan + rec = replace(rec, annotations=((80.0, 0.0, "inicio"),)) + assert preprocess.stable_start(rec) == 0.0 + + +def test_prepare_marks_every_qc_window_before_start_unclean_and_masks_states(): + rec = replace(_recording(), annotations=((45.0, 0.0, "inicio"),)) + rec = replace(rec, x=signals.bandpass(rec.x, rec.fs, 0.5, 20)) + prep = preprocess.prepare(rec, {}, 60) + assert {(float(t), 4.0) for t in range(0, 45, 4)} <= set(prep.unclean) + labels = sleep.states(prep, [], 24) + assert (labels[prep.starts < 45] == "").all() + assert (labels[prep.starts >= 48] != "").any() + + +@pytest.mark.parametrize(("seconds", "start_s", "offset_s"), [(80, 20, 20), (50, 20, 0)]) +def test_window_qc_finds_fixed_lines_after_start_when_over_thirty_seconds_remain( + monkeypatch, seconds, start_s, offset_s +): + rec = _recording(seconds=seconds) + seen = [] + + def fixed_lines(y, fs, f_max): + seen.append(y) + return [] + + monkeypatch.setattr(signals, "fixed_lines", fixed_lines) + checks.window_qc(rec.x, rec.fs, start_s) + np.testing.assert_array_equal(seen[0], rec.x[offset_s * rec.fs :]) + + +def test_sleep_features_apply_clamps_to_unscaled_fft_power(): + rec = _recording(seconds=4) + rec.x[:] *= 1e-9 + prep = preprocess.Prepared(rec.x, rec.names, rec.fs, np.array([0.0]), (), ()) + starts, features = sleep._features(prep, np.zeros(len(rec.x), bool)) + x = rec.x.T + f = np.fft.rfftfreq(len(x.T), 1 / rec.fs) + power = np.abs(np.fft.rfft((x - x.mean(axis=-1, keepdims=True)) * np.hanning(len(x.T)))) ** 2 + band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in sleep.BANDS.items()} + ratio = np.median(band["delta"] / np.maximum(band["beta"], 1e-12)) + assert starts == [0] + np.testing.assert_allclose(features["delta_beta"], [np.log10(max(ratio, 1e-6))]) + + +@pytest.mark.parametrize("keep_flat", [False, True]) +def test_analysis_passes_mains_and_flat_option_and_reports_start(monkeypatch, keep_flat): + rec = replace(_recording(), annotations=((42.0, 0.0, "inicio"),)) + monkeypatch.setattr(analysis.read, "read", lambda _: rec) + verdict = SimpleNamespace( + valid=True, level="complete", reasons=[], clean_pct=100, bad={}, line_db=0, checks=[] + ) + monkeypatch.setattr(checks, "validate", lambda rec, mains_hz: verdict) + prepare = preprocess.prepare + seen = [] + + def prepared(rec, bad, mains_hz, keep_flat=False): + seen.append((mains_hz, keep_flat)) + return prepare(rec, bad, mains_hz, keep_flat=keep_flat) + + monkeypatch.setattr(preprocess, "prepare", prepared) + monkeypatch.setattr(biomarkers, "measure", lambda *args: biomarkers.Measured({}, {}, {}, {})) + options = {"keep_flat": True} if keep_flat else {} + found = analysis.analyze(b"synthetic", age_months=24, mains_hz=50, **options) + assert found.error is None + assert seen == [(50, keep_flat)] + assert found.features[REJECTED_MINUTES]["start_s"] == 42.0 + + +def test_reference_enables_flat_reference_electrode(monkeypatch, tmp_path): + path = tmp_path / "synthetic.edf" + path.write_bytes(b"synthetic") + seen = [] + + def analyze(edf, **options): + seen.append((edf, options)) + return SimpleNamespace(valid=True, error=None, features={}) + + monkeypatch.setattr(reference, "analyze", analyze) + result = reference._one(("study", path, 24, 50)) + assert result["valid"] is True + assert seen == [(b"synthetic", {"age_months": 24, "mains_hz": 50, "keep_flat": True})]