From 4c5bccb80507db3be51345937af33d36827c9939 Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 09:29:21 +0000 Subject: [PATCH 01/28] 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)]) From 04c8cbafd179a72dc764c2e016049701f5e6c42c Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 12:34:55 +0000 Subject: [PATCH 02/28] 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"], []) From e5526b9ec349abe8e2b9f995fc7c6a4ad024198a Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 13:55:48 +0000 Subject: [PATCH 03/28] =?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"], []) From 92c5c69c2dbb43614d47a4ae56654ee9d2801914 Mon Sep 17 00:00:00 2001 From: rodrigo Date: Tue, 20 Oct 2026 19:55:13 +0000 Subject: [PATCH 04/28] =?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(): From 28ff4605f3482b27c1c86d313a4676c3979a9f09 Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 22 Oct 2026 20:48:30 +0000 Subject: [PATCH 05/28] 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", ] From c8bca59334d8fd6e1d1ca9873a73cdcd1512d788 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 19:30:08 +0000 Subject: [PATCH 06/28] 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"], []) From bc15cc3e0491db5a8b072b0427d30b630bcc8481 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 20:19:03 +0000 Subject: [PATCH 07/28] 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)) From 5fa931d92d211d1876c5f47ec81e59212264a841 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 20:27:05 +0000 Subject: [PATCH 08/28] 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. From d6f7acc1fad67f406a61ffd19e6b127a2be896d5 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 21:15:15 +0000 Subject: [PATCH 09/28] 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 From 449c67b19d765ec661918816c32364bfb56e7c27 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 21:16:51 +0000 Subject: [PATCH 10/28] 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) From dd94aba1eb513f3dcbb431d167e415eef4ea29f5 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 21:20:15 +0000 Subject: [PATCH 11/28] 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 From 0489475b8698b2b09933cdc7b56dada51d016d3b Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 21:34:40 +0000 Subject: [PATCH 12/28] training, registry: TrainingRun.log_model with modelo_sha, and registry.resolve --- models/registry.py | 33 ++++++++++ models/training.py | 36 +++++++++- tests/test_model_versions.py | 124 +++++++++++++++++++++++++++++++++++ 3 files changed, 191 insertions(+), 2 deletions(-) create mode 100644 tests/test_model_versions.py diff --git a/models/registry.py b/models/registry.py index cf104c5..60689a2 100644 --- a/models/registry.py +++ b/models/registry.py @@ -30,6 +30,7 @@ DOMAINS = ("cacu", "cama", "tea") REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri") PRODUCTION_ALIAS = "produccion" ARMADO_TAG = "kit.armado_id" +MODEL_SHA_TAG = "modelo_sha" @dataclass(frozen=True) @@ -51,6 +52,24 @@ def registered_name(domain: str, scenario: str) -> str: return f"{domain}-{scenario}" +@dataclass(frozen=True) +class ResolvedVersion: + """The version a caller will use, with what it needs to load it and to say where risks came from. + `status` is the version's status when it was resolved (`produccion`, `candidata`, `desarrollo` or + `retirada`).""" + + domain: str + scenario: str + version: str + run_id: str + status: str + modelo_sha: str | None + + @property + def model_uri(self) -> str: + return f"models:/{registered_name(self.domain, self.scenario)}/{self.version}" + + class ModelRegistry: """`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`.""" @@ -97,6 +116,20 @@ class ModelRegistry: def status(self, domain: str, scenario: str, version: str) -> str: return self._status(self.get(domain, scenario, version)) + def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion: + """With no `version`, the one holding the `produccion` alias; with a version, that one, whatever + its status (to test or compare a candidate). The status travels with it: confirming risks only + accepts versions that were in production.""" + if version is None: + try: + mv = self.client.get_model_version_by_alias(registered_name(domain, scenario), PRODUCTION_ALIAS) + except MlflowException as exc: + raise LookupError(f"({domain}, {scenario}) has no version in production") from exc + else: + mv = self.get(domain, scenario, version) + return ResolvedVersion(domain, scenario, str(mv.version), mv.run_id, self._status(mv), + mv.tags.get(MODEL_SHA_TAG)) + def register( self, *, diff --git a/models/training.py b/models/training.py index e1305c7..cbdc847 100644 --- a/models/training.py +++ b/models/training.py @@ -9,20 +9,33 @@ process never interfere. `MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their artifacts (MLflow's own default is `./mlruns`, relative to the working directory). + +A run that logs a model (`log_model`) registers `runs://model`, tagged +with its `modelo_sha`; one that doesn't registers the run itself. """ +import hashlib import json import os +import tempfile from pathlib import Path from typing import Any +import mlflow.pyfunc from core.governance.enums import ArtifactKind, Environment from mlflow import MlflowClient, MlflowException from persistance.repository import Repository from models.base import resolve_repository -from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name +from models.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" +MODEL_PATH = "model" + + +def model_sha(model_dir: str | Path) -> str: + """sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left + out because it carries ids and dates, so the same model saved twice has the same sha.""" + return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest() class ReadOnlyRepository: @@ -85,6 +98,7 @@ class TrainingRun: tags={"domain": domain, "scenario": scenario, "environment": environment.value}, ) self.run_id = run.info.run_id + self.modelo_sha: str | None = None if cohorte_armado_id is not None: self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id)) @@ -108,6 +122,21 @@ class TrainingRun: if metadata: self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json") + def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str: + """Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its + `modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input + example, so no patient data reaches MLflow.""" + if self.modelo_sha is not None: + raise RuntimeError("this run already logged its model") + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / MODEL_PATH + mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature) + sha = model_sha(path) + self.client.log_artifacts(self.run_id, str(path), MODEL_PATH) + self.client.set_tag(self.run_id, MODEL_SHA_TAG, sha) + self.modelo_sha = sha + return sha + def finish( self, *, @@ -137,7 +166,10 @@ class TrainingRun: version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value} if self.cohorte_armado_id is not None: version_tags[ARMADO_TAG] = str(self.cohorte_armado_id) + if self.modelo_sha is not None: + version_tags[MODEL_SHA_TAG] = self.modelo_sha version_tags.update({key: uri for key, uri in reports.items() if uri}) - model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags) + source = f"runs:/{self.run_id}/{MODEL_PATH}" if self.modelo_sha is not None else f"runs:/{self.run_id}" + model_version = self.client.create_model_version(name, source=source, run_id=self.run_id, tags=version_tags) self.client.set_terminated(self.run_id) return str(model_version.version) diff --git a/tests/test_model_versions.py b/tests/test_model_versions.py new file mode 100644 index 0000000..cb47c86 --- /dev/null +++ b/tests/test_model_versions.py @@ -0,0 +1,124 @@ +"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`) and +choosing the version to use (`registry.resolve`). + +Fixtures: `mlflow_tracking` (from `conftest.py`), a SQLite-backed MLflow per test; `production_ready` +(from `conftest.py`), which registers a PROD version that passes every promotion check. `Constant` is a +pyfunc that returns one fixed probability per row; `_train` registers a dev version, with or without a +logged model. +""" + +import mlflow.pyfunc +import pandas as pd +import pytest +from core.governance.enums import Environment +from mlflow import MlflowClient + +from models.registry import MODEL_SHA_TAG, registry +from models.training import TrainingRun + + +class Constant(mlflow.pyfunc.PythonModel): + """Returns `p` for every row.""" + + def __init__(self, p: float): + self.p = p + + def predict(self, context, model_input: pd.DataFrame, params=None) -> list[float]: + return [self.p] * len(model_input) + + +def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[TrainingRun, str]: + """A dev run of `cacu/` that logs `model` (if any) and is registered; returns the run and + its version.""" + run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV) + if model is not None: + run.log_model(model) + return run, run.finish(metrics={"auc": 0.7}) + + +def test_a_logged_model_is_what_the_version_loads(mlflow_tracking): + """Pins down: a run that logs a model registers `runs://model`, and loading the version gives + back that model, tagged with its `modelo_sha` on the run and on the version. + + Fails if `finish` registers the run instead of its model folder, or the sha isn't tagged. + """ + run, version = _train(Constant(0.25)) + + loaded = mlflow.pyfunc.load_model(registry.resolve("cacu", "tamizaje", version).model_uri) + mv = registry.get("cacu", "tamizaje", version) + + assert list(loaded.predict(pd.DataFrame({"x": [1, 2]}))) == [0.25, 0.25] + assert mv.source == f"runs:/{run.run_id}/model" + assert mv.tags[MODEL_SHA_TAG] == run.modelo_sha + assert MlflowClient().get_run(run.run_id).data.tags[MODEL_SHA_TAG] == run.modelo_sha + + +def test_the_sha_is_the_model_not_the_run(mlflow_tracking): + """Pins down: the same model logged in two runs has the same `modelo_sha`; a different model has + another one. + + Fails if `model_sha` starts covering files with ids or dates (`MLmodel`), or stops covering the model. + """ + first, _ = _train(Constant(0.25)) + second, _ = _train(Constant(0.25)) + other, _ = _train(Constant(0.30)) + + assert first.modelo_sha == second.modelo_sha != other.modelo_sha + + +def test_a_run_logs_one_model(mlflow_tracking): + """Pins down: a second `log_model` in the same run is refused. + + Fails if a run could hold two models, so its version wouldn't say which one it is. + """ + run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV) + run.log_model(Constant(0.25)) + + with pytest.raises(RuntimeError, match="already logged"): + run.log_model(Constant(0.30)) + + +def test_a_run_without_a_model_still_registers_the_run(mlflow_tracking): + """Pins down: a run that doesn't log a model registers `runs:/` with no `modelo_sha`, as + before `log_model` existed. + + Fails if `finish` requires a model. + """ + run, version = _train() + + resolved = registry.resolve("cacu", "tamizaje", version) + assert registry.get("cacu", "tamizaje", version).source == f"runs:/{run.run_id}" + assert resolved.modelo_sha is None + + +def test_without_a_version_resolve_takes_production(production_ready): + """Pins down: with no version, `resolve` returns the one holding `produccion`, with that status; with + none in production it raises `LookupError`. + + Fails if `resolve` falls back to the latest version instead of failing. + """ + domain, scenario, version = production_ready("v1") + with pytest.raises(LookupError, match="no version in production"): + registry.resolve(domain, scenario) + + registry.promote(domain, scenario, version) + resolved = registry.resolve(domain, scenario) + + assert (resolved.version, resolved.status) == (version, "produccion") + assert resolved.model_uri == f"models:/{domain}-{scenario}/{version}" + + +def test_an_explicit_version_is_returned_with_its_status(production_ready): + """Pins down: with a version, `resolve` returns it whatever its status (a candidate can be tested), + and says which status it has; an unknown version raises `LookupError`. + + Fails if an explicit version is refused for not being in production, or its status is lost. + """ + domain, scenario, first = production_ready("v1") + _, _, second = production_ready("v2") + registry.promote(domain, scenario, first) + + assert registry.resolve(domain, scenario, second).status == "candidata" + assert registry.resolve(domain, scenario, first).status == "produccion" + with pytest.raises(LookupError): + registry.resolve(domain, scenario, "99") From f08b249eaee8018953f7ef337a27586fbd754107 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 00:49:19 +0000 Subject: [PATCH 13/28] training: every run records the code's git commit; PROD logs only models defined in a module --- README.md | 2 +- models/training.py | 32 +++++++++++++++-- tests/test_model_versions.py | 67 +++++++++++++++++++++++++++++++++--- 3 files changed, 94 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0e717cc..32fa680 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ WebApi. | `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). | +| `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); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. | | `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). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | diff --git a/models/training.py b/models/training.py index cbdc847..d25e0a7 100644 --- a/models/training.py +++ b/models/training.py @@ -11,11 +11,17 @@ process never interfere. artifacts (MLflow's own default is `./mlruns`, relative to the working directory). A run that logs a model (`log_model`) registers `runs://model`, tagged -with its `modelo_sha`; one that doesn't registers the run itself. +with its `modelo_sha`: the hash of the stored artifact, which identifies the exact +model that produced a risk. Which code trained it is recorded apart: every run is +tagged with the git commit of this package's repository and whether it had +uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the +delivered images). A PROD run only logs models whose class lives in a module, at a +known commit, never one defined in a notebook. """ import hashlib import json import os +import subprocess import tempfile from pathlib import Path from typing import Any @@ -30,6 +36,25 @@ from models.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, reg ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" MODEL_PATH = "model" +GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets +GIT_DIRTY_TAG = "models.git.dirty" +GIT_COMMIT_ENV = "MODELS_GIT_COMMIT" + + +def code_version() -> dict[str, str]: + """The git commit of this package's repository and whether tracked files have uncommitted changes. + Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither, + nothing is recorded.""" + root = Path(__file__).resolve().parent + try: + commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, + check=True).stdout.strip() + changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"], + capture_output=True, text=True, check=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + commit = os.environ.get(GIT_COMMIT_ENV) + return {GIT_COMMIT_TAG: commit} if commit else {} + return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()} def model_sha(model_dir: str | Path) -> str: @@ -95,7 +120,7 @@ class TrainingRun: experiment_id = self._experiment_id() run = self.client.create_run( experiment_id, - tags={"domain": domain, "scenario": scenario, "environment": environment.value}, + tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()}, ) self.run_id = run.info.run_id self.modelo_sha: str | None = None @@ -128,6 +153,9 @@ class TrainingRun: example, so no patient data reaches MLflow.""" if self.modelo_sha is not None: raise RuntimeError("this run already logged its model") + if self.environment is Environment.PROD and type(python_model).__module__ == "__main__": + raise ValueError("a PROD run only logs models whose class lives in a module; " + f"{type(python_model).__name__} was defined in a notebook or script") with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / MODEL_PATH mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature) diff --git a/tests/test_model_versions.py b/tests/test_model_versions.py index cb47c86..505e23a 100644 --- a/tests/test_model_versions.py +++ b/tests/test_model_versions.py @@ -1,20 +1,24 @@ -"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`) and -choosing the version to use (`registry.resolve`). +"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`), the +code version every run records (`code_version`), and choosing the version to use (`registry.resolve`). Fixtures: `mlflow_tracking` (from `conftest.py`), a SQLite-backed MLflow per test; `production_ready` (from `conftest.py`), which registers a PROD version that passes every promotion check. `Constant` is a pyfunc that returns one fixed probability per row; `_train` registers a dev version, with or without a -logged model. +logged model; `_git` asks git about this repository, to compare with what the run recorded. """ +import subprocess +from pathlib import Path + import mlflow.pyfunc import pandas as pd import pytest from core.governance.enums import Environment from mlflow import MlflowClient +from models import training from models.registry import MODEL_SHA_TAG, registry -from models.training import TrainingRun +from models.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun class Constant(mlflow.pyfunc.PythonModel): @@ -122,3 +126,58 @@ def test_an_explicit_version_is_returned_with_its_status(production_ready): assert registry.resolve(domain, scenario, first).status == "produccion" with pytest.raises(LookupError): registry.resolve(domain, scenario, "99") + + +def _git(*args: str) -> str: + return subprocess.run(["git", "-C", str(Path(training.__file__).parent), *args], capture_output=True, text=True, + check=True).stdout.strip() + + +def test_every_run_records_the_commit_of_the_code(mlflow_tracking): + """Pins down: a run is tagged with the git commit of the `models` repository (MLflow's own tag name) and + whether tracked files had uncommitted changes; untracked files (notebooks, data) don't count. + + Fails if the tags are dropped or renamed, or the dirty flag counts untracked files. + """ + run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV) + tags = MlflowClient().get_run(run.run_id).data.tags + + assert tags[GIT_COMMIT_TAG] == _git("rev-parse", "HEAD") + assert tags[GIT_DIRTY_TAG] == str(bool(_git("status", "--porcelain", "--untracked-files=no"))).lower() + + +def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_tracking, monkeypatch): + """Pins down: where git or the repository is missing (a delivered image), the commit is read from + `MODELS_GIT_COMMIT`, with no dirty flag; with neither, the run records no commit rather than a guess. + + Fails if a missing repository raises, or a commit is invented. + """ + def no_git(*args, **kwargs): + raise FileNotFoundError("git") + + monkeypatch.setattr(training.subprocess, "run", no_git) + monkeypatch.setenv(GIT_COMMIT_ENV, "abc123") + tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje", + environment=Environment.DEV).run_id).data.tags + assert tags[GIT_COMMIT_TAG] == "abc123" and GIT_DIRTY_TAG not in tags + + monkeypatch.delenv(GIT_COMMIT_ENV) + tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje", + environment=Environment.DEV).run_id).data.tags + assert GIT_COMMIT_TAG not in tags + + +def test_a_prod_run_refuses_a_model_defined_in_a_notebook(mlflow_tracking): + """Pins down: a PROD run only logs a model whose class lives in a module; one defined in a notebook or + script (`__main__`) is refused, because its code has no commit to trace. A dev run accepts it. + + Fails if the check is dropped, or starts refusing dev runs or module classes. + """ + InNotebook = type("InNotebook", (Constant,), {"__module__": "__main__"}) + prod = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD, cohorte_armado_id=1) + + with pytest.raises(ValueError, match="defined in a notebook"): + prod.log_model(InNotebook(0.25)) + prod.log_model(Constant(0.25)) + TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).log_model(InNotebook(0.25)) + From b06ff5ce52a24f551026673711adffc1b4940348 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 11:07:01 -0600 Subject: [PATCH 14/28] notebooks: CaCu CIN2+ exploratory analysis of the surveillance cohort, from its build's Parquet file --- notebooks/cacu/cin2_logistic/01_eda.ipynb | 158 ++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 notebooks/cacu/cin2_logistic/01_eda.ipynb diff --git a/notebooks/cacu/cin2_logistic/01_eda.ipynb b/notebooks/cacu/cin2_logistic/01_eda.ipynb new file mode 100644 index 0000000..320fc8a --- /dev/null +++ b/notebooks/cacu/cin2_logistic/01_eda.ipynb @@ -0,0 +1,158 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# CaCu · CIN2+ · 01 — Exploratory analysis of the cohort\n\nFirst notebook of the `cin2_logistic` scenario: **exploratory only**. It describes the surveillance cohort\n(`cacu/cohorte_vigilancia`) from its build's Parquet file: who is in, what was measured at the index sample, and\nwhat happened afterwards. No outcome is computed and no model is fitted here.\n\n**How it gets its data, as in the deployment**\n\n- The domain's database is `CACU_DATABASE_URL`; the cohort files live next to it, in `/cohorts/`,\n or in `COHORTS_DIR` when the data folder is read-only (as in the deployments).\n- A build's file is written **once**: if it already exists for that build, it's read; if not, it's exported\n from the build's members and dbt's timeline view, then read. Running the notebook again rebuilds nothing.\n- Every read goes through the domain's repositories; the notebook never opens a session.\n- **Locally**, with no `CACU_DATABASE_URL`, it works on a copy of the DEV deployment's simulated data in\n `~/.cache/isssteleon-notebooks/`, outside the repository, kept between runs.\n\n**With real data:** commit this notebook without outputs, and don't share counts below the suppression threshold.\n\nKernel: *ISSSTELEON WebApi env: kit + Persistance + models*.", + "id": "cacu-cin2-01-00" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "## 1. Configuration", + "id": "cacu-cin2-01-01" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/notebooks/cacu/cin2_logistic → ../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[3] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))", + "id": "cacu-cin2-01-02" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "## 2. dbt's timeline view\n\nThe export reads each member's history from `cacu_linea_de_tiempo`, the view dbt creates at deployment. If the\ndatabase doesn't have it and it's a local copy, it's created here; in a deployment, it has to be deployed first.", + "id": "cacu-cin2-01-03" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "from persistance.aristas.plata import TIMELINE_COLUMNS # noqa: E402 after the URL is set\nfrom persistance.cacu import cohorte_repository, timeline_repository # noqa: E402\nfrom sqlalchemy import column, select, table # noqa: E402\nfrom sqlalchemy.exc import OperationalError # noqa: E402\n\nVIEW = table(f\"{DOMAIN}_linea_de_tiempo\", *(column(c) for c in TIMELINE_COLUMNS))\n\n\ndef from_dbt_view(*, patients, until, known_until):\n \"\"\"The timeline query over dbt's view, with the repository's filters (provisional: it belongs in Persistance).\"\"\"\n query = select(*(VIEW.c[c] for c in TIMELINE_COLUMNS)).order_by(\n VIEW.c.pac_id, VIEW.c.fecha, VIEW.c.clase, VIEW.c.tipo, VIEW.c.fuente_id)\n if patients is not None:\n query = query.where(VIEW.c.pac_id.in_(patients))\n if until is not None:\n query = query.where(VIEW.c.fecha <= until)\n if known_until is not None:\n query = query.where(VIEW.c.conocida_en <= known_until)\n return query\n\n\ndef view_present() -> bool:\n \"\"\"Whether dbt's view exists: an empty read through the repository fails if it doesn't.\"\"\"\n try:\n timeline_repository.with_query(from_dbt_view).read(patients=[])\n return True\n except OperationalError:\n return False\n\n\nhas_view = view_present()\nif not has_view and Path.home() in database.parents:\n schemas = DATA / \"dbt_schemas\"\n schemas.mkdir(exist_ok=True)\n run = subprocess.run([\"uv\", \"run\", \"--no-sync\", \"dbt\", \"run\", \"--profiles-dir\", \".\", \"--profile\", \"cacu\",\n \"--select\", \"cacu_linea_de_tiempo\"], cwd=TRANSFORMATION, capture_output=True, text=True,\n env={**os.environ, \"CACU_DB_PATH\": str(database), \"DBT_SCHEMA_DIR\": str(schemas)})\n print(run.stdout.strip().splitlines()[-1])\n has_view = view_present()\nprint(\"timeline view present:\", has_view)", + "id": "cacu-cin2-01-04" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "## 3. The build's file: read it if it exists, export it once if not\n\nProvisional helpers: they will move into the code (a cycle step that exports each build, and the timeline\nquery over dbt's view in Persistance).", + "id": "cacu-cin2-01-05" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "import hashlib\nimport json\nimport tempfile\nfrom datetime import datetime, timezone\n\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nSCHEMA = pa.schema([\n (\"pac_id\", pa.int64()), (\"fecha_indice\", pa.date32()), (\"fecha\", pa.date32()),\n (\"conocida_en\", pa.timestamp(\"us\", tz=\"UTC\")), (\"clase\", pa.string()), (\"tipo\", pa.string()),\n (\"codigo\", pa.string()), (\"valor_codigo\", pa.string()), (\"valor_numerico\", pa.float64()),\n (\"fuente_tabla\", pa.string()), (\"fuente_id\", pa.string()),\n])\ndef cohort_file(build) -> Path:\n domain, cohort = build.url.split(\"/\", 1)\n return COHORTS / domain / cohort / f\"{build.armado_id}.parquet\"\n\n\ndef lineage_of(path: Path) -> dict:\n meta = pq.read_metadata(path).metadata\n return {k.decode(): v.decode() for k, v in meta.items() if k not in (b\"pandas\", b\"ARROW:schema\")}\n\n\ndef export(build, path: Path) -> None:\n members = cohorte_repository.members(build.armado_id)\n rows = timeline_repository.with_query(from_dbt_view).read(\n patients=[m.pac_id for m in members], until=build.datos_as_of, known_until=build.conocida_hasta)\n frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(\n pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=[\"pac_id\", \"fecha_indice\"]), on=\"pac_id\")\n for name in (\"fecha_indice\", \"fecha\"):\n frame[name] = pd.to_datetime(frame[name]).dt.date\n frame[\"conocida_en\"] = pd.to_datetime(frame[\"conocida_en\"], utc=True)\n frame[\"valor_numerico\"] = pd.to_numeric(frame[\"valor_numerico\"])\n lineage = {\"url\": build.url, \"version\": build.version, \"armado_id\": build.armado_id, \"domain\": DOMAIN,\n \"datos_as_of\": build.datos_as_of.isoformat(),\n \"conocida_hasta\": build.conocida_hasta.isoformat() if build.conocida_hasta else \"\",\n \"n_members\": len(members), \"producer\": \"kit build, timeline from dbt view (provisional)\",\n \"built_at\": datetime.now(timezone.utc).isoformat()}\n arrow = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)\n arrow = arrow.replace_schema_metadata({**arrow.schema.metadata, **{k: str(v) for k, v in lineage.items()}})\n path.parent.mkdir(parents=True, exist_ok=True)\n with tempfile.NamedTemporaryFile(dir=path.parent, suffix=\".tmp\", delete=False) as tmp:\n pq.write_table(arrow, tmp.name)\n Path(tmp.name).replace(path) # appears complete or not at all\n\n\ndef ensure(build) -> tuple[Path, str]:\n \"\"\"The build's file: reused if it already exists for this build, exported once if not. Returns (path, what happened).\"\"\"\n path = cohort_file(build)\n if path.exists():\n lineage = lineage_of(path)\n if lineage.get(\"armado_id\") != str(build.armado_id) or lineage.get(\"n_members\") != str(build.n_miembros):\n raise ValueError(f\"{path} doesn't belong to build {build.armado_id}: {lineage}\")\n return path, \"reused\"\n if not has_view:\n raise RuntimeError(\"dbt's timeline view isn't in the database: deploy it before exporting\")\n export(build, path)\n return path, \"exported\"", + "id": "cacu-cin2-01-06" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "builds = pd.DataFrame([vars(b) for b in cohorte_repository.builds()])\nbuilds[[\"armado_id\", \"url\", \"version\", \"datos_as_of\", \"conocida_hasta\", \"n_miembros\", \"armado_en\"]]", + "id": "cacu-cin2-01-07" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "build = cohorte_repository.builds(COHORT_URL)[0] # the newest build of the cohort\npath, what = ensure(build)\nprint(what, path)\nprint(\"sha256:\", hashlib.sha256(path.read_bytes()).hexdigest())\nlineage_of(path)", + "id": "cacu-cin2-01-08" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "Running it again reuses the file: nothing is rebuilt and the file, and so its hash, stays the same.", + "id": "cacu-cin2-01-09" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "again, what = ensure(build)\nprint(what, \"| same file:\", again == path, \"| same sha256:\",\n hashlib.sha256(again.read_bytes()).hexdigest() == hashlib.sha256(path.read_bytes()).hexdigest())", + "id": "cacu-cin2-01-10" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "## 4. The cohort\n\nOne row per member, variable and date. `fecha_indice` is on every row; the index sample is the member's index\nevent (`fuente_tabla`, `fuente_id`), and its results are dated when they were **reported**, usually after the\nindex date.", + "id": "cacu-cin2-01-11" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "cohort = pd.read_parquet(path)\ncohort[\"dias\"] = (pd.to_datetime(cohort.fecha) - pd.to_datetime(cohort.fecha_indice)).dt.days\nmembers = cohort.groupby(\"pac_id\").fecha_indice.first()\nprint(f\"{len(cohort):,} rows · {members.size:,} members · index dates {members.min()} to {members.max()}\")\nmembers.pipe(pd.to_datetime).dt.to_period(\"Q\").value_counts().sort_index().rename(\"members by quarter of the index date\").to_frame().T", + "id": "cacu-cin2-01-12" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "cohort[\"momento\"] = pd.cut(cohort.dias, [-10**6, -1, 0, 10**6], labels=[\"before\", \"on the index date\", \"after\"])\ncohort.pivot_table(index=[\"clase\", \"tipo\"], columns=\"momento\", values=\"pac_id\", aggfunc=\"count\", observed=False, fill_value=0)", + "id": "cacu-cin2-01-13" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "## 5. At the index sample\n\nThe results of the member's own index cytology: its Bethesda category and its HPV result, matched by the source\nrow of the index event, not by date.", + "id": "cacu-cin2-01-14" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "sample = cohort[cohort.tipo == \"citologia\"].merge(members.rename(\"fi\"), left_on=\"pac_id\", right_index=True)\nsample = sample[sample.fecha == sample.fi].groupby(\"pac_id\").fuente_id.first().rename(\"muestra\")\nat_index = cohort.merge(sample, left_on=\"pac_id\", right_index=True)\nat_index = at_index[at_index.fuente_id == at_index.muestra]\nbaseline = at_index.pivot_table(index=\"pac_id\", columns=\"tipo\", values=\"valor_codigo\", aggfunc=\"first\")\nbaseline = baseline.reindex(members.index)\nprint(\"members without an HPV result at the index sample:\", f\"{baseline.vph.isna().mean():.1%}\")\npd.crosstab(baseline.bethesda.fillna(\"(none)\"), baseline.vph.fillna(\"(none)\"), margins=True)", + "id": "cacu-cin2-01-15" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "## 6. After the index\n\nFollow-up: how long it lasts, how many members had a biopsy and when, and the grades reported.", + "id": "cacu-cin2-01-16" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "after = cohort[cohort.dias > 0]\nfollow_up = after.groupby(\"pac_id\").dias.max().reindex(members.index).fillna(0)\nfirst_biopsy = after[after.tipo == \"biopsia\"].groupby(\"pac_id\").dias.min()\nprint(f\"follow-up (days to the last event): median {follow_up.median():.0f}, quartiles {follow_up.quantile(.25):.0f}–{follow_up.quantile(.75):.0f}\")\nprint(f\"members with a biopsy after the index: {first_biopsy.size:,} ({first_biopsy.size / members.size:.1%}); \"\n f\"days to the first one: median {first_biopsy.median():.0f}\")\nafter[after.tipo == \"biopsia\"].valor_codigo.fillna(\"(no grade)\").value_counts().rename(\"biopsy results after the index\").to_frame()", + "id": "cacu-cin2-01-17" + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": "import matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(1, 2, figsize=(11, 3.5))\nfollow_up.div(30.44).plot.hist(bins=30, ax=axes[0], title=\"Follow-up per member (months)\")\nfirst_biopsy.div(30.44).plot.hist(bins=30, ax=axes[1], title=\"Index to first biopsy (months)\")\nfor ax in axes:\n ax.set_ylabel(\"members\")\nplt.tight_layout()", + "id": "cacu-cin2-01-18" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "## Next\n\n- **02 — profiling and hypothesis tests**, and the outcome itself (prevalent CIN2+ and time to it), computed by\n the model from these rows, not by the cohort.\n- The helpers of sections 2 and 3 move into the code: the export into the cycle, and the timeline query over\n dbt's view into Persistance.", + "id": "cacu-cin2-01-19" + } + ], + "metadata": { + "kernelspec": { + "display_name": "ISSSTELEON WebApi env: kit + Persistance + models (feature/model-proto)", + "language": "python", + "name": "isssteleon-webapi" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file From 2d22409e1f5e307dd5900b072b377a45ceedb7a6 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 12:48:41 -0600 Subject: [PATCH 15/28] Layout: per-domain folders, io, steps and pipelines, and one command line --- README.md | 20 +++++---- models/__main__.py | 32 +++++++++++++++ models/base.py | 41 ------------------- models/cacu.py | 21 ---------- models/cacu/__init__.py | 1 + .../notebooks}/cin2_logistic/01_eda.ipynb | 2 +- models/cama.py | 21 ---------- models/cama/__init__.py | 1 + models/dags/__init__.py | 1 - models/io/__init__.py | 1 + models/{ => io}/contract.py | 0 models/{ => io}/export.py | 2 +- models/{ => io}/prediction.py | 17 +++++--- models/{ => io}/registry.py | 6 +-- models/io/repositories.py | 14 +++++++ models/{ => io}/training.py | 6 +-- models/ocr.py | 2 +- models/pipelines/__init__.py | 1 + models/{dags => pipelines}/reading.py | 0 models/steps/__init__.py | 1 + models/tea.py | 21 ---------- models/tea/__init__.py | 1 + models/testing.py | 2 +- pyproject.toml | 5 ++- tests/conftest.py | 2 +- tests/{ => io}/test_contract.py | 4 +- tests/{ => io}/test_export.py | 2 +- tests/{ => io}/test_model_versions.py | 6 +-- tests/{ => io}/test_prediction.py | 12 ++---- tests/{ => io}/test_registry.py | 4 +- tests/io/test_repositories.py | 28 +++++++++++++ tests/{ => io}/test_training.py | 4 +- tests/{ => pipelines}/test_reading_nodes.py | 4 +- tests/test_data_access.py | 27 ------------ tests/test_interfaces.py | 19 --------- tests/test_main.py | 33 +++++++++++++++ 36 files changed, 164 insertions(+), 200 deletions(-) create mode 100644 models/__main__.py delete mode 100644 models/base.py delete mode 100644 models/cacu.py create mode 100644 models/cacu/__init__.py rename {notebooks/cacu => models/cacu/notebooks}/cin2_logistic/01_eda.ipynb (92%) delete mode 100644 models/cama.py create mode 100644 models/cama/__init__.py delete mode 100644 models/dags/__init__.py create mode 100644 models/io/__init__.py rename models/{ => io}/contract.py (100%) rename models/{ => io}/export.py (94%) rename models/{ => io}/prediction.py (91%) rename models/{ => io}/registry.py (98%) create mode 100644 models/io/repositories.py rename models/{ => io}/training.py (97%) create mode 100644 models/pipelines/__init__.py rename models/{dags => pipelines}/reading.py (100%) create mode 100644 models/steps/__init__.py delete mode 100644 models/tea.py create mode 100644 models/tea/__init__.py rename tests/{ => io}/test_contract.py (95%) rename tests/{ => io}/test_export.py (97%) rename tests/{ => io}/test_model_versions.py (97%) rename tests/{ => io}/test_prediction.py (89%) rename tests/{ => io}/test_registry.py (96%) create mode 100644 tests/io/test_repositories.py rename tests/{ => io}/test_training.py (96%) rename tests/{ => pipelines}/test_reading_nodes.py (98%) delete mode 100644 tests/test_data_access.py delete mode 100644 tests/test_interfaces.py create mode 100644 tests/test_main.py diff --git a/README.md b/README.md index 32fa680..fd52038 100644 --- a/README.md +++ b/README.md @@ -9,16 +9,18 @@ WebApi. | Módulo | Qué hace | |---|---| -| `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); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. | -| `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). | +| `__main__.py` | La línea de comandos: `python -m models `. Cada área agrega ahí sus subcomandos. | +| `io/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). | +| `io/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); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. | +| `io/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`. | +| `io/prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | +| `io/export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. | +| `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. | +| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | +| `pipelines/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. | +| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | -| `export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. | +| `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. | MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`). `MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos diff --git a/models/__main__.py b/models/__main__.py new file mode 100644 index 0000000..979b835 --- /dev/null +++ b/models/__main__.py @@ -0,0 +1,32 @@ +"""The package's command line: `python -m models `. + +Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit) belong inside the +command that needs them, so `--help` stays immediate. +""" +import argparse +import sys +from collections.abc import Sequence + + +def _show_help(parser: argparse.ArgumentParser) -> int: + """A command without actions yet shows its help and fails, rather than appearing to have run.""" + parser.print_help() + return 2 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.") + commands = parser.add_subparsers(dest="command", metavar="", required=True) + + cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files") + cohorts.set_defaults(run=lambda args: _show_help(cohorts)) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + return args.run(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/models/base.py b/models/base.py deleted file mode 100644 index b6773f5..0000000 --- a/models/base.py +++ /dev/null @@ -1,41 +0,0 @@ -import importlib -from abc import ABC, abstractmethod -from typing import Any, ClassVar, Iterator - -from persistance.repository import Repository - - -def resolve_repository(domain: str, entity: str) -> Repository: - """`entity` is the repository's name in `persistance.` without - the suffix, e.g. `"paciente"`, `"citologia_cervical"`.""" - module = importlib.import_module(f"persistance.{domain}") - try: - return getattr(module, f"{entity}_repository") - except AttributeError as exc: - raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc - - -class ScreeningModel(ABC): - """Common train()/predict() interface for the CaCu, CaMa and TEA models. - - Data is read through the same `persistance.._repository` - objects WebApi writes with, so anything loaded through the import flow - is visible here. `train` may also be given rows fetched by the caller. - """ - - domain: ClassVar[str] - - def repository(self, entity: str) -> Repository: - return resolve_repository(self.domain, entity) - - def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]: - """Every row of `entity` as plain dicts, read in batches.""" - return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters)) - - @abstractmethod - def train(self, data: Any = None) -> None: - """Fit the model, optionally on `data` passed in by the caller.""" - - @abstractmethod - def predict(self, data: Any) -> Any: - """Score `data` and return predictions.""" diff --git a/models/cacu.py b/models/cacu.py deleted file mode 100644 index 03d711e..0000000 --- a/models/cacu.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from models.base import ScreeningModel - - -class CaCuModel(ScreeningModel): - """Scaffold for the CaCu (cervical cancer) screening model. - - Can pull its own training data straight from `persistance.cacu`'s - repositories (`paciente_repository`, `citologia_cervical_repository`, - `biopsia_cervical_repository`, ...) or be handed already-fetched rows. - No real model yet; this is interface scaffolding only. - """ - - domain = "cacu" - - def train(self, data: Any = None) -> None: - raise NotImplementedError("CaCu training is not implemented yet.") - - def predict(self, data: Any) -> Any: - raise NotImplementedError("CaCu prediction is not implemented yet.") diff --git a/models/cacu/__init__.py b/models/cacu/__init__.py new file mode 100644 index 0000000..d4c0509 --- /dev/null +++ b/models/cacu/__init__.py @@ -0,0 +1 @@ +"""CaCu's scenarios and notebooks.""" diff --git a/notebooks/cacu/cin2_logistic/01_eda.ipynb b/models/cacu/notebooks/cin2_logistic/01_eda.ipynb similarity index 92% rename from notebooks/cacu/cin2_logistic/01_eda.ipynb rename to models/cacu/notebooks/cin2_logistic/01_eda.ipynb index 320fc8a..c5be55f 100644 --- a/notebooks/cacu/cin2_logistic/01_eda.ipynb +++ b/models/cacu/notebooks/cin2_logistic/01_eda.ipynb @@ -17,7 +17,7 @@ "metadata": {}, "execution_count": null, "outputs": [], - "source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/notebooks/cacu/cin2_logistic → ../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[3] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))", + "source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/models/cacu/notebooks/cin2_logistic → ../../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[4] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))", "id": "cacu-cin2-01-02" }, { diff --git a/models/cama.py b/models/cama.py deleted file mode 100644 index 95d12e6..0000000 --- a/models/cama.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from models.base import ScreeningModel - - -class CaMaModel(ScreeningModel): - """Scaffold for the CaMa (breast cancer) screening model. - - Can pull its own training data straight from `persistance.cama`'s - repositories (`paciente_repository`, `mastografia_repository`, - `biopsia_mama_repository`, ...) or be handed already-fetched rows. - No real model yet; this is interface scaffolding only. - """ - - domain = "cama" - - def train(self, data: Any = None) -> None: - raise NotImplementedError("CaMa training is not implemented yet.") - - def predict(self, data: Any) -> Any: - raise NotImplementedError("CaMa prediction is not implemented yet.") diff --git a/models/cama/__init__.py b/models/cama/__init__.py new file mode 100644 index 0000000..80028b4 --- /dev/null +++ b/models/cama/__init__.py @@ -0,0 +1 @@ +"""CaMa's scenarios and notebooks.""" diff --git a/models/dags/__init__.py b/models/dags/__init__.py deleted file mode 100644 index 2d7d505..0000000 --- a/models/dags/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Hamilton modules for the model DAGs: each function is a node, each parameter an edge.""" diff --git a/models/io/__init__.py b/models/io/__init__.py new file mode 100644 index 0000000..c19e917 --- /dev/null +++ b/models/io/__init__.py @@ -0,0 +1 @@ +"""Data in and out, and the contracts: databases, files, the model registry. Nothing here computes.""" diff --git a/models/contract.py b/models/io/contract.py similarity index 100% rename from models/contract.py rename to models/io/contract.py diff --git a/models/export.py b/models/io/export.py similarity index 94% rename from models/export.py rename to models/io/export.py index 5201ebe..9d9ecc7 100644 --- a/models/export.py +++ b/models/io/export.py @@ -1,6 +1,6 @@ """ONNX checkpoint inspection (ML-01b, MLD-03). -Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`, +Writing/storing a checkpoint is `models.io.training.TrainingRun.log_artifact`, which hands it to MLflow directly — nothing here manages storage paths. `onnx` is an optional dependency (`models[export]`); without it `inspect_onnx_metadata` returns `{"available": False}`. diff --git a/models/prediction.py b/models/io/prediction.py similarity index 91% rename from models/prediction.py rename to models/io/prediction.py index fc00737..588fcd3 100644 --- a/models/prediction.py +++ b/models/io/prediction.py @@ -6,14 +6,19 @@ import hashlib import json from collections.abc import Callable from dataclasses import dataclass -from typing import Any +from typing import Any, Protocol from core.governance.models import ModelPrediction from mlflow import MlflowException from persistance.governance import model_prediction_repository -from models.base import ScreeningModel -from models.registry import PRODUCTION_ALIAS, registered_name, registry +from models.io.registry import PRODUCTION_ALIAS, registered_name, registry + + +class Predictor(Protocol): + """What the service needs from a model.""" + + def predict(self, data: Any) -> Any: ... @dataclass @@ -42,7 +47,7 @@ class ApplicabilityRejected(Exception): class PredictionService: - """Runs a `ScreeningModel` and records its predictions against the + """Runs a model and records its predictions against the MLflow version holding the `produccion` alias for `(domain, scenario)`. If `aplicable` is given, each row (a dict of fields) is checked with it @@ -52,7 +57,7 @@ class PredictionService: def __init__( self, - model: ScreeningModel, + model: Predictor, *, domain: str, scenario: str, @@ -104,7 +109,7 @@ class PredictionService: if model_version is None: raise RuntimeError( f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; " - "promueva una con models.registry.registry.promote antes de predecir" + "promueva una con models.io.registry.registry.promote antes de predecir" ) input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest() diff --git a/models/registry.py b/models/io/registry.py similarity index 98% rename from models/registry.py rename to models/io/registry.py index 60689a2..874c548 100644 --- a/models/registry.py +++ b/models/io/registry.py @@ -24,7 +24,7 @@ from mlflow import MlflowClient, MlflowException from persistance.governance import model_prediction_repository from sqlmodel import select -from models.export import inspect_onnx_metadata +from models.io.export import inspect_onnx_metadata DOMAINS = ("cacu", "cama", "tea") REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri") @@ -142,8 +142,8 @@ class ModelRegistry: **reports: str | None, ) -> str: """For training code that runs elsewhere and reports over the API. - In-process training uses `models.training.TrainingRun` directly.""" - from models.training import TrainingRun + In-process training uses `models.io.training.TrainingRun` directly.""" + from models.io.training import TrainingRun run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id) return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports) diff --git a/models/io/repositories.py b/models/io/repositories.py new file mode 100644 index 0000000..fd7e0fb --- /dev/null +++ b/models/io/repositories.py @@ -0,0 +1,14 @@ +"""Finds a domain's Persistance repository by name, the same objects WebApi writes with.""" +import importlib + +from persistance.repository import Repository + + +def resolve_repository(domain: str, entity: str) -> Repository: + """`entity` is the repository's name in `persistance.` without + the suffix, e.g. `"paciente"`, `"citologia_cervical"`.""" + module = importlib.import_module(f"persistance.{domain}") + try: + return getattr(module, f"{entity}_repository") + except AttributeError as exc: + raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc diff --git a/models/training.py b/models/io/training.py similarity index 97% rename from models/training.py rename to models/io/training.py index d25e0a7..a6d70e0 100644 --- a/models/training.py +++ b/models/io/training.py @@ -31,8 +31,8 @@ from core.governance.enums import ArtifactKind, Environment from mlflow import MlflowClient, MlflowException from persistance.repository import Repository -from models.base import resolve_repository -from models.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name +from models.io.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name +from models.io.repositories import resolve_repository ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" MODEL_PATH = "model" @@ -173,7 +173,7 @@ class TrainingRun: **reports: str | None, ) -> str: """Logs metrics/params to the run, registers it as a new version of - `-` tagged with `models.registry`'s promotion + `-` tagged with `models.io.registry`'s promotion inputs (environment, cohort link, report URIs), and returns the new version string. Call once, after training (and artifact logging) completes.""" diff --git a/models/ocr.py b/models/ocr.py index e54b671..295d17d 100644 --- a/models/ocr.py +++ b/models/ocr.py @@ -32,7 +32,7 @@ from extraction import FieldKind, FieldSpec, read_document from extraction.nlp import RecordExtractor, SegmentLine from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for from extraction.ocr import TesseractOcr -from models.base import resolve_repository +from models.io.repositories import resolve_repository from persistance.repository import Repository # Below this confidence a value is stored but flagged for manual review. diff --git a/models/pipelines/__init__.py b/models/pipelines/__init__.py new file mode 100644 index 0000000..cf0fbaa --- /dev/null +++ b/models/pipelines/__init__.py @@ -0,0 +1 @@ +"""Hamilton modules that wire steps into graphs: each function is a node, each parameter an edge.""" diff --git a/models/dags/reading.py b/models/pipelines/reading.py similarity index 100% rename from models/dags/reading.py rename to models/pipelines/reading.py diff --git a/models/steps/__init__.py b/models/steps/__init__.py new file mode 100644 index 0000000..b3a5d1c --- /dev/null +++ b/models/steps/__init__.py @@ -0,0 +1 @@ +"""Pure functions shared by every model: no I/O, testable alone.""" diff --git a/models/tea.py b/models/tea.py deleted file mode 100644 index e42bf90..0000000 --- a/models/tea.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Any - -from models.base import ScreeningModel - - -class TeaModel(ScreeningModel): - """Scaffold for the TEA (autism spectrum disorder) screening model. - - Can pull its own training data straight from `persistance.tea`'s - repositories (`pacientes_repository`, `evaluacion_psicologica_repository`, - ...) or be handed already-fetched rows. No real model yet; this is - interface scaffolding only. - """ - - domain = "tea" - - def train(self, data: Any = None) -> None: - raise NotImplementedError("TEA training is not implemented yet.") - - def predict(self, data: Any) -> Any: - raise NotImplementedError("TEA prediction is not implemented yet.") diff --git a/models/tea/__init__.py b/models/tea/__init__.py new file mode 100644 index 0000000..62a9d63 --- /dev/null +++ b/models/tea/__init__.py @@ -0,0 +1 @@ +"""TEA's scenarios and notebooks.""" diff --git a/models/testing.py b/models/testing.py index 6e1e092..a3bc49d 100644 --- a/models/testing.py +++ b/models/testing.py @@ -8,7 +8,7 @@ model and isn't used outside tests; it has no tests of its own. import hashlib import json -from models.contract import Provenance, Risk +from models.io.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} diff --git a/pyproject.toml b/pyproject.toml index d054073..a063a5f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,13 +7,13 @@ dependencies = [ "persistance", "extraction", "mlflow>=2.9", - # The model DAGs (`models/dags`): each function a node, each parameter an edge. + # The model DAGs (`models/pipelines`): each function a node, each parameter an edge. "apache-hamilton>=1.90", ] [project.optional-dependencies] # Only needed to read back a checkpoint's own metadata (opset, producer) in -# models.export.inspect_onnx_metadata — writing/logging a checkpoint never +# models.io.export.inspect_onnx_metadata — writing/logging a checkpoint never # requires it, see that module's docstring. export = [ "onnx>=1.15", @@ -29,6 +29,7 @@ build-backend = "hatchling.build" [tool.hatch.build.targets.wheel] packages = ["models"] +exclude = ["**/notebooks"] [dependency-groups] dev = [ diff --git a/tests/conftest.py b/tests/conftest.py index 67f5955..e50e900 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -49,7 +49,7 @@ def production_ready(governance_db, cacu_db, mlflow_tracking): """Factory: registers a PROD version that passes every promotion check, returns (domain, scenario, version).""" from core.governance.enums import ArtifactKind, Environment - from models.registry import registry + from models.io.registry import registry def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None): version = registry.register( diff --git a/tests/test_contract.py b/tests/io/test_contract.py similarity index 95% rename from tests/test_contract.py rename to tests/io/test_contract.py index 2ebe277..b178ee9 100644 --- a/tests/test_contract.py +++ b/tests/io/test_contract.py @@ -1,11 +1,11 @@ -"""What this module covers: the `RiskEstimator` contract in `models.contract` and the two records it +"""What this module covers: the `RiskEstimator` contract in `models.io.contract` and the two records it returns, `Risk` and `Provenance`. Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one fixed probability per member and horizon. `Incomplete` lacks `provenance`. """ -from models.contract import Provenance, Risk, RiskEstimator +from models.io.contract import Provenance, Risk, RiskEstimator class ConstantEstimator: diff --git a/tests/test_export.py b/tests/io/test_export.py similarity index 97% rename from tests/test_export.py rename to tests/io/test_export.py index 05fad8e..c516199 100644 --- a/tests/test_export.py +++ b/tests/io/test_export.py @@ -2,7 +2,7 @@ import onnx import onnx.helper import pytest -from models.export import inspect_onnx_metadata +from models.io.export import inspect_onnx_metadata def _tiny_onnx_bytes() -> bytes: diff --git a/tests/test_model_versions.py b/tests/io/test_model_versions.py similarity index 97% rename from tests/test_model_versions.py rename to tests/io/test_model_versions.py index 505e23a..a702716 100644 --- a/tests/test_model_versions.py +++ b/tests/io/test_model_versions.py @@ -16,9 +16,9 @@ import pytest from core.governance.enums import Environment from mlflow import MlflowClient -from models import training -from models.registry import MODEL_SHA_TAG, registry -from models.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun +from models.io import training +from models.io.registry import MODEL_SHA_TAG, registry +from models.io.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun class Constant(mlflow.pyfunc.PythonModel): diff --git a/tests/test_prediction.py b/tests/io/test_prediction.py similarity index 89% rename from tests/test_prediction.py rename to tests/io/test_prediction.py index 9d147b1..0b42866 100644 --- a/tests/test_prediction.py +++ b/tests/io/test_prediction.py @@ -2,17 +2,11 @@ import json import pytest -from models.base import ScreeningModel -from models.prediction import ApplicabilityRejected, Interpretability, PredictionService -from models.registry import registry +from models.io.prediction import ApplicabilityRejected, Interpretability, PredictionService +from models.io.registry import registry -class StubModel(ScreeningModel): - domain = "cacu" - - def train(self, data=None): - raise NotImplementedError - +class StubModel: def predict(self, data): return {"label": "positivo", "confianza": 0.73} diff --git a/tests/test_registry.py b/tests/io/test_registry.py similarity index 96% rename from tests/test_registry.py rename to tests/io/test_registry.py index dc36e00..bc746b5 100644 --- a/tests/test_registry.py +++ b/tests/io/test_registry.py @@ -1,6 +1,6 @@ import pytest from core.governance.enums import ArtifactKind, Environment -from models.registry import PromotionBlocked, registry +from models.io.registry import PromotionBlocked, registry def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking): @@ -56,7 +56,7 @@ def test_retire_and_lineage(production_ready): def test_invalid_onnx_checkpoint_is_rejected(production_ready): - from models.export import inspect_onnx_metadata + from models.io.export import inspect_onnx_metadata with pytest.raises(ValueError, match="ONNX"): import tempfile diff --git a/tests/io/test_repositories.py b/tests/io/test_repositories.py new file mode 100644 index 0000000..2ba6099 --- /dev/null +++ b/tests/io/test_repositories.py @@ -0,0 +1,28 @@ +"""What this module covers: `resolve_repository`, how `models` finds a domain's Persistance repository by name. + +Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test. +""" +import pytest + +from models.io.repositories import resolve_repository + + +def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db): + """A repository found by name reads what was written through it, in batches and with filters. Fails if + `resolve_repository` looks in another module or stops returning a working repository.""" + from datetime import date + + from core.cacu.models import Paciente + + repository = resolve_repository("cacu", "paciente") + for i in range(7): + repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1))) + + assert [r.pac_id_hospital for r in repository.iter_all(batch_size=3)] == [f"M-{i}" for i in range(7)] + assert list(repository.iter_all(pac_id_hospital="M-3"))[0].pac_sexo == "Femenino" + + +def test_unknown_entity_is_a_clear_error(): + """An unknown name raises `ValueError` naming it. Fails if the `AttributeError` is no longer translated.""" + with pytest.raises(ValueError, match="no nope_repository"): + resolve_repository("tea", "nope") diff --git a/tests/test_training.py b/tests/io/test_training.py similarity index 96% rename from tests/test_training.py rename to tests/io/test_training.py index c4246d2..4a2b2fb 100644 --- a/tests/test_training.py +++ b/tests/io/test_training.py @@ -1,10 +1,10 @@ import pytest from core.governance.enums import ArtifactKind, Environment -from models.registry import registry +from models.io.registry import registry from mlflow import MlflowException -from models.training import ReadOnlyRepository, TrainingRun +from models.io.training import ReadOnlyRepository, TrainingRun def test_prod_run_requires_a_cohort_build(): diff --git a/tests/test_reading_nodes.py b/tests/pipelines/test_reading_nodes.py similarity index 98% rename from tests/test_reading_nodes.py rename to tests/pipelines/test_reading_nodes.py index 13afc9c..0cb515f 100644 --- a/tests/test_reading_nodes.py +++ b/tests/pipelines/test_reading_nodes.py @@ -1,4 +1,4 @@ -"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `known_until`, `timeline`) +"""What this module covers: the reading nodes of `models.pipelines.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 @@ -29,7 +29,7 @@ from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, from sqlalchemy.pool import StaticPool from sqlmodel import Session, create_engine -from models.dags import reading +from models.pipelines import reading TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo) diff --git a/tests/test_data_access.py b/tests/test_data_access.py deleted file mode 100644 index 905043e..0000000 --- a/tests/test_data_access.py +++ /dev/null @@ -1,27 +0,0 @@ -"""`models` reads through Persistance's Repository, the same path WebApi -uses, against a temporary SQLite database.""" -import pytest - - - -def test_dataset_pages_through_every_row(cacu_db): - from datetime import date - - from core.cacu.models import Paciente - from models.cacu import CaCuModel - - model = CaCuModel() - repository = model.repository("paciente") - for i in range(7): - repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1))) - - rows = list(model.dataset("paciente", batch_size=3)) - assert [r["pac_id_hospital"] for r in rows] == [f"M-{i}" for i in range(7)] - assert list(model.dataset("paciente", pac_id_hospital="M-3"))[0]["pac_sexo"] == "Femenino" - - -def test_unknown_entity_is_a_clear_error(): - from models.tea import TeaModel - - with pytest.raises(ValueError, match="no nope_repository"): - TeaModel().repository("nope") diff --git a/tests/test_interfaces.py b/tests/test_interfaces.py deleted file mode 100644 index a5b0fee..0000000 --- a/tests/test_interfaces.py +++ /dev/null @@ -1,19 +0,0 @@ -import pytest - -from models.cacu import CaCuModel -from models.cama import CaMaModel -from models.tea import TeaModel - - -@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel]) -def test_train_not_implemented(cls): - model = cls() - with pytest.raises(NotImplementedError): - model.train() - - -@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel]) -def test_predict_not_implemented(cls): - model = cls() - with pytest.raises(NotImplementedError): - model.predict(data=None) diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..6114f79 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,33 @@ +"""What this module covers: the command line in `models/__main__.py`. + +Fixtures: none; the commands declared so far touch no data. +""" +import subprocess +import sys + +import pytest + +from models.__main__ import main + + +def test_help_lists_the_subcommands(): + """`python -m models --help` runs as a module and lists `cohorts`. Fails if the entry point breaks or the + subcommand stops being registered.""" + result = subprocess.run([sys.executable, "-m", "models", "--help"], capture_output=True, text=True) + assert result.returncode == 0 + assert "cohorts" in result.stdout + + +def test_a_command_is_required(): + """Without a command the parser exits with an error. Fails if `required=True` is dropped, which would make + a bare call look successful.""" + with pytest.raises(SystemExit) as exit_info: + main([]) + assert exit_info.value.code == 2 + + +def test_a_command_without_actions_does_not_report_success(capsys): + """`cohorts` has no actions yet, so it shows its help and returns an error code. Fails if it returns 0, which + would let a script believe it had run.""" + assert main(["cohorts"]) == 2 + assert "cohorts" in capsys.readouterr().out From 34de6e93481e371f5eeaf4672e5911ec99ddb8bf Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 18:32:07 -0600 Subject: [PATCH 16/28] Standalone export of a kit cohort build to Parquet --- README.md | 1 + pyproject.toml | 3 + scripts/export_cohort.py | 177 +++++++++++++++++++++++++++++++++ tests/test_export_cohort.py | 191 ++++++++++++++++++++++++++++++++++++ 4 files changed, 372 insertions(+) create mode 100644 scripts/export_cohort.py create mode 100644 tests/test_export_cohort.py diff --git a/README.md b/README.md index fd52038..8ec6767 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ WebApi. | `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. | | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | +| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, sin guardar nada en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. Necesita `Transformation` para compilar la línea de tiempo. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `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. | diff --git a/pyproject.toml b/pyproject.toml index a063a5f..12680a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,9 @@ dependencies = [ "mlflow>=2.9", # The model DAGs (`models/pipelines`): each function a node, each parameter an edge. "apache-hamilton>=1.90", + # Cohort builds are Parquet files, read and written as frames. + "pandas>=2.0", + "pyarrow>=15", ] [project.optional-dependencies] diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py new file mode 100644 index 0000000..bb26e5a --- /dev/null +++ b/scripts/export_cohort.py @@ -0,0 +1,177 @@ +"""Export a kit cohort build to its Parquet file, once. + + uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N] + +One file per build, `/cohorts///.parquet`, where `` is the folder of the +domain's database and `COHORTS_DIR` replaces `/cohorts`. Long format: one row per member and event, with +the member's index date on every row and the build's lineage in the file's metadata. + +The timeline comes from the dbt model `_linea_de_tiempo`. dbt only compiles it to SQL, which runs here as +a subquery, so nothing is stored in the database and it can be opened read-only (on SQLite, dbt doesn't open it at +all). In a read-only folder, with nothing writing to the file, use +`CACU_DATABASE_URL=sqlite:///file:/path/cacu.db?immutable=1&uri=true`; `mode=ro` isn't enough for a WAL database. +""" + +import argparse +import os +import subprocess +import sys +import tempfile +from collections.abc import Callable, Iterable +from datetime import datetime, timezone +from importlib import import_module +from pathlib import Path + +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +from persistance.aristas.oro import CohortBuild, CohortMember +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from persistance.settings import settings +from sqlalchemy import column, select, text +from sqlalchemy.engine import make_url + +SCHEMA = pa.schema([ + ("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()), + ("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()), + ("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()), + ("fuente_tabla", pa.string()), ("fuente_id", pa.string()), +]) +ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] +DBT_TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"} +DEFAULT_TRANSFORMATION = Path(__file__).resolve().parents[2] / "Transformation" + + +def cohorts_root(database_url: str) -> Path: + """`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder.""" + if configured := os.environ.get("COHORTS_DIR"): + return Path(configured) + url = make_url(database_url) + if url.get_backend_name() != "sqlite" or not url.database: + raise ValueError("this database has no data folder: set COHORTS_DIR") + return Path(url.database.removeprefix("file:")).parent / "cohorts" + + +def cohort_file(build: CohortBuild, root: Path) -> Path: + domain, cohort = build.url.split("/", 1) + return root / domain / cohort / f"{build.armado_id}.parquet" + + +def lineage_of(path: Path) -> dict[str, str]: + """The lineage in the file's metadata, without reading any rows.""" + metadata = pq.read_metadata(path).metadata + return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} + + +def compile_timeline(domain: str, database_url: str, transformation: Path) -> str: + """The SQL of the domain's timeline model for this engine. On SQLite, dbt connects to an empty throwaway file.""" + backend = make_url(database_url).get_backend_name() + model = f"{domain}_linea_de_tiempo" + with tempfile.TemporaryDirectory(prefix="dbt-compile-") as workdir: + work = Path(workdir) + (work / "schemas").mkdir() + env = {**os.environ, "DBT_SCHEMA_DIR": str(work / "schemas")} + if backend == "sqlite": + env[f"{domain.upper()}_DB_PATH"] = str(work / "empty.db") + subprocess.run( + ["uv", "run", "--no-sync", "dbt", "--quiet", "compile", "--profiles-dir", ".", "--profile", domain, + "--target", DBT_TARGETS[backend], "--select", model, "--target-path", str(work / "target"), + "--log-path", str(work / "logs")], + cwd=transformation, env=env, check=True, capture_output=True, text=True) + compiled = next((work / "target" / "compiled").rglob(f"{model}.sql")) + return compiled.read_text().strip().rstrip(";") + + +def read_timeline(repository: TimelineRepository, sql: str) -> list[dict]: + """Every event of the domain, with `sql` as a subquery. The cut-offs are applied in `build_table`.""" + linea = text(sql.replace(":", r"\:")).columns(*(column(name) for name in TIMELINE_COLUMNS)).subquery("linea") + query = select(*(linea.c[name] for name in TIMELINE_COLUMNS)) + return repository.with_query(lambda **_: query).read() + + +def build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str, + parametros: str | None) -> pa.Table: + """The members' events up to `datos_as_of` and loaded by `conocida_hasta`, in the file's order, with the lineage.""" + members = list(members) + index_dates = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"]) + frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(index_dates, on="pac_id") + frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date + frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True) + frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"]) + frame = frame[frame["fecha"] <= build.datos_as_of] + if build.conocida_hasta is not None: + known_until = pd.Timestamp(build.conocida_hasta) + frame = frame[frame["conocida_en"] <= (known_until.tz_localize("UTC") if known_until.tzinfo is None else known_until)] + missing = len(members) - frame["pac_id"].nunique() + if missing: + raise ValueError(f"{missing} members of build {build.armado_id} have no events in the timeline") + frame = frame.sort_values(ROW_ORDER, kind="stable") + lineage = { + "url": build.url, "version": build.version, "armado_id": build.armado_id, "domain": domain, + "parametros": parametros or "{}", "datos_as_of": build.datos_as_of.isoformat(), + "conocida_hasta": build.conocida_hasta.isoformat() if build.conocida_hasta else "", + "n_members": len(members), "producer": "kit", "built_at": datetime.now(timezone.utc).isoformat(), + } + table = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False) + return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}}) + + +def write_once(table: pa.Table, path: Path) -> None: + """The file appears complete or not at all.""" + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle: + partial = Path(handle.name) + try: + pq.write_table(table, partial) + partial.replace(path) + finally: + partial.unlink(missing_ok=True) + + +def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]: + """The build's file: reused if it's already there and belongs to the build, written once if not.""" + path = cohort_file(build, root) + if path.exists(): + lineage = lineage_of(path) + if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros): + raise ValueError(f"{path} doesn't belong to build {build.armado_id}: {lineage}") + return path, "reused" + write_once(make_table(), path) + return path, "exported" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Export a kit cohort build to its Parquet file, once.") + parser.add_argument("--domain", required=True, choices=["cacu", "cama", "tea"]) + parser.add_argument("--cohort", required=True, help="the cohort without its domain, e.g. cohorte_vigilancia") + parser.add_argument("--build", type=int, help="the build's armado_id; the cohort's latest by default") + args = parser.parse_args(argv) + + repositories = import_module(f"persistance.{args.domain}") + cohorts, timeline = repositories.cohorte_repository, repositories.timeline_repository + url = f"{args.domain}/{args.cohort}" + build_id = args.build if args.build is not None else cohorts.latest_build(url) + build = None if build_id is None else cohorts.build(build_id) + if build is None or build.url != url: + print(f"no such build of {url}: {build_id}", file=sys.stderr) + return 1 + + database_url = getattr(settings, f"{args.domain}_database_url") + transformation = Path(os.environ.get("TRANSFORMATION_DIR", DEFAULT_TRANSFORMATION)) + + def make_table() -> pa.Table: + rows = read_timeline(timeline, compile_timeline(args.domain, database_url, transformation)) + return build_table(rows, cohorts.members(build.armado_id), build, domain=args.domain, + parametros=cohorts.get(build.armado_id).parametros) + + try: + path, outcome = ensure(build, cohorts_root(database_url), make_table) + except PermissionError as error: + print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr) + return 1 + print(f"{outcome}: {path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_export_cohort.py b/tests/test_export_cohort.py new file mode 100644 index 0000000..cbe4061 --- /dev/null +++ b/tests/test_export_cohort.py @@ -0,0 +1,191 @@ +"""What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file +goes, what it holds, that it's written once, and that reading the timeline stores nothing in the database. + +Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build +cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and +one of a patient outside the build; `timeline_db`, a SQLite file with a `eventos` table and its repository. +""" + +import importlib.util +import shutil +import sqlite3 +from datetime import date, datetime, timezone +from pathlib import Path + +import pyarrow.parquet as pq +import pytest +from persistance.aristas.oro import CohortBuild, CohortMember +from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository +from sqlmodel import Session, create_engine + +ROOT = Path(__file__).resolve().parents[1] +TRANSFORMATION = ROOT.parent / "Transformation" +MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"), + CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")] + + +@pytest.fixture +def script(): + """The script as a module.""" + spec = importlib.util.spec_from_file_location("export_cohort", ROOT / "scripts" / "export_cohort.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _build(armado_id=1, known_until=None, n_miembros=2): + return CohortBuild(armado_id, "cacu/cohorte_vigilancia", "1.0", "huella", "marco", date(2025, 12, 31), known_until, + n_miembros, datetime(2026, 1, 1, tzinfo=timezone.utc)) + + +@pytest.fixture +def build(): + """A build with a clinical cut-off and a load cut-off.""" + return _build(known_until=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) + + +def _event(pac_id, fecha, conocida_en, fuente_id): + return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "medicion", "tipo": "bethesda", + "codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "citologiacervical", + "fuente_id": fuente_id} + + +@pytest.fixture +def events(): + """Dates as text, as SQLite returns them from a subquery.""" + return [_event(20, "2025-03-01", "2025-03-02 10:00:00", "kept-20"), + _event(10, "2025-02-01", "2025-02-02 10:00:00.5", "kept-10"), + _event(10, "2026-02-01", "2026-01-01 00:00:00", "after-datos-as-of"), + _event(20, "2025-06-01", "2026-01-03 00:00:00", "loaded-after-the-build"), + _event(99, "2025-02-01", "2025-02-02 00:00:00", "not-a-member")] + + +def test_table_keeps_members_within_both_cut_offs_in_the_file_order(script, build, events): + """Pins down: only members' events, up to `datos_as_of` and loaded by `conocida_hasta`, ordered by patient, each + with its index date. Fails if a cut-off or the join with the members is lost, or the rows aren't sorted.""" + table = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}') + + assert table.column("fuente_id").to_pylist() == ["kept-10", "kept-20"] + assert table.column("fecha_indice").to_pylist() == [date(2025, 1, 1), date(2025, 2, 1)] + assert table.schema.names == script.SCHEMA.names + + +def test_table_carries_the_lineage(script, build, events): + """Pins down: the file explains itself: the build's identity and cut-offs are in its metadata. Fails if a key + a reader relies on is dropped or renamed.""" + metadata = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}').schema.metadata + lineage = {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} + + assert lineage["armado_id"] == "1" and lineage["url"] == build.url and lineage["n_members"] == "2" + assert lineage["domain"] == "cacu" and lineage["producer"] == "kit" and lineage["datos_as_of"] == "2025-12-31" + assert lineage["parametros"] == '{"corte": "2025-12-31"}' + + +def test_a_member_without_events_is_refused(script, build, events): + """Pins down: every member has at least one row, so a timeline that lost someone stops the export. Fails if the + file is written with fewer members than the build.""" + with pytest.raises(ValueError, match="1 members"): + script.build_table([e for e in events if e["pac_id"] != 20], MEMBERS, build, domain="cacu", parametros=None) + + +def test_file_is_written_once(script, build, events, tmp_path): + """Pins down: a second run reuses the file without rebuilding it. Fails if `ensure` calls `make_table` again.""" + calls = [] + + def make_table(): + calls.append(1) + return script.build_table(events, MEMBERS, build, domain="cacu", parametros=None) + + path, first = script.ensure(build, tmp_path, make_table) + _, second = script.ensure(build, tmp_path, make_table) + + assert path == tmp_path / "cacu" / "cohorte_vigilancia" / "1.parquet" + assert (first, second, len(calls)) == ("exported", "reused", 1) + assert pq.read_metadata(path).num_rows == 2 + + +def test_file_of_another_build_is_refused(script, build, events, tmp_path): + """Pins down: a file whose lineage names another build isn't reused. Fails if `ensure` trusts the path alone.""" + other = tmp_path / "cacu" / "cohorte_vigilancia" + other.mkdir(parents=True) + pq.write_table(script.build_table(events, MEMBERS, _build(armado_id=7), domain="cacu", parametros=None), other / "1.parquet") + + with pytest.raises(ValueError, match="doesn't belong"): + script.ensure(build, tmp_path, lambda: pytest.fail("must not export")) + + +def test_failed_export_leaves_no_file(script, build, events, tmp_path, monkeypatch): + """Pins down: when the last step of the write fails, neither the file nor the temporary one stays behind, so a + later run can't take a partial file as the build's. Fails if `write_once` stops removing the temporary file.""" + table = script.build_table(events, MEMBERS, build, domain="cacu", parametros=None) + + def fail(*_): + raise OSError("disk full") + + monkeypatch.setattr(Path, "replace", fail) + with pytest.raises(OSError, match="disk full"): + script.write_once(table, tmp_path / "cacu" / "1.parquet") + + assert not list((tmp_path / "cacu").iterdir()) + + +@pytest.mark.parametrize("url", ["sqlite:////data/cacu.db", "sqlite:///file:/data/cacu.db?immutable=1&uri=true"]) +def test_files_live_next_to_the_database(script, monkeypatch, url): + """Pins down: `cohorts/` next to the SQLite file, in both URL forms. Fails if a read-only URL's `file:` prefix + ends up in the path.""" + monkeypatch.delenv("COHORTS_DIR", raising=False) + assert script.cohorts_root(url) == Path("/data/cohorts") + + +def test_cohorts_dir_replaces_the_folder(script, monkeypatch): + """Pins down: `COHORTS_DIR` wins, for read-only data folders and server engines. Fails if it's ignored.""" + monkeypatch.setenv("COHORTS_DIR", "/writable") + assert script.cohorts_root("mysql://host/cacu") == Path("/writable") + + +def test_server_engine_needs_cohorts_dir(script, monkeypatch): + """Pins down: a server database has no data folder, so the script says what to set. Fails if it guesses a path.""" + monkeypatch.delenv("COHORTS_DIR", raising=False) + with pytest.raises(ValueError, match="COHORTS_DIR"): + script.cohorts_root("mysql://host/cacu") + + +@pytest.fixture +def timeline_db(tmp_path): + """A SQLite file with an `eventos` table, and a repository over it.""" + path = tmp_path / "cacu.db" + connection = sqlite3.connect(path) + connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})") + connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a:b', null, 't', '1')") + connection.commit() + connection.close() + engine = create_engine(f"sqlite:///{path}") + return path, TimelineRepository(lambda: Session(engine)) + + +def test_read_timeline_stores_nothing(script, timeline_db): + """Pins down: the timeline runs as a subquery, with the column contract, and adds no object to the database. + Fails if the read creates a view, or if a colon in the SQL is taken for a bind parameter.""" + path, repository = timeline_db + sql = "select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo || ':x' as valor_codigo, valor_numerico, fuente_tabla, fuente_id from eventos" + + rows = script.read_timeline(repository, sql) + + assert rows[0]["pac_id"] == 10 and rows[0]["valor_codigo"] == "a:b:x" + connection = sqlite3.connect(path) + assert connection.execute("select name from sqlite_master").fetchall() == [("eventos",)] + connection.close() + + +@pytest.mark.skipif(not (TRANSFORMATION / ".venv").exists() or shutil.which("uv") is None, + reason="needs the Transformation environment") +def test_compile_never_opens_the_domains_database(script, monkeypatch, tmp_path): + """Pins down: dbt compiles the timeline without touching the domain's SQLite file. Fails if the compile uses the + caller's database path or stops producing SQL over `procedimiento`.""" + database = tmp_path / "cacu.db" + monkeypatch.setenv("CACU_DB_PATH", str(database)) + + sql = script.compile_timeline("cacu", f"sqlite:///{database}", TRANSFORMATION) + + assert '"procedimiento"' in sql and not sql.endswith(";") + assert not database.exists() From 27e29804aa078a5e6cfbb211289badcd1ab2fff9 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 20:39:52 -0600 Subject: [PATCH 17/28] Model interface over frames and a model catalog --- README.md | 2 + models/io/catalog.py | 73 ++++++++++++++++++++ models/io/cohorts.py | 30 +++++++++ scripts/export_cohort.py | 8 +-- tests/io/test_catalog.py | 107 ++++++++++++++++++++++++++++++ tests/sample_models/mean_rate.py | 20 ++++++ tests/sample_models/no_predict.py | 9 +++ 7 files changed, 243 insertions(+), 6 deletions(-) create mode 100644 models/io/catalog.py create mode 100644 models/io/cohorts.py create mode 100644 tests/io/test_catalog.py create mode 100644 tests/sample_models/mean_rate.py create mode 100644 tests/sample_models/no_predict.py diff --git a/README.md b/README.md index 8ec6767..1057f50 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,8 @@ WebApi. | `io/prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | | `io/export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. | | `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. | +| `io/cohorts.py` | El archivo Parquet de un armado de cohorte: sus columnas y `read_cohort`, que lo lee como marco tras revisar su esquema. | +| `io/catalog.py` | `catalog`: qué modelos existen (`/` → su módulo) y `ScreeningModel`, los pasos que define cada modelo (`prepare`, `fit`, `predict`) sobre marcos, sin leer la base. | | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | | `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, sin guardar nada en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. Necesita `Transformation` para compilar la línea de tiempo. | diff --git a/models/io/catalog.py b/models/io/catalog.py new file mode 100644 index 0000000..854d067 --- /dev/null +++ b/models/io/catalog.py @@ -0,0 +1,73 @@ +"""Which models exist: `/` to the module that holds its steps. + +A model is a module in its own folder, `models///model.py`, whose functions are nodes of the +training graph: each parameter's name is the node it takes. Adding a model is its folder plus one `register` line +at the end of this file. +""" + +from dataclasses import dataclass +from importlib import import_module +from types import ModuleType +from typing import Any, Protocol, runtime_checkable + +import pandas as pd + +# What `prepare` returns besides the model's predictors. +PREPARED_COLUMNS = ("pac_id", "fecha_indice", "y") + + +@runtime_checkable +class ScreeningModel(Protocol): + """A model's module. It receives frames and doesn't read the database.""" + + def prepare(self, cohort: pd.DataFrame) -> pd.DataFrame: + """One row per member: `PREPARED_COLUMNS` and the predictors, from the build's rows.""" + + def fit(self, train: pd.DataFrame) -> Any: + """The fitted model, from the training rows of `prepare`'s frame.""" + + def predict(self, fit: Any, test: pd.DataFrame) -> pd.Series: + """The probability of `y` for each row of `test`, in its order.""" + + +class UnknownModel(LookupError): + """No model is registered under that domain and scenario.""" + + +class NotAScreeningModel(TypeError): + """The registered module lacks a step of `ScreeningModel`.""" + + +@dataclass(frozen=True) +class CatalogEntry: + domain: str + scenario: str + module: str + + +class ModelCatalog: + def __init__(self): + self._entries: dict[tuple[str, str], CatalogEntry] = {} + + def register(self, domain: str, scenario: str, module: str | None = None) -> None: + """`module` defaults to the model's folder, `models...model`.""" + if (domain, scenario) in self._entries: + raise ValueError(f"{domain}/{scenario} is already registered") + self._entries[domain, scenario] = CatalogEntry(domain, scenario, module or f"models.{domain}.{scenario}.model") + + def entries(self) -> list[CatalogEntry]: + return sorted(self._entries.values(), key=lambda entry: (entry.domain, entry.scenario)) + + def load(self, domain: str, scenario: str) -> ModuleType: + """The model's module, ready to hand to a graph's driver.""" + try: + entry = self._entries[domain, scenario] + except KeyError: + raise UnknownModel(f"{domain}/{scenario} isn't in the catalog") from None + module = import_module(entry.module) + if not isinstance(module, ScreeningModel): + raise NotAScreeningModel(f"{entry.module} must define `prepare`, `fit` and `predict`") + return module + + +catalog = ModelCatalog() diff --git a/models/io/cohorts.py b/models/io/cohorts.py new file mode 100644 index 0000000..7f40e13 --- /dev/null +++ b/models/io/cohorts.py @@ -0,0 +1,30 @@ +"""A cohort build's Parquet file: its columns, and reading it as a frame. + +Long format: one row per member and event, with the member's index date on every row. A model gets the whole +frame and computes its own outcome and predictors from it; it never reads the database. +""" + +from pathlib import Path + +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq + +SCHEMA = pa.schema([ + ("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()), + ("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()), + ("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()), + ("fuente_tabla", pa.string()), ("fuente_id", pa.string()), +]) + + +class CohortFileError(ValueError): + """The file isn't a cohort build: its columns or types aren't `SCHEMA`'s.""" + + +def read_cohort(path: str | Path) -> pd.DataFrame: + """The build's rows, after checking the file's schema without reading them.""" + schema = pq.read_schema(path) + if not schema.equals(SCHEMA, check_metadata=False): + raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}") + return pd.read_parquet(path) diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py index bb26e5a..2894844 100644 --- a/scripts/export_cohort.py +++ b/scripts/export_cohort.py @@ -31,12 +31,8 @@ from persistance.settings import settings from sqlalchemy import column, select, text from sqlalchemy.engine import make_url -SCHEMA = pa.schema([ - ("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()), - ("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()), - ("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()), - ("fuente_tabla", pa.string()), ("fuente_id", pa.string()), -]) +from models.io.cohorts import SCHEMA + ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] DBT_TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"} DEFAULT_TRANSFORMATION = Path(__file__).resolve().parents[2] / "Transformation" diff --git a/tests/io/test_catalog.py b/tests/io/test_catalog.py new file mode 100644 index 0000000..e82085d --- /dev/null +++ b/tests/io/test_catalog.py @@ -0,0 +1,107 @@ +"""What this module covers: `models.io.catalog`: registering a model, loading it, running its steps over a cohort +file; and the rule that a model's folder doesn't import the database layer. + +Fixtures: `cohort_file`, a small Parquet file of a build with two members, one with an abnormal Bethesda result. +Test models live in `tests/sample_models/`. +""" + +import ast +from datetime import date, datetime, timezone +from pathlib import Path + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +import models +from models.io.catalog import NotAScreeningModel, ModelCatalog, PREPARED_COLUMNS, ScreeningModel, UnknownModel +from models.io.cohorts import SCHEMA, read_cohort + + +def _row(pac_id, fecha_indice, valor, fuente_id): + return {"pac_id": pac_id, "fecha_indice": fecha_indice, "fecha": fecha_indice, + "conocida_en": datetime(2025, 6, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda", + "codigo": "bethesda", "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical", + "fuente_id": fuente_id} + + +@pytest.fixture +def cohort_file(tmp_path): + """Member 10 has two normal results; member 20 has one abnormal result.""" + rows = [_row(10, date(2025, 1, 1), "NORMAL", "a"), _row(10, date(2025, 1, 1), "NORMAL", "b"), + _row(20, date(2025, 2, 1), "LIEBG", "c")] + path = tmp_path / "1.parquet" + pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), path) + return path + + +def test_a_registered_model_runs_over_a_cohort_file(cohort_file): + """Pins down: the whole path of a model's input: a registered model, loaded from the catalog, prepares, fits and + predicts from a frame read from the file, with no database. Fails if `load` returns anything else than the + module, or a step's contract changes.""" + catalog = ModelCatalog() + catalog.register("cacu", "mean_rate", "sample_models.mean_rate") + + model = catalog.load("cacu", "mean_rate") + prepared = model.prepare(read_cohort(cohort_file)) + fitted = model.fit(prepared) + + assert isinstance(model, ScreeningModel) + assert set(PREPARED_COLUMNS) <= set(prepared.columns) + assert prepared.set_index("pac_id")["y"].to_dict() == {10: 0, 20: 1} + assert model.predict(fitted, prepared).tolist() == [0.5, 0.5] + + +def test_the_default_module_is_the_models_folder(): + """Pins down: one line registers a model that follows the layout. Fails if the default path changes, which would + break every registered model.""" + catalog = ModelCatalog() + catalog.register("cacu", "cin2_logistic") + assert catalog.entries()[0].module == "models.cacu.cin2_logistic.model" + + +def test_an_unknown_model_is_refused(): + """Pins down: asking for a model that isn't registered says so. Fails if `load` guesses a module by convention + or lets a bare `KeyError` through.""" + with pytest.raises(UnknownModel, match="cacu/ninguno"): + ModelCatalog().load("cacu", "ninguno") + + +def test_a_scenario_is_registered_once(): + """Pins down: a second registration of a scenario fails, instead of silently replacing the first model. Fails if + the duplicate check goes.""" + catalog = ModelCatalog() + catalog.register("cacu", "mean_rate", "sample_models.mean_rate") + with pytest.raises(ValueError, match="already registered"): + catalog.register("cacu", "mean_rate", "sample_models.no_predict") + + +def test_a_module_without_a_step_is_refused(): + """Pins down: a module lacking a step fails when loaded, not halfway through training. Fails if `load` stops + checking `ScreeningModel`.""" + catalog = ModelCatalog() + catalog.register("cacu", "no_predict", "sample_models.no_predict") + with pytest.raises(NotAScreeningModel, match="no_predict"): + catalog.load("cacu", "no_predict") + + +def test_a_file_with_other_columns_is_refused(tmp_path): + """Pins down: `read_cohort` only accepts a cohort build's columns and types. Fails if it stops checking the + schema, which would let a model fail later on a missing column.""" + path = tmp_path / "other.parquet" + pq.write_table(pa.table({"pac_id": [1]}), path) + with pytest.raises(ValueError, match="cohort build's columns"): + read_cohort(path) + + +def test_model_folders_do_not_import_the_database_layer(): + """Pins down: a model only sees frames: nothing under `models/cacu`, `cama` or `tea` imports `persistance` or + `core`. Fails when a model's folder imports either.""" + package = Path(models.__file__).parent + offenders = [] + for path in (file for domain in ("cacu", "cama", "tea") for file in (package / domain).rglob("*.py")): + for node in ast.walk(ast.parse(path.read_text())): + names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else \ + [node.module or ""] if isinstance(node, ast.ImportFrom) else [] + offenders += [(path.name, name) for name in names if name.split(".")[0] in ("persistance", "core")] + assert not offenders diff --git a/tests/sample_models/mean_rate.py b/tests/sample_models/mean_rate.py new file mode 100644 index 0000000..83032ed --- /dev/null +++ b/tests/sample_models/mean_rate.py @@ -0,0 +1,20 @@ +"""A test model: predicts the training rows' share of `y`. `y` is 1 if a member has any Bethesda result that isn't +`NORMAL`; its only predictor is the member's number of Bethesda results.""" + +import pandas as pd + + +def prepare(cohort: pd.DataFrame) -> pd.DataFrame: + results = cohort[cohort["tipo"] == "bethesda"] + abnormal = results["valor_codigo"].ne("NORMAL").groupby(results["pac_id"]).any() + prepared = results.groupby(["pac_id", "fecha_indice"], as_index=False).size().rename(columns={"size": "n_results"}) + prepared["y"] = prepared["pac_id"].map(abnormal).astype(int) + return prepared + + +def fit(train: pd.DataFrame) -> float: + return float(train["y"].mean()) + + +def predict(fit: float, test: pd.DataFrame) -> pd.Series: + return pd.Series(fit, index=test.index) diff --git a/tests/sample_models/no_predict.py b/tests/sample_models/no_predict.py new file mode 100644 index 0000000..de797b6 --- /dev/null +++ b/tests/sample_models/no_predict.py @@ -0,0 +1,9 @@ +"""A module that isn't a model: it has no `predict`.""" + + +def prepare(cohort): + return cohort + + +def fit(train): + return None From 122f71105a6274decc57bd710696bd6a381064b0 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 20:39:53 -0600 Subject: [PATCH 18/28] Export reads the timeline from dbt's view --- README.md | 2 +- scripts/export_cohort.py | 56 +++++++++++++++---------------------- tests/test_export_cohort.py | 41 +++++++++++---------------- 3 files changed, 40 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 1057f50..e16f40d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ WebApi. | `io/catalog.py` | `catalog`: qué modelos existen (`/` → su módulo) y `ScreeningModel`, los pasos que define cada modelo (`prepare`, `fit`, `predict`) sobre marcos, sin leer la base. | | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | -| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, sin guardar nada en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. Necesita `Transformation` para compilar la línea de tiempo. | +| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select _linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `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. | diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py index 2894844..bb6e7ed 100644 --- a/scripts/export_cohort.py +++ b/scripts/export_cohort.py @@ -6,15 +6,14 @@ One file per build, `/cohorts///.parquet`, wher domain's database and `COHORTS_DIR` replaces `/cohorts`. Long format: one row per member and event, with the member's index date on every row and the build's lineage in the file's metadata. -The timeline comes from the dbt model `_linea_de_tiempo`. dbt only compiles it to SQL, which runs here as -a subquery, so nothing is stored in the database and it can be opened read-only (on SQLite, dbt doesn't open it at -all). In a read-only folder, with nothing writing to the file, use +The timeline comes from dbt's view `_linea_de_tiempo`, which holds no rows and needs creating only when its +dbt model changes (`dbt run --select _linea_de_tiempo`). The script only reads, through the domain's +repository, so it needs neither dbt nor write access. In a read-only folder, with nothing writing to the file, use `CACU_DATABASE_URL=sqlite:///file:/path/cacu.db?immutable=1&uri=true`; `mode=ro` isn't enough for a WAL database. """ import argparse import os -import subprocess import sys import tempfile from collections.abc import Callable, Iterable @@ -28,14 +27,17 @@ import pyarrow.parquet as pq from persistance.aristas.oro import CohortBuild, CohortMember from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository from persistance.settings import settings -from sqlalchemy import column, select, text +from sqlalchemy import column, select, table from sqlalchemy.engine import make_url +from sqlalchemy.exc import DBAPIError from models.io.cohorts import SCHEMA ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] -DBT_TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"} -DEFAULT_TRANSFORMATION = Path(__file__).resolve().parents[2] / "Transformation" + + +class TimelineViewError(RuntimeError): + """dbt's timeline view can't be read.""" def cohorts_root(database_url: str) -> Path: @@ -59,30 +61,15 @@ def lineage_of(path: Path) -> dict[str, str]: return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} -def compile_timeline(domain: str, database_url: str, transformation: Path) -> str: - """The SQL of the domain's timeline model for this engine. On SQLite, dbt connects to an empty throwaway file.""" - backend = make_url(database_url).get_backend_name() - model = f"{domain}_linea_de_tiempo" - with tempfile.TemporaryDirectory(prefix="dbt-compile-") as workdir: - work = Path(workdir) - (work / "schemas").mkdir() - env = {**os.environ, "DBT_SCHEMA_DIR": str(work / "schemas")} - if backend == "sqlite": - env[f"{domain.upper()}_DB_PATH"] = str(work / "empty.db") - subprocess.run( - ["uv", "run", "--no-sync", "dbt", "--quiet", "compile", "--profiles-dir", ".", "--profile", domain, - "--target", DBT_TARGETS[backend], "--select", model, "--target-path", str(work / "target"), - "--log-path", str(work / "logs")], - cwd=transformation, env=env, check=True, capture_output=True, text=True) - compiled = next((work / "target" / "compiled").rglob(f"{model}.sql")) - return compiled.read_text().strip().rstrip(";") - - -def read_timeline(repository: TimelineRepository, sql: str) -> list[dict]: - """Every event of the domain, with `sql` as a subquery. The cut-offs are applied in `build_table`.""" - linea = text(sql.replace(":", r"\:")).columns(*(column(name) for name in TIMELINE_COLUMNS)).subquery("linea") - query = select(*(linea.c[name] for name in TIMELINE_COLUMNS)) - return repository.with_query(lambda **_: query).read() +def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]: + """Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`.""" + name = f"{domain}_linea_de_tiempo" + view = table(name, *(column(c) for c in TIMELINE_COLUMNS)) + try: + return repository.with_query(lambda **_: select(*(view.c[c] for c in TIMELINE_COLUMNS))).read() + except DBAPIError as error: + raise TimelineViewError(f"can't read {name} ({error.orig}): is it created? " + f"Run `dbt run --select {name}` in Transformation") from error def build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str, @@ -153,11 +140,9 @@ def main(argv: list[str] | None = None) -> int: return 1 database_url = getattr(settings, f"{args.domain}_database_url") - transformation = Path(os.environ.get("TRANSFORMATION_DIR", DEFAULT_TRANSFORMATION)) def make_table() -> pa.Table: - rows = read_timeline(timeline, compile_timeline(args.domain, database_url, transformation)) - return build_table(rows, cohorts.members(build.armado_id), build, domain=args.domain, + return build_table(read_timeline(timeline, args.domain), cohorts.members(build.armado_id), build, domain=args.domain, parametros=cohorts.get(build.armado_id).parametros) try: @@ -165,6 +150,9 @@ def main(argv: list[str] | None = None) -> int: except PermissionError as error: print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr) return 1 + except TimelineViewError as error: + print(error, file=sys.stderr) + return 1 print(f"{outcome}: {path}") return 0 diff --git a/tests/test_export_cohort.py b/tests/test_export_cohort.py index cbe4061..064e262 100644 --- a/tests/test_export_cohort.py +++ b/tests/test_export_cohort.py @@ -1,13 +1,12 @@ """What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file -goes, what it holds, that it's written once, and that reading the timeline stores nothing in the database. +goes, what it holds, that it's written once, and that the timeline is read from dbt's view without changing the database. Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and -one of a patient outside the build; `timeline_db`, a SQLite file with a `eventos` table and its repository. +one of a patient outside the build; `timeline_db`, a SQLite file with a `cacu_linea_de_tiempo` view and its repository. """ import importlib.util -import shutil import sqlite3 from datetime import date, datetime, timezone from pathlib import Path @@ -19,7 +18,6 @@ from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository from sqlmodel import Session, create_engine ROOT = Path(__file__).resolve().parents[1] -TRANSFORMATION = ROOT.parent / "Transformation" MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"), CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")] @@ -152,40 +150,35 @@ def test_server_engine_needs_cohorts_dir(script, monkeypatch): @pytest.fixture def timeline_db(tmp_path): - """A SQLite file with an `eventos` table, and a repository over it.""" + """A SQLite file with one event behind a `cacu_linea_de_tiempo` view, and a repository over it.""" path = tmp_path / "cacu.db" connection = sqlite3.connect(path) connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})") - connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a:b', null, 't', '1')") + connection.execute("create view cacu_linea_de_tiempo as select * from eventos") + connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a', null, 't', '1')") connection.commit() connection.close() engine = create_engine(f"sqlite:///{path}") return path, TimelineRepository(lambda: Session(engine)) -def test_read_timeline_stores_nothing(script, timeline_db): - """Pins down: the timeline runs as a subquery, with the column contract, and adds no object to the database. - Fails if the read creates a view, or if a colon in the SQL is taken for a bind parameter.""" +def test_read_timeline_reads_the_view_and_changes_nothing(script, timeline_db): + """Pins down: the rows come from the domain's view, with the column contract, and the read adds no object. Fails + if the script reads another relation, or starts creating objects in the database.""" path, repository = timeline_db - sql = "select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo || ':x' as valor_codigo, valor_numerico, fuente_tabla, fuente_id from eventos" - rows = script.read_timeline(repository, sql) + rows = script.read_timeline(repository, "cacu") - assert rows[0]["pac_id"] == 10 and rows[0]["valor_codigo"] == "a:b:x" + assert [(row["pac_id"], row["valor_codigo"]) for row in rows] == [(10, "a")] connection = sqlite3.connect(path) - assert connection.execute("select name from sqlite_master").fetchall() == [("eventos",)] + assert connection.execute("select name from sqlite_master order by name").fetchall() == [("cacu_linea_de_tiempo",), ("eventos",)] connection.close() -@pytest.mark.skipif(not (TRANSFORMATION / ".venv").exists() or shutil.which("uv") is None, - reason="needs the Transformation environment") -def test_compile_never_opens_the_domains_database(script, monkeypatch, tmp_path): - """Pins down: dbt compiles the timeline without touching the domain's SQLite file. Fails if the compile uses the - caller's database path or stops producing SQL over `procedimiento`.""" - database = tmp_path / "cacu.db" - monkeypatch.setenv("CACU_DB_PATH", str(database)) +def test_missing_view_says_how_to_create_it(script, timeline_db): + """Pins down: without the view the error names the dbt command to run. Fails if the driver's error reaches the + user unexplained, or if the message stops naming the domain's model.""" + _, repository = timeline_db - sql = script.compile_timeline("cacu", f"sqlite:///{database}", TRANSFORMATION) - - assert '"procedimiento"' in sql and not sql.endswith(";") - assert not database.exists() + with pytest.raises(script.TimelineViewError, match="dbt run --select cama_linea_de_tiempo"): + script.read_timeline(repository, "cama") From 1f6e2df051e1e0e23850cbd4eb47607c225efa05 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 20:47:34 -0600 Subject: [PATCH 19/28] Remove the model catalog and its interface --- README.md | 1 - models/io/catalog.py | 73 -------------------- tests/io/test_catalog.py | 107 ------------------------------ tests/io/test_cohorts.py | 64 ++++++++++++++++++ tests/sample_models/mean_rate.py | 20 ------ tests/sample_models/no_predict.py | 9 --- 6 files changed, 64 insertions(+), 210 deletions(-) delete mode 100644 models/io/catalog.py delete mode 100644 tests/io/test_catalog.py create mode 100644 tests/io/test_cohorts.py delete mode 100644 tests/sample_models/mean_rate.py delete mode 100644 tests/sample_models/no_predict.py diff --git a/README.md b/README.md index e16f40d..98f8598 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,6 @@ WebApi. | `io/export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. | | `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. | | `io/cohorts.py` | El archivo Parquet de un armado de cohorte: sus columnas y `read_cohort`, que lo lee como marco tras revisar su esquema. | -| `io/catalog.py` | `catalog`: qué modelos existen (`/` → su módulo) y `ScreeningModel`, los pasos que define cada modelo (`prepare`, `fit`, `predict`) sobre marcos, sin leer la base. | | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | | `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select _linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. | diff --git a/models/io/catalog.py b/models/io/catalog.py deleted file mode 100644 index 854d067..0000000 --- a/models/io/catalog.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Which models exist: `/` to the module that holds its steps. - -A model is a module in its own folder, `models///model.py`, whose functions are nodes of the -training graph: each parameter's name is the node it takes. Adding a model is its folder plus one `register` line -at the end of this file. -""" - -from dataclasses import dataclass -from importlib import import_module -from types import ModuleType -from typing import Any, Protocol, runtime_checkable - -import pandas as pd - -# What `prepare` returns besides the model's predictors. -PREPARED_COLUMNS = ("pac_id", "fecha_indice", "y") - - -@runtime_checkable -class ScreeningModel(Protocol): - """A model's module. It receives frames and doesn't read the database.""" - - def prepare(self, cohort: pd.DataFrame) -> pd.DataFrame: - """One row per member: `PREPARED_COLUMNS` and the predictors, from the build's rows.""" - - def fit(self, train: pd.DataFrame) -> Any: - """The fitted model, from the training rows of `prepare`'s frame.""" - - def predict(self, fit: Any, test: pd.DataFrame) -> pd.Series: - """The probability of `y` for each row of `test`, in its order.""" - - -class UnknownModel(LookupError): - """No model is registered under that domain and scenario.""" - - -class NotAScreeningModel(TypeError): - """The registered module lacks a step of `ScreeningModel`.""" - - -@dataclass(frozen=True) -class CatalogEntry: - domain: str - scenario: str - module: str - - -class ModelCatalog: - def __init__(self): - self._entries: dict[tuple[str, str], CatalogEntry] = {} - - def register(self, domain: str, scenario: str, module: str | None = None) -> None: - """`module` defaults to the model's folder, `models...model`.""" - if (domain, scenario) in self._entries: - raise ValueError(f"{domain}/{scenario} is already registered") - self._entries[domain, scenario] = CatalogEntry(domain, scenario, module or f"models.{domain}.{scenario}.model") - - def entries(self) -> list[CatalogEntry]: - return sorted(self._entries.values(), key=lambda entry: (entry.domain, entry.scenario)) - - def load(self, domain: str, scenario: str) -> ModuleType: - """The model's module, ready to hand to a graph's driver.""" - try: - entry = self._entries[domain, scenario] - except KeyError: - raise UnknownModel(f"{domain}/{scenario} isn't in the catalog") from None - module = import_module(entry.module) - if not isinstance(module, ScreeningModel): - raise NotAScreeningModel(f"{entry.module} must define `prepare`, `fit` and `predict`") - return module - - -catalog = ModelCatalog() diff --git a/tests/io/test_catalog.py b/tests/io/test_catalog.py deleted file mode 100644 index e82085d..0000000 --- a/tests/io/test_catalog.py +++ /dev/null @@ -1,107 +0,0 @@ -"""What this module covers: `models.io.catalog`: registering a model, loading it, running its steps over a cohort -file; and the rule that a model's folder doesn't import the database layer. - -Fixtures: `cohort_file`, a small Parquet file of a build with two members, one with an abnormal Bethesda result. -Test models live in `tests/sample_models/`. -""" - -import ast -from datetime import date, datetime, timezone -from pathlib import Path - -import pyarrow as pa -import pyarrow.parquet as pq -import pytest - -import models -from models.io.catalog import NotAScreeningModel, ModelCatalog, PREPARED_COLUMNS, ScreeningModel, UnknownModel -from models.io.cohorts import SCHEMA, read_cohort - - -def _row(pac_id, fecha_indice, valor, fuente_id): - return {"pac_id": pac_id, "fecha_indice": fecha_indice, "fecha": fecha_indice, - "conocida_en": datetime(2025, 6, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda", - "codigo": "bethesda", "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical", - "fuente_id": fuente_id} - - -@pytest.fixture -def cohort_file(tmp_path): - """Member 10 has two normal results; member 20 has one abnormal result.""" - rows = [_row(10, date(2025, 1, 1), "NORMAL", "a"), _row(10, date(2025, 1, 1), "NORMAL", "b"), - _row(20, date(2025, 2, 1), "LIEBG", "c")] - path = tmp_path / "1.parquet" - pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), path) - return path - - -def test_a_registered_model_runs_over_a_cohort_file(cohort_file): - """Pins down: the whole path of a model's input: a registered model, loaded from the catalog, prepares, fits and - predicts from a frame read from the file, with no database. Fails if `load` returns anything else than the - module, or a step's contract changes.""" - catalog = ModelCatalog() - catalog.register("cacu", "mean_rate", "sample_models.mean_rate") - - model = catalog.load("cacu", "mean_rate") - prepared = model.prepare(read_cohort(cohort_file)) - fitted = model.fit(prepared) - - assert isinstance(model, ScreeningModel) - assert set(PREPARED_COLUMNS) <= set(prepared.columns) - assert prepared.set_index("pac_id")["y"].to_dict() == {10: 0, 20: 1} - assert model.predict(fitted, prepared).tolist() == [0.5, 0.5] - - -def test_the_default_module_is_the_models_folder(): - """Pins down: one line registers a model that follows the layout. Fails if the default path changes, which would - break every registered model.""" - catalog = ModelCatalog() - catalog.register("cacu", "cin2_logistic") - assert catalog.entries()[0].module == "models.cacu.cin2_logistic.model" - - -def test_an_unknown_model_is_refused(): - """Pins down: asking for a model that isn't registered says so. Fails if `load` guesses a module by convention - or lets a bare `KeyError` through.""" - with pytest.raises(UnknownModel, match="cacu/ninguno"): - ModelCatalog().load("cacu", "ninguno") - - -def test_a_scenario_is_registered_once(): - """Pins down: a second registration of a scenario fails, instead of silently replacing the first model. Fails if - the duplicate check goes.""" - catalog = ModelCatalog() - catalog.register("cacu", "mean_rate", "sample_models.mean_rate") - with pytest.raises(ValueError, match="already registered"): - catalog.register("cacu", "mean_rate", "sample_models.no_predict") - - -def test_a_module_without_a_step_is_refused(): - """Pins down: a module lacking a step fails when loaded, not halfway through training. Fails if `load` stops - checking `ScreeningModel`.""" - catalog = ModelCatalog() - catalog.register("cacu", "no_predict", "sample_models.no_predict") - with pytest.raises(NotAScreeningModel, match="no_predict"): - catalog.load("cacu", "no_predict") - - -def test_a_file_with_other_columns_is_refused(tmp_path): - """Pins down: `read_cohort` only accepts a cohort build's columns and types. Fails if it stops checking the - schema, which would let a model fail later on a missing column.""" - path = tmp_path / "other.parquet" - pq.write_table(pa.table({"pac_id": [1]}), path) - with pytest.raises(ValueError, match="cohort build's columns"): - read_cohort(path) - - -def test_model_folders_do_not_import_the_database_layer(): - """Pins down: a model only sees frames: nothing under `models/cacu`, `cama` or `tea` imports `persistance` or - `core`. Fails when a model's folder imports either.""" - package = Path(models.__file__).parent - offenders = [] - for path in (file for domain in ("cacu", "cama", "tea") for file in (package / domain).rglob("*.py")): - for node in ast.walk(ast.parse(path.read_text())): - names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else \ - [node.module or ""] if isinstance(node, ast.ImportFrom) else [] - offenders += [(path.name, name) for name in names if name.split(".")[0] in ("persistance", "core")] - assert not offenders diff --git a/tests/io/test_cohorts.py b/tests/io/test_cohorts.py new file mode 100644 index 0000000..01ecaa3 --- /dev/null +++ b/tests/io/test_cohorts.py @@ -0,0 +1,64 @@ +"""What this module covers: `models.io.cohorts`, reading a cohort build's file; and the rule that a model's folder +doesn't import the database layer, since the file is its only input. + +Fixtures: `cohort_file`, a small Parquet file of a build with two members. +""" + +import ast +from datetime import date, datetime, timezone +from pathlib import Path + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +import models +from models.io.cohorts import SCHEMA, CohortFileError, read_cohort + + +def _row(pac_id, fecha_indice, valor, fuente_id): + return {"pac_id": pac_id, "fecha_indice": fecha_indice, "fecha": fecha_indice, + "conocida_en": datetime(2025, 6, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda", + "codigo": "bethesda", "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical", + "fuente_id": fuente_id} + + +@pytest.fixture +def cohort_file(tmp_path): + """Member 10 has two results; member 20 has one.""" + rows = [_row(10, date(2025, 1, 1), "NORMAL", "a"), _row(10, date(2025, 1, 1), "NORMAL", "b"), + _row(20, date(2025, 2, 1), "LIEBG", "c")] + path = tmp_path / "1.parquet" + pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), path) + return path + + +def test_a_cohort_file_reads_as_a_frame(cohort_file): + """Pins down: a build's file comes back with all its rows and columns. Fails if `read_cohort` drops rows or + columns, or refuses a file with the right schema.""" + frame = read_cohort(cohort_file) + + assert list(frame.columns) == SCHEMA.names + assert frame["pac_id"].tolist() == [10, 10, 20] + + +def test_a_file_with_other_columns_is_refused(tmp_path): + """Pins down: `read_cohort` only accepts a cohort build's columns and types. Fails if it stops checking the + schema, which would let a model fail later on a missing column.""" + path = tmp_path / "other.parquet" + pq.write_table(pa.table({"pac_id": [1]}), path) + with pytest.raises(CohortFileError, match="cohort build's columns"): + read_cohort(path) + + +def test_model_folders_do_not_import_the_database_layer(): + """Pins down: a model only sees frames: nothing under `models/cacu`, `cama` or `tea` imports `persistance` or + `core`. Fails when a model's folder imports either.""" + package = Path(models.__file__).parent + offenders = [] + for path in (file for domain in ("cacu", "cama", "tea") for file in (package / domain).rglob("*.py")): + for node in ast.walk(ast.parse(path.read_text())): + names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else \ + [node.module or ""] if isinstance(node, ast.ImportFrom) else [] + offenders += [(path.name, name) for name in names if name.split(".")[0] in ("persistance", "core")] + assert not offenders diff --git a/tests/sample_models/mean_rate.py b/tests/sample_models/mean_rate.py deleted file mode 100644 index 83032ed..0000000 --- a/tests/sample_models/mean_rate.py +++ /dev/null @@ -1,20 +0,0 @@ -"""A test model: predicts the training rows' share of `y`. `y` is 1 if a member has any Bethesda result that isn't -`NORMAL`; its only predictor is the member's number of Bethesda results.""" - -import pandas as pd - - -def prepare(cohort: pd.DataFrame) -> pd.DataFrame: - results = cohort[cohort["tipo"] == "bethesda"] - abnormal = results["valor_codigo"].ne("NORMAL").groupby(results["pac_id"]).any() - prepared = results.groupby(["pac_id", "fecha_indice"], as_index=False).size().rename(columns={"size": "n_results"}) - prepared["y"] = prepared["pac_id"].map(abnormal).astype(int) - return prepared - - -def fit(train: pd.DataFrame) -> float: - return float(train["y"].mean()) - - -def predict(fit: float, test: pd.DataFrame) -> pd.Series: - return pd.Series(fit, index=test.index) diff --git a/tests/sample_models/no_predict.py b/tests/sample_models/no_predict.py deleted file mode 100644 index de797b6..0000000 --- a/tests/sample_models/no_predict.py +++ /dev/null @@ -1,9 +0,0 @@ -"""A module that isn't a model: it has no `predict`.""" - - -def prepare(cohort): - return cohort - - -def fit(train): - return None From 37fb292a4f431bb74547ffb1cc559c3cba536d5d Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 21:38:37 -0600 Subject: [PATCH 20/28] CaCu's dummy model in its own folder --- README.md | 1 + models/cacu/cin2_logistic/__init__.py | 0 models/cacu/cin2_logistic/model.py | 96 +++++++++++++++++++++++++++ models/cacu/cin2_logistic/model.toml | 7 ++ models/cacu/cin2_logistic/train.py | 12 ++++ models/io/cohorts.py | 6 ++ pyproject.toml | 1 + scripts/export_cohort.py | 10 +-- tests/cacu/test_cin2_logistic.py | 93 ++++++++++++++++++++++++++ 9 files changed, 218 insertions(+), 8 deletions(-) create mode 100644 models/cacu/cin2_logistic/__init__.py create mode 100644 models/cacu/cin2_logistic/model.py create mode 100644 models/cacu/cin2_logistic/model.toml create mode 100644 models/cacu/cin2_logistic/train.py create mode 100644 tests/cacu/test_cin2_logistic.py diff --git a/README.md b/README.md index 98f8598..5d6c0ec 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ WebApi. | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | | `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select _linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. | +| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `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. | diff --git a/models/cacu/cin2_logistic/__init__.py b/models/cacu/cin2_logistic/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/cacu/cin2_logistic/model.py b/models/cacu/cin2_logistic/model.py new file mode 100644 index 0000000..68524c0 --- /dev/null +++ b/models/cacu/cin2_logistic/model.py @@ -0,0 +1,96 @@ +"""CaCu's dummy model: it tests the chain from a cohort build's file to a registered version. + +No clinical meaning. `y` is 1 if any Bethesda result isn't `NORMAL`, and `days` runs from the index date to the first +abnormal result, or to the last result when `y` is 0. `days` is only known after the outcome, so the metrics say +nothing about performance. + +Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver. +""" + +import hashlib +import tomllib +from pathlib import Path + +import mlflow.pyfunc +import pandas as pd +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import brier_score_loss, roc_auc_score + +from models.io.cohorts import cohort_lineage, read_cohort +from models.io.registry import registered_name +from models.io.training import TrainingRun + +SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text()) +NORMAL = "NORMAL" + + +def cohort(cohort_path: str) -> pd.DataFrame: + return read_cohort(cohort_path) + + +def lineage(cohort_path: str) -> dict: + return cohort_lineage(cohort_path) + + +def prepare(cohort: pd.DataFrame) -> pd.DataFrame: + """One row per member with a Bethesda result: `pac_id`, `fecha_indice`, `y`, `days`.""" + results = cohort[cohort["tipo"] == "bethesda"].copy() + results["days"] = (pd.to_datetime(results["fecha"]) - pd.to_datetime(results["fecha_indice"])).dt.days + results["abnormal"] = results["valor_codigo"] != NORMAL + members = results.groupby(["pac_id", "fecha_indice"], as_index=False).agg(y=("abnormal", "any"), last=("days", "max")) + first_abnormal = results[results["abnormal"]].groupby("pac_id")["days"].min() + members["days"] = members["pac_id"].map(first_abnormal).fillna(members["last"]).astype(int) + members["y"] = members["y"].astype(int) + return members[["pac_id", "fecha_indice", "y", "days"]] + + +def split(prepare: pd.DataFrame) -> dict: + """The oldest index dates train and the newest test.""" + ordered = prepare.sort_values(["fecha_indice", "pac_id"], kind="stable") + cut = int(len(ordered) * SETTINGS["train_fraction"]) + return {"train": ordered.iloc[:cut], "test": ordered.iloc[cut:]} + + +def train(split: dict) -> pd.DataFrame: + return split["train"] + + +def test(split: dict) -> pd.DataFrame: + return split["test"] + + +def fit(train: pd.DataFrame) -> LogisticRegression: + return LogisticRegression().fit(train[["days"]], train["y"]) + + +def predict(fit: LogisticRegression, test: pd.DataFrame) -> pd.Series: + """The probability of `y` for each row of `test`.""" + return pd.Series(fit.predict_proba(test[["days"]])[:, 1], index=test.index, name="probabilidad") + + +def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dict: + """Aggregates only: no patient data reaches MLflow.""" + return {"auc": float(roc_auc_score(test["y"], predict)), "brier": float(brier_score_loss(test["y"], predict)), + "n_train": len(train), "n_test": len(test), "positive_rate_test": float(test["y"].mean())} + + +class Cin2Logistic(mlflow.pyfunc.PythonModel): + """The registered artifact: takes a build's long frame and returns each member's probability.""" + + def __init__(self, fitted: LogisticRegression): + self.fitted = fitted + + def predict(self, context, model_input, params=None): + return predict(self.fitted, prepare(model_input)) + + +def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, environment: str) -> str: + """Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content.""" + run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment, + cohorte_armado_id=int(lineage["armado_id"])) + run.log_model(Cin2Logistic(fit)) + version = run.finish(metrics=evaluate, hyperparameters={ + "cohort_file": str(cohort_path), "cohort_sha256": hashlib.sha256(Path(cohort_path).read_bytes()).hexdigest()}) + name = registered_name(SETTINGS["domain"], SETTINGS["scenario"]) + run.client.update_model_version(name, version, description=SETTINGS["description"]) + return version diff --git a/models/cacu/cin2_logistic/model.toml b/models/cacu/cin2_logistic/model.toml new file mode 100644 index 0000000..77a7594 --- /dev/null +++ b/models/cacu/cin2_logistic/model.toml @@ -0,0 +1,7 @@ +domain = "cacu" +scenario = "cin2_logistic" +cohort = "cacu/cohorte_vigilancia" +train_fraction = 0.7 +description = """ +Modelo de prueba de la cadena de entrenamiento, sin significado clínico. Los días se conocen solo después del \ +desenlace, así que sus métricas no dicen nada sobre su desempeño.""" diff --git a/models/cacu/cin2_logistic/train.py b/models/cacu/cin2_logistic/train.py new file mode 100644 index 0000000..054ebe0 --- /dev/null +++ b/models/cacu/cin2_logistic/train.py @@ -0,0 +1,12 @@ +"""The model's Hamilton driver.""" + +from hamilton import driver + +from models.cacu.cin2_logistic import model + + +def train(cohort_path: str, environment: str = "DEV") -> str: + """Trains on a build's file and returns the registered version.""" + dr = driver.Builder().with_modules(model).build() + inputs = {"cohort_path": str(cohort_path), "environment": environment} + return dr.execute(["registered_model"], inputs=inputs)["registered_model"] diff --git a/models/io/cohorts.py b/models/io/cohorts.py index 7f40e13..ae65dbc 100644 --- a/models/io/cohorts.py +++ b/models/io/cohorts.py @@ -22,6 +22,12 @@ class CohortFileError(ValueError): """The file isn't a cohort build: its columns or types aren't `SCHEMA`'s.""" +def cohort_lineage(path: str | Path) -> dict[str, str]: + """The lineage in the file's metadata, without reading any rows.""" + metadata = pq.read_metadata(path).metadata + return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} + + def read_cohort(path: str | Path) -> pd.DataFrame: """The build's rows, after checking the file's schema without reading them.""" schema = pq.read_schema(path) diff --git a/pyproject.toml b/pyproject.toml index 12680a5..fe2228b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,7 @@ dependencies = [ # Cohort builds are Parquet files, read and written as frames. "pandas>=2.0", "pyarrow>=15", + "scikit-learn>=1.4", ] [project.optional-dependencies] diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py index bb6e7ed..320e708 100644 --- a/scripts/export_cohort.py +++ b/scripts/export_cohort.py @@ -31,7 +31,7 @@ from sqlalchemy import column, select, table from sqlalchemy.engine import make_url from sqlalchemy.exc import DBAPIError -from models.io.cohorts import SCHEMA +from models.io.cohorts import SCHEMA, cohort_lineage ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] @@ -55,12 +55,6 @@ def cohort_file(build: CohortBuild, root: Path) -> Path: return root / domain / cohort / f"{build.armado_id}.parquet" -def lineage_of(path: Path) -> dict[str, str]: - """The lineage in the file's metadata, without reading any rows.""" - metadata = pq.read_metadata(path).metadata - return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} - - def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]: """Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`.""" name = f"{domain}_linea_de_tiempo" @@ -115,7 +109,7 @@ def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) - """The build's file: reused if it's already there and belongs to the build, written once if not.""" path = cohort_file(build, root) if path.exists(): - lineage = lineage_of(path) + lineage = cohort_lineage(path) if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros): raise ValueError(f"{path} doesn't belong to build {build.armado_id}: {lineage}") return path, "reused" diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py new file mode 100644 index 0000000..6670515 --- /dev/null +++ b/tests/cacu/test_cin2_logistic.py @@ -0,0 +1,93 @@ +"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal +split, and that training on a build's file registers a version with its lineage. + +Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a +build's Parquet file with its lineage; `mlflow_tracking` (conftest), a SQLite-backed MLflow. +""" + +from datetime import date, datetime, timedelta, timezone + +import mlflow.pyfunc +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from models.cacu.cin2_logistic import model +from models.cacu.cin2_logistic.train import train +from models.io.cohorts import SCHEMA +from models.io.registry import ARMADO_TAG, MODEL_SHA_TAG, registry + + +def _row(pac_id, index, days, valor, tipo="bethesda"): + return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days), + "conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo, + "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical", + "fuente_id": f"{pac_id}-{tipo}-{days}"} + + +@pytest.fixture +def cohort_frame(): + """Odd members become abnormal at day 30 after a normal result; even ones stay normal until day 300. An HPV row + each, which the outcome must ignore.""" + rows = [] + for pac_id in range(1, 21): + index = date(2025, 1, 1) + timedelta(days=pac_id) + rows += [_row(pac_id, index, 0, "NORMAL"), _row(pac_id, index, 5, "POSITIVO", tipo="vph")] + rows.append(_row(pac_id, index, 30, "LIEBG") if pac_id % 2 else _row(pac_id, index, 300, "NORMAL")) + return pd.DataFrame(rows, columns=SCHEMA.names) + + +@pytest.fixture +def cohort_file(cohort_frame, tmp_path): + """The frame as build 7's file.""" + table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False) + path = tmp_path / "7.parquet" + pq.write_table(table.replace_schema_metadata({"armado_id": "7", "url": "cacu/cohorte_vigilancia"}), path) + return path + + +def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame): + """Pins down: `y` is 1 with any abnormal result; `days` reaches the first abnormal result, or the last result when + `y` is 0. Fails if another variable's value counts as abnormal, or either date rule changes.""" + prepared = model.prepare(cohort_frame).set_index("pac_id") + + assert len(prepared) == 20 + assert prepared.loc[1, ["y", "days"]].tolist() == [1, 30] + assert prepared.loc[2, ["y", "days"]].tolist() == [0, 300] + + +def test_first_abnormal_result_sets_days_when_there_are_several(): + """Pins down: with two abnormal results, `days` is the earlier one even if the file's order says otherwise. Fails + if `days` takes the last abnormal result or the first row.""" + index = date(2025, 1, 1) + frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")]) + + assert model.prepare(frame).loc[0, "days"] == 40 + + +def test_split_trains_on_the_oldest_index_dates(cohort_frame): + """Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split + is random or follows another column.""" + parts = model.split(model.prepare(cohort_frame)) + + assert (len(parts["train"]), len(parts["test"])) == (14, 6) + assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min() + + +def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking): + """Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash and the note that + it has no clinical meaning, and an artifact that holds `prepare`, so it takes the long frame. Fails if any is lost, or + if the driver stops reaching `registered_model`.""" + version = train(cohort_file) + + resolved = registry.resolve("cacu", "cin2_logistic", version) + stored = registry.get("cacu", "cin2_logistic", version) + run = registry.client.get_run(stored.run_id).data + assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha + assert "sin significado clínico" in stored.description + assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics + assert len(run.params["cohort_sha256"]) == 64 + + probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame) + assert len(probabilities) == 20 and probabilities.between(0, 1).all() From 0fdab3651c2f447c895881f5cca8130cfdd56cee Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 23:36:46 -0600 Subject: [PATCH 21/28] models train: train a model from the command line --- README.md | 2 +- models/__main__.py | 36 +++++++++++++++++ models/io/cohorts.py | 30 ++++++++++++++ scripts/export_cohort.py | 21 +--------- tests/cacu/test_cin2_logistic.py | 67 +++++++++++++++++++++++++++++--- 5 files changed, 130 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 5d6c0ec..191e869 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ WebApi. | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | | `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select _linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. | -| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. | +| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `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. | diff --git a/models/__main__.py b/models/__main__.py index 979b835..389ea48 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -14,12 +14,48 @@ def _show_help(parser: argparse.ArgumentParser) -> int: return 2 +def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: + """Finds the model's folder from its name and trains it on the build's file.""" + if args.environment == "prod" and args.armado is None: + parser.error("a prod run names its cohort build: --armado (ML-03)") + + from importlib import import_module + + from persistance.settings import settings + + from models.io.cohorts import cohorts_root, find_cohort_file + + package = f"models.{args.domain}.{args.scenario}" + try: + model, trainer = import_module(f"{package}.model"), import_module(f"{package}.train") + except ModuleNotFoundError as error: + if not (error.name or "").startswith(package): + raise + print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr) + return 1 + try: + root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) + path = find_cohort_file(root, model.SETTINGS["cohort"], args.armado) + except (FileNotFoundError, ValueError) as error: + print(f"{error}: export it with scripts/export_cohort.py", file=sys.stderr) + return 1 + print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}") + return 0 + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.") commands = parser.add_subparsers(dest="command", metavar="", required=True) cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files") cohorts.set_defaults(run=lambda args: _show_help(cohorts)) + + train = commands.add_parser("train", help="train a model on a cohort build's file and register a version") + train.add_argument("domain", choices=["cacu", "cama", "tea"]) + train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") + train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default") + train.add_argument("--environment", choices=["dev", "prod"], default="dev") + train.set_defaults(run=lambda args: _train(train, args)) return parser diff --git a/models/io/cohorts.py b/models/io/cohorts.py index ae65dbc..91eae6b 100644 --- a/models/io/cohorts.py +++ b/models/io/cohorts.py @@ -4,11 +4,13 @@ Long format: one row per member and event, with the member's index date on every frame and computes its own outcome and predictors from it; it never reads the database. """ +import os from pathlib import Path import pandas as pd import pyarrow as pa import pyarrow.parquet as pq +from sqlalchemy.engine import make_url SCHEMA = pa.schema([ ("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()), @@ -22,6 +24,34 @@ class CohortFileError(ValueError): """The file isn't a cohort build: its columns or types aren't `SCHEMA`'s.""" +def cohorts_root(database_url: str) -> Path: + """`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder.""" + if configured := os.environ.get("COHORTS_DIR"): + return Path(configured) + url = make_url(database_url) + if url.get_backend_name() != "sqlite" or not url.database: + raise ValueError("this database has no data folder: set COHORTS_DIR") + return Path(url.database.removeprefix("file:")).parent / "cohorts" + + +def cohort_path(root: Path, url: str, armado_id: int) -> Path: + domain, cohort = url.split("/", 1) + return root / domain / cohort / f"{armado_id}.parquet" + + +def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path: + """The file of that build, or of the cohort's latest build that has a file.""" + if armado_id is None: + builds = [int(file.stem) for file in cohort_path(root, url, 0).parent.glob("*.parquet") if file.stem.isdigit()] + if not builds: + raise FileNotFoundError(f"no exported builds of {url} under {root}") + armado_id = max(builds) + path = cohort_path(root, url, armado_id) + if not path.exists(): + raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}") + return path + + def cohort_lineage(path: str | Path) -> dict[str, str]: """The lineage in the file's metadata, without reading any rows.""" metadata = pq.read_metadata(path).metadata diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py index 320e708..5943fe7 100644 --- a/scripts/export_cohort.py +++ b/scripts/export_cohort.py @@ -13,7 +13,6 @@ repository, so it needs neither dbt nor write access. In a read-only folder, wit """ import argparse -import os import sys import tempfile from collections.abc import Callable, Iterable @@ -28,10 +27,9 @@ from persistance.aristas.oro import CohortBuild, CohortMember from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository from persistance.settings import settings from sqlalchemy import column, select, table -from sqlalchemy.engine import make_url from sqlalchemy.exc import DBAPIError -from models.io.cohorts import SCHEMA, cohort_lineage +from models.io.cohorts import SCHEMA, cohort_lineage, cohort_path, cohorts_root ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] @@ -40,21 +38,6 @@ class TimelineViewError(RuntimeError): """dbt's timeline view can't be read.""" -def cohorts_root(database_url: str) -> Path: - """`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder.""" - if configured := os.environ.get("COHORTS_DIR"): - return Path(configured) - url = make_url(database_url) - if url.get_backend_name() != "sqlite" or not url.database: - raise ValueError("this database has no data folder: set COHORTS_DIR") - return Path(url.database.removeprefix("file:")).parent / "cohorts" - - -def cohort_file(build: CohortBuild, root: Path) -> Path: - domain, cohort = build.url.split("/", 1) - return root / domain / cohort / f"{build.armado_id}.parquet" - - def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]: """Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`.""" name = f"{domain}_linea_de_tiempo" @@ -107,7 +90,7 @@ def write_once(table: pa.Table, path: Path) -> None: def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]: """The build's file: reused if it's already there and belongs to the build, written once if not.""" - path = cohort_file(build, root) + path = cohort_path(root, build.url, build.armado_id) if path.exists(): lineage = cohort_lineage(path) if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros): diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py index 6670515..6732241 100644 --- a/tests/cacu/test_cin2_logistic.py +++ b/tests/cacu/test_cin2_logistic.py @@ -1,8 +1,9 @@ """What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal -split, and that training on a build's file registers a version with its lineage. +split, that training on a build's file registers a version with its lineage, and the `models train` command over it. Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a -build's Parquet file with its lineage; `mlflow_tracking` (conftest), a SQLite-backed MLflow. +build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a +SQLite-backed MLflow. """ from datetime import date, datetime, timedelta, timezone @@ -13,6 +14,7 @@ import pyarrow as pa import pyarrow.parquet as pq import pytest +from models.__main__ import main from models.cacu.cin2_logistic import model from models.cacu.cin2_logistic.train import train from models.io.cohorts import SCHEMA @@ -38,13 +40,27 @@ def cohort_frame(): return pd.DataFrame(rows, columns=SCHEMA.names) +def _write(frame, path, armado_id): + table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False) + path.parent.mkdir(parents=True, exist_ok=True) + pq.write_table(table.replace_schema_metadata({"armado_id": str(armado_id), "url": "cacu/cohorte_vigilancia"}), path) + return path + + @pytest.fixture def cohort_file(cohort_frame, tmp_path): """The frame as build 7's file.""" - table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False) - path = tmp_path / "7.parquet" - pq.write_table(table.replace_schema_metadata({"armado_id": "7", "url": "cacu/cohorte_vigilancia"}), path) - return path + return _write(cohort_frame, tmp_path / "7.parquet", 7) + + +@pytest.fixture +def exported(cohort_frame, tmp_path, monkeypatch): + """Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to.""" + folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" + _write(cohort_frame, folder / "7.parquet", 7) + _write(cohort_frame, folder / "12.parquet", 12) + monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) + return folder def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame): @@ -91,3 +107,42 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame) assert len(probabilities) == 20 and probabilities.between(0, 1).all() + + +def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys): + """Pins down: with no `--armado`, the command uses the highest build number, not the last by name, and registers a + DEV version. Fails if builds sort as text (7 after 12), or the default environment changes.""" + assert main(["train", "cacu", "cin2_logistic"]) == 0 + + assert "version 1" in capsys.readouterr().out + stored = registry.get("cacu", "cin2_logistic", "1") + assert stored.tags[ARMADO_TAG] == "12" and stored.tags["environment"] == "DEV" + + +def test_the_command_trains_on_the_build_it_is_given_as_prod(exported, mlflow_tracking): + """Pins down: `--armado` chooses the file and `--environment prod` tags the version PROD. Fails if either option + is ignored.""" + assert main(["train", "cacu", "cin2_logistic", "--armado", "7", "--environment", "prod"]) == 0 + + stored = registry.get("cacu", "cin2_logistic", "1") + assert stored.tags[ARMADO_TAG] == "7" and stored.tags["environment"] == "PROD" + + +def test_prod_without_a_build_is_refused(capsys): + """Pins down: a prod run has to name its build (ML-03), and it's refused before anything loads. Fails if prod falls + back to the latest file.""" + with pytest.raises(SystemExit) as stopped: + main(["train", "cacu", "cin2_logistic", "--environment", "prod"]) + + assert stopped.value.code == 2 and "--armado" in capsys.readouterr().err + + +@pytest.mark.parametrize("arguments, message", [ + (["cacu", "ninguno"], "no such model: cacu/ninguno"), + (["cacu", "cin2_logistic", "--armado", "99"], "export it"), +]) +def test_what_is_missing_is_named(exported, arguments, message, capsys): + """Pins down: an unknown model or a build with no file ends with exit 1 and says which, with no traceback and no + version. Fails if the command lets the import error through, or trains on another file.""" + assert main(["train", *arguments]) == 1 + assert message in capsys.readouterr().err From 9808701c4626be4829d74056bc8d3f80dcef6341 Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 5 Nov 2026 16:12:23 -0600 Subject: [PATCH 22/28] Cohorts built from dbt's rules and exported, an idempotent run command and estimate; io split by responsibility, with stored predictions moved into the registry and the ONNX check into tracking --- README.md | 18 +- models/__main__.py | 228 +++++++++++++- models/cacu/cin2_logistic/estimate.py | 39 +++ models/cacu/cin2_logistic/model.py | 36 ++- models/cacu/cin2_logistic/train.py | 17 +- models/io/cohorts.py | 66 ---- models/io/contract.py | 50 ---- models/io/contracts.py | 98 ++++++ models/io/export.py | 34 --- models/io/lineage.py | 72 +++++ models/io/prediction.py | 132 -------- models/io/registry.py | 171 ++++++++++- models/io/repositories.py | 14 - models/io/storage.py | 171 +++++++++++ models/io/{training.py => tracking.py} | 132 +++----- models/ocr.py | 2 +- models/pipelines/cohort_build.py | 70 +++++ models/pipelines/export_cohort.py | 73 +++++ models/steps/__init__.py | 5 +- models/steps/cohort.py | 52 ++++ models/steps/cohort_file.py | 40 +++ models/testing.py | 2 +- scripts/export_cohort.py | 138 --------- tests/cacu/test_cin2_logistic.py | 157 +++++++++- .../{test_contract.py => test_contracts.py} | 4 +- tests/io/test_lineage.py | 49 +++ tests/io/test_model_versions.py | 13 +- tests/io/test_registry.py | 2 +- ...iction.py => test_registry_predictions.py} | 3 +- tests/io/{test_cohorts.py => test_storage.py} | 5 +- ...tories.py => test_storage_repositories.py} | 4 +- .../io/{test_training.py => test_tracking.py} | 28 +- .../{test_export.py => test_tracking_onnx.py} | 2 +- tests/test_cohort_build.py | 221 ++++++++++++++ tests/test_export_cohort.py | 281 +++++++++++------- 35 files changed, 1710 insertions(+), 719 deletions(-) create mode 100644 models/cacu/cin2_logistic/estimate.py delete mode 100644 models/io/cohorts.py delete mode 100644 models/io/contract.py create mode 100644 models/io/contracts.py delete mode 100644 models/io/export.py create mode 100644 models/io/lineage.py delete mode 100644 models/io/prediction.py delete mode 100644 models/io/repositories.py create mode 100644 models/io/storage.py rename models/io/{training.py => tracking.py} (52%) create mode 100644 models/pipelines/cohort_build.py create mode 100644 models/pipelines/export_cohort.py create mode 100644 models/steps/cohort.py create mode 100644 models/steps/cohort_file.py delete mode 100644 scripts/export_cohort.py rename tests/io/{test_contract.py => test_contracts.py} (95%) create mode 100644 tests/io/test_lineage.py rename tests/io/{test_prediction.py => test_registry_predictions.py} (94%) rename tests/io/{test_cohorts.py => test_storage.py} (93%) rename tests/io/{test_repositories.py => test_storage_repositories.py} (86%) rename tests/io/{test_training.py => test_tracking.py} (73%) rename tests/io/{test_export.py => test_tracking_onnx.py} (97%) create mode 100644 tests/test_cohort_build.py diff --git a/README.md b/README.md index 191e869..510658b 100644 --- a/README.md +++ b/README.md @@ -10,17 +10,17 @@ WebApi. | Módulo | Qué hace | |---|---| | `__main__.py` | La línea de comandos: `python -m models `. Cada área agrega ahí sus subcomandos. | -| `io/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). | -| `io/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); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. | -| `io/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`. | -| `io/prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). | -| `io/export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. | -| `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. | -| `io/cohorts.py` | El archivo Parquet de un armado de cohorte: sus columnas y `read_cohort`, que lo lee como marco tras revisar su esquema. | +| `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). | +| `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`), dbt's manifest (`read_queries`), and Persistance repositories (`resolve_repository`, `ReadOnlyRepository`, ML-04). | +| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the hashes of code, files, tables and models (`code_version`, `model_sha`), and `matches`, the one rule for "already done". | +| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), git commit and `log_model` with its `modelo_sha`. In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. | +| `io/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`. Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). | | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/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. | -| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select _linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. | -| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. | +| `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. | +| `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. | +| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/.parquet` and writes only when its rows change. The timeline comes from dbt's view `_linea_de_tiempo`. | +| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. Estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--armado N] [--version N]` (`estimate.py`); by default it uses the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `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. | diff --git a/models/__main__.py b/models/__main__.py index 389ea48..347cd9c 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -14,41 +14,222 @@ def _show_help(parser: argparse.ArgumentParser) -> int: return 2 -def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: - """Finds the model's folder from its name and trains it on the build's file.""" - if args.environment == "prod" and args.armado is None: - parser.error("a prod run names its cohort build: --armado (ML-03)") - +def _model_module(args: argparse.Namespace, name: str): + """A module of the model's folder; `None` and a message on stderr if there's no such model.""" from importlib import import_module - from persistance.settings import settings - - from models.io.cohorts import cohorts_root, find_cohort_file - package = f"models.{args.domain}.{args.scenario}" try: - model, trainer = import_module(f"{package}.model"), import_module(f"{package}.train") + return import_module(f"{package}.{name}") except ModuleNotFoundError as error: if not (error.name or "").startswith(package): raise print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr) - return 1 + return None + + +def _cohort_file(args: argparse.Namespace, model): + """The build's exported file; `None` and a message on stderr if it's missing.""" + from persistance.settings import settings + + from models.io.storage import cohorts_root, find_cohort_file + try: root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) - path = find_cohort_file(root, model.SETTINGS["cohort"], args.armado) + return find_cohort_file(root, model.SETTINGS["cohort"], args.armado) except (FileNotFoundError, ValueError) as error: - print(f"{error}: export it with scripts/export_cohort.py", file=sys.stderr) + print(f"{error}: export it with `python -m models cohorts export {model.SETTINGS['cohort'].replace('/', ' ')}`", file=sys.stderr) + return None + + +def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: + """Trains the model on the build's file, always as a new version.""" + if args.environment == "prod" and args.armado is None: + parser.error("a prod run names its cohort build: --armado (ML-03)") + if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")): + return 1 + if not (path := _cohort_file(args, model)): return 1 print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}") return 0 +def _estimate_step(args: argparse.Namespace, path) -> int: + estimator = _model_module(args, "estimate") + if not estimator: + return 1 + try: + resolved, written = estimator.estimate(path, args.output, args.version) + except LookupError as error: + print(error, file=sys.stderr) + return 1 + print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {path}, to {args.output}") + return 0 + + +def _estimate(args: argparse.Namespace) -> int: + """Scores the build's file with a registered version and writes the output file.""" + if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)): + return 1 + return _estimate_step(args, path) + + +def _promote_step(args: argparse.Namespace, version: str) -> int: + from mlflow import MlflowException + + from models.io.registry import PRODUCTION_ALIAS, registered_name, registry + + name = registered_name(args.domain, args.scenario) + try: + current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version + except MlflowException: + current = None + if str(current) == str(version): + print(f"already in production: version {version}") + return 0 + registry.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version) + print(f"in production: version {version}") + return 0 + + +def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: + """Runs the steps asked for, in their order. A step whose result already exists is a no-op.""" + if not (args.export or args.train or args.promote or args.estimate): + parser.error("name at least one step: --export, --train, --promote, --estimate") + if args.estimate and not args.output: + parser.error("--estimate needs --output") + if args.train and args.environment == "prod" and args.armado is None: + parser.error("a prod run names its cohort build: --armado (ML-03)") + if args.train and args.version: + parser.error("--version names an existing version: it can't go with --train") + if not (model := _model_module(args, "model")): + return 1 + + if args.export: + cohort = model.SETTINGS["cohort"].split("/", 1)[1] + export = argparse.Namespace(domain=args.domain, cohort=cohort, source="kit", build=args.armado, manifest=None) + if code := _cohort_export(export): + return code + if not (args.train or args.promote or args.estimate): + return 0 + + if not (path := _cohort_file(args, model)): + return 1 + version = args.version + if args.train or (args.promote and not version): + if not (trainer := _model_module(args, "train")): + return 1 + environment = args.environment.upper() + version = trainer.find_trained(path, environment) + if args.train and version: + print(f"already trained: version {version}, from {path}") + elif args.train: + version = trainer.train(path, environment) + print(f"trained: version {version}, from {path}") + elif not version: + print(f"no {environment} version trained on {path}: use --train or --version", file=sys.stderr) + return 1 + if args.promote and (code := _promote_step(args, version)): + return code + return _estimate_step(args, path) if args.estimate else 0 + + +def _cohort_build(args: argparse.Namespace) -> int: + """Runs the cohort's rules and shows its attrition, or only its graph. Stores nothing.""" + from sqlalchemy.exc import DBAPIError + + from importlib import import_module + + from models.io.contracts import CohortDefinitionError + from models.io.storage import read_queries + from models.pipelines.cohort_build import build_cohort, build_driver, mermaid + + url = f"{args.domain}/{args.cohort}" + try: + queries = read_queries(args.manifest, url) + if args.graph: + print(mermaid(build_driver(queries).graph)) + return 0 + built = build_cohort(queries, import_module(f"persistance.{args.domain}").dbt_query_repository) + except (FileNotFoundError, CohortDefinitionError) as error: + print(error, file=sys.stderr) + return 1 + except DBAPIError as error: + print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? " + f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr) + return 1 + print(built.attrition.to_string(index=False)) + print(f"{url}: {len(built.study_population)} members, not stored") + return 0 + + +def _cohort_export(args: argparse.Namespace) -> int: + """Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules.""" + from importlib import import_module + + from persistance.aristas.dbt import DbtRelationError + from persistance.settings import settings + from sqlalchemy.exc import DBAPIError + + from models.io.contracts import CohortDefinitionError + from models.io.storage import read_queries + from models.io.storage import cohorts_root + from models.pipelines.export_cohort import export_dbt_build, export_kit_build + + url = f"{args.domain}/{args.cohort}" + repositories = import_module(f"persistance.{args.domain}") + timeline = repositories.timeline_repository + try: + root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) + if args.source == "dbt": + queries = read_queries(args.manifest, url) + path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain) + else: + path, outcome = export_kit_build(repositories.cohorte_repository, timeline, root, args.domain, url, args.build) + except PermissionError as error: + print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr) + return 1 + except DBAPIError as error: + print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? " + f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr) + return 1 + except (FileNotFoundError, LookupError, ValueError, DbtRelationError) as error: + print(error, file=sys.stderr) + return 1 + print(f"{outcome}: {path}") + return 0 + + +def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: + if args.source == "dbt" and not args.manifest: + parser.error("--source dbt needs --manifest") + if args.source == "dbt" and args.build is not None: + parser.error("--build names a kit build: it can't go with --source dbt") + return _cohort_export(args) + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.") commands = parser.add_subparsers(dest="command", metavar="", required=True) cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files") cohorts.set_defaults(run=lambda args: _show_help(cohorts)) + actions = cohorts.add_subparsers(dest="action", metavar="") + build = actions.add_parser("build", help="run a cohort's rules and show its attrition; stores nothing") + build.add_argument("domain", choices=["cacu", "cama", "tea"]) + build.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia") + build.add_argument("--manifest", required=True, help="the manifest.json `dbt compile` wrote") + build.add_argument("--graph", action="store_true", help="print the chain as a Mermaid diagram without running it") + build.set_defaults(run=_cohort_build) + + export = actions.add_parser("export", help="export a build to its Parquet file, once") + export.add_argument("domain", choices=["cacu", "cama", "tea"]) + export.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia") + export.add_argument("--source", choices=["kit", "dbt"], default="kit", + help="the kit's stored build, or one built now from dbt's rules") + export.add_argument("--build", type=int, help="the kit build's armado_id; the cohort's latest by default") + export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt") + export.set_defaults(run=lambda args: _cohort_export_checked(export, args)) train = commands.add_parser("train", help="train a model on a cohort build's file and register a version") train.add_argument("domain", choices=["cacu", "cama", "tea"]) @@ -56,6 +237,27 @@ def build_parser() -> argparse.ArgumentParser: train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default") train.add_argument("--environment", choices=["dev", "prod"], default="dev") train.set_defaults(run=lambda args: _train(train, args)) + + estimate = commands.add_parser("estimate", help="score a cohort build's file with a registered version") + estimate.add_argument("domain", choices=["cacu", "cama", "tea"]) + estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") + estimate.add_argument("--output", required=True, help="the Parquet file to write") + estimate.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default") + estimate.add_argument("--version", help="the model version; the one in production by default") + estimate.set_defaults(run=_estimate) + + run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops") + run.add_argument("domain", choices=["cacu", "cama", "tea"]) + run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") + run.add_argument("--export", action="store_true", help="export the build to its Parquet file") + run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists") + run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version") + run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production") + run.add_argument("--armado", type=int, help="the build's armado_id; the latest by default") + run.add_argument("--version", help="an existing model version, for --promote and --estimate") + run.add_argument("--environment", choices=["dev", "prod"], default="dev") + run.add_argument("--output", help="the Parquet file --estimate writes") + run.set_defaults(run=lambda args: _run(run, args)) return parser diff --git a/models/cacu/cin2_logistic/estimate.py b/models/cacu/cin2_logistic/estimate.py new file mode 100644 index 0000000..9d17514 --- /dev/null +++ b/models/cacu/cin2_logistic/estimate.py @@ -0,0 +1,39 @@ +"""Scores a build's file with a registered version and writes the probabilities to a Parquet file.""" + +from pathlib import Path + +import mlflow.pyfunc +import pyarrow as pa + +from models.cacu.cin2_logistic.model import SETTINGS +from models.io.contracts import ESTIMATE_COLUMNS +from models.io.lineage import matches +from models.io.registry import ResolvedVersion, registered_name, registry +from models.io.storage import read_cohort, read_metadata, write_once + + +def already_estimated(output_path: Path, version: str, armado_id: str) -> bool: + """Whether the output file already holds this version's scores of this build.""" + return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, "armado_id": armado_id}) + + +def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]: + """Uses the version holding the production alias unless given one, and returns it and whether it wrote the file. + The file's metadata says which version and build its rows come from; `modelo_sha` is copied when the version has + it, and isn't checked.""" + domain, scenario = SETTINGS["domain"], SETTINGS["scenario"] + output_path = Path(output_path) + resolved = registry.resolve(domain, scenario, version) + armado_id = read_metadata(cohort_path)["armado_id"] + if already_estimated(output_path, resolved.version, armado_id): + return resolved, False + risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path)) + if tuple(risks.columns) != ESTIMATE_COLUMNS: + raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}") + provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version, + "mlflow_run_id": resolved.run_id, "armado_id": armado_id} + if resolved.modelo_sha: + provenance["modelo_sha"] = resolved.modelo_sha + table = pa.Table.from_pandas(risks, preserve_index=False) + write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path) + return resolved, True diff --git a/models/cacu/cin2_logistic/model.py b/models/cacu/cin2_logistic/model.py index 68524c0..fe78f01 100644 --- a/models/cacu/cin2_logistic/model.py +++ b/models/cacu/cin2_logistic/model.py @@ -7,7 +7,6 @@ nothing about performance. Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver. """ -import hashlib import tomllib from pathlib import Path @@ -16,9 +15,10 @@ import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.metrics import brier_score_loss, roc_auc_score -from models.io.cohorts import cohort_lineage, read_cohort -from models.io.registry import registered_name -from models.io.training import TrainingRun +from models.io.lineage import file_sha256 +from models.io.registry import registry +from models.io.storage import read_cohort, read_metadata +from models.io.tracking import TrainingRun SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text()) NORMAL = "NORMAL" @@ -29,7 +29,17 @@ def cohort(cohort_path: str) -> pd.DataFrame: def lineage(cohort_path: str) -> dict: - return cohort_lineage(cohort_path) + return read_metadata(cohort_path) + + +def cohort_sha256(cohort_path: str) -> str: + return file_sha256(cohort_path) + + +def code_sha256() -> str: + """The hash of this folder's steps and settings: what says the model itself changed.""" + folder = Path(__file__).parent + return file_sha256(folder / "model.py", folder / "model.toml") def prepare(cohort: pd.DataFrame) -> pd.DataFrame: @@ -75,22 +85,24 @@ def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dic class Cin2Logistic(mlflow.pyfunc.PythonModel): - """The registered artifact: takes a build's long frame and returns each member's probability.""" + """The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`.""" def __init__(self, fitted: LogisticRegression): self.fitted = fitted def predict(self, context, model_input, params=None): - return predict(self.fitted, prepare(model_input)) + members = prepare(model_input) + return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members)) -def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, environment: str) -> str: +def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str, + code_sha256: str, environment: str) -> str: """Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content.""" run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment, cohorte_armado_id=int(lineage["armado_id"])) run.log_model(Cin2Logistic(fit)) - version = run.finish(metrics=evaluate, hyperparameters={ - "cohort_file": str(cohort_path), "cohort_sha256": hashlib.sha256(Path(cohort_path).read_bytes()).hexdigest()}) - name = registered_name(SETTINGS["domain"], SETTINGS["scenario"]) - run.client.update_model_version(name, version, description=SETTINGS["description"]) + run.finish(metrics=evaluate, hyperparameters={ + "cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256}) + version = registry.register_run(run) + registry.set_description(SETTINGS["domain"], SETTINGS["scenario"], version, SETTINGS["description"]) return version diff --git a/models/cacu/cin2_logistic/train.py b/models/cacu/cin2_logistic/train.py index 054ebe0..510de7b 100644 --- a/models/cacu/cin2_logistic/train.py +++ b/models/cacu/cin2_logistic/train.py @@ -1,8 +1,10 @@ -"""The model's Hamilton driver.""" +"""The model's Hamilton driver, and what makes repeating a training a no-op.""" from hamilton import driver from models.cacu.cin2_logistic import model +from models.io.lineage import matches +from models.io.registry import registered_name, registry def train(cohort_path: str, environment: str = "DEV") -> str: @@ -10,3 +12,16 @@ def train(cohort_path: str, environment: str = "DEV") -> str: dr = driver.Builder().with_modules(model).build() inputs = {"cohort_path": str(cohort_path), "environment": environment} return dr.execute(["registered_model"], inputs=inputs)["registered_model"] + + +def find_trained(cohort_path: str, environment: str = "DEV") -> str | None: + """The newest version not retired from the same file, code and environment.""" + name = registered_name(model.SETTINGS["domain"], model.SETTINGS["scenario"]) + expected = {"cohort_sha256": model.cohort_sha256(str(cohort_path)), "code_sha256": model.code_sha256()} + versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True) + for mv in versions: + if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"): + continue + if matches(registry.client.get_run(mv.run_id).data.params, expected): + return str(mv.version) + return None diff --git a/models/io/cohorts.py b/models/io/cohorts.py deleted file mode 100644 index 91eae6b..0000000 --- a/models/io/cohorts.py +++ /dev/null @@ -1,66 +0,0 @@ -"""A cohort build's Parquet file: its columns, and reading it as a frame. - -Long format: one row per member and event, with the member's index date on every row. A model gets the whole -frame and computes its own outcome and predictors from it; it never reads the database. -""" - -import os -from pathlib import Path - -import pandas as pd -import pyarrow as pa -import pyarrow.parquet as pq -from sqlalchemy.engine import make_url - -SCHEMA = pa.schema([ - ("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()), - ("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()), - ("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()), - ("fuente_tabla", pa.string()), ("fuente_id", pa.string()), -]) - - -class CohortFileError(ValueError): - """The file isn't a cohort build: its columns or types aren't `SCHEMA`'s.""" - - -def cohorts_root(database_url: str) -> Path: - """`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder.""" - if configured := os.environ.get("COHORTS_DIR"): - return Path(configured) - url = make_url(database_url) - if url.get_backend_name() != "sqlite" or not url.database: - raise ValueError("this database has no data folder: set COHORTS_DIR") - return Path(url.database.removeprefix("file:")).parent / "cohorts" - - -def cohort_path(root: Path, url: str, armado_id: int) -> Path: - domain, cohort = url.split("/", 1) - return root / domain / cohort / f"{armado_id}.parquet" - - -def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path: - """The file of that build, or of the cohort's latest build that has a file.""" - if armado_id is None: - builds = [int(file.stem) for file in cohort_path(root, url, 0).parent.glob("*.parquet") if file.stem.isdigit()] - if not builds: - raise FileNotFoundError(f"no exported builds of {url} under {root}") - armado_id = max(builds) - path = cohort_path(root, url, armado_id) - if not path.exists(): - raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}") - return path - - -def cohort_lineage(path: str | Path) -> dict[str, str]: - """The lineage in the file's metadata, without reading any rows.""" - metadata = pq.read_metadata(path).metadata - return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} - - -def read_cohort(path: str | Path) -> pd.DataFrame: - """The build's rows, after checking the file's schema without reading them.""" - schema = pq.read_schema(path) - if not schema.equals(SCHEMA, check_metadata=False): - raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}") - return pd.read_parquet(path) diff --git a/models/io/contract.py b/models/io/contract.py deleted file mode 100644 index ed4c780..0000000 --- a/models/io/contract.py +++ /dev/null @@ -1,50 +0,0 @@ -"""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. -""" - -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]: ... diff --git a/models/io/contracts.py b/models/io/contracts.py new file mode 100644 index 0000000..6be006c --- /dev/null +++ b/models/io/contracts.py @@ -0,0 +1,98 @@ +"""The shapes of the data the pipelines read and write. Nothing here reads or writes. + +- A cohort build's Parquet file (`COHORT_SCHEMA`): long, one row per member and event, with the member's index date on + every row. +- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`). +- An estimate's output (`ESTIMATE_COLUMNS`): one row per member. +- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build, + `(columns, rows)` with `columns = ["pac_id", "fecha_indice", ]`. `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. +""" + +from dataclasses import asdict, dataclass +from datetime import date +from typing import NamedTuple, Protocol, runtime_checkable + +import pandas as pd +import pyarrow as pa + +COHORT_SCHEMA = pa.schema([ + ("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()), + ("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()), + ("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()), + ("fuente_tabla", pa.string()), ("fuente_id", pa.string()), +]) + +ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad") + +POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion" + + +class CohortFileError(ValueError): + """The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s.""" + + +class CohortDefinitionError(ValueError): + """The cohort's queries or their results don't follow the structure a build chains.""" + + +@dataclass(frozen=True) +class ExclusionRule: + name: str + description: str + order: int + sql: str + + +@dataclass(frozen=True) +class CohortQueries: + url: str + all_patients: str + index_date: str + rules: tuple[ExclusionRule, ...] + cutoff: date + parameters: dict + + +@dataclass(frozen=True) +class BuiltCohort: + """The study population (`pac_id`, `fecha_indice` and the index event) and the attrition, one row per step.""" + + study_population: pd.DataFrame + attrition: pd.DataFrame + + +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]: ... diff --git a/models/io/export.py b/models/io/export.py deleted file mode 100644 index 9d9ecc7..0000000 --- a/models/io/export.py +++ /dev/null @@ -1,34 +0,0 @@ -"""ONNX checkpoint inspection (ML-01b, MLD-03). - -Writing/storing a checkpoint is `models.io.training.TrainingRun.log_artifact`, -which hands it to MLflow directly — nothing here manages storage paths. -`onnx` is an optional dependency (`models[export]`); without it -`inspect_onnx_metadata` returns `{"available": False}`. -""" -from pathlib import Path -from typing import Any - - -def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]: - """IR version, opsets, producer and graph inputs/outputs of a checkpoint. - `{"available": False}` when the optional `onnx` package isn't installed; - `ValueError` when it is and the file isn't a valid ONNX model.""" - try: - import onnx - except ImportError: - return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"} - - try: - model = onnx.load(str(path)) - onnx.checker.check_model(model) - except Exception as exc: - raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc - return { - "available": True, - "ir_version": model.ir_version, - "producer_name": model.producer_name, - "producer_version": model.producer_version, - "opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import], - "graph_inputs": [i.name for i in model.graph.input], - "graph_outputs": [o.name for o in model.graph.output], - } diff --git a/models/io/lineage.py b/models/io/lineage.py new file mode 100644 index 0000000..2890fdb --- /dev/null +++ b/models/io/lineage.py @@ -0,0 +1,72 @@ +"""What each output came from, in one vocabulary for files, runs and versions: the names models are registered under, +the keys lineage is recorded with, the hashes that identify code, data and models, and the rule that an output already +exists when its recorded lineage matches what's expected. +""" + +import hashlib +import os +import subprocess +from pathlib import Path + +import pyarrow as pa + +DOMAINS = ("cacu", "cama", "tea") +ARMADO_TAG = "kit.armado_id" +MODEL_SHA_TAG = "modelo_sha" +GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets +GIT_DIRTY_TAG = "models.git.dirty" +GIT_COMMIT_ENV = "MODELS_GIT_COMMIT" + + +def registered_name(domain: str, scenario: str) -> str: + return f"{domain}-{scenario}" + + +def code_version() -> dict[str, str]: + """The git commit of this package's repository and whether tracked files have uncommitted changes. + Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither, + nothing is recorded.""" + root = Path(__file__).resolve().parent + try: + commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, + check=True).stdout.strip() + changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"], + capture_output=True, text=True, check=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + commit = os.environ.get(GIT_COMMIT_ENV) + return {GIT_COMMIT_TAG: commit} if commit else {} + return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()} + + +def model_sha(model_dir: str | Path) -> str: + """sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left + out because it carries ids and dates, so the same model saved twice has the same sha.""" + return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest() + + +def file_sha256(*paths: str | Path) -> str: + """The hash of these files' bytes, in this order.""" + digest = hashlib.sha256() + for path in paths: + digest.update(Path(path).read_bytes()) + return digest.hexdigest() + + +def table_sha256(table: pa.Table) -> str: + """The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same.""" + sink = pa.BufferOutputStream() + table = table.replace_schema_metadata(None) + with pa.ipc.new_stream(sink, table.schema) as stream: + stream.write_table(table) + return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest() + + +def matches(recorded: dict, expected: dict) -> bool: + """Whether an output's recorded lineage has every expected value: then it is already done.""" + return all(str(recorded.get(key)) == str(value) for key, value in expected.items()) + + +def require_match(recorded: dict, expected: dict, what: str) -> None: + """Refuses an output whose recorded lineage disagrees with what's expected of it.""" + if not matches(recorded, expected): + raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}") diff --git a/models/io/prediction.py b/models/io/prediction.py deleted file mode 100644 index 588fcd3..0000000 --- a/models/io/prediction.py +++ /dev/null @@ -1,132 +0,0 @@ -"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that -produced it. Callers go through `PredictionService` rather than calling -`model.predict(...)` directly. -""" -import hashlib -import json -from collections.abc import Callable -from dataclasses import dataclass -from typing import Any, Protocol - -from core.governance.models import ModelPrediction -from mlflow import MlflowException -from persistance.governance import model_prediction_repository - -from models.io.registry import PRODUCTION_ALIAS, registered_name, registry - - -class Predictor(Protocol): - """What the service needs from a model.""" - - def predict(self, data: Any) -> Any: ... - - -@dataclass -class Interpretability: - """MLD-03: the minimum a prediction reports for clinical interpretation. - Each model fills the ones its method has (odds ratio for a logistic - regression, hazard ratio for a survival model).""" - - odds_ratio: float | None = None - hazard_ratio: float | None = None - probabilidad_acumulada: float | None = None - - def to_json(self) -> str: - return json.dumps( - { - "odds_ratio": self.odds_ratio, - "hazard_ratio": self.hazard_ratio, - "probabilidad_acumulada": self.probabilidad_acumulada, - } - ) - - -class ApplicabilityRejected(Exception): - """Raised when the EL-04b applicability gate rejects a row. Callers - should report it as a client error (4xx), not a server error.""" - - -class PredictionService: - """Runs a model and records its predictions against the - MLflow version holding the `produccion` alias for `(domain, scenario)`. - - If `aplicable` is given, each row (a dict of fields) is checked with it - (EL-04b). Inapplicable rows are still scored but stored with - `applicability_passed=False`, unless `reject_inapplicable` is set. - """ - - def __init__( - self, - model: Predictor, - *, - domain: str, - scenario: str, - aplicable: Callable[[dict], bool] | None = None, - reject_inapplicable: bool = False, - ): - self.model = model - self.domain = domain - self.scenario = scenario - self.aplicable = aplicable - self.reject_inapplicable = reject_inapplicable - - def active_model_version(self): - """The MLflow model version currently holding the `produccion` - alias for this (domain, scenario), or `None`.""" - name = registered_name(self.domain, self.scenario) - try: - return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS) - except MlflowException: - return None - - def predict_and_record( - self, - data: Any, - *, - pac_id_hospital: str, - episodio_id: int | None = None, - interpretability: Interpretability | None = None, - ) -> ModelPrediction: - """Scores `data` and stores the result (MLD-5) tagged with the active - MLflow model version (MLD-4). `NotImplementedError` from the model is - propagated unchanged. - """ - applicability_passed = True - if self.aplicable is not None: - if not isinstance(data, dict): - raise TypeError("the applicability check needs the input as a dict of fields") - applicability_passed = self.aplicable(data) - if not applicability_passed and self.reject_inapplicable: - raise ApplicabilityRejected( - f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)" - ) - - # Predict first, so an unimplemented model raises NotImplementedError - # even when no version is in production. - output = self.model.predict(data) - - model_version = self.active_model_version() - if model_version is None: - raise RuntimeError( - f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; " - "promueva una con models.io.registry.registry.promote antes de predecir" - ) - - input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest() - prediction = model_prediction_repository.create( - ModelPrediction( - mlflow_run_id=model_version.run_id, - modelo_nombre=model_version.name, - modelo_version=str(model_version.version), - domain=self.domain, - pac_id_hospital=pac_id_hospital, - episodio_id=episodio_id, - input_hash=input_hash, - output=json.dumps(output, default=str), - prediccion=str(output) if not isinstance(output, (dict, list)) else None, - confianza=output.get("confianza") if isinstance(output, dict) else None, - interpretability=interpretability.to_json() if interpretability else None, - applicability_passed=applicability_passed, - ) - ) - return prediction diff --git a/models/io/registry.py b/models/io/registry.py index 874c548..6b95a01 100644 --- a/models/io/registry.py +++ b/models/io/registry.py @@ -1,7 +1,9 @@ """Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02, ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know about on its own: the promotion checks tied to the cohort a version was -trained on and to the validation-report convention. +trained on and to the validation-report convention, and `PredictionService`, +which stores each single prediction with the version in production (MLD-4/5, +EL-04b). Training, versioning, artifact storage and stage live in MLflow itself (`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is @@ -11,26 +13,28 @@ Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's database). A version points to its build with the `kit.armado_id` tag, and the kit's risk batches point back by `mlflow_run_id`; neither copies rows. """ +import hashlib +import json import re import tempfile +from collections.abc import Callable from dataclasses import asdict, dataclass from datetime import datetime, timezone from importlib import import_module from pathlib import Path -from typing import Any +from typing import Any, Protocol from core.governance.enums import ArtifactKind, Environment +from core.governance.models import ModelPrediction from mlflow import MlflowClient, MlflowException from persistance.governance import model_prediction_repository from sqlmodel import select -from models.io.export import inspect_onnx_metadata +from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, registered_name +from models.io.tracking import MODEL_PATH, TrainingRun, inspect_onnx_metadata, log_artifact_file -DOMAINS = ("cacu", "cama", "tea") REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri") PRODUCTION_ALIAS = "produccion" -ARMADO_TAG = "kit.armado_id" -MODEL_SHA_TAG = "modelo_sha" @dataclass(frozen=True) @@ -48,10 +52,6 @@ class PromotionBlocked(Exception): super().__init__(f"la versión no cumple: {failed}") -def registered_name(domain: str, scenario: str) -> str: - return f"{domain}-{scenario}" - - @dataclass(frozen=True) class ResolvedVersion: """The version a caller will use, with what it needs to load it and to say where risks came from. @@ -141,12 +141,34 @@ class ModelRegistry: hyperparameters: dict[str, Any] | None = None, **reports: str | None, ) -> str: - """For training code that runs elsewhere and reports over the API. - In-process training uses `models.io.training.TrainingRun` directly.""" - from models.io.training import TrainingRun - + """For training code that runs elsewhere and reports over the API: a run with these metrics, registered. + In-process training opens its own `TrainingRun` and calls `register_run`.""" run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id) - return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports) + return self.register_run(run.finish(metrics=metrics, hyperparameters=hyperparameters), **reports) + + def register_run(self, run: TrainingRun, **reports: str | None) -> str: + """Registers a run as a new version of `-`, tagged with the promotion inputs (environment, + cohort link, `modelo_sha`, report URIs), and returns the version.""" + unknown = set(reports) - set(REPORT_TAGS) + if unknown: + raise ValueError(f"campos desconocidos: {sorted(unknown)}") + name = registered_name(run.domain, run.scenario) + try: + self.client.create_registered_model(name) + except MlflowException as exc: + if exc.error_code != "RESOURCE_ALREADY_EXISTS": + raise + version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value} + if run.cohorte_armado_id is not None: + version_tags[ARMADO_TAG] = str(run.cohorte_armado_id) + if run.modelo_sha is not None: + version_tags[MODEL_SHA_TAG] = run.modelo_sha + version_tags.update({key: uri for key, uri in reports.items() if uri}) + source = f"runs:/{run.run_id}/{MODEL_PATH}" if run.modelo_sha is not None else f"runs:/{run.run_id}" + return str(self.client.create_model_version(name, source=source, run_id=run.run_id, tags=version_tags).version) + + def set_description(self, domain: str, scenario: str, version: str, description: str) -> None: + self.client.update_model_version(registered_name(domain, scenario), version, description=description) def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None: """MLD-01/01b/03 documents are usually written after training.""" @@ -169,7 +191,7 @@ class ModelRegistry: path.write_bytes(data) if kind_value == ArtifactKind.ONNX_CHECKPOINT.value: inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint - self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value) + log_artifact_file(self.client, mv.run_id, kind_value, path) def _describe(self, mv) -> dict[str, Any]: run = self.client.get_run(mv.run_id) @@ -280,3 +302,120 @@ def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict] "n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(), "armado_en": armado.armado_en.isoformat()}, [{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos]) + + +class Predictor(Protocol): + """What the service needs from a model.""" + + def predict(self, data: Any) -> Any: ... + + +@dataclass +class Interpretability: + """MLD-03: the minimum a prediction reports for clinical interpretation. + Each model fills the ones its method has (odds ratio for a logistic + regression, hazard ratio for a survival model).""" + + odds_ratio: float | None = None + hazard_ratio: float | None = None + probabilidad_acumulada: float | None = None + + def to_json(self) -> str: + return json.dumps( + { + "odds_ratio": self.odds_ratio, + "hazard_ratio": self.hazard_ratio, + "probabilidad_acumulada": self.probabilidad_acumulada, + } + ) + + +class ApplicabilityRejected(Exception): + """Raised when the EL-04b applicability gate rejects a row. Callers + should report it as a client error (4xx), not a server error.""" + + +class PredictionService: + """Runs a model and records its predictions against the + MLflow version holding the `produccion` alias for `(domain, scenario)`. + + If `aplicable` is given, each row (a dict of fields) is checked with it + (EL-04b). Inapplicable rows are still scored but stored with + `applicability_passed=False`, unless `reject_inapplicable` is set. + """ + + def __init__( + self, + model: Predictor, + *, + domain: str, + scenario: str, + aplicable: Callable[[dict], bool] | None = None, + reject_inapplicable: bool = False, + ): + self.model = model + self.domain = domain + self.scenario = scenario + self.aplicable = aplicable + self.reject_inapplicable = reject_inapplicable + + def active_model_version(self): + """The MLflow model version currently holding the `produccion` + alias for this (domain, scenario), or `None`.""" + name = registered_name(self.domain, self.scenario) + try: + return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS) + except MlflowException: + return None + + def predict_and_record( + self, + data: Any, + *, + pac_id_hospital: str, + episodio_id: int | None = None, + interpretability: Interpretability | None = None, + ) -> ModelPrediction: + """Scores `data` and stores the result (MLD-5) tagged with the active + MLflow model version (MLD-4). `NotImplementedError` from the model is + propagated unchanged. + """ + applicability_passed = True + if self.aplicable is not None: + if not isinstance(data, dict): + raise TypeError("the applicability check needs the input as a dict of fields") + applicability_passed = self.aplicable(data) + if not applicability_passed and self.reject_inapplicable: + raise ApplicabilityRejected( + f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)" + ) + + # Predict first, so an unimplemented model raises NotImplementedError + # even when no version is in production. + output = self.model.predict(data) + + model_version = self.active_model_version() + if model_version is None: + raise RuntimeError( + f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; " + "promueva una con registry.promote antes de predecir" + ) + + input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest() + prediction = model_prediction_repository.create( + ModelPrediction( + mlflow_run_id=model_version.run_id, + modelo_nombre=model_version.name, + modelo_version=str(model_version.version), + domain=self.domain, + pac_id_hospital=pac_id_hospital, + episodio_id=episodio_id, + input_hash=input_hash, + output=json.dumps(output, default=str), + prediccion=str(output) if not isinstance(output, (dict, list)) else None, + confianza=output.get("confianza") if isinstance(output, dict) else None, + interpretability=interpretability.to_json() if interpretability else None, + applicability_passed=applicability_passed, + ) + ) + return prediction diff --git a/models/io/repositories.py b/models/io/repositories.py deleted file mode 100644 index fd7e0fb..0000000 --- a/models/io/repositories.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Finds a domain's Persistance repository by name, the same objects WebApi writes with.""" -import importlib - -from persistance.repository import Repository - - -def resolve_repository(domain: str, entity: str) -> Repository: - """`entity` is the repository's name in `persistance.` without - the suffix, e.g. `"paciente"`, `"citologia_cervical"`.""" - module = importlib.import_module(f"persistance.{domain}") - try: - return getattr(module, f"{entity}_repository") - except AttributeError as exc: - raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc diff --git a/models/io/storage.py b/models/io/storage.py new file mode 100644 index 0000000..8b52eb2 --- /dev/null +++ b/models/io/storage.py @@ -0,0 +1,171 @@ +"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's +manifest, and a domain's Persistance repositories. + +The kit's builds are `///.parquet`. The builds of dbt's rules go in a `dbt/` folder +beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a +repository is used, so a model folder reading its cohort file never loads the database layer. +""" + +import importlib +import json +import os +import tempfile +from datetime import date +from pathlib import Path + +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +from sqlalchemy.engine import make_url + +from models.io.contracts import (COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError, + CohortQueries, ExclusionRule) + + +def cohorts_root(database_url: str) -> Path: + """`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder.""" + if configured := os.environ.get("COHORTS_DIR"): + return Path(configured) + url = make_url(database_url) + if url.get_backend_name() != "sqlite" or not url.database: + raise ValueError("this database has no data folder: set COHORTS_DIR") + return Path(url.database).parent / "cohorts" + + +def cohort_path(root: Path, url: str, armado_id: int) -> Path: + domain, cohort = url.split("/", 1) + return root / domain / cohort / f"{armado_id}.parquet" + + +def dbt_build_path(root: Path, url: str, number: int) -> Path: + return cohort_path(root, url, number).parent / "dbt" / f"{number}.parquet" + + +def _numbers(folder: Path) -> list[int]: + return sorted(int(file.stem) for file in folder.glob("*.parquet") if file.stem.isdigit()) + + +def latest_dbt_build(root: Path, url: str) -> tuple[int, Path] | None: + """The highest-numbered build of dbt's rules, or `None` if there's none.""" + numbers = _numbers(dbt_build_path(root, url, 0).parent) + return (numbers[-1], dbt_build_path(root, url, numbers[-1])) if numbers else None + + +def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path: + """The file of that build, or of the cohort's latest build that has a file.""" + if armado_id is None: + builds = _numbers(cohort_path(root, url, 0).parent) + if not builds: + raise FileNotFoundError(f"no exported builds of {url} under {root}") + armado_id = max(builds) + path = cohort_path(root, url, armado_id) + if not path.exists(): + raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}") + return path + + +def read_cohort(path: str | Path) -> pd.DataFrame: + """The build's rows, after checking the file's schema without reading them.""" + schema = pq.read_schema(path) + if not schema.equals(COHORT_SCHEMA, check_metadata=False): + raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}") + return pd.read_parquet(path) + + +def write_once(table: pa.Table, path: Path) -> None: + """The file appears complete or not at all: written beside it, then renamed.""" + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle: + partial = Path(handle.name) + try: + pq.write_table(table, partial) + partial.replace(path) + finally: + partial.unlink(missing_ok=True) + + +def read_metadata(path: str | Path) -> dict[str, str]: + """A Parquet file's own metadata, without reading any rows.""" + metadata = pq.read_metadata(path).metadata or {} + return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} + + +def _one(nodes: list[dict], kind: str, url: str) -> dict: + found = [node for node in nodes if node["config"]["meta"]["kind"] == kind] + if len(found) != 1: + raise CohortDefinitionError(f"{url} needs exactly one `{kind}` query, not {len(found)}") + return found[0] + + +def _compiled(node: dict) -> str: + if not node.get("compiled_code"): + raise CohortDefinitionError(f"{node['name']} has no compiled SQL in the manifest: run `dbt compile`") + return node["compiled_code"] + + +def read_queries(manifest: str | Path, url: str) -> CohortQueries: + """The cohort's compiled queries, with its exclusions in their `order`. + + An exclusion may read only the index query and the data, never another of the cohort's queries: that keeps every + rule's excluded members, and the study population, independent of the order. + """ + nodes = json.loads(Path(manifest).read_text())["nodes"].values() + nodes = [node for node in nodes if node.get("config", {}).get("meta", {}).get("cohort") == url] + if not nodes: + raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}") + population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url) + exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION] + if not exclusions: + raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries") + orders = [node["config"]["meta"]["order"] for node in exclusions] + if len(set(orders)) != len(orders): + raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}") + steps = {node["unique_id"] for node in nodes} - {index["unique_id"]} + for node in exclusions: + if read := steps & set(node["depends_on"]["nodes"]): + raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}") + meta = population["config"]["meta"] + if "cutoff" not in meta: + raise CohortDefinitionError(f"the population query of {url} has no `cutoff` in its meta") + rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node)) + for node in exclusions) + return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)), + date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}"))) + + +def resolve_repository(domain: str, entity: str): + """`entity` is the repository's name in `persistance.` without + the suffix, e.g. `"paciente"`, `"citologia_cervical"`.""" + module = importlib.import_module(f"persistance.{domain}") + try: + return getattr(module, f"{entity}_repository") + except AttributeError as exc: + raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc + + +class ReadOnlyRepository: + """ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`. + Write methods raise `PermissionError` so a training routine cannot + modify clinical data.""" + + _WRITE_METHODS = {"create", "bulk_upsert", "open_session"} + + def __init__(self, repository): + self._repository = repository + self.model = repository.model + + def get(self, id_): + return self._repository.get(id_) + + def list(self, *, limit: int = 100, offset: int = 0, **filters): + return self._repository.list(limit=limit, offset=offset, **filters) + + def count(self, **filters) -> int: + return self._repository.count(**filters) + + def __getattr__(self, name: str): + if name in self._WRITE_METHODS: + raise PermissionError( + f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository." + ) + raise AttributeError(name) diff --git a/models/io/training.py b/models/io/tracking.py similarity index 52% rename from models/io/training.py rename to models/io/tracking.py index a6d70e0..b513474 100644 --- a/models/io/training.py +++ b/models/io/tracking.py @@ -1,9 +1,10 @@ -"""Bookkeeping around a training run (ML-01..ML-05). +"""MLflow runs: what happened in one execution (ML-01..ML-05). Does not train anything. It opens an MLflow run, records which cohort build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow -stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped +stores the run, metrics and artifacts. Turning a run into a registered +version is `models.io.registry`'s. It uses `MlflowClient`'s run-scoped methods instead of the fluent API's global active run, so two runs in one process never interfere. @@ -18,77 +19,55 @@ uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the delivered images). A PROD run only logs models whose class lives in a module, at a known commit, never one defined in a notebook. """ -import hashlib import json import os -import subprocess import tempfile from pathlib import Path from typing import Any import mlflow.pyfunc from core.governance.enums import ArtifactKind, Environment -from mlflow import MlflowClient, MlflowException -from persistance.repository import Repository +from mlflow import MlflowClient -from models.io.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name -from models.io.repositories import resolve_repository +from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, model_sha, registered_name +from models.io.storage import ReadOnlyRepository, resolve_repository ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" MODEL_PATH = "model" -GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets -GIT_DIRTY_TAG = "models.git.dirty" -GIT_COMMIT_ENV = "MODELS_GIT_COMMIT" -def code_version() -> dict[str, str]: - """The git commit of this package's repository and whether tracked files have uncommitted changes. - Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither, - nothing is recorded.""" - root = Path(__file__).resolve().parent +def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]: + """IR version, opsets, producer and graph inputs/outputs of a checkpoint (ML-01b, MLD-03), checked before it's + logged. `onnx` is an optional dependency (`models[export]`). + `{"available": False}` when the optional `onnx` package isn't installed; + `ValueError` when it is and the file isn't a valid ONNX model.""" try: - commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, - check=True).stdout.strip() - changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"], - capture_output=True, text=True, check=True).stdout.strip() - except (OSError, subprocess.CalledProcessError): - commit = os.environ.get(GIT_COMMIT_ENV) - return {GIT_COMMIT_TAG: commit} if commit else {} - return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()} + import onnx + except ImportError: + return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"} + + try: + model = onnx.load(str(path)) + onnx.checker.check_model(model) + except Exception as exc: + raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc + return { + "available": True, + "ir_version": model.ir_version, + "producer_name": model.producer_name, + "producer_version": model.producer_version, + "opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import], + "graph_inputs": [i.name for i in model.graph.input], + "graph_outputs": [o.name for o in model.graph.output], + } -def model_sha(model_dir: str | Path) -> str: - """sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left - out because it carries ids and dates, so the same model saved twice has the same sha.""" - return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest() - - -class ReadOnlyRepository: - """ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`. - Write methods raise `PermissionError` so a training routine cannot - modify clinical data.""" - - _WRITE_METHODS = {"create", "bulk_upsert", "open_session"} - - def __init__(self, repository: Repository): - self._repository = repository - self.model = repository.model - - def get(self, id_): - return self._repository.get(id_) - - def list(self, *, limit: int = 100, offset: int = 0, **filters): - return self._repository.list(limit=limit, offset=offset, **filters) - - def count(self, **filters) -> int: - return self._repository.count(**filters) - - def __getattr__(self, name: str): - if name in self._WRITE_METHODS: - raise PermissionError( - f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository." - ) - raise AttributeError(name) +def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | Path, *, + metadata: dict[str, Any] | None = None) -> None: + """ML-01a/ML-01b: logs an artifact file to a run, under a folder named for its kind.""" + client.log_artifact(run_id, str(path), artifact_path=kind) + if metadata: + client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json") class TrainingRun: @@ -142,10 +121,7 @@ class TrainingRun: def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None: """ML-01a/ML-01b: logs an artifact file to the run, under a folder named for its kind.""" - kind = ArtifactKind(kind) - self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value) - if metadata: - self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json") + log_artifact_file(self.client, self.run_id, ArtifactKind(kind).value, path, metadata=metadata) def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str: """Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its @@ -165,39 +141,13 @@ class TrainingRun: self.modelo_sha = sha return sha - def finish( - self, - *, - metrics: dict[str, Any] | None = None, - hyperparameters: dict[str, Any] | None = None, - **reports: str | None, - ) -> str: - """Logs metrics/params to the run, registers it as a new version of - `-` tagged with `models.io.registry`'s promotion - inputs (environment, cohort link, report URIs), and returns the new - version string. Call once, after training (and artifact logging) - completes.""" - unknown = set(reports) - set(REPORT_TAGS) - if unknown: - raise ValueError(f"campos desconocidos: {sorted(unknown)}") + def finish(self, *, metrics: dict[str, Any] | None = None, hyperparameters: dict[str, Any] | None = None) -> "TrainingRun": + """Logs metrics and parameters and closes the run. Registering it as a version is the registry's + (`models.io.registry.registry.register_run`).""" for key, value in (metrics or {}).items(): self.client.log_metric(self.run_id, key, value) for key, value in (hyperparameters or {}).items(): self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str)) - - name = registered_name(self.domain, self.scenario) - try: - self.client.create_registered_model(name) - except MlflowException as exc: - if exc.error_code != "RESOURCE_ALREADY_EXISTS": - raise - version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value} - if self.cohorte_armado_id is not None: - version_tags[ARMADO_TAG] = str(self.cohorte_armado_id) - if self.modelo_sha is not None: - version_tags[MODEL_SHA_TAG] = self.modelo_sha - version_tags.update({key: uri for key, uri in reports.items() if uri}) - source = f"runs:/{self.run_id}/{MODEL_PATH}" if self.modelo_sha is not None else f"runs:/{self.run_id}" - model_version = self.client.create_model_version(name, source=source, run_id=self.run_id, tags=version_tags) self.client.set_terminated(self.run_id) - return str(model_version.version) + return self + diff --git a/models/ocr.py b/models/ocr.py index 295d17d..fa52045 100644 --- a/models/ocr.py +++ b/models/ocr.py @@ -32,7 +32,7 @@ from extraction import FieldKind, FieldSpec, read_document from extraction.nlp import RecordExtractor, SegmentLine from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for from extraction.ocr import TesseractOcr -from models.io.repositories import resolve_repository +from models.io.storage import resolve_repository from persistance.repository import Repository # Below this confidence a value is stored but flagged for manual review. diff --git a/models/pipelines/cohort_build.py b/models/pipelines/cohort_build.py new file mode 100644 index 0000000..d6fd418 --- /dev/null +++ b/models/pipelines/cohort_build.py @@ -0,0 +1,70 @@ +"""Builds a cohort: all patients -> index date -> A1 -> ... -> An -> study population. + +Lists the steps of `models.steps.cohort`, gives each rule its own `em_` and `a_` node, and runs them. +""" + +import types + +from hamilton import ad_hoc_utils, driver +from hamilton.function_modifiers import group, inject, parameterize, source, value + +from persistance.aristas.dbt import DbtQueryRepository + +from models.io.contracts import BuiltCohort, CohortQueries +from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population + +INPUTS = ("cohort_queries", "dbt_queries") + + +def _fresh(function): + """A copy to decorate: Hamilton keeps a decorator on the function itself, so decorating the step would carry it into + the next build.""" + copy = types.FunctionType(function.__code__, function.__globals__, function.__name__, function.__defaults__, + function.__closure__) + copy.__annotations__, copy.__doc__ = dict(function.__annotations__), function.__doc__ + copy.__module__, copy.__qualname__ = function.__module__, function.__qualname__ + return copy + + +def build_driver(queries: CohortQueries) -> driver.Driver: + """The chain for the cohort's rules, in their order.""" + rules = list(queries.rules) + previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]] + nodes = [ + all_patients, + indexed, + parameterize(**{f"em_{rule.name}": {"rule": value(rule)} for rule in rules})(_fresh(excluded)), + parameterize(**{f"a_{rule.name}": {"population": source(before), "flagged": source(f"em_{rule.name}")} + for rule, before in zip(rules, previous)})(_fresh(remaining)), + inject(last=source(f"a_{rules[-1].name}"))(_fresh(study_population)), + inject(populations=group(*[source(f"a_{rule.name}") for rule in rules]), rules=value(rules))(_fresh(attrition)), + ] + return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build() + + +def build_cohort(queries: CohortQueries, dbt_queries: DbtQueryRepository) -> BuiltCohort: + """Runs the chain; `dbt_queries` is the domain's `dbt_query_repository`.""" + results = build_driver(queries).execute(["study_population", "attrition"], + inputs={"cohort_queries": queries, "dbt_queries": dbt_queries}) + return BuiltCohort(results["study_population"], results["attrition"]) + + +def mermaid(graph) -> str: + """The chain as a Mermaid diagram, read from the graph without running it.""" + def label(name: str) -> str: + if name.startswith("em_"): + return f'{name}["EM: {name[3:]}"]' + if name.startswith("a_"): + return f'{name}["A: {name[2:]}"]' + return f"{name}[({name})]" if name in ("all_patients", "study_population") else f"{name}[{name}]" + + lines = ["graph LR"] + for node in graph.nodes.values(): + if node.name in INPUTS or node.name == "attrition": + continue + if node.name.startswith("em_"): + lines.append(f' r_{node.name[3:]}[/"R: {node.name[3:]}"/] --> {label(node.name)}') + lines += [f" {dependency.name} --> {label(node.name)}" for dependency in node.dependencies + if dependency.name not in INPUTS] + lines += [f" {dependency.name} -.-> attrition" for dependency in graph.nodes["attrition"].dependencies] + return "\n".join(lines) diff --git a/models/pipelines/export_cohort.py b/models/pipelines/export_cohort.py new file mode 100644 index 0000000..94ac0bd --- /dev/null +++ b/models/pipelines/export_cohort.py @@ -0,0 +1,73 @@ +"""Exports a cohort build to its Parquet file: the members' events up to the cut-off, with the build's lineage. + +The steps come from `models.steps.cohort_file`, the reading and writing from `models.io`. Two sources share them: + +- `export_kit_build`: a build the kit stored, written once to `.parquet`; +- `export_dbt_build`: the study population of dbt's rules, built now. A file whose rows hash like the latest one's is + reused; otherwise the next number is written. + +The timeline comes from the domain's `timeline_repository` (dbt's view `_linea_de_tiempo`), cut at the +build's date in the query, and dbt's rules run through its `dbt_query_repository`. Nothing here writes to the +database. +""" + +import json +from datetime import date +from pathlib import Path + +import pandas as pd +import pyarrow as pa +from hamilton import ad_hoc_utils, driver + +from models.io.contracts import CohortQueries +from models.io.lineage import matches, require_match +from models.io.storage import cohort_path, dbt_build_path, latest_dbt_build, read_metadata, write_once +from models.pipelines.cohort_build import build_cohort +from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage + +NODES = [cohort_events, content_sha256, lineage, cohort_table] + + +def _table(timeline_rows: list[dict], population: pd.DataFrame, cutoff: date, base_lineage: dict) -> tuple[pa.Table, str]: + dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*NODES)).build() + inputs = {"timeline_rows": timeline_rows, "study_population": population, "cutoff": cutoff, "base_lineage": base_lineage} + results = dr.execute(["cohort_table", "content_sha256"], inputs=inputs) + return results["cohort_table"], results["content_sha256"] + + +def export_kit_build(cohorts, timeline, root: Path, domain: str, url: str, build_id: int | None = None) -> tuple[Path, str]: + """The kit build's file, reused if it's there and belongs to the build. `cohorts` and `timeline` are the domain's + `cohorte_repository` and `timeline_repository`.""" + build_id = build_id if build_id is not None else cohorts.latest_build(url) + build = None if build_id is None else cohorts.build(build_id) + if build is None or build.url != url: + raise LookupError(f"no such build of {url}: {build_id}") + path = cohort_path(root, url, build.armado_id) + if path.exists(): + require_match(read_metadata(path), {"armado_id": build.armado_id, "n_members": build.n_miembros}, str(path)) + return path, "reused" + population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in cohorts.members(build.armado_id)], + columns=["pac_id", "fecha_indice"]) + base = {"url": url, "version": build.version, "armado_id": build.armado_id, "domain": domain, "producer": "kit", + "parametros": cohorts.get(build.armado_id).parametros or "{}", "datos_as_of": build.datos_as_of.isoformat()} + table, _ = _table(timeline.read(until=build.datos_as_of), population, build.datos_as_of, base) + write_once(table, path) + return path, "exported" + + +def export_dbt_build(queries: CohortQueries, dbt_queries, timeline, root: Path, domain: str) -> tuple[Path, str]: + """Builds the cohort from dbt's rules and writes it, unless its rows are the latest file's. `dbt_queries` and + `timeline` are the domain's `dbt_query_repository` and `timeline_repository`.""" + built = build_cohort(queries, dbt_queries) + latest = latest_dbt_build(root, queries.url) + number = latest[0] + 1 if latest else 1 + base = {"url": queries.url, "build": number, "domain": domain, "producer": "dbt", + "parametros": json.dumps(queries.parameters, sort_keys=True), "datos_as_of": queries.cutoff.isoformat(), + "rules": json.dumps([rule.name for rule in queries.rules]), + "attrition": built.attrition.astype(object).where(built.attrition.notna(), None).to_json(orient="records")} + table, sha = _table(timeline.read(until=queries.cutoff), built.study_population, queries.cutoff, base) + if latest and matches(read_metadata(latest[1]), {"content_sha256": sha}): + return latest[1], "reused" + path = dbt_build_path(root, queries.url, number) + write_once(table, path) + return path, "exported" diff --git a/models/steps/__init__.py b/models/steps/__init__.py index b3a5d1c..1870f00 100644 --- a/models/steps/__init__.py +++ b/models/steps/__init__.py @@ -1 +1,4 @@ -"""Pure functions shared by every model: no I/O, testable alone.""" +"""The plain functions pipelines are built from: each becomes a Hamilton node once a pipeline lists it. + +They neither read nor write on their own: what they read comes in as a parameter, and a pipeline decides when they run. +""" diff --git a/models/steps/cohort.py b/models/steps/cohort.py new file mode 100644 index 0000000..da634a4 --- /dev/null +++ b/models/steps/cohort.py @@ -0,0 +1,52 @@ +"""The steps of a cohort build: all patients, the index date, each rule's excluded members and what remains. + +They know no rule by name: a pipeline gives each rule its own `excluded` and `remaining` node. The queries run through +the domain's `dbt_query_repository`. +""" + +import pandas as pd + +from persistance.aristas.dbt import DbtQueryRepository + +from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule + + +def _frame(rows: list[dict], columns: list[str]) -> pd.DataFrame: + return pd.DataFrame(rows) if rows else pd.DataFrame(columns=columns) + + +def all_patients(cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame: + return _frame(dbt_queries.read(cohort_queries.all_patients), ["pac_id"]) + + +def indexed(all_patients: pd.DataFrame, cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame: + """The patients with an index date. A patient outside `all_patients` is an error, not attrition.""" + index = _frame(dbt_queries.read(cohort_queries.index_date), ["pac_id", "fecha_indice"]) + if index["pac_id"].duplicated().any(): + raise CohortDefinitionError("the index query gives a patient more than one index date") + if unknown := len(set(index["pac_id"]) - set(all_patients["pac_id"])): + raise CohortDefinitionError(f"the index query gives {unknown} patients outside all patients") + return index.assign(fecha_indice=pd.to_datetime(index["fecha_indice"]).dt.date) + + +def excluded(rule: ExclusionRule, dbt_queries: DbtQueryRepository) -> set: + """Everyone the rule flags.""" + return {row["pac_id"] for row in dbt_queries.read(rule.sql)} + + +def remaining(population: pd.DataFrame, flagged: set) -> pd.DataFrame: + """The previous population minus a rule's excluded members.""" + return population[~population["pac_id"].isin(flagged)] + + +def study_population(last: pd.DataFrame) -> pd.DataFrame: + return last + + +def attrition(all_patients: pd.DataFrame, indexed: pd.DataFrame, populations: list[pd.DataFrame], + rules: list[ExclusionRule]) -> pd.DataFrame: + """Each rule is charged only for those it removes from the population it receives.""" + sizes = [("all_patients", len(all_patients)), ("indexed", len(indexed)), + *[(rule.name, len(population)) for rule, population in zip(rules, populations)]] + rows = [(step, n, None if i == 0 else sizes[i - 1][1] - n) for i, (step, n) in enumerate(sizes)] + return pd.DataFrame(rows, columns=["step", "n", "excluded"]).astype({"excluded": "Int64"}) diff --git a/models/steps/cohort_file.py b/models/steps/cohort_file.py new file mode 100644 index 0000000..604209e --- /dev/null +++ b/models/steps/cohort_file.py @@ -0,0 +1,40 @@ +"""The steps from a study population and the timeline to a build's table, with its lineage.""" + +from datetime import date, datetime, timezone + +import pandas as pd +import pyarrow as pa + +from models.io.contracts import COHORT_SCHEMA as SCHEMA +from models.io.lineage import table_sha256 + +ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] +TIMELINE = [name for name in SCHEMA.names if name != "fecha_indice"] + + +def cohort_events(timeline_rows: list[dict], study_population: pd.DataFrame, cutoff: date) -> pd.DataFrame: + """The members' events up to `cutoff`, in the file's order. A member without events stops the build.""" + members = study_population[["pac_id", "fecha_indice"]] + frame = pd.DataFrame(timeline_rows, columns=TIMELINE).merge(members, on="pac_id") + frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date + frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True) + frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"]) + frame = frame[frame["fecha"] <= cutoff] + if missing := len(members) - frame["pac_id"].nunique(): + raise ValueError(f"{missing} members have no events in the timeline") + return frame.sort_values(ROW_ORDER, kind="stable")[SCHEMA.names].reset_index(drop=True) + + +def content_sha256(cohort_events: pd.DataFrame) -> str: + """The hash of the rows alone, so the same content gives the same hash whenever it's built.""" + return table_sha256(pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)) + + +def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str) -> dict: + return {**base_lineage, "n_members": cohort_events["pac_id"].nunique(), "content_sha256": content_sha256, + "built_at": datetime.now(timezone.utc).isoformat()} + + +def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table: + table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False) + return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}}) diff --git a/models/testing.py b/models/testing.py index a3bc49d..c6b2846 100644 --- a/models/testing.py +++ b/models/testing.py @@ -8,7 +8,7 @@ model and isn't used outside tests; it has no tests of its own. import hashlib import json -from models.io.contract import Provenance, Risk +from models.io.contracts 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} diff --git a/scripts/export_cohort.py b/scripts/export_cohort.py deleted file mode 100644 index 5943fe7..0000000 --- a/scripts/export_cohort.py +++ /dev/null @@ -1,138 +0,0 @@ -"""Export a kit cohort build to its Parquet file, once. - - uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N] - -One file per build, `/cohorts///.parquet`, where `` is the folder of the -domain's database and `COHORTS_DIR` replaces `/cohorts`. Long format: one row per member and event, with -the member's index date on every row and the build's lineage in the file's metadata. - -The timeline comes from dbt's view `_linea_de_tiempo`, which holds no rows and needs creating only when its -dbt model changes (`dbt run --select _linea_de_tiempo`). The script only reads, through the domain's -repository, so it needs neither dbt nor write access. In a read-only folder, with nothing writing to the file, use -`CACU_DATABASE_URL=sqlite:///file:/path/cacu.db?immutable=1&uri=true`; `mode=ro` isn't enough for a WAL database. -""" - -import argparse -import sys -import tempfile -from collections.abc import Callable, Iterable -from datetime import datetime, timezone -from importlib import import_module -from pathlib import Path - -import pandas as pd -import pyarrow as pa -import pyarrow.parquet as pq -from persistance.aristas.oro import CohortBuild, CohortMember -from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository -from persistance.settings import settings -from sqlalchemy import column, select, table -from sqlalchemy.exc import DBAPIError - -from models.io.cohorts import SCHEMA, cohort_lineage, cohort_path, cohorts_root - -ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] - - -class TimelineViewError(RuntimeError): - """dbt's timeline view can't be read.""" - - -def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]: - """Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`.""" - name = f"{domain}_linea_de_tiempo" - view = table(name, *(column(c) for c in TIMELINE_COLUMNS)) - try: - return repository.with_query(lambda **_: select(*(view.c[c] for c in TIMELINE_COLUMNS))).read() - except DBAPIError as error: - raise TimelineViewError(f"can't read {name} ({error.orig}): is it created? " - f"Run `dbt run --select {name}` in Transformation") from error - - -def build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str, - parametros: str | None) -> pa.Table: - """The members' events up to `datos_as_of` and loaded by `conocida_hasta`, in the file's order, with the lineage.""" - members = list(members) - index_dates = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"]) - frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(index_dates, on="pac_id") - frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date - frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True) - frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"]) - frame = frame[frame["fecha"] <= build.datos_as_of] - if build.conocida_hasta is not None: - known_until = pd.Timestamp(build.conocida_hasta) - frame = frame[frame["conocida_en"] <= (known_until.tz_localize("UTC") if known_until.tzinfo is None else known_until)] - missing = len(members) - frame["pac_id"].nunique() - if missing: - raise ValueError(f"{missing} members of build {build.armado_id} have no events in the timeline") - frame = frame.sort_values(ROW_ORDER, kind="stable") - lineage = { - "url": build.url, "version": build.version, "armado_id": build.armado_id, "domain": domain, - "parametros": parametros or "{}", "datos_as_of": build.datos_as_of.isoformat(), - "conocida_hasta": build.conocida_hasta.isoformat() if build.conocida_hasta else "", - "n_members": len(members), "producer": "kit", "built_at": datetime.now(timezone.utc).isoformat(), - } - table = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False) - return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}}) - - -def write_once(table: pa.Table, path: Path) -> None: - """The file appears complete or not at all.""" - path.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle: - partial = Path(handle.name) - try: - pq.write_table(table, partial) - partial.replace(path) - finally: - partial.unlink(missing_ok=True) - - -def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]: - """The build's file: reused if it's already there and belongs to the build, written once if not.""" - path = cohort_path(root, build.url, build.armado_id) - if path.exists(): - lineage = cohort_lineage(path) - if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros): - raise ValueError(f"{path} doesn't belong to build {build.armado_id}: {lineage}") - return path, "reused" - write_once(make_table(), path) - return path, "exported" - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description="Export a kit cohort build to its Parquet file, once.") - parser.add_argument("--domain", required=True, choices=["cacu", "cama", "tea"]) - parser.add_argument("--cohort", required=True, help="the cohort without its domain, e.g. cohorte_vigilancia") - parser.add_argument("--build", type=int, help="the build's armado_id; the cohort's latest by default") - args = parser.parse_args(argv) - - repositories = import_module(f"persistance.{args.domain}") - cohorts, timeline = repositories.cohorte_repository, repositories.timeline_repository - url = f"{args.domain}/{args.cohort}" - build_id = args.build if args.build is not None else cohorts.latest_build(url) - build = None if build_id is None else cohorts.build(build_id) - if build is None or build.url != url: - print(f"no such build of {url}: {build_id}", file=sys.stderr) - return 1 - - database_url = getattr(settings, f"{args.domain}_database_url") - - def make_table() -> pa.Table: - return build_table(read_timeline(timeline, args.domain), cohorts.members(build.armado_id), build, domain=args.domain, - parametros=cohorts.get(build.armado_id).parametros) - - try: - path, outcome = ensure(build, cohorts_root(database_url), make_table) - except PermissionError as error: - print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr) - return 1 - except TimelineViewError as error: - print(error, file=sys.stderr) - return 1 - print(f"{outcome}: {path}") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py index 6732241..7b506cb 100644 --- a/tests/cacu/test_cin2_logistic.py +++ b/tests/cacu/test_cin2_logistic.py @@ -1,5 +1,6 @@ """What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal -split, that training on a build's file registers a version with its lineage, and the `models train` command over it. +split, that training on a build's file registers a version with its lineage, and the `models train` and +`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none. Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a @@ -16,9 +17,10 @@ import pytest from models.__main__ import main from models.cacu.cin2_logistic import model -from models.cacu.cin2_logistic.train import train -from models.io.cohorts import SCHEMA -from models.io.registry import ARMADO_TAG, MODEL_SHA_TAG, registry +from models.cacu.cin2_logistic.train import find_trained, train +from models.io.contracts import COHORT_SCHEMA as SCHEMA +from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG +from models.io.registry import PRODUCTION_ALIAS, registry def _row(pac_id, index, days, valor, tipo="bethesda"): @@ -105,8 +107,8 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics assert len(run.params["cohort_sha256"]) == 64 - probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame) - assert len(probabilities) == 20 and probabilities.between(0, 1).all() + risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame) + assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all() def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys): @@ -146,3 +148,146 @@ def test_what_is_missing_is_named(exported, arguments, message, capsys): version. Fails if the command lets the import error through, or trains on another file.""" assert main(["train", *arguments]) == 1 assert message in capsys.readouterr().err + + +def test_estimate_scores_each_member_with_the_production_version(exported, mlflow_tracking, tmp_path, capsys): + """Pins down: with no `--version`, the command uses the version holding the production alias and writes one row per + member, identified by `pac_id`, with the version and build in the file's metadata. Fails if it takes the newest + version instead of the alias, or the output can't be matched to members.""" + main(["train", "cacu", "cin2_logistic"]) + main(["train", "cacu", "cin2_logistic"]) + registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1") + output = tmp_path / "risks" / "output.parquet" + + assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 0 + + assert "version 1" in capsys.readouterr().out + risks = pd.read_parquet(output) + assert list(risks.columns) == ["pac_id", "fecha_indice", "probabilidad"] + assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all() + metadata = pq.read_metadata(output).metadata + assert metadata[b"modelo_version"] == b"1" and metadata[b"armado_id"] == b"12" + + +def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path): + """Pins down: `--version` runs that version even if it isn't in production. Fails if the option is ignored or the + alias becomes mandatory.""" + main(["train", "cacu", "cin2_logistic"]) + output = tmp_path / "output.parquet" + + assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output), "--version", "1"]) == 0 + + assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1" + + +def test_estimate_without_a_production_version_is_refused(exported, mlflow_tracking, tmp_path, capsys): + """Pins down: with no `--version` and no version in production, the command ends with exit 1, says so and writes + nothing. Fails if it falls back to another version or lets the error through.""" + main(["train", "cacu", "cin2_logistic"]) + output = tmp_path / "output.parquet" + + assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 1 + + assert "no version in production" in capsys.readouterr().err and not output.exists() + + +RUN = ["run", "cacu", "cin2_logistic"] + + +def _versions(): + return registry.client.search_model_versions("name='cacu-cin2_logistic'") + + +def test_run_without_a_step_is_refused(capsys): + """Pins down: `run` needs a step named, so it never does everything by default. Fails if an empty call starts running + steps.""" + with pytest.raises(SystemExit) as stopped: + main(RUN) + + assert stopped.value.code == 2 and "--export" in capsys.readouterr().err + + +def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path): + """Pins down: `--train` alone registers a version, sets no alias and writes no output. Fails if a step runs without + its option.""" + assert main([*RUN, "--train"]) == 0 + + assert len(_versions()) == 1 + with pytest.raises(LookupError): + registry.resolve("cacu", "cin2_logistic") + + +def test_repeating_every_step_changes_nothing(exported, mlflow_tracking, tmp_path, capsys): + """Pins down: a second identical run registers no version and doesn't rewrite the output. Fails if `--train` stops + looking for the existing version, or `--estimate` stops reading the output's metadata.""" + output = tmp_path / "output.parquet" + steps = [*RUN, "--train", "--promote", "--estimate", "--output", str(output)] + assert main(steps) == 0 + written = output.stat().st_mtime_ns + capsys.readouterr() + + assert main(steps) == 0 + + assert len(_versions()) == 1 and output.stat().st_mtime_ns == written + out = capsys.readouterr().out + assert "already trained" in out and "already in production" in out and "already estimated" in out + + +def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking): + """Pins down: what says a training is the same is the file and the environment, so a build with other content or a + PROD run gets its own version. Fails if the check ignores either and reuses a version from something else.""" + assert main([*RUN, "--train", "--armado", "7"]) == 0 + assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0 + frame = pd.read_parquet(exported / "12.parquet") + _write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12) + assert main([*RUN, "--train", "--armado", "12"]) == 0 + + assert len(_versions()) == 3 + + +def test_changed_model_code_trains_again(exported, mlflow_tracking, monkeypatch): + """Pins down: a version trained by other code isn't reused. Fails if the check stops comparing `code_sha256`.""" + assert main([*RUN, "--train"]) == 0 + assert find_trained(exported / "12.parquet") == "1" + + monkeypatch.setattr(model, "code_sha256", lambda: "other") + + assert find_trained(exported / "12.parquet") is None + + +def test_a_moved_alias_estimates_again(exported, mlflow_tracking, tmp_path): + """Pins down: the output is reused only for the same version, so a new production version rewrites it. Fails if + `--estimate` skips because the file exists.""" + output = tmp_path / "output.parquet" + assert main(["train", "cacu", "cin2_logistic"]) == 0 + assert main(["train", "cacu", "cin2_logistic"]) == 0 + assert main([*RUN, "--promote", "--version", "1", "--estimate", "--output", str(output)]) == 0 + assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1" + + assert main([*RUN, "--promote", "--version", "2", "--estimate", "--output", str(output)]) == 0 + + assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2" + + +def test_promote_needs_a_version(exported, mlflow_tracking, capsys): + """Pins down: `--promote` with nothing trained on the file and no `--version` ends with exit 1 and sets no alias. + Fails if it promotes some other version.""" + assert main([*RUN, "--promote"]) == 1 + assert "use --train or --version" in capsys.readouterr().err + + +def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_tracking, monkeypatch): + """Pins down: `--export` exports the kit build of `model.toml`'s cohort, and its failure stops the next steps. Fails if + the cohort or the build change, or training continues on a stale file.""" + calls = [] + + def refuse(cohorts, read_timeline, root, domain, url, build_id=None): + calls.append((domain, url, build_id)) + raise LookupError(f"no such build of {url}: {build_id}") + + monkeypatch.setattr("models.pipelines.export_cohort.export_kit_build", refuse) + + assert main([*RUN, "--export", "--train", "--armado", "7"]) == 1 + + assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)] + assert not _versions() diff --git a/tests/io/test_contract.py b/tests/io/test_contracts.py similarity index 95% rename from tests/io/test_contract.py rename to tests/io/test_contracts.py index b178ee9..b7b27dd 100644 --- a/tests/io/test_contract.py +++ b/tests/io/test_contracts.py @@ -1,11 +1,11 @@ -"""What this module covers: the `RiskEstimator` contract in `models.io.contract` and the two records it +"""What this module covers: the `RiskEstimator` contract in `models.io.contracts` and the two records it returns, `Risk` and `Provenance`. Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one fixed probability per member and horizon. `Incomplete` lacks `provenance`. """ -from models.io.contract import Provenance, Risk, RiskEstimator +from models.io.contracts import Provenance, Risk, RiskEstimator class ConstantEstimator: diff --git a/tests/io/test_lineage.py b/tests/io/test_lineage.py new file mode 100644 index 0000000..e02e7b8 --- /dev/null +++ b/tests/io/test_lineage.py @@ -0,0 +1,49 @@ +"""What this module covers: `models.io.lineage`, the vocabulary files, runs and versions record their origin with: the +hashes of files and tables, and the rule that decides an output is already done. + +Fixtures: none; each test builds its own small table or file. +""" + +import pyarrow as pa +import pytest + +from models.io.lineage import file_sha256, matches, registered_name, require_match, table_sha256 + + +def test_a_table_hashes_by_its_rows_not_its_metadata(): + """Pins down: the same rows hash the same whatever metadata the table carries, and another row changes the hash. + Fails if metadata such as `built_at` enters the hash, so every rebuild would look new.""" + table = pa.table({"pac_id": [1, 2]}) + + assert table_sha256(table) == table_sha256(table.replace_schema_metadata({"built_at": "now"})) + assert table_sha256(table) != table_sha256(pa.table({"pac_id": [1, 2, 3]})) + + +def test_files_hash_in_order(tmp_path): + """Pins down: several files hash as their bytes in the order given, so a model's code hash covers each file. Fails + if a file is skipped or the order stops mattering.""" + a, b = tmp_path / "a", tmp_path / "b" + a.write_bytes(b"one") + b.write_bytes(b"two") + + assert file_sha256(a, b) != file_sha256(b, a) != file_sha256(a) + + +def test_an_output_is_done_when_its_lineage_has_every_expected_value(): + """Pins down: recorded lineage matches when every expected key has its value, compared as text since files and + MLflow store text; extra keys don't matter. Fails if a missing key counts as a match or numbers stop matching text.""" + recorded = {"armado_id": "7", "n_members": "2", "built_at": "now"} + + assert matches(recorded, {"armado_id": 7, "n_members": 2}) + assert not matches(recorded, {"armado_id": 7, "content_sha256": "x"}) + + +def test_a_mismatch_is_refused_with_both_sides(): + """Pins down: `require_match` names what was expected and what was found. Fails if a mismatch passes silently.""" + with pytest.raises(ValueError, match="doesn't belong.*armado_id"): + require_match({"armado_id": "1"}, {"armado_id": 2}, "build.parquet") + + +def test_models_are_registered_as_domain_and_scenario(): + """Pins down: the name runs and versions share. Fails if the convention changes on one side only.""" + assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic" diff --git a/tests/io/test_model_versions.py b/tests/io/test_model_versions.py index a702716..4d4f161 100644 --- a/tests/io/test_model_versions.py +++ b/tests/io/test_model_versions.py @@ -16,9 +16,10 @@ import pytest from core.governance.enums import Environment from mlflow import MlflowClient -from models.io import training -from models.io.registry import MODEL_SHA_TAG, registry -from models.io.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun +from models.io import lineage +from models.io.lineage import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, MODEL_SHA_TAG +from models.io.registry import registry +from models.io.tracking import TrainingRun class Constant(mlflow.pyfunc.PythonModel): @@ -37,7 +38,7 @@ def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[T run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV) if model is not None: run.log_model(model) - return run, run.finish(metrics={"auc": 0.7}) + return run, registry.register_run(run.finish(metrics={"auc": 0.7})) def test_a_logged_model_is_what_the_version_loads(mlflow_tracking): @@ -129,7 +130,7 @@ def test_an_explicit_version_is_returned_with_its_status(production_ready): def _git(*args: str) -> str: - return subprocess.run(["git", "-C", str(Path(training.__file__).parent), *args], capture_output=True, text=True, + return subprocess.run(["git", "-C", str(Path(lineage.__file__).parent), *args], capture_output=True, text=True, check=True).stdout.strip() @@ -155,7 +156,7 @@ def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_track def no_git(*args, **kwargs): raise FileNotFoundError("git") - monkeypatch.setattr(training.subprocess, "run", no_git) + monkeypatch.setattr(lineage.subprocess, "run", no_git) monkeypatch.setenv(GIT_COMMIT_ENV, "abc123") tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).run_id).data.tags diff --git a/tests/io/test_registry.py b/tests/io/test_registry.py index bc746b5..9bc6e9a 100644 --- a/tests/io/test_registry.py +++ b/tests/io/test_registry.py @@ -56,7 +56,7 @@ def test_retire_and_lineage(production_ready): def test_invalid_onnx_checkpoint_is_rejected(production_ready): - from models.io.export import inspect_onnx_metadata + from models.io.tracking import inspect_onnx_metadata with pytest.raises(ValueError, match="ONNX"): import tempfile diff --git a/tests/io/test_prediction.py b/tests/io/test_registry_predictions.py similarity index 94% rename from tests/io/test_prediction.py rename to tests/io/test_registry_predictions.py index 0b42866..0555941 100644 --- a/tests/io/test_prediction.py +++ b/tests/io/test_registry_predictions.py @@ -2,8 +2,7 @@ import json import pytest -from models.io.prediction import ApplicabilityRejected, Interpretability, PredictionService -from models.io.registry import registry +from models.io.registry import ApplicabilityRejected, Interpretability, PredictionService, registry class StubModel: diff --git a/tests/io/test_cohorts.py b/tests/io/test_storage.py similarity index 93% rename from tests/io/test_cohorts.py rename to tests/io/test_storage.py index 01ecaa3..d66dc28 100644 --- a/tests/io/test_cohorts.py +++ b/tests/io/test_storage.py @@ -1,4 +1,4 @@ -"""What this module covers: `models.io.cohorts`, reading a cohort build's file; and the rule that a model's folder +"""What this module covers: `models.io.storage`, reading a cohort build's file; and the rule that a model's folder doesn't import the database layer, since the file is its only input. Fixtures: `cohort_file`, a small Parquet file of a build with two members. @@ -13,7 +13,8 @@ import pyarrow.parquet as pq import pytest import models -from models.io.cohorts import SCHEMA, CohortFileError, read_cohort +from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortFileError +from models.io.storage import read_cohort def _row(pac_id, fecha_indice, valor, fuente_id): diff --git a/tests/io/test_repositories.py b/tests/io/test_storage_repositories.py similarity index 86% rename from tests/io/test_repositories.py rename to tests/io/test_storage_repositories.py index 2ba6099..af8b062 100644 --- a/tests/io/test_repositories.py +++ b/tests/io/test_storage_repositories.py @@ -1,10 +1,10 @@ -"""What this module covers: `resolve_repository`, how `models` finds a domain's Persistance repository by name. +"""What this module covers: `models.io.storage.resolve_repository`, how `models` finds a domain's Persistance repository by name. Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test. """ import pytest -from models.io.repositories import resolve_repository +from models.io.storage import resolve_repository def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db): diff --git a/tests/io/test_training.py b/tests/io/test_tracking.py similarity index 73% rename from tests/io/test_training.py rename to tests/io/test_tracking.py index 4a2b2fb..b192ece 100644 --- a/tests/io/test_training.py +++ b/tests/io/test_tracking.py @@ -4,7 +4,8 @@ from core.governance.enums import ArtifactKind, Environment from models.io.registry import registry from mlflow import MlflowException -from models.io.training import ReadOnlyRepository, TrainingRun +from models.io.storage import ReadOnlyRepository +from models.io.tracking import TrainingRun def test_prod_run_requires_a_cohort_build(): @@ -23,7 +24,7 @@ def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path) run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV) run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17}) - version = run.finish(metrics={"auc": 0.81}) + version = registry.register_run(run.finish(metrics={"auc": 0.81})) mv = registry.get("cacu", "tamizaje", version) assert mv.tags["environment"] == Environment.DEV.value @@ -61,23 +62,34 @@ def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, t assert experiment.artifact_location.endswith(str(root / "cama-riesgo")) -def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch): +def test_registering_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch): + from mlflow import MlflowClient + run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV) - assert run.finish() == "1" + assert registry.register_run(run.finish()) == "1" second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV) - assert second.finish() == "2" + assert registry.register_run(second.finish()) == "2" third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV) - def unreachable(name): + def unreachable(self, name): raise MlflowException("servidor no disponible") - monkeypatch.setattr(third.client, "create_registered_model", unreachable) + monkeypatch.setattr(MlflowClient, "create_registered_model", unreachable) with pytest.raises(MlflowException, match="no disponible"): - third.finish() + registry.register_run(third.finish()) def test_unknown_domain_is_rejected(): with pytest.raises(ValueError, match="dominio desconocido"): TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV) + + +def test_finishing_a_run_registers_nothing(mlflow_tracking): + """Pins down: closing a run logs its metrics and ends it, and only the registry turns it into a version, so a run + can be kept without becoming a model. Fails if `finish` starts registering again.""" + run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).finish(metrics={"auc": 0.5}) + + assert registry.client.get_run(run.run_id).info.status == "FINISHED" + assert registry.client.search_model_versions("name='cacu-tamizaje'") == [] diff --git a/tests/io/test_export.py b/tests/io/test_tracking_onnx.py similarity index 97% rename from tests/io/test_export.py rename to tests/io/test_tracking_onnx.py index c516199..862cb1c 100644 --- a/tests/io/test_export.py +++ b/tests/io/test_tracking_onnx.py @@ -2,7 +2,7 @@ import onnx import onnx.helper import pytest -from models.io.export import inspect_onnx_metadata +from models.io.tracking import inspect_onnx_metadata def _tiny_onnx_bytes() -> bytes: diff --git a/tests/test_cohort_build.py b/tests/test_cohort_build.py new file mode 100644 index 0000000..09e00f3 --- /dev/null +++ b/tests/test_cohort_build.py @@ -0,0 +1,221 @@ +"""What this module covers: reading a cohort's queries from dbt's manifest (`models.io.storage.read_queries`), the +graph `models.pipelines.cohort_build` generates from them, and the `models cohorts build` command over it. + +Fixtures: `manifest`, a function writing a `manifest.json` whose queries are literal rows, so no dbt or tables are +needed: patients 1 to 6 with a cut-off in their meta, 1 to 5 with an index date, rule `first` flags 2 and 3, rule `second` flags 3 and 4; +`cacu_db` (conftest), a temporary CaCu database whose session the command reads through. +""" + +import json +from datetime import date + +import pytest +from persistance.aristas.dbt import DbtQueryRepository +from sqlalchemy import create_engine, text +from sqlmodel import Session + +from models.__main__ import main +from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule +from models.io.storage import read_queries +from models.pipelines.cohort_build import build_cohort, build_driver, mermaid +from models.steps import cohort + +URL = "cacu/sample" + + +def _rows(*ids): + return " union all ".join(f"select {i} as pac_id" for i in ids) + + +INDEX = " union all ".join(f"select {i} as pac_id, '2025-01-0{i}' as fecha_indice" for i in range(1, 6)) + + +def _node(name, kind, sql, order=None, reads=()): + meta = {"cohort": URL, "kind": kind} | ({"cutoff": "2025-12-31", "parameters": '{"cutoff": "2025-12-31"}'} if kind == "population" else {}) + if order is not None: + meta |= {"name": name, "order": order} + return {"name": name, "unique_id": f"model.p.{name}", "description": f"{name} rule", "compiled_code": sql, + "config": {"meta": meta}, "depends_on": {"nodes": [f"model.p.{r}" for r in reads]}} + + +def _standard(): + return [_node("all_patients", "population", _rows(1, 2, 3, 4, 5, 6)), _node("index", "index", INDEX), + _node("first", "exclusion", _rows(2, 3), 1, ["index", "timeline"]), + _node("second", "exclusion", _rows(3, 4), 2, ["index", "timeline"])] + + +@pytest.fixture +def manifest(tmp_path): + """Writes the given nodes, the standard cohort by default, plus a model of another cohort, and returns the path.""" + def write(nodes=None): + other = _node("foreign", "population", _rows(99)) | {"config": {"meta": {"cohort": "cacu/other", "kind": "population"}}} + nodes = _standard() if nodes is None else nodes + path = tmp_path / "manifest.json" + path.write_text(json.dumps({"nodes": {node["unique_id"]: node for node in [*nodes, other]}})) + return path + return write + + + + +def _sqlite_reader(): + """The real `DbtQueryRepository` over an empty in-memory database: the test queries are literal rows.""" + return DbtQueryRepository(lambda: Session(create_engine("sqlite://"))) + + +def test_rules_come_from_the_manifest_in_their_order(manifest): + """Pins down: only this cohort's queries are read, with name, description and order from the YAML. Fails if another + cohort's models leak in, or the rules follow the manifest's order instead of `order`.""" + nodes = _standard() + queries = read_queries(manifest(nodes[:2] + nodes[:1:-1]), URL) + + assert [(rule.name, rule.order) for rule in queries.rules] == [("first", 1), ("second", 2)] + assert queries.rules[0].description == "first rule" and "99" not in queries.all_patients + + +def test_the_chain_gives_population_and_attrition(manifest): + """Pins down: the study population is the indexed patients minus every rule's set, and a patient two rules flag is + charged to the first. Fails if attrition counts each set whole, or a rule stops applying.""" + built = build_cohort(read_queries(manifest(), URL), _sqlite_reader()) + + assert sorted(built.study_population["pac_id"]) == [1, 5] + assert built.attrition.to_dict("list")["step"] == ["all_patients", "indexed", "first", "second"] + assert built.attrition["n"].tolist() == [6, 5, 3, 2] + assert built.attrition["excluded"].tolist()[1:] == [1, 2, 1] + + +def test_order_changes_the_charge_not_the_population(manifest): + """Pins down: with the rules reversed the population is the same and patient 3 is charged to the other rule. Fails if + a rule starts depending on the chain.""" + forward = read_queries(manifest(), URL) + backward = CohortQueries(URL, forward.all_patients, forward.index_date, tuple(reversed(forward.rules)), forward.cutoff, {}) + one, other = build_cohort(forward, _sqlite_reader()), build_cohort(backward, _sqlite_reader()) + + assert set(one.study_population["pac_id"]) == set(other.study_population["pac_id"]) + assert one.attrition["step"].tolist()[2:] == ["first", "second"] and other.attrition["step"].tolist()[2:] == ["second", "first"] + assert one.attrition["excluded"].tolist()[2:] == [2, 1] and other.attrition["excluded"].tolist()[2:] == [2, 1] + + +def test_a_new_rule_only_needs_its_query(manifest): + """Pins down: adding a rule in the manifest adds its nodes, with no code naming it. Fails if the chain stops being + generated from the rules.""" + queries = read_queries(manifest([*_standard(), _node("third", "exclusion", _rows(5), 3, ["index"])]), URL) + built = build_cohort(queries, _sqlite_reader()) + + assert {"em_third", "a_third"} <= set(build_driver(queries).graph.nodes) + assert built.study_population["pac_id"].tolist() == [1] + + +def test_index_dates_become_dates(manifest): + """Pins down: `fecha_indice` is a date whatever the engine returns; SQLite returns text. Fails if the conversion is + lost, which the export's schema would reject.""" + built = build_cohort(read_queries(manifest(), URL), _sqlite_reader()) + + assert built.study_population.set_index("pac_id").loc[1, "fecha_indice"] == date(2025, 1, 1) + + +def test_a_population_without_cutoff_is_refused(manifest): + """Pins down: the build needs the cut-off its events are cut at. Fails if the export could run without one.""" + nodes = _standard() + del nodes[0]["config"]["meta"]["cutoff"] + + with pytest.raises(CohortDefinitionError, match="no `cutoff`"): + read_queries(manifest(nodes), URL) + + +@pytest.mark.parametrize("change, message", [ + (lambda n: n[:1] + n[2:], "exactly one `index`"), + (lambda n: n[:2], "no `exclusion` queries"), + (lambda n: [*n, _node("third", "exclusion", _rows(5), 1)], "repeats an `order`"), + (lambda n: [*n, _node("third", "exclusion", _rows(5), 3, ["first"])], "may only read"), + (lambda n: [*n[:2], n[2] | {"compiled_code": None}, n[3]], "dbt compile"), +]) +def test_a_badly_defined_cohort_is_refused(manifest, change, message): + """Pins down: what the chain relies on is checked when reading. The fourth case is what keeps the rules commutable: an + exclusion can't read another step. Fails if any of these reaches the graph.""" + with pytest.raises(CohortDefinitionError, match=message): + read_queries(manifest(change(_standard())), URL) + + +@pytest.mark.parametrize("index_sql, message", [ + ("select 1 as pac_id, '2025-01-01' as fecha_indice union all select 1, '2025-01-02'", "more than one index date"), + ("select 7 as pac_id, '2025-01-01' as fecha_indice", "outside all patients"), +]) +def test_a_wrong_index_is_an_error_not_attrition(index_sql, message): + """Pins down: a repeated patient or one unknown to `all_patients` stops the build. Fails if an inner join silently + drops them and they pass as attrition.""" + queries = CohortQueries(URL, _rows(1, 2), index_sql, (ExclusionRule("r", "", 1, _rows(2)),), date(2025, 12, 31), {}) + + with pytest.raises(Exception, match=message): + build_cohort(queries, _sqlite_reader()) + + +def test_the_graph_comes_without_running_anything(manifest): + """Pins down: the diagram shows each rule, its excluded members and its population, and leaves the inputs out. Fails if + the nodes stop being derived from the rules.""" + diagram = mermaid(build_driver(read_queries(manifest(), URL)).graph) + + assert 'em_first["EM: first"]' in diagram and "a_first --> " in diagram + assert "dbt_queries" not in diagram and "cohort_queries" not in diagram and "a_second --> study_population" in diagram + + +def test_cutoff_and_parameters_come_from_the_population_meta(manifest): + """Pins down: the cut-off and the parameters dbt rendered into the population query's meta are read with the rules, + so the export cuts the events where the rules did. Fails if they're lost or not parsed.""" + queries = read_queries(manifest(), URL) + + assert queries.cutoff == date(2025, 12, 31) and queries.parameters == {"cutoff": "2025-12-31"} + + +def test_two_builds_with_other_rules_stay_apart(manifest): + """Pins down: building a chain decorates copies, so a second build with other rules doesn't inherit the first's + nodes, and the steps themselves stay plain. Fails if the pipeline decorates the step functions in place.""" + queries = read_queries(manifest(), URL) + build_driver(queries) + other = build_driver(CohortQueries(URL, queries.all_patients, queries.index_date, (ExclusionRule("only", "", 1, _rows(2)),), + queries.cutoff, {})) + + assert {"em_only", "a_only"} <= set(other.graph.nodes) and "em_first" not in other.graph.nodes + assert not getattr(cohort.excluded, "__dict__", {}) + + +def test_the_command_builds_through_the_session(manifest, cacu_db, capsys): + """Pins down: `cohorts build` reads through the domain's session, shows the attrition and says nothing was stored. + Fails if the wiring to the session or the output changes.""" + assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest())]) == 0 + + out = capsys.readouterr().out + assert "second" in out and "cacu/sample: 2 members, not stored" in out + + +def test_the_command_prints_the_graph_without_a_database(manifest, capsys): + """Pins down: `--graph` needs only the manifest. Fails if it runs a query.""" + nodes = _standard() + nodes[0]["compiled_code"] = "select from nowhere" + + assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes)), "--graph"]) == 0 + assert capsys.readouterr().out.startswith("graph LR") + + +@pytest.mark.parametrize("arguments, message", [ + (["--manifest", "/nowhere/manifest.json"], "manifest.json"), + (["--graph"], "has no queries"), +]) +def test_what_is_missing_is_named(manifest, arguments, message, capsys): + """Pins down: a missing manifest or an unknown cohort ends with exit 1 and a message. Fails if a traceback gets out.""" + if arguments[0] == "--graph": + arguments = ["--manifest", str(manifest())] + assert main(["cohorts", "build", "cacu", "unknown", *arguments]) == 1 + else: + assert main(["cohorts", "build", "cacu", "sample", *arguments]) == 1 + assert message in capsys.readouterr().err + + +def test_a_query_that_fails_points_to_the_view(manifest, cacu_db, capsys): + """Pins down: a query that can't run, usually because the view isn't created, ends with exit 1 and names the dbt + command. Fails if the database error reaches the user raw.""" + nodes = _standard() + nodes[0]["compiled_code"] = "select pac_id from no_such_view" + + assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes))]) == 1 + assert "dbt run --select cacu_linea_de_tiempo" in capsys.readouterr().err diff --git a/tests/test_export_cohort.py b/tests/test_export_cohort.py index 064e262..af86373 100644 --- a/tests/test_export_cohort.py +++ b/tests/test_export_cohort.py @@ -1,49 +1,56 @@ -"""What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file -goes, what it holds, that it's written once, and that the timeline is read from dbt's view without changing the database. +"""What this module covers: exporting a cohort build to its Parquet file. The steps (`models.steps.cohort_file`), the +file (`models.io.storage`, `models.io.lineage`), both sources of `models.pipelines.export_cohort`, and the `models cohorts export` command. +Reading the timeline and dbt's queries is Persistance's, tested there. -Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build -cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and -one of a patient outside the build; `timeline_db`, a SQLite file with a `cacu_linea_de_tiempo` view and its repository. +Fixtures: `build`, a kit build cut at 2025-12-31 with two members, and `kit`, a stand-in of its repository; `events`, one +kept event per member plus one after the cut-off and one of a patient outside the build; `dbt_cohort`, compiled queries +whose rules keep patients 10 and 20. """ -import importlib.util -import sqlite3 from datetime import date, datetime, timezone from pathlib import Path +from types import SimpleNamespace +import pandas as pd import pyarrow.parquet as pq import pytest from persistance.aristas.oro import CohortBuild, CohortMember -from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository -from sqlmodel import Session, create_engine +from persistance.aristas.dbt import DbtQueryRepository +from sqlalchemy import create_engine, text +from sqlmodel import Session -ROOT = Path(__file__).resolve().parents[1] +from models.__main__ import main +from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortQueries, ExclusionRule +from models.io.storage import cohorts_root, read_metadata, write_once +from models.pipelines.export_cohort import export_dbt_build, export_kit_build +from models.steps.cohort_file import cohort_events, content_sha256 + +URL = "cacu/cohorte_vigilancia" MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"), CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")] +POPULATION = pd.DataFrame({"pac_id": [20, 10], "fecha_indice": [date(2025, 2, 1), date(2025, 1, 1)]}) -@pytest.fixture -def script(): - """The script as a module.""" - spec = importlib.util.spec_from_file_location("export_cohort", ROOT / "scripts" / "export_cohort.py") - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def _build(armado_id=1, known_until=None, n_miembros=2): - return CohortBuild(armado_id, "cacu/cohorte_vigilancia", "1.0", "huella", "marco", date(2025, 12, 31), known_until, - n_miembros, datetime(2026, 1, 1, tzinfo=timezone.utc)) +def _build(armado_id=1, n_miembros=2): + return CohortBuild(armado_id, URL, "1.0", "huella", "marco", date(2025, 12, 31), None, n_miembros, + datetime(2026, 1, 1, tzinfo=timezone.utc)) @pytest.fixture def build(): - """A build with a clinical cut-off and a load cut-off.""" - return _build(known_until=datetime(2026, 1, 2, 8, tzinfo=timezone.utc)) + """A kit build with a clinical cut-off.""" + return _build() -def _event(pac_id, fecha, conocida_en, fuente_id): - return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "medicion", "tipo": "bethesda", +@pytest.fixture +def kit(build): + """The cohort repository's reads an export needs, over `build` and its members.""" + return SimpleNamespace(latest_build=lambda url: build.armado_id, build=lambda i: build if i == build.armado_id else None, + members=lambda i: MEMBERS, get=lambda i: SimpleNamespace(parametros='{"corte": "2025-12-31"}')) + + +def _event(pac_id, fecha, fuente_id): + return {"pac_id": pac_id, "fecha": fecha, "conocida_en": "2025-02-02 10:00:00", "clase": "medicion", "tipo": "bethesda", "codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "citologiacervical", "fuente_id": fuente_id} @@ -51,134 +58,188 @@ def _event(pac_id, fecha, conocida_en, fuente_id): @pytest.fixture def events(): """Dates as text, as SQLite returns them from a subquery.""" - return [_event(20, "2025-03-01", "2025-03-02 10:00:00", "kept-20"), - _event(10, "2025-02-01", "2025-02-02 10:00:00.5", "kept-10"), - _event(10, "2026-02-01", "2026-01-01 00:00:00", "after-datos-as-of"), - _event(20, "2025-06-01", "2026-01-03 00:00:00", "loaded-after-the-build"), - _event(99, "2025-02-01", "2025-02-02 00:00:00", "not-a-member")] + return [_event(20, "2025-03-01", "kept-20"), _event(10, "2025-02-01", "kept-10"), + _event(10, "2026-02-01", "after-the-cutoff"), _event(99, "2025-02-01", "not-a-member")] -def test_table_keeps_members_within_both_cut_offs_in_the_file_order(script, build, events): - """Pins down: only members' events, up to `datos_as_of` and loaded by `conocida_hasta`, ordered by patient, each - with its index date. Fails if a cut-off or the join with the members is lost, or the rows aren't sorted.""" - table = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}') - - assert table.column("fuente_id").to_pylist() == ["kept-10", "kept-20"] - assert table.column("fecha_indice").to_pylist() == [date(2025, 1, 1), date(2025, 2, 1)] - assert table.schema.names == script.SCHEMA.names -def test_table_carries_the_lineage(script, build, events): - """Pins down: the file explains itself: the build's identity and cut-offs are in its metadata. Fails if a key - a reader relies on is dropped or renamed.""" - metadata = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}').schema.metadata - lineage = {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")} +class _Timeline: + """Stands in for `timeline_repository`: the given rows, counting reads; the export cuts them itself too.""" - assert lineage["armado_id"] == "1" and lineage["url"] == build.url and lineage["n_members"] == "2" - assert lineage["domain"] == "cacu" and lineage["producer"] == "kit" and lineage["datos_as_of"] == "2025-12-31" - assert lineage["parametros"] == '{"corte": "2025-12-31"}' + def __init__(self, rows): + self.rows, self.reads = rows, 0 + + def read(self, *, until=None, **_): + self.reads += 1 + return self.rows -def test_a_member_without_events_is_refused(script, build, events): +_query = DbtQueryRepository(lambda: Session(create_engine("sqlite://"))) + + +@pytest.fixture +def dbt_cohort(): + """Patients 10, 20 and 30, all indexed; one rule excludes 30.""" + index = "select 10 as pac_id, '2025-01-01' as fecha_indice union all select 20, '2025-02-01' union all select 30, '2025-03-01'" + return CohortQueries(URL, "select 10 as pac_id union all select 20 union all select 30", index, + (ExclusionRule("third", "", 1, "select 30 as pac_id"),), date(2025, 12, 31), {"cutoff": "2025-12-31"}) + + +def test_events_are_the_members_up_to_the_cutoff_in_order(events): + """Pins down: only members' events, up to the cut-off, ordered by patient, each with its index date. Fails if the + cut-off or the join with the members is lost, or the rows aren't sorted.""" + frame = cohort_events(events, POPULATION, date(2025, 12, 31)) + + assert frame["fuente_id"].tolist() == ["kept-10", "kept-20"] + assert frame["fecha_indice"].tolist() == [date(2025, 1, 1), date(2025, 2, 1)] and list(frame.columns) == SCHEMA.names + + +def test_a_member_without_events_is_refused(events): """Pins down: every member has at least one row, so a timeline that lost someone stops the export. Fails if the - file is written with fewer members than the build.""" + file is written with fewer members than the population.""" with pytest.raises(ValueError, match="1 members"): - script.build_table([e for e in events if e["pac_id"] != 20], MEMBERS, build, domain="cacu", parametros=None) + cohort_events([e for e in events if e["pac_id"] != 20], POPULATION, date(2025, 12, 31)) -def test_file_is_written_once(script, build, events, tmp_path): - """Pins down: a second run reuses the file without rebuilding it. Fails if `ensure` calls `make_table` again.""" - calls = [] +def test_the_hash_follows_the_rows_only(events): + """Pins down: the same rows hash the same however they arrive, and another row changes the hash. Fails if the hash + takes in the input order or misses a row.""" + one = content_sha256(cohort_events(events, POPULATION, date(2025, 12, 31))) + reordered = content_sha256(cohort_events(events[::-1], POPULATION, date(2025, 12, 31))) + longer = content_sha256(cohort_events(events, POPULATION, date(2026, 12, 31))) - def make_table(): - calls.append(1) - return script.build_table(events, MEMBERS, build, domain="cacu", parametros=None) + assert one == reordered != longer - path, first = script.ensure(build, tmp_path, make_table) - _, second = script.ensure(build, tmp_path, make_table) + +def test_kit_build_is_written_once_with_its_lineage(kit, events, tmp_path): + """Pins down: the kit's build goes to `.parquet` with its identity and cut-off, and a second run reuses it + without reading the timeline. Fails if the lineage loses a key a reader relies on, or the export repeats.""" + timeline = _Timeline(events) + + path, first = export_kit_build(kit, timeline, tmp_path, "cacu", URL) + _, second = export_kit_build(kit, timeline, tmp_path, "cacu", URL) assert path == tmp_path / "cacu" / "cohorte_vigilancia" / "1.parquet" - assert (first, second, len(calls)) == ("exported", "reused", 1) - assert pq.read_metadata(path).num_rows == 2 + assert (first, second, timeline.reads) == ("exported", "reused", 1) + lineage = read_metadata(path) + assert lineage["armado_id"] == "1" and lineage["n_members"] == "2" and lineage["producer"] == "kit" + assert lineage["datos_as_of"] == "2025-12-31" and lineage["parametros"] == '{"corte": "2025-12-31"}' -def test_file_of_another_build_is_refused(script, build, events, tmp_path): - """Pins down: a file whose lineage names another build isn't reused. Fails if `ensure` trusts the path alone.""" - other = tmp_path / "cacu" / "cohorte_vigilancia" - other.mkdir(parents=True) - pq.write_table(script.build_table(events, MEMBERS, _build(armado_id=7), domain="cacu", parametros=None), other / "1.parquet") +def test_file_of_another_build_is_refused(kit, events, tmp_path): + """Pins down: a file whose lineage names another build isn't reused. Fails if the export trusts the path alone.""" + other = SimpleNamespace(**{**kit.__dict__, "build": lambda i: _build(armado_id=1, n_miembros=5)}) + export_kit_build(kit, _Timeline(events), tmp_path, "cacu", URL) with pytest.raises(ValueError, match="doesn't belong"): - script.ensure(build, tmp_path, lambda: pytest.fail("must not export")) + export_kit_build(other, _Timeline(None), tmp_path, "cacu", URL) -def test_failed_export_leaves_no_file(script, build, events, tmp_path, monkeypatch): +def test_unknown_kit_build_is_named(kit, tmp_path): + """Pins down: a build that doesn't exist ends in `LookupError` before anything is read. Fails if it exports another.""" + with pytest.raises(LookupError, match="no such build"): + export_kit_build(kit, _Timeline(None), tmp_path, "cacu", URL, build_id=9) + + +def test_dbt_build_writes_its_population_and_attrition(dbt_cohort, events, tmp_path): + """Pins down: dbt's rules give the members, numbered in the `dbt/` folder, with their parameters, rules and attrition + in the lineage. Fails if the export ignores the rules, or the file lands where the kit's builds are looked for.""" + path, outcome = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu") + + assert (path, outcome) == (tmp_path / "cacu" / "cohorte_vigilancia" / "dbt" / "1.parquet", "exported") + assert sorted(set(pq.read_table(path).column("pac_id").to_pylist())) == [10, 20] + lineage = read_metadata(path) + assert lineage["producer"] == "dbt" and lineage["build"] == "1" and lineage["rules"] == '["third"]' + assert '"step":"third","n":2,"excluded":1' in lineage["attrition"] and len(lineage["content_sha256"]) == 64 + + +def test_dbt_build_is_reused_until_its_rows_change(dbt_cohort, events, tmp_path): + """Pins down: building again with the same rows writes nothing; new rows write the next number. Fails if every run + writes a file, or a change is missed.""" + first, _ = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu") + again, outcome = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu") + more = [*events, _event(20, "2025-04-01", "new-20")] + second, changed = export_dbt_build(dbt_cohort, _query, _Timeline(more), tmp_path, "cacu") + + assert (again, outcome) == (first, "reused") + assert (second.name, changed) == ("2.parquet", "exported") + + +def test_failed_write_leaves_no_file(events, tmp_path, monkeypatch): """Pins down: when the last step of the write fails, neither the file nor the temporary one stays behind, so a later run can't take a partial file as the build's. Fails if `write_once` stops removing the temporary file.""" - table = script.build_table(events, MEMBERS, build, domain="cacu", parametros=None) + table = pq.read_table(export_kit_build(SimpleNamespace(latest_build=lambda u: 1, build=lambda i: _build(), members=lambda i: MEMBERS, + get=lambda i: SimpleNamespace(parametros=None)), + _Timeline(events), tmp_path / "first", "cacu", URL)[0]) def fail(*_): raise OSError("disk full") monkeypatch.setattr(Path, "replace", fail) with pytest.raises(OSError, match="disk full"): - script.write_once(table, tmp_path / "cacu" / "1.parquet") + write_once(table, tmp_path / "cacu" / "1.parquet") assert not list((tmp_path / "cacu").iterdir()) -@pytest.mark.parametrize("url", ["sqlite:////data/cacu.db", "sqlite:///file:/data/cacu.db?immutable=1&uri=true"]) -def test_files_live_next_to_the_database(script, monkeypatch, url): - """Pins down: `cohorts/` next to the SQLite file, in both URL forms. Fails if a read-only URL's `file:` prefix - ends up in the path.""" +def test_files_live_next_to_the_database(monkeypatch): + """Pins down: `cohorts/` next to the SQLite file. Fails if the default folder moves.""" monkeypatch.delenv("COHORTS_DIR", raising=False) - assert script.cohorts_root(url) == Path("/data/cohorts") + assert cohorts_root("sqlite:////data/cacu.db") == Path("/data/cohorts") -def test_cohorts_dir_replaces_the_folder(script, monkeypatch): +def test_cohorts_dir_replaces_the_folder(monkeypatch): """Pins down: `COHORTS_DIR` wins, for read-only data folders and server engines. Fails if it's ignored.""" monkeypatch.setenv("COHORTS_DIR", "/writable") - assert script.cohorts_root("mysql://host/cacu") == Path("/writable") + assert cohorts_root("mysql://host/cacu") == Path("/writable") -def test_server_engine_needs_cohorts_dir(script, monkeypatch): - """Pins down: a server database has no data folder, so the script says what to set. Fails if it guesses a path.""" +def test_server_engine_needs_cohorts_dir(monkeypatch): + """Pins down: a server database has no data folder, so the export says what to set. Fails if it guesses a path.""" monkeypatch.delenv("COHORTS_DIR", raising=False) with pytest.raises(ValueError, match="COHORTS_DIR"): - script.cohorts_root("mysql://host/cacu") + cohorts_root("mysql://host/cacu") -@pytest.fixture -def timeline_db(tmp_path): - """A SQLite file with one event behind a `cacu_linea_de_tiempo` view, and a repository over it.""" - path = tmp_path / "cacu.db" - connection = sqlite3.connect(path) - connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})") - connection.execute("create view cacu_linea_de_tiempo as select * from eventos") - connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a', null, 't', '1')") - connection.commit() - connection.close() - engine = create_engine(f"sqlite:///{path}") - return path, TimelineRepository(lambda: Session(engine)) +def test_the_command_exports_from_dbt_through_the_session(cacu_db, tmp_path, monkeypatch, capsys): + """Pins down: `cohorts export --source dbt` reads the manifest, runs the rules and the timeline through the domain's + session and writes the file, then reuses it. Fails if the wiring to the session, the manifest or the folder changes.""" + import json + + from persistance.db import get_cacu_engine + + with get_cacu_engine().begin() as connection: + connection.execute(text("create view cacu_linea_de_tiempo as select 10 as pac_id, '2025-02-01' as fecha, " + "'2025-02-02 10:00:00' as conocida_en, 'medicion' as clase, 'bethesda' as tipo, 'bethesda' as codigo, " + "'NORMAL' as valor_codigo, null as valor_numerico, 't' as fuente_tabla, '1' as fuente_id")) + nodes = [ + {"name": "p", "kind": "population", "sql": "select 10 as pac_id union all select 20", + "meta": {"cutoff": "2025-12-31", "parameters": '{"cutoff": "2025-12-31"}'}}, + {"name": "i", "kind": "index", "sql": "select 10 as pac_id, '2025-01-01' as fecha_indice union all select 20, '2025-01-01'"}, + {"name": "x", "kind": "exclusion", "sql": "select 20 as pac_id", "meta": {"name": "only", "order": 1}}, + ] + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({"nodes": {n["name"]: { + "name": n["name"], "unique_id": n["name"], "description": "", "compiled_code": n["sql"], "depends_on": {"nodes": []}, + "config": {"meta": {"cohort": URL, "kind": n["kind"], **n.get("meta", {})}}} for n in nodes}})) + monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) + command = ["cohorts", "export", "cacu", "cohorte_vigilancia", "--source", "dbt", "--manifest", str(manifest)] + + assert main(command) == 0 and main(command) == 0 + + out = capsys.readouterr().out + assert "exported:" in out and "reused:" in out + assert pq.read_table(tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "1.parquet").column("pac_id").to_pylist() == [10] -def test_read_timeline_reads_the_view_and_changes_nothing(script, timeline_db): - """Pins down: the rows come from the domain's view, with the column contract, and the read adds no object. Fails - if the script reads another relation, or starts creating objects in the database.""" - path, repository = timeline_db +@pytest.mark.parametrize("arguments, message", [ + (["--source", "dbt"], "needs --manifest"), + (["--source", "dbt", "--manifest", "m.json", "--build", "1"], "can't go with --source dbt"), +]) +def test_dbt_source_arguments_are_checked(arguments, message, capsys): + """Pins down: `--source dbt` needs the manifest and takes no kit build. Fails if either combination runs.""" + with pytest.raises(SystemExit) as stopped: + main(["cohorts", "export", "cacu", "cohorte_vigilancia", *arguments]) - rows = script.read_timeline(repository, "cacu") - - assert [(row["pac_id"], row["valor_codigo"]) for row in rows] == [(10, "a")] - connection = sqlite3.connect(path) - assert connection.execute("select name from sqlite_master order by name").fetchall() == [("cacu_linea_de_tiempo",), ("eventos",)] - connection.close() - - -def test_missing_view_says_how_to_create_it(script, timeline_db): - """Pins down: without the view the error names the dbt command to run. Fails if the driver's error reaches the - user unexplained, or if the message stops naming the domain's model.""" - _, repository = timeline_db - - with pytest.raises(script.TimelineViewError, match="dbt run --select cama_linea_de_tiempo"): - script.read_timeline(repository, "cama") + assert stopped.value.code == 2 and message in capsys.readouterr().err From 3853cc552265602cf697fc349348036c74809ff2 Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 5 Nov 2026 18:21:06 -0600 Subject: [PATCH 23/28] Training, estimating and running on dbt cohort builds: runs and versions record the cohort file they used --- models/__main__.py | 44 +++++++++++++++++------ models/cacu/cin2_logistic/estimate.py | 17 ++++----- models/cacu/cin2_logistic/model.py | 9 +++-- models/io/lineage.py | 11 ++++++ models/io/registry.py | 3 +- models/io/tracking.py | 15 +++++--- tests/cacu/test_cin2_logistic.py | 52 +++++++++++++++++++++++++-- 7 files changed, 122 insertions(+), 29 deletions(-) diff --git a/models/__main__.py b/models/__main__.py index 347cd9c..278f769 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -32,20 +32,30 @@ def _cohort_file(args: argparse.Namespace, model): """The build's exported file; `None` and a message on stderr if it's missing.""" from persistance.settings import settings - from models.io.storage import cohorts_root, find_cohort_file + from models.io.storage import cohorts_root, dbt_build_path, find_cohort_file, latest_dbt_build + url = model.SETTINGS["cohort"] + command = f"python -m models cohorts export {url.replace('/', ' ')}" + (" --source dbt" if args.source == "dbt" else "") try: root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) - return find_cohort_file(root, model.SETTINGS["cohort"], args.armado) + if args.source == "kit": + return find_cohort_file(root, url, args.armado) + if args.armado is not None: + if not (path := dbt_build_path(root, url, args.armado)).exists(): + raise FileNotFoundError(f"dbt build {args.armado} of {url} isn't exported: no {path}") + return path + if not (latest := latest_dbt_build(root, url)): + raise FileNotFoundError(f"no exported dbt builds of {url} under {root}") + return latest[1] except (FileNotFoundError, ValueError) as error: - print(f"{error}: export it with `python -m models cohorts export {model.SETTINGS['cohort'].replace('/', ' ')}`", file=sys.stderr) + print(f"{error}: export it with `{command}`", file=sys.stderr) return None def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: """Trains the model on the build's file, always as a new version.""" if args.environment == "prod" and args.armado is None: - parser.error("a prod run names its cohort build: --armado (ML-03)") + parser.error("a prod run names its cohort build: --build (ML-03)") if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")): return 1 if not (path := _cohort_file(args, model)): @@ -98,8 +108,12 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: parser.error("name at least one step: --export, --train, --promote, --estimate") if args.estimate and not args.output: parser.error("--estimate needs --output") - if args.train and args.environment == "prod" and args.armado is None: - parser.error("a prod run names its cohort build: --armado (ML-03)") + if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"): + parser.error("a prod run names its cohort build: --build (ML-03)") + if args.export and args.source == "dbt" and not args.manifest: + parser.error("--export with --source dbt needs --manifest") + if args.export and args.source == "dbt" and args.armado is not None: + parser.error("a dbt build is numbered when it's exported: --build can't go with --export --source dbt") if args.train and args.version: parser.error("--version names an existing version: it can't go with --train") if not (model := _model_module(args, "model")): @@ -107,7 +121,10 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: if args.export: cohort = model.SETTINGS["cohort"].split("/", 1)[1] - export = argparse.Namespace(domain=args.domain, cohort=cohort, source="kit", build=args.armado, manifest=None) + export = argparse.Namespace(domain=args.domain, cohort=cohort, source=args.source, build=args.armado, + manifest=args.manifest) + if args.source == "dbt": + export.build = None if code := _cohort_export(export): return code if not (args.train or args.promote or args.estimate): @@ -234,7 +251,9 @@ def build_parser() -> argparse.ArgumentParser: train = commands.add_parser("train", help="train a model on a cohort build's file and register a version") train.add_argument("domain", choices=["cacu", "cama", "tea"]) train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") - train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default") + train.add_argument("--build", "--armado", dest="armado", type=int, + help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") + train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") train.add_argument("--environment", choices=["dev", "prod"], default="dev") train.set_defaults(run=lambda args: _train(train, args)) @@ -242,7 +261,9 @@ def build_parser() -> argparse.ArgumentParser: estimate.add_argument("domain", choices=["cacu", "cama", "tea"]) estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") estimate.add_argument("--output", required=True, help="the Parquet file to write") - estimate.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default") + estimate.add_argument("--build", "--armado", dest="armado", type=int, + help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") + estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") estimate.add_argument("--version", help="the model version; the one in production by default") estimate.set_defaults(run=_estimate) @@ -253,10 +274,13 @@ def build_parser() -> argparse.ArgumentParser: run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists") run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version") run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production") - run.add_argument("--armado", type=int, help="the build's armado_id; the latest by default") + run.add_argument("--build", "--armado", dest="armado", type=int, + help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") + run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") run.add_argument("--version", help="an existing model version, for --promote and --estimate") run.add_argument("--environment", choices=["dev", "prod"], default="dev") run.add_argument("--output", help="the Parquet file --estimate writes") + run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt") run.set_defaults(run=lambda args: _run(run, args)) return parser diff --git a/models/cacu/cin2_logistic/estimate.py b/models/cacu/cin2_logistic/estimate.py index 9d17514..f0deb7a 100644 --- a/models/cacu/cin2_logistic/estimate.py +++ b/models/cacu/cin2_logistic/estimate.py @@ -7,31 +7,32 @@ import pyarrow as pa from models.cacu.cin2_logistic.model import SETTINGS from models.io.contracts import ESTIMATE_COLUMNS -from models.io.lineage import matches +from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches from models.io.registry import ResolvedVersion, registered_name, registry from models.io.storage import read_cohort, read_metadata, write_once -def already_estimated(output_path: Path, version: str, armado_id: str) -> bool: - """Whether the output file already holds this version's scores of this build.""" - return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, "armado_id": armado_id}) +def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool: + """Whether the output file already holds this version's scores of this build's file.""" + return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort}) def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]: """Uses the version holding the production alias unless given one, and returns it and whether it wrote the file. - The file's metadata says which version and build its rows come from; `modelo_sha` is copied when the version has + The file's metadata says which version and which build's file (`models.io.lineage.cohort_reference`) its rows + come from; `modelo_sha` is copied when the version has it, and isn't checked.""" domain, scenario = SETTINGS["domain"], SETTINGS["scenario"] output_path = Path(output_path) resolved = registry.resolve(domain, scenario, version) - armado_id = read_metadata(cohort_path)["armado_id"] - if already_estimated(output_path, resolved.version, armado_id): + cohort = cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path)) + if already_estimated(output_path, resolved.version, cohort): return resolved, False risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path)) if tuple(risks.columns) != ESTIMATE_COLUMNS: raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}") provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version, - "mlflow_run_id": resolved.run_id, "armado_id": armado_id} + "mlflow_run_id": resolved.run_id, **cohort} if resolved.modelo_sha: provenance["modelo_sha"] = resolved.modelo_sha table = pa.Table.from_pandas(risks, preserve_index=False) diff --git a/models/cacu/cin2_logistic/model.py b/models/cacu/cin2_logistic/model.py index fe78f01..9fdeed8 100644 --- a/models/cacu/cin2_logistic/model.py +++ b/models/cacu/cin2_logistic/model.py @@ -15,7 +15,7 @@ import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.metrics import brier_score_loss, roc_auc_score -from models.io.lineage import file_sha256 +from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256 from models.io.registry import registry from models.io.storage import read_cohort, read_metadata from models.io.tracking import TrainingRun @@ -97,9 +97,12 @@ class Cin2Logistic(mlflow.pyfunc.PythonModel): def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str, code_sha256: str, environment: str) -> str: - """Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content.""" + """Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content, + and which build it is, from the kit or from dbt's rules.""" + cohort = cohort_reference(lineage, cohort_sha256) + armado_id = int(lineage["armado_id"]) if cohort[COHORT_SOURCE_TAG] == "kit" else None run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment, - cohorte_armado_id=int(lineage["armado_id"])) + cohorte_armado_id=armado_id, cohort=cohort) run.log_model(Cin2Logistic(fit)) run.finish(metrics=evaluate, hyperparameters={ "cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256}) diff --git a/models/io/lineage.py b/models/io/lineage.py index 2890fdb..81ed871 100644 --- a/models/io/lineage.py +++ b/models/io/lineage.py @@ -16,6 +16,8 @@ MODEL_SHA_TAG = "modelo_sha" GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets GIT_DIRTY_TAG = "models.git.dirty" GIT_COMMIT_ENV = "MODELS_GIT_COMMIT" +COHORT_URL_TAG, COHORT_SOURCE_TAG = "cohort.url", "cohort.source" +COHORT_BUILD_TAG, COHORT_FILE_TAG = "cohort.build", "cohort.file_sha256" def registered_name(domain: str, scenario: str) -> str: @@ -44,6 +46,15 @@ def model_sha(model_dir: str | Path) -> str: return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest() +def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]: + """How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or + `dbt`), its number in that source and the file's hash. A kit build's number is its `armado_id`.""" + source = metadata.get("producer", "kit") + build = metadata["armado_id"] if source == "kit" else metadata["build"] + return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build), + COHORT_FILE_TAG: file_sha256} + + def file_sha256(*paths: str | Path) -> str: """The hash of these files' bytes, in this order.""" digest = hashlib.sha256() diff --git a/models/io/registry.py b/models/io/registry.py index 6b95a01..f7784aa 100644 --- a/models/io/registry.py +++ b/models/io/registry.py @@ -148,7 +148,7 @@ class ModelRegistry: def register_run(self, run: TrainingRun, **reports: str | None) -> str: """Registers a run as a new version of `-`, tagged with the promotion inputs (environment, - cohort link, `modelo_sha`, report URIs), and returns the version.""" + cohort link and cohort file, `modelo_sha`, report URIs), and returns the version.""" unknown = set(reports) - set(REPORT_TAGS) if unknown: raise ValueError(f"campos desconocidos: {sorted(unknown)}") @@ -161,6 +161,7 @@ class ModelRegistry: version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value} if run.cohorte_armado_id is not None: version_tags[ARMADO_TAG] = str(run.cohorte_armado_id) + version_tags.update(run.cohort) if run.modelo_sha is not None: version_tags[MODEL_SHA_TAG] = run.modelo_sha version_tags.update({key: uri for key, uri in reports.items() if uri}) diff --git a/models/io/tracking.py b/models/io/tracking.py index b513474..877b9f0 100644 --- a/models/io/tracking.py +++ b/models/io/tracking.py @@ -72,9 +72,10 @@ def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | class TrainingRun: """One instance per training execution, wrapping one MLflow run. PROD - runs require `cohorte_armado_id`, the indicator kit cohort build they were - trained on, so their metrics trace back to that data (ML-03); dev runs may - omit it. + runs name the cohort build they were trained on, so their metrics trace + back to that data (ML-03): `cohort`, the reference to its file + (`models.io.lineage.cohort_reference`), or `cohorte_armado_id`, a kit build + by number; dev runs may omit both. """ def __init__( @@ -84,17 +85,19 @@ class TrainingRun: scenario: str, environment: Environment | str, cohorte_armado_id: int | None = None, + cohort: dict[str, str] | None = None, ): if domain not in DOMAINS: raise ValueError(f"dominio desconocido: {domain!r}") environment = Environment(environment) - if environment is Environment.PROD and cohorte_armado_id is None: - raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).") + if environment is Environment.PROD and cohorte_armado_id is None and cohort is None: + raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id o cohort).") self.domain = domain self.scenario = scenario self.environment = environment self.cohorte_armado_id = cohorte_armado_id + self.cohort = dict(cohort or {}) self.client = MlflowClient() experiment_id = self._experiment_id() run = self.client.create_run( @@ -105,6 +108,8 @@ class TrainingRun: self.modelo_sha: str | None = None if cohorte_armado_id is not None: self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id)) + for tag, value in self.cohort.items(): + self.client.set_tag(self.run_id, tag, value) def _experiment_id(self) -> str: name = registered_name(self.domain, self.scenario) diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py index 7b506cb..fc3afcf 100644 --- a/tests/cacu/test_cin2_logistic.py +++ b/tests/cacu/test_cin2_logistic.py @@ -136,7 +136,7 @@ def test_prod_without_a_build_is_refused(capsys): with pytest.raises(SystemExit) as stopped: main(["train", "cacu", "cin2_logistic", "--environment", "prod"]) - assert stopped.value.code == 2 and "--armado" in capsys.readouterr().err + assert stopped.value.code == 2 and "--build" in capsys.readouterr().err @pytest.mark.parametrize("arguments, message", [ @@ -166,7 +166,7 @@ def test_estimate_scores_each_member_with_the_production_version(exported, mlflo assert list(risks.columns) == ["pac_id", "fecha_indice", "probabilidad"] assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all() metadata = pq.read_metadata(output).metadata - assert metadata[b"modelo_version"] == b"1" and metadata[b"armado_id"] == b"12" + assert metadata[b"modelo_version"] == b"1" and metadata[b"cohort.build"] == b"12" and metadata[b"cohort.source"] == b"kit" def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path): @@ -291,3 +291,51 @@ def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_track assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)] assert not _versions() + + +@pytest.fixture +def dbt_exported(cohort_frame, tmp_path, monkeypatch): + """Builds 1 and 2 of dbt's rules under `COHORTS_DIR`, in the `dbt/` folder the export writes to; build 2 lacks member 1.""" + folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" + for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])): + path = folder / f"{number}.parquet" + path.parent.mkdir(parents=True, exist_ok=True) + table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False) + pq.write_table(table.replace_schema_metadata({"build": str(number), "producer": "dbt", "url": "cacu/cohorte_vigilancia"}), path) + monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) + return folder + + +def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported, mlflow_tracking, capsys): + """Pins down: `--source dbt` trains on the latest dbt build, and the version points to that file (cohort, source, + number, hash) with no kit `armado_id`, which would name a kit build that doesn't exist. Fails if the dbt folder is + ignored, or the version loses its cohort file.""" + assert main(["train", "cacu", "cin2_logistic", "--source", "dbt"]) == 0 + + tags = registry.get("cacu", "cin2_logistic", "1").tags + assert ARMADO_TAG not in tags + assert (tags["cohort.source"], tags["cohort.build"], tags["cohort.url"]) == ("dbt", "2", "cacu/cohorte_vigilancia") + assert len(tags["cohort.file_sha256"]) == 64 and "dbt/2.parquet" in capsys.readouterr().out + + +def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, mlflow_tracking, tmp_path): + """Pins down: a PROD version from dbt build 1 is linked to that build (ML-03) without a kit build, and estimating + it writes the same file reference. Fails if PROD still demands a kit `armado_id`, or `--build` stops choosing the + dbt file.""" + output = tmp_path / "output.parquet" + + assert main(["run", "cacu", "cin2_logistic", "--source", "dbt", "--build", "1", "--environment", "prod", + "--train", "--promote", "--estimate", "--output", str(output)]) == 0 + + tags = registry.get("cacu", "cin2_logistic", "1").tags + assert tags["environment"] == "PROD" and tags["cohort.build"] == "1" + metadata = pq.read_metadata(output).metadata + assert metadata[b"cohort.source"] == b"dbt" and metadata[b"cohort.build"] == b"1" + assert metadata[b"cohort.file_sha256"].decode() == tags["cohort.file_sha256"] + + +def test_a_missing_dbt_build_says_how_to_export_it(dbt_exported, capsys): + """Pins down: a dbt build that isn't exported ends with exit 1 and the dbt export command. Fails if the kit's + command is suggested or another build is used.""" + assert main(["train", "cacu", "cin2_logistic", "--source", "dbt", "--build", "9"]) == 1 + assert "--source dbt" in capsys.readouterr().err From 22d1fda0f37c01dc9f93c30756d53742dde3783e Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:15:12 -0600 Subject: [PATCH 24/28] CaCu CIN2+ prototype: a CIN2+ biopsy within a provisional 12-month window, predicted from the index sample's results --- README.md | 2 +- models/cacu/cin2_logistic/model.py | 93 +++++++++++++++------ models/cacu/cin2_logistic/model.toml | 10 ++- tests/cacu/test_cin2_logistic.py | 120 ++++++++++++++++++--------- 4 files changed, 159 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index 510658b..165f792 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ WebApi. | `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. | | `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. | | `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/.parquet` and writes only when its rows change. The timeline comes from dbt's view `_linea_de_tiempo`. | -| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. Estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--armado N] [--version N]` (`estimate.py`); by default it uses the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | +| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | | `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. | diff --git a/models/cacu/cin2_logistic/model.py b/models/cacu/cin2_logistic/model.py index 9fdeed8..4e8c8d3 100644 --- a/models/cacu/cin2_logistic/model.py +++ b/models/cacu/cin2_logistic/model.py @@ -1,19 +1,25 @@ -"""CaCu's dummy model: it tests the chain from a cohort build's file to a registered version. +"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology. -No clinical meaning. `y` is 1 if any Bethesda result isn't `NORMAL`, and `days` runs from the index date to the first -abnormal result, or to the last result when `y` is 0. `days` is only known after the outcome, so the metrics say -nothing about performance. +`y` is 1 when a biopsy graded in `event_grades` falls within `outcome_window_months` of the index date. A member with +no such biopsy whose follow-up to the build's cut-off (`datos_as_of`) is shorter than the window isn't known yet: +it's scored but left out of training and evaluation. The predictors are the index sample's own results (Bethesda +category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported; +nothing after them is used. Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver. """ import tomllib +from datetime import date from pathlib import Path import mlflow.pyfunc import pandas as pd +from sklearn.compose import ColumnTransformer from sklearn.linear_model import LogisticRegression from sklearn.metrics import brier_score_loss, roc_auc_score +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import OneHotEncoder from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256 from models.io.registry import registry @@ -21,7 +27,9 @@ from models.io.storage import read_cohort, read_metadata from models.io.tracking import TrainingRun SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text()) -NORMAL = "NORMAL" +PREDICTORS = ("bethesda", "vph", "vph_16_18") +MISSING = "(none)" +DAYS_PER_MONTH = 30.44 def cohort(cohort_path: str) -> pd.DataFrame: @@ -42,16 +50,44 @@ def code_sha256() -> str: return file_sha256(folder / "model.py", folder / "model.toml") -def prepare(cohort: pd.DataFrame) -> pd.DataFrame: - """One row per member with a Bethesda result: `pac_id`, `fecha_indice`, `y`, `days`.""" - results = cohort[cohort["tipo"] == "bethesda"].copy() - results["days"] = (pd.to_datetime(results["fecha"]) - pd.to_datetime(results["fecha_indice"])).dt.days - results["abnormal"] = results["valor_codigo"] != NORMAL - members = results.groupby(["pac_id", "fecha_indice"], as_index=False).agg(y=("abnormal", "any"), last=("days", "max")) - first_abnormal = results[results["abnormal"]].groupby("pac_id")["days"].min() - members["days"] = members["pac_id"].map(first_abnormal).fillna(members["last"]).astype(int) - members["y"] = members["y"].astype(int) - return members[["pac_id", "fecha_indice", "y", "days"]] +def cutoff(lineage: dict) -> date: + """The build's cut-off: no event after it is in the file.""" + return date.fromisoformat(lineage["datos_as_of"]) + + +def predictors(cohort: pd.DataFrame) -> pd.DataFrame: + """One row per member: `pac_id`, `fecha_indice` and the index sample's results, `(none)` where it has none.""" + members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]] + sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] == cohort["fecha_indice"])] + sample = sample.groupby("pac_id")["fuente_id"].first().rename("sample") + results = cohort.merge(sample, left_on="pac_id", right_index=True) + results = results[results["fuente_id"] == results["sample"]] + genotype = results["tipo"] == "vph_genotipo_16_18" + results.loc[genotype, "valor_codigo"] = results.loc[genotype, "valor_numerico"].map({1.0: "POSITIVO", 0.0: "NEGATIVO"}) + results["tipo"] = results["tipo"].replace({"vph_genotipo_16_18": "vph_16_18"}) + wide = results[results["tipo"].isin(PREDICTORS)].pivot_table( + index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first") + wide = wide.reindex(columns=list(PREDICTORS)) + return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna( + {name: MISSING for name in PREDICTORS}) + + +def outcome(cohort: pd.DataFrame, cutoff: date) -> pd.DataFrame: + """One row per member: `y`, and `known`, whether the window is complete or the event already happened.""" + window = SETTINGS["outcome_window_months"] * DAYS_PER_MONTH + days = (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days + event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(SETTINGS["event_grades"]) & days.between(0, window) + members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]] + members["y"] = members["pac_id"].isin(cohort.loc[event, "pac_id"]).astype(int) + follow_up = (pd.Timestamp(cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days + members["known"] = (members["y"] == 1) | (follow_up >= window) + return members[["pac_id", "y", "known"]] + + +def prepare(predictors: pd.DataFrame, outcome: pd.DataFrame) -> pd.DataFrame: + """The members whose outcome is known, with their predictors and `y`.""" + labelled = predictors.merge(outcome, on="pac_id") + return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True) def split(prepare: pd.DataFrame) -> dict: @@ -69,33 +105,38 @@ def test(split: dict) -> pd.DataFrame: return split["test"] -def fit(train: pd.DataFrame) -> LogisticRegression: - return LogisticRegression().fit(train[["days"]], train["y"]) +def fit(train: pd.DataFrame) -> Pipeline: + """One-hot predictors, an unseen category counted as none of the known ones, and a logistic regression.""" + encode = ColumnTransformer([("results", OneHotEncoder(handle_unknown="ignore"), list(PREDICTORS))]) + return Pipeline([("encode", encode), ("logistic", LogisticRegression(max_iter=1000))]).fit( + train[list(PREDICTORS)], train["y"]) -def predict(fit: LogisticRegression, test: pd.DataFrame) -> pd.Series: +def predict(fit: Pipeline, test: pd.DataFrame) -> pd.Series: """The probability of `y` for each row of `test`.""" - return pd.Series(fit.predict_proba(test[["days"]])[:, 1], index=test.index, name="probabilidad") + return pd.Series(fit.predict_proba(test[list(PREDICTORS)])[:, 1], index=test.index, name="probabilidad") def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dict: """Aggregates only: no patient data reaches MLflow.""" return {"auc": float(roc_auc_score(test["y"], predict)), "brier": float(brier_score_loss(test["y"], predict)), - "n_train": len(train), "n_test": len(test), "positive_rate_test": float(test["y"].mean())} + "n_train": len(train), "n_test": len(test), "positive_rate_train": float(train["y"].mean()), + "positive_rate_test": float(test["y"].mean()), "mean_probability_test": float(predict.mean())} class Cin2Logistic(mlflow.pyfunc.PythonModel): - """The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`.""" + """The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad` + for every member, whether their outcome is known or not.""" - def __init__(self, fitted: LogisticRegression): + def __init__(self, fitted: Pipeline): self.fitted = fitted def predict(self, context, model_input, params=None): - members = prepare(model_input) + members = predictors(model_input) return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members)) -def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str, +def registered_model(fit: Pipeline, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str, code_sha256: str, environment: str) -> str: """Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content, and which build it is, from the kit or from dbt's rules.""" @@ -105,7 +146,9 @@ def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, coh cohorte_armado_id=armado_id, cohort=cohort) run.log_model(Cin2Logistic(fit)) run.finish(metrics=evaluate, hyperparameters={ - "cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256}) + "cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256, + "outcome_window_months": SETTINGS["outcome_window_months"], "event_grades": ",".join(SETTINGS["event_grades"]), + "horizon_years": SETTINGS["outcome_window_months"] / 12}) version = registry.register_run(run) registry.set_description(SETTINGS["domain"], SETTINGS["scenario"], version, SETTINGS["description"]) return version diff --git a/models/cacu/cin2_logistic/model.toml b/models/cacu/cin2_logistic/model.toml index 77a7594..10ebeda 100644 --- a/models/cacu/cin2_logistic/model.toml +++ b/models/cacu/cin2_logistic/model.toml @@ -2,6 +2,12 @@ domain = "cacu" scenario = "cin2_logistic" cohort = "cacu/cohorte_vigilancia" train_fraction = 0.7 +# Provisional, to be decided with the domain expert: the window in which a CIN2+ biopsy counts as the outcome. On the +# DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 24-month window leaves no member with a +# complete window; 12 months leaves 5,231 known members, 162 with the event. +outcome_window_months = 12 +event_grades = ["LIEAG", "CIS", "CARCINOMA"] description = """ -Modelo de prueba de la cadena de entrenamiento, sin significado clínico. Los días se conocen solo después del \ -desenlace, así que sus métricas no dicen nada sobre su desempeño.""" +Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \ +a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \ +validación clínica.""" diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py index fc3afcf..b9ea0fb 100644 --- a/tests/cacu/test_cin2_logistic.py +++ b/tests/cacu/test_cin2_logistic.py @@ -1,10 +1,11 @@ -"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal -split, that training on a build's file registers a version with its lineage, and the `models train` and -`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none. +"""What this module covers: `models.cacu.cin2_logistic`: its outcome (a CIN2+ biopsy within the window, with members +whose window isn't complete left out) and predictors (the index sample's results), its temporal split, that training on +a build's file registers a version with its lineage, and the `models train`, `models estimate` and `models run` +commands over it, repeating no step. Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a -build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a -SQLite-backed MLflow. +build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `dbt_exported`, builds 1 and 2 +of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow. """ from datetime import date, datetime, timedelta, timezone @@ -22,88 +23,132 @@ from models.io.contracts import COHORT_SCHEMA as SCHEMA from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG from models.io.registry import PRODUCTION_ALIAS, registry +CUTOFF = date(2027, 6, 30) -def _row(pac_id, index, days, valor, tipo="bethesda"): + +def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None): + clase = {"citologia": "procedimiento", "biopsia": "medicion"}.get(tipo, "medicion") return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days), - "conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo, - "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical", - "fuente_id": f"{pac_id}-{tipo}-{days}"} + "conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": clase, "tipo": tipo, "codigo": tipo, + "valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": "citologiacervical", + "fuente_id": sample or f"{pac_id}-{tipo}-{days}"} + + +def _member(pac_id, index, bethesda, vph, biopsy=None, biopsy_day=60): + """The index cytology, its Bethesda and HPV results (same sample, reported on day 7), and a biopsy if given.""" + sample = f"S{pac_id}" + rows = [_row(pac_id, index, 0, "citologia", sample=sample), _row(pac_id, index, 7, "bethesda", bethesda, sample), + _row(pac_id, index, 7, "vph", vph, sample)] + if biopsy: + rows.append(_row(pac_id, index, biopsy_day, "biopsia", biopsy)) + return rows @pytest.fixture def cohort_frame(): - """Odd members become abnormal at day 30 after a normal result; even ones stay normal until day 300. An HPV row - each, which the outcome must ignore.""" + """Odd members: LIEAG and HPV positive at the index sample, then a LIEAG biopsy on day 60 (the event). Even members: + NORMAL and HPV negative, then a second cytology on day 400 graded LIEAG, which the predictors must ignore.""" rows = [] for pac_id in range(1, 21): index = date(2025, 1, 1) + timedelta(days=pac_id) - rows += [_row(pac_id, index, 0, "NORMAL"), _row(pac_id, index, 5, "POSITIVO", tipo="vph")] - rows.append(_row(pac_id, index, 30, "LIEBG") if pac_id % 2 else _row(pac_id, index, 300, "NORMAL")) + if pac_id % 2: + rows += _member(pac_id, index, "LIEAG", "POSITIVO", biopsy="LIEAG") + else: + rows += _member(pac_id, index, "NORMAL", "NEGATIVO") + rows += [_row(pac_id, index, 400, "citologia", sample=f"T{pac_id}"), + _row(pac_id, index, 405, "bethesda", "LIEAG", f"T{pac_id}")] return pd.DataFrame(rows, columns=SCHEMA.names) -def _write(frame, path, armado_id): +def _write(frame, path, metadata): table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False) path.parent.mkdir(parents=True, exist_ok=True) - pq.write_table(table.replace_schema_metadata({"armado_id": str(armado_id), "url": "cacu/cohorte_vigilancia"}), path) + lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), **metadata} + pq.write_table(table.replace_schema_metadata({k: str(v) for k, v in lineage.items()}), path) return path @pytest.fixture def cohort_file(cohort_frame, tmp_path): """The frame as build 7's file.""" - return _write(cohort_frame, tmp_path / "7.parquet", 7) + return _write(cohort_frame, tmp_path / "7.parquet", {"armado_id": 7}) @pytest.fixture def exported(cohort_frame, tmp_path, monkeypatch): """Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to.""" folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" - _write(cohort_frame, folder / "7.parquet", 7) - _write(cohort_frame, folder / "12.parquet", 12) + _write(cohort_frame, folder / "7.parquet", {"armado_id": 7}) + _write(cohort_frame, folder / "12.parquet", {"armado_id": 12}) monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) return folder -def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame): - """Pins down: `y` is 1 with any abnormal result; `days` reaches the first abnormal result, or the last result when - `y` is 0. Fails if another variable's value counts as abnormal, or either date rule changes.""" - prepared = model.prepare(cohort_frame).set_index("pac_id") +def test_predictors_are_the_index_sample_results(cohort_frame): + """Pins down: each member's predictors come from the sample of the index cytology, matched by its source row, and a + result the sample doesn't have is `(none)`. Fails if a later sample's result (member 2's LIEAG on day 405) is + taken, or a missing result becomes NaN, which the encoder would reject.""" + found = model.predictors(cohort_frame).set_index("pac_id") - assert len(prepared) == 20 - assert prepared.loc[1, ["y", "days"]].tolist() == [1, 30] - assert prepared.loc[2, ["y", "days"]].tolist() == [0, 300] + assert len(found) == 20 + assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"] + assert found.loc[2, ["bethesda", "vph"]].tolist() == ["NORMAL", "NEGATIVO"] -def test_first_abnormal_result_sets_days_when_there_are_several(): - """Pins down: with two abnormal results, `days` is the earlier one even if the file's order says otherwise. Fails - if `days` takes the last abnormal result or the first row.""" +def test_the_genotype_is_read_from_its_number(): + """Pins down: the HPV 16/18 result is stored as 1 or 0 in `valor_numerico`, and becomes POSITIVO or NEGATIVO. Fails + if the genotype is read from `valor_codigo`, which is empty for it.""" index = date(2025, 1, 1) - frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")]) + frame = pd.DataFrame(_member(1, index, "ASC-US", "POSITIVO") + + [_row(1, index, 7, "vph_genotipo_16_18", sample="S1", numero=1.0)], columns=SCHEMA.names) - assert model.prepare(frame).loc[0, "days"] == 40 + assert model.predictors(frame).loc[0, "vph_16_18"] == "POSITIVO" + + +@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0), + ("LIEAG", 400, 0)]) +def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected): + """Pins down: `y` is 1 only for a biopsy graded LIEAG, CIS or CARCINOMA within 12 months of the index date. Fails if + a lower grade counts, or a biopsy after the window does.""" + frame = pd.DataFrame(_member(1, date(2025, 1, 1), "NORMAL", "NEGATIVO", biopsy=grade, biopsy_day=day), + columns=SCHEMA.names) + + assert model.outcome(frame, CUTOFF).loc[0, "y"] == expected + + +def test_a_member_without_a_complete_window_is_scored_but_not_trained_on(): + """Pins down: a member with no event and less than the window's follow-up to the cut-off isn't known and is left out + of `prepare`; one with the event is kept however short the follow-up. Fails if unknown members train as negatives, + which biases the risk down.""" + late = date(2027, 3, 1) + frame = pd.DataFrame(_member(1, late, "NORMAL", "NEGATIVO") + _member(2, late, "LIEAG", "POSITIVO", biopsy="CIS", + biopsy_day=30), columns=SCHEMA.names) + outcome = model.outcome(frame, CUTOFF).set_index("pac_id") + + assert outcome["known"].tolist() == [False, True] + assert model.prepare(model.predictors(frame), model.outcome(frame, CUTOFF))["pac_id"].tolist() == [2] def test_split_trains_on_the_oldest_index_dates(cohort_frame): """Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split is random or follows another column.""" - parts = model.split(model.prepare(cohort_frame)) + parts = model.split(model.prepare(model.predictors(cohort_frame), model.outcome(cohort_frame, CUTOFF))) assert (len(parts["train"]), len(parts["test"])) == (14, 6) assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min() def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking): - """Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash and the note that - it has no clinical meaning, and an artifact that holds `prepare`, so it takes the long frame. Fails if any is lost, or - if the driver stops reaching `registered_model`.""" + """Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash, the outcome's + window and the note that it's a prototype, and an artifact that holds `predictors`, so it takes the long frame. Fails + if any is lost, or if the driver stops reaching `registered_model`.""" version = train(cohort_file) resolved = registry.resolve("cacu", "cin2_logistic", version) stored = registry.get("cacu", "cin2_logistic", version) run = registry.client.get_run(stored.run_id).data assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha - assert "sin significado clínico" in stored.description + assert "Prototipo" in stored.description and run.params["outcome_window_months"] == "12" assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics assert len(run.params["cohort_sha256"]) == 64 @@ -239,7 +284,7 @@ def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking): assert main([*RUN, "--train", "--armado", "7"]) == 0 assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0 frame = pd.read_parquet(exported / "12.parquet") - _write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12) + _write(frame[frame["pac_id"] != 1], exported / "12.parquet", {"armado_id": 12}) assert main([*RUN, "--train", "--armado", "12"]) == 0 assert len(_versions()) == 3 @@ -300,8 +345,7 @@ def dbt_exported(cohort_frame, tmp_path, monkeypatch): for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])): path = folder / f"{number}.parquet" path.parent.mkdir(parents=True, exist_ok=True) - table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False) - pq.write_table(table.replace_schema_metadata({"build": str(number), "producer": "dbt", "url": "cacu/cohorte_vigilancia"}), path) + _write(frame, path, {"build": number, "producer": "dbt"}) monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) return folder From 761b5b03bc4a0651819726c392185a58d354b23f Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:21:53 -0600 Subject: [PATCH 25/28] Estimates stored as batches of risks in the domain's database: models store and run --store; a kit file is read as dbt's only when its producer is dbt --- README.md | 1 + models/__main__.py | 40 +++++++-- models/cacu/cin2_logistic/estimate.py | 8 +- models/io/lineage.py | 7 +- models/io/storage.py | 9 +- models/pipelines/store_risks.py | 31 +++++++ models/steps/risks.py | 17 ++++ tests/io/test_lineage.py | 17 +++- tests/test_store_risks.py | 121 ++++++++++++++++++++++++++ 9 files changed, 236 insertions(+), 15 deletions(-) create mode 100644 models/pipelines/store_risks.py create mode 100644 models/steps/risks.py create mode 100644 tests/test_store_risks.py diff --git a/README.md b/README.md index 165f792..6e3532d 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ WebApi. | `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. | | `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. | | `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/.parquet` and writes only when its rows change. The timeline comes from dbt's view `_linea_de_tiempo`. | +| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. | | `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | diff --git a/models/__main__.py b/models/__main__.py index 278f769..b4b31ac 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -77,6 +77,23 @@ def _estimate_step(args: argparse.Namespace, path) -> int: return 0 +def _store_step(args: argparse.Namespace, estimate_path) -> int: + from models.pipelines.store_risks import store_estimate + + try: + batch, written = store_estimate(estimate_path, args.domain) + except (LookupError, ValueError, FileNotFoundError) as error: + print(error, file=sys.stderr) + return 1 + print(f"{'stored' if written else 'already stored'}: batch {batch}, from {estimate_path}") + return 0 + + +def _store(args: argparse.Namespace) -> int: + """Stores an estimate file as a batch of risks in the domain's database.""" + return _store_step(args, args.input) + + def _estimate(args: argparse.Namespace) -> int: """Scores the build's file with a registered version and writes the output file.""" if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)): @@ -104,10 +121,10 @@ def _promote_step(args: argparse.Namespace, version: str) -> int: def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: """Runs the steps asked for, in their order. A step whose result already exists is a no-op.""" - if not (args.export or args.train or args.promote or args.estimate): - parser.error("name at least one step: --export, --train, --promote, --estimate") - if args.estimate and not args.output: - parser.error("--estimate needs --output") + if not (args.export or args.train or args.promote or args.estimate or args.store): + parser.error("name at least one step: --export, --train, --promote, --estimate, --store") + if (args.estimate or args.store) and not args.output: + parser.error("--estimate and --store need --output") if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"): parser.error("a prod run names its cohort build: --build (ML-03)") if args.export and args.source == "dbt" and not args.manifest: @@ -128,7 +145,7 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: if code := _cohort_export(export): return code if not (args.train or args.promote or args.estimate): - return 0 + return _store_step(args, args.output) if args.store else 0 if not (path := _cohort_file(args, model)): return 1 @@ -148,7 +165,9 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: return 1 if args.promote and (code := _promote_step(args, version)): return code - return _estimate_step(args, path) if args.estimate else 0 + if args.estimate and (code := _estimate_step(args, path)): + return code + return _store_step(args, args.output) if args.store else 0 def _cohort_build(args: argparse.Namespace) -> int: @@ -267,6 +286,12 @@ def build_parser() -> argparse.ArgumentParser: estimate.add_argument("--version", help="the model version; the one in production by default") estimate.set_defaults(run=_estimate) + store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database") + store.add_argument("domain", choices=["cacu", "cama", "tea"]) + store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") + store.add_argument("--input", required=True, help="the Parquet file `estimate` wrote") + store.set_defaults(run=_store) + run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops") run.add_argument("domain", choices=["cacu", "cama", "tea"]) run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") @@ -274,12 +299,13 @@ def build_parser() -> argparse.ArgumentParser: run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists") run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version") run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production") + run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks") run.add_argument("--build", "--armado", dest="armado", type=int, help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") run.add_argument("--version", help="an existing model version, for --promote and --estimate") run.add_argument("--environment", choices=["dev", "prod"], default="dev") - run.add_argument("--output", help="the Parquet file --estimate writes") + run.add_argument("--output", help="the Parquet file --estimate writes and --store reads") run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt") run.set_defaults(run=lambda args: _run(run, args)) return parser diff --git a/models/cacu/cin2_logistic/estimate.py b/models/cacu/cin2_logistic/estimate.py index f0deb7a..4014cf6 100644 --- a/models/cacu/cin2_logistic/estimate.py +++ b/models/cacu/cin2_logistic/estimate.py @@ -20,8 +20,8 @@ def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) - def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]: """Uses the version holding the production alias unless given one, and returns it and whether it wrote the file. The file's metadata says which version and which build's file (`models.io.lineage.cohort_reference`) its rows - come from; `modelo_sha` is copied when the version has - it, and isn't checked.""" + come from, and the outcome and horizon they estimate (`cin2_12m`, 1.0 years); `modelo_sha` is copied when the + version has it, and isn't checked.""" domain, scenario = SETTINGS["domain"], SETTINGS["scenario"] output_path = Path(output_path) resolved = registry.resolve(domain, scenario, version) @@ -31,8 +31,10 @@ def estimate(cohort_path: str | Path, output_path: str | Path, version: str | No risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path)) if tuple(risks.columns) != ESTIMATE_COLUMNS: raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}") + window = SETTINGS["outcome_window_months"] provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version, - "mlflow_run_id": resolved.run_id, **cohort} + "mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12), + **cohort} if resolved.modelo_sha: provenance["modelo_sha"] = resolved.modelo_sha table = pa.Table.from_pandas(risks, preserve_index=False) diff --git a/models/io/lineage.py b/models/io/lineage.py index 81ed871..b63e284 100644 --- a/models/io/lineage.py +++ b/models/io/lineage.py @@ -48,9 +48,10 @@ def model_sha(model_dir: str | Path) -> str: def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]: """How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or - `dbt`), its number in that source and the file's hash. A kit build's number is its `armado_id`.""" - source = metadata.get("producer", "kit") - build = metadata["armado_id"] if source == "kit" else metadata["build"] + `dbt`), its number in that source and the file's hash. Only a file whose producer is `dbt` is dbt's; any other is a kit + build, numbered by its `armado_id`.""" + source = "dbt" if metadata.get("producer") == "dbt" else "kit" + build = metadata["build"] if source == "dbt" else metadata["armado_id"] return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build), COHORT_FILE_TAG: file_sha256} diff --git a/models/io/storage.py b/models/io/storage.py index 8b52eb2..d1414b0 100644 --- a/models/io/storage.py +++ b/models/io/storage.py @@ -1,5 +1,5 @@ """Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's -manifest, and a domain's Persistance repositories. +manifest, a domain's Persistance repositories, and the batches of risks they store. The kit's builds are `///.parquet`. The builds of dbt's rules go in a `dbt/` folder beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a @@ -133,6 +133,13 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries: date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}"))) +def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]: + """Writes a batch of risks for a kit build through the domain's `cohorte_repository`: its `lote_id` and whether it's + new. The only write the pipelines make to the database; risks of anyone outside the build are refused.""" + cohorts = importlib.import_module(f"persistance.{domain}").cohorte_repository + return cohorts.guardar_lote(armado_id, provenance, outcome, rows) + + def resolve_repository(domain: str, entity: str): """`entity` is the repository's name in `persistance.` without the suffix, e.g. `"paciente"`, `"citologia_cervical"`.""" diff --git a/models/pipelines/store_risks.py b/models/pipelines/store_risks.py new file mode 100644 index 0000000..e88571b --- /dev/null +++ b/models/pipelines/store_risks.py @@ -0,0 +1,31 @@ +"""Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`). + +The estimate's metadata carries everything the batch needs: the model version and its run (`modelo_nombre`, +`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome and its horizon, and the cohort build it scored. A batch +points to its build by `armado_id`, so only builds with a row in `cohorte_armado` can be stored. Storing the same +estimate again adds nothing: Persistance finds the batch by its content. +""" + +from pathlib import Path + +import pandas as pd + +from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG +from models.io.storage import read_metadata, store_risk_batch +from models.steps.risks import risk_rows + +PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha") +REQUIRED = (*PROVENANCE, "desenlace", "horizonte_anios", COHORT_SOURCE_TAG, COHORT_BUILD_TAG) + + +def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]: + """Returns the batch's `lote_id` and whether it was written now.""" + metadata = read_metadata(estimate_path) + if missing := [key for key in REQUIRED if not metadata.get(key)]: + raise ValueError(f"{estimate_path} lacks {missing}: write it with `python -m models estimate`") + if metadata[COHORT_SOURCE_TAG] != "kit": + raise LookupError(f"{estimate_path} scores {metadata[COHORT_SOURCE_TAG]} build {metadata[COHORT_BUILD_TAG]}, " + "which has no row in cohorte_armado for its batch to point to") + rows = risk_rows(pd.read_parquet(estimate_path), float(metadata["horizonte_anios"])) + return store_risk_batch(domain, int(metadata[COHORT_BUILD_TAG]), {key: metadata[key] for key in PROVENANCE}, + metadata["desenlace"], rows) diff --git a/models/steps/risks.py b/models/steps/risks.py new file mode 100644 index 0000000..b2b2d3c --- /dev/null +++ b/models/steps/risks.py @@ -0,0 +1,17 @@ +"""From an estimate's rows to the risks a batch stores: `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`.""" + +import pandas as pd + +from models.io.contracts import ESTIMATE_COLUMNS + + +def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]: + """One risk per member at the model's horizon, without an interval; a member scored twice stops the batch.""" + if tuple(estimate.columns) != ESTIMATE_COLUMNS: + raise ValueError(f"an estimate has {list(ESTIMATE_COLUMNS)}, not {list(estimate.columns)}") + if estimate["pac_id"].duplicated().any(): + raise ValueError(f"members scored twice: {sorted(estimate.loc[estimate['pac_id'].duplicated(), 'pac_id'])[:10]}") + if not estimate["probabilidad"].between(0, 1).all(): + raise ValueError("a probability outside 0..1") + return [(int(pac_id), float(horizon_years), float(probability), None, None) + for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])] diff --git a/tests/io/test_lineage.py b/tests/io/test_lineage.py index e02e7b8..93e8863 100644 --- a/tests/io/test_lineage.py +++ b/tests/io/test_lineage.py @@ -7,7 +7,7 @@ Fixtures: none; each test builds its own small table or file. import pyarrow as pa import pytest -from models.io.lineage import file_sha256, matches, registered_name, require_match, table_sha256 +from models.io.lineage import cohort_reference, file_sha256, matches, registered_name, require_match, table_sha256 def test_a_table_hashes_by_its_rows_not_its_metadata(): @@ -47,3 +47,18 @@ def test_a_mismatch_is_refused_with_both_sides(): def test_models_are_registered_as_domain_and_scenario(): """Pins down: the name runs and versions share. Fails if the convention changes on one side only.""" assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic" + + +@pytest.mark.parametrize("metadata, expected", [ + ({"url": "u", "producer": "dbt", "build": "4"}, ("dbt", "4")), + ({"url": "u", "producer": "kit", "armado_id": "2"}, ("kit", "2")), + ({"url": "u", "producer": "kit build, timeline from dbt view", "armado_id": "1"}, ("kit", "1")), + ({"url": "u", "armado_id": "3"}, ("kit", "3")), +]) +def test_a_file_is_dbts_only_when_its_producer_says_dbt(metadata, expected): + """Pins down: a cohort file's source is dbt only for `producer: dbt`; any other producer, or none, is a kit build + numbered by `armado_id`. Fails if an older kit file with a descriptive producer is read as dbt's and loses its + `armado_id`.""" + reference = cohort_reference(metadata, "f" * 64) + + assert (reference["cohort.source"], reference["cohort.build"]) == expected diff --git a/tests/test_store_risks.py b/tests/test_store_risks.py new file mode 100644 index 0000000..5e08044 --- /dev/null +++ b/tests/test_store_risks.py @@ -0,0 +1,121 @@ +"""What this module covers: storing an estimate file as a batch of risks (`models.steps.risks`, +`models.io.storage.store_risk_batch`, `models.pipelines.store_risks`) and the `models store` command: one risk per +member at the model's horizon, the batch's MLflow keys, no duplicate batch, and builds without a `cohorte_armado` row +refused. + +Fixtures: `cacu_db` (conftest), an empty CaCu schema on SQLite; `kit_build`, kit build 1 with members 1 to 3; +`estimate_file`, an estimate of those members with the metadata `models estimate` writes. +""" + +from datetime import date, datetime, timezone + +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +import pytest +from sqlmodel import select + +from models.__main__ import main +from models.pipelines.store_risks import store_estimate +from models.steps.risks import risk_rows + +METADATA = {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "3", "mlflow_run_id": "run-a", "modelo_sha": "sha-a", + "desenlace": "cin2_12m", "horizonte_anios": "1.0", "cohort.url": "cacu/cohorte_vigilancia", + "cohort.source": "kit", "cohort.build": "1", "cohort.file_sha256": "f" * 64} + + +def _estimate(pac_ids=(1, 2, 3)): + return pd.DataFrame({"pac_id": list(pac_ids), "fecha_indice": [date(2025, 1, i) for i in pac_ids], + "probabilidad": [0.1 * i for i in pac_ids]}) + + +def _write(frame, path, **metadata): + table = pa.Table.from_pandas(frame, preserve_index=False) + pq.write_table(table.replace_schema_metadata({**table.schema.metadata, **METADATA, **metadata}), path) + return path + + +@pytest.fixture +def kit_build(cacu_db): + """Kit build 1 of the surveillance cohort, with members 1, 2 and 3 (and their `persona` rows).""" + from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, Persona + from persistance.db import get_cacu_session + + with get_cacu_session() as session: + session.add_all(Persona(pac_id=i, pac_id_hospital=f"H{i}") for i in (1, 2, 3)) + session.add(CohorteArmado(armado_id=1, url="cacu/cohorte_vigilancia", version="1", definicion_sha="d", reglas_sha="r", + parametros="{}", datos_as_of=date(2026, 12, 31), huella="h", marco_sha="m", n_miembros=3, + armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))) + session.add_all(CohorteMiembro(armado_id=1, pac_id=i, fecha_indice=date(2025, 1, i), indice_fuente_tabla="t", + indice_fuente_id=str(i)) for i in (1, 2, 3)) + session.commit() + return 1 + + +@pytest.fixture +def estimate_file(tmp_path): + return _write(_estimate(), tmp_path / "estimate.parquet") + + +def _stored(): + from core.cacu.indicadores.models import EvaluacionRiesgo, EvaluacionRiesgoLote + from persistance.db import get_cacu_session + + with get_cacu_session() as session: + return session.exec(select(EvaluacionRiesgoLote)).all(), session.exec(select(EvaluacionRiesgo)).all() + + +def test_each_member_becomes_one_risk_at_the_horizon(): + """Pins down: a risk is `(pac_id, horizonte_anios, probabilidad, None, None)`, one per member. Fails if the horizon is + dropped or the interval is filled with something the model didn't give.""" + assert risk_rows(_estimate((1, 2)), 1.0) == [(1, 1.0, 0.1, None, None), (2, 1.0, 0.2, None, None)] + + +@pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]), + _estimate().rename(columns={"probabilidad": "p"})]) +def test_a_malformed_estimate_stops_the_batch(frame): + """Pins down: a member scored twice, a probability outside 0..1, or other columns stop the batch before anything is + written. Fails if any of them reaches the database.""" + with pytest.raises(ValueError): + risk_rows(frame, 1.0) + + +def test_storing_writes_one_batch_with_the_versions_keys(kit_build, estimate_file): + """Pins down: the batch points to the kit build and to the MLflow version and run, holds the outcome, and its risks + are preliminary version 1 at the horizon. Fails if a key is lost or a risk is stored at another horizon.""" + batch, written = store_estimate(estimate_file, "cacu") + + batches, risks = _stored() + assert written and [b.lote_id for b in batches] == [batch] + assert (batches[0].armado_id, batches[0].modelo_version, batches[0].mlflow_run_id, batches[0].desenlace) == (1, "3", "run-a", "cin2_12m") + assert sorted((r.pac_id, r.horizonte_anios, r.estado, r.version) for r in risks) == [ + (1, 1.0, "preliminary", 1), (2, 1.0, "preliminary", 1), (3, 1.0, "preliminary", 1)] + + +def test_storing_the_same_estimate_again_adds_nothing(kit_build, estimate_file, capsys): + """Pins down: the command is idempotent: the second time it reports the existing batch. Fails if Persistance's + content check stops matching what this module sends.""" + assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0 + assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0 + + assert "already stored: batch 1" in capsys.readouterr().out + assert len(_stored()[0]) == 1 + + +def test_a_dbt_build_has_no_batch_to_point_to(kit_build, tmp_path, capsys): + """Pins down: an estimate of a dbt build is refused with the reason, since a batch needs a `cohorte_armado` row. + Fails if a dbt build's number is taken for a kit `armado_id`, which would point the batch to another build.""" + path = _write(_estimate(), tmp_path / "dbt.parquet", **{"cohort.source": "dbt"}) + + assert main(["store", "cacu", "cin2_logistic", "--input", str(path)]) == 1 + assert "cohorte_armado" in capsys.readouterr().err and not _stored()[0] + + +def test_an_estimate_without_its_keys_is_refused(kit_build, tmp_path): + """Pins down: a file without the version's keys (a hand-made one, or one from an older `estimate`) isn't stored. + Fails if a batch could be written without knowing which model produced it.""" + path = tmp_path / "bare.parquet" + pq.write_table(pa.Table.from_pandas(_estimate(), preserve_index=False), path) + + with pytest.raises(ValueError, match="lacks"): + store_estimate(path, "cacu") From 15ffeb3efecff780eb592d789e5e4cb9c2d750bb Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:28:47 -0600 Subject: [PATCH 26/28] models report eda: the exploratory notebook run on a build's file, rendered with Quarto and kept as an MLflow run of the notebook's experiment --- README.md | 1 + models/__main__.py | 36 ++++++++ models/io/rendering.py | 49 +++++++++++ models/io/tracking.py | 45 ++++++++-- models/pipelines/report_eda.py | 48 +++++++++++ models/steps/report.py | 21 +++++ tests/test_report_eda.py | 148 +++++++++++++++++++++++++++++++++ 7 files changed, 341 insertions(+), 7 deletions(-) create mode 100644 models/io/rendering.py create mode 100644 models/pipelines/report_eda.py create mode 100644 models/steps/report.py create mode 100644 tests/test_report_eda.py diff --git a/README.md b/README.md index 6e3532d..feb22a0 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ WebApi. | `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. | | `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/.parquet` and writes only when its rows change. The timeline comes from dbt's view `_linea_de_tiempo`. | | `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. | +| `steps/report.py`, `io/rendering.py`, `pipelines/report_eda.py` | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `notebooks//01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `-/`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). | | `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). | | `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). | diff --git a/models/__main__.py b/models/__main__.py index b4b31ac..7ac6715 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -94,6 +94,29 @@ def _store(args: argparse.Namespace) -> int: return _store_step(args, args.input) +def _report_eda(args: argparse.Namespace) -> int: + """Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report.""" + from pathlib import Path + + from models.io.rendering import RenderError + from models.pipelines.report_eda import report_eda + + if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)): + return 1 + notebook = Path(args.notebook) if args.notebook else ( + Path(model.__file__).parents[1] / "notebooks" / args.scenario / "01_eda.ipynb") + if not notebook.exists(): + print(f"no notebook at {notebook}", file=sys.stderr) + return 1 + try: + run_id, written = report_eda(notebook, path, args.domain, args.scenario, kernel=args.kernel) + except RenderError as error: + print(error, file=sys.stderr) + return 1 + print(f"{'reported' if written else 'already reported'}: run {run_id}, {notebook.name} on {path}") + return 0 + + def _estimate(args: argparse.Namespace) -> int: """Scores the build's file with a registered version and writes the output file.""" if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)): @@ -286,6 +309,19 @@ def build_parser() -> argparse.ArgumentParser: estimate.add_argument("--version", help="the model version; the one in production by default") estimate.set_defaults(run=_estimate) + report = commands.add_parser("report", help="notebooks run on a build's file and kept as MLflow reports") + report.set_defaults(run=lambda args: _show_help(report)) + reports = report.add_subparsers(dest="action", metavar="") + eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow") + eda.add_argument("domain", choices=["cacu", "cama", "tea"]) + eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") + eda.add_argument("--notebook", help="the notebook; the scenario's notebooks//01_eda.ipynb by default") + eda.add_argument("--build", "--armado", dest="armado", type=int, + help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") + eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'") + eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default") + eda.set_defaults(run=_report_eda) + store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database") store.add_argument("domain", choices=["cacu", "cama", "tea"]) store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") diff --git a/models/io/rendering.py b/models/io/rendering.py new file mode 100644 index 0000000..fed229e --- /dev/null +++ b/models/io/rendering.py @@ -0,0 +1,49 @@ +"""Renders a notebook to a self-contained HTML page with Quarto, running it first. + +`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has +Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so +`QUARTO_PYTHON` names one that does. The notebook runs with the kernel its metadata +names, or `kernel` if given, in the environment given: that's how a report points the notebook at a database, a +cohort folder and a build's file. Quarto writes next to its input, so the notebook is copied to a temporary folder +first and the source folder is left untouched. +""" + +import json +import os +import shutil +import subprocess +import tempfile +from pathlib import Path + +QUARTO_ENV = "QUARTO_BIN" + + +class RenderError(RuntimeError): + """Quarto failed: a cell raised, the kernel is missing, or Quarto isn't installed.""" + + +def quarto() -> str: + found = os.environ.get(QUARTO_ENV) or shutil.which("quarto") + if not found: + raise RenderError(f"quarto isn't installed: put it on the PATH or set {QUARTO_ENV}") + return found + + +def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None, + kernel: str | None = None) -> Path: + """Runs and renders `notebook` (its JSON) as `name`, and writes the page to `output`.""" + command = quarto() + if kernel: + notebook = {**notebook, "metadata": {**notebook.get("metadata", {}), + "kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}} + with tempfile.TemporaryDirectory(prefix="render-") as folder: + source = Path(folder) / f"{name}.ipynb" + source.write_text(json.dumps(notebook, ensure_ascii=False)) + done = subprocess.run([command, "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"], + cwd=folder, env={**os.environ, **(env or {})}, capture_output=True, text=True) + page = source.with_suffix(".html") + if done.returncode or not page.exists(): + raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}") + output.parent.mkdir(parents=True, exist_ok=True) + shutil.move(page, output) + return output diff --git a/models/io/tracking.py b/models/io/tracking.py index 877b9f0..841a1be 100644 --- a/models/io/tracking.py +++ b/models/io/tracking.py @@ -11,6 +11,9 @@ process never interfere. `MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their artifacts (MLflow's own default is `./mlruns`, relative to the working directory). +Reports are runs too: `record_report` keeps a rendered notebook and its source as artifacts, in an experiment of +their own, and `find_run` finds one already made from the same inputs. + A run that logs a model (`log_model`) registers `runs://model`, tagged with its `modelo_sha`: the hash of the stored artifact, which identifies the exact model that produced a risk. Which code trained it is recorded apart: every run is @@ -29,7 +32,7 @@ import mlflow.pyfunc from core.governance.enums import ArtifactKind, Environment from mlflow import MlflowClient -from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, model_sha, registered_name +from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, matches, model_sha, registered_name from models.io.storage import ReadOnlyRepository, resolve_repository ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" @@ -70,6 +73,39 @@ def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json") +def experiment_id(client: MlflowClient, name: str) -> str: + """The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set.""" + experiment = client.get_experiment_by_name(name) + if experiment: + return experiment.experiment_id + root = os.environ.get(ARTIFACT_ROOT_ENV) + return client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None) + + +def find_run(client: MlflowClient, experiment: str, expected: dict[str, str]) -> str | None: + """The newest finished run of `experiment` whose tags hold every expected value, or `None`.""" + found = client.get_experiment_by_name(experiment) + if found is None: + return None + for run in client.search_runs([found.experiment_id], order_by=["attributes.start_time DESC"]): + if run.info.status == "FINISHED" and matches(run.data.tags, expected): + return run.info.run_id + return None + + +def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], files: dict[str, Path]) -> str: + """A finished run of `experiment` with `tags`, the code version, and each file logged under its kind's folder.""" + run = client.create_run(experiment_id(client, experiment), tags={**code_version(), **tags}) + try: + for kind, path in files.items(): + log_artifact_file(client, run.info.run_id, kind, path) + except Exception: + client.set_terminated(run.info.run_id, "FAILED") + raise + client.set_terminated(run.info.run_id, "FINISHED") + return run.info.run_id + + class TrainingRun: """One instance per training execution, wrapping one MLflow run. PROD runs name the cohort build they were trained on, so their metrics trace @@ -112,12 +148,7 @@ class TrainingRun: self.client.set_tag(self.run_id, tag, value) def _experiment_id(self) -> str: - name = registered_name(self.domain, self.scenario) - experiment = self.client.get_experiment_by_name(name) - if experiment: - return experiment.experiment_id - root = os.environ.get(ARTIFACT_ROOT_ENV) - return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None) + return experiment_id(self.client, registered_name(self.domain, self.scenario)) def repository(self, entity: str) -> ReadOnlyRepository: """ML-04: read-only access to `persistance.._repository`.""" diff --git a/models/pipelines/report_eda.py b/models/pipelines/report_eda.py new file mode 100644 index 0000000..7922145 --- /dev/null +++ b/models/pipelines/report_eda.py @@ -0,0 +1,48 @@ +"""An exploratory notebook as an MLflow report: run on a build's file, rendered with Quarto, kept as artifacts. + +Each notebook is an experiment, `-/` (`cacu-cin2_logistic/01_eda`), and each report a run +in it, tagged with the notebook's content hash and the build's file (`models.io.lineage.cohort_reference`). Its +artifacts are the rendered page (`report/`) and the notebook without outputs (`notebook/`). A notebook and a file that +were already reported together are not rendered again. + +The notebook reads the build's file from `COHORT_FILE`, set here, and the database and cohort folder from the +environment it inherits. +""" + +import json +import tempfile +from pathlib import Path + +from mlflow import MlflowClient + +from models.io.lineage import cohort_reference, file_sha256, registered_name +from models.io.rendering import render_notebook +from models.io.storage import read_metadata +from models.io.tracking import find_run, record_report +from models.steps.report import notebook_sha256, without_outputs + +COHORT_FILE_ENV = "COHORT_FILE" +NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report" + + +def report_experiment(domain: str, scenario: str, notebook: Path) -> str: + return f"{registered_name(domain, scenario)}/{notebook.stem}" + + +def report_eda(notebook_path: str | Path, cohort_path: str | Path, domain: str, scenario: str, + kernel: str | None = None) -> tuple[str, bool]: + """Returns the report's run id and whether it was rendered now.""" + notebook_path, cohort_path = Path(notebook_path), Path(cohort_path) + notebook = json.loads(notebook_path.read_text()) + experiment = report_experiment(domain, scenario, notebook_path) + tags = {REPORT_TAG: "eda", NOTEBOOK_TAG: notebook_path.name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook), + **cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))} + client = MlflowClient() + if existing := find_run(client, experiment, tags): + return existing, False + with tempfile.TemporaryDirectory(prefix="report-") as folder: + page = render_notebook(notebook, notebook_path.stem, Path(folder) / f"{notebook_path.stem}.html", + env={COHORT_FILE_ENV: str(cohort_path.resolve())}, kernel=kernel) + source = Path(folder) / notebook_path.name + source.write_text(json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1)) + return record_report(client, experiment, tags, {"report": page, "notebook": source}), True diff --git a/models/steps/report.py b/models/steps/report.py new file mode 100644 index 0000000..87bd222 --- /dev/null +++ b/models/steps/report.py @@ -0,0 +1,21 @@ +"""What identifies a notebook's content: its cells' sources, without outputs or execution counts.""" + +import copy +import hashlib +import json + + +def without_outputs(notebook: dict) -> dict: + """The notebook as written: code cells keep their source and lose their outputs.""" + cleared = copy.deepcopy(notebook) + for cell in cleared["cells"]: + if cell["cell_type"] == "code": + cell["outputs"], cell["execution_count"] = [], None + return cleared + + +def notebook_sha256(notebook: dict) -> str: + """Changes when a cell's type or source changes, not when the notebook is run again.""" + cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]] + for cell in notebook["cells"]] + return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest() diff --git a/tests/test_report_eda.py b/tests/test_report_eda.py new file mode 100644 index 0000000..65704c6 --- /dev/null +++ b/tests/test_report_eda.py @@ -0,0 +1,148 @@ +"""What this module covers: an exploratory notebook as an MLflow report (`models.steps.report`, `models.io.rendering`, +`models.io.tracking.find_run`/`record_report`, `models.pipelines.report_eda`) and `models report eda`: the content hash, +rendering with the build's file in the environment, one run per notebook and file, and its artifacts. + +Fixtures: `fake_quarto`, a stand-in `quarto` (through `QUARTO_BIN`) that writes a page naming the kernel and the +`COHORT_FILE` it was given, or fails when the notebook says so; `notebook`, a two-cell notebook with outputs; +`cohort`, a dbt build's file with its metadata; `mlflow_tracking` (conftest), a SQLite-backed MLflow. +""" + +import json +import os +import stat +import sys +from pathlib import Path + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest +from mlflow import MlflowClient + +from models.__main__ import main +from models.io.rendering import RenderError, render_notebook +from models.pipelines.report_eda import report_eda +from models.steps.report import notebook_sha256, without_outputs + +FAKE = '''#!{python} +import json, os, pathlib, sys +source = pathlib.Path(sys.argv[2]) +notebook = json.loads(source.read_text()) +if "fail" in json.dumps(notebook["cells"]): + sys.exit("a cell raised") +kernel = notebook["metadata"]["kernelspec"]["name"] +source.with_suffix(".html").write_text(f"kernel={{kernel}} cohort={{os.environ.get('COHORT_FILE')}}") +''' + + +@pytest.fixture +def fake_quarto(tmp_path, monkeypatch): + path = tmp_path / "quarto" + path.write_text(FAKE.format(python=sys.executable)) + path.chmod(path.stat().st_mode | stat.S_IEXEC) + monkeypatch.setenv("QUARTO_BIN", str(path)) + return path + + +def _notebook(source="print(1)"): + return {"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# EDA"]}, + {"cell_type": "code", "metadata": {}, "execution_count": 3, "source": [source], + "outputs": [{"output_type": "stream", "name": "stdout", "text": ["1\n"]}]}], + "metadata": {"kernelspec": {"name": "isssteleon-webapi", "display_name": "k", "language": "python"}}, + "nbformat": 4, "nbformat_minor": 5} + + +@pytest.fixture +def notebook(tmp_path): + path = tmp_path / "notebooks" / "01_eda.ipynb" + path.parent.mkdir() + path.write_text(json.dumps(_notebook())) + return path + + +def _cohort(path, build): + path.parent.mkdir(parents=True, exist_ok=True) + table = pa.table({"pac_id": [1, 2]}) + pq.write_table(table.replace_schema_metadata({"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": str(build)}), path) + return path + + +@pytest.fixture +def cohort(tmp_path): + return _cohort(tmp_path / "cohorts" / "dbt" / "1.parquet", 1) + + +def test_the_hash_follows_the_sources_not_the_outputs(): + """Pins down: running a notebook again (new outputs, counts) keeps its hash; editing a cell changes it. Fails if + outputs enter the hash, which would make every rendering a new report.""" + ran_again = _notebook() + ran_again["cells"][1].update(outputs=[], execution_count=9) + + assert notebook_sha256(ran_again) == notebook_sha256(_notebook()) + assert notebook_sha256(_notebook("print(2)")) != notebook_sha256(_notebook()) + assert without_outputs(_notebook())["cells"][1]["outputs"] == [] + + +def test_rendering_gets_the_environment_and_the_kernel(fake_quarto, tmp_path): + """Pins down: the page is rendered with the extra environment (the build's file) and with `kernel` when given. + Fails if either is lost on the way to Quarto.""" + page = render_notebook(_notebook(), "01_eda", tmp_path / "out" / "01_eda.html", env={"COHORT_FILE": "/x.parquet"}, + kernel="models") + + assert page.read_text() == "kernel=models cohort=/x.parquet" + + +def test_a_failing_notebook_or_missing_quarto_is_a_render_error(fake_quarto, tmp_path, monkeypatch): + """Pins down: a cell that raises, and Quarto not being installed, end as `RenderError` with the reason. Fails if a + broken report is logged or the error is a bare `FileNotFoundError`.""" + with pytest.raises(RenderError, match="a cell raised"): + render_notebook(_notebook("fail"), "01_eda", tmp_path / "page.html") + monkeypatch.setenv("QUARTO_BIN", "") + monkeypatch.setenv("PATH", str(tmp_path / "empty")) + with pytest.raises(RenderError, match="isn't installed"): + render_notebook(_notebook(), "01_eda", tmp_path / "page.html") + + +def test_a_report_is_a_run_of_the_notebooks_experiment_with_its_page(fake_quarto, notebook, cohort, mlflow_tracking): + """Pins down: the run is in `-/`, tagged with the notebook's hash and the build's file, + and holds the page (rendered on that file) and the notebook without outputs. Fails if the page or the source is + missing, or the run can't be traced to its inputs.""" + run_id, written = report_eda(notebook, cohort, "cacu", "cin2_logistic") + + client = MlflowClient() + run = client.get_run(run_id) + assert written and client.get_experiment(run.info.experiment_id).name == "cacu-cin2_logistic/01_eda" + assert run.data.tags["notebook.sha256"] == notebook_sha256(_notebook()) + assert (run.data.tags["cohort.source"], run.data.tags["cohort.build"]) == ("dbt", "1") + assert sorted(a.path for a in client.list_artifacts(run_id)) == ["notebook", "report"] + page = Path(client.download_artifacts(run_id, "report/01_eda.html")).read_text() + assert str(cohort.resolve()) in page + source = json.loads(Path(client.download_artifacts(run_id, "notebook/01_eda.ipynb")).read_text()) + assert source["cells"][1]["outputs"] == [] + + +def test_the_same_notebook_and_file_are_reported_once(fake_quarto, notebook, cohort, mlflow_tracking, tmp_path): + """Pins down: reporting again reuses the run; an edited notebook or another build's file makes a new one. Fails if + the check ignores either input, or renders every time.""" + first, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic") + again, written = report_eda(notebook, cohort, "cacu", "cin2_logistic") + other_build, _ = report_eda(notebook, _cohort(tmp_path / "cohorts" / "dbt" / "2.parquet", 2), "cacu", "cin2_logistic") + notebook.write_text(json.dumps(_notebook("print(2)"))) + edited, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic") + + assert again == first and not written + assert len({first, other_build, edited}) == 3 + + +def test_the_command_reports_on_the_latest_dbt_build(fake_quarto, notebook, tmp_path, monkeypatch, mlflow_tracking, capsys): + """Pins down: `models report eda` takes dbt's latest exported build by default and the notebook given. Fails if it + reads the kit's builds by default, or ignores `--notebook`.""" + folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" + _cohort(folder / "1.parquet", 1) + _cohort(folder / "2.parquet", 2) + monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts")) + + assert main(["report", "eda", "cacu", "cin2_logistic", "--notebook", str(notebook)]) == 0 + + assert "reported" in capsys.readouterr().out + run = MlflowClient().search_runs([MlflowClient().get_experiment_by_name("cacu-cin2_logistic/01_eda").experiment_id])[0] + assert run.data.tags["cohort.build"] == "2" From 71e77f0c7ed06e9120169843dea19dd14a7d0890 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:40:50 -0600 Subject: [PATCH 27/28] models cohorts list and show: a cohort's builds from both sources, and one build's file, hash and lineage --- README.md | 1 + models/__main__.py | 60 +++++++++++++++++++++ models/io/storage.py | 39 ++++++++++++++ tests/io/test_build_listing.py | 95 ++++++++++++++++++++++++++++++++++ 4 files changed, 195 insertions(+) create mode 100644 tests/io/test_build_listing.py diff --git a/README.md b/README.md index feb22a0..5c469b4 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ WebApi. | `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. | | `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. | | `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/.parquet` and writes only when its rows change. The timeline comes from dbt's view `_linea_de_tiempo`. | +| `cohorts list`, `cohorts show` | `python -m models cohorts list cacu cohorte_vigilancia [--source kit\|dbt]` lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); `cohorts show … --source kit\|dbt --build N` prints one build's file, hash, parameters, rules and attrition as JSON (`io/storage.py`: `list_builds`, `describe_build`). | | `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. | | `steps/report.py`, `io/rendering.py`, `pipelines/report_eda.py` | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `notebooks//01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `-/`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). | | `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | diff --git a/models/__main__.py b/models/__main__.py index 7ac6715..189de5f 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -259,6 +259,53 @@ def _cohort_export(args: argparse.Namespace) -> int: return 0 +def _cohort_list(args: argparse.Namespace) -> int: + """Prints the cohort's builds: dbt's from their files, the kit's from the database.""" + from importlib import import_module + + from persistance.settings import settings + + from models.io.storage import cohorts_root, list_builds + + url = f"{args.domain}/{args.cohort}" + try: + root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) + except ValueError as error: + print(error, file=sys.stderr) + return 1 + cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohorte_repository + rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])] + if not rows: + print(f"{url}: no builds", file=sys.stderr) + return 1 + print(f"{'source':<6} {'build':>5} {'datos_as_of':<11} {'members':>7} {'created':<25} file") + for row in rows: + print(f"{row['source']:<6} {row['build']:>5} {row['datos_as_of'] or '':<11} {row['n_members'] or '':>7} " + f"{(row['created'] or '')[:25]:<25} {row['file'] or '(not exported)'}") + return 0 + + +def _cohort_show(args: argparse.Namespace) -> int: + """Prints one build's file, hash and lineage as JSON.""" + import json + from importlib import import_module + + from persistance.settings import settings + + from models.io.storage import cohorts_root, describe_build + + url = f"{args.domain}/{args.cohort}" + try: + root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) + cohorts = import_module(f"persistance.{args.domain}").cohorte_repository if args.source == "kit" else None + described = describe_build(root, url, args.source, args.build, cohorts) + except (ValueError, LookupError) as error: + print(error, file=sys.stderr) + return 1 + print(json.dumps(described, indent=2, ensure_ascii=False)) + return 0 + + def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: if args.source == "dbt" and not args.manifest: parser.error("--source dbt needs --manifest") @@ -290,6 +337,19 @@ def build_parser() -> argparse.ArgumentParser: export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt") export.set_defaults(run=lambda args: _cohort_export_checked(export, args)) + listing = actions.add_parser("list", help="the cohort's builds, from both sources, and whether each has its file") + listing.add_argument("domain", choices=["cacu", "cama", "tea"]) + listing.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia") + listing.add_argument("--source", choices=["kit", "dbt"], help="only one source's builds; dbt's read no database") + listing.set_defaults(run=_cohort_list) + + show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition") + show.add_argument("domain", choices=["cacu", "cama", "tea"]) + show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia") + show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'") + show.add_argument("--build", type=int, required=True, help="the build's number") + show.set_defaults(run=_cohort_show) + train = commands.add_parser("train", help="train a model on a cohort build's file and register a version") train.add_argument("domain", choices=["cacu", "cama", "tea"]) train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") diff --git a/models/io/storage.py b/models/io/storage.py index d1414b0..99246ed 100644 --- a/models/io/storage.py +++ b/models/io/storage.py @@ -6,6 +6,7 @@ beside them, numbered in order, so a lookup of the kit's builds never picks one repository is used, so a model folder reading its cohort file never loads the database layer. """ +import hashlib import importlib import json import os @@ -64,6 +65,44 @@ def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path return path +def list_builds(root: Path, url: str, cohorts=None) -> list[dict]: + """One row per build of the cohort, newest first within each source: dbt's builds from their files' metadata, and, + with `cohorts` (the domain's `cohorte_repository`), the kit's builds and whether each has its file. Without + `cohorts` only files are read, never the database.""" + rows = [] + for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)): + path = dbt_build_path(root, url, number) + lineage = read_metadata(path) + rows.append({"source": "dbt", "build": number, "datos_as_of": lineage.get("datos_as_of"), + "n_members": lineage.get("n_members"), "created": lineage.get("built_at"), "file": str(path)}) + for build in (cohorts.builds(url) if cohorts is not None else []): + path = cohort_path(root, url, build.armado_id) + rows.append({"source": "kit", "build": build.armado_id, "datos_as_of": build.datos_as_of.isoformat(), + "n_members": str(build.n_miembros), "created": build.armado_en.isoformat(), + "file": str(path) if path.exists() else None}) + return rows + + +def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict: + """One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build + without a file is described from `cohorts` (the domain's `cohorte_repository`). `LookupError` if there's no such + build.""" + path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build) + if path.exists(): + lineage = read_metadata(path) + for key in ("parametros", "rules", "attrition"): + if lineage.get(key): + lineage[key] = json.loads(lineage[key]) + digest = hashlib.sha256(path.read_bytes()).hexdigest() + return {"source": source, "build": build, "file": str(path), "file_sha256": digest, "lineage": lineage} + stored = cohorts.build(build) if source == "kit" and cohorts is not None else None + if stored is None or stored.url != url: + raise LookupError(f"no {source} build {build} of {url}") + return {"source": "kit", "build": build, "file": None, "file_sha256": None, + "lineage": {"url": stored.url, "version": stored.version, "datos_as_of": stored.datos_as_of.isoformat(), + "n_members": str(stored.n_miembros), "huella": stored.huella, "armado_en": stored.armado_en.isoformat()}} + + def read_cohort(path: str | Path) -> pd.DataFrame: """The build's rows, after checking the file's schema without reading them.""" schema = pq.read_schema(path) diff --git a/tests/io/test_build_listing.py b/tests/io/test_build_listing.py new file mode 100644 index 0000000..3daca17 --- /dev/null +++ b/tests/io/test_build_listing.py @@ -0,0 +1,95 @@ +"""What this module covers: listing and describing a cohort's builds (`models.io.storage.list_builds`, +`describe_build`) and the `models cohorts list` and `cohorts show` commands. + +Fixtures: `root`, a cohorts folder with dbt builds 1 and 2 and kit build 7's file; `kit`, a stand-in of the cohort +repository with kit builds 7 (exported) and 8 (not exported). +""" + +import json +from datetime import date, datetime, timezone +from types import SimpleNamespace + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from models.__main__ import main +from models.io.storage import cohort_path, dbt_build_path, describe_build, list_builds + +URL = "cacu/cohorte_vigilancia" +ATTRITION = [{"step": "all_patients", "n": 3, "excluded": None}, {"step": "indexed", "n": 2, "excluded": 1}] + + +def _file(path, **metadata): + path.parent.mkdir(parents=True, exist_ok=True) + pq.write_table(pa.table({"pac_id": [1]}).replace_schema_metadata({k: str(v) for k, v in metadata.items()}), path) + + +@pytest.fixture +def root(tmp_path): + for number in (1, 2): + _file(dbt_build_path(tmp_path, URL, number), producer="dbt", build=number, datos_as_of="2026-12-31", + n_members=2, built_at=f"2026-11-0{number}T00:00:00+00:00", rules=json.dumps(["prior_event"]), + parametros=json.dumps({"cutoff": "2026-12-31"}), attrition=json.dumps(ATTRITION)) + _file(cohort_path(tmp_path, URL, 7), producer="kit", armado_id=7, datos_as_of="2026-12-31", n_members=2) + return tmp_path + + +def _kit_build(armado_id): + return SimpleNamespace(armado_id=armado_id, url=URL, version="0.2.0", datos_as_of=date(2026, 12, 31), n_miembros=2, + huella="h", armado_en=datetime(2026, 10, armado_id, tzinfo=timezone.utc)) + + +@pytest.fixture +def kit(): + builds = {8: _kit_build(8), 7: _kit_build(7)} + return SimpleNamespace(builds=lambda url: list(builds.values()) if url == URL else [], build=builds.get) + + +def test_both_sources_are_listed_newest_first_with_their_files(root, kit): + """Pins down: dbt's builds come from their files, newest first, and the kit's from the repository, each saying + whether its file exists. Fails if a source is dropped, the order is by name, or an unexported build shows a file.""" + rows = list_builds(root, URL, kit) + + assert [(r["source"], r["build"]) for r in rows] == [("dbt", 2), ("dbt", 1), ("kit", 8), ("kit", 7)] + assert rows[2]["file"] is None and rows[3]["file"].endswith("7.parquet") + assert rows[0]["created"] == "2026-11-02T00:00:00+00:00" + + +def test_without_the_repository_only_files_are_read(root): + """Pins down: listing dbt's builds needs no database. Fails if `list_builds` reaches for the kit's builds anyway.""" + assert [r["source"] for r in list_builds(root, URL)] == ["dbt", "dbt"] + + +def test_a_dbt_build_is_described_with_its_lineage_decoded(root): + """Pins down: `describe_build` gives the file, its hash, and the parameters, rules and attrition as JSON values, + not strings. Fails if the hash is missing or the lineage stays encoded.""" + described = describe_build(root, URL, "dbt", 2) + + assert len(described["file_sha256"]) == 64 + assert described["lineage"]["attrition"] == ATTRITION and described["lineage"]["rules"] == ["prior_event"] + assert described["lineage"]["parametros"] == {"cutoff": "2026-12-31"} + + +def test_an_unexported_kit_build_is_described_from_the_database(root, kit): + """Pins down: a kit build without a file still has its lineage, from the repository; an unknown build is a + `LookupError`. Fails if an unexported build is reported as missing, or a missing one as empty.""" + described = describe_build(root, URL, "kit", 8, kit) + + assert described["file"] is None and described["lineage"]["n_members"] == "2" + with pytest.raises(LookupError): + describe_build(root, URL, "kit", 9, kit) + with pytest.raises(LookupError): + describe_build(root, URL, "dbt", 9) + + +def test_the_commands_print_the_dbt_builds(root, monkeypatch, capsys): + """Pins down: `cohorts list --source dbt` and `cohorts show` work from the files alone. Fails if either opens the + database for dbt's builds, or `show` prints something other than JSON.""" + monkeypatch.setenv("COHORTS_DIR", str(root)) + + assert main(["cohorts", "list", "cacu", "cohorte_vigilancia", "--source", "dbt"]) == 0 + listed = capsys.readouterr().out + assert "dbt/2.parquet" in listed and "dbt/1.parquet" in listed + assert main(["cohorts", "show", "cacu", "cohorte_vigilancia", "--build", "1"]) == 0 + assert json.loads(capsys.readouterr().out)["build"] == 1 From 5d65730b989e24e8291ab690989ca2f3de12a0c3 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:44:58 -0600 Subject: [PATCH 28/28] Value checks with pandera on cohort files, read and written, and on estimates, written and stored --- models/cacu/cin2_logistic/estimate.py | 5 +- models/io/contracts.py | 38 +++++++++++++- models/io/storage.py | 6 +-- models/steps/cohort_file.py | 4 +- models/steps/risks.py | 12 ++--- pyproject.toml | 4 +- tests/io/test_frame_checks.py | 75 +++++++++++++++++++++++++++ 7 files changed, 127 insertions(+), 17 deletions(-) create mode 100644 tests/io/test_frame_checks.py diff --git a/models/cacu/cin2_logistic/estimate.py b/models/cacu/cin2_logistic/estimate.py index 4014cf6..e7e39c1 100644 --- a/models/cacu/cin2_logistic/estimate.py +++ b/models/cacu/cin2_logistic/estimate.py @@ -6,7 +6,7 @@ import mlflow.pyfunc import pyarrow as pa from models.cacu.cin2_logistic.model import SETTINGS -from models.io.contracts import ESTIMATE_COLUMNS +from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches from models.io.registry import ResolvedVersion, registered_name, registry from models.io.storage import read_cohort, read_metadata, write_once @@ -29,8 +29,7 @@ def estimate(cohort_path: str | Path, output_path: str | Path, version: str | No if already_estimated(output_path, resolved.version, cohort): return resolved, False risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path)) - if tuple(risks.columns) != ESTIMATE_COLUMNS: - raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}") + check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output") window = SETTINGS["outcome_window_months"] provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version, "mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12), diff --git a/models/io/contracts.py b/models/io/contracts.py index 6be006c..363c88e 100644 --- a/models/io/contracts.py +++ b/models/io/contracts.py @@ -4,6 +4,7 @@ every row. - A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`). - An estimate's output (`ESTIMATE_COLUMNS`): one row per member. +- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`). - The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build, `(columns, rows)` with `columns = ["pac_id", "fecha_indice", ]`. `Risk` and `Provenance` keep the names of the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what @@ -15,6 +16,7 @@ from datetime import date from typing import NamedTuple, Protocol, runtime_checkable import pandas as pd +import pandera.pandas as pandera import pyarrow as pa COHORT_SCHEMA = pa.schema([ @@ -26,11 +28,45 @@ COHORT_SCHEMA = pa.schema([ ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad") +# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow +# schema says which columns and types; these say what a valid row and a valid file are. +COHORT_FRAME = pandera.DataFrameSchema( + {"pac_id": pandera.Column(int, pandera.Check.gt(0)), + "fecha_indice": pandera.Column(nullable=False), + "fecha": pandera.Column(nullable=False), + "clase": pandera.Column(str, pandera.Check.str_length(min_value=1)), + "tipo": pandera.Column(str, pandera.Check.str_length(min_value=1)), + "fuente_tabla": pandera.Column(str, nullable=False), + "fuente_id": pandera.Column(str, nullable=False)}, + checks=pandera.Check(lambda frame: frame.groupby("pac_id")["fecha_indice"].nunique().le(1).all(), + error="a member has more than one index date"), + name="cohort build") + +ESTIMATE_FRAME = pandera.DataFrameSchema( + {"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True), + "fecha_indice": pandera.Column(nullable=False), + "probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))}, + strict=True, ordered=True, name="estimate") + POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion" class CohortFileError(ValueError): - """The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s.""" + """The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s, or its rows break + `COHORT_FRAME`.""" + + +class EstimateError(ValueError): + """An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1.""" + + +def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame: + """`frame` if it satisfies `schema`, else `error` naming every failed check (up to ten).""" + try: + return schema.validate(frame, lazy=True) + except pandera.errors.SchemaErrors as failed: + cases = failed.failure_cases[["column", "check", "failure_case"]].head(10).to_dict("records") + raise error(f"{where} isn't a valid {schema.name}: {cases}") from None class CohortDefinitionError(ValueError): diff --git a/models/io/storage.py b/models/io/storage.py index 99246ed..34bdf17 100644 --- a/models/io/storage.py +++ b/models/io/storage.py @@ -19,8 +19,8 @@ import pyarrow as pa import pyarrow.parquet as pq from sqlalchemy.engine import make_url -from models.io.contracts import (COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError, - CohortQueries, ExclusionRule) +from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, + CohortFileError, CohortQueries, ExclusionRule, check_frame) def cohorts_root(database_url: str) -> Path: @@ -108,7 +108,7 @@ def read_cohort(path: str | Path) -> pd.DataFrame: schema = pq.read_schema(path) if not schema.equals(COHORT_SCHEMA, check_metadata=False): raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}") - return pd.read_parquet(path) + return check_frame(COHORT_FRAME, pd.read_parquet(path), CohortFileError, str(path)) def write_once(table: pa.Table, path: Path) -> None: diff --git a/models/steps/cohort_file.py b/models/steps/cohort_file.py index 604209e..599ce0b 100644 --- a/models/steps/cohort_file.py +++ b/models/steps/cohort_file.py @@ -5,7 +5,7 @@ from datetime import date, datetime, timezone import pandas as pd import pyarrow as pa -from models.io.contracts import COHORT_SCHEMA as SCHEMA +from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame from models.io.lineage import table_sha256 ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"] @@ -36,5 +36,7 @@ def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table: + """The file's table, once its rows satisfy `COHORT_FRAME`: a build that would fail to read is never written.""" + check_frame(COHORT_FRAME, cohort_events, CohortFileError, f"build {lineage.get('build') or lineage.get('armado_id')}") table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False) return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}}) diff --git a/models/steps/risks.py b/models/steps/risks.py index b2b2d3c..3d38bfe 100644 --- a/models/steps/risks.py +++ b/models/steps/risks.py @@ -2,16 +2,12 @@ import pandas as pd -from models.io.contracts import ESTIMATE_COLUMNS +from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]: - """One risk per member at the model's horizon, without an interval; a member scored twice stops the batch.""" - if tuple(estimate.columns) != ESTIMATE_COLUMNS: - raise ValueError(f"an estimate has {list(ESTIMATE_COLUMNS)}, not {list(estimate.columns)}") - if estimate["pac_id"].duplicated().any(): - raise ValueError(f"members scored twice: {sorted(estimate.loc[estimate['pac_id'].duplicated(), 'pac_id'])[:10]}") - if not estimate["probabilidad"].between(0, 1).all(): - raise ValueError("a probability outside 0..1") + """One risk per member at the model's horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a + member scored twice or a probability outside 0..1 stops the batch.""" + check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate") return [(int(pac_id), float(horizon_years), float(probability), None, None) for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])] diff --git a/pyproject.toml b/pyproject.toml index fe2228b..ee19814 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,11 +13,13 @@ dependencies = [ "pandas>=2.0", "pyarrow>=15", "scikit-learn>=1.4", + # The values of the cohort and estimate files (`models.io.contracts`). + "pandera>=0.20", ] [project.optional-dependencies] # Only needed to read back a checkpoint's own metadata (opset, producer) in -# models.io.export.inspect_onnx_metadata — writing/logging a checkpoint never +# models.io.tracking.inspect_onnx_metadata — writing/logging a checkpoint never # requires it, see that module's docstring. export = [ "onnx>=1.15", diff --git a/tests/io/test_frame_checks.py b/tests/io/test_frame_checks.py new file mode 100644 index 0000000..e74cf63 --- /dev/null +++ b/tests/io/test_frame_checks.py @@ -0,0 +1,75 @@ +"""What this module covers: the value checks of the cohort and estimate files (`COHORT_FRAME`, `ESTIMATE_FRAME`, +`check_frame` in `models.io.contracts`), and that reading a cohort file and building one apply them. + +Fixtures: none; `_events` makes a valid two-member frame and each test breaks one rule. +""" + +from datetime import date, datetime, timezone + +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, ESTIMATE_FRAME, CohortFileError, EstimateError, + check_frame) +from models.io.storage import read_cohort +from models.steps.cohort_file import cohort_table + + +def _events(**changes): + frame = pd.DataFrame({"pac_id": [1, 1, 2], "fecha_indice": [date(2025, 1, 1)] * 2 + [date(2025, 2, 1)], + "fecha": [date(2025, 1, 1), date(2025, 3, 1), date(2025, 2, 1)], + "conocida_en": [datetime(2025, 4, 1, tzinfo=timezone.utc)] * 3, + "clase": ["procedimiento", "medicion", "procedimiento"], + "tipo": ["citologia", "bethesda", "citologia"], "codigo": ["c", "b", "c"], + "valor_codigo": [None, "NORMAL", None], "valor_numerico": [None, None, None], + "fuente_tabla": ["citologiacervical"] * 3, "fuente_id": ["a", "a", "b"]}) + for column, (row, value) in changes.items(): + frame.loc[row, column] = value + return frame + + +def test_a_valid_build_passes(): + """Pins down: a well-formed frame comes back unchanged. Fails if a check rejects valid data, which would stop every + export and training.""" + assert check_frame(COHORT_FRAME, _events(), CohortFileError, "test").equals(_events()) + + +@pytest.mark.parametrize("changes, check", [ + ({"fecha_indice": (1, date(2025, 1, 5))}, "more than one index date"), + ({"pac_id": (2, 0)}, "greater_than"), + ({"fecha": (0, None)}, "not_nullable"), + ({"tipo": (1, "")}, "str_length"), +]) +def test_a_broken_build_names_what_failed(changes, check): + """Pins down: two index dates for a member, a non-positive id, a missing date or an empty type are refused, and + the error names the check. Fails if a broken file reaches a model, where it would train on wrong rows.""" + with pytest.raises(CohortFileError, match=check): + check_frame(COHORT_FRAME, _events(**changes), CohortFileError, "test") + + +def test_reading_and_building_a_file_apply_the_checks(tmp_path): + """Pins down: `read_cohort` refuses a file whose rows break `COHORT_FRAME`, and `cohort_table` refuses to build + one. Fails if either path skips the check.""" + broken = _events(fecha_indice=(1, date(2025, 1, 5))) + path = tmp_path / "1.parquet" + pq.write_table(pa.Table.from_pandas(broken, schema=COHORT_SCHEMA, preserve_index=False), path) + + with pytest.raises(CohortFileError): + read_cohort(path) + with pytest.raises(CohortFileError): + cohort_table(broken, {"build": 1}) + + +@pytest.mark.parametrize("estimate", [ + pd.DataFrame({"pac_id": [1, 1], "fecha_indice": [date(2025, 1, 1)] * 2, "probabilidad": [0.1, 0.2]}), + pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [1.2]}), + pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [0.1], "extra": [1]}), + pd.DataFrame({"fecha_indice": [date(2025, 1, 1)], "pac_id": [1], "probabilidad": [0.1]}), +]) +def test_an_estimate_is_one_probability_per_member_in_its_columns(estimate): + """Pins down: a member twice, a probability outside 0..1, an extra column or another column order are refused. + Fails if a malformed output can be written or stored as risks.""" + with pytest.raises(EstimateError): + check_frame(ESTIMATE_FRAME, estimate, EstimateError, "test")