from dataclasses import replace from types import SimpleNamespace import numpy as np import pandas as pd import pytest from scipy import signal 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(): table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]}) baseline = curves.train(table, "eeg-gradient")["value"] empty = dict.fromkeys(("z", "outside", "p5", "median", "p95")) assert curves.score(baseline, None, 25.0) == {**empty, "reason": None} assert curves.score(baseline, 2.0, 25.0) == {**empty, "reason": "age-out-of-range"} def test_dominant_peak_recovers_a_posterior_rhythm_above_background(): frequencies = np.arange(1.0, 46.0, 0.5) background = 1 / frequencies power = background.copy() power[frequencies == 8] *= 10 assert signals.dominant_peak(frequencies, power) == (8.0, pytest.approx(10), True) assert not signals.dominant_peak(frequencies, background)[2] 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})]