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}) fit = a.firth(frame, "event", "z", ()) assert np.isfinite(fit["odds_ratio"]) assert fit["ci_low"] < fit["odds_ratio"] < fit["ci_high"] def test_bh(): np.testing.assert_allclose(a.bh([0.04, 0.01, np.nan, 0.03]), [0.04, 0.03, np.nan, 0.04]) def test_ordinal_on_monotone_trend(): frame = pd.DataFrame({"z": np.arange(12), "level": [0, 0, 1, 0, 1, 1, 2, 0, 2, 1, 2, 2]}) assert a.ordinal(frame, "level", "z", (), high=2)["odds_ratio"] > 1 def test_ordinal_separated_binary_predictor(): frame = pd.DataFrame({"z": [0] * 8 + [1] * 8, "level": [0, 1] * 4 + [3, 4] * 4}) fit = a.ordinal(frame, "level", "z", (), high=3) assert fit["reason"] == "does not converge (separation)" 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()