testing: CacuStandIn as a helper for other code's tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-03 21:20:15 +00:00
parent 449c67b19d
commit dd94aba1eb
2 changed files with 53 additions and 0 deletions
+1
View File
@@ -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 (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
+52
View File
@@ -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