diff --git a/tests/test_ados2_relation_step.py b/tests/test_ados2_relation_step.py new file mode 100644 index 0000000..09081ff --- /dev/null +++ b/tests/test_ados2_relation_step.py @@ -0,0 +1,60 @@ +"""What this module covers: the cycle's `relate_ados2` step (TEA's ADOS-2 association, after the EEG analysis and +before the silver load) and how the cycle gets the association (`webapi.orchestration.eeg.live_ados2_relation`). + +Fixtures: none; the graph is built from `webapi.orchestration.cycle` and the association 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 RELATION_ENV, live_ados2_relation + + +@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"]) +def test_the_association_runs_after_the_analysis_and_before_the_load(proyecto): + """Pins down: `relate_ados2` waits for `analyze_eeg` only, and `load` waits for it, so the same cycle's gold + views show the association fitted on that cycle's analysis. Fails if the association runs before the analysis + (it would fit on the previous one) or after 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["relate_ados2"] == {"analyze_eeg"} + assert "relate_ados2" in deps["load"] + order = steps_of(proyecto) + assert order.index("analyze_eeg") < order.index("relate_ados2") < order.index("load") + + +def test_the_step_returns_the_associations_summary_or_nothing(): + """Pins down: without an association the step is a no-op, and with one it runs it once and returns its summary + as a dict. Fails if the step runs an association nobody configured, or stops reporting what it wrote.""" + assert [(p.name, p.summary) for p in run(Context("cacu", 2025, 2025), only=["relate_ados2"])] == [ + ("relate_ados2", {})] + calls = [] + + def relation(): + calls.append(1) + from models.ados2_relation import Summary + + return Summary(version="tea-20261121T120000-abcd1234", level="domain", children=3, associations=2, scored=6) + + pasos = run(Context("tea", 2025, 2025, ados2_relation=relation, repos=SimpleNamespace()), only=["relate_ados2"]) + assert calls == [1] + assert pasos[0].summary["version"] == "tea-20261121T120000-abcd1234" and pasos[0].summary["scored"] == 6 + + +def test_only_tea_has_the_association_and_it_can_be_turned_off(monkeypatch): + """Pins down: TEA's cycle gets `models.ados2_relation.relate`, the other domains none, `ADOS2_RELATION=off` + leaves it out and an unknown value is refused. Fails if another domain starts fitting it, `off` stops working, + or a mistyped value silently counts as on.""" + from models.ados2_relation import relate + + monkeypatch.delenv(RELATION_ENV, raising=False) + assert live_ados2_relation("tea") is relate + assert live_ados2_relation("cama") is None + monkeypatch.setenv(RELATION_ENV, "off") + assert live_ados2_relation("tea") is None + monkeypatch.setenv(RELATION_ENV, "maybe") + with pytest.raises(ValueError, match=RELATION_ENV): + live_ados2_relation("tea") diff --git a/tests/test_fhir_relacion_ados2.py b/tests/test_fhir_relacion_ados2.py index 418d03b..d73975b 100644 --- a/tests/test_fhir_relacion_ados2.py +++ b/tests/test_fhir_relacion_ados2.py @@ -1,9 +1,9 @@ """What this module covers: `$resumen-tea`'s `RiskAssessment`, the ADOS-2 association model as idiomatic FHIR: one resource per patient with a prediction per association row of the latest model version that scored the study's -EEG (the clearest cohort association, lowest q, first), the model's metadata on the resource, the outcome as the -ADOS-2 item or domain with its label from the code systems, the observed outcome read from the patient's ADOS-2, -and the resource omitted entirely when no model row scored the patient's study EEG. Every resource is checked -against FHIR's models. +EEG (the clearest cohort association, lowest q, first), the model's metadata on the resource, the outcome as an +ADOS-2 item meaning or the total CSS with its label from the code systems, the observed outcome read from the patient's ADOS-2, +and the resource omitted entirely when no model row scored the patient's study EEG; and the code systems the +outcomes and zones are labelled from. Every resource is checked against FHIR's models. Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`) over TEA's fixture database (`staging.tea`) plus model and patient rows for child 1's study EEG (`eeg-1b`); needs `DBT_MANIFEST`. @@ -21,9 +21,9 @@ UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_m def _rows(sesion): - """The kit's seven children, plus a fitted model: one item row (sa_b2) and one domain row (SA) of version - 0.2.0, both scored for child 1's study EEG (eeg-1b, 20 May). Child 1's ADOS-2 (ado-1) scores sa_b2 2 and its - SA domain total is 6; no other child gets model rows.""" + """The kit's seven children, plus a fitted model: one item row (ados2_item_07, shared enjoyment) and one domain + row (CSS) of version 0.2.0, both scored for child 1's study EEG (eeg-1b, 20 May). Child 1's ADOS-2 (ado-1) is + Module 1, where item 07 is sa_b5, scored 2, and its CSS is 7; no other child gets model rows.""" from importlib import import_module import_module("staging.tea").insertar(sesion) @@ -32,11 +32,11 @@ def _rows(sesion): sesion.add_all([ RelacionAdos2(rel_id="rel-2a", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item", - rel_resultado="sa_b2", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7, + rel_resultado="ados2_item_07", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7, rel_q=0.02), RelacionAdos2(rel_id="rel-2b", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio", - rel_resultado="SA", rel_evento=">=4", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6, + rel_resultado="CSS", rel_evento=">=8", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6, rel_q=0.3), ]) sesion.add_all([ @@ -93,15 +93,15 @@ def test_the_summary_emits_the_model_as_one_risk_assessment(client): assert riesgo["basis"] == [{"reference": f"DiagnosticReport/{report['id']}"}, {"reference": f"Observation/{ados2['id']}"}] assert len(riesgo["prediction"]) == 2 - assert [p["outcome"]["coding"][0]["code"] for p in riesgo["prediction"]] == ["ados2.sa_b2", "SA"] + assert [p["outcome"]["coding"][0]["code"] for p in riesgo["prediction"]] == ["ados2_item_07", "CSS"] def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_outcome(client): - """Pins down: a prediction has the outcome as the ADOS-2 item or domain with its label from the code systems - (not from the row), the model's probability for the patient, and as extensions the EEG metric and scalp zone + """Pins down: a prediction has the outcome as the ADOS-2 item meaning or the CSS, under the outcome code system + with its label from `ADOS2_ITEM_MEANINGS` (not from the row), the model's probability for the patient, and as extensions the EEG metric and scalp zone (with labels), the patient's z, the cohort's odds ratio with its interval and q, the event as stored, the - reference probability (z = 0) and the outcome observed in the patient's ADOS-2 (the item's score 2, the SA - domain's algorithm total 6). Fails if a label starts coming from the stored row, or a value stops reaching the + reference probability (z = 0) and the outcome observed in the patient's ADOS-2 (item 07's algorithm score 2, + the CSS 7). Fails if a label starts coming from the stored row, or a value stops reaching the prediction.""" episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished")) (child_1,) = episodes @@ -109,11 +109,11 @@ def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_ (riesgo,) = resources(bundle, "RiskAssessment") item, dominio = riesgo["prediction"] assert item["outcome"]["coding"][0] == { - "system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo", "code": "ados2.sa_b2", - "display": "Sonrisa social en respuesta"} + "system": "https://isssteleon.org/fhir/CodeSystem/tea-ados2-resultado", "code": "ados2_item_07", + "display": "Disfrute compartido en la interacción"} assert dominio["outcome"]["coding"][0] == { - "system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio", "code": "SA", - "display": "Afecto social"} + "system": "https://isssteleon.org/fhir/CodeSystem/tea-ados2-resultado", "code": "CSS", + "display": "Puntaje de severidad calibrado (CSS)"} assert (item["probabilityDecimal"], dominio["probabilityDecimal"]) == (0.81, 0.35) extension = _extension(item) assert extension["biomarcador"]["valueCoding"] == { @@ -128,7 +128,7 @@ def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_ extension["ic-sup"]["valueDecimal"], extension["q"]["valueDecimal"]) == (3.5, 1.4, 8.7, 0.02) assert extension["probabilidad-referencia"]["valueDecimal"] == 0.22 assert extension["observado"]["valueInteger"] == 2 - assert _extension(dominio)["observado"]["valueInteger"] == 6 + assert _extension(dominio)["observado"]["valueInteger"] == 7 def test_the_summary_omits_the_model_without_rows(client): @@ -138,3 +138,18 @@ def test_the_summary_omits_the_model_without_rows(client): (child_2,) = episodes bundle = get(client, f"/tea/fhir/Patient/{child_2['id']}/$resumen-tea") assert not resources(bundle, "RiskAssessment") + + +def test_the_outcome_and_zone_code_systems_cover_what_the_model_writes(client): + """Pins down: `CodeSystem/tea-ados2-resultado` has one concept per item meaning of `ADOS2_ITEM_MEANINGS`, with + its label, plus `CSS`; `CodeSystem/tea-eeg-zona` has the `tea` library's zones (`tea.contracts.ZONES`) plus `posterior` and `global`. + Fails if an outcome or zone code the model writes has no label, so the screen would show the raw code.""" + from core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS + from tea.contracts import ZONES + + resultados = {c["code"]: c["display"] for c in get(client, "/tea/fhir/CodeSystem/tea-ados2-resultado")["concept"]} + assert set(resultados) == set(ADOS2_ITEM_MEANINGS) | {ADOS2_CSS} + assert resultados["ados2_item_11"] == "Mostrar" + assert resultados["CSS"] == "Puntaje de severidad calibrado (CSS)" + zonas = {c["code"] for c in get(client, "/tea/fhir/CodeSystem/tea-eeg-zona")["concept"]} + assert zonas == set(ZONES) | {"posterior", "global"} diff --git a/tests/test_imports_relacion_ados2.py b/tests/test_imports_relacion_ados2.py index 479b253..23a279a 100644 --- a/tests/test_imports_relacion_ados2.py +++ b/tests/test_imports_relacion_ados2.py @@ -34,17 +34,18 @@ def _json_source(records: list[dict], *, target: str) -> dict: } -# One item row and one domain row of a fitted model version, as the `tea` library writes them. +# One item row (an item meaning code) and one domain row (the total CSS) of a fitted model version, as the `tea` +# library writes them. _MODELO_ITEM = { "rel_id": "rel-1", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42, "rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "item", - "rel_resultado": "sa_b9", "rel_evento": ">=1", "rel_or": 3.5, "rel_ic_inf": 1.4, "rel_ic_sup": 8.7, + "rel_resultado": "ados2_item_11", "rel_evento": ">=1", "rel_or": 3.5, "rel_ic_inf": 1.4, "rel_ic_sup": 8.7, "rel_q": 0.02, } _MODELO_DOMINIO = { "rel_id": "rel-2", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42, "rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "dominio", - "rel_resultado": "SA", "rel_evento": ">=4", "rel_or": 0.8, "rel_ic_inf": 0.4, "rel_ic_sup": 1.6, + "rel_resultado": "CSS", "rel_evento": ">=8", "rel_or": 0.8, "rel_ic_inf": 0.4, "rel_ic_sup": 1.6, "rel_q": 0.3, } # The probabilities of one EEG for both association rows, by the model. @@ -89,8 +90,8 @@ def test_model_and_patient_rows_import_and_reimport_upserts_on_the_natural_keys( def test_invalid_model_rows_are_rejected(client): """Pins down: a model row with an out-of-range q, a non-positive odds ratio, an inverted confidence - interval, an unknown level or biomarker, an outcome code that doesn't match its level, or an over-long key - is rejected, none of it written. Fails if the schema loses one of those validations (the staging is + interval, an unknown level or biomarker, an outcome code that doesn't match its level (`CSS` as an item, a + domain code instead of `CSS`), or an over-long key is rejected, none of it written. Fails if the schema loses one of those validations (the staging is permissive; without them nothing else catches them).""" casos = [ {**_MODELO_ITEM, "rel_id": "rel-m1", "rel_version": "v" * 33}, @@ -98,8 +99,9 @@ def test_invalid_model_rows_are_rejected(client): {**_MODELO_ITEM, "rel_id": "rel-m3", "rel_version": "0.9.2", "rel_or": 0}, {**_MODELO_ITEM, "rel_id": "rel-m4", "rel_version": "0.9.3", "rel_ic_inf": 9.0, "rel_ic_sup": 4.0}, {**_MODELO_ITEM, "rel_id": "rel-m5", "rel_version": "0.9.4", "rel_nivel": "itemm"}, - {**_MODELO_ITEM, "rel_id": "rel-m6", "rel_version": "0.9.5", "rel_tipo": "item", "rel_resultado": "SA"}, + {**_MODELO_ITEM, "rel_id": "rel-m6", "rel_version": "0.9.5", "rel_tipo": "item", "rel_resultado": "CSS"}, {**_MODELO_ITEM, "rel_id": "rel-m7", "rel_version": "0.9.6", "rel_biomarcador": "ritmo posterior"}, + {**_MODELO_DOMINIO, "rel_id": "rel-m8", "rel_version": "0.9.7", "rel_resultado": "SA"}, ] body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2")], "on_conflict": "upsert"}).get_json() @@ -111,6 +113,18 @@ def test_invalid_model_rows_are_rejected(client): assert not [f for f in filas if f["rel_id"].startswith("rel-m")] +def test_per_module_column_code_is_rejected_as_an_item_outcome(client): + """Pins down: an item outcome given as a module's column code (`sa_b9`, a different item in each module) is + rejected with a cross-field error. Fails if the schema accepts column codes again, which would break the + natural key and the observed-outcome join across modules.""" + fila = {**_MODELO_ITEM, "rel_id": "rel-c1", "rel_version": "0.9.8", "rel_resultado": "sa_b9"} + body = client.post("/imports/commit", json={"sources": [_json_source([fila], target="tea.RelacionAdos2")], + "on_conflict": "upsert"}).get_json() + resultado = body["results"][0] + assert (resultado["created"], resultado["rejected"]) == (0, 1) + assert {e["field"] for e in resultado["errors"]} == {""} + + def test_invalid_patient_rows_are_rejected(client): """Pins down: a probability outside [0, 1] (the model's or the reference's) is rejected. Fails if the Bounded validation loosens, since a probability over 1 would silently skew what the screen shows.""" diff --git a/tests/test_tea_relacion_ados2.py b/tests/test_tea_relacion_ados2.py index d633267..25251cc 100644 --- a/tests/test_tea_relacion_ados2.py +++ b/tests/test_tea_relacion_ados2.py @@ -1,18 +1,25 @@ """What this module covers: `tea_paciente_relacion_ados2`, the gold view of the ADOS-2 association model: per patient it keeps only the latest model version that scored the study's EEG, it takes the probabilities of the study's EEG alone (not later EEGs, not model rows without a probability for it), and it computes `observado` from -the first ADOS-2 by date (the item's score, the domain's algorithm total, null when the outcome wasn't scored). +the first ADOS-2 by date (an item meaning's algorithm score in that ADOS-2's module, the CSS for `CSS`, null when +the module has no such item or it wasn't scored); and the dbt var the view maps item meanings with +(`tea.ados2_reactivos`) equals `core.tea.models.ADOS2_ITEM_MEANINGS`. Fixtures: `loaded`, a TEA database (`base_de`) with one child in the cohort (M-CHAT, ADOS-2 with items), two good EEGs (`e-1` the study's, `e-2` a later one), a second child without model rows, and a fitted model in two -versions whose patient rows point at both EEGs and both versions; needs `DBT_MANIFEST`. +versions whose patient rows point at both EEGs and both versions; needs `DBT_MANIFEST`. The var test reads +`Transformation/dbt_project.yml` and needs no fixture. """ import os from datetime import date +from pathlib import Path import pytest +import yaml from sqlalchemy import text +DBT_PROJECT = Path(__file__).resolve().parents[2] / "Transformation" / "dbt_project.yml" + UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") @@ -32,9 +39,12 @@ def _rows(sesion): Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12), Mchat(mch_id="m-2", mch_pac_id=2, mch_fecha=date(2025, 1, 10), mch_puntaje=8), ]) - # Items: sa_b1 2, sa_b9 1 (SA algorithm total 3), rrb_d1 2, rrb_d2 1 (RRB total 3). rrb_d4 is not scored. + # Module 1 items: sa_b1 2 (item 04), sa_b9 3 (item 11, algorithm score 2), rrb_d1 2 (item 20), rrb_d2 8 + # (item 21, algorithm score 0). rrb_d4 (item 22) is not scored. A later ADOS-2 in another module doesn't count. sesion.add(Ados2(ado_id="a-1", ado_pac_id=1, ado_fecha=date(2025, 2, 5), ado_modulo="MODULO_1", ado_css=7, - ado_clasificacion="AUTISMO", ado_sa_b1=2, ado_sa_b9=1, ado_rrb_d1=2, ado_rrb_d2=1)) + ado_clasificacion="AUTISMO", ado_sa_b1=2, ado_sa_b9=3, ado_rrb_d1=2, ado_rrb_d2=8)) + sesion.add(Ados2(ado_id="a-2", ado_pac_id=1, ado_fecha=date(2025, 8, 5), ado_modulo="TODDLER", ado_css=4, + ado_clasificacion="AUTISMO", ado_sa_b9=1)) sesion.add_all([ Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1), Eeg(eeg_id="e-2", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 6, 1), eeg_valido=1), @@ -43,29 +53,38 @@ def _rows(sesion): sesion.add_all([ RelacionAdos2(rel_id="rel-10", rel_version="1.0.0", rel_nivel="item", rel_validado=1, rel_n_cohorte=42, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item", - rel_resultado="sa_b9", rel_evento=">=1", rel_or=2.0, rel_ic_inf=1.0, rel_ic_sup=4.0, + rel_resultado="ados2_item_11", rel_evento=">=1", rel_or=2.0, rel_ic_inf=1.0, rel_ic_sup=4.0, rel_q=0.05), RelacionAdos2(rel_id="rel-11", rel_version="1.0.0", rel_nivel="item", rel_validado=1, rel_n_cohorte=42, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio", - rel_resultado="SA", rel_evento=">=4", rel_or=0.6, rel_ic_inf=0.3, rel_ic_sup=1.2, + rel_resultado="CSS", rel_evento=">=8", rel_or=0.6, rel_ic_inf=0.3, rel_ic_sup=1.2, rel_q=0.4), RelacionAdos2(rel_id="rel-20", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item", - rel_resultado="sa_b9", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7, + rel_resultado="ados2_item_11", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7, rel_q=0.02), RelacionAdos2(rel_id="rel-21", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio", - rel_resultado="SA", rel_evento=">=4", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6, + rel_resultado="CSS", rel_evento=">=8", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6, rel_q=0.3), # A row of the latest version no probability was computed for: it can't reach the patient. RelacionAdos2(rel_id="rel-22", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="PICOS_PAROXISTICOS", rel_zona="frontal_izq", rel_tipo="item", - rel_resultado="rrb_d4", rel_evento=">=1", rel_or=1.5, rel_ic_inf=0.8, rel_ic_sup=2.9, + rel_resultado="ados2_item_22", rel_evento=">=1", rel_or=1.5, rel_ic_inf=0.8, rel_ic_sup=2.9, rel_q=0.1), + # Item 10 is sa_b9 in the Toddler module only: Module 1's sa_b9 is item 11, not this one. + RelacionAdos2(rel_id="rel-24", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, + rel_biomarcador="HUSOS_SUENO_N2", rel_zona="central", rel_tipo="item", + rel_resultado="ados2_item_10", rel_evento=">=1", rel_or=1.3, rel_ic_inf=0.9, rel_ic_sup=2.0, + rel_q=0.2), + RelacionAdos2(rel_id="rel-25", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, + rel_biomarcador="HUSOS_SUENO_N2", rel_zona="central", rel_tipo="item", + rel_resultado="ados2_item_21", rel_evento=">=1", rel_or=1.2, rel_ic_inf=0.8, rel_ic_sup=1.9, + rel_q=0.3), # The same, without even a patient row anywhere: nothing to join on. RelacionAdos2(rel_id="rel-23", rel_version="1.1.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="PICOS_PAROXISTICOS", rel_zona="frontal_izq", rel_tipo="item", - rel_resultado="sa_b1", rel_evento=">=1", rel_or=1.1, rel_ic_inf=0.7, rel_ic_sup=1.8, + rel_resultado="ados2_item_04", rel_evento=">=1", rel_or=1.1, rel_ic_inf=0.7, rel_ic_sup=1.8, rel_q=0.2), ]) sesion.add_all([ @@ -78,6 +97,10 @@ def _rows(sesion): rap_probabilidad=0.35, rap_probabilidad_referencia=0.4), RelacionAdos2Paciente(rap_id="rap-3", rap_rel_id="rel-22", rap_eeg_id="e-1", rap_valor_z=1.1, rap_probabilidad=0.5, rap_probabilidad_referencia=0.45), + RelacionAdos2Paciente(rap_id="rap-5", rap_rel_id="rel-24", rap_eeg_id="e-1", rap_valor_z=0.2, + rap_probabilidad=0.4, rap_probabilidad_referencia=0.4), + RelacionAdos2Paciente(rap_id="rap-6", rap_rel_id="rel-25", rap_eeg_id="e-1", rap_valor_z=0.3, + rap_probabilidad=0.45, rap_probabilidad_referencia=0.4), # A probability for the later EEG: not the study's, it doesn't count. RelacionAdos2Paciente(rap_id="rap-4", rap_rel_id="rel-20", rap_eeg_id="e-2", rap_valor_z=0.4, rap_probabilidad=0.3, rap_probabilidad_referencia=0.25), @@ -113,7 +136,9 @@ def test_the_view_keeps_the_latest_version_of_the_study_eeg_only(loaded): latest version.""" filas = _filas(loaded) claves = sorted((f.version, f.resultado, f.tipo) for f in filas) - assert claves == [("1.1.0", "SA", "dominio"), ("1.1.0", "rrb_d4", "item"), ("1.1.0", "sa_b9", "item")] + assert claves == [("1.1.0", "CSS", "dominio"), ("1.1.0", "ados2_item_10", "item"), + ("1.1.0", "ados2_item_11", "item"), ("1.1.0", "ados2_item_21", "item"), + ("1.1.0", "ados2_item_22", "item")] assert {f.pac_id for f in filas} == {1} @@ -121,7 +146,7 @@ def test_a_row_carries_the_model_metadata_and_the_patient_values(loaded): """Pins down: each row carries the model row as it arrived (version, validation, level, cohort size, metric, zone, event, odds ratio with its interval and q) and the patient's values for the study's EEG. Fails if a column stops being selected or gets renamed without the FHIR layer changing with it.""" - (item,) = [f for f in _filas(loaded) if f.resultado == "sa_b9"] + (item,) = [f for f in _filas(loaded) if f.resultado == "ados2_item_11"] assert (item.version, item.validado, item.nivel, item.n_cohorte) == ("1.1.0", 0, "item", 60) assert (item.biomarcador, item.zona, item.evento) == ("RITMO_POSTERIOR", "occipital", ">=1") assert (item.odds_ratio, item.ic_inf, item.ic_sup, item.q) == (3.5, 1.4, 8.7, 0.02) @@ -129,9 +154,22 @@ def test_a_row_carries_the_model_metadata_and_the_patient_values(loaded): def test_observado_is_the_outcome_score_of_the_first_ados2(loaded): - """Pins down: `observado` is read from the first ADOS-2 by date (the one the patient summary shows): the - item's score for an item (sa_b9 1), the domain's algorithm total for a domain (SA: sa_b1 2 + sa_b9 1 = 3), and - null when the outcome wasn't scored (rrb_d4). It is never stored in the association tables. Fails if the view - starts reading another ADOS-2, sums the raw scores, or stores the outcome.""" + """Pins down: `observado` is read from the first ADOS-2 by date (Module 1, the one the patient summary shows): + an item meaning's algorithm score through its column code in that module (item 11 is sa_b9 there, 3 counts as + 2; item 21 is rrb_d2, 8 counts as 0), null for an item the module doesn't have (item 10, Toddler only, even + though sa_b9 was scored) or that wasn't scored (item 22, rrb_d4), and the ADOS-2's CSS for `CSS` (7). Fails if + the view joins by column code instead of meaning and module, stops applying the algorithm's score mapping, + reads the later ADOS-2, or stores the outcome.""" observados = {f.resultado: f.observado for f in _filas(loaded)} - assert observados == {"sa_b9": 1, "SA": 3, "rrb_d4": None} + assert observados == {"ados2_item_11": 2, "ados2_item_21": 0, "ados2_item_10": None, "ados2_item_22": None, + "CSS": 7} + + +def test_the_dbt_item_map_equals_the_item_meanings(): + """Pins down: `vars.tea.ados2_reactivos` in dbt_project.yml, which the view maps item outcomes with, has the + same meaning codes and per-module column codes as `core.tea.models.ADOS2_ITEM_MEANINGS`, which the import + schema and the FHIR layer use. Fails if one copy gains, loses or remaps an item without the other.""" + from core.tea.models import ADOS2_ITEM_MEANINGS + + reactivos = yaml.safe_load(DBT_PROJECT.read_text(encoding="utf-8"))["vars"]["tea"]["ados2_reactivos"] + assert reactivos == {codigo: modulos for codigo, (_, _, modulos) in ADOS2_ITEM_MEANINGS.items()} diff --git a/uv.lock b/uv.lock index 71ab4dd..8d970d7 100644 --- a/uv.lock +++ b/uv.lock @@ -4424,7 +4424,7 @@ wheels = [ [[package]] name = "tea" -version = "0.2.0" +version = "0.3.0" source = { editable = "../models/libs/tea" } dependencies = [ { name = "antropy" }, diff --git a/webapi/fhir/tea.py b/webapi/fhir/tea.py index 2ad3f4a..3da3405 100644 --- a/webapi/fhir/tea.py +++ b/webapi/fhir/tea.py @@ -379,24 +379,20 @@ def relacion_ados2(rows: list[dict], pseudonym: str, fecha: date | None, ados2_i simulated: bool) -> dict | None: """The association model as one `RiskAssessment`: a prediction per association row that scored the study's EEG, the clearest cohort association (lowest q) first. The model's version, expert validation, level and cohort size - sit on the resource; each prediction carries the outcome (the ADOS-2 item or domain) and the probability the + sit on the resource; each prediction carries the outcome (an ADOS-2 item meaning or the total CSS) and the probability the model gives the patient, and as extensions the EEG metric and scalp zone, the patient's z, the cohort's odds ratio with its confidence interval and q, the reference probability (z = 0) and the outcome observed in the patient's ADOS-2. Zone and outcome labels come from the code systems, not from the row. Without rows there is no resource.""" if not rows: return None - from webapi.fhir.terminology import DOMINIOS_ADOS2, TEA_EEG, ados2_resultados + from webapi.fhir.terminology import TEA_EEG, ados2_resultados resultados, metricas, zonas = ados2_resultados(), TEA_EEG["metricas"], TEA_EEG["zonas"] def prediction(f: dict) -> dict: - if f["tipo"] == "item": - code = f"ados2.{f['resultado']}" - outcome = concept(CATALOG, code, resultados.get(code, f["resultado"])) - else: - outcome = concept(f"{CODE_SYSTEM}/ados2-dominio", f["resultado"], - DOMINIOS_ADOS2.get(f["resultado"], f["resultado"])) + outcome = concept(f"{CODE_SYSTEM}/tea-ados2-resultado", f["resultado"], + resultados.get(f["resultado"], f["resultado"])) return { "outcome": outcome, "probabilityDecimal": float(f["probabilidad"]), diff --git a/webapi/fhir/tea_eeg.toml b/webapi/fhir/tea_eeg.toml index ddce6d2..13e09a8 100644 --- a/webapi/fhir/tea_eeg.toml +++ b/webapi/fhir/tea_eeg.toml @@ -58,12 +58,16 @@ O1 = [-0.25, -0.77] O2 = [0.25, -0.77] # The scalp zones the association model relates an EEG alteration in with an ADOS-2 outcome, as the `tea` library -# codes them: what each zone is called on screen. A code outside this list shows as written. +# codes them, plus `posterior` (the posterior rhythm) and `global` (the anteroposterior gradient): what each zone is +# called on screen. A code outside this list shows as written. [zonas] frontal_izq = "Frontal izquierda" frontal_der = "Frontal derecha" +frontal_media = "Frontal media" central = "Central" temporal_izq = "Temporal izquierda" temporal_der = "Temporal derecha" parietal = "Parietal" occipital = "Occipital" +posterior = "Posterior" +global = "Global" diff --git a/webapi/fhir/terminology.py b/webapi/fhir/terminology.py index a375994..3f2a54e 100644 --- a/webapi/fhir/terminology.py +++ b/webapi/fhir/terminology.py @@ -1,6 +1,6 @@ """The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's catalog (`core/catalogos/.toml`: studies, results and their values), TEA's screening stages and diagnostic -results, TEA's EEG metrics with their effect texts (`tea_eeg.toml`), and the EEG analysis's quality checks, under +results, the ADOS-2 association model's outcomes (`core.tea.models.ADOS2_ITEM_MEANINGS` and the CSS), TEA's EEG metrics with their effect texts (`tea_eeg.toml`), and the EEG analysis's quality checks, under the analysis's own code system with the catalog's labels.""" import tomllib @@ -15,13 +15,14 @@ STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psico DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado")) QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar")) DOMINIOS_ADOS2 = {"SA": "Afecto social", "RRB": "Comportamiento restringido y repetitivo"} +CSS_ETIQUETA = "Puntaje de severidad calibrado (CSS)" def ados2_resultados() -> dict[str, str]: - """The ADOS-2 results' labels from the domain catalog, by their catalog code (`ados2.sa_b9`): what an - association row's outcome shows as.""" - results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["ados2"]["resultados"] - return {f"ados2.{name}": spec["etiqueta"] for name, spec in results.items()} + """The association model's outcome labels by code: each item meaning (`ados2_item_11`) and the total CSS.""" + from core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS + + return {**{code: label for code, (label, _, _) in ADOS2_ITEM_MEANINGS.items()}, ADOS2_CSS: CSS_ETIQUETA} def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict: @@ -76,6 +77,8 @@ def tea_code_systems() -> dict[str, dict]: [{"code": e, "display": e} for e in TEA_EEG["electrodos"]]), _code_system("tea-eeg-zona", "Zonas del cuero cabelludo", [{"code": z, "display": e} for z, e in TEA_EEG["zonas"].items()]), + _code_system("tea-ados2-resultado", "Desenlaces del ADOS-2 del modelo de asociación", + [{"code": c, "display": e} for c, e in ados2_resultados().items()]), _code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [ {"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"}, {"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]), diff --git a/webapi/imports/schemas/tea/relacion_ados2.py b/webapi/imports/schemas/tea/relacion_ados2.py index 632c1f9..0b01ea1 100644 --- a/webapi/imports/schemas/tea/relacion_ados2.py +++ b/webapi/imports/schemas/tea/relacion_ados2.py @@ -1,18 +1,19 @@ """Import schema for `core.tea.models.RelacionAdos2`: one association of an EEG alteration in a scalp zone with an -ADOS-2 item or domain outcome, per fitted model version. `rel_evento` is the outcome event as a threshold on its -score, machine-readable (`>=2`); it is shown as written, never parsed.""" +ADOS-2 outcome, per fitted model version. An item outcome is an item meaning code (`ADOS2_ITEM_MEANINGS`), the same +in every module; a domain outcome is the total calibrated severity score (`ADOS2_CSS`). `rel_evento` is the outcome +event as a threshold on its score, machine-readable (`>=1`); it is shown as written, never parsed.""" from typing import Annotated, Optional from pydantic import Field, model_validator from core.tea.enums import MetricaEeg, NivelRelacionAdos2 -from core.tea.models import ADOS2_ITEMS +from core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS from webapi.imports.schemas.base import ImportSchema from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, OptionalStr, ShortKey, SourceId _NIVEL_CATALOG = Catalog(NivelRelacionAdos2) _BIOMARCADOR_CATALOG = Catalog(MetricaEeg) -_DOMINIOS_ADOS2 = {"SA", "RRB"} +_RESULTADOS_DOMINIO = {ADOS2_CSS} class RelacionAdos2ImportSchema(ImportSchema): @@ -37,7 +38,8 @@ class RelacionAdos2ImportSchema(ImportSchema): if self.rel_ic_inf is not None and self.rel_ic_sup is not None and self.rel_ic_inf > self.rel_ic_sup: raise ValueError("rel_ic_inf no puede ser mayor que rel_ic_sup") if self.rel_tipo is not None and self.rel_resultado is not None: - validos = set(ADOS2_ITEMS) if self.rel_tipo == NivelRelacionAdos2.ITEM.value else _DOMINIOS_ADOS2 + validos = (set(ADOS2_ITEM_MEANINGS) if self.rel_tipo == NivelRelacionAdos2.ITEM.value + else _RESULTADOS_DOMINIO) if self.rel_resultado not in validos: raise ValueError(f"'{self.rel_resultado}' no es un código de {self.rel_tipo} del ADOS-2") return self diff --git a/webapi/orchestration/__init__.py b/webapi/orchestration/__init__.py index ca609c7..13f9346 100644 --- a/webapi/orchestration/__init__.py +++ b/webapi/orchestration/__init__.py @@ -6,7 +6,9 @@ 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 Persistance's repositories (`ctx.repos`), so each one can run on its own. - migrate -> catalogs, registry, definitions + migrate -> catalogs, registry, definitions, analyze_eeg + analyze_eeg -> relate_ados2, load (TEA: the EEG analysis) + relate_ados2 -> load (TEA: the ADOS-2 association) catalogs -> load, check_silver load -> views, event_models, observe, check_silver registry -> observe diff --git a/webapi/orchestration/__main__.py b/webapi/orchestration/__main__.py index f041902..941ccc7 100644 --- a/webapi/orchestration/__main__.py +++ b/webapi/orchestration/__main__.py @@ -13,7 +13,7 @@ from datetime import date from pathlib import Path from webapi.orchestration.context import Context -from webapi.orchestration.eeg import live_eeg_analysis +from webapi.orchestration.eeg import live_ados2_relation, live_eeg_analysis from webapi.orchestration.estimators import live_estimators from webapi.orchestration.runner import run @@ -45,7 +45,8 @@ def main(argv: list[str] | None = None) -> None: return 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, - 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)) for paso in run(ctx, only=args.only): print(f"{paso.name:20} {paso.seconds:6.1f} s") diff --git a/webapi/orchestration/context.py b/webapi/orchestration/context.py index 19e90a9..9e855d8 100644 --- a/webapi/orchestration/context.py +++ b/webapi/orchestration/context.py @@ -42,5 +42,8 @@ class Context: # 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. eeg_analysis: 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 + # 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) # Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan. repos: Any = field(default=None, compare=False, repr=False) diff --git a/webapi/orchestration/cycle.py b/webapi/orchestration/cycle.py index e1b8d77..329d525 100644 --- a/webapi/orchestration/cycle.py +++ b/webapi/orchestration/cycle.py @@ -84,15 +84,26 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]: def analyze_eeg(migrate: str, ctx: Context) -> dict[str, int]: """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` and `eeg_metrica_electrodo`. + it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica`, `eeg_metrica_electrodo` + and `eeg_metrica_zona`. Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA).""" if ctx.eeg_analysis is None: return {} return asdict(ctx.eeg_analysis()) -def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], ctx: Context) -> SQLModel: - """`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis. +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 + `relacion_ados2` and `relacion_ados2_paciente` before `load`, so the same cycle's gold views show it. Returns + the version and its counts; nothing without an association (every domain but TEA).""" + if ctx.ados2_relation is None: + return {} + return asdict(ctx.ados2_relation()) + + +def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], relate_ados2: dict, ctx: Context) -> SQLModel: + """`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis and + the ADOS-2 association. Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada. """ diff --git a/webapi/orchestration/eeg.py b/webapi/orchestration/eeg.py index d19d5a2..1ad7bc7 100644 --- a/webapi/orchestration/eeg.py +++ b/webapi/orchestration/eeg.py @@ -1,8 +1,10 @@ -"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load. +"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load, and the +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 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). +`ADOS2_RELATION=off` leaves the association out (`python -m models tea relate-ados2` still runs it). """ import os from collections.abc import Callable @@ -11,6 +13,7 @@ from typing import Any CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER" CLUSTERS = ("auto", "local", "remote", "sync") +RELATION_ENV = "ADOS2_RELATION" def cluster() -> str: @@ -27,3 +30,15 @@ def live_eeg_analysis(domain: str) -> Callable[[], Any] | None: from models.eeg_analysis import analyze_pending return partial(analyze_pending, cluster=cluster()) + + +def live_ados2_relation(domain: str) -> Callable[[], Any] | None: + """The domain's ADOS-2 association for the cycle, or none: only TEA has one, and `off` leaves it out.""" + value = os.environ.get(RELATION_ENV, "on") + if value not in ("on", "off"): + raise ValueError(f"{RELATION_ENV} must be on or off, not {value!r}") + if domain != "tea" or value == "off": + return None + from models.ados2_relation import relate + + return relate diff --git a/webapi/recomputation.py b/webapi/recomputation.py index b3819bb..04b895e 100644 --- a/webapi/recomputation.py +++ b/webapi/recomputation.py @@ -106,7 +106,7 @@ class RecomputationQueue: 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).""" from webapi.orchestration import Context, run, steps_of - from webapi.orchestration.eeg import live_eeg_analysis + from webapi.orchestration.eeg import live_ados2_relation, live_eeg_analysis from webapi.orchestration.estimators import live_estimators desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5)) @@ -117,7 +117,7 @@ class RecomputationQueue: entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio), - eeg_analysis=live_eeg_analysis(dominio)) + eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio)) pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"]) entrada.update( estado="ok",