Model interface over frames and a model catalog
This commit is contained in:
@@ -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