Files
models/models/io/contract.py
T

51 lines
1.7 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.
"""
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]: ...