920003c5d4
Assign spike candidates and accepted gate midpoints to the inherited 0.5 s state grid, with a 30 s reach, no state before the first labelled window, and transitions between different surrounding labels. Count useful sleep and awake discharges separately. Export awake_rate, awake_minutes and each zone's electrode count as features without adding metrics or baselines. Train zone count baselines from value times minutes over minutes times present electrodes. Keep observed counts and reported zone rates in their existing units while scaling expected counts by the child's electrodes. Carry the optional electrodes argument through curves.score, deviations, Baseline.predict and saved-study scoring as specified by the coordinator. Internal choices: - Use a private NumPy grid helper, preserve labelled-window input order, and look up times by flooring into half-open 0.5 s cells. Keep the existing internal unlabelled sentinel. Apply the 30 s limit before assigning either an inherited label or transition. - Append the three required fields to Spikes. Use integer zone electrode counts, including zero for absent zones. The few-electrode fallback reports available zone members, zero awake minutes and a NaN awake rate. - Divide rates by accumulated minutes before rounding. Round overall sleep and awake rates to three decimals, minutes to four, and retain four decimals for electrode and zone rates. Missing state exposure produces NaN rates. - Preserve rounded event reconstruction and the existing count-law fit. Missing or null training electrode counts default to one; scoring normalizes nonfinite counts to the same default. Nonpositive electrode exposure yields no-exposure when scoring and is excluded when training. Score centiles remain counts divided by minutes. - Use invented intervals, counts and deterministic candidate fixtures; keep the quality gate, candidate extraction and merging rules unchanged. Validation from the worktree root using the shared virtualenv, with local package roots on PYTHONPATH: - ruff check models: passed. - ruff format --check models: passed, 56 files. - ruff format --check: passed, 152 files. - lint-imports: passed, both contracts kept. - pytest test_eeg_spikes, test_curves, test_eeg, test_eeg_reasons, test_eeg_spindles and test_tea_job: 46 passed; run under flock /home/milk/tea-parity/heavy.lock nice -n 10. - git diff --check: passed. Whole-repository ruff check also ran and found the pre-existing E501 at tests/test_dbt_tea_follow_up.py:35, confirmed in HEAD. That file is outside this task's allowed scope and is unchanged.
128 lines
5.1 KiB
Python
128 lines
5.1 KiB
Python
import numpy as np
|
|
import pytest
|
|
|
|
from models.tea.eeg import biomarkers, spikes
|
|
from models.tea.eeg.preprocess import Prepared
|
|
|
|
|
|
def test_inheritance_reaches_thirty_seconds_from_the_last_labelled_grid_point():
|
|
grid = spikes._states([(10.0, 14.0, "sleep")], 50.0)
|
|
assert (grid[:20] == "unlabelled").all()
|
|
assert (grid[20:88] == "sleep").all()
|
|
assert (grid[88:] == "unlabelled").all()
|
|
assert grid[87] == "sleep"
|
|
assert grid[88] == "unlabelled"
|
|
|
|
|
|
def test_transition_between_different_labels_counts_in_neither_state():
|
|
grid = spikes._states([(2.0, 6.0, "wake"), (12.0, 16.0, "sleep")], 18.0)
|
|
assert (grid[:4] == "unlabelled").all()
|
|
assert (grid[4:12] == "wake").all()
|
|
assert (grid[12:24] == "transition").all()
|
|
assert (grid[24:] == "sleep").all()
|
|
|
|
|
|
def test_matching_labels_inherit_from_either_side_with_no_state_beyond_reach():
|
|
grid = spikes._states([(0.0, 4.0, "sleep"), (80.0, 84.0, "sleep")], 85.0)
|
|
assert grid[67] == "sleep"
|
|
assert (grid[68:100] == "unlabelled").all()
|
|
assert grid[100] == "sleep"
|
|
|
|
|
|
def test_direct_windows_keep_the_first_label_and_empty_windows_have_no_state():
|
|
grid = spikes._states([(4.0, 8.0, "wake"), (6.0, 10.0, "sleep")], 12.0)
|
|
assert (grid[8:16] == "wake").all()
|
|
assert (grid[16:] == "sleep").all()
|
|
assert (spikes._states([], 12.0) == "unlabelled").all()
|
|
assert spikes._states([], 0.0).size == 0
|
|
|
|
|
|
def prepared(starts, seconds=90, names=("C3", "Cz", "P3", "P4")):
|
|
return Prepared(np.zeros((seconds * 128, len(names))), names, 128, np.array(starts), (), ())
|
|
|
|
|
|
def test_gate_minutes_and_candidates_use_the_grid_state(monkeypatch):
|
|
prep = prepared([10.0, 30.0, 50.0])
|
|
gate = [(float(t), float(t + 2)) for t in range(0, 90, 2)]
|
|
monkeypatch.setattr(spikes, "_gate", lambda *args: (gate, {}))
|
|
|
|
def candidates(x, fs, channel):
|
|
return [
|
|
dict(
|
|
channel=channel,
|
|
t=t,
|
|
sign=1,
|
|
width=50.0,
|
|
size=5.0 if channel == "C3" else 4.0,
|
|
post=0.0,
|
|
)
|
|
for t in (9.5, 10.1, 20.1, 30.1, 40.1, 50.1, 60.1, 83.75, 84.1)
|
|
if channel in ("C3", "Cz")
|
|
]
|
|
|
|
monkeypatch.setattr(spikes, "_candidates", candidates)
|
|
found = spikes.detect(prep, np.array(["wake", "drowsy", "sleep"]), [])
|
|
assert found.minutes == pytest.approx(34 / 60, abs=1e-4)
|
|
assert found.awake_minutes == pytest.approx(8 / 60, abs=1e-4)
|
|
assert found.rate == pytest.approx(round(3 / (34 / 60), 3))
|
|
assert found.awake_rate == 15.0
|
|
assert found.electrodes["C3"] == pytest.approx(round(3 / (34 / 60), 4))
|
|
assert found.zones["central"] == found.electrodes["C3"]
|
|
assert found.zone_electrodes["central"] == 2
|
|
assert found.zone_electrodes["frontal_left"] == 0
|
|
|
|
|
|
def test_gate_minutes_follow_the_midpoint_even_when_a_window_crosses_labels(monkeypatch):
|
|
prep = prepared([1.5], seconds=8)
|
|
monkeypatch.setattr(spikes, "_gate", lambda *args: ([(0.0, 2.0), (2.0, 4.0)], {}))
|
|
monkeypatch.setattr(spikes, "_candidates", lambda *args: [])
|
|
found = spikes.detect(prep, np.array(["sleep"]), [])
|
|
assert found.minutes == pytest.approx(2 / 60, abs=1e-4)
|
|
assert found.rate == 0.0
|
|
assert found.awake_minutes == 0.0
|
|
assert np.isnan(found.awake_rate)
|
|
|
|
|
|
@pytest.mark.parametrize("state", ["wake", "drowsy"])
|
|
def test_awake_rates_include_direct_and_inherited_discharges(monkeypatch, state):
|
|
prep = prepared([0.0], seconds=8)
|
|
monkeypatch.setattr(
|
|
spikes, "_gate", lambda *args: ([(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)], {})
|
|
)
|
|
|
|
def candidates(x, fs, channel):
|
|
return [
|
|
dict(channel=channel, t=t, sign=1, width=50.0, size=5.0, post=0.0)
|
|
for t in (1.0, 7.0)
|
|
if channel in ("C3", "Cz")
|
|
]
|
|
|
|
monkeypatch.setattr(spikes, "_candidates", candidates)
|
|
found = spikes.detect(prep, np.array([state]), [])
|
|
assert found.awake_minutes == pytest.approx(8 / 60, abs=1e-4)
|
|
assert found.awake_rate == 15.0
|
|
assert found.minutes == 0.0
|
|
assert np.isnan(found.rate)
|
|
|
|
|
|
def test_biomarker_features_include_awake_rates_and_present_zone_electrodes(monkeypatch):
|
|
prep = prepared([0.0], seconds=8)
|
|
monkeypatch.setattr(spikes, "_gate", lambda *args: ([(0.0, 2.0)], {}))
|
|
monkeypatch.setattr(spikes, "_candidates", lambda *args: [])
|
|
measured = biomarkers.measure(prep, np.array(["wake"]), [])
|
|
features = measured.features["eeg-spikes"]
|
|
assert features["awake_rate"] == 0.0
|
|
assert features["awake_minutes"] == pytest.approx(2 / 60, abs=1e-4)
|
|
assert features["zone_electrodes_central"] == 2
|
|
assert features["zone_electrodes_parietal"] == 2
|
|
assert set(measured.metrics) == set(biomarkers.CODES)
|
|
|
|
|
|
def test_few_electrodes_still_reports_present_zone_electrodes():
|
|
prep = prepared([0.0], seconds=8, names=("C3", "Cz"))
|
|
measured = biomarkers.measure(prep, np.array(["sleep"]), [])
|
|
assert measured.reasons["paroxysmal_spikes"] == "few-electrodes"
|
|
assert measured.features["eeg-spikes"]["zone_electrodes_central"] == 2
|
|
assert measured.features["eeg-spikes"]["awake_minutes"] == 0.0
|
|
assert np.isnan(measured.features["eeg-spikes"]["awake_rate"])
|