Model interface over frames and a model catalog

This commit is contained in:
2026-11-04 20:39:52 -06:00
parent 34de6e9348
commit 27e29804aa
7 changed files with 243 additions and 6 deletions
+73
View File
@@ -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()
+30
View File
@@ -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)