410de1d3b7
models/steps/indexing.py: a scenario that lists it gets its source cohort as `source_cohort`, and the node `cohort` re-indexes it by `[config.index]` of its model.toml: the surveillance kind (first cytology) and the post-colposcopy kind (visit k), with dbt's rules in dbt's order and names, the recruitment window taken from the source cohort's parameters. Every kind ends with `observacion_previa_insuficiente`, a threshold on the days observed before the index (0 for now: the data are left-truncated, so rules on earlier events read only what was recorded). On the synthetic copy the pipeline gives dbt's patients, index dates and attrition for cin2_pim and cin2_logistic (surveillance) and cin2_pim_post_colposcopy (visit 1, now on cacu/cohorte_total). cin2_logistic's MUESTREO records the index attrition and the prior history; a stored build's lineage carries its parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
281 lines
16 KiB
Python
281 lines
16 KiB
Python
"""What this module covers: `models.cacu.cin2_pim`: how a member's screening visits and biopsies become a code and an
|
|
interval (one test per worked example of `docs/codificacion_pim.md`), the dataflow from a long frame to its metrics by horizon, and training and estimating through the generic
|
|
driver, with every member scored at every horizon, also outside this repository.
|
|
|
|
Fixtures: `cohort_frame`, a long frame of 300 simulated members (a quarter with an abnormal index sample, some with a
|
|
prevalent or a later CIN2+ biopsy, the normal ones with a later negative cotest); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
|
|
`predict_without_repository` (conftest).
|
|
"""
|
|
|
|
from datetime import date, datetime, timedelta, timezone
|
|
|
|
import mlflow.pyfunc
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pyarrow as pa
|
|
import pyarrow.parquet as pq
|
|
import pytest
|
|
|
|
from models.cacu.cin2_pim import model
|
|
from models.dags import training
|
|
from models.dags.estimation import estimate
|
|
from models.io.contracts import COHORT_SCHEMA
|
|
from models.io.registry import PRODUCTION_ALIAS, registry
|
|
from models.io.storage import CohortFile
|
|
|
|
CUTOFF = date(2027, 6, 30)
|
|
SCENARIO = training.Scenario.load("cacu", "cin2_pim")
|
|
CONFIG = SCENARIO.config
|
|
|
|
|
|
def _row(pac_id, index, days, tipo, valor=None, sample=None):
|
|
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": "t",
|
|
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
|
|
|
|
|
|
def _visit(pac_id, index, day, bethesda, vph, sample=None):
|
|
return [_row(pac_id, index, day, "bethesda", bethesda, sample), _row(pac_id, index, day, "vph", vph, sample)]
|
|
|
|
|
|
def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()):
|
|
"""The index sample (its Bethesda and HPV results share its source row, as in the timeline), later visits and
|
|
biopsies."""
|
|
sample = f"S{pac_id}"
|
|
rows = [_row(pac_id, index, 0, "citologia", sample=sample), *_visit(pac_id, index, 7, bethesda, vph, sample)]
|
|
rows += [row for day, b, v in visits for row in _visit(pac_id, index, day, b, v)]
|
|
return rows + [_row(pac_id, index, day, "biopsia", grade) for day, grade in biopsies]
|
|
|
|
|
|
def _coded(rows):
|
|
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
|
coded = model.interval_coded_members(frame, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
|
|
CONFIG["index_sample_days"], CONFIG["known_negative"], CONFIG["cytology"],
|
|
CONFIG["history"])
|
|
return tuple(coded.iloc[0][["c", "l", "r"]])
|
|
|
|
|
|
INDEX = date(2025, 1, 1)
|
|
ASCUS_HPV = ("ASC-US", "POSITIVO")
|
|
COTEST_NEGATIVE = ("NORMAL", "NEGATIVO")
|
|
|
|
|
|
@pytest.fixture
|
|
def cohort_frame():
|
|
"""Abnormal members (every fourth) are biopsied within 2 months, CIN2+ for a third of them; a tenth of the normal
|
|
ones has a CIN2+ biopsy between 1 and 2 years later. Index dates rise with `pac_id` over 2023-2024."""
|
|
rng = np.random.default_rng(0)
|
|
rows = []
|
|
for pac_id in range(1, 301):
|
|
index = date(2023, 1, 1) + timedelta(days=2 * pac_id)
|
|
if pac_id % 4 == 0:
|
|
grade = "LIEAG" if rng.random() < 0.35 else "NEGATIVO"
|
|
rows += _member(pac_id, index, "LIEBG", "POSITIVO", [(45, grade)])
|
|
elif rng.random() < 0.1:
|
|
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")],
|
|
[(365, *COTEST_NEGATIVE)])
|
|
else:
|
|
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", visits=[(int(rng.integers(300, 900)), *COTEST_NEGATIVE)])
|
|
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
|
|
|
|
|
@pytest.fixture
|
|
def cohort_file(cohort_frame, tmp_path):
|
|
table = pa.Table.from_pandas(cohort_frame, schema=COHORT_SCHEMA, preserve_index=False)
|
|
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), "armado_id": "3"}
|
|
path = tmp_path / "3.parquet"
|
|
pq.write_table(table.replace_schema_metadata(lineage), path)
|
|
return path
|
|
|
|
|
|
def test_patient_1_a_cin2_biopsy_at_the_referral_colposcopy_is_prevalent():
|
|
"""Patient 1: ASC-US/HPV+ at T0, colposcopy a month later finds CIN3. Pins down `(1, 0, 0)`: she counts as a case
|
|
in the prevalence and adds nothing to the incidence. Fails if a CIN2+ within the window stops being prevalent."""
|
|
assert _coded(_member(1, INDEX, *ASCUS_HPV, [(30, "LIEAG")])) == (1, 0.0, 0.0)
|
|
|
|
|
|
def test_patient_2_the_interval_opens_at_the_last_negative_not_at_the_index():
|
|
"""Patient 2: ASC-US/HPV+ at T0, negative biopsies at T1 (a month), negative cotest at T2 (a year), ASC-US/HPV+ at
|
|
T3 (two years), CIN3 at T4. Pins down `(0, T2, T4]`: the negative colposcopy makes her a control in the prevalence,
|
|
T2 is the last time she was free, and T3's abnormal result isn't a negative. Fails if `l` goes back to 0 or an
|
|
abnormal visit is taken for a negative."""
|
|
c, l, r = _coded(_member(2, INDEX, *ASCUS_HPV, [(30, "NEGATIVO"), (760, "LIEAG")],
|
|
[(365, *COTEST_NEGATIVE), (730, *ASCUS_HPV)]))
|
|
|
|
assert (c, l, r) == (0, pytest.approx(365 / 365.25), pytest.approx(760 / 365.25))
|
|
|
|
|
|
def test_patient_3_a_case_never_found_free_has_an_unknown_baseline():
|
|
"""Patient 3: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US/HPV+ again at T1, CIN3 at T2. Pins down
|
|
`(-999, 0, T2]`: she may have been prevalent or incident, the likelihood weighs both, and onset is anywhere up to
|
|
T2 (not exactly at T2). Fails if a repeated abnormal result is taken for a known baseline."""
|
|
c, l, r = _coded(_member(3, INDEX, *ASCUS_HPV, [(395, "LIEAG")], [(365, *ASCUS_HPV)]))
|
|
|
|
assert (c, l, r) == (-999, 0.0, pytest.approx(395 / 365.25))
|
|
|
|
|
|
def test_patient_4_a_later_negative_cotest_settles_an_unknown_baseline():
|
|
"""Patient 4: ASC-US/HPV+ at T0, colposcopy skipped, negative cotest at T1 (a year). Pins down `(0, T1, inf)`: CIN2+
|
|
being absorbing, free at T1 means free at T0, so she's a control in the prevalence and right-censored at T1. Fails
|
|
if she's left unknown, which throws her away, or censored at the cut-off."""
|
|
c, l, r = _coded(_member(4, INDEX, *ASCUS_HPV, visits=[(365, *COTEST_NEGATIVE)]))
|
|
|
|
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
|
|
|
|
|
|
def test_an_hpv_negative_ascus_is_a_negative_visit():
|
|
"""KPNC's second negative without histology: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US with HPV negative at T1
|
|
(a year). Pins down `(0, T1, inf)`, as for patient 4's negative cotest. Fails if `known_negative` goes back to NILM
|
|
only, which leaves her unknown."""
|
|
c, l, r = _coded(_member(7, INDEX, *ASCUS_HPV, visits=[(365, "ASC-US", "NEGATIVO")]))
|
|
|
|
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
|
|
|
|
|
|
def test_an_hpv_positive_nilm_is_not_a_negative_visit():
|
|
"""The other side of the criterion: ASC-US/HPV+ at T0, colposcopy skipped, NILM with HPV positive at T1. Pins down
|
|
`(-999, 0, inf)`: a positive test without histology leaves the status unknown. Fails if a NILM alone counts."""
|
|
assert _coded(_member(8, INDEX, *ASCUS_HPV, visits=[(365, "NORMAL", "POSITIVO")])) == (-999, 0.0, np.inf)
|
|
|
|
|
|
def test_patient_5_a_negative_colposcopy_without_follow_up_counts_only_for_the_prevalence():
|
|
"""Patient 5: ASC-US/HPV+ at T0, negative biopsies a month later, no further visit. Pins down `(0, 0, inf)`: a
|
|
control in the prevalence whose factor holds no survival (S(0) = 1). Fails if she's credited follow-up up to the
|
|
cut-off that no test checked."""
|
|
assert _coded(_member(5, INDEX, *ASCUS_HPV, [(30, "NEGATIVO")])) == (0, 0.0, np.inf)
|
|
|
|
|
|
def test_patient_6_referred_and_lost_carries_no_information():
|
|
"""Patient 6: ASC-US/HPV+ at T0, colposcopy skipped, never seen again. Pins down `(-999, 0, inf)`, whose factor
|
|
is 1. Fails if she's given a code that adds a term."""
|
|
assert _coded(_member(6, INDEX, *ASCUS_HPV)) == (-999, 0.0, np.inf)
|
|
|
|
|
|
def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
|
"""Pins down the driver's external inputs: the loaders' `source_cohort` and `cohort_lineage` (the scenario's index
|
|
re-indexes the first into `cohort`) and the config's keys, and nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
|
|
or a module added to the driver rewires a parameter."""
|
|
required, optional = training.external_inputs(training.dataflow(*SCENARIO.modules, config=CONFIG))
|
|
|
|
assert required == {"source_cohort", "cohort_lineage", "cytology", "event_grades", "history", "horizons_years", "incidence",
|
|
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
|
|
"train_fraction"}
|
|
assert optional == {"index"} # from the config; a scenario without one keeps its cohort's index
|
|
|
|
|
|
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
|
|
"""Pins down: the graph runs from a frame to aggregates per horizon with no file and no MLflow, and the expected
|
|
rate at the index visit is near the observed one. Fails if a horizon is dropped, a metric isn't a number, or the
|
|
fit stops recovering the prevalence."""
|
|
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
|
|
["metrics"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["metrics"]
|
|
|
|
assert found["n_train"] == 210 and found["n_test"] == 90
|
|
assert {f"n_known_{h:g}y" for h in CONFIG["horizons_years"]} <= set(found)
|
|
assert all(isinstance(value, (int, float)) for value in found.values())
|
|
assert found["expected_0y"] == pytest.approx(found["observed_0y"], abs=0.05)
|
|
|
|
|
|
def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path,
|
|
predict_without_repository):
|
|
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per member
|
|
and horizon, a risk that doesn't fall with the horizon, the same outside this repository, and storable metadata.
|
|
Fails if the model or the estimate go back to one horizon, or the registered model needs this repository."""
|
|
version = training.train(SCENARIO, CohortFile(cohort_file))
|
|
registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version)
|
|
output = tmp_path / "estimate.parquet"
|
|
|
|
estimate(SCENARIO, CohortFile(cohort_file), output)
|
|
|
|
risks = pd.read_parquet(output)
|
|
assert len(risks) == 300 * len(CONFIG["horizons_years"])
|
|
by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad")
|
|
assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all()
|
|
assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2"
|
|
|
|
uri = registry.resolve("cacu", "cin2_pim", version).model_uri
|
|
outside = predict_without_repository(uri, pd.read_parquet(cohort_file))
|
|
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
|
|
assert outside.shape == (300, len(CONFIG["horizons_years"]))
|
|
np.testing.assert_allclose(outside.to_numpy(), inside)
|
|
|
|
|
|
def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame):
|
|
"""Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN
|
|
(not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up."""
|
|
members = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
|
|
["interval_coded_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["interval_coded_members"]
|
|
only_negative = members[members["hpv_positive"] == 0]
|
|
mixture = model.PrevalenceIncidenceMixture(CONFIG["horizons_years"], ("cytology",), ("hpv_positive",),
|
|
CONFIG["incidence"], {"cytology": list(CONFIG["cytology"])}).fit(
|
|
only_negative[model.FEATURES], only_negative[["c", "l", "r"]])
|
|
|
|
risks = mixture.predict_proba(members[model.FEATURES])
|
|
|
|
assert list(mixture.fits_) == [(0,)]
|
|
assert np.isnan(risks[members["hpv_positive"].to_numpy() == 1]).all()
|
|
assert not np.isnan(risks[members["hpv_positive"].to_numpy() == 0]).any()
|
|
|
|
|
|
def test_the_index_cytology_takes_kpncs_categories_not_a_binary():
|
|
"""Pins down the cytology of the TOML: each squamous or glandular code goes to its KPNC category (LIEBG is LSIL;
|
|
CIS and adenocarcinoma are HSIL+), with both results the more severe wins (AGC over ASC-US, HSIL+ over AGC), and a
|
|
member without a cytology gets none rather than the reference. Fails if the categories collapse back to
|
|
normal/abnormal, the glandular result is ignored, or a missing cytology is read as NILM."""
|
|
rows = [*_member(1, INDEX, "LIEBG", "POSITIVO"), *_member(2, INDEX, "CIS", "NEGATIVO"),
|
|
*_member(3, INDEX, "NORMAL", "NEGATIVO"), *_member(4, INDEX, "ASC-US", "POSITIVO"),
|
|
*_member(5, INDEX, "LIEAG", "POSITIVO"), *_member(6, INDEX, "NORMAL", "POSITIVO")]
|
|
glandular = [(4, "AGC"), (5, "AGC"), (6, "ADENOCARCINOMA")]
|
|
rows += [_row(pac_id, INDEX, 7, "glandular", code) for pac_id, code in glandular]
|
|
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
|
frame = frame[~((frame["pac_id"] == 3) & (frame["tipo"] == "bethesda"))]
|
|
|
|
found = model.index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
|
|
|
|
assert found["cytology"].tolist() == ["LSIL", "HSIL+", None, "AGC", "HSIL+", "HSIL+"]
|
|
|
|
|
|
POST_COLPOSCOPY = training.Scenario.load("cacu", "cin2_pim_post_colposcopy")
|
|
|
|
|
|
def _with_referral(rows, pac_id, index, bethesda, vph, colposcopy_days=-200, referral_days=-300):
|
|
"""A member's rows plus a referral result and a colposcopy before her index date."""
|
|
return rows + [*_visit(pac_id, index, referral_days, bethesda, vph), _row(pac_id, index, colposcopy_days, "colposcopia")]
|
|
|
|
|
|
def test_the_referral_grade_follows_kpncs_low_and_high_grade():
|
|
"""Pins down the history of the post-colposcopy TOML: HPV-positive NILM and LSIL referrals are low grade, ASC-H
|
|
high, an HPV-negative NILM refers no one and a result past the lookback doesn't count. Fails if the grade stops
|
|
reading the referral before the colposcopy, its HPV condition or the lookback."""
|
|
config = POST_COLPOSCOPY.config
|
|
rows = []
|
|
for pac_id, (bethesda, vph, referral_days) in enumerate([("NORMAL", "POSITIVO", -300), ("LIEBG", "NEGATIVO", -300),
|
|
("ASC-H", "NEGATIVO", -300), ("NORMAL", "NEGATIVO", -300),
|
|
("ASC-H", "POSITIVO", -700)], start=1):
|
|
rows = _with_referral(rows + _member(pac_id, INDEX, "NORMAL", "NEGATIVO"), pac_id, INDEX, bethesda, vph,
|
|
referral_days=referral_days)
|
|
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
|
|
|
found = model.index_results(frame, config["index_sample_days"], config["cytology"], config["history"])
|
|
|
|
assert found["referral_grade"].tolist() == ["low", "low", "high", None, None]
|
|
assert found["cytology"].tolist() == ["NILM"] * 5
|
|
|
|
|
|
def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame):
|
|
"""Pins down that a scenario is only its TOML: the post-colposcopy one runs `cin2_pim`'s dataflow with its own
|
|
cytology groups and referral grade, and gives metrics at every horizon. Fails if the shared dataflow stops taking
|
|
the history from the config or a scenario needs code of its own."""
|
|
rows = cohort_frame.to_dict("records")
|
|
for pac_id, group in cohort_frame.groupby("pac_id"):
|
|
index = group["fecha_indice"].iloc[0]
|
|
rows = _with_referral(rows, pac_id, index, "ASC-H" if pac_id % 3 == 0 else "LIEBG", "POSITIVO")
|
|
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
|
|
|
found = training.dataflow(*POST_COLPOSCOPY.modules, config=POST_COLPOSCOPY.config).execute(
|
|
["metrics"], inputs={"source_cohort": frame, "cohort_lineage": {}})["metrics"]
|
|
|
|
assert {f"n_known_{h:g}y" for h in POST_COLPOSCOPY.config["horizons_years"]} <= set(found)
|
|
assert training.Scenario.load("cacu", "cin2_pim_post_treatment").cohort == "cacu/cohorte_post_tratamiento"
|