aab20683aa
The 33 zone x item spike pairs could not be estimated with about 46 children. The four spike tests accepted before seeing the ADOS-2 replace them: any zone with the total CSS (repetitive behaviours and social affect are one pair until the hospital sends CSS by domain), left with items 1 and 18, right with items 4, 5 and 7, and central with item 21 as exploratory. The predictor is any useful spike in NREM on the group's electrodes. Item altered from 2, CSS high from 8, at least 5 children with and without the event, q within each biomarker without the exploratory pair, one CSS family adjusted by age and module, no z clipping. The settings are module constants; each fit saves them with its pairs, and a model without them is refused. score() leaves each fitted child out. Keys are stored hashed.
170 lines
6.6 KiB
Python
170 lines
6.6 KiB
Python
import json
|
|
from datetime import date
|
|
from types import SimpleNamespace
|
|
|
|
import dagster as dg
|
|
import pandas as pd
|
|
import pytest
|
|
from pydantic import ValidationError
|
|
|
|
from core.tea import ADOS2_ITEMS
|
|
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
|
|
|
|
|
|
def test_scope_validation():
|
|
assert eeg.Scope().mode == "pending"
|
|
assert eeg.Scope(mode="first_n", n=3).n == 3
|
|
good = "p1|2024-05-06"
|
|
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
|
|
bad = [
|
|
{"mode": "first_n"},
|
|
{"mode": "first_n", "n": 0},
|
|
{"mode": "first_n", "n": 2, "ids": [good]},
|
|
{"mode": "ids"},
|
|
{"mode": "ids", "ids": [good], "n": 1},
|
|
{"mode": "ids", "ids": ["nobar"]},
|
|
{"mode": "ids", "ids": ["p|2024-5-6"]},
|
|
{"mode": "ids", "ids": ["|2024-05-06"]},
|
|
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
|
|
{"mode": "pending", "n": 1},
|
|
{"mode": "pending", "ids": [good]},
|
|
{"mode": "other"},
|
|
{"extra": 1},
|
|
]
|
|
for kwargs in bad:
|
|
with pytest.raises(ValidationError):
|
|
eeg.Scope(**kwargs)
|
|
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
|
|
with pytest.raises(ValidationError, match="first_n needs n"):
|
|
ScopeConfig(mode="first_n").model()
|
|
|
|
|
|
def test_the_domain_routine_scores_the_curves_then_relates_the_association():
|
|
assert JOBS.routine() == [*MODELS, ASSOCIATION]
|
|
|
|
|
|
def test_the_association_cohort_takes_spikes_as_yes_or_no(monkeypatch):
|
|
def study(child, day, features):
|
|
return {
|
|
**dict.fromkeys(ADOS2_ITEMS),
|
|
"person_id": child,
|
|
"study_date": day,
|
|
"edf": f"{child}-{day}",
|
|
"age_months": 24.0,
|
|
"module": "toddler",
|
|
"evaluation_date": None,
|
|
"birth_date": None,
|
|
"language_level": None,
|
|
"features": json.dumps(features),
|
|
}
|
|
|
|
spikes = {"eeg-spikes": {"minutes": 10.0, "electrode_F8": 0.2, "electrode_C3": 0.0}}
|
|
studies = [study("one", "2025-01-01", spikes), study("two", "2025-01-01", {})]
|
|
scores = [
|
|
{"edf": "one-2025-01-01", "metric": metric, "part": "zones", "site": "central", "z": 1.5}
|
|
for metric in ("paroxysmal_spikes", "spindles")
|
|
]
|
|
monkeypatch.setattr(eeg, "association_cohort_rows", lambda: (studies, scores))
|
|
fit, scored = jobs.cohort()
|
|
assert list(fit.child) == ["one"]
|
|
assert list(scored.child) == ["one", "two"]
|
|
assert [c for c in scored.columns if c.startswith("z_")] == ["z_spindles_central"]
|
|
found = fit.iloc[0]
|
|
assert (found.spikes_any_any, found.spikes_any_right, found.spikes_any_central) == (1, 1, 0)
|
|
assert pd.isna(found.spikes_any_left)
|
|
assert scored.iloc[1].filter(like="spikes_any_").isna().all()
|
|
|
|
|
|
def test_after_ingest_requests_a_run_only_with_pending_eegs():
|
|
skip = after_ingest("r1", lambda: False)
|
|
assert isinstance(skip, dg.SkipReason)
|
|
request = after_ingest("r1", lambda: True)
|
|
assert isinstance(request, dg.RunRequest)
|
|
assert request.run_key == "after-ingest-r1"
|
|
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
|
|
assert scope == {"mode": "pending"}
|
|
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
|
|
|
|
|
|
def test_tea_eeg_first_n_selects_exactly_n_pending_studies(fresh_platform):
|
|
with fresh_platform.begin() as con:
|
|
con.exec_driver_sql("create table silver.person (person_id text, birth_date text)")
|
|
con.exec_driver_sql("insert into silver.person values ('p1', '2023-01-01')")
|
|
con.exec_driver_sql("create table silver.eeg (person_id text, study_date text, edf text)")
|
|
con.exec_driver_sql(
|
|
"insert into silver.eeg values (?, ?, ?)",
|
|
[
|
|
("p1", "2025-01-01", "c"),
|
|
("p1", "2025-02-01", "b"),
|
|
("p1", "2025-03-01", "a"),
|
|
("p1", "2025-04-01", "d"),
|
|
("p1", "2025-05-01", None),
|
|
],
|
|
)
|
|
con.exec_driver_sql("create table bronze.eeg_analysis (edf text)")
|
|
con.exec_driver_sql("insert into bronze.eeg_analysis values ('b')")
|
|
|
|
birth = date(2023, 1, 1)
|
|
assert eeg.select(eeg.Scope(mode="first_n", n=2)) == [
|
|
{"edf": "a", "birth_date": birth},
|
|
{"edf": "c", "birth_date": birth},
|
|
]
|
|
assert eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-02-01"])) == [
|
|
{"edf": "b", "birth_date": birth}
|
|
]
|
|
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
|