Files
models/tests/cacu/test_cin2_pim_likelihood.py
edgar 3e72063e3f cin2_pim with PIMixture's I-spline baseline, frequency weights, HPV strata and KPNC's cytology categories
The incidence baseline is chosen in model.toml (Weibull or I-splines of order 4 with knots at quantiles, equal to
PIMixture's Ispline); identical rows are fitted once with their count as weight; one mixture per stratum, a member of
an unseen stratum or level gets NaN. The index cytology goes into KPNC's six categories, glandular results included and
the most severe winning; an optional history feature is read from the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 12:06:05 -06:00

120 lines
5.5 KiB
Python

import numpy as np
import pytest
from models.cacu.cin2_pim import likelihood as L
def simulate(n=4000, seed=0):
"""Two groups, known prevalence and Weibull incidence, screening every year for 5 years."""
rng = np.random.default_rng(seed)
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([-3.0, 1.5]), np.array([0.7]), 8.0, 1.3
prevalent = rng.random(n) < L.prevalence(theta, X)
time = scale * (-np.log(rng.random(n)) / np.exp(Z @ beta)) ** (1 / shape)
c = np.where(prevalent, 1, 0)
l = np.where(prevalent, 0.0, np.minimum(np.floor(time), 5.0))
r = np.where(prevalent, 0.0, np.where(time < 5, np.floor(time) + 1, np.inf))
return c, l, r, X, Z, theta, beta, scale, shape
def test_survival_limits():
Z = np.zeros((3, 1))
s = L.weibull_survival([0.0, 2.0, np.inf], np.log(5.0), 0.0, np.zeros(1), Z)
assert s[0] == 1.0 and s[2] == 0.0
assert s[1] == pytest.approx(np.exp(-2 / 5))
def test_fit_recovers_simulated_parameters():
c, l, r, X, Z, theta, beta, scale, shape = simulate()
fitted = L.fit(c, l, r, X, Z)
assert fitted["converged"]
np.testing.assert_allclose(fitted["theta"], theta, atol=0.3)
np.testing.assert_allclose(fitted["beta"], beta, atol=0.3)
assert np.exp(fitted["log_scale"]) == pytest.approx(scale, rel=0.3)
assert np.exp(fitted["log_shape"]) == pytest.approx(shape, rel=0.3)
def test_unknown_rows_only_add_information_about_the_mixture():
"""A row with c = -999 and l = 0, r = inf says nothing: it contributes log(1) = 0."""
c, l, r, X, Z, *_ = simulate(n=200)
params = np.zeros(X.shape[1] + Z.shape[1] + 2)
base = L.neg_loglik(params, c, l, r, X, Z)
c2 = np.r_[c, L.UNKNOWN]
l2, r2 = np.r_[l, 0.0], np.r_[r, np.inf]
X2, Z2 = np.vstack([X, X[:1]]), np.vstack([Z, Z[:1]])
assert L.neg_loglik(params, c2, l2, r2, X2, Z2) == pytest.approx(base, abs=1e-9)
def test_cumulative_risk_starts_at_prevalence():
c, l, r, X, Z, *_ = simulate(n=500)
fitted = L.fit(c, l, r, X, Z)
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"]))
def test_the_ispline_basis_rises_from_0_to_1_and_has_knots_plus_order_minus_2_functions():
"""Pins down PIMixture's basis: H0(0) = 0, flat at 1 from the last knot on, each function non-decreasing, and the
count PIMixture's `Ispline` gives. Fails if the basis stops starting at 0 (the bug that gave events at t = 1 zero
probability) or the count drifts from PIMixture's."""
knots = (0.0, 2.0, 5.0)
t = np.linspace(0, 8, 81)
basis = L.ispline_basis(np.r_[t, np.inf], 3, knots)
assert basis.shape == (82, len(knots) + 3 - 2)
assert (basis[0] == 0).all() and (basis[:-1][t >= 5] == 1).all() and (basis[-1] == 1).all()
assert (np.diff(basis[:-1], axis=0) >= -1e-12).all()
def test_the_ispline_mixture_recovers_a_weibull_cumulative_risk():
"""Pins down that the weakly-parametric baseline fits data it wasn't generated from: the I-spline's cumulative
risk at 1 to 5 years is close to the Weibull truth. Fails if the I-spline's start or parameterization breaks."""
c, l, r, X, Z, theta, beta, scale, shape = simulate()
baseline = L.ISpline(L.quantile_knots(l, r, 3), order=3)
fitted = L.fit(c, l, r, X, Z, baseline)
years = [1.0, 3.0, 5.0]
truth = L.cumulative_risk({"theta": theta, "beta": beta, "log_scale": np.log(scale), "log_shape": np.log(shape)},
X[:2], Z[:2], years)
assert fitted["converged"]
np.testing.assert_allclose(L.cumulative_risk(fitted, X[:2], Z[:2], years), truth, atol=0.02)
def test_a_frequency_weight_is_the_same_as_repeating_the_row():
"""Pins down the weights: a row with weight 2 contributes as two identical rows, so collapsing duplicates
doesn't change the fit. Fails if the weights stop multiplying each row's log-likelihood."""
c, l, r, X, Z, *_ = simulate(n=300)
params = np.r_[-3.0, 1.5, 0.7, np.log(8.0), np.log(1.3)]
twice = L.neg_loglik(params, *(np.r_[a, a] for a in (c, l, r)), np.r_[X, X], np.r_[Z, Z])
assert L.neg_loglik(params, c, l, r, X, Z, w=np.full(len(c), 2.0)) == pytest.approx(twice)