Files
models/tests/test_eeg_reasons.py
T
alberto ee9537b1f2 F7c: one spindle metric over all NREM sleep
Spindles are measured once, over every window the state classifier labels
sleep, and each child's detection thresholds come from all NREM sleep
samples. The 75 uV slow-wave rule labelled 89 % of the epochs after N2
onset in Helsinki toddlers (16-36 months) as N3 and was never validated
against technician-scored stages (biomarcadores-tea E13, usar_n3 = false).

spindles_n2 and spindles_n3 become spindles; the four N2/N3 age scenarios
become eeg-spindles and eeg-spindle-topography. The director's flag for a
posterior rhythm near the sigma band is kept as the rhythm_near_sigma
feature. Reasons: no-sleep under one minute of sleep, else no-spindles.
2026-12-03 20:47:28 -06:00

164 lines
6.1 KiB
Python

from dataclasses import replace
import numpy as np
import pandas as pd
import pytest
from edf_files import small_edf
from core.tea.reasons import METRIC_REASONS, REJECTED_MINUTES
from models.tea.eeg import biomarkers, curves, spikes
from models.tea.eeg.analysis import analyze
from models.tea.eeg.preprocess import STEP_S, WINDOW_S, Prepared
from models.tea.eeg.spindles import CHANNELS
FS = 128
SCALP = tuple(biomarkers.FRONT_BACK)
POSTERIOR = ("O1", "O2", "P3", "P4")
def smooth(t: np.ndarray, channels: int, rng) -> np.ndarray:
f = np.arange(0.5, 40.0, 0.25)
phase = rng.uniform(0, 2 * np.pi, (len(f), channels))
wave = np.sin(2 * np.pi * np.outer(t, f)[:, :, None] + phase[None])
return (wave / f[None, :, None]).sum(axis=1) * 100
def prepared(names=SCALP, seconds=70, rhythm=None, seed=0, flat=False) -> Prepared:
rng = np.random.default_rng(seed)
t = np.arange(seconds * FS) / FS
x = smooth(t, len(names), rng) if flat else rng.normal(0, 10, (len(t), len(names)))
for k, name in enumerate(names):
if rhythm and name in POSTERIOR:
x[:, k] += 40 * np.sin(2 * np.pi * rhythm * t)
starts = np.arange(0.0, seconds - WINDOW_S + 1e-9, STEP_S)
return Prepared(np.asfortranarray(x), tuple(names), FS, starts, (), ())
def states(prep: Prepared, state: str, count: int | None = None) -> np.ndarray:
out = np.full(len(prep.starts), "", dtype=object)
out[:count] = state
return out
def test_posterior_rhythm_without_enough_wake_windows():
prep = prepared(rhythm=10.0)
value, reason = biomarkers.posterior_rhythm(prep, states(prep, "wake", 14))
assert np.isnan(value)
assert reason == "few-wake-windows"
def test_posterior_rhythm_without_a_dominant_peak():
prep = prepared(names=("Fp1", "Fp2", "O1", "O2"), flat=True)
value, reason = biomarkers.posterior_rhythm(prep, states(prep, "wake"))
assert np.isnan(value)
assert reason == "no-dominant-peak"
only_frontal = prepared(names=("Fp1", "Fp2", "F3"))
assert biomarkers.posterior_rhythm(only_frontal, states(only_frontal, "wake"))[1] == (
"no-dominant-peak"
)
def test_posterior_rhythm_measured_has_no_reason():
prep = prepared(rhythm=10.0)
value, reason = biomarkers.posterior_rhythm(prep, states(prep, "wake"))
assert value == pytest.approx(10.0, abs=0.5)
assert reason is None
def test_gradient_without_sleep():
prep = prepared()
assert biomarkers.delta_gradient(prep, states(prep, "wake"))[1] == "no-sleep"
assert biomarkers.delta_gradient(prep, states(prep, "sleep", 14))[1] == "no-sleep"
def test_gradient_with_few_electrodes():
prep = prepared(names=("Fp1", "Fp2", "F3", "Fz", "C3"))
value, reason = biomarkers.delta_gradient(prep, states(prep, "sleep"))
assert np.isnan(value)
assert reason == "few-electrodes"
def test_gradient_measured_has_no_reason():
prep = prepared()
value, reason = biomarkers.delta_gradient(prep, states(prep, "sleep"))
assert np.isfinite(value)
assert reason is None
def test_wake_only_recording_has_no_sleep_reasons():
prep = prepared(rhythm=10.0)
measured = biomarkers.measure(prep, states(prep, "wake"), [])
assert measured.reasons == {
"spindles": "no-sleep",
"paroxysmal_spikes": "no-sleep",
"anteroposterior_gradient": "no-sleep",
}
assert set(measured.metrics) == set(biomarkers.CODES)
def test_spikes_with_few_electrodes():
prep = prepared(names=("Fp1", "Fp2", "Cz"))
measured = biomarkers.measure(prep, states(prep, "sleep"), [])
assert measured.reasons["paroxysmal_spikes"] == "few-electrodes"
assert measured.rejected == {}
def test_spindles_without_enough_sleep_minutes():
prep = prepared()
measured = biomarkers.measure(prep, states(prep, "sleep", 10), [])
assert measured.reasons["spindles"] == "no-sleep"
def test_sleep_without_spindles():
prep = prepared()
silent = replace(prep, x=np.zeros_like(prep.x))
measured = biomarkers.measure(silent, states(silent, "sleep"), [])
assert measured.reasons["spindles"] == "no-spindles"
def test_gate_rejects_windows_by_reason_in_minutes():
prep = prepared(names=CHANNELS[:6], seconds=20, flat=True)
x = np.array(prep.x)
x[: 2 * FS] = np.nan
x[2 * FS : 4 * FS] = 1.0
kept, rejected = spikes._gate(x, FS, [(0.0, 20.0, "crying")])
assert kept == []
assert rejected["gap"] == pytest.approx(2 / 60, abs=1e-4)
assert rejected["frozen"] == pytest.approx(2 / 60, abs=1e-4)
assert rejected["state"] == pytest.approx(18 / 60, abs=1e-4)
clean, none = spikes._gate(np.array(prep.x), FS, [(0.0, 20.0, "sleep")])
assert len(clean) == 10
assert none == {}
def test_score_reasons():
table = {"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]}
baseline = curves.train(pd.DataFrame(table), "eeg-gradient")["value"]
assert curves.score(baseline, None, 25.0)["reason"] is None
assert curves.score(baseline, 2.0, None)["reason"] == "no-age"
assert curves.score(baseline, 2.0, 25.0)["reason"] == "age-out-of-range"
rate = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 1.0, "k": None}
assert curves.score(rate, 1.0, 40.0, 5.0)["reason"] == "age-out-of-range"
assert curves.score(rate, 1.0, 20.0, None)["reason"] == "no-exposure"
assert curves.score(rate, 1.0, 20.0, 0.0)["reason"] == "no-exposure"
measured = curves.score(rate, 1.0, 20.0, 5.0)
assert measured["reason"] is None
assert measured["z"] is not None
def test_invalid_study_carries_the_reasons_on_every_metric(tmp_path):
found = analyze(small_edf(tmp_path / "small.edf", seconds=60))
assert found.valid is False
assert "few-electrodes" in found.reasons
assert [m.code for m in found.metrics] == list(biomarkers.CODES)
assert all(m.value is None for m in found.metrics)
assert found.features[METRIC_REASONS] == dict.fromkeys(biomarkers.CODES, "invalid-eeg")
assert found.features[REJECTED_MINUTES] == {}
def test_a_file_that_is_not_an_edf_is_invalid_with_its_reason():
found = analyze(b"not an edf")
assert found.valid is False
assert found.reasons == ["invalid-file"]
assert found.features[METRIC_REASONS] == dict.fromkeys(biomarkers.CODES, "invalid-eeg")