F7b: ADOS-2 association as library 0.4.0 with the accepted spike tests
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.
This commit is contained in:
+239
-11
@@ -1,9 +1,14 @@
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from core.tea import ADOS2_ITEMS
|
||||
from models.tea import association as a
|
||||
|
||||
KEYS = ["key", "biomarker", "zone", "outcome_code"]
|
||||
|
||||
|
||||
def test_firth_on_separation():
|
||||
frame = pd.DataFrame({"z": np.arange(12), "event": [0] * 6 + [1] * 6})
|
||||
@@ -21,21 +26,244 @@ def test_ordinal_on_monotone_trend():
|
||||
assert a.ordinal(frame, "level", "z", (), high=2)["odds_ratio"] > 1
|
||||
|
||||
|
||||
def test_pairs_and_item_availability():
|
||||
assert len(a.pairs("item")) == 41
|
||||
assert len(a.pairs("domain")) == 15
|
||||
assert ADOS2_ITEMS == [
|
||||
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact",
|
||||
"facial_expressions", "gaze_integration", "shared_enjoyment", "response_to_name",
|
||||
"ignoring", "requesting", "showing", "joint_attention_initiation",
|
||||
"joint_attention_response", "social_overtures_quality", "social_overtures_caregiver",
|
||||
"reciprocal_communication", "rapport_quality", "intonation", "stereotyped_language",
|
||||
"unusual_sensory_interest", "hand_finger_mannerisms", "repetitive_interests",
|
||||
] # fmt: skip
|
||||
def test_pairs_by_level():
|
||||
item = a.pairs("item")
|
||||
spikes = [p for p in item if p["biomarker"] == "spikes"]
|
||||
assert [(p["zone"], p["kind"], a.outcome_code(p)) for p in spikes] == [
|
||||
("any", "domain", "CSS"),
|
||||
("left", "composite", "ados2_items_01_18"),
|
||||
("right", "composite", "ados2_items_04_05_07"),
|
||||
("central", "exploratory", "ados2_item_21"),
|
||||
]
|
||||
assert len(item) == 12
|
||||
domain = a.pairs("domain")
|
||||
assert [p["zone"] for p in domain if p["biomarker"] == "spikes"] == ["any"]
|
||||
assert len(domain) == 8
|
||||
|
||||
|
||||
def test_item_scores_follow_the_algorithm_and_the_module():
|
||||
assert ADOS2_ITEMS[0] == "vocalization_directed"
|
||||
assert ADOS2_ITEMS[20] == "hand_finger_mannerisms"
|
||||
frame = pd.DataFrame(
|
||||
{
|
||||
"ados_module": ["toddler", "module_1", "module_2", "module_3"],
|
||||
"vocalization_directed": [3, 7, 1, 1],
|
||||
"unusual_eye_contact": [1, 1, 1, 1],
|
||||
}
|
||||
)
|
||||
np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan])
|
||||
np.testing.assert_allclose(a.item_scores(frame, 4), [2, 1, 1, np.nan])
|
||||
|
||||
|
||||
def test_spikes_any_from_the_electrode_rates():
|
||||
rates = {f"electrode_{e}": 0.0 for zone in a.ZONES.values() for e in zone}
|
||||
found = a.spikes_any({**rates, "minutes": 20.0, "electrode_T3": 0.05})
|
||||
assert found == {
|
||||
"spikes_any_any": 1,
|
||||
"spikes_any_left": 1,
|
||||
"spikes_any_right": 0,
|
||||
"spikes_any_central": 0,
|
||||
}
|
||||
unmeasured = {**rates, "minutes": 20.0, "electrode_C3": None, "electrode_C4": None}
|
||||
assert a.spikes_any(unmeasured)["spikes_any_central"] == 0
|
||||
assert np.isnan(a.spikes_any({**unmeasured, "electrode_Cz": None})["spikes_any_central"])
|
||||
for features in ({**rates, "minutes": 0.0}, {**rates, "minutes": None}, {}):
|
||||
assert all(np.isnan(v) for v in a.spikes_any(features).values())
|
||||
|
||||
|
||||
def _domain_cohort(n_toddler=60, n_other=8, seed=3):
|
||||
rng = np.random.default_rng(seed)
|
||||
n = n_toddler + n_other
|
||||
z = rng.normal(0, 1.2, n)
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"key": [f"k{i}" for i in range(n)],
|
||||
"age_months": rng.uniform(16, 36, n).round(1),
|
||||
"ados_module": ["toddler"] * n_toddler
|
||||
+ ["module_1"] * (n_other // 2)
|
||||
+ ["module_2"] * (n_other - n_other // 2),
|
||||
"css": np.clip(np.round(6 + 1.3 * z + rng.normal(0, 1.2, n)), 1, 10),
|
||||
"z_gradient": z,
|
||||
"z_spindles_central": rng.normal(0, 1, n),
|
||||
"spikes_any_any": (z > 0).astype(float),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fitted():
|
||||
cohort = _domain_cohort()
|
||||
return cohort, a.Ados2Association(level="domain").fit(cohort)
|
||||
|
||||
|
||||
def test_one_css_family_for_every_module(fitted):
|
||||
_, model = fitted
|
||||
found = model.associations()
|
||||
gradient = found[found.biomarker == "gradient"]
|
||||
assert list(gradient.outcome_code) == ["CSS"]
|
||||
assert gradient.n.iloc[0] == 68
|
||||
assert gradient.odds_ratio.iloc[0] > 1
|
||||
assert gradient.model.iloc[0] == "ordinal"
|
||||
assert set(found.event) == {">=8"}
|
||||
assert found[found.biomarker == "spikes"].q.notna().all()
|
||||
assert model.fitted["css_sources"] == {"computed": 68}
|
||||
assert model.fitted["settings"] == {
|
||||
"item_altered": 2,
|
||||
"css_high": 8,
|
||||
"min_events": 5,
|
||||
"q_family": "biomarker",
|
||||
"clip_z": 0,
|
||||
}
|
||||
assert model.fitted["pairs"] == a.pairs("domain")
|
||||
|
||||
|
||||
def test_few_events_are_fitted_and_flagged():
|
||||
cohort = _domain_cohort()
|
||||
cohort["css"] = np.where(cohort.index < 3, 9.0, 4.0 + cohort.index % 3)
|
||||
found = a.Ados2Association(level="domain").fit(cohort).associations()
|
||||
gradient = found[found.biomarker == "gradient"].iloc[0]
|
||||
assert np.isfinite(gradient.odds_ratio)
|
||||
assert gradient.reason == "datos insuficientes: 3 con evento y 65 sin evento (minimo 5)"
|
||||
|
||||
|
||||
def test_leave_one_out(fitted):
|
||||
cohort, model = fitted
|
||||
both = model.score(cohort).merge(
|
||||
model.score(cohort, leave_one_out=False), on=KEYS, suffixes=("_out", "_in")
|
||||
)
|
||||
assert len(both) and np.isfinite(both.probability_out).all()
|
||||
assert (both.probability_out != both.probability_in).any()
|
||||
|
||||
|
||||
def test_a_new_child_gets_the_full_model(fitted):
|
||||
cohort, model = fitted
|
||||
new = cohort.iloc[[0]].assign(key="new")
|
||||
left_out, full = model.score(new), model.score(new, leave_one_out=False)
|
||||
assert len(full)
|
||||
np.testing.assert_allclose(left_out.probability, full.probability)
|
||||
|
||||
|
||||
def test_every_study_of_a_fitted_child_is_scored_without_the_child():
|
||||
cohort = _domain_cohort().assign(child=lambda t: t.key)
|
||||
model = a.Ados2Association(level="domain").fit(cohort)
|
||||
again = cohort.iloc[[0]].assign(key="later")
|
||||
scored = model.score(pd.concat([cohort, again], ignore_index=True))
|
||||
first, later = (
|
||||
scored[scored.key == key].set_index(["biomarker", "zone"]).probability
|
||||
for key in ("k0", "later")
|
||||
)
|
||||
pd.testing.assert_series_equal(first, later)
|
||||
alone = model.score(again).set_index(["biomarker", "zone"]).probability
|
||||
assert (later != alone).any()
|
||||
|
||||
|
||||
def test_the_saved_model_lists_no_keys(fitted, tmp_path):
|
||||
cohort, model = fitted
|
||||
model.save(tmp_path)
|
||||
text = (tmp_path / "association.json").read_text()
|
||||
assert not any(f'"{key}"' in text for key in cohort.key)
|
||||
keys = json.loads(text)["fitted"]["keys"]
|
||||
assert len(keys) == len(cohort)
|
||||
assert all(len(key) == 16 for key in keys)
|
||||
loaded = a.Ados2Association.load(tmp_path)
|
||||
pd.testing.assert_frame_equal(loaded.score(cohort), model.score(cohort))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", ["settings", "pairs"])
|
||||
def test_an_old_saved_model_is_refused(fitted, tmp_path, missing):
|
||||
_, model = fitted
|
||||
old = {k: v for k, v in model.fitted.items() if k != missing}
|
||||
(tmp_path / "association.json").write_text(json.dumps({"level": "domain", "fitted": old}))
|
||||
with pytest.raises(ValueError, match="retrain"):
|
||||
a.Ados2Association.load(tmp_path)
|
||||
with pytest.raises(ValueError, match="retrain"):
|
||||
a.Model(old).predict(None, pd.DataFrame())
|
||||
|
||||
|
||||
def test_clipping_leaves_the_scored_z(monkeypatch):
|
||||
monkeypatch.setattr(a, "CLIP_Z", 3)
|
||||
cohort = _domain_cohort()
|
||||
cohort.loc[0, "z_gradient"] = 9.0
|
||||
model = a.Ados2Association(level="domain").fit(cohort)
|
||||
scored = model.score(cohort)
|
||||
assert scored.loc[(scored.key == "k0") & (scored.biomarker == "gradient"), "z"].item() == 9.0
|
||||
|
||||
|
||||
def _item_cohort(n=60, seed=5):
|
||||
rng = np.random.default_rng(seed)
|
||||
spikes = (rng.random(n) < 0.5).astype(float)
|
||||
cohort = pd.DataFrame(
|
||||
{
|
||||
"key": [f"k{i}" for i in range(n)],
|
||||
"age_months": rng.uniform(16, 36, n).round(1),
|
||||
"ados_module": ["toddler", "module_1", "module_2"] * (n // 3),
|
||||
"css": rng.integers(4, 11, n).astype(float),
|
||||
"spikes_any_any": spikes,
|
||||
"spikes_any_left": spikes,
|
||||
"spikes_any_right": spikes,
|
||||
"spikes_any_central": spikes,
|
||||
}
|
||||
)
|
||||
for item in (1, 4, 5, 7, 18, 21):
|
||||
cohort[ADOS2_ITEMS[item - 1]] = rng.choice([0, 1, 2], n, p=[0.5, 0.25, 0.25])
|
||||
return cohort
|
||||
|
||||
|
||||
def _spike_rows(model):
|
||||
found = model.associations()
|
||||
return found[found.biomarker == "spikes"].set_index("zone")
|
||||
|
||||
|
||||
def test_composites_and_the_exploratory_pair():
|
||||
cohort = _item_cohort()
|
||||
model = a.Ados2Association().fit(cohort)
|
||||
found = _spike_rows(model)
|
||||
assert list(found.index) == ["any", "left", "right", "central"]
|
||||
assert found.n.to_dict() == {"any": 60, "left": 40, "right": 60, "central": 60}
|
||||
assert found.event.to_dict() == {
|
||||
"any": ">=8",
|
||||
"left": "alguno >=2",
|
||||
"right": "alguno >=2",
|
||||
"central": ">=2",
|
||||
}
|
||||
assert list(found.loc[["left", "right", "central"]].model) == ["firth"] * 3
|
||||
assert list(found.loc[["left", "right", "central"]].sens_model) == ["ordinal"] * 3
|
||||
assert found.outcome["left"] == [1, 18]
|
||||
assert found.kind["central"] == "exploratory"
|
||||
assert np.isfinite(found.odds_ratio["central"])
|
||||
assert np.isnan(found.q["central"])
|
||||
tested = found.loc[["any", "left", "right"]]
|
||||
np.testing.assert_allclose(tested.q.to_numpy(float), a.bh(tested.p).round(5))
|
||||
scored = model.score(cohort)
|
||||
left = scored[scored.outcome_code == "ados2_items_01_18"]
|
||||
assert set(cohort.ados_module[cohort.key.isin(left.key)]) == {"toddler", "module_1"}
|
||||
assert set(scored.z[scored.biomarker == "spikes"]) == {0.0, 1.0}
|
||||
|
||||
|
||||
def test_a_composite_event_is_any_of_its_items_altered():
|
||||
cohort = _item_cohort()
|
||||
scores = pd.concat([a.item_scores(cohort, n) for n in (4, 5, 7)], axis=1)
|
||||
pair = next(p for p in a.pairs("item") if p["zone"] == "right")
|
||||
settings = a.Ados2Association().fit(cohort).fitted["settings"]
|
||||
event, count = a._outcome(cohort, pair, settings)
|
||||
np.testing.assert_allclose(event, (scores == 2).any(axis=1))
|
||||
np.testing.assert_allclose(count, (scores == 2).sum(axis=1))
|
||||
|
||||
|
||||
def test_a_composite_with_a_small_group_counts_the_altered_items():
|
||||
cohort = _item_cohort()
|
||||
rng = np.random.default_rng(11)
|
||||
cohort["facial_expressions"] = 2
|
||||
cohort["unusual_eye_contact"] = rng.choice([0, 2], len(cohort))
|
||||
cohort["shared_enjoyment"] = rng.choice([0, 2], len(cohort))
|
||||
model = a.Ados2Association().fit(cohort)
|
||||
found = _spike_rows(model).loc["right"]
|
||||
assert (found.model, found.sens_model, found.event) == ("ordinal", "firth", "alguno >=2")
|
||||
assert found.reason == (
|
||||
"datos insuficientes: 60 con evento y 0 sin evento (minimo 5); "
|
||||
"se usa el numero de reactivos alterados"
|
||||
)
|
||||
scored = model.score(cohort)
|
||||
right = scored[scored.zone == "right"]
|
||||
assert (right.probability == 1).all()
|
||||
assert (right.reference_probability == 1).all()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -6,6 +7,7 @@ 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
|
||||
@@ -45,6 +47,38 @@ 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)
|
||||
|
||||
Reference in New Issue
Block a user