Merge dev into the CaMa consolidation branch
This commit is contained in:
@@ -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")
|
||||
@@ -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"])
|
||||
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
|
||||
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()
|
||||
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 deps["analyze_eeg"] == {"migrate"}
|
||||
assert deps["analyze_eeg"] == {"migrate", "score_ados2"}
|
||||
order = steps_of(proyecto)
|
||||
assert order.index("analyze_eeg") < order.index("load")
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Every FHIR URL the API emits hangs from one base, which FHIR_BASE_URL sets (issue 199)."""
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
from webapi import durations, fhir_base, metrics
|
||||
from webapi.fhir import common
|
||||
|
||||
POR_DEFECTO = "https://isssteleon.org/fhir"
|
||||
|
||||
|
||||
def test_todas_las_urls_cuelgan_de_la_misma_base():
|
||||
estructuras = [metrics.EVENT_CUTOFF, metrics.KNOWLEDGE_CUTOFF, metrics.HISTORY_ENTRY, metrics.INTERVAL_LOW, metrics.INTERVAL_HIGH]
|
||||
assert all(u.startswith(f"{common.STRUCTURE}/") for u in estructuras)
|
||||
assert common.STRUCTURE == f"{common.BASE}/StructureDefinition" == fhir_base.STRUCTURE
|
||||
assert common.CODE_SYSTEM.startswith(common.BASE) and common.VALUE_SET.startswith(common.BASE)
|
||||
|
||||
|
||||
def test_no_quedan_dominios_escritos_a_mano_fuera_de_la_base():
|
||||
import pathlib
|
||||
raiz = pathlib.Path(fhir_base.__file__).parent
|
||||
escritos = [p.name for p in raiz.rglob("*.py") if "isssteleon.org" in p.read_text() and p.name != "fhir_base.py"]
|
||||
assert escritos == []
|
||||
|
||||
|
||||
def test_la_base_se_puede_cambiar_por_ambiente(monkeypatch):
|
||||
monkeypatch.setenv("FHIR_BASE_URL", "https://fhir.ejemplo.test/base/")
|
||||
try:
|
||||
importlib.reload(fhir_base)
|
||||
assert fhir_base.BASE == "https://fhir.ejemplo.test/base"
|
||||
assert fhir_base.STRUCTURE == "https://fhir.ejemplo.test/base/StructureDefinition"
|
||||
finally:
|
||||
monkeypatch.delenv("FHIR_BASE_URL")
|
||||
importlib.reload(fhir_base)
|
||||
assert fhir_base.BASE == POR_DEFECTO
|
||||
|
||||
|
||||
def test_los_q1_y_q3_de_los_tiempos_usan_la_misma_base():
|
||||
assert durations.STRUCTURE == metrics.INTERVAL_LOW.rsplit("/", 1)[0]
|
||||
@@ -107,3 +107,55 @@ def test_the_capability_statement_declares_the_search(client):
|
||||
|
||||
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
|
||||
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
|
||||
|
||||
|
||||
def test_each_outcome_is_its_own_risk_assessment(client, seeded):
|
||||
"""Pins down: with a confirmed cancer batch next to the CIN2+ one, the patient's Bundle holds one RiskAssessment
|
||||
per outcome, the newest first, each with its own outcome code. Fails if the route goes back to one batch, which
|
||||
hides the other outcome's risk. Runs last: it adds a batch to the module's database."""
|
||||
from persistance import cacu
|
||||
|
||||
scored, _, batch = seeded
|
||||
cancer, _ = cacu.cohort_repository.save_batch(
|
||||
_build_of(batch),
|
||||
{"modelo_nombre": "cacu-cancer_pim", "modelo_version": "1", "mlflow_run_id": "r2", "modelo_sha": "s2"},
|
||||
"cancer", [(scored, MODEL_INDEX, 3.0, 0.02, 0.01, 0.04)], ahora=datetime(2026, 10, 2, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(cancer, "final", "revisado")
|
||||
|
||||
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()
|
||||
|
||||
found = [e["resource"] for e in bundle["entry"]]
|
||||
assert bundle["total"] == 2 and [r["id"] for r in found] == [f"{cancer}-{scored}", f"{batch}-{scored}"]
|
||||
assert [r["prediction"][0]["outcome"]["coding"][0]["code"] for r in found] == ["cancer", "cin2_mas"]
|
||||
|
||||
|
||||
def _build_of(batch: int) -> int:
|
||||
from core.cacu.indicadores.models import EvaluacionRiesgoLote
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
return session.get(EvaluacionRiesgoLote, batch).armado_id
|
||||
|
||||
|
||||
def test_a_current_model_that_did_not_score_her_says_so(client, seeded):
|
||||
"""Pins down: a confirmed batch of another outcome that scored only another patient gives the scored patient a
|
||||
RiskAssessment with no prediction and the `sin-estimacion` extension, while a patient with no risk at all still
|
||||
gets an empty Bundle. Fails if the record can't tell "no model" from "not estimated for her", or a patient with
|
||||
no risk gets one. Runs after the cancer test: it adds another batch to the module's database."""
|
||||
from persistance import cacu
|
||||
|
||||
from webapi.fhir.risk import NOT_SCORED
|
||||
|
||||
scored, unscored, batch = seeded
|
||||
other, _ = cacu.cohort_repository.save_batch(
|
||||
_build_of(batch), {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r3",
|
||||
"modelo_sha": "s3"},
|
||||
"muerte", [(unscored, MODEL_INDEX, 1.0, 0.1, None, None)], ahora=datetime(2026, 10, 3, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(other, "final", "revisado")
|
||||
|
||||
found = {e["resource"]["id"]: e["resource"] for e in
|
||||
client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()["entry"]}
|
||||
missing = found[f"{other}-{scored}"]
|
||||
marker = next(e for e in missing["extension"] if e["url"] == NOT_SCORED)
|
||||
assert "prediction" not in missing and {"url": "desenlace", "valueCode": "muerte"} in marker["extension"]
|
||||
assert len(found) == 3
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""What this module covers: `webapi.fhir.risk.risk_assessment` naming what the model's number is (`[estimand]` of its
|
||||
scenario's `model.toml`) in the extension `estimando` and `method.text`, and leaving both out for a model whose
|
||||
scenario can't be read.
|
||||
|
||||
Fixtures: none; the patient's risk is a stand-in with the fields `PatientRisk` has.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from webapi.fhir import risk
|
||||
|
||||
|
||||
def _risk(modelo_nombre):
|
||||
horizon = SimpleNamespace(horizonte_anios=1.0, probabilidad=0.1, ic_bajo=0.05, ic_alto=0.2)
|
||||
return SimpleNamespace(lote_id=1, estado_lote="final", evaluado_en=datetime(2026, 1, 1, tzinfo=timezone.utc),
|
||||
modelo_nombre=modelo_nombre, modelo_version="2", fecha_indice=date(2025, 1, 1),
|
||||
horizontes=[horizon], desenlace="cin2")
|
||||
|
||||
|
||||
def test_the_risk_says_what_its_number_is():
|
||||
"""Pins down: a PIM risk carries its scenario's quantity, outcome and horizons' unit. Fails if the extension's url
|
||||
or keys change, which the WebApp reads, or the scenario stops being found by the registered name."""
|
||||
found = risk.risk_assessment(7, _risk("cacu-cin2_pim"), True, {}, "cin2_mas")
|
||||
|
||||
extension = {e["url"]: e["valueString"] for e in found["extension"][0]["extension"]}
|
||||
assert found["extension"][0]["url"] == risk.ESTIMAND and found["method"]["text"] == "Riesgo acumulado"
|
||||
assert extension["horizons_unit"] == "años" and extension["outcome"].startswith("CIN2+")
|
||||
|
||||
|
||||
def test_a_model_without_a_scenario_has_no_estimand():
|
||||
"""Pins down: a registered name with no scenario behind it gives the resource without the extension. Fails if
|
||||
a missing scenario breaks the patient's risk."""
|
||||
found = risk.risk_assessment(7, _risk("cacu-no_existe"), True, {}, "cin2_mas")
|
||||
assert "text" not in found["method"] and not any(e.get("url") == risk.ESTIMAND for e in found.get("extension", []))
|
||||
|
||||
|
||||
def test_a_cacu_risk_names_the_results_of_its_index_cytology(monkeypatch):
|
||||
"""Pins down: CaCu's RiskAssessment carries the squamous, glandular and HPV results of the cytology sampled on the
|
||||
risk's index date (the most complete if there are several), which the record words its sentence with; a risk
|
||||
with none that day has no such extension. Fails if the extension's url or keys change, or another day's sample
|
||||
is read."""
|
||||
from persistance import cacu as repos
|
||||
|
||||
from webapi.fhir import cacu
|
||||
|
||||
asked = []
|
||||
|
||||
def rows(**filters):
|
||||
asked.append(filters)
|
||||
return [SimpleNamespace(cit_celulas_escamosas="LIEBG", cit_celulas_glandulares=None, cit_vph_resultado=None),
|
||||
SimpleNamespace(cit_celulas_escamosas="LIEBG", cit_celulas_glandulares=None,
|
||||
cit_vph_resultado="POSITIVO")]
|
||||
|
||||
monkeypatch.setattr(repos.citologia_cervical_repository, "list", rows)
|
||||
found = cacu.risk_assessment(7, _risk("cacu-cin2_pim"), True)
|
||||
|
||||
extension = next(e for e in found["extension"] if e["url"] == cacu.INDEX_RESULTS)
|
||||
assert {e["url"]: e["valueString"] for e in extension["extension"]} == {"escamosas": "LIEBG", "vph": "POSITIVO"}
|
||||
assert asked[0]["pac_id"] == 7 and asked[0]["cit_fecha_toma"] == date(2025, 1, 1)
|
||||
|
||||
monkeypatch.setattr(repos.citologia_cervical_repository, "list", lambda **filters: [])
|
||||
without = cacu.risk_assessment(7, _risk("cacu-cin2_pim"), True)["extension"]
|
||||
assert not any(e["url"] == cacu.INDEX_RESULTS for e in without)
|
||||
@@ -0,0 +1,147 @@
|
||||
"""What this module covers: filling `tea.Ados2`'s item columns from the ADOS-2 score table of a PDF read from a SQL
|
||||
source (`DocumentConnector` with `sql`, the score-table extractor of `extraction.nlp.score_tables`) and merging them
|
||||
with `on_conflict=upsert` into the row the hospital's table import created, which keeps its header.
|
||||
|
||||
Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`); `hospital`, a SQLite file
|
||||
standing for the hospital with one ADOS-2 row whose evaluation PDF is a two-page report, prose first and the
|
||||
Module 2 score table second.
|
||||
"""
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
# Module 2 rows as the evaluation prints them: description, algorithm score, column.
|
||||
_ROWS = [
|
||||
("Señalar", "1", "ado_sa_a6"),
|
||||
("Gestos descriptivos, convencionales, instrumentales o informativos", "0", "ado_sa_a7"),
|
||||
("Contacto visual inusual", "2", "ado_sa_b1"),
|
||||
("Expresiones faciales dirigidas a otros", "1", "ado_sa_b2"),
|
||||
("Disfrute compartido durante la interacción", "0", "ado_sa_b3"),
|
||||
("Mostrar", "2", "ado_sa_b5"),
|
||||
("Iniciación espontánea de la atención conjunta", "1", "ado_sa_b6"),
|
||||
("Características de las iniciaciones sociales", "1", "ado_sa_b8"),
|
||||
("Cantidad de comunicación social recíproca", "S/D", "ado_sa_b11"),
|
||||
("Calidad general de la relación", "2", "ado_sa_b12"),
|
||||
("Uso estereotipado o idiosincrásico de palabras o frases", "1", "ado_rrb_a4"),
|
||||
("Interés sensorial inusual en los materiales de juego o en las personas", "0", "ado_rrb_d1"),
|
||||
("Manierismos de manos y dedos y otros manierismos complejos", "2", "ado_rrb_d2"),
|
||||
("Intereses inusualmente repetitivos o comportamientos estereotipados", "1", "ado_rrb_d4"),
|
||||
]
|
||||
|
||||
|
||||
def _evaluation_pdf() -> bytes:
|
||||
from reportlab.pdfgen.canvas import Canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
pdf = Canvas(buffer, pagesize=(612, 792))
|
||||
pdf.setFont("Helvetica", 10)
|
||||
pdf.drawString(72, 720, "Evaluación psicológica. Se observa afectación social en el juego libre.")
|
||||
pdf.showPage()
|
||||
pdf.setFont("Helvetica", 10)
|
||||
y = 720
|
||||
|
||||
def row(caption, score=None):
|
||||
nonlocal y
|
||||
pdf.drawString(76, y, caption)
|
||||
if score is not None:
|
||||
pdf.drawCentredString(512, y, score)
|
||||
y -= 20
|
||||
|
||||
row("Afectación Social (AS)")
|
||||
for caption, score, _ in _ROWS[:10]:
|
||||
row(caption, score)
|
||||
social = sum(int(s) for _, s, _ in _ROWS[:10] if s != "S/D")
|
||||
row("TOTAL DE AFECTACIÓN SOCIAL", str(social))
|
||||
row("Comportamiento restringido y repetitivo (CRR)")
|
||||
for caption, score, _ in _ROWS[10:]:
|
||||
row(caption, score)
|
||||
restricted = sum(int(s) for _, s, _ in _ROWS[10:])
|
||||
row("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", str(restricted))
|
||||
row("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", str(social + restricted))
|
||||
pdf.showPage()
|
||||
pdf.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hospital(tmp_path):
|
||||
"""The hospital: `ados2` with one header row and no items, and the ADOS-2 order holding the evaluation PDF."""
|
||||
url = f"sqlite:///{tmp_path / 'hospital.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE ados2 (ado_id TEXT, ado_pac_id INTEGER, ado_ord_id TEXT)"))
|
||||
conn.execute(text("CREATE TABLE ordenes_estudio (ord_id TEXT, ord_pdf_blob BLOB)"))
|
||||
conn.execute(text("INSERT INTO ados2 VALUES ('ADO-1', 7, 'ORD-1')"))
|
||||
conn.execute(text("INSERT INTO ordenes_estudio VALUES ('ORD-1', :pdf)"), {"pdf": _evaluation_pdf()})
|
||||
return url
|
||||
|
||||
|
||||
def _json_source(records: list[dict]) -> dict:
|
||||
return {
|
||||
"source_type": "json",
|
||||
"target": "tea.Ados2",
|
||||
"column_mapping": {name: name for name in records[0]},
|
||||
"payload": {"file_base64": base64.b64encode(json.dumps(records).encode()).decode()},
|
||||
}
|
||||
|
||||
|
||||
def _document_source(url: str) -> dict:
|
||||
items = [column for _, _, column in _ROWS]
|
||||
return {
|
||||
"source_type": "document",
|
||||
"target": "tea.Ados2",
|
||||
"column_mapping": {name: name for name in ["ado_id", *items]},
|
||||
"payload": {
|
||||
"target": "tea.Ados2",
|
||||
"sql": {
|
||||
"connection_string": url,
|
||||
"query": "select a.ado_id, a.ado_pac_id, o.ord_pdf_blob from ados2 a "
|
||||
"join ordenes_estudio o on o.ord_id = a.ado_ord_id",
|
||||
"column": "ord_pdf_blob",
|
||||
"key_column": "ado_id",
|
||||
"fields": {"ado_id": "ado_id", "ado_pac_id": "ado_pac_id"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_the_evaluations_score_table_fills_the_items_of_the_existing_row(client, hospital, wire_domain):
|
||||
"""Pins down: after the header row is imported, a `document` source over the hospital's ADOS-2 PDF, committed
|
||||
with upsert, writes each item's algorithm score into its Module 2 column on that same row, leaves an `S/D` item
|
||||
empty, and keeps the header (module, CSS, patient). Fails if the document's items stop reaching the columns,
|
||||
the upsert creates a second row or blanks the header, or the module is read from the wrong item set."""
|
||||
header = {"ado_id": "ADO-1", "ado_pac_id": 7, "ado_modulo": "MODULO_2", "ado_algoritmo": "Menor de 5 años",
|
||||
"ado_css": 6, "ado_clasificacion": "AUTISMO"}
|
||||
first = client.post("/imports/commit", json={"sources": [_json_source([header])], "on_conflict": "upsert"})
|
||||
assert first.status_code == 200, first.get_json()
|
||||
second = client.post("/imports/commit", json={"sources": [_document_source(hospital)], "on_conflict": "upsert"})
|
||||
body = second.get_json()
|
||||
assert second.status_code == 200, body
|
||||
assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 1, 0)]
|
||||
|
||||
from persistance import settings
|
||||
|
||||
path = settings.settings.tea_database_url.removeprefix("sqlite:///")
|
||||
con = sqlite3.connect(path)
|
||||
con.row_factory = sqlite3.Row
|
||||
rows = con.execute("select * from ados2").fetchall()
|
||||
assert len(rows) == 1
|
||||
stored = dict(rows[0])
|
||||
expected = {column: (None if score == "S/D" else int(score)) for _, score, column in _ROWS}
|
||||
assert {column: stored[column] for column in expected} == expected
|
||||
assert (stored["ado_modulo"], stored["ado_css"], stored["ado_pac_id"]) == ("MODULO_2", 6, 7)
|
||||
@@ -200,6 +200,27 @@ def test_an_import_into_tea_queues_its_recomputation(client):
|
||||
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
|
||||
def sql_source_db(tmp_path):
|
||||
db_path = tmp_path / "external_source.db"
|
||||
|
||||
@@ -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"]} == {"<entre campos>"}
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
@@ -89,7 +89,7 @@ def test_the_list_names_what_is_answered_on_request(client):
|
||||
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
|
||||
"""Pins down the route for durations: the samples measurable and measured as populations, the median as the
|
||||
score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day
|
||||
by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its
|
||||
by default). 2025-S2's samples resolved in 40 and 161 days, and the 120-day horizon keeps only the first. Fails if a duration stops being served or its
|
||||
contract changes."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True)
|
||||
(entry,) = bundle["entry"]
|
||||
@@ -97,9 +97,9 @@ def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
|
||||
(group,) = report["group"]
|
||||
assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3"
|
||||
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
||||
"initial-population": 4, "measure-observation": 2}
|
||||
assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d"
|
||||
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75]
|
||||
"initial-population": 4, "measure-observation": 1}
|
||||
assert group["measureScore"]["value"] == 40.0 and group["measureScore"]["unit"] == "d"
|
||||
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [40.0, 40.0]
|
||||
assert any(e["url"].endswith("corte-evento") for e in report["extension"])
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text(
|
||||
|
||||
@@ -13,34 +13,38 @@ from webapi.recomputation import RecomputationQueue
|
||||
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
|
||||
|
||||
|
||||
def test_only_cacu_has_a_live_estimator():
|
||||
"""With no version in the registry, CaMa's cycle estimates nothing, and TEA never has a live estimator. Fails if a
|
||||
domain without a production model gets an estimator that would then fail resolving a version."""
|
||||
def test_with_an_empty_registry_no_domain_has_a_live_estimator():
|
||||
"""With no version in the registry, neither CaMa's nor TEA's cycle estimates anything. Fails if a domain without
|
||||
a production model gets an estimator that would then fail resolving a version."""
|
||||
assert estimators.live_estimators("cama") == {}
|
||||
assert estimators.live_estimators("tea") == {}
|
||||
|
||||
|
||||
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
|
||||
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
|
||||
Fails if `live_estimators` stops catching the registry's `LookupError`."""
|
||||
Fails if `live_estimators` offers a scenario the registry does not list as in production."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
|
||||
monkeypatch.setattr(registry, "in_production", lambda domain: [])
|
||||
assert estimators.live_estimators("cacu") == {}
|
||||
|
||||
|
||||
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
|
||||
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
|
||||
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
|
||||
def test_every_scenario_in_production_scores_its_cohort(monkeypatch):
|
||||
"""Each scenario the registry has in production gets an estimator on the cohort its `model.toml` names, so two
|
||||
scenarios on one cohort give that cohort two estimators; a registered name with no scenario in `models` is
|
||||
skipped. An estimator reports nothing until it has estimated. Fails if the scenarios go back to a fixed list,
|
||||
if one cohort keeps a single estimator, or if an unknown registered name breaks the cycle."""
|
||||
from models.dags.training import Scenario
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
|
||||
monkeypatch.setattr(registry, "in_production", lambda domain: ["cancer_pim", "cin2_pim", "no_such_model"])
|
||||
live = estimators.live_estimators("cacu")
|
||||
assert list(live) == [URL]
|
||||
estimator = live[URL]
|
||||
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
|
||||
cohort = Scenario.load("cacu", "cin2_pim").cohort
|
||||
assert Scenario.load("cacu", "cancer_pim").cohort == cohort
|
||||
assert list(live) == [cohort]
|
||||
assert [e.scenario for e in live[cohort]] == ["cancer_pim", "cin2_pim"]
|
||||
with pytest.raises(RuntimeError):
|
||||
estimator.procedencia()
|
||||
live[cohort][0].procedencia()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
@@ -48,7 +52,7 @@ def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monk
|
||||
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
|
||||
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
|
||||
as anything but `preliminary`."""
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: [EstimadorFijo()]})
|
||||
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
|
||||
assert result["estado"] == "ok", result
|
||||
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
|
||||
|
||||
@@ -354,7 +354,14 @@ TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
|
||||
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO])
|
||||
# The oracle is the kit's output at the kit's 180-day horizon from the sample to the diagnosis; the project's is 120 (a
|
||||
# parameter it set on purpose), so a sample the kit measures at 161 days is no longer measured. The comparison fails
|
||||
# for that period until the oracle is regenerated from the kit with the project's horizon (strict: it then asks for
|
||||
# this mark to go).
|
||||
SIN_ORACULO_DE_120 = pytest.mark.xfail(strict=True, reason="the kit's oracle uses a 180-day horizon from the sample to the diagnosis; the project's is 120")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, pytest.param(DIAS_TOMA_DIAGNOSTICO, marks=SIN_ORACULO_DE_120)])
|
||||
def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url):
|
||||
"""Pins down the duration construct, for the time to the result and the time to the first note that resolves
|
||||
the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the
|
||||
@@ -526,14 +533,15 @@ DIAS_TOMA_TRATAMIENTO = "cacu/CACU_DIAS_TOMA_TRATAMIENTO"
|
||||
DIAS_DIAGNOSTICO_TRATAMIENTO = "cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url, expected", [(DIAS_TOMA_TRATAMIENTO, (4, 1, 58.0, 3)), (DIAS_DIAGNOSTICO_TRATAMIENTO, (1, 1, 18.0, 0))])
|
||||
@pytest.mark.parametrize("url, expected", [(DIAS_TOMA_TRATAMIENTO, (1, 1, 58.0, 0)), (DIAS_DIAGNOSTICO_TRATAMIENTO, (1, 1, 18.0, 0))])
|
||||
def test_the_times_to_treatment_are_counted_from_their_start_to_the_first_treatment(base_con_tratamiento, manifest, url, expected):
|
||||
"""Pins down the two times to treatment on the fixture with H-004's colposcopy and treatment, 2025-S2 cut at the
|
||||
end of the year, with a 60-day horizon. From the sample: H-004's July sample reaches her treatment of August 28 in
|
||||
58 days; the other three samples of the semester have no treatment and their horizon has passed, so they are in
|
||||
the initial population and not measured. From the diagnosis: only that sample has one in the period, and its
|
||||
diagnosis of August 10 reaches the treatment in 18 days. Fails if the end event, the start (sample or diagnosis),
|
||||
the horizon rule or the split between not measured yet and without event changes."""
|
||||
end of the year. From the sample (a 180-day horizon): H-004's July sample reaches her treatment of August 28 in 58
|
||||
days; the others of the semester (August 12, September 1 and October 2) have no treatment and their horizon is
|
||||
after the cut, so they are pending and not in the initial population. From the diagnosis (60 days): only that
|
||||
sample has one in the period, and its diagnosis of August 10 reaches the treatment in 18 days. Fails if the end
|
||||
event, the start (sample or diagnosis), the horizon
|
||||
rule or the split between not measured yet and without event changes."""
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
|
||||
definition = duration_definitions(manifest)[url]
|
||||
|
||||
@@ -56,7 +56,7 @@ def cuenta(base, sql):
|
||||
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
estimador = EstimadorFijo()
|
||||
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL]
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: [estimador]})["estimate"][URL][0]
|
||||
|
||||
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
|
||||
assert nuevo and miembros > 0
|
||||
@@ -68,16 +68,30 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
|
||||
|
||||
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
|
||||
assert cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0] == (primero, False)
|
||||
assert cacu.run("estimate")["estimate"] == {}
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_dos_modelos_de_una_cohorte_dejan_un_lote_cada_uno(cacu):
|
||||
"""Two estimators on one cohort (two scenarios in production on the same build) write one batch each. Fails if
|
||||
`estimate` keeps only one estimator per cohort or folds two models into one batch."""
|
||||
class OtroModelo(EstimadorFijo):
|
||||
def procedencia(self):
|
||||
return Procedencia(modelo_nombre="cacu-otro")
|
||||
|
||||
lotes = cacu.run("estimate", estimators={URL: [EstimadorFijo(), OtroModelo()]})["estimate"][URL]
|
||||
|
||||
assert [nuevo for _, nuevo in lotes] == [True, True] and lotes[0][0] != lotes[1][0]
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
|
||||
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
|
||||
|
||||
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
|
||||
|
||||
@@ -100,3 +100,17 @@ def test_an_unknown_batch_is_404(client):
|
||||
"""Pins down: a `lote_id` with no evaluations is 404, not a silent no-op. Fails if it answers 200 having changed
|
||||
nothing."""
|
||||
assert client.post("/cacu/riesgos/lotes/987654321/confirmar", json={"reason": "revisado"}).status_code == 404
|
||||
|
||||
|
||||
def test_a_decision_that_collides_with_another_is_409(client, monkeypatch):
|
||||
"""Pins down: two decisions of one batch at the same moment (a double click reaching both workers) give the
|
||||
second a 409 instead of a server error. Fails if the unique version of an evaluation surfaces as a 500."""
|
||||
from persistance import cacu
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
def collide(*args, **kwargs):
|
||||
raise IntegrityError("INSERT", {}, Exception("UNIQUE constraint failed"))
|
||||
|
||||
monkeypatch.setattr(cacu.cohort_repository, "change_state", collide)
|
||||
|
||||
assert client.post("/cacu/riesgos/lotes/1/confirmar", json={"reason": "revisado"}).status_code == 409
|
||||
|
||||
@@ -43,6 +43,18 @@ def test_paciente_schema_coerces_date_from_datetime_object():
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_cacu_paciente_keeps_her_date_of_death():
|
||||
"""Pins down: a CaCu patient's `pac_fecha_defuncion` is imported (the survival scenario's outcome), and an alive
|
||||
patient has none. Fails if the schema drops the column again: every CaCu death would be lost on import and the
|
||||
survival model would train with no deaths."""
|
||||
from datetime import date
|
||||
|
||||
dead = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="1960-03-01", pac_fecha_defuncion="2025-07-09")
|
||||
alive = PacienteImportSchema(pac_id_hospital="H-2", pac_fecha_nacimiento="1960-03-01")
|
||||
|
||||
assert dead.pac_fecha_defuncion == date(2025, 7, 9) and alive.pac_fecha_defuncion is None
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_is_fully_optional():
|
||||
schema = PacientesImportSchema()
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
+124
-4
@@ -8,9 +8,10 @@ de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostr
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "horizontes_disponibles", "reglas",
|
||||
"paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -41,12 +42,13 @@ def test_el_pedido_se_respeta(client):
|
||||
|
||||
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
||||
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA"}
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA", "orden": "reciente", "horizonte": 5.0}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500"],
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500",
|
||||
"?orden=edad", "?horizonte=cinco"],
|
||||
)
|
||||
def test_un_pedido_mal_escrito_o_fuera_de_rango_da_400(client, query):
|
||||
response = client.get(f"/cacu/seguimiento{query}")
|
||||
@@ -68,3 +70,121 @@ def test_in_dev_esta_obsoleta():
|
||||
|
||||
with pytest.warns(DeprecationWarning):
|
||||
in_dev()
|
||||
|
||||
|
||||
def test_la_lista_se_ordena_por_la_probabilidad_de_lieag_al_horizonte_pedido(client):
|
||||
"""Fija: con un lote de CIN2+ confirmado, cada fila trae sus probabilidades por horizonte y `orden=lieag` pone
|
||||
primero a la de mayor probabilidad al `horizonte` pedido, y al final a quien el modelo no evalúa; un horizonte que
|
||||
los modelos no dan es 400. Falla si la lista deja de leer los lotes vigentes, o si ordena solo dentro de la página."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
baja, alta = int(filas[0]["pac_id"]), int(filas[1]["pac_id"])
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.3.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-orden",
|
||||
marco_sha="m", n_miembros=2, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (baja, alta)])
|
||||
session.commit()
|
||||
armado = build.armado_id
|
||||
indice = date(2025, 3, 1)
|
||||
lote, _ = cacu.cohort_repository.save_batch(
|
||||
armado, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "9", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2", [(baja, indice, 1.0, 0.02, 0.01, 0.04), (baja, indice, 5.0, 0.05, 0.03, 0.08),
|
||||
(alta, indice, 1.0, 0.10, 0.07, 0.14), (alta, indice, 5.0, 0.30, 0.22, 0.40)])
|
||||
cacu.cohort_repository.change_state(lote, "final", "revisado")
|
||||
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=lieag&horizonte=1").get_json()
|
||||
|
||||
assert cuerpo["horizontes_disponibles"] == [1.0, 5.0] and cuerpo["filtros"]["orden"] == "lieag"
|
||||
assert [i["pac_id"] for i in cuerpo["items"][:2]] == [str(alta), str(baja)]
|
||||
assert cuerpo["items"][0]["probabilidades"]["lieag"][1] == {"horizonte_anios": 5.0, "probabilidad": 0.30,
|
||||
"ic_bajo": 0.22, "ic_alto": 0.40}
|
||||
assert all(i["probabilidades"] is None for i in cuerpo["items"][2:])
|
||||
assert client.get("/cacu/seguimiento?corte=2025-12-31&orden=lieag&horizonte=3").status_code == 400
|
||||
|
||||
|
||||
def test_un_caso_tiene_su_estatus_y_su_probabilidad_de_supervivencia(client):
|
||||
"""Fija: una paciente con biopsia de carcinoma es CASO, gane lo que gane lo demás, y su probabilidad de supervivencia
|
||||
es 1 − la de morir del modelo de supervivencia, con el IC invertido, y 1 a los 0 años; la lista se ordena por ella.
|
||||
Falla si CASO
|
||||
deja de ganar o si la supervivencia se muestra como la probabilidad de morir."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
from webapi.follow_up.status import ESTATUS
|
||||
|
||||
assert ESTATUS[0] == "CASO"
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
paciente = int(filas[2]["pac_id"])
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_total", version="0.4.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-caso",
|
||||
marco_sha="m", n_miembros=1, armado_en=datetime(2026, 1, 2, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=paciente, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="biopsiacervical", indice_fuente_id=str(paciente)))
|
||||
session.commit()
|
||||
armado = build.armado_id
|
||||
lote, _ = cacu.cohort_repository.save_batch(
|
||||
armado, {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"muerte", [(paciente, date(2025, 3, 1), 5.0, 0.30, 0.20, 0.45)])
|
||||
cacu.cohort_repository.change_state(lote, "final", "revisado")
|
||||
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=supervivencia&horizonte=5"
|
||||
).get_json()
|
||||
|
||||
primera = cuerpo["items"][0]
|
||||
assert primera["pac_id"] == str(paciente)
|
||||
assert primera["probabilidades"]["supervivencia"] == [
|
||||
{"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0},
|
||||
{"horizonte_anios": 5.0, "probabilidad": 0.7, "ic_bajo": 0.55, "ic_alto": 0.8}]
|
||||
|
||||
|
||||
def test_una_biopsia_de_un_grado_de_caso_hace_caso_a_la_paciente(client, monkeypatch):
|
||||
"""Fija: quien tiene una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` al corte es CASO, gane lo
|
||||
que gane lo demás, y nadie sin una lo es; el filtro `estatus=CASO` las da. La base de demostración no tiene
|
||||
carcinomas, así que la regla se toma aquí como CIN2. Falla si la precedencia deja de poner CASO primero o el
|
||||
estatus deja de leer el grado de la biopsia de su regla."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from persistance.db import get_cacu_session
|
||||
from webapi.follow_up import listing
|
||||
from webapi.follow_up.silver import biopsias
|
||||
|
||||
original = listing.valor_de
|
||||
monkeypatch.setattr(listing, "valor_de", lambda sesion, clave, **kw:
|
||||
["CIN2"] if clave == "cacu.seguimiento.caso.grados" else original(sesion, clave, **kw))
|
||||
b = biopsias()
|
||||
with get_cacu_session() as session:
|
||||
con_cin2 = {r.pac_id for r in session.execute(select(b.c.pac_id).where(b.c.grado == "CIN2"))}
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
casos = {int(i["pac_id"]) for i in filas if i["estatus"]["codigo"] == "CASO"}
|
||||
|
||||
assert casos and casos == con_cin2 & {int(i["pac_id"]) for i in filas}
|
||||
solo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&estatus=CASO").get_json()["items"]
|
||||
assert {int(i["pac_id"]) for i in solo} == casos
|
||||
|
||||
|
||||
def test_un_caso_es_un_carcinoma_invasor_o_in_situ():
|
||||
"""Fija: la regla de CASO toma CIS y carcinoma, como el índice del escenario de supervivencia, para que la tabla y
|
||||
la supervivencia hablen de las mismas pacientes. Falla si la regla deja fuera el in situ."""
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import webapi.orchestration.reference as referencia
|
||||
|
||||
parametros = tomllib.loads((Path(referencia.__file__).parent / "parametros.toml").read_text(encoding="utf-8"))
|
||||
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
|
||||
|
||||
@@ -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()}
|
||||
|
||||
Reference in New Issue
Block a user