From c8bca59334d8fd6e1d1ca9873a73cdcd1512d788 Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 3 Nov 2026 19:30:08 +0000 Subject: [PATCH] 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"], [])