ADOS-2 scoring step in the indicators cycle, run after the document import commits; EEG analysis ordered before the relation steps
This commit is contained in:
@@ -0,0 +1,60 @@
|
|||||||
|
"""What this module covers: the cycle's `score_ados2` step (TEA's ADOS-2 CSS and classification, before the
|
||||||
|
association and the silver load) and how the cycle gets the scoring (`webapi.orchestration.eeg.live_ados2_scoring`).
|
||||||
|
|
||||||
|
Fixtures: none; the graph is built from `webapi.orchestration.cycle` and the scoring is a stand-in.
|
||||||
|
"""
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from hamilton import driver
|
||||||
|
|
||||||
|
from webapi.orchestration import cycle, run, steps_of
|
||||||
|
from webapi.orchestration.context import Context
|
||||||
|
from webapi.orchestration.eeg import SCORING_ENV, live_ados2_scoring
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||||
|
def test_the_scoring_runs_before_the_analysis_the_association_and_the_load(proyecto):
|
||||||
|
"""Pins down: `score_ados2` needs only the migrated schema and `analyze_eeg` waits for it, so the CSS is written
|
||||||
|
in seconds instead of after a long EEG analysis, and still before the association and the silver load read it.
|
||||||
|
Fails if the scoring moves after the analysis, the association or the load."""
|
||||||
|
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
|
||||||
|
deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
|
||||||
|
assert deps["score_ados2"] == {"migrate"}
|
||||||
|
assert deps["analyze_eeg"] == {"migrate", "score_ados2"}
|
||||||
|
order = steps_of(proyecto)
|
||||||
|
assert order.index("score_ados2") < order.index("analyze_eeg") < order.index("relate_ados2") < order.index("load")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_step_returns_the_scorings_summary_or_nothing():
|
||||||
|
"""Pins down: without a scoring the step is a no-op, and with one it runs it once and returns its summary as a
|
||||||
|
dict. Fails if the step scores when nobody configured it, or stops reporting what it did."""
|
||||||
|
assert [(p.name, p.summary) for p in run(Context("cacu", 2025, 2025), only=["score_ados2"])] == [
|
||||||
|
("score_ados2", {})]
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def scoring():
|
||||||
|
calls.append(1)
|
||||||
|
from models.ados2_scoring import Summary
|
||||||
|
|
||||||
|
return Summary(evaluations=5, scored=4, unscored=1)
|
||||||
|
|
||||||
|
pasos = run(Context("tea", 2025, 2025, ados2_scoring=scoring, repos=SimpleNamespace()), only=["score_ados2"])
|
||||||
|
assert calls == [1]
|
||||||
|
assert pasos[0].summary == {"evaluations": 5, "scored": 4, "unscored": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_tea_has_the_scoring_and_it_can_be_turned_off(monkeypatch):
|
||||||
|
"""Pins down: TEA's cycle gets `models.ados2_scoring.score_pending`, the other domains none, `ADOS2_SCORING=off`
|
||||||
|
leaves it out and an unknown value is refused. Fails if another domain starts scoring, `off` stops working, or
|
||||||
|
a mistyped value silently counts as on."""
|
||||||
|
from models.ados2_scoring import score_pending
|
||||||
|
|
||||||
|
monkeypatch.delenv(SCORING_ENV, raising=False)
|
||||||
|
assert live_ados2_scoring("tea") is score_pending
|
||||||
|
assert live_ados2_scoring("cama") is None
|
||||||
|
monkeypatch.setenv(SCORING_ENV, "off")
|
||||||
|
assert live_ados2_scoring("tea") is None
|
||||||
|
monkeypatch.setenv(SCORING_ENV, "maybe")
|
||||||
|
with pytest.raises(ValueError, match=SCORING_ENV):
|
||||||
|
live_ados2_scoring("tea")
|
||||||
@@ -58,15 +58,15 @@ def fake_analysis(tea_base):
|
|||||||
|
|
||||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||||
def test_the_eeg_analysis_runs_before_the_silver_load(proyecto):
|
def test_the_eeg_analysis_runs_before_the_silver_load(proyecto):
|
||||||
"""Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema.
|
"""Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema and the quick ADOS-2 scoring.
|
||||||
|
|
||||||
Fails if `load` stops waiting for the analysis (the cycle would load an EEG's old analysis and pick the new one up
|
Fails if `load` stops waiting for the analysis (the cycle would load an EEG's old analysis and pick the new one up
|
||||||
only on the next cycle), or the analysis starts waiting for steps it doesn't need.
|
only on the next cycle), or the analysis starts waiting for steps other than the migration and the scoring.
|
||||||
"""
|
"""
|
||||||
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
|
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
|
||||||
deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
|
deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
|
||||||
assert "analyze_eeg" in deps["load"]
|
assert "analyze_eeg" in deps["load"]
|
||||||
assert deps["analyze_eeg"] == {"migrate"}
|
assert deps["analyze_eeg"] == {"migrate", "score_ados2"}
|
||||||
order = steps_of(proyecto)
|
order = steps_of(proyecto)
|
||||||
assert order.index("analyze_eeg") < order.index("load")
|
assert order.index("analyze_eeg") < order.index("load")
|
||||||
|
|
||||||
|
|||||||
@@ -200,6 +200,27 @@ def test_an_import_into_tea_queues_its_recomputation(client):
|
|||||||
assert body["indicadores_en_recalculo"] is True
|
assert body["indicadores_en_recalculo"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_ados2_import_scores_the_evaluations_it_wrote(client):
|
||||||
|
"""Pins down: after a commit that wrote `tea.Ados2` rows, their CSS and classification are computed from the
|
||||||
|
stored items, module and the child's age, without waiting for the cycle; a value the source gave stays. Fails if
|
||||||
|
the commit stops scoring (the CSS would wait for the next cycle, behind any EEG analysis) or scores over a value
|
||||||
|
the source supplied."""
|
||||||
|
patient = _json_source([{"pac_id": 9100, "pac_id_hospital": "T-ADOS", "pac_fecha_nacimiento": "2022-01-01"}],
|
||||||
|
target="tea.Pacientes", column_mapping={"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital",
|
||||||
|
"pac_fecha_nacimiento": "pac_fecha_nacimiento"})
|
||||||
|
client.post("/imports/commit", json={"sources": [patient], "on_conflict": "upsert"})
|
||||||
|
items = {"ado_sa_b1": 2, "ado_sa_b2": 2, "ado_sa_b3": 2, "ado_sa_b4": 2, "ado_rrb_d1": 2, "ado_rrb_d2": 2}
|
||||||
|
rows = [{"ado_id": "a-1", "ado_pac_id": 9100, "ado_fecha": "2026-01-01", "ado_modulo": "MODULO_3", **items},
|
||||||
|
{"ado_id": "a-2", "ado_pac_id": 9100, "ado_fecha": "2026-01-01", "ado_modulo": "MODULO_3", "ado_css": 9,
|
||||||
|
"ado_clasificacion": "AUTISMO", **items}]
|
||||||
|
ados = _json_source(rows, target="tea.Ados2", column_mapping={k: k for k in rows[0] | rows[1]})
|
||||||
|
body = client.post("/imports/commit", json={"sources": [ados], "on_conflict": "upsert"}).get_json()
|
||||||
|
assert body["results"][0]["created"] == 2
|
||||||
|
stored = {r["ado_id"]: r for r in client.get("/data/tea.Ados2").get_json()["rows"]}
|
||||||
|
assert (stored["a-1"]["ado_css"], stored["a-1"]["ado_clasificacion"]) == (7, "AUTISMO")
|
||||||
|
assert stored["a-2"]["ado_css"] == 9
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def sql_source_db(tmp_path):
|
def sql_source_db(tmp_path):
|
||||||
db_path = tmp_path / "external_source.db"
|
db_path = tmp_path / "external_source.db"
|
||||||
|
|||||||
@@ -384,6 +384,23 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
|
|||||||
return reports
|
return reports
|
||||||
|
|
||||||
|
|
||||||
|
def _score_ados2_after(domain: str, results: list) -> None:
|
||||||
|
"""After a commit that wrote ADOS-2 evaluations, their CSS and classification from the items just stored, so they
|
||||||
|
exist before the recomputation (which may be queued behind a long EEG analysis). Best-effort, like the request
|
||||||
|
for the recomputation: the rows are saved, and the cycle's `score_ados2` step scores whatever this missed."""
|
||||||
|
if not any(r.target == "tea.Ados2" and (r.created or r.updated) for r in results):
|
||||||
|
return
|
||||||
|
from webapi.orchestration.eeg import live_ados2_scoring
|
||||||
|
|
||||||
|
scoring = live_ados2_scoring(domain)
|
||||||
|
if scoring is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
scoring()
|
||||||
|
except Exception:
|
||||||
|
log.exception("no se pudo calcular el CSS del ADOS-2 de %s", domain)
|
||||||
|
|
||||||
|
|
||||||
@imports_bp.post("/commit")
|
@imports_bp.post("/commit")
|
||||||
def commit():
|
def commit():
|
||||||
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
||||||
@@ -404,6 +421,7 @@ def commit():
|
|||||||
import_audit.record(audit)
|
import_audit.record(audit)
|
||||||
recalculating = False
|
recalculating = False
|
||||||
if audit.domain in DOMAINS and any(r.created or r.updated for r in results):
|
if audit.domain in DOMAINS and any(r.created or r.updated for r in results):
|
||||||
|
_score_ados2_after(audit.domain, results)
|
||||||
try:
|
try:
|
||||||
RecomputationQueue().request_run(audit.domain)
|
RecomputationQueue().request_run(audit.domain)
|
||||||
recalculating = True
|
recalculating = True
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ Each step is a function of `cycle.py`. It takes the `Context` and, as parameters
|
|||||||
Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by
|
Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by
|
||||||
Persistance's repositories (`ctx.repos`), so each one can run on its own.
|
Persistance's repositories (`ctx.repos`), so each one can run on its own.
|
||||||
|
|
||||||
migrate -> catalogs, registry, definitions, analyze_eeg
|
migrate -> catalogs, registry, definitions, score_ados2
|
||||||
|
score_ados2 -> analyze_eeg (TEA: the ADOS-2 CSS and classification, quick)
|
||||||
analyze_eeg -> relate_ados2, load (TEA: the EEG analysis)
|
analyze_eeg -> relate_ados2, load (TEA: the EEG analysis)
|
||||||
relate_ados2 -> load (TEA: the ADOS-2 association)
|
relate_ados2 -> load (TEA: the ADOS-2 association)
|
||||||
catalogs -> load, check_silver
|
catalogs -> load, check_silver
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ from datetime import date
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from webapi.orchestration.context import Context
|
from webapi.orchestration.context import Context
|
||||||
from webapi.orchestration.eeg import live_ados2_relation, live_eeg_analysis
|
from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
|
||||||
from webapi.orchestration.estimators import live_estimators
|
from webapi.orchestration.estimators import live_estimators
|
||||||
from webapi.orchestration.runner import run
|
from webapi.orchestration.runner import run
|
||||||
|
|
||||||
@@ -46,7 +46,8 @@ def main(argv: list[str] | None = None) -> None:
|
|||||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||||
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
|
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
|
||||||
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project),
|
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project),
|
||||||
ados2_relation=live_ados2_relation(args.project))
|
ados2_relation=live_ados2_relation(args.project),
|
||||||
|
ados2_scoring=live_ados2_scoring(args.project))
|
||||||
for paso in run(ctx, only=args.only):
|
for paso in run(ctx, only=args.only):
|
||||||
print(f"{paso.name:20} {paso.seconds:6.1f} s")
|
print(f"{paso.name:20} {paso.seconds:6.1f} s")
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ class Context:
|
|||||||
# The domain's EEG analysis (`webapi.orchestration.eeg.live_eeg_analysis`): run by the `analyze_eeg` step before
|
# The domain's EEG analysis (`webapi.orchestration.eeg.live_eeg_analysis`): run by the `analyze_eeg` step before
|
||||||
# the silver load, it writes the analysis of each stored EDF to bronze. Without it, that step does nothing.
|
# the silver load, it writes the analysis of each stored EDF to bronze. Without it, that step does nothing.
|
||||||
eeg_analysis: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
eeg_analysis: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
||||||
|
# The domain's ADOS-2 scoring (`webapi.orchestration.eeg.live_ados2_scoring`): run by the `score_ados2` step, it
|
||||||
|
# writes each evaluation's CSS and classification from its items. Without it, that step does nothing.
|
||||||
|
ados2_scoring: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
||||||
# The domain's ADOS-2 association (`webapi.orchestration.eeg.live_ados2_relation`): run by the `relate_ados2` step
|
# The domain's ADOS-2 association (`webapi.orchestration.eeg.live_ados2_relation`): run by the `relate_ados2` step
|
||||||
# after the EEG analysis, it fits the model on the analysed EEGs. Without it, that step does nothing.
|
# after the EEG analysis, it fits the model on the analysed EEGs. Without it, that step does nothing.
|
||||||
ados2_relation: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
ados2_relation: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
||||||
|
|||||||
@@ -82,16 +82,26 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
|
|||||||
return counts
|
return counts
|
||||||
|
|
||||||
|
|
||||||
def analyze_eeg(migrate: str, ctx: Context) -> dict[str, int]:
|
def analyze_eeg(migrate: str, score_ados2: dict, ctx: Context) -> dict[str, int]:
|
||||||
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
|
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
|
||||||
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica`, `eeg_metrica_electrodo`
|
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica`, `eeg_metrica_electrodo`
|
||||||
and `eeg_metrica_zona`.
|
and `eeg_metrica_zona`.
|
||||||
|
Waits for `score_ados2` only so the quick scoring doesn't queue behind a long analysis.
|
||||||
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
|
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
|
||||||
if ctx.eeg_analysis is None:
|
if ctx.eeg_analysis is None:
|
||||||
return {}
|
return {}
|
||||||
return asdict(ctx.eeg_analysis())
|
return asdict(ctx.eeg_analysis())
|
||||||
|
|
||||||
|
|
||||||
|
def score_ados2(migrate: str, ctx: Context) -> dict:
|
||||||
|
"""The CSS and classification of each ADOS-2 from its items, module, algorithm and the child's age
|
||||||
|
(`ctx.ados2_scoring`), written to bronze before the association and `load` read them. Returns how many
|
||||||
|
evaluations were scored; nothing without a scoring (every domain but TEA)."""
|
||||||
|
if ctx.ados2_scoring is None:
|
||||||
|
return {}
|
||||||
|
return asdict(ctx.ados2_scoring())
|
||||||
|
|
||||||
|
|
||||||
def relate_ados2(analyze_eeg: dict[str, int], ctx: Context) -> dict:
|
def relate_ados2(analyze_eeg: dict[str, int], ctx: Context) -> dict:
|
||||||
"""The ADOS-2 association fitted on the EEGs the analysis left (`ctx.ados2_relation`), written to
|
"""The ADOS-2 association fitted on the EEGs the analysis left (`ctx.ados2_relation`), written to
|
||||||
`relacion_ados2` and `relacion_ados2_paciente` before `load`, so the same cycle's gold views show it. Returns
|
`relacion_ados2` and `relacion_ados2_paciente` before `load`, so the same cycle's gold views show it. Returns
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ ADOS-2 association fitted on what it left.
|
|||||||
`EEG_ANALYSIS_CLUSTER` says where the batch runs: `auto` (the default: the scheduler in `DASK_SCHEDULER_ADDRESS` if
|
`EEG_ANALYSIS_CLUSTER` says where the batch runs: `auto` (the default: the scheduler in `DASK_SCHEDULER_ADDRESS` if
|
||||||
set, otherwise a local cluster), `local`, `remote`, `sync` (in the cycle's own process), or `off`, which leaves the
|
set, otherwise a local cluster), `local`, `remote`, `sync` (in the cycle's own process), or `off`, which leaves the
|
||||||
analysis out of the cycle (`python -m models tea analyze` and `POST /governance/eeg/run` still run it).
|
analysis out of the cycle (`python -m models tea analyze` and `POST /governance/eeg/run` still run it).
|
||||||
|
`ADOS2_SCORING=off` leaves the ADOS-2 CSS and classification out of the cycle (`python -m models tea score-ados2`
|
||||||
|
still computes them).
|
||||||
`ADOS2_RELATION=off` leaves the association out (`python -m models tea relate-ados2` still runs it).
|
`ADOS2_RELATION=off` leaves the association out (`python -m models tea relate-ados2` still runs it).
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
@@ -14,6 +16,7 @@ from typing import Any
|
|||||||
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
|
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
|
||||||
CLUSTERS = ("auto", "local", "remote", "sync")
|
CLUSTERS = ("auto", "local", "remote", "sync")
|
||||||
RELATION_ENV = "ADOS2_RELATION"
|
RELATION_ENV = "ADOS2_RELATION"
|
||||||
|
SCORING_ENV = "ADOS2_SCORING"
|
||||||
|
|
||||||
|
|
||||||
def cluster() -> str:
|
def cluster() -> str:
|
||||||
@@ -42,3 +45,15 @@ def live_ados2_relation(domain: str) -> Callable[[], Any] | None:
|
|||||||
from models.ados2_relation import relate
|
from models.ados2_relation import relate
|
||||||
|
|
||||||
return relate
|
return relate
|
||||||
|
|
||||||
|
|
||||||
|
def live_ados2_scoring(domain: str) -> Callable[[], Any] | None:
|
||||||
|
"""The domain's ADOS-2 scoring for the cycle, or none: only TEA has one, and `off` leaves it out."""
|
||||||
|
value = os.environ.get(SCORING_ENV, "on")
|
||||||
|
if value not in ("on", "off"):
|
||||||
|
raise ValueError(f"{SCORING_ENV} must be on or off, not {value!r}")
|
||||||
|
if domain != "tea" or value == "off":
|
||||||
|
return None
|
||||||
|
from models.ados2_scoring import score_pending
|
||||||
|
|
||||||
|
return score_pending
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ class RecomputationQueue:
|
|||||||
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||||
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
|
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
|
||||||
from webapi.orchestration import Context, run, steps_of
|
from webapi.orchestration import Context, run, steps_of
|
||||||
from webapi.orchestration.eeg import live_ados2_relation, live_eeg_analysis
|
from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
|
||||||
from webapi.orchestration.estimators import live_estimators
|
from webapi.orchestration.estimators import live_estimators
|
||||||
|
|
||||||
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
||||||
@@ -117,7 +117,8 @@ class RecomputationQueue:
|
|||||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||||
try:
|
try:
|
||||||
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
|
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
|
||||||
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio))
|
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
|
||||||
|
ados2_scoring=live_ados2_scoring(dominio))
|
||||||
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
||||||
entrada.update(
|
entrada.update(
|
||||||
estado="ok",
|
estado="ok",
|
||||||
|
|||||||
Reference in New Issue
Block a user