ADOS-2 association model: Firth/ordinal port, MLflow model, bronze and gold, gate
Port the association estimator and add its source-parity tests in models. Wire cohort selection, fingerprint deduplication, MLflow registration, and champion scoring into the TEA jobs. Add both bronze tables, gold models and key tests, and extend the existing WebApi hospital gate. Follow the spec's resolved silver/bronze cohort and full CSV fingerprint. No adaptations beyond the resolved spec. Preserve the source numerical code with Ruff formatting and reflowed docstrings. Internal choices: - Select the first ADOS-2 with a SQL window and assemble predictor columns by EDF in pandas. Normalize dates to days across SQLite and PostgreSQL and use the undated CSS path if evaluation date is absent. - Treat unstaged analysis or score tables as empty inputs. Retain the existing as_of argument without a cutoff in the specified cohort. - Keep missing and non-finite report and bronze values as null, including open confidence limits. Store counts as bigint and direction as boolean. Reuse the EEG bronze merge writer after deleting the prior projection. - Use a NumPy default_rng seeded with 0, uniform ages, normal predictors, and independent draws of module, item codes, and CSS for source parity. Load the reference modules in a test-only namespace with stub contracts. - Record model and WebApi changes in their existing submodule branches and update the corresponding gitlinks in the parent commit. Checks: Ruff lint and format check passed. lint-imports kept both contracts. The association unit suite passed all five tests. Eight lightweight TEA job tests passed, with two integration tests deselected. SQLite smoke checks passed for cohort, registration and deduplication, promotion, prediction, bronze writes, and both dbt models and their four key tests. Fixture replay matched the 15 published pairs and 470 published scores. The full hospital API gate runs on the test machines.
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
"""The association fit and its parity with the pinned tea-lib source."""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core.tea import ADOS2_ITEMS
|
||||
from models.tea import association as a
|
||||
|
||||
REFERENCE = Path("/home/milk/tea-parity/specs/P2-ref")
|
||||
MODULES = {"toddler": "TODDLER", "module_1": "MODULO_1", "module_2": "MODULO_2"}
|
||||
ZONES = dict(zip(
|
||||
a.ZONE_ITEMS,
|
||||
("frontal_izq", "frontal_der", "frontal_media", "central", "parietal",
|
||||
"temporal_izq", "temporal_der", "occipital"),
|
||||
strict=True,
|
||||
)) # fmt: skip
|
||||
|
||||
|
||||
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_pairs_and_item_availability():
|
||||
assert len(a.pairs("item")) == 41
|
||||
assert len(a.pairs("domain")) == 15
|
||||
# Item order in the source, translated by meaning into the platform catalog names.
|
||||
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
|
||||
frame = pd.DataFrame(
|
||||
{
|
||||
"ados_module": ["toddler", "module_1", "module_2", "module_3"],
|
||||
"vocalization_directed": [3, 7, 1, 1],
|
||||
}
|
||||
)
|
||||
np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan])
|
||||
|
||||
|
||||
def _reference(monkeypatch):
|
||||
package = ModuleType("p2_reference")
|
||||
package.__path__ = [str(REFERENCE)]
|
||||
contracts = ModuleType("tea.contracts")
|
||||
contracts.ZONES = tuple(ZONES.values())
|
||||
contracts.ASSOCIATION_COLUMNS = a.ASSOCIATION_COLUMNS
|
||||
contracts.SCORE_COLUMNS = a.SCORE_COLUMNS
|
||||
contracts.CONTRACT_VERSION = None
|
||||
monkeypatch.setitem(sys.modules, "p2_reference", package)
|
||||
monkeypatch.setitem(sys.modules, "tea.contracts", contracts)
|
||||
for name in ("_items", "_models", "api"):
|
||||
qualified = f"p2_reference.{name}"
|
||||
spec = importlib.util.spec_from_file_location(qualified, REFERENCE / f"{name}.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, qualified, module)
|
||||
spec.loader.exec_module(module)
|
||||
return sys.modules["p2_reference.api"]
|
||||
|
||||
|
||||
def test_reference_parity(monkeypatch):
|
||||
ref = _reference(monkeypatch)
|
||||
rng = np.random.default_rng(0)
|
||||
cohort = pd.DataFrame(
|
||||
{
|
||||
"key": range(50),
|
||||
"age_months": rng.uniform(16, 48, 50),
|
||||
"ados_module": rng.choice(list(MODULES), 50),
|
||||
"css": rng.integers(1, 11, 50),
|
||||
**{item: rng.choice([0, 1, 2, 3, 7, 8], 50) for item in ADOS2_ITEMS},
|
||||
**{
|
||||
predictor: rng.normal(size=50)
|
||||
for predictor in dict.fromkeys(pair["predictor"] for pair in a.pairs("item"))
|
||||
},
|
||||
}
|
||||
)
|
||||
other = cohort.drop(columns=ADOS2_ITEMS).copy()
|
||||
other["ados_module"] = other["ados_module"].map(MODULES)
|
||||
for number, (_, _, modules) in ref.it.ITEMS.items():
|
||||
for module, code in modules.items():
|
||||
chosen = other["ados_module"] == module
|
||||
other.loc[chosen, code] = cohort.loc[chosen, ADOS2_ITEMS[number - 1]]
|
||||
other = other.rename(
|
||||
columns={
|
||||
f"z_{b}_{zone}": f"z_{b}_{old}"
|
||||
for zone, old in ZONES.items()
|
||||
for b in ("spikes", "spindles")
|
||||
}
|
||||
)
|
||||
ours = a.Ados2Association().fit(cohort)
|
||||
theirs = ref.Ados2Association().fit(other)
|
||||
for actual, expected in (
|
||||
(ours.associations(), theirs.associations()),
|
||||
(a.Model(ours.fitted).predict(None, cohort), theirs.score(other)),
|
||||
):
|
||||
actual["zone"] = actual["zone"].replace(ZONES)
|
||||
pd.testing.assert_frame_equal(actual, expected, check_exact=True)
|
||||
Reference in New Issue
Block a user