142 lines
8.2 KiB
Python
142 lines
8.2 KiB
Python
"""What this module covers: the `tea` library's ADOS-2 association (`tea.associations.ados2`, modern, and
|
|
`tea.legacy.associations.ados2`, the research code vendored): the pairs it tests, the module-independent outcome
|
|
codes, recovery of planted effects, legacy and modern agreeing, the per-child scores and the saved state.
|
|
|
|
Fixtures: `cohort_items`, 60 invented children of 16 to 37 months (Toddler module under 31 months, Module 1 or 2
|
|
above) with item scores and a CSS, whose spike z in temporal_izq raises item 18 (intonation) and whose spindle z in
|
|
central lowers the CSS, everything else null; `cohort_css`, the same children without item scores; `fits`, both
|
|
implementations fitted once on each cohort.
|
|
"""
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pytest
|
|
from ados2_cohort import ITEM_CODES, cohort
|
|
|
|
from tea.associations.ados2 import Ados2Association
|
|
from tea.associations.ados2 import _items as items
|
|
from tea.contracts import ASSOCIATION_COLUMNS, SCORE_COLUMNS, ZONES
|
|
from tea.legacy.associations.ados2 import LegacyAdos2Association
|
|
|
|
@pytest.fixture(scope="module")
|
|
def cohort_items():
|
|
"""60 children with item scores: spikes in temporal_izq raise item 18, spindles in central lower the CSS."""
|
|
return cohort()
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def cohort_css(cohort_items):
|
|
"""The same children with the CSS only, as when the psychologist reports no items."""
|
|
return cohort_items.drop(columns=[c for c in ITEM_CODES if c in cohort_items])
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def fits(cohort_items, cohort_css):
|
|
"""Modern and legacy, each fitted once on both cohorts, by (impl, level)."""
|
|
return {(impl, level): cls().fit(c) for impl, cls in (("modern", Ados2Association),
|
|
("legacy", LegacyAdos2Association))
|
|
for level, c in (("item", cohort_items), ("domain", cohort_css))}
|
|
|
|
|
|
def test_level_follows_the_cohort_and_codes_are_module_independent(fits):
|
|
"""Pins down: a cohort with items is fitted by item and one without by the CSS; item outcomes carry
|
|
`ados2_item_NN` and domain outcomes `CSS`, with events `>=1` and `>=8`; zones are the library's, `posterior`
|
|
or `global`. Fails if the level stops following the data, an outcome goes back to a per-module column code (one
|
|
code is another item in another module), or a zone code leaves the shared list."""
|
|
for impl in ("modern", "legacy"):
|
|
assert fits[impl, "item"].fitted["level"] == "item"
|
|
assert fits[impl, "domain"].fitted["level"] == "domain"
|
|
a = fits[impl, "item"].associations()
|
|
assert list(a.columns) == list(ASSOCIATION_COLUMNS)
|
|
assert set(a.outcome_code) <= {items.item_code(n) for n in items.ITEMS} | {"CSS"}
|
|
assert set(a.loc[a.kind == "item", "event"]) == {">=1"}
|
|
assert set(a.loc[a.kind == "domain", "event"]) == {">=8"}
|
|
assert set(a.zone) <= set(ZONES) | {"posterior", "global"}
|
|
assert set(fits[impl, "domain"].associations().outcome_code) == {"CSS"}
|
|
|
|
|
|
def test_the_planted_effects_are_found(fits):
|
|
"""Pins down: the item fit finds spikes in temporal_izq raising item 18 (odds ratio above 1, q < 0.05) and the CSS
|
|
fit finds spindles in central lowering the CSS (odds ratio below 1, q < 0.05). Fails if the Firth or ordinal fit,
|
|
the item read per module, or the q values break."""
|
|
a = fits["modern", "item"].associations().set_index(["biomarker", "zone", "outcome_code"])
|
|
item = a.loc[("spikes", "temporal_izq", "ados2_item_18")]
|
|
assert item.odds_ratio > 1 and item.q < .05
|
|
d = fits["modern", "domain"].associations().set_index(["biomarker", "zone", "outcome_code"])
|
|
css = d.loc[("spindles", "central", "CSS")]
|
|
assert css.odds_ratio < 1 and css.q < .05
|
|
|
|
|
|
@pytest.mark.parametrize("level", ["item", "domain"])
|
|
def test_legacy_and_modern_agree(fits, cohort_items, cohort_css, level):
|
|
"""Pins down: the modern port gives the vendored research code's odds ratios, intervals, p, q and per-child
|
|
probabilities exactly, at both levels. Fails if either side's design matrix, fit, interval search, FLIC
|
|
intercept or pair list drifts from the other."""
|
|
cohort = cohort_items if level == "item" else cohort_css
|
|
m, legacy = fits["modern", level], fits["legacy", level]
|
|
keys = ["biomarker", "zone", "outcome_code"]
|
|
joined = m.associations().merge(legacy.associations(), on=keys, suffixes=("_m", "_l"), validate="1:1")
|
|
assert len(joined) == len(m.associations()) == len(legacy.associations())
|
|
for c in ("odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio"):
|
|
np.testing.assert_allclose(joined[f"{c}_m"].astype(float), joined[f"{c}_l"].astype(float), rtol=1e-9)
|
|
scores = m.score(cohort).merge(legacy.score(cohort), on=["key", *keys], suffixes=("_m", "_l"), validate="1:1")
|
|
assert len(scores) == len(legacy.score(cohort)) > 0
|
|
np.testing.assert_allclose(scores.probability_m, scores.probability_l, atol=1e-9)
|
|
np.testing.assert_allclose(scores.reference_probability_m, scores.reference_probability_l, atol=1e-9)
|
|
|
|
|
|
def test_an_item_is_read_from_the_column_of_the_childs_module(cohort_items):
|
|
"""Pins down: item 11 (showing) is `sa_b12` in the Toddler module, `sa_b9` in Module 1 and `sa_b5` in Module 2,
|
|
and each child's score comes from its own module's column, with 3 as 2 and 7 as 0. Fails if items are read by
|
|
one column code for every module."""
|
|
t = pd.DataFrame({"ados_module": ["TODDLER", "MODULO_1", "MODULO_2", "MODULO_2"],
|
|
"sa_b12": [1, 2, 0, 0], "sa_b9": [0, 3, 0, 0], "sa_b5": [2, 0, 7, np.nan]})
|
|
assert items.item_scores(t, 11).tolist()[:3] == [1.0, 2.0, 0.0]
|
|
assert np.isnan(items.item_scores(t, 11).iloc[3])
|
|
|
|
|
|
def test_scores_cover_only_the_modules_with_the_item_and_survive_save_and_load(fits, cohort_items, tmp_path):
|
|
"""Pins down: a child is scored on an item only when its module has that item, every score row has a z and a
|
|
probability in [0, 1], and a saved and reloaded fit scores the same. Fails if scoring ignores the module, the
|
|
saved state misses what scoring needs, or the columns drift from `SCORE_COLUMNS`."""
|
|
m = fits["modern", "item"]
|
|
scores = m.score(cohort_items)
|
|
assert list(scores.columns) == list(SCORE_COLUMNS)
|
|
modules = cohort_items.set_index("key").ados_module
|
|
item_16 = scores[scores.outcome_code == "ados2_item_16"] # Module 2 only
|
|
assert set(modules[item_16.key]) <= {"MODULO_2"}
|
|
assert scores.probability.between(0, 1).all() and scores.z.notna().all()
|
|
m.save(tmp_path)
|
|
again = Ados2Association.load(tmp_path).score(cohort_items)
|
|
pd.testing.assert_frame_equal(scores, again)
|
|
|
|
|
|
def test_registered_under_the_association_groups():
|
|
"""Pins down: both implementations resolve through the entry points and pass the association protocol, and
|
|
the per-study pipeline does not load them. Fails if a registration is dropped or the association lands in the
|
|
pipeline's module groups."""
|
|
from tea.pipeline import registry
|
|
|
|
assert registry.association("ados2_association").impl == "modern"
|
|
assert registry.association("ados2_association", "legacy").impl == "legacy"
|
|
assert "ados2_association" not in registry.available("modern")
|
|
|
|
|
|
def test_a_module_the_fit_never_saw_is_not_scored_as_the_reference(fits, cohort_items):
|
|
"""Pins down: a child whose module was not in the pair's fit (here an unknown `MODULO_3`) gets no probability
|
|
instead of the reference module's. Fails if unseen levels fall back to all-zero indicators."""
|
|
m = fits["modern", "domain"]
|
|
other = cohort_items.head(3).assign(ados_module="MODULO_3", key=["x-1", "x-2", "x-3"])
|
|
assert m.score(other).empty
|
|
|
|
|
|
def test_a_singular_pair_or_an_infinite_z_does_not_stop_the_fit(cohort_css):
|
|
"""Pins down: a predictor equal to the module indicator (a rank-deficient design) leaves that pair with a reason
|
|
and no estimate while every other pair is fitted, and an infinite z is dropped rather than fitted. Fails if a
|
|
singular information matrix aborts the whole fit, or `inf` reaches the design."""
|
|
t = cohort_css.copy()
|
|
t["z_gradient"] = (t["ados_module"] == "TODDLER").astype(float)
|
|
t.loc[0, "z_posterior_rhythm"] = np.inf
|
|
a = Ados2Association().fit(t).associations().set_index(["biomarker", "zone"])
|
|
assert a["odds_ratio"].notna().sum() >= len(a) - 2
|
|
assert a.loc[("posterior_rhythm", "posterior"), "n"] == len(t) - 1
|