Remove the model catalog and its interface

This commit is contained in:
2026-11-04 20:47:34 -06:00
parent 122f71105a
commit 1f6e2df051
6 changed files with 64 additions and 210 deletions
-107
View File
@@ -1,107 +0,0 @@
"""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
+64
View File
@@ -0,0 +1,64 @@
"""What this module covers: `models.io.cohorts`, reading a cohort build's file; and the rule that a model's folder
doesn't import the database layer, since the file is its only input.
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
"""
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.cohorts import SCHEMA, CohortFileError, 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 results; member 20 has one."""
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_cohort_file_reads_as_a_frame(cohort_file):
"""Pins down: a build's file comes back with all its rows and columns. Fails if `read_cohort` drops rows or
columns, or refuses a file with the right schema."""
frame = read_cohort(cohort_file)
assert list(frame.columns) == SCHEMA.names
assert frame["pac_id"].tolist() == [10, 10, 20]
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(CohortFileError, 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