Limpiar los avisos de estilo

This commit is contained in:
2026-12-04 09:12:15 -06:00
parent 984d168da7
commit cc5cfd1792
16 changed files with 440 additions and 206 deletions
+43 -15
View File
@@ -1,12 +1,13 @@
import pytest
import numpy as np
import pytest
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."""
"""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)
@@ -24,7 +25,8 @@ def test_latent_sign_follows_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
"""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)
@@ -33,7 +35,8 @@ def test_prob_g_by_observation():
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
"""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
@@ -41,13 +44,24 @@ def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
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)
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
"""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]))
@@ -57,8 +71,10 @@ def test_referral_odds():
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 %."""
"""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])
@@ -71,10 +87,13 @@ def _referral_sample(n=8000, seed=5):
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
"""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)
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
@@ -83,7 +102,8 @@ def test_the_arc_removes_the_selection_bias():
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."""
"""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
@@ -94,12 +114,15 @@ def test_patterns_keep_every_woman():
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))
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."""
"""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))
@@ -107,8 +130,13 @@ def test_summed_likelihood_matches_a_direct_sum():
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))
def pr(shift):
return 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()
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)