From 920003c5d40ed7331d254af18ac37959b262ce08 Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 3 Dec 2026 22:08:43 -0600 Subject: [PATCH] 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. --- models/tea/eeg/biomarkers.py | 12 +++- models/tea/eeg/curves.py | 48 ++++++++++--- models/tea/eeg/spikes.py | 59 +++++++++++++--- models/tea/jobs.py | 10 ++- tests/test_curves.py | 56 +++++++++++++++ tests/test_eeg_spikes.py | 127 +++++++++++++++++++++++++++++++++++ tests/test_tea_job.py | 53 +++++++++++++++ 7 files changed, 345 insertions(+), 20 deletions(-) create mode 100644 tests/test_eeg_spikes.py diff --git a/models/tea/eeg/biomarkers.py b/models/tea/eeg/biomarkers.py index 7196cbb..a58ac5e 100644 --- a/models/tea/eeg/biomarkers.py +++ b/models/tea/eeg/biomarkers.py @@ -115,7 +115,14 @@ def measure(prep: Prepared, states, intervals) -> Measured: if found is None: nan = dict.fromkeys found = spikes.Spikes( - np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0, {} + np.nan, + nan(spikes.ELECTRODES, np.nan), + nan(spindles.ZONES, np.nan), + 0.0, + {}, + np.nan, + 0.0, + {z: sum(e in prep.names for e in members) for z, members in spindles.ZONES.items()}, ) reasons["paroxysmal_spikes"] = "few-electrodes" elif np.isnan(found.rate): @@ -126,6 +133,9 @@ def measure(prep: Prepared, states, intervals) -> Measured: **{f"electrode_{e}": v for e, v in found.electrodes.items()}, **{f"zone_{z}": v for z, v in found.zones.items()}, "minutes": found.minutes, + "awake_rate": found.awake_rate, + "awake_minutes": found.awake_minutes, + **{f"zone_electrodes_{z}": n for z, n in found.zone_electrodes.items()}, } gradient, why = delta_gradient(prep, states) metrics["anteroposterior_gradient"] = (gradient, {}, {}) diff --git a/models/tea/eeg/curves.py b/models/tea/eeg/curves.py index 022e059..bd2a295 100644 --- a/models/tea/eeg/curves.py +++ b/models/tea/eeg/curves.py @@ -60,8 +60,11 @@ def _curve(values: np.ndarray, ages: np.ndarray) -> dict: } -def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict: +def _count_rate( + values: np.ndarray, ages: np.ndarray, exposure: np.ndarray, electrodes: np.ndarray +) -> dict: n = np.round(values * exposure) + exposure = exposure * electrodes keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0) keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1]) n, x = n[keep], exposure[keep] @@ -84,9 +87,17 @@ def train(features: pd.DataFrame, scenario: str) -> dict: ages = features["age_months"].to_numpy(float) out = {} for name in features.columns.drop(list(NOT_MEASURES), errors="ignore"): + if name.startswith(("zone_electrodes_", "awake_")): + continue values = pd.to_numeric(features[name]).to_numpy(float) if counts: - out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float)) + column = f"zone_electrodes_{name.removeprefix('zone_')}" + electrodes = ( + pd.to_numeric(features[column]).fillna(1).to_numpy(float) + if name.startswith("zone_") and column in features + else np.ones(len(features)) + ) + out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float), electrodes) else: out[name] = _curve(values, ages) return out @@ -129,14 +140,16 @@ def _score_curve(baseline: dict, value: float, age: float) -> dict: } -def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict: +def _score_count( + baseline: dict, value: float, age: float, exposure: float | None, electrodes: float +) -> dict: rate, k = baseline["rate"], baseline["k"] lo, hi = baseline["ages"] if not lo <= age < hi: return _unscored("age-out-of-range") - if exposure is None or not math.isfinite(rate) or not exposure > 0: + if exposure is None or not math.isfinite(rate) or not exposure > 0 or not electrodes > 0: return _unscored("no-exposure") - n, mu = float(np.round(value * exposure)), rate * exposure + n, mu = float(np.round(value * exposure)), rate * exposure * electrodes law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu)) tail, at = law.sf(n - 1), law.pmf(n) z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX)) @@ -152,7 +165,11 @@ def _score_count(baseline: dict, value: float, age: float, exposure: float | Non def score( - baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None + baseline: dict, + value: float | None, + age_months: float | None, + exposure: float | None = None, + electrodes: float | None = None, ) -> dict: value, age_months = _number(value), _number(age_months) if value is None: @@ -160,7 +177,14 @@ def score( if age_months is None: return _unscored("no-age") if baseline["kind"] == "count_rate": - return _score_count(baseline, value, age_months, _number(exposure)) + electrodes = _number(electrodes) + return _score_count( + baseline, + value, + age_months, + _number(exposure), + electrodes if electrodes is not None else 1.0, + ) return _score_curve(baseline, value, age_months) @@ -179,7 +203,15 @@ def deviations(models: dict[str, dict], analysis) -> dict[str, dict]: ) else: out[metric.code][part] = { - key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure) + key: score( + model[PREFIX[part] + key], + v, + analysis.age_months, + exposure, + analysis.features[name].get(f"zone_electrodes_{key}") + if scenario.counts and part == "zones" + else None, + ) for key, v in getattr(metric, part).items() } return out diff --git a/models/tea/eeg/spikes.py b/models/tea/eeg/spikes.py index 96c87fd..9b215eb 100644 --- a/models/tea/eeg/spikes.py +++ b/models/tea/eeg/spikes.py @@ -11,6 +11,7 @@ from models.tea.eeg.spindles import ZONES ELECTRODES = tuple(NEIGHBOURS) GATE_S = 2.0 +INHERIT_S = 30.0 VERTEX = ("Cz", "Fz", "Pz") POSTS = ("O1", "O2") OCULAR = ("Fp1", "Fp2", "F7", "F8") @@ -26,6 +27,31 @@ class Spikes: zones: dict[str, float] minutes: float rejected: dict[str, float] + awake_rate: float + awake_minutes: float + zone_electrodes: dict[str, int] + + +def _states(labelled, duration_s: float) -> np.ndarray: + t = np.arange(0.0, duration_s, 0.5) + out = np.full(len(t), "unlabelled", dtype=object) + for t0, t1, label in labelled: + hit = (out == "unlabelled") & (t0 <= t) & (t < t1) + out[hit] = label + direct = np.flatnonzero(out != "unlabelled") + if not len(direct): + return out + missing = np.flatnonzero((out == "unlabelled") & (t >= t[direct[0]])) + j = np.searchsorted(direct, missing) + before, after = direct[np.maximum(j - 1, 0)], direct[np.minimum(j, len(direct) - 1)] + da = np.where(j > 0, t[missing] - t[before], np.inf) + dd = np.where(j < len(direct), t[after] - t[missing], np.inf) + close = np.minimum(da, dd) <= INHERIT_S + labels = np.where(da <= dd, out[before], out[after]) + transition = (j > 0) & (j < len(direct)) & (out[before] != out[after]) + labels[transition] = "transition" + out[missing[close]] = labels[close] + return out def _mad(v: np.ndarray) -> float: @@ -178,12 +204,13 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None: for s, label in zip(prep.starts, states, strict=True) if label in ("wake", "drowsy", "sleep") ] + grid = _states(labelled, prep.duration_s) def state_at(t: np.ndarray) -> np.ndarray: - out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool) - for t0, t1, label in labelled: - hit = open_ & (t0 <= t) & (t < t1) - out[hit], open_ = label, open_ & ~hit + out = np.full(len(t), "unlabelled", dtype=object) + index = np.floor(t / 0.5).astype(int) + inside = (t >= 0) & (t < prep.duration_s) & (index < len(grid)) + out[inside] = grid[index[inside]] return out gate, rejected = _gate(x, fs, intervals) @@ -192,6 +219,8 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None: for (t0, t1), state in zip(gate, middles, strict=True): minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0 sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",))) + awake_minutes = float(sum(minutes.get(s, 0.0) for s in ("wake", "drowsy"))) + awake_count = 0 counts = dict.fromkeys(channels, 0) candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)] if candidates and gate: @@ -204,18 +233,30 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None: if len(c): c = c.assign(field=_field(c), state=state_at(c.t.to_numpy())) found = _merge(c) - found = found[found.useful & (found.field > 0) & (found.state == "sleep")] + found = found[found.useful & (found.field > 0)] + awake_count = int(found.state.isin(("wake", "drowsy")).sum()) + found = found[found.state == "sleep"] for channel, n in found.channel.value_counts().items(): counts[channel] = int(n) - rounded = round(sleep_minutes, 2) - rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan + rate = round(sum(counts.values()) / sleep_minutes, 3) if sleep_minutes > 0 else np.nan + awake_rate = round(awake_count / awake_minutes, 3) if awake_minutes > 0 else np.nan electrodes = { e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan for e in ELECTRODES } - zones = {} + zones, zone_electrodes = {}, {} for zone, members in ZONES.items(): present = [e for e in members if e in counts] + zone_electrodes[zone] = len(present) total = sum(counts[e] for e in present) zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan - return Spikes(rate, electrodes, zones, round(sleep_minutes, 4), rejected) + return Spikes( + rate, + electrodes, + zones, + round(sleep_minutes, 4), + rejected, + awake_rate, + round(awake_minutes, 4), + zone_electrodes, + ) diff --git a/models/tea/jobs.py b/models/tea/jobs.py index 2dc1eae..3b1d038 100644 --- a/models/tea/jobs.py +++ b/models/tea/jobs.py @@ -42,7 +42,8 @@ class Baseline(mlflow.pyfunc.PythonModel): feature = (params or {}).get("feature", "value") rows = model_input.to_dict("records") return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"), - r.get("age_months"), r.get("exposure")) + r.get("age_months"), r.get("exposure"), + r.get("electrodes")) for r in rows]) # fmt: skip @@ -289,7 +290,12 @@ def score(name: str) -> int | None: feature = "value" if part == "value" else prefix + site if feature not in baseline: continue - s = curves.score(baseline[feature], value, one["age_months"], exposure) + electrodes = ( + (one["features"].get(name) or {}).get(f"zone_electrodes_{site}") + if scenario.counts and part == "zones" + else None + ) + s = curves.score(baseline[feature], value, one["age_months"], exposure, electrodes) rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"], "scenario": name, "model": label, "metric": scenario.metric, "part": part, "site": site or None, **s}) # fmt: skip diff --git a/tests/test_curves.py b/tests/test_curves.py index 28b0f29..947c3d0 100644 --- a/tests/test_curves.py +++ b/tests/test_curves.py @@ -1,6 +1,12 @@ +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(): @@ -24,3 +30,53 @@ def test_centile_interpolation_preserves_scoring(): 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"] diff --git a/tests/test_eeg_spikes.py b/tests/test_eeg_spikes.py new file mode 100644 index 0000000..1cb5266 --- /dev/null +++ b/tests/test_eeg_spikes.py @@ -0,0 +1,127 @@ +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"]) diff --git a/tests/test_tea_job.py b/tests/test_tea_job.py index 5ff523d..1a0f9d8 100644 --- a/tests/test_tea_job.py +++ b/tests/test_tea_job.py @@ -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