From 6d653e9f17a9c4aa42f6c07a08878f6fa86cae63 Mon Sep 17 00:00:00 2001 From: ulises Date: Sun, 22 Nov 2026 22:01:50 -0600 Subject: [PATCH] TEA: score ADOS-2 evaluations from their items (calibrated severity score and classification) with a score-ados2 command; tea library pointer --- libs/tea | 2 +- models/__main__.py | 13 ++++ models/ados2_scoring.py | 61 +++++++++++++++++++ tests/tea/test_ados2_scoring.py | 104 ++++++++++++++++++++++++++++++++ 4 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 models/ados2_scoring.py create mode 100644 tests/tea/test_ados2_scoring.py diff --git a/libs/tea b/libs/tea index 24e7824..fcf8e6e 160000 --- a/libs/tea +++ b/libs/tea @@ -1 +1 @@ -Subproject commit 24e7824fe763fea19df4651d5d6d39f1740523e4 +Subproject commit fcf8e6ef03b54d0c1bbd7447f0e9a9009ffe31fe diff --git a/models/__main__.py b/models/__main__.py index ca3c08c..5a0cf9c 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -171,6 +171,15 @@ def _tea_analyze(args: argparse.Namespace) -> int: return 1 if s.failed else 0 +def _tea_score_ados2(args: argparse.Namespace) -> int: + """The ADOS-2 CSS and classification from the stored item scores (`models.ados2_scoring`).""" + from models.ados2_scoring import score_pending + + s = score_pending(overwrite=args.all) + print(f"{s.evaluations} evaluations: {s.scored} scored, {s.unscored} without enough to score") + return 0 + + def _tea_relate_ados2(args: argparse.Namespace) -> int: """The ADOS-2 association fitted on the analysed EEGs (`models.ados2_relation`).""" from models.ados2_relation import relate @@ -536,6 +545,10 @@ def build_parser() -> argparse.ArgumentParser: analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto", help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process") analyze.set_defaults(run=_tea_analyze) + score_ados2 = tea_actions.add_parser( + "score-ados2", help="compute the ADOS-2 CSS and classification from the item scores, module and age") + score_ados2.add_argument("--all", action="store_true", help="also recompute values already stored") + score_ados2.set_defaults(run=_tea_score_ados2) relate_ados2 = tea_actions.add_parser( "relate-ados2", help="fit the ADOS-2 association on the analysed EEGs and store it as a new version") relate_ados2.set_defaults(run=_tea_relate_ados2) diff --git a/models/ados2_scoring.py b/models/ados2_scoring.py new file mode 100644 index 0000000..93c5dc8 --- /dev/null +++ b/models/ados2_scoring.py @@ -0,0 +1,61 @@ +"""The ADOS-2 CSS and classification against the TEA database: each evaluation's item scores, module, algorithm and +the child's age at the evaluation go through `tea.scoring`, and the result is written to `ado_css` and +`ado_clasificacion`. + +A value a source already gave is kept unless `overwrite` is set. An evaluation without items or module is left as +it is. +""" +from __future__ import annotations + +from dataclasses import dataclass + +from sqlmodel import Session, select + +from core.tea.models import ADOS2_ITEMS, Ados2, Pacientes +from tea.scoring import score + +DAYS_PER_MONTH = 30.4375 + + +@dataclass +class Summary: + evaluations: int = 0 + scored: int = 0 + unscored: int = 0 + + +def age_months(born, on) -> float | None: + if born is None or on is None: + return None + return (on - born).days / DAYS_PER_MONTH + + +def score_all(session: Session, *, overwrite: bool = False) -> Summary: + """Scores every evaluation in the session's database and commits.""" + births = dict(session.exec(select(Pacientes.pac_id, Pacientes.pac_fecha_nacimiento)).all()) + summary = Summary() + for row in session.exec(select(Ados2)).all(): + summary.evaluations += 1 + if not overwrite and row.ado_css is not None and row.ado_clasificacion is not None: + continue + items = {code: getattr(row, f"ado_{code}") for code in ADOS2_ITEMS} + result = score(row.ado_modulo, items, age_months=age_months(births.get(row.ado_pac_id), row.ado_fecha), + algorithm=row.ado_algoritmo) + if result is None or (result.css is None and result.classification is None): + summary.unscored += 1 + continue + if overwrite or row.ado_css is None: + row.ado_css = result.css if result.css is not None else row.ado_css + if overwrite or row.ado_clasificacion is None: + row.ado_clasificacion = result.classification or row.ado_clasificacion + session.add(row) + summary.scored += 1 + session.commit() + return summary + + +def score_pending(*, overwrite: bool = False) -> Summary: + from persistance.tea import relacion_ados2_repository + + with relacion_ados2_repository.open_session() as session: + return score_all(session, overwrite=overwrite) diff --git a/tests/tea/test_ados2_scoring.py b/tests/tea/test_ados2_scoring.py new file mode 100644 index 0000000..fabd499 --- /dev/null +++ b/tests/tea/test_ados2_scoring.py @@ -0,0 +1,104 @@ +"""What this module covers: the ADOS-2 totals, CSS and classification of `tea.scoring`, and the job that writes +them to the TEA database (`models.ados2_scoring`). + +Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, a child born 2022-01-01 with three Module 3 evaluations +(items summing to 12, no CSS), one Module 1 evaluation (some words, items summing to 6) and one evaluation that +already carries a CSS of 9 and a classification from its source. +""" +from datetime import date + +import pytest +from sqlmodel import Session, select + +from core.tea.models import Ados2, Pacientes +from models import ados2_scoring +from tea.scoring import score + +ITEMS_12 = {"sa_b1": 2, "sa_b2": 2, "sa_b3": 2, "sa_b4": 2, "rrb_d1": 2, "rrb_d2": 2} + + +def test_a_score_of_three_counts_as_two(): + """Pins down: item scores above 2 are capped at 2, as the algorithms do. Fails if the cap is dropped (the + total would be 8, not 4).""" + s = score("MODULO_3", {"sa_b1": 3, "sa_b2": 3, "rrb_d1": 3, "rrb_d2": 3}) + assert (s.social_affect, s.restricted_repetitive, s.total) == (4, 4, 8) + + +def test_the_css_rises_with_the_total_and_the_classification_follows_it(): + """Pins down: for one module a higher total never gives a lower CSS, and the classification is no-spectrum + under CSS 3, spectrum from 3 and autism from 5. Fails if a cut-point row stops being ordered or the + classification thresholds move.""" + codes = [f"sa_b{i}" for i in range(1, 13)] + ["rrb_d1", "rrb_d2", "rrb_d4", "rrb_d5"] + scores = [score("MODULO_3", {c: 2 if i < n else 0 for i, c in enumerate(codes)}) for n in range(0, 17)] + css = [s.css for s in scores] + assert css == sorted(css) and css[0] == 1 and css[-1] == 10 + assert [scores[0].classification, scores[3].classification, scores[8].classification] == [ + "NO_ESPECTRO", "ESPECTRO_AUTISTA", "AUTISMO"] + + +@pytest.mark.parametrize("module, age, algorithm, expected", [ + ("MODULO_1", None, "Algunas palabras", None), + ("MODULO_1", 40.0, None, None), + ("MODULO_2", None, None, None), + ("MODULO_3", None, None, 7), +]) +def test_a_table_that_needs_age_or_language_level_gives_no_css_without_them(module, age, algorithm, expected): + """Pins down: Modules 1 and 2 give no CSS without the child's age (and Module 1 without its algorithm), Module 3 + needs neither. Fails if a missing age silently picks a table.""" + assert score(module, ITEMS_12, age_months=age, algorithm=algorithm).css == expected + + +def test_the_toddler_module_gives_a_range_of_concern_and_no_css(): + """Pins down: Toddler totals become a classification by age band and never a CSS: a total of 12 is mild to + moderate at 25 months and at 19, 9 is none at 19 but mild to moderate at 25. Fails if Toddler starts + returning a CSS or the two age bands share cut points.""" + t12 = {**{f"sa_b{i}": 2 for i in (1, 4, 5, 6)}, "rrb_d1": 2, "rrb_d2": 2} + t9 = {**{f"sa_b{i}": 2 for i in (1, 4, 5)}, "rrb_d1": 2, "rrb_d2": 1} + assert [score("TODDLER", t12, age_months=m).classification for m in (19, 25)] == ["PREOCUPACION_LEVE_MODERADA"] * 2 + assert [score("TODDLER", t9, age_months=m).classification for m in (19, 25)] == [ + "NO_ESPECTRO", "PREOCUPACION_LEVE_MODERADA"] + assert score("TODDLER", t12, age_months=25).css is None + + +def test_an_unknown_module_or_missing_domain_is_not_scored(): + """Pins down: no score without a known module or without items in both domains. Fails if a half-read PDF is + scored from one domain.""" + assert score(None, ITEMS_12) is None + assert score("MODULO_9", ITEMS_12) is None + assert score("MODULO_3", {"sa_b1": 2}) is None + + +@pytest.fixture +def stored(tea_db): + """Child 1 (born 2022-01-01) with the evaluations the module docstring lists.""" + from persistance.db import get_tea_engine + + with Session(get_tea_engine()) as s: + s.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2022, 1, 1))) + for i in (1, 2, 3): + s.add(Ados2(ado_id=f"a-{i}", ado_pac_id=1, ado_fecha=date(2026, 1, 1), ado_modulo="MODULO_3", + **{f"ado_{k}": v for k, v in ITEMS_12.items()})) + s.add(Ados2(ado_id="m1", ado_pac_id=1, ado_fecha=date(2025, 1, 1), ado_modulo="MODULO_1", + ado_algoritmo="Algunas palabras", ado_sa_a2=2, ado_sa_b1=2, ado_sa_b3=1, ado_rrb_d1=1)) + s.add(Ados2(ado_id="given", ado_pac_id=1, ado_fecha=date(2026, 1, 1), ado_modulo="MODULO_3", ado_css=9, + ado_clasificacion="AUTISMO", **{f"ado_{k}": v for k, v in ITEMS_12.items()})) + s.commit() + yield s + + +def test_the_job_fills_what_is_empty_and_keeps_what_a_source_gave(stored): + """Pins down: `score_all` writes CSS and classification on evaluations that lack them, uses the age at the + evaluation (3 years for the Module 1 one, so the under-five table) and leaves a stored CSS alone. Fails if it + overwrites a source's value by default or reads the wrong age.""" + summary = ados2_scoring.score_all(stored) + assert (summary.evaluations, summary.scored) == (5, 4) + rows = {r.ado_id: r for r in stored.exec(select(Ados2)).all()} + assert rows["a-1"].ado_css == 7 and rows["a-1"].ado_clasificacion == "AUTISMO" + assert rows["m1"].ado_css == 3 and rows["m1"].ado_clasificacion == "ESPECTRO_AUTISTA" + assert rows["given"].ado_css == 9 + + +def test_overwrite_recomputes_what_a_source_gave(stored): + """Pins down: with `overwrite` the stored CSS is recomputed from the items. Fails if `overwrite` is ignored.""" + ados2_scoring.score_all(stored, overwrite=True) + assert stored.get(Ados2, "given").ado_css == 7