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
+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"