Cohorts built from dbt's rules and exported, an idempotent run command and estimate; io split by responsibility, with stored predictions moved into the registry and the ONNX check into tracking

This commit is contained in:
2026-11-05 16:12:23 -06:00
parent 0fdab3651c
commit 9808701c46
35 changed files with 1710 additions and 719 deletions
+98
View File
@@ -0,0 +1,98 @@
"""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 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 `PROCEDENCIA` expects.
"""
from dataclasses import asdict, dataclass
from datetime import date
from typing import NamedTuple, Protocol, runtime_checkable
import pandas as pd
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")
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."""
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]: ...