Files
models/models/io/contracts.py
T

135 lines
5.0 KiB
Python

"""The shapes of the data the pipelines read and write. Nothing here reads or writes.
- A cohort build's Parquet file (`COHORT_SCHEMA`): long, one row per member and event, with the member's index date on
every row.
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`).
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `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 `PROVENANCE` expects.
"""
from dataclasses import asdict, dataclass
from datetime import date
from typing import NamedTuple, Protocol, runtime_checkable
import pandas as pd
import pandera.pandas as pandera
import pyarrow as pa
COHORT_SCHEMA = pa.schema([
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()),
("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()),
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
])
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow
# schema says which columns and types; these say what a valid row and a valid file are.
COHORT_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False),
"fecha": pandera.Column(nullable=False),
"clase": pandera.Column(str, pandera.Check.str_length(min_value=1)),
"tipo": pandera.Column(str, pandera.Check.str_length(min_value=1)),
"fuente_tabla": pandera.Column(str, nullable=False),
"fuente_id": pandera.Column(str, nullable=False)},
checks=pandera.Check(lambda frame: frame.groupby("pac_id")["fecha_indice"].nunique().le(1).all(),
error="a member has more than one index date"),
name="cohort build")
ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
strict=True, ordered=True, name="estimate")
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
class CohortFileError(ValueError):
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s, or its rows break
`COHORT_FRAME`."""
class EstimateError(ValueError):
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1."""
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
"""`frame` if it satisfies `schema`, else `error` naming every failed check (up to ten)."""
try:
return schema.validate(frame, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases[["column", "check", "failure_case"]].head(10).to_dict("records")
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
class CohortDefinitionError(ValueError):
"""The cohort's queries or their results don't follow the structure a build chains."""
@dataclass(frozen=True)
class ExclusionRule:
name: str
description: str
order: int
sql: str
@dataclass(frozen=True)
class CohortQueries:
url: str
all_patients: str
index_date: str
rules: tuple[ExclusionRule, ...]
cutoff: date
parameters: dict
@dataclass(frozen=True)
class BuiltCohort:
"""The study population (`pac_id`, `fecha_indice` and the index event) and the attrition, one row per step."""
study_population: pd.DataFrame
attrition: pd.DataFrame
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]: ...