Compare commits

...

12 Commits

Author SHA1 Message Date
edgar 2ee95576a8 Tests: the cycle builds every dbt cohort of each project, CaMa's survival cohort included
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 02:14:26 -06:00
edgar f34c2b5116 Merge remote-tracking branch 'origin/feature/163-cama-risk-curves' into feature/cohorts-dbt-canonical 2026-11-21 02:06:26 -06:00
rockdrigo 9b617db9d0 CaMa: two clinical scenarios, post-treatment and under observation, with the follow-up list's scenario column and filter 2026-11-21 01:55:04 -06:00
rockdrigo d1e06798c9 Tests: no CaMa measure is served by clinical stage or tumour size; the stratifiers view is built in its own test 2026-11-20 23:28:33 -06:00
edgar 26f2b35338 Retire GET /cacu/pacientes/<id>/riesgo: the record reads the FHIR RiskAssessment
The WebApp patient record now reads GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> (WebApp
feature/cohorts-dbt-canonical), so the custom route, its blueprint and its tests go; the risk batches and the
follow-up list point to the FHIR search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:15:55 -06:00
edgar 0c1b383da2 CaCu's individual risk as a FHIR RiskAssessment, and each risk's index date
GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> (DEV only, tagged simulado, a searchset validated with R4B, as
TEA's patient resources): the patient's current batch, one prediction per horizon with its outcome, probability and
whenPeriod from the risk's index date, the confidence interval in an extension; declared in the CapabilityStatement.
GET /cacu/pacientes/<id>/riesgo adds riesgo.fecha_indice. Tests and the risk-band fixture carry the index date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:46 -06:00
edgar 7d06f9db9d The cycle builds the cohorts dbt defines; models' moved modules
The `cohorts` and `estimate` steps take the project's cohorts from dbt's manifest (`cohort_urls`) and build each one
with models' `build_of` over dbt's queries, instead of the Python-frame TOMLs in models/cohorts, which are gone; without
a manifest a project has no cohort steps. The recruitment window and cut-off are dbt's vars. The live estimator reads
cin2_logistic through `Scenario` and `KitBuild`, and governance imports `models.reports.experiment`, where models now
keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:18:00 -06:00
rockdrigo 8130f86f3a Silver persona carries the date of death in CaCu and CaMa; tests for it and for CaMa's birth and death on the timeline 2026-11-20 18:46:40 -06:00
rockdrigo 028f774400 Tests: CaMa's clinical scenarios as a hierarchy, with discharge notes starting post-treatment 2026-11-20 17:03:38 -06:00
rockdrigo ca0f02aa0c A coded catalog result may name the code system of its values; the histological type comes out as its ICD-O-3 code 2026-11-20 17:03:38 -06:00
rockdrigo 7a84cb19c9 Tests: each CaMa patient's scenario and the evidence that starts it 2026-11-20 17:03:38 -06:00
rockdrigo 5a4baeb33e Tests: CaMa's stage and size measures of invasive cancers, and the measure counts 2026-11-20 17:03:38 -06:00
30 changed files with 574 additions and 310 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
set -e
# The notebook runner shares the image but runs with no network, a read-only
# system and only the jobs folder (models.io.notebook_jobs): it never touches /data.
# system and only the jobs folder (models.reports.notebook_jobs): it never touches /data.
if [ "$1" = "notebooks" ]; then
exec /app/WebApi/.venv/bin/python -m models notebooks serve
fi
+18 -8
View File
@@ -16,9 +16,9 @@ armado = [
]
lote_final = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 3, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, fecha_indice = 2025-08-01, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
[[caso]]
@@ -34,6 +34,16 @@ incluye = ["armado", "lote_final"]
filas = []
espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 }
[[caso]]
nombre = "el periodo es el de la fecha índice del riesgo, no la del miembro"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-09-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0 }
espera."2025-S2" = { "cat:BAJO" = 1 }
[[caso]]
nombre = "los cortes son parámetros"
incluye = ["armado", "lote_final"]
@@ -46,7 +56,7 @@ nombre = "un lote preliminar más nuevo no desplaza al vigente"
incluye = ["armado", "lote_final"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 2, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "2", mlflow_run_id = "sin-mlflow", modelo_sha = "s2", desenlace = "c", evaluado_en = 2026-02-01T00:00:00Z, n_evaluaciones = 1, huella = "l2" },
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
@@ -54,7 +64,7 @@ espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
nombre = "una evaluación anulada en su versión 2 queda sin dato"
incluye = ["armado", "lote_final"]
filas = [
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
]
espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 }
@@ -63,7 +73,7 @@ nombre = "una evaluación a otro horizonte no cuenta"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
@@ -72,7 +82,7 @@ nombre = "sin lote confirmado no hay población"
incluye = ["armado"]
filas = [
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
@@ -82,6 +92,6 @@ filas = [
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/otra", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 1, armado_en = 2026-01-01T00:00:00Z },
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
]
espera."2025-S1" = { "cat:BAJO" = 0 }
+55 -4
View File
@@ -8,6 +8,7 @@ invented patients with the cases below; their names (`P01`...) are the source id
Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6):
BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day.
P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it.
No patient has a post-treatment fact in her timeline, so everyone is under observation; `con_postratamiento` adds some.
"""
import json
@@ -151,14 +152,16 @@ def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app):
def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app):
"""Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its
date: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data
doesn't support is added, or the hospital's identifier leaks."""
date, and the clinical scenario: no status, priority, days or pseudonym, and no source id anywhere in the body.
Fails if a column the data doesn't support is added, or the hospital's identifier leaks."""
respuesta = get(app, page_size=200)
cuerpo = respuesta.get_json()
assert cuerpo["simulado"] is True
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha"} for i in cuerpo["items"])
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha",
"escenario_clinico"} for i in cuerpo["items"])
assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"}
assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"])
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia"]
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"]
assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES)
assert respuesta.headers["Cache-Control"] == "no-store"
@@ -368,3 +371,51 @@ def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_
with Session(base.motor) as sesion:
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")]
@pytest.fixture
def con_postratamiento(tmp_path):
"""The same 17 patients, with the timeline replaced by a table holding post-treatment facts: P01 to P05 on
2025-11-01 and P06 on 2026-01-15, after the cut-off."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
from sqlalchemy import text
base = base_de("cama", tmp_path, datos=insertar)
base.run(*UNTIL_MODELS, allow_undecided=True)
hechos = {**{f"P0{n}": "2025-11-01" for n in range(1, 6)}, "P06": "2026-01-15"}
with base.motor.begin() as c:
for drop in ("drop view cama_linea_de_tiempo", "drop table cama_linea_de_tiempo"):
try:
with c.begin_nested():
c.execute(text(drop))
except Exception:
pass
c.execute(text("create table cama_linea_de_tiempo (pac_id integer, tipo text, fecha date)"))
for hospital, fecha in hechos.items():
c.execute(text("insert into cama_linea_de_tiempo select pac_id, 'escenario_postratamiento', :f from paciente "
"where pac_id_hospital = :h"), {"f": fecha, "h": hospital})
flask = Flask(__name__)
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
yield base, flask.test_client()
base.motor.dispose()
def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observation_otherwise(con_postratamiento):
"""Pins down: a patient is `POST_TRATAMIENTO` once her timeline's `escenario_postratamiento` fact is on or before the
cut-off (P01-P05 at 2025-12-31, P06 only from 2026-01-15) and `EN_OBSERVACION` otherwise; the filter selects by it
and offers both values with their labels. Fails if a fact after the cut-off counts, if the scenario is read from
something other than the timeline, or if the filter stops being offered."""
base, app = con_postratamiento
nombres = hospital_de(base)
escenario = lambda corte: {nombres[i["pac_id"]]: i["escenario_clinico"]
for i in get(app, corte=corte, page_size=200).get_json()["items"]}
al_corte = escenario(CORTE)
assert {h for h, e in al_corte.items() if e == "POST_TRATAMIENTO"} == {"P01", "P02", "P03", "P04", "P05"}
assert {e for h, e in al_corte.items() if h not in {"P01", "P02", "P03", "P04", "P05"}} == {"EN_OBSERVACION"}
assert escenario("2026-01-31")["P06"] == "POST_TRATAMIENTO"
filtrada = get(app, escenario_clinico="POST_TRATAMIENTO", page_size=200)
assert {nombres[p] for p in pacs(filtrada)} == {"P01", "P02", "P03", "P04", "P05"}
filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico")
assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"},
{"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}]
+78
View File
@@ -0,0 +1,78 @@
"""What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`,
rules in `cama.escenarios`): post-treatment from a discharge note after a malignant breast tumour's diagnosis, carried by
her timeline as an `escenario_postratamiento` fact with the evidence that started it; every other patient is under
observation ("en observación"), which has no fact.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30,
H-101 01-15, H-102 02-20, H-103 07-01, H-104 11-11; notes H-003 C50.4 (08-04), H-103 C50.9 (07-20), H-102 C50.9 (09-30),
H-001 D05.1 (03-01), H-101 Z12.3 (01-15), H-104 C50 without a date; H-003 an invasive biopsy (07-28). No note has a
type: the tests that need a discharge write `nota_medica.tipo_nota` themselves.
"""
import os
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
@pytest.fixture
def base(tmp_path, manifest):
base = base_de("cama", tmp_path)
base.run("catalogs", "load", "views", "event_models")
yield base
base.motor.dispose()
def scenarios(base) -> dict[str, set[tuple[str, date, str]]]:
"""Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence)."""
with base.motor.connect() as con:
rows = con.execute(text(
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l "
"join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all()
found: dict[str, set[tuple[str, date, str]]] = {}
for r in rows:
found.setdefault(r.pac_id_hospital, set()).add((r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo))
return found
def discharge(base, hospital_id: str) -> None:
"""Marks the patient's notes as discharge notes, as a load that brings `nm_tipo_nota` would."""
with base.motor.begin() as con:
con.execute(text(
"insert into observacion_clinica (procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) "
"select p.procedimiento_id, p.carga_id, p.pac_id, 'nota_medica.tipo_nota', 'EGRESO', 'EGRESO' "
"from procedimiento p join paciente x on x.pac_id = p.pac_id "
"where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id})
def test_without_a_discharge_every_patient_is_under_observation(base):
"""Pins down: a mammogram, a malignant ICD-10 note (H-003, H-102, H-103) or an invasive biopsy (H-003) alone start
no scenario: with no discharge note nobody is in post-treatment and the timeline has no scenario fact, which reads as
under observation. Fails if screening or a diagnosis go back to being scenarios of their own."""
assert scenarios(base) == {}
def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base):
"""Pins down: a discharge note that carries a malignant tumour's ICD-10 puts H-003 in post-treatment from its date,
and only her. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops reading the note's type."""
discharge(base, "H-003")
assert scenarios(base) == {"H-003": {("escenario_postratamiento", date(2025, 8, 4), "egreso")}}
def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base):
"""Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her
under observation: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it."""
discharge(base, "H-101")
assert scenarios(base) == {}
+31 -60
View File
@@ -1,13 +1,13 @@
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata.
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the
labels a timeline stratum's values carry into FHIR.
"""What this module covers: CaMa's tumour characteristics read from reports. dbt's `cama_estratificadores` (stage
group, early or advanced stage, T by size) as timeline facts; that no measure is served by clinical stage or tumour
size; `CAMA_BIRADS_CANCER_INVASOR` without tumour strata; and the labels a timeline stratum's values carry into FHIR.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on
2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA.
2025-07-28 from her BI-RADS 4A mammogram (14 mm), and a note of 2025-08-04 with stage IIA.
"""
import json
import os
from dataclasses import replace
from datetime import date
@@ -20,7 +20,7 @@ from webapi.compositions import answer_composition, composition_definitions
from webapi.fhir.measures import _label
from webapi.metrics import Question
URL = "cama/CAMA_BIRADS_CANCER_INVASOR"
BIRADS = "cama/CAMA_BIRADS_CANCER_INVASOR"
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
@@ -40,72 +40,43 @@ def base(tmp_path, sin_supresion, manifest):
base.motor.dispose()
def answered(base, manifest, period: str, event_cutoff: date | None = None):
def answered(base, manifest, url: str, period: str, event_cutoff: date | None = None):
d = base.dominio
definition = composition_definitions(manifest)[URL]
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff),
definition = composition_definitions(manifest)[url]
return answer_composition("cama", definition, Question(url, period, event_cutoff=event_cutoff),
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True)
def stratifiers(base) -> set[str]:
def stratifiers(base, manifest) -> set[str]:
"""The stratifiers' `tipo`s, from the view built here: no served measure reads it, so the cycle doesn't."""
node = next(n for n in json.loads(manifest.read_text(encoding="utf-8"))["nodes"].values()
if n["resource_type"] == "model" and n["name"] == "cama_estratificadores")
with base.motor.connect() as con:
return set(con.execute(text("select tipo from cama_estratificadores")).scalars())
return set(con.execute(text(f"select tipo from ({node['compiled_code']}) e")).scalars())
def test_the_stratifiers_come_from_h003_s_reports(base):
"""Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in
`vars.cama.estratos` or a timeline `tipo` it reads changes."""
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"}
def test_the_stratifiers_come_from_h003_s_reports(base, manifest):
"""Pins down: the view derives the stage's group and early stage from the note and T1 from the 14 mm lesion, and
nothing else: there's no molecular subtype. Fails if a rule in `vars.cama.estratos` or a timeline `tipo` it reads
changes, or a subtype comes back."""
assert stratifiers(base, manifest) == {"estadio_ii", "etapa_temprana", "tamano_t1"}
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest):
"""Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the
category or a stratum's values drift."""
assert answered(base, manifest, "2025-S1").categories == {}
result = answered(base, manifest, "2025-S2")
assert result.categories == {"B4A": 1}
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}},
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}},
"tamano": {"T1": {"B4A": 1}}}
def test_no_measure_is_served_by_stage_or_tumour_size(manifest):
"""Pins down: clinical stage and tumour size aren't served as measures; they come from reports read by text, not
yet validated. Fails if a measure on them is published again."""
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
urls = {m["config"].get("meta", {}).get("measure_url") for m in metrics} - {None}
assert BIRADS in urls and BIRADS in composition_definitions(manifest)
assert not {u for u in urls if "ESTADIO" in u or "TAMANO" in u}
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest):
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype
(report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage)."""
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
SUBTIPOS = [
({"her2": "H3"}, "subtipo_her2"),
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"),
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"),
({"her2": "H0", "ki67_pct": None}, None),
({"her2": "H2"}, None),
]
@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS)
def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo):
"""Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both
receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and
progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's
report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise.
Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes."""
valores = {"receptor_progesterona": "POSITIVO", **cambios}
with base.motor.begin() as con:
for nombre, valor in valores.items():
columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id"
con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"),
{"v": valor, "r": f"biopsia.{nombre}"})
assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set())
def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest):
"""Pins down: the BI-RADS of the mammogram before an invasive cancer isn't broken down by the tumour's
characteristics, which describe the cancer and not that mammogram. Fails if tumour strata come back."""
result = answered(base, manifest, BIRADS, "2025-S2")
assert (result.categories, result.strata) == ({"B4A": 1}, {})
def test_a_timeline_stratum_s_values_carry_their_labels():
+62
View File
@@ -0,0 +1,62 @@
"""What this module covers: a patient's date of death, from staging (`paciente.pac_fecha_defuncion`) to silver's
`persona.fecha_defuncion` in CaCu and CaMa, and in CaMa onto her timeline as a `defuncion` fact next to her birth.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base_con_defuncion`, the domain's
fixture database (`staging/<domain>.py`) with one patient given a date of death before it's loaded.
"""
import os
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
DEATH = date(2026, 2, 1)
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
def with_death(domain: str, tmp_path):
"""The domain's fixture database with its first patient (lowest `pac_id`) dead on `DEATH`, loaded to silver."""
base = base_de(domain, tmp_path)
with base.motor.begin() as con:
con.execute(text("update paciente set pac_fecha_defuncion = :d where pac_id = (select min(pac_id) from paciente)"),
{"d": DEATH})
return base
@pytest.mark.parametrize("domain", ["cacu", "cama"])
def test_silver_persona_carries_the_date_of_death(domain, tmp_path, manifest):
"""Pins down: the dead patient's `persona` has her date of death and everyone else's is null. Fails if the
staging-to-silver copy (`persons.de_derechohabiente`) stops carrying `pac_fecha_defuncion`."""
base = with_death(domain, tmp_path)
base.run("catalogs", "load")
with base.motor.connect() as con:
rows = con.execute(text("select pac_id, fecha_defuncion from persona order by pac_id")).all()
base.motor.dispose()
assert [date.fromisoformat(str(rows[0].fecha_defuncion)[:10])] + [r.fecha_defuncion for r in rows[1:]] \
== [DEATH] + [None] * (len(rows) - 1)
def test_cama_timeline_has_birth_for_everyone_and_death_for_the_dead(tmp_path, manifest):
"""Pins down: every CaMa patient has a `nacimiento` fact and only the dead one a `defuncion` fact, on her date of
death, with class `persona`. Fails if the timeline stops reading `persona` or reads a null date as a death."""
base = with_death("cama", tmp_path)
base.run("catalogs", "load", "views", "event_models")
with base.motor.connect() as con:
people = con.execute(text("select count(*) from persona")).scalar_one()
facts = con.execute(text(
"select tipo, pac_id, fecha, clase from cama_linea_de_tiempo where tipo in ('nacimiento', 'defuncion')")).all()
first = con.execute(text("select min(pac_id) from persona")).scalar_one()
base.motor.dispose()
assert sum(f.tipo == "nacimiento" for f in facts) == people
assert [(f.pac_id, date.fromisoformat(str(f.fecha)[:10]), f.clase) for f in facts if f.tipo == "defuncion"] \
== [(first, DEATH, "persona")]
+1 -1
View File
@@ -125,7 +125,7 @@ def test_a_pathology_pdf_s_text_layer_gives_its_results():
going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor."""
leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1])))
assert {r: v for r, (v, _) in leido.items()} == {
"biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2",
"biopsia.tipo_histologico": "8500/3", "biopsia.grado_nottingham": "G2",
"biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0,
"biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0,
"biopsia.her2": "H3", "biopsia.ki67_pct": 25.0,
+109
View File
@@ -0,0 +1,109 @@
"""What this module covers: `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cacu`): a patient's
current risk as a FHIR R4 `RiskAssessment` in a `searchset` Bundle, as TEA's patient resources are served: the
resource's shape (status, subject, method, one prediction per horizon from the risk's index date, the interval
extension), the `simulado` tag, an empty Bundle without a confirmed batch, a 400 without `subject`, and the
`CapabilityStatement` entry. The reads behind it are Persistance's, tested there.
Fixtures: `client`, the app in DEV (`DEV_REVISION`, so the patient routes exist) over the kit's CaCu demonstration
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a surveillance build with two of its patients, one
with a confirmed batch whose risks have the model's index date.
"""
import os
from datetime import date, datetime, timezone
import pytest
from conftest import cliente_de
MODEL_INDEX = date(2026, 6, 1)
@pytest.fixture(scope="module")
def client(tmp_path_factory):
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
with pytest.MonkeyPatch.context() as mp:
mp.setenv("DEV_REVISION", "pruebas")
yield from cliente_de("cacu", tmp_path_factory)
@pytest.fixture(scope="module")
def seeded(client):
"""Two demo patients in a new surveillance build; the first has a confirmed batch with risks at 0 and 3 years, the
3-year one with an interval. Returns (scored patient, member without risks)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
from persistance import cacu
from persistance.db import get_cacu_session
scored, unscored = [p.pac_id for p in cacu.persona_repository.list(limit=2)]
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk", marco_sha="m",
n_miembros=2, armado_en=datetime(2027, 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 (scored, unscored)])
session.commit()
build_id = build.armado_id
batch, _ = cacu.cohort_repository.save_batch(
build_id, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2_mas", [(scored, MODEL_INDEX, 3.0, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.0, 0.08, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(batch, "final", "revisado")
return scored, unscored, batch
def test_a_scored_patient_gets_her_risk_assessment(client, seeded):
"""Pins down the resource: a `searchset` of one `RiskAssessment`, `final`, about `Patient/<pac_id>`, evaluated
when the batch was, by the registered model and version, with one prediction per horizon whose period starts at
the risk's index date (the model's, not the member's) and ends a horizon later; the interval in its extension;
tagged `simulado`. Fails if a field moves out of FHIR's shape or the period is anchored elsewhere."""
scored, _, batch = seeded
response = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}")
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
bundle = response.get_json()
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 1)
risk = bundle["entry"][0]["resource"]
assert bundle["entry"][0]["fullUrl"].endswith(f"/cacu/fhir/RiskAssessment/{batch}-{scored}")
assert (risk["resourceType"], risk["status"], risk["subject"]) == ("RiskAssessment", "final", {"reference": f"Patient/{scored}"})
assert risk["occurrenceDateTime"] == "2026-10-01T00:00:00Z"
assert risk["method"]["coding"][0]["code"] == "cacu-cin2_pim" and risk["method"]["coding"][0]["version"] == "3"
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["cin2_mas", "cin2_mas"]
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
(0.08, {"start": "2026-06-01", "end": "2026-06-01"}), (0.21, {"start": "2026-06-01", "end": "2029-06-01"})]
assert "extension" not in risk["prediction"][0]
assert risk["prediction"][1]["extension"][0]["valueRange"] == {"low": {"value": 0.15}, "high": {"value": 0.28}}
assert any(t["code"] == "simulado" for t in risk["meta"]["tag"])
def test_without_a_confirmed_batch_the_bundle_is_empty(client, seeded):
"""Pins down: a member with no confirmed risk, and an unknown patient, get an empty searchset, not an error.
Fails if a missing risk becomes a 404 or a resource with no predictions."""
_, unscored, _ = seeded
for subject in (f"Patient/{unscored}", "Patient/987654321"):
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject={subject}").get_json()
assert (bundle["total"], bundle.get("entry", [])) == (0, []) # R4B drops an empty `entry`
@pytest.mark.parametrize("query", ["", "?subject=Patient/abc", "?subject=Group/1"])
def test_the_risk_is_searched_by_patient(client, query):
"""Pins down: without `subject=Patient/<pac_id>` the answer is a 400 `OperationOutcome`. Fails if the route lists
every patient's risk."""
response = client.get(f"/cacu/fhir/RiskAssessment{query}")
assert response.status_code == 400 and response.get_json()["resourceType"] == "OperationOutcome"
def test_the_capability_statement_declares_the_search(client):
"""Pins down: CaCu's CapabilityStatement lists `RiskAssessment` with its `subject` search; TEA's patient
resources stay TEA's. Fails if the route exists without being declared, or the other way round."""
resources = client.get("/cacu/fhir/metadata").get_json()["rest"][0]["resource"]
risk = [r for r in resources if r["type"] == "RiskAssessment"]
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
+16 -7
View File
@@ -15,6 +15,7 @@ from sqlalchemy import create_engine, text
from sqlmodel import Session
from webapi.orchestration import Context, run
from webapi.orchestration.project import cohort_urls
from webapi.orchestration.connection import point_to
ANIO = 2025
@@ -65,16 +66,24 @@ def test_volver_a_correr_no_agrega_reportes(bases):
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
def test_en_cacu_arma_su_cohorte_una_vez(bases):
def test_arma_cada_cohorte_de_dbt_una_vez(bases):
"""Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores
as many members as it counts (CaCu's, CaMa's survival cohort); a project without dbt cohorts (TEA) has no cohort
step. Fails if a cohort comes from anywhere else than dbt, or a build's count and members disagree."""
proyecto, ctx, motor, _, pasos = bases
if proyecto != "cacu":
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
urls = set(cohort_urls(proyecto, ctx.dbt_manifest))
if not urls:
assert "cohorts" not in [p.name for p in pasos]
return
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
armados = [p.summary for p in pasos if p.name == "cohorts"][0]
assert set(armados) == urls
assert {"cacu": "cacu/cohorte_vigilancia", "cama": "cama/cohorte_supervivencia"}[proyecto] in armados
with motor.connect() as con:
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados)
for armado_id, _ in armados.values():
assert con.execute(text("SELECT n_miembros FROM cohorte_armado WHERE armado_id = :a"),
{"a": armado_id}).scalar_one() == con.execute(
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
+3 -3
View File
@@ -84,9 +84,9 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
# TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto]
# CaCu: three strata and its seven measures; CaMa: the BI-RADS stratum of the histopathological result and its
# eleven measures; TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 12, "tea": 11}[base.proyecto]
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0
+14 -4
View File
@@ -1,5 +1,7 @@
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
import json
import pytest
from hamilton import driver
@@ -33,8 +35,16 @@ def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
assert {"load", "catalogs"} <= antes(deps, "check_silver")
def test_solo_cacu_arma_cohortes_y_estima_por_ahora():
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
def test_las_cohortes_son_las_del_manifiesto_de_dbt(tmp_path, monkeypatch):
"""Pins down: a project builds cohorts and estimates only if dbt's manifest has a cohort of it (`meta.cohort` of
a population query), today only CaCu's; without a manifest no project does. Fails if the cycle reads cohort
definitions from anywhere else than dbt."""
manifest = tmp_path / "manifest.json"
nodo = {"config": {"meta": {"cohort": "cacu/cohorte_vigilancia", "kind": "population"}}}
manifest.write_text(json.dumps({"nodes": {"model.p.cacu_surveillance_all_patients": nodo}}))
assert {"cohorts", "estimate"} <= set(steps_of("cacu", manifest))
for proyecto in ("cama", "tea"):
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
assert not {"cohorts", "estimate"} & set(steps_of(proyecto, manifest))
monkeypatch.delenv("DBT_MANIFEST", raising=False)
assert not {"cohorts", "estimate"} & set(steps_of("cacu"))
+1 -1
View File
@@ -38,7 +38,7 @@ class EstimadorFijo:
def estimar(self, columnas, filas):
self.columnas = columnas
return [(fila[0], self.horizonte, self.probabilidad, None, None) for fila in filas]
return [(fila[0], fila[1], self.horizonte, self.probabilidad, None, None) for fila in filas]
@pytest.fixture
-87
View File
@@ -1,87 +0,0 @@
"""What this module covers: `GET /cacu/pacientes/<pac_id>/riesgo` (`webapi.patient_risk`): when the route exists, the
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
there.
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
"""
from datetime import date, datetime, timezone
import pytest
from conftest import cliente_de
COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"}
RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "estado_lote", "horizontes"}
HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"}
@pytest.fixture(scope="module")
def client(tmp_path_factory):
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
with pytest.MonkeyPatch.context() as mp:
mp.delenv("DEV_REVISION", raising=False)
yield from cliente_de("cacu", tmp_path_factory)
@pytest.fixture(scope="module")
def seeded(client):
"""Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at
1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable
from persistance import cacu
from persistance.db import get_cacu_session
scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)]
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-route", marco_sha="m",
n_miembros=2, armado_en=datetime(2027, 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 (scored, unscored)])
session.flush()
session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"),
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
session.commit()
build_id = build.armado_id
batch, _ = cacu.cohort_repository.save_batch(
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(batch, "final", "revisado")
return scored, unscored, outside
def test_a_scored_member_has_the_contracts_shape(client, seeded):
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
the WebApp's validation."""
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
body = response.get_json()
assert response.status_code == 200 and body["simulado"] is True
assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS
assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None)
assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final"
horizons = body["riesgo"]["horizontes"]
assert all(set(h) == HORIZON_KEYS for h in horizons)
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
null. Fails if either case errors or invents a risk."""
member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json()
outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json()
assert member["cohorte"] is not None and member["riesgo"] is None
assert outside == {"simulado": True, "cohorte": None, "riesgo": None}
def test_an_unknown_patient_is_404(client, seeded):
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
+1 -1
View File
@@ -41,7 +41,7 @@ def batches(client):
def batch(version, risk, ahora):
lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version},
"cin2_12m", [(pac_id, 1.0, risk, None, None)], ahora=ahora)
"cin2_12m", [(pac_id, date(2025, 1, 1), 1.0, risk, None, None)], ahora=ahora)
return lote_id
older = batch("1", 0.1, datetime(2026, 10, 1, tzinfo=timezone.utc))
+2 -4
View File
@@ -92,18 +92,16 @@ def create_app() -> Flask:
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
url_prefix=f"/{domain}/fhir")
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
# an access rule still to be defined, not an environment variable.
# Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's
# `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined.
from persistance import cacu as cacu_repositories
from persistance.db import get_cacu_session, get_cama_session
from webapi.patient_risk import patient_risk_blueprint
from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
return app
+2 -2
View File
@@ -8,7 +8,7 @@ either run elsewhere and register its result through `POST /model-versions`
`cohorte_armado_id`), or be triggered in place through `POST
/model-versions/<domain>/<scenario>/train`, for a deployment with no
command-line access to run the `entrenar` compose profile by hand.
Notebooks (`models.pipelines.experiment`) run in the background on the build's
Notebooks (`models.reports.experiment`) run in the background on the build's
file alone and are kept as MLflow runs.
"""
import contextlib
@@ -28,7 +28,7 @@ from models.io.lineage import DOMAINS
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
from models.io.storage import build_file, cohorts_root, exported_builds
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
from models.pipelines import experiment
from models.reports import experiment
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
from persistance.settings import settings
+21 -3
View File
@@ -6,12 +6,14 @@ date taken, then the greatest source id, then the latest report date, then the g
always gives the same cohort. A report that carries two different BI-RADS counts through the more severe one
(`cama.birads_gravedad`), and a biopsy report with two different grades through the more severe grade. The biopsy
shown is the latest report, on or before the cut-off and not before the mammogram, of a biopsy that mammogram led to.
Her clinical scenario at the cut-off is post-treatment when her timeline has an `escenario_postratamiento` fact dated on
or before it (`cama_procedimientos_inferidos`, rules in `cama.escenarios`), and under observation otherwise.
Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off.
"""
from dataclasses import dataclass
from datetime import date
from datetime import date, timedelta
from sqlalchemy import Date, Integer, String, column, func, inspect, select, table
from sqlmodel import Session
@@ -25,6 +27,8 @@ ESCENARIO = "diagnostico"
VERSION = "0.1.0"
SIN_DATO = "SIN_DATO"
SIN_BIOPSIA = "SIN_BIOPSIA"
POST_TRATAMIENTO = "POST_TRATAMIENTO"
EN_OBSERVACION = "EN_OBSERVACION"
# Grades from least to most severe, for two contradictory results of the same report; any other grade ranks lowest.
GRADOS_POR_GRAVEDAD = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR")
@@ -35,14 +39,17 @@ CANDIDATOS = table(
column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String),
column("biopsia_fecha_reporte", Date), column("biopsia_grado", String),
)
LINEA_DE_TIEMPO = table("cama_linea_de_tiempo", column("pac_id", Integer), column("tipo", String), column("fecha", Date))
class CohorteNoDisponible(RuntimeError):
"""The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503)."""
"""The cohort's view or the timeline isn't in the database: the indicator cycle that creates the event views hasn't
run (503)."""
def disponible(sesion: Session) -> bool:
return inspect(sesion.get_bind()).has_table(CANDIDATOS.name)
inspector = inspect(sesion.get_bind())
return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO))
@dataclass(frozen=True)
@@ -58,6 +65,7 @@ class Fila:
# The earliest eligible biopsy report, and the earliest one whose grade counts as cancer (`cama.biopsia_cancer`).
primera_biopsia_fecha: date | None = None
primer_maligno_fecha: date | None = None
escenario_clinico: str = EN_OBSERVACION
@property
def resultado(self) -> str:
@@ -93,8 +101,17 @@ def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str:
return SIN_DATO
def en_postratamiento(sesion: Session, corte: date) -> set[int]:
"""The patients whose timeline puts them in post-treatment on or before `corte`."""
linea = LINEA_DE_TIEMPO.c
# Before the next day, so a date stored with a time still counts on its own day.
return set(sesion.execute(select(linea.pac_id).distinct().where(
linea.tipo == "escenario_postratamiento", linea.fecha < corte + timedelta(days=1))).scalars())
def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
postratamiento = en_postratamiento(sesion, corte)
admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS))
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
grupos = grupos_de_cortes(valor_de(sesion, "cama.grupos_edad", tablas=TABLAS), tablas=TABLAS)
@@ -133,6 +150,7 @@ def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
biopsia_fecha=biopsia["biopsia_fecha_reporte"] if biopsia else None,
primera_biopsia_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"]), default=None),
primer_maligno_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"] if b["biopsia_grado"] in malignos), default=None),
escenario_clinico=POST_TRATAMIENTO if pac_id in postratamiento else EN_OBSERVACION,
))
return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id))
+7 -2
View File
@@ -14,7 +14,7 @@ from datetime import date, timedelta
from sqlmodel import Session
from webapi.cama_follow_up.cohort import (
COHORTE, ESCENARIO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
COHORTE, EN_OBSERVACION, ESCENARIO, POST_TRATAMIENTO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
disponible, grupos_de_edad,
)
from webapi.orchestration.reference.rules import valor_de
@@ -25,11 +25,13 @@ VENTANA_POR_OMISION = 3
PAGINA_MAXIMA = 200
EXPORTACION_MAXIMA = 5000
GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"}
ESCENARIOS_CLINICOS = {POST_TRATAMIENTO: "Post-tratamiento", EN_OBSERVACION: "En observación"}
COLUMNAS = [
{"clave": "pac_id", "etiqueta": "Identificador de paciente"},
{"clave": "grupo_edad", "etiqueta": "Grupo de edad"},
{"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]},
{"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico"},
]
@@ -80,6 +82,8 @@ def filtros_disponibles(sesion: Session) -> list[dict]:
*({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()),
{"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"},
{"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]},
{"clave": "escenario_clinico", "etiqueta": "Escenario clínico", "opciones": [
{"codigo": c, "etiqueta": e} for c, e in ESCENARIOS_CLINICOS.items()]},
]
@@ -114,7 +118,8 @@ def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict)
def _item(f: Fila) -> dict:
return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads,
"mastografia_fecha": f.mastografia_fecha.isoformat(), "biopsia": f.biopsia,
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None}
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None,
"escenario_clinico": f.escenario_clinico}
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
+1 -1
View File
@@ -15,7 +15,7 @@ from webapi.cama_follow_up.listing import (
)
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
FILTROS = ("birads", "grupo_edad", "biopsia")
FILTROS = ("birads", "grupo_edad", "biopsia", "escenario_clinico")
CONTEXTO = ("cohorte", "escenario", "revision")
ENTEROS = ("meses", "page", "page_size")
+29 -1
View File
@@ -1,4 +1,5 @@
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA and CaCu, its patients' screening and
individual risk.
GET metadata CapabilityStatement
GET Measure, Measure/<id> the measures (dbt's definitions)
@@ -8,6 +9,7 @@
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
GET RiskAssessment?subject=Patient/<pac_id> CaCu's individual risk, the current batch (DEV only)
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
@@ -36,6 +38,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
blueprint = Blueprint(f"{project}_fhir", __name__)
titles = labels(manifest)
patients = with_patients and project == "tea"
risks = with_patients and project == "cacu"
def definitions() -> dict:
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
@@ -80,6 +83,9 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
"definition": canonical("OperationDefinition/resumen-tea")}]},
{"type": "ValueSet", "interaction": [{"code": "read"}]},
]
if risks:
resources += [{"type": "RiskAssessment", "interaction": [{"code": "search-type"}],
"searchParam": [{"name": "subject", "type": "reference"}]}]
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
@@ -169,9 +175,31 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
if patients:
_patient_routes(blueprint, repositories, now)
if risks:
_risk_routes(blueprint, repositories)
return blueprint
def _risk_routes(blueprint: Blueprint, repositories) -> None:
"""CaCu's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data)."""
from webapi.fhir import cacu
@blueprint.get("/RiskAssessment")
def risk_assessments():
subject = request.args.get("subject", "")
reference = subject.removeprefix("Patient/")
if not reference.isdigit():
return outcome(400, "invalid", "falta `subject=Patient/<pac_id>`: el riesgo se busca por paciente")
try:
count, offset = page()
except ValueError as error:
return outcome(400, "invalid", str(error))
pac_id = int(reference)
risk = repositories.cohort_repository.current_risk(pac_id)
found = [] if risk is None else [cacu.risk_assessment(pac_id, risk, simulated_data())]
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
def _period_asked(repositories):
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
if periodo := request.args.get("periodo"):
+62
View File
@@ -0,0 +1,62 @@
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data).
The risk is the patient's current batch (`CohortRepository.current_risk`): the newest batch with a confirmed
evaluation, the same the patient record shows. One `RiskAssessment` per batch and patient:
id `<lote_id>-<pac_id>`
status the batch's state (`final`)
subject `Patient/<pac_id>`: CaCu's follow-up list uses the platform's `pac_id` (TEA keeps a
pseudonym until its patients get their own identity)
occurrenceDateTime when the batch was evaluated
method the registered model and its version (MLflow)
prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod`
from the risk's index date (the model's decision point) to that date plus the horizon;
the immediate risk (horizon 0) is a period of one day. A confidence interval, when the
model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a
decimal or a range, not both).
Not yet: `basis` (CaCu doesn't publish its cytology and HPV `Observation`s) and `mitigation` (ASCCP's clinical
action thresholds are for CIN3+; the outcome here is CIN2+).
"""
from datetime import date, datetime, timedelta, timezone
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
OUTCOME = f"{CODE_SYSTEM}/desenlace"
MODEL = f"{CODE_SYSTEM}/modelo"
INTERVAL = f"{STRUCTURE}/intervalo-confianza"
OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses"}
DAYS_PER_YEAR = 365.25
def _utc(moment: datetime) -> str:
moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _until(start: date, years: float) -> date:
return start + timedelta(days=round(years * DAYS_PER_YEAR))
def _prediction(horizon, outcome: dict, start: date | None) -> dict:
item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad}
if start is not None:
item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()}
if horizon.ic_bajo is not None and horizon.ic_alto is not None:
item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo},
"high": {"value": horizon.ic_alto}}}]
return item
def risk_assessment(pac_id: int, risk, simulated: bool) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`."""
desenlace = risk.desenlace or "cin2_mas"
outcome = concept(OUTCOME, desenlace, OUTCOMES.get(desenlace))
resource = {
"resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote,
"subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en),
"method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]},
"prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes],
}
return tagged(resource, simulated)
+1 -1
View File
@@ -9,7 +9,7 @@ de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
misma que usan los lotes de riesgo y `GET /cacu/pacientes/<pac_id>/riesgo`; `id_seudonimo` repite ese valor
misma que usan los lotes de riesgo y `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`; `id_seudonimo` repite ese valor
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
+17 -33
View File
@@ -37,13 +37,13 @@ from webapi.orchestration.reference.rules import (
from webapi.orchestration.reference.periods import periodos_de_tipos
from webapi.orchestration.tables import tablas_de
from persistance.edges.silver import save_load_in
from sqlmodel import SQLModel, func, select
from sqlmodel import SQLModel, select
from webapi.orchestration.context import Context
from webapi.orchestration.semantic_layer import catalog_layers, event_views
from models.cohorts.build import build_of, latest_build, read_frame
from models.cohorts.definition import read_definition
from webapi.orchestration.project import cohort_definitions, period_types
from models.io.storage import read_queries
from webapi.orchestration.project import cohort_urls, period_types
log = logging.getLogger(__name__)
@@ -188,23 +188,17 @@ def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict
@config.when(with_cohorts=True)
def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read.
"""Arma cada cohorte del proyecto con las reglas de dbt, su única definición: la población, la fecha índice, las
exclusiones y las variables son consultas del manifest (`read_queries`), con su ventana de reclutamiento y su
corte (las variables de dbt), y corren en la base después de `event_models`.
"""
tablas = tablas_de(ctx.project)
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1)
def armado(definicion, sesion):
corte = ctx.cutoff or _last_load_date(sesion, tablas)
return build_of(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
linea=ctx.repos.silver.timeline.query)
manifest = _manifest(ctx)
armados = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion))
for url in cohort_urls(ctx.project, manifest):
consultas = read_queries(manifest, url)
armados[url] = ctx.repos.gold.cohorts.assemble(
lambda sesion, consultas=consultas: build_of(sesion, consultas, cohortes=tablas_cohorte))
return armados
@@ -220,30 +214,20 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
"""
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
lotes = {}
for ruta in cohort_definitions(ctx.project):
definicion = read_definition(ruta)
estimador = ctx.estimators.get(definicion.url)
for url in cohort_urls(ctx.project, _manifest(ctx)):
estimador = ctx.estimators.get(url)
if estimador is None:
continue
def frame(sesion, definicion=definicion):
armado_id = latest_build(sesion, definicion.url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, definicion,
cohortes=tablas_cohorte)
def frame(sesion, url=url):
armado_id = latest_build(sesion, url, cohortes=tablas_cohorte)
return armado_id, None if armado_id is None else read_frame(sesion, armado_id, cohortes=tablas_cohorte)
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
if armado_id is None:
continue
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
lotes[definicion.url] = ctx.repos.gold.cohorts.save_batch(
lotes[url] = ctx.repos.gold.cohorts.save_batch(
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
)
return lotes
def _last_load_date(sesion, tablas) -> date | None:
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
if ultima is None or isinstance(ultima, date):
return ultima.date() if isinstance(ultima, datetime) else ultima
return date.fromisoformat(str(ultima)[:10])
+23 -21
View File
@@ -3,9 +3,9 @@ its domain has in production.
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an
estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership,
the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go
set, so an estimator here ignores the wide frame and rebuilds the model's own input (`models.io.storage.KitBuild`):
the cycle's latest build for membership, the domain's timeline for the events, then the production version in
MLflow to score it at the horizons its run recorded (`horizons_years`). `estimar`'s arguments go
unused by design.
"""
@@ -37,28 +37,29 @@ class Cin2LogisticEstimator:
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
import mlflow.pyfunc
from persistance.settings import settings
import json
from models.cacu.cin2_logistic.model import SETTINGS
import mlflow.pyfunc
import numpy as np
from models.dags.estimation import estimate_frame
from models.dags.training import Scenario
from models.io.registry import registered_name, registry
from models.io.storage import cohorts_root, read_cohort
from models.pipelines.export_cohort import export_kit_build
from models.io.storage import KitBuild
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
url = SETTINGS["cohort"]
build_id = repos.cohort_repository.latest_build(url)
resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version)
root = cohorts_root(getattr(settings, f"{self.domain}_database_url"))
path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id)
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path))
window = SETTINGS["outcome_window_months"]
self.desenlace = f"cin2_{window}m"
scenario = Scenario.load(self.domain, "cin2_logistic")
build_id = repos.cohort_repository.latest_build(scenario.cohort)
resolved = registry.resolve(self.domain, scenario.scenario, self.version)
frame = KitBuild(self.domain, build_id).frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(frame))
self.desenlace = scenario.outcome
self._provenance = Provenance(
modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version,
modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version,
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
return [tuple(row) for row in risk_rows(risks, window / 12)]
return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))]
def procedencia(self) -> Provenance:
if self._provenance is None:
@@ -71,11 +72,12 @@ def live_estimators(domain: str) -> dict[str, Any]:
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
from models.cacu.cin2_logistic.model import SETTINGS
from models.dags.training import Scenario
from models.io.registry import registry
scenario = Scenario.load(domain, "cin2_logistic")
try:
registry.resolve(domain, SETTINGS["scenario"])
registry.resolve(domain, scenario.scenario)
except LookupError:
return {}
return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)}
return {scenario.cohort: Cin2LogisticEstimator(domain)}
+6 -6
View File
@@ -1,9 +1,9 @@
"""What the cycle needs to know of a project's definitions: its period types (dbt) and its cohorts (`models.cohorts`)."""
"""What the cycle needs to know of a project's definitions, all from dbt's manifest: its period types and its cohorts."""
import json
from pathlib import Path
from models.cohorts.definition import ROOT
from models.io.storage import cohort_urls as _cohort_urls
def period_types(proyecto: str, manifest: Path) -> list[str]:
@@ -13,7 +13,7 @@ def period_types(proyecto: str, manifest: Path) -> list[str]:
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
def cohort_definitions(proyecto: str) -> list[Path]:
"""The cohort TOMLs the cycle builds (`models/cohorts/<project>/*.toml`): today only CaCu's surveillance cohort.
Those in `<project>/proposals/` aren't built."""
return sorted((ROOT / proyecto).glob("*.toml"))
def cohort_urls(proyecto: str, manifest: Path | None) -> list[str]:
"""The cohorts the cycle builds: those of the project in dbt's manifest (`Transformation/models/<project>/cohorts/`,
`meta.cohort` of their population query). dbt is their only definition. None without a manifest."""
return _cohort_urls(manifest, proyecto) if manifest else []
+2 -2
View File
@@ -204,8 +204,8 @@ def _tipo_de_valor(resultado: dict, resultado_id: str) -> str:
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.")
if tipo_valor != "codigo" and "valores" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.")
if tipo_valor != "externo" and "sistema" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.")
if tipo_valor not in ("codigo", "externo") and "sistema" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo o externo lleva sistema, no uno de tipo {tipo_valor}.")
if tipo_valor != "numero" and "unidad" in resultado:
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.")
return tipo_valor
+7 -6
View File
@@ -18,7 +18,8 @@ from hamilton.lifecycle import NodeExecutionHook
from webapi.orchestration import cycle
from webapi.orchestration.context import Context
from webapi.orchestration.project import cohort_definitions
from webapi.orchestration.context import dbt_manifest_path
from webapi.orchestration.project import cohort_urls
from webapi.orchestration.repositories import repositories_of
log = logging.getLogger(__name__)
@@ -49,10 +50,10 @@ class _Logbook(NodeExecutionHook):
log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds)
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
def _driver(proyecto: str, manifest, *adaptadores) -> driver.Driver:
return (driver.Builder()
.with_modules(cycle)
.with_config({"with_cohorts": bool(cohort_definitions(proyecto))})
.with_config({"with_cohorts": bool(cohort_urls(proyecto, manifest))})
.with_adapters(*adaptadores)
.build())
@@ -61,9 +62,9 @@ def _in_order(dr: driver.Driver) -> list[str]:
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
def steps_of(proyecto: str) -> list[str]:
def steps_of(proyecto: str, manifest=None) -> list[str]:
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, only donde hay definiciones)."""
return _in_order(_driver(proyecto))
return _in_order(_driver(proyecto, manifest or dbt_manifest_path()))
def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
@@ -75,7 +76,7 @@ def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
if ctx.repos is None:
ctx = replace(ctx, repos=repositories_of(ctx.project))
bitacora = _Logbook()
dr = _driver(ctx.project, bitacora)
dr = _driver(ctx.project, ctx.dbt_manifest, bitacora)
todos = _in_order(dr)
pedidos = [p for p in todos if only is None or p in only]
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})
+1
View File
@@ -22,6 +22,7 @@ def de_derechohabiente(paciente) -> dict:
"dependencia": texto_limpio(paciente.pac_dependencia),
"parentesco": texto_limpio(paciente.pac_parentesco),
"codigo_postal": texto_limpio(paciente.pac_codigo_postal),
"fecha_defuncion": paciente.pac_fecha_defuncion,
}
-49
View File
@@ -1,49 +0,0 @@
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
evaluation. Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
removed or renamed, only added.
"""
from datetime import timezone
from flask import Blueprint, jsonify
COHORT_URL = "cacu/cohorte_vigilancia"
COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
def patient_risk_blueprint(repositories) -> Blueprint:
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
blueprint = Blueprint("cacu_patient_risk", __name__)
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
def get_patient_risk(pac_id: int):
"""A patient's cohort membership and risks in the current batch (DEV only, simulated data)."""
if repositories.persona_repository.get(pac_id) is None:
return jsonify({"error": f"no existe la paciente {pac_id}"}), 404
membership = repositories.cohort_repository.membership(pac_id, COHORT_URL)
risk = repositories.cohort_repository.current_risk(pac_id)
return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)})
return blueprint
def _cohort(membership) -> dict | None:
if membership is None:
return None
return {"url": membership.url, "version": membership.version, "fecha_indice": membership.fecha_indice.isoformat(),
**{name: membership.variables.get(name) for name in COHORT_VARIABLES}}
def _risk(risk) -> dict | None:
if risk is None:
return None
evaluated = risk.evaluado_en if risk.evaluado_en.tzinfo else risk.evaluado_en.replace(tzinfo=timezone.utc)
return {"lote_id": risk.lote_id, "modelo_nombre": risk.modelo_nombre, "modelo_version": risk.modelo_version,
"evaluado_en": evaluated.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"estado_lote": risk.estado_lote,
"horizontes": [{"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
"ic_alto": h.ic_alto, "estado": h.estado} for h in risk.horizontes]}
+3 -2
View File
@@ -1,7 +1,8 @@
"""Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet,
confirm one (`preliminary` -> `final`, visible on `/cacu/pacientes/<id>/riesgo`) or void it (`entered-in-error`).
confirm one (`preliminary` -> `final`, then served as the patient's FHIR `RiskAssessment`,
`/cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`) or void it (`entered-in-error`).
`GET/POST /<domain>/riesgos/lotes...`. The route is always registered; who may act on it is an access rule still
to be defined, as `patient_risk.py` notes for reads.
to be defined.
"""
from flask import Blueprint, jsonify, request