From 4c5bccb80507db3be51345937af33d36827c9939 Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 09:29:21 +0000 Subject: [PATCH 01/11] T-21b: el contrato EstimadorDeRiesgo y el estimador sustituto RiesgoSintetico (ADR-MD-008) CSO5.5 Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++ models/riesgo.py | 91 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_riesgo.py | 47 +++++++++++++++++++++++ 3 files changed, 146 insertions(+) create mode 100644 models/riesgo.py create mode 100644 tests/test_riesgo.py diff --git a/README.md b/README.md index de51761..824f879 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,11 @@ Each domain's available repositories (`paciente_repository`, `citologia_cervical_repository`, etc.) and how to extend one with table-specific business logic are documented in `../Persistance/README.md`. + +## Riesgos (ADR-MD-008) + +`models/riesgo.py` es el contrato con que Orquestacion pide riesgos a un modelo: `EstimadorDeRiesgo` +(recibe el marco ancho de un armado de cohorte y devuelve un `Riesgo` por miembro y horizonte, más su +`Procedencia`, las llaves para conciliar con MLflow). `RiesgoSintetico` es un sustituto determinista, sin +MLflow, para pruebas y para desplegar sin el modelo real; no es un modelo clínico. El modelo real +(Modelo-cacu, con su artefacto de MLflow) entra como otra clase que cumple el contrato (MD-Q6). diff --git a/models/riesgo.py b/models/riesgo.py new file mode 100644 index 0000000..f9dcc1a --- /dev/null +++ b/models/riesgo.py @@ -0,0 +1,91 @@ +"""El contrato con que se le pide a un modelo el riesgo de los miembros de una cohorte (ADR-MD-008). + +Quien llama (la arista `estimar` de Orquestacion) le da al estimador el marco de un armado +de cohorte, ancho: `(columnas, filas)`, con `columnas = ["pac_id", "fecha_indice", ]` +(lo que devuelve `indicadores_kit.cohortes.armado.leer_marco`). El estimador devuelve un +`Riesgo` por miembro y horizonte, y su `Procedencia`: las llaves con que se concilia con +MLflow (opción A del prototipo; MLflow no guarda filas ni pacientes). + +Este módulo no importa al kit, a Persistance ni a Orquestacion: recibe listas. +""" + +import hashlib +import json +from dataclasses import asdict, dataclass +from typing import NamedTuple, Protocol, runtime_checkable + + +class Riesgo(NamedTuple): + """El riesgo de un miembro a un horizonte (FHIR `RiskAssessment.prediction`).""" + + pac_id: int + horizonte_anios: float # años desde la fecha índice; 0 = prevalente + probabilidad: float # de 0 a 1 + ic_bajo: float | None = None + ic_alto: float | None = None + + +@dataclass(frozen=True) +class Procedencia: + """De qué modelo salen los riesgos: las llaves que guarda el lote (`PROCEDENCIA` de Persistance).""" + + modelo_nombre: str + modelo_version: str + mlflow_run_id: str + modelo_sha: str + + def como_dict(self) -> dict[str, str]: + return asdict(self) + + +@runtime_checkable +class EstimadorDeRiesgo(Protocol): + """Lo que cumple todo modelo de riesgo que Orquestacion puede llamar.""" + + cohorte_url: str # la cohorte cuyo marco consume ("cacu/cohorte_vigilancia") + desenlace: str # lo que predice ("cin2_mas") + + def procedencia(self) -> Procedencia: ... + + def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: ... + + +# La regla del sustituto: una probabilidad base y lo que suma cada predictor basal. +REGLA_SINTETICA = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95} +PAP_NORMALES = ("NORMAL",) + + +class RiesgoSintetico: + """Un estimador sustituto determinista, sin MLflow: para pruebas y para desplegar sin el modelo real. + + La probabilidad sale de una tabla fija por los predictores basales: `REGLA_SINTETICA["base"]`, + más `pap_anormal` si `pap_0` no es `NORMAL` ni nulo, más `vph_positivo` si `hpv_0` es + `POSITIVO`, con tope. Sin intervalo. No es un modelo clínico. + """ + + def __init__(self, cohorte_url: str = "cacu/cohorte_vigilancia", desenlace: str = "cin2_mas", + horizontes: tuple[float, ...] = (0.0,)): + self.cohorte_url = cohorte_url + self.desenlace = desenlace + self.horizontes = tuple(horizontes) + + def procedencia(self) -> Procedencia: + regla = {"regla": REGLA_SINTETICA, "pap_normales": PAP_NORMALES, "horizontes": self.horizontes} + sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest() + return Procedencia(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha) + + def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: + faltan = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columnas] + if faltan: + raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.") + i_pac, i_pap, i_vph = (columnas.index(c) for c in ("pac_id", "pap_0", "hpv_0")) + riesgos = [] + for fila in filas: + p = REGLA_SINTETICA["base"] + if fila[i_pap] is not None and fila[i_pap] not in PAP_NORMALES: + p += REGLA_SINTETICA["pap_anormal"] + if fila[i_vph] == "POSITIVO": + p += REGLA_SINTETICA["vph_positivo"] + p = min(p, REGLA_SINTETICA["tope"]) + riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] + return riesgos diff --git a/tests/test_riesgo.py b/tests/test_riesgo.py new file mode 100644 index 0000000..2a19da7 --- /dev/null +++ b/tests/test_riesgo.py @@ -0,0 +1,47 @@ +"""El contrato `EstimadorDeRiesgo` y el estimador sustituto (ADR-MD-008).""" + +import pytest + +from models import riesgo +from models.riesgo import EstimadorDeRiesgo, Riesgo, RiesgoSintetico + +COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"] +FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)] + + +def test_el_sustituto_cumple_el_contrato(): + assert isinstance(RiesgoSintetico(), EstimadorDeRiesgo) + + +def test_un_riesgo_por_miembro_y_horizonte_en_el_orden_del_marco(): + riesgos = RiesgoSintetico(horizontes=(0.0, 1.0)).estimar(COLUMNAS, FILAS) + + assert [(r.pac_id, r.horizonte_anios) for r in riesgos] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)] + assert all(isinstance(r, Riesgo) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in riesgos) + + +def test_la_regla_suma_por_predictor_basal(): + p = {r.pac_id: r.probabilidad for r in RiesgoSintetico().estimar(COLUMNAS, FILAS)} + + assert p == {1: 0.01, 2: 0.16, 3: 0.01} + + +def test_es_determinista(): + a, b = RiesgoSintetico(), RiesgoSintetico() + + assert a.estimar(COLUMNAS, FILAS) == b.estimar(COLUMNAS, FILAS) + assert a.procedencia() == b.procedencia() + + +def test_la_procedencia_trae_las_cuatro_llaves_y_su_sha_cambia_con_la_regla(monkeypatch): + procedencia = RiesgoSintetico().procedencia() + assert set(procedencia.como_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"} + assert all(procedencia.como_dict().values()) + + monkeypatch.setitem(riesgo.REGLA_SINTETICA, "vph_positivo", 0.2) + assert RiesgoSintetico().procedencia().modelo_sha != procedencia.modelo_sha + + +def test_sin_los_predictores_falla_y_los_nombra(): + with pytest.raises(ValueError, match="pap_0"): + RiesgoSintetico().estimar(["pac_id", "hpv_0"], [(1, None)]) -- 2.53.0 From 04c8cbafd179a72dc764c2e016049701f5e6c42c Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 12:34:55 +0000 Subject: [PATCH 02/11] T-21f: RiesgoSinteticoTea, el sustituto de TEA sobre la cohorte de tamizaje CSO5.5 Co-Authored-By: Claude Opus 5.5 --- models/riesgo.py | 45 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_riesgo.py | 28 ++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/models/riesgo.py b/models/riesgo.py index f9dcc1a..b716758 100644 --- a/models/riesgo.py +++ b/models/riesgo.py @@ -89,3 +89,48 @@ class RiesgoSintetico: p = min(p, REGLA_SINTETICA["tope"]) riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] return riesgos + + +# La regla del sustituto de TEA: lo que suma la interpretación del M-CHAT índice y lo perinatal. +REGLA_SINTETICA_TEA = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05, + "apgar_corte": 7, "tope": 0.95} + + +class RiesgoSinteticoTea: + """El sustituto determinista de TEA, sobre el marco de `tea/cohorte_tamizaje` (T-21e). Sin MLflow. + + La probabilidad de un diagnóstico de TEA al horizonte (2 años, el de la cohorte) es + `REGLA_SINTETICA_TEA["base"]`, más `mchat_medio` o `mchat_alto` según `mchat_0`, más `ucin` si + `ingreso_ucin` es 1, más `apgar_bajo` si `apgar_5min` es menor que `apgar_corte`, con tope. Sin + intervalo. No es un modelo clínico. + """ + + def __init__(self, cohorte_url: str = "tea/cohorte_tamizaje", desenlace: str = "d", + horizontes: tuple[float, ...] = (2.0,)): + self.cohorte_url = cohorte_url + self.desenlace = desenlace + self.horizontes = tuple(horizontes) + + def procedencia(self) -> Procedencia: + regla = {"regla": REGLA_SINTETICA_TEA, "horizontes": self.horizontes} + sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest() + return Procedencia(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow", + modelo_sha=sha) + + def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: + necesarias = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min") + faltan = [c for c in necesarias if c not in columnas] + if faltan: + raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.") + i_pac, i_mchat, i_ucin, i_apgar = (columnas.index(c) for c in necesarias) + r = REGLA_SINTETICA_TEA + riesgos = [] + for fila in filas: + p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(fila[i_mchat], 0.0) + if fila[i_ucin] == 1: + p += r["ucin"] + if fila[i_apgar] is not None and fila[i_apgar] < r["apgar_corte"]: + p += r["apgar_bajo"] + p = min(p, r["tope"]) + riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] + return riesgos diff --git a/tests/test_riesgo.py b/tests/test_riesgo.py index 2a19da7..c45fa15 100644 --- a/tests/test_riesgo.py +++ b/tests/test_riesgo.py @@ -3,7 +3,7 @@ import pytest from models import riesgo -from models.riesgo import EstimadorDeRiesgo, Riesgo, RiesgoSintetico +from models.riesgo import REGLA_SINTETICA_TEA, EstimadorDeRiesgo, Riesgo, RiesgoSintetico, RiesgoSinteticoTea COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"] FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)] @@ -45,3 +45,29 @@ def test_la_procedencia_trae_las_cuatro_llaves_y_su_sha_cambia_con_la_regla(monk def test_sin_los_predictores_falla_y_los_nombra(): with pytest.raises(ValueError, match="pap_0"): RiesgoSintetico().estimar(["pac_id", "hpv_0"], [(1, None)]) + + +# --- El sustituto de TEA (T-21f) --------------------------------------------------------------- + +COLUMNAS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes", + "hipoacusia_0"] + + +def test_el_sustituto_de_tea_cumple_el_contrato_y_lee_su_cohorte(): + estimador = RiesgoSinteticoTea() + assert isinstance(estimador, EstimadorDeRiesgo) + assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (2.0,) + + +def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo(): + filas = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None), + (2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"), + (3, None, None, None, None, None, None, 0, None)] + r = REGLA_SINTETICA_TEA + assert [x.probabilidad for x in RiesgoSinteticoTea().estimar(COLUMNAS_TEA, filas)] == pytest.approx( + [r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]]) + + +def test_el_sustituto_de_tea_sin_sus_predictores_falla(): + with pytest.raises(ValueError, match="mchat_0"): + RiesgoSinteticoTea().estimar(["pac_id", "fecha_indice"], []) -- 2.53.0 From e5526b9ec349abe8e2b9f995fc7c6a4ad024198a Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 13:55:48 +0000 Subject: [PATCH 03/11] =?UTF-8?q?T-21g:=20RiesgoSinteticoCama,=20el=20sust?= =?UTF-8?q?ituto=20de=20CaMa=20por=20BI-RADS=20=C3=ADndice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CSO5.5 Co-Authored-By: Claude Opus 5.5 --- models/riesgo.py | 40 ++++++++++++++++++++++++++++++++++++++++ tests/test_riesgo.py | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/models/riesgo.py b/models/riesgo.py index b716758..9381958 100644 --- a/models/riesgo.py +++ b/models/riesgo.py @@ -134,3 +134,43 @@ class RiesgoSinteticoTea: p = min(p, r["tope"]) riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] return riesgos + + +# La regla del sustituto de CaMa: lo que suma el BI-RADS índice. +REGLA_SINTETICA_CAMA = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80, + "tope": 0.95} +BIRADS_SUSPECHA = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4", + "B4C": "birads_4", "B5": "birads_5"} + + +class RiesgoSinteticoCama: + """El sustituto determinista de CaMa, sobre el marco de `cama/cohorte_tamizaje` (T-21g). Sin MLflow. + + La probabilidad de cáncer de mama por biopsia al horizonte (1 año, el de la cohorte) es + `REGLA_SINTETICA_CAMA["base"]` más lo que suma la categoría del BI-RADS índice (`birads_0`), con + tope. Las subcategorías 4A, 4B y 4C suman como 4. Sin intervalo. No es un modelo clínico. + """ + + def __init__(self, cohorte_url: str = "cama/cohorte_tamizaje", desenlace: str = "d", + horizontes: tuple[float, ...] = (1.0,)): + self.cohorte_url = cohorte_url + self.desenlace = desenlace + self.horizontes = tuple(horizontes) + + def procedencia(self) -> Procedencia: + regla = {"regla": REGLA_SINTETICA_CAMA, "birads": BIRADS_SUSPECHA, "horizontes": self.horizontes} + sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest() + return Procedencia(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow", + modelo_sha=sha) + + def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: + faltan = [c for c in ("pac_id", "birads_0") if c not in columnas] + if faltan: + raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.") + i_pac, i_birads = columnas.index("pac_id"), columnas.index("birads_0") + r = REGLA_SINTETICA_CAMA + riesgos = [] + for fila in filas: + p = min(r["base"] + r.get(BIRADS_SUSPECHA.get(fila[i_birads]), 0.0), r["tope"]) + riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] + return riesgos diff --git a/tests/test_riesgo.py b/tests/test_riesgo.py index c45fa15..030d93c 100644 --- a/tests/test_riesgo.py +++ b/tests/test_riesgo.py @@ -3,7 +3,15 @@ import pytest from models import riesgo -from models.riesgo import REGLA_SINTETICA_TEA, EstimadorDeRiesgo, Riesgo, RiesgoSintetico, RiesgoSinteticoTea +from models.riesgo import ( + REGLA_SINTETICA_CAMA, + REGLA_SINTETICA_TEA, + EstimadorDeRiesgo, + Riesgo, + RiesgoSintetico, + RiesgoSinteticoCama, + RiesgoSinteticoTea, +) COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"] FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)] @@ -71,3 +79,27 @@ def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo(): def test_el_sustituto_de_tea_sin_sus_predictores_falla(): with pytest.raises(ValueError, match="mchat_0"): RiesgoSinteticoTea().estimar(["pac_id", "fecha_indice"], []) + + +# --- El sustituto de CaMa (T-21g) -------------------------------------------------------------- + +COLUMNAS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"] + + +def test_el_sustituto_de_cama_cumple_el_contrato_y_lee_su_cohorte(): + estimador = RiesgoSinteticoCama() + assert isinstance(estimador, EstimadorDeRiesgo) + assert estimador.cohorte_url == "cama/cohorte_tamizaje" and estimador.horizontes == (1.0,) + + +def test_la_regla_de_cama_suma_por_birads_indice_y_4a_cuenta_como_4(): + filas = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0), + (3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)] + r = REGLA_SINTETICA_CAMA + assert [x.probabilidad for x in RiesgoSinteticoCama().estimar(COLUMNAS_CAMA, filas)] == pytest.approx( + [r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]]) + + +def test_el_sustituto_de_cama_sin_su_predictor_falla(): + with pytest.raises(ValueError, match="birads_0"): + RiesgoSinteticoCama().estimar(["pac_id", "fecha_indice"], []) -- 2.53.0 From 92c5c69c2dbb43614d47a4ae56654ee9d2801914 Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 19:55:13 +0000 Subject: [PATCH 04/11] =?UTF-8?q?T-21h:=20el=20sustituto=20de=20TEA=20a=20?= =?UTF-8?q?4=20a=C3=B1os=20(48=20meses)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CSO5.5 Co-Authored-By: Claude Opus 5.5 --- models/riesgo.py | 4 ++-- tests/test_riesgo.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/models/riesgo.py b/models/riesgo.py index 9381958..738cbeb 100644 --- a/models/riesgo.py +++ b/models/riesgo.py @@ -99,14 +99,14 @@ REGLA_SINTETICA_TEA = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "u class RiesgoSinteticoTea: """El sustituto determinista de TEA, sobre el marco de `tea/cohorte_tamizaje` (T-21e). Sin MLflow. - La probabilidad de un diagnóstico de TEA al horizonte (2 años, el de la cohorte) es + La probabilidad de un diagnóstico de TEA al horizonte (4 años = 48 meses, el de la cohorte) es `REGLA_SINTETICA_TEA["base"]`, más `mchat_medio` o `mchat_alto` según `mchat_0`, más `ucin` si `ingreso_ucin` es 1, más `apgar_bajo` si `apgar_5min` es menor que `apgar_corte`, con tope. Sin intervalo. No es un modelo clínico. """ def __init__(self, cohorte_url: str = "tea/cohorte_tamizaje", desenlace: str = "d", - horizontes: tuple[float, ...] = (2.0,)): + horizontes: tuple[float, ...] = (4.0,)): self.cohorte_url = cohorte_url self.desenlace = desenlace self.horizontes = tuple(horizontes) diff --git a/tests/test_riesgo.py b/tests/test_riesgo.py index 030d93c..75c26d1 100644 --- a/tests/test_riesgo.py +++ b/tests/test_riesgo.py @@ -64,7 +64,7 @@ COLUMNAS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "in def test_el_sustituto_de_tea_cumple_el_contrato_y_lee_su_cohorte(): estimador = RiesgoSinteticoTea() assert isinstance(estimador, EstimadorDeRiesgo) - assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (2.0,) + assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (4.0,) def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo(): -- 2.53.0 From 28ff4605f3482b27c1c86d313a4676c3979a9f09 Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 22 Oct 2026 20:48:30 +0000 Subject: [PATCH 05/11] MD-008: prueba de concepto del modelo CIN2+ con MLflow (riesgo_logistico) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Entrena una logística sobre el marco de cacu/cohorte_vigilancia, la registra en MLflow (MLFLOW_TRACKING_URI; en el despliegue, el 9705) y la sirve a la arista `estimar` con EstimadorMlflow, que verifica el sha del artefacto. Sin pacientes en MLflow. mlflow-skinny fijado a la versión del servidor; mlflow completo solo en dev para las pruebas con sqlite. CSO5.5 Co-Authored-By: Claude Opus 5.5 --- models/riesgo_logistico.py | 187 +++++++++++++++++++++++++++++++++++++ pyproject.toml | 10 ++ 2 files changed, 197 insertions(+) create mode 100644 models/riesgo_logistico.py diff --git a/models/riesgo_logistico.py b/models/riesgo_logistico.py new file mode 100644 index 0000000..5b44366 --- /dev/null +++ b/models/riesgo_logistico.py @@ -0,0 +1,187 @@ +"""Prueba de concepto: un modelo de riesgo de CIN2+ con MLflow, de `toy-model/riesgo_juguete.py`. + +Entrena una logística sobre el marco de `cacu/cohorte_vigilancia`, la registra en MLflow +(`MLFLOW_TRACKING_URI`; en el despliegue, `http://:9705`) y la sirve a la arista `estimar` con +`EstimadorMlflow`, que cumple `EstimadorDeRiesgo`. Lo corre Orquestacion: + + uv run python -m orquestacion modelos entrenar [--horizonte 1] [--armado 3] + uv run python -m orquestacion ciclo cacu --desde 2025 --hasta 2025 --solo estimar --modelo cacu_cin2_mas --version 1 + +Sin pacientes en MLflow (ADR-MD-008): ni filas ni `input_example`. `ModeloCin2Mas` se serializa por +referencia a este módulo: cargarlo pide `models` instalado. +""" + +import hashlib +import tempfile +from pathlib import Path + +import mlflow +import numpy as np +import pandas as pd +from mlflow.models import ModelSignature +from mlflow.types import ColSpec, Schema +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import brier_score_loss, roc_auc_score + +from indicadores_kit.cacu.tablas import COHORTES +from indicadores_kit.oro.cohortes.armado import leer_marco, linaje, ultimo_armado +from indicadores_kit.oro.cohortes.definicion import leer_definicion, ruta_de_cohorte + +from models.riesgo import Procedencia, Riesgo + +EXPERIMENTO = "cacu-cin2" +NOMBRE_MODELO = "cacu_cin2_mas" +COHORTE_URL = "cacu/cohorte_vigilancia" +DESENLACE = "cin2_mas" +COVARIABLES = ["pap_0", "hpv_0"] +SIN_ESTADO = -999 +HORIZONTE = 1.0 + + +# 1 · descargar --------------------------------------------------------------------------- + +def descargar(repositorio, armado_id=None): + """El marco del armado (el último si no se dice) y su linaje `kit.*`, en una sesión de `repositorio`. Solo lee.""" + d = leer_definicion(ruta_de_cohorte("cacu", "cohorte_vigilancia")) + + def leer(sesion): + aid = armado_id if armado_id is not None else ultimo_armado(sesion, d.url, cohortes=COHORTES) + if aid is None: + raise LookupError(f"No hay armados de {d.url}: corre antes la arista `cohortes`.") + columnas, filas = leer_marco(sesion, aid, d, cohortes=COHORTES) + return pd.DataFrame(filas, columns=columnas), linaje(sesion, aid, d, cohortes=COHORTES) + + return repositorio.leer(leer) + + +# 2 · preparar ---------------------------------------------------------------------------- + +def a_nulos(df): + """`-999` es nulo, en números y en códigos.""" + return df.replace({SIN_ESTADO: np.nan, float(SIN_ESTADO): np.nan, str(SIN_ESTADO): np.nan}) + + +def preparar(marco, horizonte=HORIZONTE): + """El marco con la etiqueta `y` a `horizonte` años, sin las filas no etiquetables. + + Provisional (MD-Q6): y = 1 si `c == 1` o `r <= h`; y = 0 si `c == 0` y `l >= h`; lo demás se excluye. + """ + df = a_nulos(marco) + df["fecha_indice"] = pd.to_datetime(df["fecha_indice"]) + positivo = (df["c"] == 1) | (df["r"] <= horizonte) + negativo = (df["c"] == 0) & (df["l"] >= horizonte) & ~positivo + df["y"] = np.where(positivo, 1, np.where(negativo, 0, -1)) + return df[df["y"] >= 0].sort_values(["fecha_indice", "pac_id"]).reset_index(drop=True) + + +# 3 · entrenar y evaluar ------------------------------------------------------------------ + +def dividir(df, fraccion=0.7): + """Partición temporal: las fechas índice más antiguas entrenan. Nunca al azar.""" + corte = df["fecha_indice"].iloc[int(len(df) * fraccion)] + return df[df["fecha_indice"] < corte], df[df["fecha_indice"] >= corte], corte + + +class ModeloCin2Mas(mlflow.pyfunc.PythonModel): + """El pyfunc: indicadoras de las covariables y una logística. Recibe el marco, devuelve P(CIN2+) por fila. + + Un nulo o un nivel que no se vio al ajustar da ceros en sus indicadoras. + """ + + def __init__(self, horizonte=HORIZONTE, C=1.0): + self.horizonte, self.C = float(horizonte), C + self.niveles, self.logistica = {}, None + + def indicadoras(self, df): + df = a_nulos(df) + return pd.DataFrame( + {f"{c}={n}": (df[c].astype("string") == n).fillna(False).astype(float).to_numpy() + for c in COVARIABLES for n in self.niveles[c]}, + index=df.index, + ) + + def ajustar(self, df): + self.niveles = {c: sorted(a_nulos(df)[c].dropna().astype(str).unique()) for c in COVARIABLES} + self.logistica = LogisticRegression(C=self.C, max_iter=1000).fit(self.indicadoras(df), df["y"]) + return self + + def predict(self, context, model_input, params=None): + return self.logistica.predict_proba(self.indicadoras(model_input))[:, 1] + + +def evaluar(modelo, entrena, prueba): + p = modelo.predict(None, prueba) + return { + "brier": brier_score_loss(prueba["y"], p, labels=[0, 1]), + "auc": roc_auc_score(prueba["y"], p) if prueba["y"].nunique() == 2 else float("nan"), + "n_entrenamiento": len(entrena), "n_prueba": len(prueba), + "positivos_entrenamiento": int(entrena["y"].sum()), "positivos_prueba": int(prueba["y"].sum()), + } + + +# 4 · registrar --------------------------------------------------------------------------- + +def sha_del_artefacto(model_uri): + """sha256 de `python_model.pkl` (preprocesamiento + logística); el `MLmodel` lleva ids y fechas.""" + with tempfile.TemporaryDirectory() as tmp: + ruta = Path(mlflow.artifacts.download_artifacts(model_uri, dst_path=tmp)) / "python_model.pkl" + return hashlib.sha256(ruta.read_bytes()).hexdigest() + + +def registrar(modelo, metricas, parametros, linaje): + """Una corrida con el linaje, los parámetros, las métricas y el pyfunc registrado. Sin pacientes.""" + firma = ModelSignature(inputs=Schema([ColSpec("string", c, required=False) for c in COVARIABLES])) + mlflow.set_experiment(EXPERIMENTO) + with mlflow.start_run() as corrida: + mlflow.set_tags({**linaje, "desenlace": DESENLACE}) + mlflow.log_params(parametros) + mlflow.log_metrics(metricas) + info = mlflow.pyfunc.log_model(name="modelo", python_model=modelo, signature=firma, + registered_model_name=NOMBRE_MODELO) + mlflow.set_tag("modelo_sha", sha_del_artefacto(info.model_uri)) + return corrida.info.run_id, str(info.registered_model_version) + + +def entrenar(repositorio, horizonte=HORIZONTE, armado_id=None): + """Pasos 1-4. Devuelve (`run_id`, versión registrada, métricas).""" + marco, linaje = descargar(repositorio, armado_id) + df = preparar(marco, horizonte) + entrena, prueba, corte = dividir(df) + if entrena["y"].nunique() < 2: + raise ValueError(f"La partición de entrenamiento tiene una sola clase ({len(entrena)} etiquetados).") + modelo = ModeloCin2Mas(horizonte).ajustar(entrena) + metricas = evaluar(modelo, entrena, prueba) + # El corte es la fecha índice de una paciente: a MLflow va solo su mes. + parametros = {"horizonte_anios": horizonte, "C": modelo.C, "corte_temporal_mes": corte.strftime("%Y-%m"), + "covariables": ",".join(COVARIABLES), "etiqueta": "provisional MD-Q6"} + run_id, version = registrar(modelo, metricas, parametros, linaje) + return run_id, version, metricas + + +# 6b · el estimador de la arista `estimar` ------------------------------------------------- + +class EstimadorMlflow: + """Cumple `EstimadorDeRiesgo` con una versión registrada de `NOMBRE_MODELO`.""" + + cohorte_url = COHORTE_URL + desenlace = DESENLACE + + def __init__(self, version): + cliente = mlflow.MlflowClient() + mv = cliente.get_model_version(NOMBRE_MODELO, str(version)) + uri = f"models:/{NOMBRE_MODELO}/{mv.version}" + sha = sha_del_artefacto(uri) + if sha != cliente.get_run(mv.run_id).data.tags.get("modelo_sha"): + raise ValueError(f"El artefacto de {uri} no es el que se registró.") + self.pyfunc = mlflow.pyfunc.load_model(uri) + self.horizonte = self.pyfunc.unwrap_python_model().horizonte + self._procedencia = Procedencia(NOMBRE_MODELO, str(mv.version), mv.run_id, sha) + + def procedencia(self): + return self._procedencia + + def estimar(self, columnas, filas): + marco = pd.DataFrame(filas, columns=columnas) + entrada = a_nulos(marco)[COVARIABLES].astype(object) + p = self.pyfunc.predict(entrada.where(entrada.notna(), None)) + return [Riesgo(int(pac), self.horizonte, round(float(q), 6)) for pac, q in zip(marco["pac_id"], p)] diff --git a/pyproject.toml b/pyproject.toml index c2c254c..acc8f5b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,10 +5,18 @@ description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening requires-python = ">=3.11" dependencies = [ "persistance", + # El marco y el linaje de las cohortes (`leer_marco`, `linaje`): `riesgo_logistico`. + "indicadores-kit", + # Solo el cliente: registra y carga contra el servidor del despliegue (9705), fijado a su versión. + "mlflow-skinny==3.16.1", + "scikit-learn==1.9.1", + "pandas==3.0.6", ] [tool.uv.sources] +core = { path = "../Core", editable = true } persistance = { path = "../Persistance", editable = true } +indicadores-kit = { path = "../indicadores_kit", editable = true } [build-system] requires = ["hatchling"] @@ -20,4 +28,6 @@ packages = ["models"] [dependency-groups] dev = [ "pytest>=8.0.0", + # Las pruebas registran en un sqlite temporal, que el cliente `skinny` no admite. + "mlflow==3.16.1", ] -- 2.53.0 From c8bca59334d8fd6e1d1ca9873a73cdcd1512d788 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 19:30:08 +0000 Subject: [PATCH 06/11] contract: translate the risk estimation contract to English riesgo.py becomes contract.py: RiskEstimator, Risk, Provenance and the CacuStandIn, TeaStandIn and CamaStandIn stand-ins. Fields that mirror the batch columns keep their names, and the stand-ins' provenance is unchanged. Tests say why each one exists. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + models/contract.py | 178 +++++++++++++++++++++++++++++++++++++++++ models/riesgo.py | 176 ---------------------------------------- tests/test_contract.py | 152 +++++++++++++++++++++++++++++++++++ tests/test_riesgo.py | 105 ------------------------ 5 files changed, 331 insertions(+), 281 deletions(-) create mode 100644 models/contract.py delete mode 100644 models/riesgo.py create mode 100644 tests/test_contract.py delete mode 100644 tests/test_riesgo.py diff --git a/README.md b/README.md index 52c1490..e411dcf 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ WebApi. |---|---| | `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | | `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | +| `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). `CacuStandIn`, `TeaStandIn` y `CamaStandIn`: sustitutos deterministas sin MLflow, para pruebas y para desplegar sin el modelo real; no son modelos clínicos. | | `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | | `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | diff --git a/models/contract.py b/models/contract.py new file mode 100644 index 0000000..5550cbd --- /dev/null +++ b/models/contract.py @@ -0,0 +1,178 @@ +"""The contract through which a model is asked for the risk of a cohort build's members. + +The caller hands the estimator the wide frame of a cohort build, `(columns, rows)`, with +`columns = ["pac_id", "fecha_indice", ]`. The estimator returns one `Risk` per member and +horizon, and its `Provenance`: the keys that reconcile a batch with MLflow (MLflow keeps no rows and no +patients). + +`Risk` and `Provenance` keep the names of the columns they're saved to (`evaluacion_riesgo`, +`evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what Persistance's `PROCEDENCIA` expects. + +This module doesn't import the kit, Persistance or the orchestration: it receives lists. +""" + +import hashlib +import json +from dataclasses import asdict, dataclass +from typing import NamedTuple, Protocol, runtime_checkable + + +class Risk(NamedTuple): + """A member's risk at one horizon (FHIR `RiskAssessment.prediction`).""" + + pac_id: int + horizonte_anios: float # years from the index date; 0 = prevalent + probabilidad: float # 0 to 1 + ic_bajo: float | None = None + ic_alto: float | None = None + + +@dataclass(frozen=True) +class Provenance: + """Which model the risks come from: the keys a batch stores.""" + + modelo_nombre: str + modelo_version: str + mlflow_run_id: str + modelo_sha: str + + def as_dict(self) -> dict[str, str]: + return asdict(self) + + +@runtime_checkable +class RiskEstimator(Protocol): + """What every risk model the orchestration can call provides.""" + + cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia") + outcome: str # what it predicts ("cin2_mas") + + def provenance(self) -> Provenance: ... + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ... + + +def _rule_sha(rule: dict) -> str: + return hashlib.sha256(json.dumps(rule, sort_keys=True).encode("utf-8")).hexdigest() + + +def _missing(columns: list[str], needed: tuple[str, ...]) -> None: + missing = [c for c in needed if c not in columns] + if missing: + raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.") + + +# The CaCu stand-in's rule: a base probability and what each baseline predictor adds. +CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95} +NORMAL_PAPS = ("NORMAL",) + + +class CacuStandIn: + """A deterministic stand-in estimator, without MLflow: for tests and for deploying without the real model. + + The probability comes from a fixed rule over the baseline predictors: `CACU_RULE["base"]`, plus + `pap_anormal` if `pap_0` is neither `NORMAL` nor null, plus `vph_positivo` if `hpv_0` is `POSITIVO`, + capped at `tope`. No interval. Not a clinical model. + """ + + def __init__(self, cohort_url: str = "cacu/cohorte_vigilancia", outcome: str = "cin2_mas", + horizons: tuple[float, ...] = (0.0,)): + self.cohort_url = cohort_url + self.outcome = outcome + self.horizons = tuple(horizons) + + def provenance(self) -> Provenance: + sha = _rule_sha({"regla": CACU_RULE, "pap_normales": NORMAL_PAPS, "horizontes": self.horizons}) + return Provenance(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha) + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: + _missing(columns, ("pac_id", "pap_0", "hpv_0")) + i_pac, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "pap_0", "hpv_0")) + risks = [] + for row in rows: + p = CACU_RULE["base"] + if row[i_pap] is not None and row[i_pap] not in NORMAL_PAPS: + p += CACU_RULE["pap_anormal"] + if row[i_hpv] == "POSITIVO": + p += CACU_RULE["vph_positivo"] + p = min(p, CACU_RULE["tope"]) + risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] + return risks + + +# The TEA stand-in's rule: what the index M-CHAT interpretation and the perinatal history add. +TEA_RULE = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05, + "apgar_corte": 7, "tope": 0.95} + + +class TeaStandIn: + """The deterministic TEA stand-in, over the frame of `tea/cohorte_tamizaje`. Without MLflow. + + The probability of a TEA diagnosis at the horizon (4 years = 48 months, the cohort's) is + `TEA_RULE["base"]`, plus `mchat_medio` or `mchat_alto` by `mchat_0`, plus `ucin` if `ingreso_ucin` + is 1, plus `apgar_bajo` if `apgar_5min` is below `apgar_corte`, capped at `tope`. No interval. Not a + clinical model. + """ + + def __init__(self, cohort_url: str = "tea/cohorte_tamizaje", outcome: str = "d", + horizons: tuple[float, ...] = (4.0,)): + self.cohort_url = cohort_url + self.outcome = outcome + self.horizons = tuple(horizons) + + def provenance(self) -> Provenance: + sha = _rule_sha({"regla": TEA_RULE, "horizontes": self.horizons}) + return Provenance(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow", + modelo_sha=sha) + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: + needed = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min") + _missing(columns, needed) + i_pac, i_mchat, i_ucin, i_apgar = (columns.index(c) for c in needed) + r = TEA_RULE + risks = [] + for row in rows: + p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(row[i_mchat], 0.0) + if row[i_ucin] == 1: + p += r["ucin"] + if row[i_apgar] is not None and row[i_apgar] < r["apgar_corte"]: + p += r["apgar_bajo"] + p = min(p, r["tope"]) + risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] + return risks + + +# The CaMa stand-in's rule: what the index BI-RADS adds. +CAMA_RULE = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80, "tope": 0.95} +BIRADS_SUSPICION = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4", + "B4C": "birads_4", "B5": "birads_5"} + + +class CamaStandIn: + """The deterministic CaMa stand-in, over the frame of `cama/cohorte_tamizaje`. Without MLflow. + + The probability of breast cancer by biopsy at the horizon (1 year, the cohort's) is + `CAMA_RULE["base"]` plus what the index BI-RADS category (`birads_0`) adds, capped at `tope`. + Subcategories 4A, 4B and 4C add as 4. No interval. Not a clinical model. + """ + + def __init__(self, cohort_url: str = "cama/cohorte_tamizaje", outcome: str = "d", + horizons: tuple[float, ...] = (1.0,)): + self.cohort_url = cohort_url + self.outcome = outcome + self.horizons = tuple(horizons) + + def provenance(self) -> Provenance: + sha = _rule_sha({"regla": CAMA_RULE, "birads": BIRADS_SUSPICION, "horizontes": self.horizons}) + return Provenance(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow", + modelo_sha=sha) + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: + _missing(columns, ("pac_id", "birads_0")) + i_pac, i_birads = columns.index("pac_id"), columns.index("birads_0") + r = CAMA_RULE + risks = [] + for row in rows: + p = min(r["base"] + r.get(BIRADS_SUSPICION.get(row[i_birads]), 0.0), r["tope"]) + risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] + return risks diff --git a/models/riesgo.py b/models/riesgo.py deleted file mode 100644 index 738cbeb..0000000 --- a/models/riesgo.py +++ /dev/null @@ -1,176 +0,0 @@ -"""El contrato con que se le pide a un modelo el riesgo de los miembros de una cohorte (ADR-MD-008). - -Quien llama (la arista `estimar` de Orquestacion) le da al estimador el marco de un armado -de cohorte, ancho: `(columnas, filas)`, con `columnas = ["pac_id", "fecha_indice", ]` -(lo que devuelve `indicadores_kit.cohortes.armado.leer_marco`). El estimador devuelve un -`Riesgo` por miembro y horizonte, y su `Procedencia`: las llaves con que se concilia con -MLflow (opción A del prototipo; MLflow no guarda filas ni pacientes). - -Este módulo no importa al kit, a Persistance ni a Orquestacion: recibe listas. -""" - -import hashlib -import json -from dataclasses import asdict, dataclass -from typing import NamedTuple, Protocol, runtime_checkable - - -class Riesgo(NamedTuple): - """El riesgo de un miembro a un horizonte (FHIR `RiskAssessment.prediction`).""" - - pac_id: int - horizonte_anios: float # años desde la fecha índice; 0 = prevalente - probabilidad: float # de 0 a 1 - ic_bajo: float | None = None - ic_alto: float | None = None - - -@dataclass(frozen=True) -class Procedencia: - """De qué modelo salen los riesgos: las llaves que guarda el lote (`PROCEDENCIA` de Persistance).""" - - modelo_nombre: str - modelo_version: str - mlflow_run_id: str - modelo_sha: str - - def como_dict(self) -> dict[str, str]: - return asdict(self) - - -@runtime_checkable -class EstimadorDeRiesgo(Protocol): - """Lo que cumple todo modelo de riesgo que Orquestacion puede llamar.""" - - cohorte_url: str # la cohorte cuyo marco consume ("cacu/cohorte_vigilancia") - desenlace: str # lo que predice ("cin2_mas") - - def procedencia(self) -> Procedencia: ... - - def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: ... - - -# La regla del sustituto: una probabilidad base y lo que suma cada predictor basal. -REGLA_SINTETICA = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95} -PAP_NORMALES = ("NORMAL",) - - -class RiesgoSintetico: - """Un estimador sustituto determinista, sin MLflow: para pruebas y para desplegar sin el modelo real. - - La probabilidad sale de una tabla fija por los predictores basales: `REGLA_SINTETICA["base"]`, - más `pap_anormal` si `pap_0` no es `NORMAL` ni nulo, más `vph_positivo` si `hpv_0` es - `POSITIVO`, con tope. Sin intervalo. No es un modelo clínico. - """ - - def __init__(self, cohorte_url: str = "cacu/cohorte_vigilancia", desenlace: str = "cin2_mas", - horizontes: tuple[float, ...] = (0.0,)): - self.cohorte_url = cohorte_url - self.desenlace = desenlace - self.horizontes = tuple(horizontes) - - def procedencia(self) -> Procedencia: - regla = {"regla": REGLA_SINTETICA, "pap_normales": PAP_NORMALES, "horizontes": self.horizontes} - sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest() - return Procedencia(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha) - - def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: - faltan = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columnas] - if faltan: - raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.") - i_pac, i_pap, i_vph = (columnas.index(c) for c in ("pac_id", "pap_0", "hpv_0")) - riesgos = [] - for fila in filas: - p = REGLA_SINTETICA["base"] - if fila[i_pap] is not None and fila[i_pap] not in PAP_NORMALES: - p += REGLA_SINTETICA["pap_anormal"] - if fila[i_vph] == "POSITIVO": - p += REGLA_SINTETICA["vph_positivo"] - p = min(p, REGLA_SINTETICA["tope"]) - riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] - return riesgos - - -# La regla del sustituto de TEA: lo que suma la interpretación del M-CHAT índice y lo perinatal. -REGLA_SINTETICA_TEA = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05, - "apgar_corte": 7, "tope": 0.95} - - -class RiesgoSinteticoTea: - """El sustituto determinista de TEA, sobre el marco de `tea/cohorte_tamizaje` (T-21e). Sin MLflow. - - La probabilidad de un diagnóstico de TEA al horizonte (4 años = 48 meses, el de la cohorte) es - `REGLA_SINTETICA_TEA["base"]`, más `mchat_medio` o `mchat_alto` según `mchat_0`, más `ucin` si - `ingreso_ucin` es 1, más `apgar_bajo` si `apgar_5min` es menor que `apgar_corte`, con tope. Sin - intervalo. No es un modelo clínico. - """ - - def __init__(self, cohorte_url: str = "tea/cohorte_tamizaje", desenlace: str = "d", - horizontes: tuple[float, ...] = (4.0,)): - self.cohorte_url = cohorte_url - self.desenlace = desenlace - self.horizontes = tuple(horizontes) - - def procedencia(self) -> Procedencia: - regla = {"regla": REGLA_SINTETICA_TEA, "horizontes": self.horizontes} - sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest() - return Procedencia(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow", - modelo_sha=sha) - - def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: - necesarias = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min") - faltan = [c for c in necesarias if c not in columnas] - if faltan: - raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.") - i_pac, i_mchat, i_ucin, i_apgar = (columnas.index(c) for c in necesarias) - r = REGLA_SINTETICA_TEA - riesgos = [] - for fila in filas: - p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(fila[i_mchat], 0.0) - if fila[i_ucin] == 1: - p += r["ucin"] - if fila[i_apgar] is not None and fila[i_apgar] < r["apgar_corte"]: - p += r["apgar_bajo"] - p = min(p, r["tope"]) - riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] - return riesgos - - -# La regla del sustituto de CaMa: lo que suma el BI-RADS índice. -REGLA_SINTETICA_CAMA = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80, - "tope": 0.95} -BIRADS_SUSPECHA = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4", - "B4C": "birads_4", "B5": "birads_5"} - - -class RiesgoSinteticoCama: - """El sustituto determinista de CaMa, sobre el marco de `cama/cohorte_tamizaje` (T-21g). Sin MLflow. - - La probabilidad de cáncer de mama por biopsia al horizonte (1 año, el de la cohorte) es - `REGLA_SINTETICA_CAMA["base"]` más lo que suma la categoría del BI-RADS índice (`birads_0`), con - tope. Las subcategorías 4A, 4B y 4C suman como 4. Sin intervalo. No es un modelo clínico. - """ - - def __init__(self, cohorte_url: str = "cama/cohorte_tamizaje", desenlace: str = "d", - horizontes: tuple[float, ...] = (1.0,)): - self.cohorte_url = cohorte_url - self.desenlace = desenlace - self.horizontes = tuple(horizontes) - - def procedencia(self) -> Procedencia: - regla = {"regla": REGLA_SINTETICA_CAMA, "birads": BIRADS_SUSPECHA, "horizontes": self.horizontes} - sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest() - return Procedencia(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow", - modelo_sha=sha) - - def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: - faltan = [c for c in ("pac_id", "birads_0") if c not in columnas] - if faltan: - raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.") - i_pac, i_birads = columnas.index("pac_id"), columnas.index("birads_0") - r = REGLA_SINTETICA_CAMA - riesgos = [] - for fila in filas: - p = min(r["base"] + r.get(BIRADS_SUSPECHA.get(fila[i_birads]), 0.0), r["tope"]) - riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes] - return riesgos diff --git a/tests/test_contract.py b/tests/test_contract.py new file mode 100644 index 0000000..e697f6e --- /dev/null +++ b/tests/test_contract.py @@ -0,0 +1,152 @@ +"""What this module covers: the `RiskEstimator` contract and the three stand-ins in `models.contract` +(`CacuStandIn`, `TeaStandIn`, `CamaStandIn`). + +Fixtures: no pytest fixtures. Each stand-in has a small hand-written frame (`COLUMNS*`, `ROWS*`) shaped like +its cohort's: `pac_id`, `fecha_indice`, outcome columns and the predictors the rule reads. `monkeypatch` +changes a rule to check that the provenance follows it. +""" + +import pytest + +from models import contract +from models.contract import CAMA_RULE, TEA_RULE, CacuStandIn, CamaStandIn, Risk, RiskEstimator, TeaStandIn + +COLUMNS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"] +ROWS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), + (3, "2024-09-01", 0, None, None)] + + +def test_the_cacu_stand_in_meets_the_contract(): + """Pins down: `CacuStandIn` is a `RiskEstimator` (runtime check of the protocol). + + Fails if the protocol or the stand-in renames `cohort_url`, `outcome`, `provenance` or `estimate`. + """ + assert isinstance(CacuStandIn(), RiskEstimator) + + +def test_one_risk_per_member_and_horizon_in_frame_order(): + """Pins down: `estimate` returns one `Risk` per member and horizon, members in the frame's order, + probabilities in [0, 1], no interval. + + Fails if risks are grouped by horizon, reordered, or the interval stops being `None`. + """ + risks = CacuStandIn(horizons=(0.0, 1.0)).estimate(COLUMNS, ROWS) + + assert [(r.pac_id, r.horizonte_anios) for r in risks] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)] + assert all(isinstance(r, Risk) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in risks) + + +def test_the_cacu_rule_adds_per_baseline_predictor(): + """Pins down: normal or missing results add nothing; an abnormal pap and a positive HPV add their terms. + + Fails if a term of `CACU_RULE` changes or a null pap starts counting as abnormal. + """ + p = {r.pac_id: r.probabilidad for r in CacuStandIn().estimate(COLUMNS, ROWS)} + + assert p == {1: 0.01, 2: 0.16, 3: 0.01} + + +def test_it_is_deterministic(): + """Pins down: two instances give the same risks and the same provenance. + + Fails if anything random or time-dependent enters the stand-in. + """ + a, b = CacuStandIn(), CacuStandIn() + + assert a.estimate(COLUMNS, ROWS) == b.estimate(COLUMNS, ROWS) + assert a.provenance() == b.provenance() + + +def test_provenance_has_the_four_keys_and_its_sha_follows_the_rule(monkeypatch): + """Pins down: `Provenance.as_dict()` has exactly the four keys a batch stores, none empty, and + `modelo_sha` changes when the rule changes. + + Fails if a provenance field is renamed (the batch columns wouldn't match) or the sha stops covering + the rule. + """ + provenance = CacuStandIn().provenance() + assert set(provenance.as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"} + assert all(provenance.as_dict().values()) + + monkeypatch.setitem(contract.CACU_RULE, "vph_positivo", 0.2) + assert CacuStandIn().provenance().modelo_sha != provenance.modelo_sha + + +def test_without_its_predictors_it_fails_and_names_them(): + """Pins down: a frame without a predictor the rule reads raises `ValueError` naming it. + + Fails if a missing column is silently treated as null. + """ + with pytest.raises(ValueError, match="pap_0"): + CacuStandIn().estimate(["pac_id", "hpv_0"], [(1, None)]) + + +COLUMNS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes", + "hipoacusia_0"] + + +def test_the_tea_stand_in_meets_the_contract_and_reads_its_cohort(): + """Pins down: `TeaStandIn` is a `RiskEstimator` over `tea/cohorte_tamizaje` at 4 years. + + Fails if its default cohort or horizon changes. + """ + estimator = TeaStandIn() + assert isinstance(estimator, RiskEstimator) + assert estimator.cohort_url == "tea/cohorte_tamizaje" and estimator.horizons == (4.0,) + + +def test_the_tea_rule_adds_mchat_nicu_and_low_apgar(): + """Pins down: a low-risk M-CHAT adds nothing; a high-risk one, NICU admission and a low Apgar each add + their term; missing values add nothing. + + Fails if a term of `TEA_RULE` is dropped or the Apgar cut-off changes side. + """ + rows = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None), + (2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"), + (3, None, None, None, None, None, None, 0, None)] + r = TEA_RULE + assert [x.probabilidad for x in TeaStandIn().estimate(COLUMNS_TEA, rows)] == pytest.approx( + [r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]]) + + +def test_the_tea_stand_in_without_its_predictors_fails(): + """Pins down: a TEA frame without `mchat_0` raises `ValueError` naming it. + + Fails if the TEA stand-in stops checking its columns. + """ + with pytest.raises(ValueError, match="mchat_0"): + TeaStandIn().estimate(["pac_id", "fecha_indice"], []) + + +COLUMNS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"] + + +def test_the_cama_stand_in_meets_the_contract_and_reads_its_cohort(): + """Pins down: `CamaStandIn` is a `RiskEstimator` over `cama/cohorte_tamizaje` at 1 year. + + Fails if its default cohort or horizon changes. + """ + estimator = CamaStandIn() + assert isinstance(estimator, RiskEstimator) + assert estimator.cohort_url == "cama/cohorte_tamizaje" and estimator.horizons == (1.0,) + + +def test_the_cama_rule_adds_by_index_birads_and_4a_counts_as_4(): + """Pins down: BI-RADS 2 and a missing BI-RADS add nothing; 4A adds as 4; 5 adds its term. + + Fails if `BIRADS_SUSPICION` loses the 4A/4B/4C mapping or a term of `CAMA_RULE` changes. + """ + rows = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0), + (3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)] + r = CAMA_RULE + assert [x.probabilidad for x in CamaStandIn().estimate(COLUMNS_CAMA, rows)] == pytest.approx( + [r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]]) + + +def test_the_cama_stand_in_without_its_predictor_fails(): + """Pins down: a CaMa frame without `birads_0` raises `ValueError` naming it. + + Fails if the CaMa stand-in stops checking its columns. + """ + with pytest.raises(ValueError, match="birads_0"): + CamaStandIn().estimate(["pac_id", "fecha_indice"], []) diff --git a/tests/test_riesgo.py b/tests/test_riesgo.py deleted file mode 100644 index 75c26d1..0000000 --- a/tests/test_riesgo.py +++ /dev/null @@ -1,105 +0,0 @@ -"""El contrato `EstimadorDeRiesgo` y el estimador sustituto (ADR-MD-008).""" - -import pytest - -from models import riesgo -from models.riesgo import ( - REGLA_SINTETICA_CAMA, - REGLA_SINTETICA_TEA, - EstimadorDeRiesgo, - Riesgo, - RiesgoSintetico, - RiesgoSinteticoCama, - RiesgoSinteticoTea, -) - -COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"] -FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)] - - -def test_el_sustituto_cumple_el_contrato(): - assert isinstance(RiesgoSintetico(), EstimadorDeRiesgo) - - -def test_un_riesgo_por_miembro_y_horizonte_en_el_orden_del_marco(): - riesgos = RiesgoSintetico(horizontes=(0.0, 1.0)).estimar(COLUMNAS, FILAS) - - assert [(r.pac_id, r.horizonte_anios) for r in riesgos] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)] - assert all(isinstance(r, Riesgo) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in riesgos) - - -def test_la_regla_suma_por_predictor_basal(): - p = {r.pac_id: r.probabilidad for r in RiesgoSintetico().estimar(COLUMNAS, FILAS)} - - assert p == {1: 0.01, 2: 0.16, 3: 0.01} - - -def test_es_determinista(): - a, b = RiesgoSintetico(), RiesgoSintetico() - - assert a.estimar(COLUMNAS, FILAS) == b.estimar(COLUMNAS, FILAS) - assert a.procedencia() == b.procedencia() - - -def test_la_procedencia_trae_las_cuatro_llaves_y_su_sha_cambia_con_la_regla(monkeypatch): - procedencia = RiesgoSintetico().procedencia() - assert set(procedencia.como_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"} - assert all(procedencia.como_dict().values()) - - monkeypatch.setitem(riesgo.REGLA_SINTETICA, "vph_positivo", 0.2) - assert RiesgoSintetico().procedencia().modelo_sha != procedencia.modelo_sha - - -def test_sin_los_predictores_falla_y_los_nombra(): - with pytest.raises(ValueError, match="pap_0"): - RiesgoSintetico().estimar(["pac_id", "hpv_0"], [(1, None)]) - - -# --- El sustituto de TEA (T-21f) --------------------------------------------------------------- - -COLUMNAS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes", - "hipoacusia_0"] - - -def test_el_sustituto_de_tea_cumple_el_contrato_y_lee_su_cohorte(): - estimador = RiesgoSinteticoTea() - assert isinstance(estimador, EstimadorDeRiesgo) - assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (4.0,) - - -def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo(): - filas = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None), - (2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"), - (3, None, None, None, None, None, None, 0, None)] - r = REGLA_SINTETICA_TEA - assert [x.probabilidad for x in RiesgoSinteticoTea().estimar(COLUMNAS_TEA, filas)] == pytest.approx( - [r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]]) - - -def test_el_sustituto_de_tea_sin_sus_predictores_falla(): - with pytest.raises(ValueError, match="mchat_0"): - RiesgoSinteticoTea().estimar(["pac_id", "fecha_indice"], []) - - -# --- El sustituto de CaMa (T-21g) -------------------------------------------------------------- - -COLUMNAS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"] - - -def test_el_sustituto_de_cama_cumple_el_contrato_y_lee_su_cohorte(): - estimador = RiesgoSinteticoCama() - assert isinstance(estimador, EstimadorDeRiesgo) - assert estimador.cohorte_url == "cama/cohorte_tamizaje" and estimador.horizontes == (1.0,) - - -def test_la_regla_de_cama_suma_por_birads_indice_y_4a_cuenta_como_4(): - filas = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0), - (3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)] - r = REGLA_SINTETICA_CAMA - assert [x.probabilidad for x in RiesgoSinteticoCama().estimar(COLUMNAS_CAMA, filas)] == pytest.approx( - [r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]]) - - -def test_el_sustituto_de_cama_sin_su_predictor_falla(): - with pytest.raises(ValueError, match="birads_0"): - RiesgoSinteticoCama().estimar(["pac_id", "fecha_indice"], []) -- 2.53.0 From bc15cc3e0491db5a8b072b0427d30b630bcc8481 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 20:19:03 +0000 Subject: [PATCH 07/11] dags: reading nodes for a cohort build, its members and their timeline The timeline is cut at the build's clinical and load cut-offs, so the read can be repeated. Adds apache-hamilton. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + models/dags/__init__.py | 1 + models/dags/reading.py | 44 ++++++++++ pyproject.toml | 2 + tests/test_reading_nodes.py | 169 ++++++++++++++++++++++++++++++++++++ 5 files changed, 217 insertions(+) create mode 100644 models/dags/__init__.py create mode 100644 models/dags/reading.py create mode 100644 tests/test_reading_nodes.py diff --git a/README.md b/README.md index e411dcf..f907652 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ WebApi. | `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | | `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | | `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). `CacuStandIn`, `TeaStandIn` y `CamaStandIn`: sustitutos deterministas sin MLflow, para pruebas y para desplegar sin el modelo real; no son modelos clínicos. | +| `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` y `conocida_hasta` del armado). Los repositorios entran como insumos. | | `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | | `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | diff --git a/models/dags/__init__.py b/models/dags/__init__.py new file mode 100644 index 0000000..2d7d505 --- /dev/null +++ b/models/dags/__init__.py @@ -0,0 +1 @@ +"""Hamilton modules for the model DAGs: each function is a node, each parameter an edge.""" diff --git a/models/dags/reading.py b/models/dags/reading.py new file mode 100644 index 0000000..63f5777 --- /dev/null +++ b/models/dags/reading.py @@ -0,0 +1,44 @@ +"""The nodes every model DAG reads through: a cohort build, its members and their timeline. + +Each node's first parameter is the asset it reads, given as an input (`Asset`), so the graph shows +which tables a model depends on (`persistance.assets.validate` with them as sources). The repositories +are inputs too: whoever builds the driver passes a domain's `cohorte_repository` and a +`timeline_repository` already bound to its query. + +The timeline is cut at the build's clinical date (`datos_as_of`) and at what had been loaded when the +build was made (`conocida_hasta`), so reading it again gives the build's input. +""" + +from dataclasses import fields + +import pandas as pd +from persistance.aristas.oro import CohortBuild, CohortMember, CohorteRepository +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from persistance.assets import Asset + +MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember)) + + +class UnknownBuild(LookupError): + """The requested cohort build doesn't exist.""" + + +def cohort_build(cohorte_armado: Asset, cohort_repository: CohorteRepository, build_id: int) -> CohortBuild: + """The build's lineage: cohort, version, fingerprints and cut-offs.""" + build = cohort_repository.build(build_id) + if build is None: + raise UnknownBuild(f"cohort build {build_id} doesn't exist") + return build + + +def members(cohorte_miembro: Asset, cohort_repository: CohorteRepository, cohort_build: CohortBuild) -> pd.DataFrame: + """One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`.""" + return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS)) + + +def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, + timeline_repository: TimelineRepository) -> pd.DataFrame: + """The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and `conocida_hasta`.""" + rows = timeline_repository.read(patients=members["pac_id"].tolist(), until=cohort_build.datos_as_of, + known_until=cohort_build.conocida_hasta) + return pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)) diff --git a/pyproject.toml b/pyproject.toml index 52bb574..d054073 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,6 +7,8 @@ dependencies = [ "persistance", "extraction", "mlflow>=2.9", + # The model DAGs (`models/dags`): each function a node, each parameter an edge. + "apache-hamilton>=1.90", ] [project.optional-dependencies] diff --git a/tests/test_reading_nodes.py b/tests/test_reading_nodes.py new file mode 100644 index 0000000..6dbb707 --- /dev/null +++ b/tests/test_reading_nodes.py @@ -0,0 +1,169 @@ +"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `timeline`) +run by a Hamilton driver built from that module alone, and their place in the asset graph. + +Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain +`timeline_events` table; it returns the `CohorteRepository` and a `TimelineRepository` bound to +`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and +executes the requested nodes. +""" + +import json +from datetime import date, datetime, timezone + +import pytest +from core.cacu.base import CaCuModel +from core.cacu.indicadores.models import ( + CohorteArmado, + CohorteExclusion, + CohorteMiembro, + CohorteVariable, + EvaluacionRiesgo, + EvaluacionRiesgoLote, +) +from core.indicadores.cohortes import TablasCohorte +from hamilton import driver +from persistance.aristas.oro import CohorteRepository +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from persistance.assets import Asset, InvalidGraph, validate +from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select +from sqlalchemy.pool import StaticPool +from sqlmodel import Session, create_engine + +from models.dags import reading + +TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, + EvaluacionRiesgo) +ASSETS = {name: Asset(name) for name in ("cohorte_armado", "cohorte_miembro", "linea_de_tiempo")} + +metadata = MetaData() +events = Table( + "timeline_events", metadata, + Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime), + Column("clase", String), Column("tipo", String), Column("codigo", String), + Column("valor_codigo", String), Column("valor_numerico", Float), + Column("fuente_tabla", String), Column("fuente_id", String), +) + + +def _event(pac_id, fecha, conocida_en, fuente_id): + return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "procedimiento", + "tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "NORMAL", "valor_numerico": None, + "fuente_tabla": "citologiacervical", "fuente_id": fuente_id} + + +EVENTS = [ + _event(10, date(2025, 2, 1), datetime(2025, 2, 2), "kept-10"), + _event(20, date(2025, 3, 1), datetime(2025, 3, 2), "kept-20"), + _event(10, date(2026, 2, 1), datetime(2026, 1, 1), "after-datos-as-of"), + _event(20, date(2025, 6, 1), datetime(2026, 1, 3), "loaded-after-the-build"), + _event(99, date(2025, 2, 1), datetime(2025, 2, 2), "not-a-member"), +] + + +def timeline_query(*, patients, until, known_until): + """Stands in for the kit's query: same columns and filters, over `timeline_events`.""" + query = select(*(events.c[name] for name in TIMELINE_COLUMNS)).order_by(events.c.pac_id, events.c.fecha) + if patients is not None: + query = query.where(events.c.pac_id.in_(patients)) + if until is not None: + query = query.where(events.c.fecha <= until) + if known_until is not None: + query = query.where(events.c.conocida_en <= known_until.replace(tzinfo=None)) + return query + + +@pytest.fixture +def repositories(): + """Build 1 of `cacu/cohorte_vigilancia`: clinical cut-off 2025-12-31, load cut-off 2026-01-02 08:00 + UTC, members 20 and 10 (inserted in that order). Build 2 exists with no members. `EVENTS` has one + event per member inside both cut-offs, one past the clinical cut-off, one loaded after the build and + one of a patient outside the cohort. + """ + engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False}) + CaCuModel.metadata.create_all(engine) + metadata.create_all(engine) + parameters = json.dumps({"corte": "2025-12-31", "conocida_hasta": "2026-01-02T08:00:00+00:00"}) + with Session(engine) as session: + session.add_all([ + CohorteArmado(armado_id=armado_id, url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", + reglas_sha="r", parametros=parameters, datos_as_of=date(2025, 12, 31), + huella=f"h{armado_id}", marco_sha=f"m{armado_id}", n_miembros=2 if armado_id == 1 else 0, + armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) + for armado_id in (1, 2) + ]) + session.add_all([ + CohorteMiembro(armado_id=1, pac_id=pac_id, fecha_indice=fecha, indice_fuente_tabla="citologiacervical", + indice_fuente_id=str(pac_id)) + for pac_id, fecha in ((20, date(2025, 3, 1)), (10, date(2025, 2, 1))) + ]) + session.commit() + session.connection().execute(insert(events), EVENTS) + session.commit() + factory = lambda: Session(engine) # noqa: E731 + return CohorteRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query) + + +def _run(repositories, build_id, nodes=("members", "timeline")): + cohort_repository, timeline_repository = repositories + dr = driver.Builder().with_modules(reading).build() + return dr.execute(list(nodes), inputs={**ASSETS, "cohort_repository": cohort_repository, + "timeline_repository": timeline_repository, "build_id": build_id}) + + +def test_reads_the_members_and_their_timeline_of_a_build(repositories): + """Pins down: a driver with only the reading nodes returns the build's members ordered by `pac_id` + with `MEMBER_COLUMNS`, and a timeline with `TIMELINE_COLUMNS` holding only the members' events. + + Fails if `members` loses its order or columns, or `timeline` stops filtering by the members. + """ + result = _run(repositories, 1) + + assert list(result["members"].columns) == list(reading.MEMBER_COLUMNS) + assert result["members"]["pac_id"].tolist() == [10, 20] + assert list(result["timeline"].columns) == list(TIMELINE_COLUMNS) + assert 99 not in result["timeline"]["pac_id"].tolist() + + +def test_the_timeline_is_cut_where_the_build_was_made(repositories): + """Pins down: the timeline keeps events up to the build's `datos_as_of` and loaded by its + `conocida_hasta`, so reading it again gives the build's input. + + Fails if `timeline` reads with no cut-off, or takes the cut-offs from anywhere but the build. + """ + timeline = _run(repositories, 1)["timeline"] + + assert timeline["fuente_id"].tolist() == ["kept-10", "kept-20"] + + +def test_a_build_without_members_reads_an_empty_timeline(repositories): + """Pins down: a build with no members gives empty frames with their columns, not everyone's timeline. + + Fails if an empty member list reaches the query as "no patient filter". + """ + result = _run(repositories, 2) + + assert result["members"].empty and list(result["members"].columns) == list(reading.MEMBER_COLUMNS) + assert result["timeline"].empty and list(result["timeline"].columns) == list(TIMELINE_COLUMNS) + + +def test_an_unknown_build_fails(repositories): + """Pins down: asking for a build that doesn't exist raises `UnknownBuild` naming it. + + Fails if `cohort_build` lets `None` through to the other nodes. + """ + with pytest.raises(reading.UnknownBuild, match="404"): + _run(repositories, 404, nodes=("cohort_build",)) + + +def test_the_assets_read_are_sources_of_the_graph(): + """Pins down: the reading nodes read three assets nobody in `models` produces (`cohorte_armado`, + `cohorte_miembro`, `linea_de_tiempo`), so the graph validates only with them declared as sources. + + Fails if a node stops declaring the asset it reads, or reads one more without saying so. + """ + nodes = driver.Builder().with_modules(reading).build().list_available_variables() + + with pytest.raises(InvalidGraph) as error: + validate(nodes) + assert len(str(error.value).splitlines()) == 3 + validate(nodes, sources=set(ASSETS)) -- 2.53.0 From 5fa931d92d211d1876c5f47ec81e59212264a841 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 20:27:05 +0000 Subject: [PATCH 08/11] dags: the timeline is always read with an explicit known_until known_until is the build's conocida_hasta or, when the build has none, the moment of the read; it's a node, so the run can record it. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- models/dags/reading.py | 17 +++++++++++----- tests/test_reading_nodes.py | 40 ++++++++++++++++++++++++++----------- 3 files changed, 41 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index f907652..ed71a80 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ WebApi. | `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | | `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | | `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). `CacuStandIn`, `TeaStandIn` y `CamaStandIn`: sustitutos deterministas sin MLflow, para pruebas y para desplegar sin el modelo real; no son modelos clínicos. | -| `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` y `conocida_hasta` del armado). Los repositorios entran como insumos. | +| `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. | | `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | | `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | diff --git a/models/dags/reading.py b/models/dags/reading.py index 63f5777..29fea47 100644 --- a/models/dags/reading.py +++ b/models/dags/reading.py @@ -5,11 +5,13 @@ which tables a model depends on (`persistance.assets.validate` with them as sour are inputs too: whoever builds the driver passes a domain's `cohorte_repository` and a `timeline_repository` already bound to its query. -The timeline is cut at the build's clinical date (`datos_as_of`) and at what had been loaded when the -build was made (`conocida_hasta`), so reading it again gives the build's input. +The timeline is cut at the build's clinical date (`datos_as_of`) and always at an explicit load cut-off +(`known_until`): the build's `conocida_hasta`, or the moment of the read when the build has none. The run +records `known_until`, so the read can be repeated once silver keeps its history. """ from dataclasses import fields +from datetime import datetime, timezone import pandas as pd from persistance.aristas.oro import CohortBuild, CohortMember, CohorteRepository @@ -36,9 +38,14 @@ def members(cohorte_miembro: Asset, cohort_repository: CohorteRepository, cohort return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS)) -def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, +def known_until(cohort_build: CohortBuild) -> datetime: + """The load cut-off of the read: the build's `conocida_hasta`, or now (UTC) when the build has none.""" + return cohort_build.conocida_hasta or datetime.now(timezone.utc) + + +def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, known_until: datetime, timeline_repository: TimelineRepository) -> pd.DataFrame: - """The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and `conocida_hasta`.""" + """The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and at `known_until`.""" rows = timeline_repository.read(patients=members["pac_id"].tolist(), until=cohort_build.datos_as_of, - known_until=cohort_build.conocida_hasta) + known_until=known_until) return pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)) diff --git a/tests/test_reading_nodes.py b/tests/test_reading_nodes.py index 6dbb707..13afc9c 100644 --- a/tests/test_reading_nodes.py +++ b/tests/test_reading_nodes.py @@ -1,4 +1,4 @@ -"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `timeline`) +"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `known_until`, `timeline`) run by a Hamilton driver built from that module alone, and their place in the asset graph. Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain @@ -57,6 +57,7 @@ EVENTS = [ _event(10, date(2026, 2, 1), datetime(2026, 1, 1), "after-datos-as-of"), _event(20, date(2025, 6, 1), datetime(2026, 1, 3), "loaded-after-the-build"), _event(99, date(2025, 2, 1), datetime(2025, 2, 2), "not-a-member"), + _event(10, date(2025, 4, 1), datetime(2099, 1, 1), "loaded-in-the-future"), ] @@ -75,26 +76,27 @@ def timeline_query(*, patients, until, known_until): @pytest.fixture def repositories(): """Build 1 of `cacu/cohorte_vigilancia`: clinical cut-off 2025-12-31, load cut-off 2026-01-02 08:00 - UTC, members 20 and 10 (inserted in that order). Build 2 exists with no members. `EVENTS` has one - event per member inside both cut-offs, one past the clinical cut-off, one loaded after the build and - one of a patient outside the cohort. + UTC, members 20 and 10 (inserted in that order). Build 2 has no members; build 3 has member 10 and no + load cut-off. `EVENTS` has one event per member inside both cut-offs, one past the clinical cut-off, + one loaded after build 1, one of a patient outside the cohort and one loaded in the future. """ engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False}) CaCuModel.metadata.create_all(engine) metadata.create_all(engine) - parameters = json.dumps({"corte": "2025-12-31", "conocida_hasta": "2026-01-02T08:00:00+00:00"}) + load_cut = {1: "2026-01-02T08:00:00+00:00", 2: "2026-01-02T08:00:00+00:00", 3: None} with Session(engine) as session: session.add_all([ CohorteArmado(armado_id=armado_id, url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", - reglas_sha="r", parametros=parameters, datos_as_of=date(2025, 12, 31), - huella=f"h{armado_id}", marco_sha=f"m{armado_id}", n_miembros=2 if armado_id == 1 else 0, - armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) - for armado_id in (1, 2) + reglas_sha="r", parametros=json.dumps({"corte": "2025-12-31", "conocida_hasta": cut}), + datos_as_of=date(2025, 12, 31), huella=f"h{armado_id}", marco_sha=f"m{armado_id}", + n_miembros=0, armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) + for armado_id, cut in load_cut.items() ]) session.add_all([ - CohorteMiembro(armado_id=1, pac_id=pac_id, fecha_indice=fecha, indice_fuente_tabla="citologiacervical", - indice_fuente_id=str(pac_id)) - for pac_id, fecha in ((20, date(2025, 3, 1)), (10, date(2025, 2, 1))) + CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=fecha, + indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id)) + for armado_id, pac_id, fecha in ((1, 20, date(2025, 3, 1)), (1, 10, date(2025, 2, 1)), + (3, 10, date(2025, 2, 1))) ]) session.commit() session.connection().execute(insert(events), EVENTS) @@ -135,6 +137,20 @@ def test_the_timeline_is_cut_where_the_build_was_made(repositories): assert timeline["fuente_id"].tolist() == ["kept-10", "kept-20"] +def test_a_build_without_a_load_cut_off_is_read_up_to_now(repositories): + """Pins down: when the build has no `conocida_hasta`, `known_until` is the moment of the read (UTC), + never `None`, and the timeline is cut there. + + Fails if `known_until` lets `None` through (the read couldn't be repeated) or isn't the one the + timeline used. + """ + before = datetime.now(timezone.utc) + result = _run(repositories, 3, nodes=("known_until", "timeline")) + + assert before <= result["known_until"] <= datetime.now(timezone.utc) + assert result["timeline"]["fuente_id"].tolist() == ["kept-10"] + + def test_a_build_without_members_reads_an_empty_timeline(repositories): """Pins down: a build with no members gives empty frames with their columns, not everyone's timeline. -- 2.53.0 From d6f7acc1fad67f406a61ffd19e6b127a2be896d5 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 21:15:15 +0000 Subject: [PATCH 09/11] STADIN not necessary for now --- models/contract.py | 116 --------------------------------------------- 1 file changed, 116 deletions(-) diff --git a/models/contract.py b/models/contract.py index 5550cbd..152d2cd 100644 --- a/models/contract.py +++ b/models/contract.py @@ -60,119 +60,3 @@ def _missing(columns: list[str], needed: tuple[str, ...]) -> None: missing = [c for c in needed if c not in columns] if missing: raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.") - - -# The CaCu stand-in's rule: a base probability and what each baseline predictor adds. -CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95} -NORMAL_PAPS = ("NORMAL",) - - -class CacuStandIn: - """A deterministic stand-in estimator, without MLflow: for tests and for deploying without the real model. - - The probability comes from a fixed rule over the baseline predictors: `CACU_RULE["base"]`, plus - `pap_anormal` if `pap_0` is neither `NORMAL` nor null, plus `vph_positivo` if `hpv_0` is `POSITIVO`, - capped at `tope`. No interval. Not a clinical model. - """ - - def __init__(self, cohort_url: str = "cacu/cohorte_vigilancia", outcome: str = "cin2_mas", - horizons: tuple[float, ...] = (0.0,)): - self.cohort_url = cohort_url - self.outcome = outcome - self.horizons = tuple(horizons) - - def provenance(self) -> Provenance: - sha = _rule_sha({"regla": CACU_RULE, "pap_normales": NORMAL_PAPS, "horizontes": self.horizons}) - return Provenance(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha) - - def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: - _missing(columns, ("pac_id", "pap_0", "hpv_0")) - i_pac, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "pap_0", "hpv_0")) - risks = [] - for row in rows: - p = CACU_RULE["base"] - if row[i_pap] is not None and row[i_pap] not in NORMAL_PAPS: - p += CACU_RULE["pap_anormal"] - if row[i_hpv] == "POSITIVO": - p += CACU_RULE["vph_positivo"] - p = min(p, CACU_RULE["tope"]) - risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] - return risks - - -# The TEA stand-in's rule: what the index M-CHAT interpretation and the perinatal history add. -TEA_RULE = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05, - "apgar_corte": 7, "tope": 0.95} - - -class TeaStandIn: - """The deterministic TEA stand-in, over the frame of `tea/cohorte_tamizaje`. Without MLflow. - - The probability of a TEA diagnosis at the horizon (4 years = 48 months, the cohort's) is - `TEA_RULE["base"]`, plus `mchat_medio` or `mchat_alto` by `mchat_0`, plus `ucin` if `ingreso_ucin` - is 1, plus `apgar_bajo` if `apgar_5min` is below `apgar_corte`, capped at `tope`. No interval. Not a - clinical model. - """ - - def __init__(self, cohort_url: str = "tea/cohorte_tamizaje", outcome: str = "d", - horizons: tuple[float, ...] = (4.0,)): - self.cohort_url = cohort_url - self.outcome = outcome - self.horizons = tuple(horizons) - - def provenance(self) -> Provenance: - sha = _rule_sha({"regla": TEA_RULE, "horizontes": self.horizons}) - return Provenance(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow", - modelo_sha=sha) - - def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: - needed = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min") - _missing(columns, needed) - i_pac, i_mchat, i_ucin, i_apgar = (columns.index(c) for c in needed) - r = TEA_RULE - risks = [] - for row in rows: - p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(row[i_mchat], 0.0) - if row[i_ucin] == 1: - p += r["ucin"] - if row[i_apgar] is not None and row[i_apgar] < r["apgar_corte"]: - p += r["apgar_bajo"] - p = min(p, r["tope"]) - risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] - return risks - - -# The CaMa stand-in's rule: what the index BI-RADS adds. -CAMA_RULE = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80, "tope": 0.95} -BIRADS_SUSPICION = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4", - "B4C": "birads_4", "B5": "birads_5"} - - -class CamaStandIn: - """The deterministic CaMa stand-in, over the frame of `cama/cohorte_tamizaje`. Without MLflow. - - The probability of breast cancer by biopsy at the horizon (1 year, the cohort's) is - `CAMA_RULE["base"]` plus what the index BI-RADS category (`birads_0`) adds, capped at `tope`. - Subcategories 4A, 4B and 4C add as 4. No interval. Not a clinical model. - """ - - def __init__(self, cohort_url: str = "cama/cohorte_tamizaje", outcome: str = "d", - horizons: tuple[float, ...] = (1.0,)): - self.cohort_url = cohort_url - self.outcome = outcome - self.horizons = tuple(horizons) - - def provenance(self) -> Provenance: - sha = _rule_sha({"regla": CAMA_RULE, "birads": BIRADS_SUSPICION, "horizontes": self.horizons}) - return Provenance(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow", - modelo_sha=sha) - - def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: - _missing(columns, ("pac_id", "birads_0")) - i_pac, i_birads = columns.index("pac_id"), columns.index("birads_0") - r = CAMA_RULE - risks = [] - for row in rows: - p = min(r["base"] + r.get(BIRADS_SUSPICION.get(row[i_birads]), 0.0), r["tope"]) - risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] - return risks -- 2.53.0 From 449c67b19d765ec661918816c32364bfb56e7c27 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 21:16:51 +0000 Subject: [PATCH 10/11] contract: only the contract after removing the stand-ins Drops the helpers only the stand-ins used, tests the contract with an estimator defined in the test, and updates the README. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- models/contract.py | 12 --- tests/test_contract.py | 183 +++++++++++------------------------------ 3 files changed, 48 insertions(+), 149 deletions(-) diff --git a/README.md b/README.md index ed71a80..057a9de 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ WebApi. |---|---| | `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | | `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | -| `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). `CacuStandIn`, `TeaStandIn` y `CamaStandIn`: sustitutos deterministas sin MLflow, para pruebas y para desplegar sin el modelo real; no son modelos clínicos. | +| `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). | | `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. | | `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | diff --git a/models/contract.py b/models/contract.py index 152d2cd..ed4c780 100644 --- a/models/contract.py +++ b/models/contract.py @@ -11,8 +11,6 @@ patients). This module doesn't import the kit, Persistance or the orchestration: it receives lists. """ -import hashlib -import json from dataclasses import asdict, dataclass from typing import NamedTuple, Protocol, runtime_checkable @@ -50,13 +48,3 @@ class RiskEstimator(Protocol): def provenance(self) -> Provenance: ... def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ... - - -def _rule_sha(rule: dict) -> str: - return hashlib.sha256(json.dumps(rule, sort_keys=True).encode("utf-8")).hexdigest() - - -def _missing(columns: list[str], needed: tuple[str, ...]) -> None: - missing = [c for c in needed if c not in columns] - if missing: - raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.") diff --git a/tests/test_contract.py b/tests/test_contract.py index e697f6e..2ebe277 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -1,152 +1,63 @@ -"""What this module covers: the `RiskEstimator` contract and the three stand-ins in `models.contract` -(`CacuStandIn`, `TeaStandIn`, `CamaStandIn`). +"""What this module covers: the `RiskEstimator` contract in `models.contract` and the two records it +returns, `Risk` and `Provenance`. -Fixtures: no pytest fixtures. Each stand-in has a small hand-written frame (`COLUMNS*`, `ROWS*`) shaped like -its cohort's: `pac_id`, `fecha_indice`, outcome columns and the predictors the rule reads. `monkeypatch` -changes a rule to check that the provenance follows it. +Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one +fixed probability per member and horizon. `Incomplete` lacks `provenance`. """ -import pytest - -from models import contract -from models.contract import CAMA_RULE, TEA_RULE, CacuStandIn, CamaStandIn, Risk, RiskEstimator, TeaStandIn - -COLUMNS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"] -ROWS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), - (3, "2024-09-01", 0, None, None)] +from models.contract import Provenance, Risk, RiskEstimator -def test_the_cacu_stand_in_meets_the_contract(): - """Pins down: `CacuStandIn` is a `RiskEstimator` (runtime check of the protocol). +class ConstantEstimator: + """Meets the contract with a fixed probability for every member and horizon.""" - Fails if the protocol or the stand-in renames `cohort_url`, `outcome`, `provenance` or `estimate`. + cohort_url = "cacu/cohorte_vigilancia" + outcome = "cin2_mas" + + def provenance(self) -> Provenance: + return Provenance(modelo_nombre="constant", modelo_version="1", mlflow_run_id="none", modelo_sha="sha") + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: + i_pac = columns.index("pac_id") + return [Risk(row[i_pac], h, 0.1) for row in rows for h in (0.0, 1.0)] + + +class Incomplete: + """Has everything but `provenance`.""" + + cohort_url = "cacu/cohorte_vigilancia" + outcome = "cin2_mas" + + def estimate(self, columns, rows): + return [] + + +def test_a_class_with_the_four_members_meets_the_contract(): + """Pins down: `RiskEstimator` is checked at run time by its members (`cohort_url`, `outcome`, + `provenance`, `estimate`), not by inheritance; missing one fails the check. + + Fails if the protocol stops being `runtime_checkable` or a member is renamed. """ - assert isinstance(CacuStandIn(), RiskEstimator) + assert isinstance(ConstantEstimator(), RiskEstimator) + assert not isinstance(Incomplete(), RiskEstimator) -def test_one_risk_per_member_and_horizon_in_frame_order(): - """Pins down: `estimate` returns one `Risk` per member and horizon, members in the frame's order, - probabilities in [0, 1], no interval. +def test_provenance_has_the_four_keys_a_batch_stores(): + """Pins down: `Provenance.as_dict()` has exactly the four keys of the risk batch's provenance columns. - Fails if risks are grouped by horizon, reordered, or the interval stops being `None`. + Fails if a field is renamed or added: the batch columns wouldn't match. """ - risks = CacuStandIn(horizons=(0.0, 1.0)).estimate(COLUMNS, ROWS) - - assert [(r.pac_id, r.horizonte_anios) for r in risks] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)] - assert all(isinstance(r, Risk) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in risks) + assert set(ConstantEstimator().provenance().as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", + "modelo_sha"} -def test_the_cacu_rule_adds_per_baseline_predictor(): - """Pins down: normal or missing results add nothing; an abnormal pap and a positive HPV add their terms. +def test_a_risk_keeps_the_column_names_and_its_interval_is_optional(): + """Pins down: `Risk` fields are named after the columns they're saved to, in that order, and the + interval defaults to `None`. - Fails if a term of `CACU_RULE` changes or a null pap starts counting as abnormal. + Fails if a field is renamed or reordered, or the interval becomes required. """ - p = {r.pac_id: r.probabilidad for r in CacuStandIn().estimate(COLUMNS, ROWS)} + risk = Risk(1, 0.0, 0.25) - assert p == {1: 0.01, 2: 0.16, 3: 0.01} - - -def test_it_is_deterministic(): - """Pins down: two instances give the same risks and the same provenance. - - Fails if anything random or time-dependent enters the stand-in. - """ - a, b = CacuStandIn(), CacuStandIn() - - assert a.estimate(COLUMNS, ROWS) == b.estimate(COLUMNS, ROWS) - assert a.provenance() == b.provenance() - - -def test_provenance_has_the_four_keys_and_its_sha_follows_the_rule(monkeypatch): - """Pins down: `Provenance.as_dict()` has exactly the four keys a batch stores, none empty, and - `modelo_sha` changes when the rule changes. - - Fails if a provenance field is renamed (the batch columns wouldn't match) or the sha stops covering - the rule. - """ - provenance = CacuStandIn().provenance() - assert set(provenance.as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"} - assert all(provenance.as_dict().values()) - - monkeypatch.setitem(contract.CACU_RULE, "vph_positivo", 0.2) - assert CacuStandIn().provenance().modelo_sha != provenance.modelo_sha - - -def test_without_its_predictors_it_fails_and_names_them(): - """Pins down: a frame without a predictor the rule reads raises `ValueError` naming it. - - Fails if a missing column is silently treated as null. - """ - with pytest.raises(ValueError, match="pap_0"): - CacuStandIn().estimate(["pac_id", "hpv_0"], [(1, None)]) - - -COLUMNS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes", - "hipoacusia_0"] - - -def test_the_tea_stand_in_meets_the_contract_and_reads_its_cohort(): - """Pins down: `TeaStandIn` is a `RiskEstimator` over `tea/cohorte_tamizaje` at 4 years. - - Fails if its default cohort or horizon changes. - """ - estimator = TeaStandIn() - assert isinstance(estimator, RiskEstimator) - assert estimator.cohort_url == "tea/cohorte_tamizaje" and estimator.horizons == (4.0,) - - -def test_the_tea_rule_adds_mchat_nicu_and_low_apgar(): - """Pins down: a low-risk M-CHAT adds nothing; a high-risk one, NICU admission and a low Apgar each add - their term; missing values add nothing. - - Fails if a term of `TEA_RULE` is dropped or the Apgar cut-off changes side. - """ - rows = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None), - (2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"), - (3, None, None, None, None, None, None, 0, None)] - r = TEA_RULE - assert [x.probabilidad for x in TeaStandIn().estimate(COLUMNS_TEA, rows)] == pytest.approx( - [r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]]) - - -def test_the_tea_stand_in_without_its_predictors_fails(): - """Pins down: a TEA frame without `mchat_0` raises `ValueError` naming it. - - Fails if the TEA stand-in stops checking its columns. - """ - with pytest.raises(ValueError, match="mchat_0"): - TeaStandIn().estimate(["pac_id", "fecha_indice"], []) - - -COLUMNS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"] - - -def test_the_cama_stand_in_meets_the_contract_and_reads_its_cohort(): - """Pins down: `CamaStandIn` is a `RiskEstimator` over `cama/cohorte_tamizaje` at 1 year. - - Fails if its default cohort or horizon changes. - """ - estimator = CamaStandIn() - assert isinstance(estimator, RiskEstimator) - assert estimator.cohort_url == "cama/cohorte_tamizaje" and estimator.horizons == (1.0,) - - -def test_the_cama_rule_adds_by_index_birads_and_4a_counts_as_4(): - """Pins down: BI-RADS 2 and a missing BI-RADS add nothing; 4A adds as 4; 5 adds its term. - - Fails if `BIRADS_SUSPICION` loses the 4A/4B/4C mapping or a term of `CAMA_RULE` changes. - """ - rows = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0), - (3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)] - r = CAMA_RULE - assert [x.probabilidad for x in CamaStandIn().estimate(COLUMNS_CAMA, rows)] == pytest.approx( - [r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]]) - - -def test_the_cama_stand_in_without_its_predictor_fails(): - """Pins down: a CaMa frame without `birads_0` raises `ValueError` naming it. - - Fails if the CaMa stand-in stops checking its columns. - """ - with pytest.raises(ValueError, match="birads_0"): - CamaStandIn().estimate(["pac_id", "fecha_indice"], []) + assert Risk._fields == ("pac_id", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto") + assert (risk.ic_bajo, risk.ic_alto) == (None, None) -- 2.53.0 From dd94aba1eb513f3dcbb431d167e415eef4ea29f5 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 21:20:15 +0000 Subject: [PATCH 11/11] testing: CacuStandIn as a helper for other code's tests Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + models/testing.py | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 models/testing.py diff --git a/README.md b/README.md index 057a9de..0e717cc 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ WebApi. | `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. | | `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. | | `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). | +| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. | | `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. | | `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). | | `registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. | diff --git a/models/testing.py b/models/testing.py new file mode 100644 index 0000000..6e1e092 --- /dev/null +++ b/models/testing.py @@ -0,0 +1,52 @@ +"""Helpers for other code's tests: a known `RiskEstimator` to run the risk chain without a trained model. + +`CacuStandIn` gives a fixed, predictable probability from two baseline predictors, without MLflow, so a +test of estimating, storing, confirming or publishing risks can assert exact values. It isn't a clinical +model and isn't used outside tests; it has no tests of its own. +""" + +import hashlib +import json + +from models.contract import Provenance, Risk + +# A base probability and what each baseline predictor adds, capped at `tope`. +CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95} +NORMAL_PAPS = ("NORMAL",) + + +class CacuStandIn: + """A deterministic estimator over the frame of `cacu/cohorte_vigilancia`. + + The probability is `CACU_RULE["base"]`, plus `pap_anormal` if `pap_0` is neither `NORMAL` nor null, + plus `vph_positivo` if `hpv_0` is `POSITIVO`, capped at `tope`. One `Risk` per member and horizon, in + the frame's order, with no interval. `modelo_sha` is the sha256 of the rule, so changing it changes + the provenance. + """ + + def __init__(self, cohort_url: str = "cacu/cohorte_vigilancia", outcome: str = "cin2_mas", + horizons: tuple[float, ...] = (0.0,)): + self.cohort_url = cohort_url + self.outcome = outcome + self.horizons = tuple(horizons) + + def provenance(self) -> Provenance: + rule = {"regla": CACU_RULE, "pap_normales": NORMAL_PAPS, "horizontes": self.horizons} + sha = hashlib.sha256(json.dumps(rule, sort_keys=True).encode("utf-8")).hexdigest() + return Provenance(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha) + + def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: + missing = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columns] + if missing: + raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.") + i_pac, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "pap_0", "hpv_0")) + risks = [] + for row in rows: + p = CACU_RULE["base"] + if row[i_pap] is not None and row[i_pap] not in NORMAL_PAPS: + p += CACU_RULE["pap_anormal"] + if row[i_hpv] == "POSITIVO": + p += CACU_RULE["vph_positivo"] + p = min(p, CACU_RULE["tope"]) + risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons] + return risks -- 2.53.0