F2b: No evaluable carries the reason ported from the tea library
Study level: Validation.reasons, built from the three gates that decide validity (triage-not-analyzable, few-clean-minutes, few-electrodes; the library's run_study reasons plus its usable-electrode gate) and invalid-file for an unreadable file. Analysis.reasons sits next to valid, level and clean_fraction. Window level: the spike detector's 2 s gate now records every reason a window is rejected (gap, state, mixed-states, muscle, frozen) and the minutes rejected by each, kept in Spikes.rejected. A window can count under more than one reason, as in the library. The platform has no transient rejection, so there is no transient reason. Metric level: biomarkers.measure returns a Measured result with the reason per unmeasured metric: few-wake-windows and no-dominant-peak (posterior rhythm), no-n2 and no-n3 (under one minute of the stage or no events), no-sleep and few-electrodes (gradient, spikes). A study that is not valid now returns its five metrics with no value, each carrying invalid-eeg. Curve scoring returns a reason next to z: no-age, age-out-of-range and no-exposure, because only scoring knows the baseline's age coverage. The reasons and the rejected minutes travel in the features JSON under metric-reasons and rejected-minutes, outside the scenario keys so the reference tables and curve training do not see them.
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
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"), states(prep, ""), [])
|
||||
assert measured.reasons == {
|
||||
"spindles_n2": "no-n2",
|
||||
"spindles_n3": "no-n3",
|
||||
"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"), states(prep, "N2"), [])
|
||||
assert measured.reasons["paroxysmal_spikes"] == "few-electrodes"
|
||||
assert measured.rejected == {}
|
||||
|
||||
|
||||
def test_spindles_without_enough_stage_minutes():
|
||||
prep = prepared()
|
||||
measured = biomarkers.measure(prep, states(prep, "sleep"), states(prep, "N2", 10), [])
|
||||
assert measured.reasons["spindles_n2"] == "no-n2"
|
||||
assert measured.reasons["spindles_n3"] == "no-n3"
|
||||
|
||||
|
||||
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")
|
||||
Reference in New Issue
Block a user