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:
@@ -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", <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
|
||||
@@ -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", <variables>]`
|
||||
(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
|
||||
Reference in New Issue
Block a user