CaCu models: no risk without HPV, hidden models untrained, inputs kept per prediction, attrition and variance diagnostics, rebuild job, opt-in Firth development evaluation

This commit is contained in:
Roberto Treviño
2026-12-05 19:42:07 -06:00
parent 69f5c20e2f
commit 20651b8d17
16 changed files with 802 additions and 68 deletions
+46
View File
@@ -0,0 +1,46 @@
"""The opt-in development evaluation (models.cacu.development): Firth and its FLIC and FLAC
corrections, and the nested selection that never looks outside its training partition."""
import numpy as np
import pandas as pd
import pytest
from models.cacu.development import METHODS, Firth, candidates, evaluate
def data(n=60, seed=0):
rng = np.random.default_rng(seed)
X = pd.DataFrame({"a": rng.integers(0, 2, n), "b": rng.integers(0, 2, n)}, dtype=float)
X.loc[:5, "a"] = np.nan
X["not_a"], X["sparse"], X["counts"] = 1 - X["a"], np.nan, rng.integers(0, 5, n)
y = (rng.random(n) < 0.15 + 0.5 * X["b"]).astype(int).to_numpy()
return X, y
def test_flic_matches_the_outcome_rate_and_flac_stays_near_firth():
X, y = data()
fitted = {m: Firth(m).fit(X[["b"]], y).predict_proba(X[["b"]])[:, 1] for m in METHODS}
assert fitted["flic"].sum() == pytest.approx(y.sum())
assert np.abs(fitted["flac"] - fitted["firth"]).max() < 0.05
with pytest.raises(ValueError, match="collinear"):
Firth().fit(np.column_stack([X["b"], X["b"]]), y)
def test_candidates_are_known_binary_and_distinguishable():
X, _ = data()
assert candidates(X, 0.7, 5) == ["b", "a"] # not_a is a's complement; the rest aren't 0/1
assert candidates(X, 0.95, 5) == ["b"]
def test_nested_selection_reports_every_method_validation_and_attempt():
X, y = data()
found = evaluate(X, y)
assert found["development_only"] and found["max_subsets"] == 16
for plan in ("cv", "loocv"):
for method in METHODS:
result = found["validation"][plan][method]
assert result["unscored"] == 0 and set(result["metrics"]) >= {"auc", "brier"}
assert all(set(chosen) <= {"a", "b"} for chosen in result["selected"])
assert {a["method"] for a in found["attempts"]} == set(METHODS)
with pytest.raises(ValueError, match="exceeds"):
evaluate(X, y, max_fits=10)
+113
View File
@@ -0,0 +1,113 @@
"""The development encoders (models.cacu.encoders) read only what was available at the index
and never turn an absent value into 0."""
import numpy as np
import pandas as pd
import pytest
from models.cacu.encoders import FINDINGS, encode
INDEX = "2025-06-10"
SAMPLE = "2025-01-10"
def ev(date, kind, code=None, *, person="p1", table="cervical_cytology", source=None,
clinical=None, available=None) -> dict: # fmt: skip
return {"person_id": person, "index_date": INDEX, "date": date, "type": kind,
"value_code": code, "value_num": np.nan, "source_table": table,
"source_id": source or date, "evidence_date": clinical,
"source_available_at": available} # fmt: skip
def encoded(events, forms=None, person="p1") -> pd.Series:
blank = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
forms = None if forms is None else pd.DataFrame([blank | f for f in forms])
found = encode(pd.DataFrame(events), forms).set_index("person_id")
return found.loc[person].drop("index_date").astype(float)
def test_an_unknown_value_is_missing_never_zero():
assert encoded([ev(INDEX, "cytology", "satisfactory")]).isna().all()
found = encoded([
ev("1980-06-11", "birth", table="person"),
*(ev("2025-01-15", k, c, source=SAMPLE) for k, c in (
("bethesda", "LSIL"), ("hpv", "positive"), ("hpv_16", "negative"))),
ev(INDEX, "cervix_appearance", "lesion"), ev(INDEX, "presenting_symptom", "other?"),
]) # fmt: skip
assert (found["age__35-44"], found["age__45-54"]) == (1, 0)
assert (found["bethesda__LSIL"], found["bethesda__HSIL"]) == (1, 0)
assert (found["cytology_ascus_plus"], found["cytology_hsil_plus"]) == (1, 0)
assert (found["hpv_positive"], found["hpv_16_positive"]) == (1, 0)
assert np.isnan(found["hpv_18_positive"])
assert np.isnan(found["hpv_16_or_18_positive"]) # one negative, the other unreported
assert (found["cervix_appearance__lesion"], found["cervix_appearance__healthy"]) == (1, 0)
assert found.filter(like="presenting_symptom").isna().all() # not one of its codes
assert found.filter(like="prior_").isna().all()
@pytest.mark.parametrize("hpv_16, hpv_18, expected", [
("positive", None, 1.0), ("negative", "negative", 0.0),
("negative", "positive", 1.0)]) # fmt: skip
def test_genotypes_of_one_sample(hpv_16, hpv_18, expected):
events = [ev("2025-01-15", "hpv_16", hpv_16)]
events += [ev("2025-01-15", "hpv_18", hpv_18)] if hpv_18 else []
assert encoded(events)["hpv_16_or_18_positive"] == expected
def test_what_was_not_available_at_the_index_is_not_read():
base = [ev(INDEX, "cytology", "satisfactory")]
later = [
ev("2025-06-20", "bethesda", "HSIL", source=INDEX), # the index sample's report
ev("2025-06-20", "hpv", "positive", source=INDEX),
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
ev("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
# the index day's procedures may be the outcome
ev(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
ev(INDEX, "colposcopy", table="clinical_note"),
ev(INDEX, "treatment", table="clinical_note"),
ev("2025-08-01", "history", table="clinical_note"),
# standalone evidence with no availability: its onset says nothing of when it was known
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence"),
] # fmt: skip
forms = [{"person_id": "p1", "sample_date": INDEX, "report_date": "2025-06-20",
"adequacy": "unsatisfactory", "finding_atrophy": True}] # fmt: skip
pd.testing.assert_series_equal(encoded(base + later, forms), encoded(base))
found = encoded([
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence", available="2024-01-01"),
]) # fmt: skip
assert (found["cytology_hsil_plus"], found["history_hysterectomy"]) == (1, 1)
def test_prior_procedures_and_the_referral_grade():
found = encoded([
ev("2025-01-15", "bethesda", "HSIL", source=SAMPLE),
ev("2025-03-01", "colposcopy", table="clinical_note"),
ev("2025-03-01", "biopsy_order", table="cervical_biopsy"),
ev("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
]) # fmt: skip
assert (found["prior_colposcopy"], found["prior_biopsy_order"]) == (1, 1)
assert (found["prior_biopsy_lsil_plus"], found["prior_biopsy_hsil_plus"]) == (1, 0)
assert found["referral_high_grade"] == 1 and np.isnan(found["prior_treatment"])
def test_the_form_is_read_from_its_latest_report_whole():
forms = [
{"person_id": "p1", "sample_date": "2024-01-10", "report_date": "2024-01-20",
"screening_history": "never", "finding_atrophy": True},
{"person_id": "p1", "sample_date": SAMPLE, "report_date": "2025-01-20",
"adequacy": "satisfactory", "finding_candida": 1},
] # fmt: skip
found = encoded([ev(INDEX, "cytology")], forms)
assert found["screening_history__never"] == 1
assert (found["sample_unsatisfactory"], found["finding_candida"]) == (0, 1)
assert np.isnan(found["finding_atrophy"])
def test_members_apart_and_a_timeline_without_availability_refused():
events = [ev("2025-01-15", "hpv", "positive"), ev(INDEX, "cytology", person="p2")]
assert np.isnan(encoded(events, person="p2")["hpv_positive"])
with pytest.raises(KeyError, match="source_available_at"):
encode(pd.DataFrame([ev(INDEX, "cytology")]).drop(columns="source_available_at"))
+21 -1
View File
@@ -5,6 +5,9 @@ gives the current model's predictions.
Fixed on purpose, so left out of the comparison:
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
(1970-01-01 for everyone); the rewrite returns the index sample's date.
- A patient without an HPV result at the index is not evaluated; the current models read it
as negative, so a result that is not positive stands in for it here.
- An interval whose covariance can't be estimated is unknown, not the current platform's.
"""
import json
@@ -14,6 +17,8 @@ import numpy as np
import pandas as pd
import pytest
from core import cacu
from models.cacu.features import days, prepared
from models.cacu.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
@@ -55,11 +60,23 @@ def timelines(cohort: str) -> pd.DataFrame:
return found
def assumed_hpv(events: pd.DataFrame) -> pd.DataFrame:
"""A not-positive HPV result (nor a negative one) at the index of whoever has none."""
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
tested = events.loc[(events["type"] == "hpv") & near.to_numpy(), "person_id"]
index = events.groupby("person_id", as_index=False).first()
missing = index[~index["person_id"].isin(tested)]
assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed")
return pd.concat([events, assumed[events.columns]], ignore_index=True)
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
"cin2_logistic"]) # fmt: skip
def test_predictions_match_the_current_models(name):
spec = MODELS[name]
events = timelines(COHORTS[spec.cohort])
if spec.method != "logistic regression":
events = assumed_hpv(events)
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
model, metrics, _ = spec.train(events, *args)
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
@@ -78,7 +95,9 @@ def test_predictions_match_the_current_models(name):
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
if theirs in both:
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
kept = both[ours].notna() | (ours == "probability") # estimable intervals
np.testing.assert_allclose(both.loc[kept, ours], both.loc[kept, theirs], rtol=RTOL,
atol=0) # fmt: skip
if spec.method != "logistic regression":
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
@@ -105,6 +124,7 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
found = spec.predict(model, events)
assert all(set(json.loads(v)) == set(spec.features) for v in found["input_values"])
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
+75
View File
@@ -0,0 +1,75 @@
"""What CaCu training keeps besides the models: who each cohort lost and why; that a patient
without HPV is not evaluated; and that the mixture never makes up a risk or an interval it
can't estimate (unseen levels, improper covariances, frozen parameters)."""
from datetime import date
import numpy as np
import pandas as pd
from core import cacu
from models.cacu import features, reports
from models.cacu.pim import Fit, ISpline, Mixture
BASELINE = ISpline((0.0, 1.0, 2.0), 2)
PARAMS = np.zeros(1 + BASELINE.n_params)
X1, Z0 = np.ones((1, 1)), np.empty((1, 0))
def fit(covariance) -> Fit:
return Fit(1, 0, BASELINE, PARAMS, covariance, 0.0, True)
def test_a_candidate_out_for_two_reasons_is_excluded_once():
rows = pd.DataFrame([
("eligible", "2025-01-01", None), ("two", "2025-01-01", "hysterectomy"),
("two", "2025-01-01", "under_18"), ("waiting", "2025-01-01", "no_index_result"),
("both", "2025-01-01", "no_index_result"), ("both", "2025-01-01", "prior_outcome"),
("after", "2025-07-01", "hysterectomy"),
], columns=["person_id", "index_date", "criterion"]).assign(index_sample_id=None) # fmt: skip
found = reports.attrition("cacu_cohort_surveillance", "surveillance", rows, 10,
date(2025, 6, 30)) # fmt: skip
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
assert (found["pending"], found["without_candidate"]) == (1, 6)
assert found["by_reason"] == {"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1,
"under_18": 1} # fmt: skip
assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2}
assert found["stage_by_reason"]["no_index_result"] == "index"
def test_without_an_hpv_result_she_is_not_evaluated():
day = pd.Timestamp("2025-01-01")
rows = [(p, day, day, "bethesda", "NILM") for p in ("negative", "positive", "none")]
rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")]
events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"])
found = features.index_results(events, cacu.KPNC)
assert dict(zip(found["person_id"], found["hpv_positive"], strict=True)) == {
"negative": 0.0, "positive": 1.0} # fmt: skip
def test_rows_only_at_unseen_levels_get_no_risk():
X = pd.DataFrame({"cytology": ["NILM", "NILM", "ASC-US", "ASC-US"] * 10})
y = pd.DataFrame({"c": [0, 1] * 20, "l": [1.0, 0.0] * 20, "r": [np.inf, 0.0] * 20})
y.loc[::5, ["c", "l", "r"]] = [-999, 0.5, 2.0]
mixture = Mixture((1, 5), ["cytology"], (), {"cytology": ["NILM", "ASC-US", "High Grade"]})
mixture.fit(X, y)
assert np.isnan(mixture.predict(pd.DataFrame({"cytology": ["High Grade"]}))).all()
def test_an_improper_covariance_gives_no_interval_never_a_zero_width_one():
assert np.isfinite(fit(np.eye(len(PARAMS))).risk_with_variance(X1, Z0, [0, 1])[1]).all()
n = len(PARAMS)
for covariance in (np.full((n, n), np.nan), -np.eye(n), np.zeros((n, n))):
assert np.isnan(fit(covariance).risk_with_variance(X1, Z0, [0, 1])[1]).all()
frozen = np.eye(n)
frozen[1, :] = frozen[:, 1] = np.nan # a frozen parameter moves only some horizons
variance = fit(frozen).risk_with_variance(X1, Z0, [0, 1])[1]
assert np.isfinite(variance[0, 0]) and np.isnan(variance[0, 1])
def test_diagnostics_count_the_rows_without_an_interval():
model = Mixture((0, 1), (), (), {})
model.fits_, model.seen_ = {(): fit(-np.eye(len(PARAMS)))}, {(): {}}
(stratum,) = model.variance_diagnostics(pd.DataFrame(index=range(2)))["strata"]
assert stratum["rows_without_interval"] == 2 and stratum["negative_variances"]
assert stratum["status"] == "not_estimable"