CaCu CIN2+ prototype: a CIN2+ biopsy within a provisional 12-month window, predicted from the index sample's results

This commit is contained in:
2026-11-06 00:15:12 -06:00
parent f070d9f037
commit 22d1fda0f3
4 changed files with 159 additions and 66 deletions
+82 -38
View File
@@ -1,10 +1,11 @@
"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
split, that training on a build's file registers a version with its lineage, and the `models train` and
`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none.
"""What this module covers: `models.cacu.cin2_logistic`: its outcome (a CIN2+ biopsy within the window, with members
whose window isn't complete left out) and predictors (the index sample's results), its temporal split, that training on
a build's file registers a version with its lineage, and the `models train`, `models estimate` and `models run`
commands over it, repeating no step.
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; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a
SQLite-backed MLflow.
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `dbt_exported`, builds 1 and 2
of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
from datetime import date, datetime, timedelta, timezone
@@ -22,88 +23,132 @@ from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
from models.io.registry import PRODUCTION_ALIAS, registry
CUTOFF = date(2027, 6, 30)
def _row(pac_id, index, days, valor, tipo="bethesda"):
def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None):
clase = {"citologia": "procedimiento", "biopsia": "medicion"}.get(tipo, "medicion")
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}"}
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": clase, "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": "citologiacervical",
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
def _member(pac_id, index, bethesda, vph, biopsy=None, biopsy_day=60):
"""The index cytology, its Bethesda and HPV results (same sample, reported on day 7), and a biopsy if given."""
sample = f"S{pac_id}"
rows = [_row(pac_id, index, 0, "citologia", sample=sample), _row(pac_id, index, 7, "bethesda", bethesda, sample),
_row(pac_id, index, 7, "vph", vph, sample)]
if biopsy:
rows.append(_row(pac_id, index, biopsy_day, "biopsia", biopsy))
return rows
@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."""
"""Odd members: LIEAG and HPV positive at the index sample, then a LIEAG biopsy on day 60 (the event). Even members:
NORMAL and HPV negative, then a second cytology on day 400 graded LIEAG, which the predictors 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"))
if pac_id % 2:
rows += _member(pac_id, index, "LIEAG", "POSITIVO", biopsy="LIEAG")
else:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
rows += [_row(pac_id, index, 400, "citologia", sample=f"T{pac_id}"),
_row(pac_id, index, 405, "bethesda", "LIEAG", f"T{pac_id}")]
return pd.DataFrame(rows, columns=SCHEMA.names)
def _write(frame, path, armado_id):
def _write(frame, path, metadata):
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
path.parent.mkdir(parents=True, exist_ok=True)
pq.write_table(table.replace_schema_metadata({"armado_id": str(armado_id), "url": "cacu/cohorte_vigilancia"}), path)
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), **metadata}
pq.write_table(table.replace_schema_metadata({k: str(v) for k, v in lineage.items()}), path)
return path
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 7's file."""
return _write(cohort_frame, tmp_path / "7.parquet", 7)
return _write(cohort_frame, tmp_path / "7.parquet", {"armado_id": 7})
@pytest.fixture
def exported(cohort_frame, tmp_path, monkeypatch):
"""Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to."""
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia"
_write(cohort_frame, folder / "7.parquet", 7)
_write(cohort_frame, folder / "12.parquet", 12)
_write(cohort_frame, folder / "7.parquet", {"armado_id": 7})
_write(cohort_frame, folder / "12.parquet", {"armado_id": 12})
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
return folder
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")
def test_predictors_are_the_index_sample_results(cohort_frame):
"""Pins down: each member's predictors come from the sample of the index cytology, matched by its source row, and a
result the sample doesn't have is `(none)`. Fails if a later sample's result (member 2's LIEAG on day 405) is
taken, or a missing result becomes NaN, which the encoder would reject."""
found = model.predictors(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]
assert len(found) == 20
assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"]
assert found.loc[2, ["bethesda", "vph"]].tolist() == ["NORMAL", "NEGATIVO"]
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."""
def test_the_genotype_is_read_from_its_number():
"""Pins down: the HPV 16/18 result is stored as 1 or 0 in `valor_numerico`, and becomes POSITIVO or NEGATIVO. Fails
if the genotype is read from `valor_codigo`, which is empty for it."""
index = date(2025, 1, 1)
frame = pd.DataFrame([_row(1, index, 90, "LIEAG"), _row(1, index, 40, "ASC-US"), _row(1, index, 200, "NORMAL")])
frame = pd.DataFrame(_member(1, index, "ASC-US", "POSITIVO")
+ [_row(1, index, 7, "vph_genotipo_16_18", sample="S1", numero=1.0)], columns=SCHEMA.names)
assert model.prepare(frame).loc[0, "days"] == 40
assert model.predictors(frame).loc[0, "vph_16_18"] == "POSITIVO"
@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0),
("LIEAG", 400, 0)])
def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected):
"""Pins down: `y` is 1 only for a biopsy graded LIEAG, CIS or CARCINOMA within 12 months of the index date. Fails if
a lower grade counts, or a biopsy after the window does."""
frame = pd.DataFrame(_member(1, date(2025, 1, 1), "NORMAL", "NEGATIVO", biopsy=grade, biopsy_day=day),
columns=SCHEMA.names)
assert model.outcome(frame, CUTOFF).loc[0, "y"] == expected
def test_a_member_without_a_complete_window_is_scored_but_not_trained_on():
"""Pins down: a member with no event and less than the window's follow-up to the cut-off isn't known and is left out
of `prepare`; one with the event is kept however short the follow-up. Fails if unknown members train as negatives,
which biases the risk down."""
late = date(2027, 3, 1)
frame = pd.DataFrame(_member(1, late, "NORMAL", "NEGATIVO") + _member(2, late, "LIEAG", "POSITIVO", biopsy="CIS",
biopsy_day=30), columns=SCHEMA.names)
outcome = model.outcome(frame, CUTOFF).set_index("pac_id")
assert outcome["known"].tolist() == [False, True]
assert model.prepare(model.predictors(frame), model.outcome(frame, CUTOFF))["pac_id"].tolist() == [2]
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))
parts = model.split(model.prepare(model.predictors(cohort_frame), model.outcome(cohort_frame, CUTOFF)))
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`."""
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash, the outcome's
window and the note that it's a prototype, and an artifact that holds `predictors`, 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 "Prototipo" in stored.description and run.params["outcome_window_months"] == "12"
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
assert len(run.params["cohort_sha256"]) == 64
@@ -239,7 +284,7 @@ def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
assert main([*RUN, "--train", "--armado", "7"]) == 0
assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0
frame = pd.read_parquet(exported / "12.parquet")
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12)
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", {"armado_id": 12})
assert main([*RUN, "--train", "--armado", "12"]) == 0
assert len(_versions()) == 3
@@ -300,8 +345,7 @@ def dbt_exported(cohort_frame, tmp_path, monkeypatch):
for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])):
path = folder / f"{number}.parquet"
path.parent.mkdir(parents=True, exist_ok=True)
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
pq.write_table(table.replace_schema_metadata({"build": str(number), "producer": "dbt", "url": "cacu/cohorte_vigilancia"}), path)
_write(frame, path, {"build": number, "producer": "dbt"})
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
return folder