78a4748592
A run with `risk_interval_level` has a model that gives, after the risk at each horizon, its interval's lower and upper ends; the estimate keeps them as `ic_bajo` and `ic_alto`, the contract checks that they hold the risk, and the batch stores them. `scored_frame` is the one place that reads the run and calls the model, for the command and the WebApi's cycle. A member whose risk is NaN (a combination the model never saw) is left out instead of stopping the whole batch.
148 lines
6.2 KiB
Python
148 lines
6.2 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 and horizon (`horizonte_anios`, years from the
|
|
index date; 0 is the prevalence).
|
|
- 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", "horizonte_anios", "probabilidad")
|
|
DAYS_PER_YEAR = 365.25 # horizons and intervals are in years from the index date
|
|
|
|
# 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)),
|
|
"fecha_indice": pandera.Column(nullable=False),
|
|
"horizonte_anios": pandera.Column(float, pandera.Check.ge(0)),
|
|
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1)),
|
|
# the risk's interval, from a model that gives one (NaN where it can't)
|
|
"ic_bajo": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False),
|
|
"ic_alto": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False)},
|
|
checks=pandera.Check(lambda f: ~(f["ic_bajo"] > f["probabilidad"]) & ~(f["ic_alto"] < f["probabilidad"])
|
|
if "ic_bajo" in f else pd.Series(True, index=f.index), error="ic_bajo <= probabilidad <= ic_alto"),
|
|
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
|
|
|
|
POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables"
|
|
|
|
|
|
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 at one horizon, a negative
|
|
horizon, 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
|
|
version: str = "" # the population meta's `version`: bumped when a rule changes
|
|
# optional: the members' stored variables, long (`pac_id`, `variable`, `valor_codigo`, `valor_numerico`)
|
|
variables: str | None = None
|
|
|
|
|
|
@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
|
|
fecha_indice: date # the model's index date for this member: the horizons count from it
|
|
horizonte_anios: float # years from `fecha_indice`; 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]: ...
|