CIN2+ PIM coding as KPNC's: a visit is free of CIN2+ with HPV-negative and NILM or ASC-US, a positive without histology leaves it unknown

known_negative takes lists per key; the last negative carries every earlier one, and follow-up without a test isn't
counted. docs/codificacion_pim.md gives the six example patients, each with its unit test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-19 20:23:36 -06:00
parent 0be622c12d
commit fe7f881ade
6 changed files with 358 additions and 62 deletions
+84 -28
View File
@@ -1,9 +1,9 @@
"""What this module covers: `models.cacu.cin2_pim`: how a member's index results and biopsies become a code and an
interval, the dataflow from a long frame to its metrics by horizon, and training and estimating through the generic
"""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); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
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).
"""
@@ -35,16 +35,26 @@ def _row(pac_id, index, days, tipo, valor=None):
"fuente_id": f"{pac_id}-{tipo}-{days}"}
def _member(pac_id, index, bethesda, vph, biopsies=()):
rows = [_row(pac_id, index, 0, "citologia"), _row(pac_id, index, 7, "bethesda", bethesda),
_row(pac_id, index, 7, "vph", vph)]
def _visit(pac_id, index, day, bethesda, vph):
return [_row(pac_id, index, day, "bethesda", bethesda), _row(pac_id, index, day, "vph", vph)]
def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()):
rows = [_row(pac_id, index, 0, "citologia"), *_visit(pac_id, index, 7, bethesda, vph)]
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)
return model.interval_coded_members(frame, CUTOFF, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
CONFIG["index_sample_days"], CONFIG["known_negative"]).set_index("pac_id")
coded = model.interval_coded_members(frame, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
CONFIG["index_sample_days"], CONFIG["known_negative"])
return tuple(coded.iloc[0][["c", "l", "r"]])
INDEX = date(2025, 1, 1)
ASCUS_HPV = ("ASC-US", "POSITIVO")
COTEST_NEGATIVE = ("NORMAL", "NEGATIVO")
@pytest.fixture
@@ -59,9 +69,10 @@ def cohort_frame():
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")])
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")],
[(365, *COTEST_NEGATIVE)])
else:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", visits=[(int(rng.integers(300, 900)), *COTEST_NEGATIVE)])
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
@@ -74,31 +85,76 @@ def cohort_file(cohort_frame, tmp_path):
return path
def test_each_member_gets_its_code_and_interval():
"""Pins down the coding: a CIN2+ biopsy in the window is prevalent; a known negative baseline with a later CIN2+
biopsy is incident in `(0, t]`; a known negative without one is censored at its follow-up; an abnormal sample with
no biopsy is unknown in `(0, inf)`; a negative biopsy in the window makes the baseline known. Fails if any case
gets another code, which changes what the likelihood counts."""
index = date(2025, 1, 1)
coded = _coded(_member(1, index, "LIEAG", "POSITIVO", [(30, "LIEAG")])
+ _member(2, index, "NORMAL", "NEGATIVO", [(730, "CIS")])
+ _member(3, index, "NORMAL", "NEGATIVO")
+ _member(4, index, "ASC-US", "POSITIVO")
+ _member(5, index, "ASC-US", "POSITIVO", [(60, "NEGATIVO")]))
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)
assert coded["c"].tolist() == [1, 0, 0, -999, 0]
assert coded.loc[2, "r"] == pytest.approx(730 / 365.25) and coded.loc[2, "l"] == 0.0
assert coded.loc[3, "l"] == pytest.approx((CUTOFF - index).days / 365.25) and np.isinf(coded.loc[3, "r"])
assert (coded.loc[4, "l"], coded.loc[4, "r"]) == (0.0, np.inf)
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' `cohort` and `cohort_lineage` and the config's keys, and
"""Pins down the driver's external inputs: the loader's `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 == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "index_sample_days",
assert required == {"cohort", "event_grades", "horizons_years", "index_sample_days",
"known_negative", "prevalent_window_months", "train_fraction"}
assert optional == set()
@@ -108,7 +164,7 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
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={"cohort": cohort_frame, "cohort_lineage": {"datos_as_of": CUTOFF.isoformat()}})["metrics"]
["metrics"], inputs={"cohort": cohort_frame})["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)
+25
View File
@@ -55,3 +55,28 @@ def test_cumulative_risk_starts_at_prevalence():
cr = L.cumulative_risk(fitted, X, Z, years=[0, 1, 5])
np.testing.assert_allclose(cr[:, 0], L.prevalence(fitted["theta"], X))
assert np.all(np.diff(cr, axis=1) >= 0)
def test_fit_finds_a_rare_incidence():
"""A rare outcome, like CIN3+ with HPV negative: the Weibull scale is thousands of years and only ~1 % has an
incident case in 7 yearly visits. Pins down that the fit reaches the optimum near the truth and not the far worse
one where a start at the median detection time used to leave it. Fails if the starting scale goes back to the
detection times."""
rng = np.random.default_rng(3)
n = 20000
group = rng.integers(0, 2, n)
X = np.column_stack([np.ones(n), group])
Z = group[:, None].astype(float)
theta, beta, scale, shape = np.array([-5.0, 1.0]), np.array([1.4]), 2500.0, 1.08
prevalent = rng.random(n) < L.prevalence(theta, X)
time = scale * (rng.exponential(size=n) / np.exp(Z @ beta)) ** (1 / shape)
c = np.where(prevalent, 1, 0)
l = np.where(prevalent, 0.0, np.minimum(np.floor(time), 7.0))
r = np.where(prevalent, 0.0, np.where(time < 7, np.floor(time) + 1, np.inf))
fitted = L.fit(c, l, r, X, Z)
truth = L.neg_loglik(np.r_[theta, beta, np.log(scale), np.log(shape)], c, l, r, X, Z)
assert fitted["converged"] and fitted["neg_loglik"] <= truth + 1e-6
np.testing.assert_allclose(fitted["beta"], beta, atol=0.4)
assert np.all(np.isfinite(fitted["se"]))