import pytest import numpy as np from scipy.stats import norm from models.cacu.bayes_development import prevalence_gibbs as PG def test_normal_posterior_is_least_squares_under_a_flat_prior(): """Fails if the conjugate mean does not reduce to least squares when the prior carries no information.""" rng = np.random.default_rng(1) X = np.column_stack([np.ones(200), rng.normal(size=200)]) z = X @ [0.5, -1.0] + rng.normal(size=200) m, L = PG.normal_posterior(X, z, np.zeros(2), np.eye(2) * 1e-10) assert np.allclose(m, np.linalg.lstsq(X, z, rcond=None)[0], atol=1e-6) assert np.allclose(L @ L.T, np.linalg.inv(X.T @ X), rtol=1e-6) def test_latent_sign_follows_g(): """Fails if a truncated latent falls on the wrong side of zero.""" rng = np.random.default_rng(2) g = rng.random(1000) < 0.5 z = PG.draw_latent(rng.normal(size=1000) * 3, g, rng) assert np.all((z > 0) == g) def test_prob_g_by_observation(): """Fails if a tested positive is not certainly diseased, an untested woman does not keep her prior, or a tested negative is not discounted by 1 - kappa.""" p, k = np.full(3, 0.2), 0.7 out = PG.prob_g(p, np.array([1, 0, 1]), np.array([1.0, np.nan, 0.0]), k) assert out[0] == 1.0 and np.isclose(out[1], 0.2) assert np.isclose(out[2], 0.2 * 0.3 / (0.2 * 0.3 + 0.8)) def test_gibbs_recovers_the_prevalence_with_known_sensitivity(): """Fails if, with kappa pinned by a strong prior, the chain misses the true probit coefficients of a simulated cross-sectional sample (60 % tested, one test each).""" rng = np.random.default_rng(3) n, beta, kappa = 6000, np.array([-1.2, 0.8]), 0.7 X = np.column_stack([np.ones(n), rng.random(n) < 0.4]) g = rng.random(n) < norm.cdf(X @ beta) r = (rng.random(n) < 0.6).astype(int) y = np.where(r == 1, g & (rng.random(n) < kappa), np.nan) out = PG.gibbs(X, r, y, np.zeros(2), np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=4) assert np.allclose(out["beta"].mean(0), beta, atol=0.12) assert abs(out["kappa"].mean() - 0.7) < 0.02 def test_referral_odds(): """Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) / Phi(eta) for a tested woman and the same with the survival function for an untested one.""" eta, gg = np.array([-1.0, -1.0, 0.5]), 0.8 out = PG.referral_odds(eta, gg, np.array([0.0, 1.0, 1.0]), np.array([1, 1, 0])) assert np.isclose(out[0], 1.0) assert np.isclose(out[1], norm.cdf(-0.2) / norm.cdf(-1.0)) assert np.isclose(out[2], norm.sf(1.3) / norm.sf(0.5)) def _referral_sample(n=8000, seed=5): """Two cells: the protocol refers the abnormal one (84 %); the normal one is referred mostly when diseased (3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell: Phi(-1.6) = 5.5 %.""" rng = np.random.default_rng(seed) abnormal = (rng.random(n) < 0.2).astype(float) X = np.column_stack([np.ones(n), abnormal]) g = rng.random(n) < norm.cdf(X @ [-1.6, 1.2]) U = np.column_stack([np.ones(n), abnormal]) arc = 1.0 - abnormal r = (rng.random(n) < norm.cdf(U @ [-1.8, 2.8] + 1.5 * arc * g)).astype(int) y = np.where(r == 1, g & (rng.random(n) < 0.7), np.nan) return X, r, y, U, arc def test_the_arc_removes_the_selection_bias(): """Fails if ignoring who gets referred does not overstate the prevalence of the unreferred cell, or if the arc with an informative prior on gamma_g does not bring it back to the truth (5.5 %).""" X, r, y, U, arc = _referral_sample() common = dict(b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6) without = PG.gibbs(X, r, y, **common) with_arc = PG.gibbs(X, r, y, U=U, arc=arc, d0=[0, 0, 1.5], D0=np.diag([4, 4, 0.09]), **common) assert norm.cdf(without["beta"][:, 0]).mean() > 0.2 assert abs(norm.cdf(with_arc["beta"][:, 0]).mean() - norm.cdf(-1.6)) < 0.02 assert abs(with_arc["delta"][:, -1].mean() - 1.5) < 0.3 def test_split_rhat(): """Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different levels do not exceed 1.1.""" rng = np.random.default_rng(7) assert abs(PG.split_rhat(rng.normal(size=(4, 2000))) - 1) < 0.01 assert PG.split_rhat(rng.normal(size=(4, 2000)) + np.arange(4)[:, None]) > 1.1 def test_patterns_keep_every_woman(): """Fails if collapsing identical women loses anyone or merges different observations.""" X, r, y, U, arc = _referral_sample(n=500) d = PG.patterns(X, r, y, U, arc) assert d["n"].sum() == 500 assert len(d["n"]) == len(np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0)) def test_summed_likelihood_matches_a_direct_sum(): pytest.importorskip("pymc") # optional dependency, not in the production environment """Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g) woman by woman.""" X, r, y, U, arc = _referral_sample(n=400) beta, kappa, delta = np.array([-1.0, 0.9]), 0.65, np.array([-1.5, 2.5, 1.2]) model = PG.pymc_model(X, r, y, np.zeros(2), np.eye(2), (2, 2), U, arc, np.zeros(3), np.eye(3)) point = model.initial_point() point.update({"beta": beta, "kappa_logodds__": np.log(kappa / (1 - kappa)), "delta": delta}) got = model.compile_logp(vars=model.potentials)(point) p = norm.cdf(X @ beta) pr = lambda shift: np.where(r == 1, norm.cdf(shift), norm.sf(shift)) py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0) py0 = np.where((r == 1) & (y == 1), 0.0, 1.0) direct = np.log(p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0).sum() assert np.isclose(got, direct)