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.
This commit is contained in:
2026-12-03 22:08:43 -06:00
parent 8dbd96bca8
commit 920003c5d4
7 changed files with 345 additions and 20 deletions
+53
View File
@@ -1,10 +1,14 @@
from datetime import date
from types import SimpleNamespace
import dagster as dg
import pandas as pd
import pytest
from pydantic import ValidationError
from models.definitions import ScopeConfig, after_ingest
from models.tea import jobs
from models.tea.eeg import curves
from models.tea.jobs import ASSOCIATION, JOBS, MODELS
from persistance import eeg
@@ -80,3 +84,52 @@ def test_tea_eeg_first_n_selects_exactly_n_pending_studies(fresh_platform):
]
with pytest.raises(LookupError, match="has no signal"):
eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-05-01"]))
@pytest.mark.parametrize("electrodes", [None, 2.0])
def test_baseline_predict_accepts_optional_electrode_counts(electrodes):
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
model = jobs.Baseline("eeg-spikes", {"zone_central": baseline})
row = {"value": 6.0, "age_months": 24.0, "exposure": 5.0}
rows = [row, {**row, "electrodes": electrodes}]
scored = model.predict(None, pd.DataFrame(rows), {"feature": "zone_central"})
assert scored.to_dict("records") == [
curves.score(baseline, 6.0, 24.0, 5.0),
curves.score(baseline, 6.0, 24.0, 5.0, electrodes),
]
def test_saved_study_scoring_uses_the_childs_present_zone_electrodes(monkeypatch):
baseline = {"kind": "count_rate", "ages": [16.0, 37.0], "rate": 3.0, "k": None}
model = jobs.Baseline(
"eeg-spikes", dict.fromkeys(("value", "electrode_C3", "zone_central"), baseline)
)
champion = SimpleNamespace(unwrap_python_model=lambda: model)
monkeypatch.setattr(jobs.registry, "champion", lambda name: (1, champion))
monkeypatch.setattr(
eeg,
"analysed",
lambda: [
{
"edf": "child",
"age_months": 24.0,
"features": {"eeg-spikes": {"minutes": 5.0, "zone_electrodes_central": 2.0}},
"metrics": [
{
"code": "paroxysmal_spikes",
"value": 6.0,
"electrodes": {"C3": 6.0},
"zones": {"central": 6.0},
}
],
}
],
)
saved = []
monkeypatch.setattr(eeg, "save_scores", lambda name, rows: saved.extend(rows))
assert jobs.score("eeg-spikes") == 1
assert len(saved) == 3
for row in saved:
electrodes = 2.0 if row["part"] == "zones" else None
expected = curves.score(baseline, 6.0, 24.0, 5.0, electrodes)
assert {field: row[field] for field in expected} == expected