Files
models/tests/test_curves.py
T
alberto 920003c5d4 F7e: spikes inherit the nearest window state; zone rates by electrodes present
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.
2026-12-03 22:08:43 -06:00

83 lines
3.2 KiB
Python

from types import SimpleNamespace
import numpy as np
import pandas as pd
import pytest
from scipy import stats
from models.tea.eeg import curves
from models.tea.eeg.analysis import Metric
def test_centile_interpolation_preserves_scoring():
baseline = {
"kind": "curves",
"curve": {
"age_months": [16, 36],
"p5": [1, 3],
"p25": [2, 4],
"median": [3, 5],
"p75": [5, 7],
"p95": [7, 9],
},
}
assert curves.centiles(baseline, 24) == pytest.approx(
{"p5": 2, "p25": 3, "median": 4, "p75": 6, "p95": 8}
)
for value, z, outside in ((0, -3.29, -1), (3, -0.8225, 0), (6, 0.8225, 0), (10, 2.4675, 1)):
scored = curves.score(baseline, value, 24)
assert scored.pop("reason") is None
assert scored == pytest.approx(
{"z": z, "outside": outside, "p5": 2, "median": 4, "p95": 8}, rel=1e-9
)
def test_zone_training_uses_counts_over_minutes_times_present_electrodes():
features = pd.DataFrame(
{
"value": [6.0, 9.0],
"electrode_C3": [3.0, 3.0],
"zone_central": [6.0, 9.0],
"minutes": [2.0, 4.0],
"zone_electrodes_central": [2.0, 3.0],
"awake_rate": [1.0, 2.0],
"awake_minutes": [5.0, 6.0],
"age_months": [20.0, 30.0],
}
)
baseline = curves.train(features, "eeg-spikes")
assert set(baseline) == {"value", "electrode_C3", "zone_central"}
assert baseline["zone_central"]["events"] == 48
assert baseline["zone_central"]["rate"] == 3.0
assert baseline["zone_central"]["k"] is None
assert baseline["value"]["rate"] == 8.0
assert baseline["electrode_C3"]["rate"] == 3.0
@pytest.mark.parametrize("electrodes", [None, np.nan, 1.0, 2.0, 3.0])
def test_count_score_scales_expected_counts_by_electrodes(electrodes):
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
scored = curves.score(baseline, 6.0, 24.0, exposure=5.0, electrodes=electrodes)
present = 1.0 if electrodes is None or np.isnan(electrodes) else electrodes
law = stats.poisson(3 * 5 * present)
tail = law.sf(29)
assert scored["reason"] is None
assert scored["z"] == pytest.approx(np.clip(stats.norm.ppf(1 - tail + law.pmf(30) / 2), -8, 8))
assert scored["outside"] == int(tail < 0.05)
for name, q in (("p5", 0.05), ("median", 0.5), ("p95", 0.95)):
assert scored[name] == law.ppf(q) / 5
def test_deviations_use_the_childs_zone_electrodes():
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
model = dict.fromkeys(("value", "electrode_C3", "zone_central"), baseline)
analysis = SimpleNamespace(
age_months=24.0,
metrics=[Metric("paroxysmal_spikes", 6.0, {"C3": 6.0}, {"central": 6.0})],
features={"eeg-spikes": {"minutes": 5.0, "zone_electrodes_central": 2.0}},
)
scored = curves.deviations({"eeg-spikes": model}, analysis)["paroxysmal_spikes"]
assert scored["zones"]["central"] == curves.score(baseline, 6.0, 24.0, 5.0, 2.0)
assert scored["value"] == curves.score(baseline, 6.0, 24.0, 5.0)
assert scored["electrodes"]["C3"] == scored["value"]