Files
models/models/contract.py
T
edgar c8bca59334 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>
2026-11-03 19:30:08 +00:00

179 lines
7.4 KiB
Python

"""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", <variables>]`. 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