Model interface over frames and a model catalog
This commit is contained in:
@@ -16,6 +16,8 @@ WebApi.
|
||||
| `io/prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
|
||||
| `io/export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
|
||||
| `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. |
|
||||
| `io/cohorts.py` | El archivo Parquet de un armado de cohorte: sus columnas y `read_cohort`, que lo lee como marco tras revisar su esquema. |
|
||||
| `io/catalog.py` | `catalog`: qué modelos existen (`<dominio>/<escenario>` → su módulo) y `ScreeningModel`, los pasos que define cada modelo (`prepare`, `fit`, `predict`) sobre marcos, sin leer la base. |
|
||||
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
||||
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||
| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, sin guardar nada en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. Necesita `Transformation` para compilar la línea de tiempo. |
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Which models exist: `<domain>/<scenario>` to the module that holds its steps.
|
||||
|
||||
A model is a module in its own folder, `models/<domain>/<scenario>/model.py`, whose functions are nodes of the
|
||||
training graph: each parameter's name is the node it takes. Adding a model is its folder plus one `register` line
|
||||
at the end of this file.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
from types import ModuleType
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
import pandas as pd
|
||||
|
||||
# What `prepare` returns besides the model's predictors.
|
||||
PREPARED_COLUMNS = ("pac_id", "fecha_indice", "y")
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ScreeningModel(Protocol):
|
||||
"""A model's module. It receives frames and doesn't read the database."""
|
||||
|
||||
def prepare(self, cohort: pd.DataFrame) -> pd.DataFrame:
|
||||
"""One row per member: `PREPARED_COLUMNS` and the predictors, from the build's rows."""
|
||||
|
||||
def fit(self, train: pd.DataFrame) -> Any:
|
||||
"""The fitted model, from the training rows of `prepare`'s frame."""
|
||||
|
||||
def predict(self, fit: Any, test: pd.DataFrame) -> pd.Series:
|
||||
"""The probability of `y` for each row of `test`, in its order."""
|
||||
|
||||
|
||||
class UnknownModel(LookupError):
|
||||
"""No model is registered under that domain and scenario."""
|
||||
|
||||
|
||||
class NotAScreeningModel(TypeError):
|
||||
"""The registered module lacks a step of `ScreeningModel`."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CatalogEntry:
|
||||
domain: str
|
||||
scenario: str
|
||||
module: str
|
||||
|
||||
|
||||
class ModelCatalog:
|
||||
def __init__(self):
|
||||
self._entries: dict[tuple[str, str], CatalogEntry] = {}
|
||||
|
||||
def register(self, domain: str, scenario: str, module: str | None = None) -> None:
|
||||
"""`module` defaults to the model's folder, `models.<domain>.<scenario>.model`."""
|
||||
if (domain, scenario) in self._entries:
|
||||
raise ValueError(f"{domain}/{scenario} is already registered")
|
||||
self._entries[domain, scenario] = CatalogEntry(domain, scenario, module or f"models.{domain}.{scenario}.model")
|
||||
|
||||
def entries(self) -> list[CatalogEntry]:
|
||||
return sorted(self._entries.values(), key=lambda entry: (entry.domain, entry.scenario))
|
||||
|
||||
def load(self, domain: str, scenario: str) -> ModuleType:
|
||||
"""The model's module, ready to hand to a graph's driver."""
|
||||
try:
|
||||
entry = self._entries[domain, scenario]
|
||||
except KeyError:
|
||||
raise UnknownModel(f"{domain}/{scenario} isn't in the catalog") from None
|
||||
module = import_module(entry.module)
|
||||
if not isinstance(module, ScreeningModel):
|
||||
raise NotAScreeningModel(f"{entry.module} must define `prepare`, `fit` and `predict`")
|
||||
return module
|
||||
|
||||
|
||||
catalog = ModelCatalog()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""A cohort build's Parquet file: its columns, and reading it as a frame.
|
||||
|
||||
Long format: one row per member and event, with the member's index date on every row. A model gets the whole
|
||||
frame and computes its own outcome and predictors from it; it never reads the database.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
|
||||
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()),
|
||||
])
|
||||
|
||||
|
||||
class CohortFileError(ValueError):
|
||||
"""The file isn't a cohort build: its columns or types aren't `SCHEMA`'s."""
|
||||
|
||||
|
||||
def read_cohort(path: str | Path) -> pd.DataFrame:
|
||||
"""The build's rows, after checking the file's schema without reading them."""
|
||||
schema = pq.read_schema(path)
|
||||
if not schema.equals(SCHEMA, check_metadata=False):
|
||||
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
||||
return pd.read_parquet(path)
|
||||
@@ -31,12 +31,8 @@ from persistance.settings import settings
|
||||
from sqlalchemy import column, select, text
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
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()),
|
||||
])
|
||||
from models.io.cohorts import SCHEMA
|
||||
|
||||
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
||||
DBT_TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"}
|
||||
DEFAULT_TRANSFORMATION = Path(__file__).resolve().parents[2] / "Transformation"
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""What this module covers: `models.io.catalog`: registering a model, loading it, running its steps over a cohort
|
||||
file; and the rule that a model's folder doesn't import the database layer.
|
||||
|
||||
Fixtures: `cohort_file`, a small Parquet file of a build with two members, one with an abnormal Bethesda result.
|
||||
Test models live in `tests/sample_models/`.
|
||||
"""
|
||||
|
||||
import ast
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
import models
|
||||
from models.io.catalog import NotAScreeningModel, ModelCatalog, PREPARED_COLUMNS, ScreeningModel, UnknownModel
|
||||
from models.io.cohorts import SCHEMA, read_cohort
|
||||
|
||||
|
||||
def _row(pac_id, fecha_indice, valor, fuente_id):
|
||||
return {"pac_id": pac_id, "fecha_indice": fecha_indice, "fecha": fecha_indice,
|
||||
"conocida_en": datetime(2025, 6, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda",
|
||||
"codigo": "bethesda", "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": fuente_id}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(tmp_path):
|
||||
"""Member 10 has two normal results; member 20 has one abnormal result."""
|
||||
rows = [_row(10, date(2025, 1, 1), "NORMAL", "a"), _row(10, date(2025, 1, 1), "NORMAL", "b"),
|
||||
_row(20, date(2025, 2, 1), "LIEBG", "c")]
|
||||
path = tmp_path / "1.parquet"
|
||||
pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), path)
|
||||
return path
|
||||
|
||||
|
||||
def test_a_registered_model_runs_over_a_cohort_file(cohort_file):
|
||||
"""Pins down: the whole path of a model's input: a registered model, loaded from the catalog, prepares, fits and
|
||||
predicts from a frame read from the file, with no database. Fails if `load` returns anything else than the
|
||||
module, or a step's contract changes."""
|
||||
catalog = ModelCatalog()
|
||||
catalog.register("cacu", "mean_rate", "sample_models.mean_rate")
|
||||
|
||||
model = catalog.load("cacu", "mean_rate")
|
||||
prepared = model.prepare(read_cohort(cohort_file))
|
||||
fitted = model.fit(prepared)
|
||||
|
||||
assert isinstance(model, ScreeningModel)
|
||||
assert set(PREPARED_COLUMNS) <= set(prepared.columns)
|
||||
assert prepared.set_index("pac_id")["y"].to_dict() == {10: 0, 20: 1}
|
||||
assert model.predict(fitted, prepared).tolist() == [0.5, 0.5]
|
||||
|
||||
|
||||
def test_the_default_module_is_the_models_folder():
|
||||
"""Pins down: one line registers a model that follows the layout. Fails if the default path changes, which would
|
||||
break every registered model."""
|
||||
catalog = ModelCatalog()
|
||||
catalog.register("cacu", "cin2_logistic")
|
||||
assert catalog.entries()[0].module == "models.cacu.cin2_logistic.model"
|
||||
|
||||
|
||||
def test_an_unknown_model_is_refused():
|
||||
"""Pins down: asking for a model that isn't registered says so. Fails if `load` guesses a module by convention
|
||||
or lets a bare `KeyError` through."""
|
||||
with pytest.raises(UnknownModel, match="cacu/ninguno"):
|
||||
ModelCatalog().load("cacu", "ninguno")
|
||||
|
||||
|
||||
def test_a_scenario_is_registered_once():
|
||||
"""Pins down: a second registration of a scenario fails, instead of silently replacing the first model. Fails if
|
||||
the duplicate check goes."""
|
||||
catalog = ModelCatalog()
|
||||
catalog.register("cacu", "mean_rate", "sample_models.mean_rate")
|
||||
with pytest.raises(ValueError, match="already registered"):
|
||||
catalog.register("cacu", "mean_rate", "sample_models.no_predict")
|
||||
|
||||
|
||||
def test_a_module_without_a_step_is_refused():
|
||||
"""Pins down: a module lacking a step fails when loaded, not halfway through training. Fails if `load` stops
|
||||
checking `ScreeningModel`."""
|
||||
catalog = ModelCatalog()
|
||||
catalog.register("cacu", "no_predict", "sample_models.no_predict")
|
||||
with pytest.raises(NotAScreeningModel, match="no_predict"):
|
||||
catalog.load("cacu", "no_predict")
|
||||
|
||||
|
||||
def test_a_file_with_other_columns_is_refused(tmp_path):
|
||||
"""Pins down: `read_cohort` only accepts a cohort build's columns and types. Fails if it stops checking the
|
||||
schema, which would let a model fail later on a missing column."""
|
||||
path = tmp_path / "other.parquet"
|
||||
pq.write_table(pa.table({"pac_id": [1]}), path)
|
||||
with pytest.raises(ValueError, match="cohort build's columns"):
|
||||
read_cohort(path)
|
||||
|
||||
|
||||
def test_model_folders_do_not_import_the_database_layer():
|
||||
"""Pins down: a model only sees frames: nothing under `models/cacu`, `cama` or `tea` imports `persistance` or
|
||||
`core`. Fails when a model's folder imports either."""
|
||||
package = Path(models.__file__).parent
|
||||
offenders = []
|
||||
for path in (file for domain in ("cacu", "cama", "tea") for file in (package / domain).rglob("*.py")):
|
||||
for node in ast.walk(ast.parse(path.read_text())):
|
||||
names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else \
|
||||
[node.module or ""] if isinstance(node, ast.ImportFrom) else []
|
||||
offenders += [(path.name, name) for name in names if name.split(".")[0] in ("persistance", "core")]
|
||||
assert not offenders
|
||||
@@ -0,0 +1,20 @@
|
||||
"""A test model: predicts the training rows' share of `y`. `y` is 1 if a member has any Bethesda result that isn't
|
||||
`NORMAL`; its only predictor is the member's number of Bethesda results."""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def prepare(cohort: pd.DataFrame) -> pd.DataFrame:
|
||||
results = cohort[cohort["tipo"] == "bethesda"]
|
||||
abnormal = results["valor_codigo"].ne("NORMAL").groupby(results["pac_id"]).any()
|
||||
prepared = results.groupby(["pac_id", "fecha_indice"], as_index=False).size().rename(columns={"size": "n_results"})
|
||||
prepared["y"] = prepared["pac_id"].map(abnormal).astype(int)
|
||||
return prepared
|
||||
|
||||
|
||||
def fit(train: pd.DataFrame) -> float:
|
||||
return float(train["y"].mean())
|
||||
|
||||
|
||||
def predict(fit: float, test: pd.DataFrame) -> pd.Series:
|
||||
return pd.Series(fit, index=test.index)
|
||||
@@ -0,0 +1,9 @@
|
||||
"""A module that isn't a model: it has no `predict`."""
|
||||
|
||||
|
||||
def prepare(cohort):
|
||||
return cohort
|
||||
|
||||
|
||||
def fit(train):
|
||||
return None
|
||||
Reference in New Issue
Block a user