Files
models/tests/cacu/test_cin2_logistic.py
T

94 lines
4.5 KiB
Python

"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
split, and that training on a build's file registers a version with its lineage.
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
build's Parquet file with its lineage; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
from datetime import date, datetime, timedelta, timezone
import mlflow.pyfunc
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cacu.cin2_logistic import model
from models.cacu.cin2_logistic.train import train
from models.io.cohorts import SCHEMA
from models.io.registry import ARMADO_TAG, MODEL_SHA_TAG, registry
def _row(pac_id, index, days, valor, tipo="bethesda"):
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical",
"fuente_id": f"{pac_id}-{tipo}-{days}"}
@pytest.fixture
def cohort_frame():
"""Odd members become abnormal at day 30 after a normal result; even ones stay normal until day 300. An HPV row
each, which the outcome must ignore."""
rows = []
for pac_id in range(1, 21):
index = date(2025, 1, 1) + timedelta(days=pac_id)
rows += [_row(pac_id, index, 0, "NORMAL"), _row(pac_id, index, 5, "POSITIVO", tipo="vph")]
rows.append(_row(pac_id, index, 30, "LIEBG") if pac_id % 2 else _row(pac_id, index, 300, "NORMAL"))
return pd.DataFrame(rows, columns=SCHEMA.names)
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 7's file."""
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
path = tmp_path / "7.parquet"
pq.write_table(table.replace_schema_metadata({"armado_id": "7", "url": "cacu/cohorte_vigilancia"}), path)
return path
def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame):
"""Pins down: `y` is 1 with any abnormal result; `days` reaches the first abnormal result, or the last result when
`y` is 0. Fails if another variable's value counts as abnormal, or either date rule changes."""
prepared = model.prepare(cohort_frame).set_index("pac_id")
assert len(prepared) == 20
assert prepared.loc[1, ["y", "days"]].tolist() == [1, 30]
assert prepared.loc[2, ["y", "days"]].tolist() == [0, 300]
def test_first_abnormal_result_sets_days_when_there_are_several():
"""Pins down: with two abnormal results, `days` is the earlier one even if the file's order says otherwise. Fails
if `days` takes the last abnormal result or the first row."""
index = date(2025, 1, 1)
frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")])
assert model.prepare(frame).loc[0, "days"] == 40
def test_split_trains_on_the_oldest_index_dates(cohort_frame):
"""Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split
is random or follows another column."""
parts = model.split(model.prepare(cohort_frame))
assert (len(parts["train"]), len(parts["test"])) == (14, 6)
assert parts["train"]["fecha_indice"].max() < parts["test"]["fecha_indice"].min()
def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking):
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash and the note that
it has no clinical meaning, and an artifact that holds `prepare`, so it takes the long frame. Fails if any is lost, or
if the driver stops reaching `registered_model`."""
version = train(cohort_file)
resolved = registry.resolve("cacu", "cin2_logistic", version)
stored = registry.get("cacu", "cin2_logistic", version)
run = registry.client.get_run(stored.run_id).data
assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha
assert "sin significado clínico" in stored.description
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
assert len(run.params["cohort_sha256"]) == 64
probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
assert len(probabilities) == 20 and probabilities.between(0, 1).all()