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 <noreply@anthropic.com>
This commit is contained in:
2026-11-03 19:30:08 +00:00
parent c11575f656
commit c8bca59334
5 changed files with 331 additions and 281 deletions
+152
View File
@@ -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"], [])
-105
View File
@@ -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"], [])