Incorporar base bayesiana de investigación

This commit is contained in:
2026-12-03 00:47:02 -06:00
parent d27b585560
commit 3a033efc1b
4 changed files with 322 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
# Fundamento bayesiano en desarrollo
`prevalence_gibbs.py` y sus pruebas proceden de `edgar/bayes-pim`, commit
`1cef69be90a7a9ea30378118cd2a2c9fa312943e`. Solo se cambió el import de las
pruebas. El módulo incluye Gibbs de prevalencia transversal y funciones NUTS
con importación diferida de PyMC; no está conectado a producción ni a Dagster.
Esto **no implementa todavía** el modelo longitudinal: faltan los módulos de
Markov y Klausch, el adaptador de visitas gold con fecha de disponibilidad,
la ejecución NUTS, y el artefacto de diagnóstico y comparación. El original
usa CIN3+ y categorías de biopsia que esta plataforma no puede identificar
por separado; no se deben transformar HSIL o CIN2+ en CIN3+. Su fitting
además importa `models.cacu.cin2_pim.likelihood`, que no existe aquí: hay que
verificar matemáticamente la equivalencia con el PIM actual antes de conectar
las verosimilitudes. La disponibilidad temporal y la definición del desenlace
se deben resolver antes de entrenar con datos reales.
No se añadieron PyMC ni otras dependencias al entorno de producción. El modelo
se mantiene únicamente como código de investigación, sin registro, promoción,
servicio de predicciones ni entrenamiento con datos de pacientes.
@@ -0,0 +1,190 @@
"""The prevalence part of Klausch's BayesPIM as a conjugate Gibbs sampler, for cross-sectional screening data.
Klausch, Lissenberg-Witte and Coupé (2026), Stat Med 45(8-9):e70433, doi:10.1002/sim.70433. Their R package needs
follow-up times to initialise the incidence part, so it cannot fit a sample with one test per woman (2026 sample of
Modelo-cacu, issue 0120). With no follow-up only the prevalence part is informed, and it is this:
z_i ~ N(x_i beta, 1), g_i = 1[z_i > 0] true state at the test (probit, Albert and Chib 1993)
y_i | g_i, r_i = 1 ~ Bernoulli(kappa g_i) the test: specificity 1, sensitivity kappa
r_i = 0 no test (or no result): g_i is only augmented
Every full conditional is a standard distribution, so each step is an exact draw:
g (Bernoulli, z integrated out), z (truncated normal), beta (normal), kappa (beta).
The extension proposed in chapter 19 (selection of who gets the test, the arc g -> r) adds a second probit,
w_i ~ N(u_i gamma + gamma_g arc_i g_i, 1), r_i = 1[w_i > 0]
with arc_i = 1 where the hospital protocol does not refer the woman's cell (referral there is clinical suspicion or
persistence). It keeps conjugacy: w is another truncated normal, (gamma, gamma_g) another normal regression with the
augmented g as a column, and g gains the factor P(r_i | g = 1) / P(r_i | g = 0). With one test per woman gamma_g is
weakly identified and needs an informative prior.
"""
from __future__ import annotations
import numpy as np
from scipy.stats import norm, truncnorm
def normal_posterior(X: np.ndarray, z: np.ndarray, b0: np.ndarray, B0inv: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""beta | z for a regression with unit-variance errors and prior N(b0, B0): N(m, V) with
V = (X'X + B0^-1)^-1 and m = V (X'z + B0^-1 b0). Returns m and the Cholesky factor of V."""
V = np.linalg.inv(X.T @ X + B0inv)
m = V @ (X.T @ z + B0inv @ b0)
return m, np.linalg.cholesky(V)
def draw_latent(mean: np.ndarray, positive: np.ndarray, rng: np.random.Generator) -> np.ndarray:
"""Albert-Chib step: z ~ N(mean, 1) truncated to z > 0 where `positive`, to z <= 0 elsewhere."""
lo = np.where(positive, -mean, -np.inf)
hi = np.where(positive, np.inf, -mean)
return mean + truncnorm.rvs(lo, hi, random_state=rng)
def prob_g(p: np.ndarray, r: np.ndarray, y: np.ndarray, kappa: float, odds_r=1.0) -> np.ndarray:
"""P(g_i = 1 | beta, kappa, data) with z_i integrated out: prior odds p / (1 - p) times the likelihood ratio of
what was observed of woman i, P(data | g = 1) / P(data | g = 0):
* tested positive: infinite (specificity 1: only a diseased woman tests positive), so g = 1;
* tested negative: (1 - kappa) / 1 (a diseased woman is missed with probability 1 - kappa);
* untested: 1 (nothing observed).
`odds_r` is the extra ratio P(r_i | g = 1) / P(r_i | g = 0) of the referral arc; 1 without it."""
lr = np.where(r == 1, np.where(y == 1, np.inf, 1.0 - kappa), 1.0) * odds_r
odds = p / (1.0 - p) * lr
with np.errstate(invalid="ignore"): # inf / inf in the branch that np.where drops
return np.where(np.isinf(odds), 1.0, odds / (1.0 + odds))
def draw_kappa(g: np.ndarray, r: np.ndarray, y: np.ndarray, a: float, b: float, rng: np.random.Generator) -> float:
"""kappa | g, y ~ Beta(a + detected, b + missed), counting only tested women whose (augmented) g is 1."""
diseased = (r == 1) & (g == 1)
detected = int((y[diseased] == 1).sum())
return rng.beta(a + detected, b + int(diseased.sum()) - detected)
def referral_odds(eta_r: np.ndarray, gamma_g: float, arc: np.ndarray, r: np.ndarray) -> np.ndarray:
"""The arc g -> r: P(r_i | g_i = 1) / P(r_i | g_i = 0) when r_i = 1[w_i > 0], w_i ~ N(eta_r_i + gamma_g arc_i g_i, 1).
For a tested woman it is Phi(eta + gamma_g) / Phi(eta); for an untested one, the same with the survival
function. Where arc_i = 0 (the protocol refers her cell) both are equal and the ratio is 1. Logs for stability."""
shifted = eta_r + gamma_g * arc
log1 = np.where(r == 1, norm.logcdf(shifted), norm.logsf(shifted))
log0 = np.where(r == 1, norm.logcdf(eta_r), norm.logsf(eta_r))
return np.exp(log1 - log0)
def gibbs(X: np.ndarray, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None,
iterations: int = 4000, warmup: int = 2000, seed: int = 0) -> dict:
"""One chain. X carries the intercept column; r = 1 if the test was done with a result, y its result (ignored
where r = 0). Prior beta ~ N(b0, B0), kappa ~ Beta(kappa_ab). Returns the kept draws of beta and kappa.
With `U` (the referral design, with its intercept), the arc g -> r is added: w_i ~ N(U_i gamma + gamma_g arc_i g_i,
1), r_i = 1[w_i > 0], with `arc` = 1 where the protocol does not refer the woman's cell (the arc acts) and
delta = (gamma, gamma_g) ~ N(d0, D0), gamma_g last. Its draws are returned as "delta"."""
rng = np.random.default_rng(seed)
r, y = np.asarray(r, int), np.asarray(y, float)
b0, B0inv = np.asarray(b0, float), np.linalg.inv(np.asarray(B0, float))
beta, kappa = b0.copy(), kappa_ab[0] / sum(kappa_ab)
with_arc = U is not None
if with_arc:
arc, d0 = np.asarray(arc, float), np.asarray(d0, float)
D0inv, delta = np.linalg.inv(np.asarray(D0, float)), np.asarray(d0, float).copy()
kept = {"beta": [], "kappa": [], "delta": []}
for it in range(iterations):
eta = X @ beta
p = np.clip(norm.cdf(eta), 1e-12, 1 - 1e-12)
odds_r = referral_odds(U @ delta[:-1], delta[-1], arc, r) if with_arc else 1.0
g = rng.random(len(r)) < prob_g(p, r, y, kappa, odds_r) # 1. g | beta, delta, kappa, data
z = draw_latent(eta, g, rng) # 2. z | g, beta
m, L = normal_posterior(X, z, b0, B0inv) # 3. beta | z
beta = m + L @ rng.standard_normal(len(m))
if with_arc:
D = np.column_stack([U, g * arc]) # 4. the referral design, with g as a column
w = draw_latent(D @ delta, r == 1, rng) # w | r, g, delta
m, L = normal_posterior(D, w, d0, D0inv) # delta | w, g
delta = m + L @ rng.standard_normal(len(m))
kappa = draw_kappa(g, r, y, *kappa_ab, rng) # 5. kappa | g, y
if it >= warmup:
kept["beta"].append(beta)
kept["kappa"].append(kappa)
if with_arc:
kept["delta"].append(delta)
return {k: np.array(v) for k, v in kept.items() if v}
def split_rhat(draws: np.ndarray) -> float:
"""Split R-hat of one scalar (Gelman et al., BDA3, section 11.4): `draws` has shape (chains, iterations). Each
chain is cut in half, and the spread between the halves' means is compared with the spread within them."""
half = draws.shape[1] // 2
parts = np.concatenate([draws[:, :half], draws[:, half:2 * half]])
within = parts.var(axis=1, ddof=1).mean()
between = half * parts.mean(axis=1).var(ddof=1)
return float(np.sqrt(((half - 1) / half * within + between / half) / within))
def patterns(X, r, y, U=None, arc=None) -> dict:
"""Women with the same covariates and the same observation share their likelihood term: the distinct rows and
how many women each one stands for (y = -1 marks an untested row)."""
cols = [X, r[:, None], np.nan_to_num(y, nan=-1.0)[:, None]]
if U is not None:
cols += [U, np.asarray(arc, float)[:, None]]
rows, counts = np.unique(np.column_stack(cols), axis=0, return_counts=True)
p = X.shape[1]
out = {"X": rows[:, :p], "r": rows[:, p].astype(int), "y": rows[:, p + 1], "n": counts.astype(float)}
if U is not None:
out["U"], out["arc"] = rows[:, p + 2:-1], rows[:, -1]
return out
def pymc_model(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None):
"""The same model with g summed out of the likelihood, so that NUTS samples only continuous parameters:
P(data_i) = P(g=1) P(r_i | g=1) P(y_i | g=1) + P(g=0) P(r_i | g=0) P(y_i | g=0)
with P(y=1 | g=0) = 0 (specificity 1), so a tested positive keeps only the first term. Without `U` the test is
taken as done at random given x, and P(r | g) drops out, as in the Gibbs."""
import pymc as pm
import pytensor.tensor as pt
d = patterns(np.asarray(X, float), np.asarray(r, int), np.asarray(y, float), U, arc)
positive = (d["r"] == 1) & (d["y"] == 1)
negative = (d["r"] == 1) & (d["y"] == 0)
log_phi = lambda v: pm.logcdf(pm.Normal.dist(0.0, 1.0), v) # log Phi(v), stable in the tails
with pm.Model() as model:
beta = pm.MvNormal("beta", mu=np.asarray(b0, float), cov=np.asarray(B0, float))
kappa = pm.Beta("kappa", *kappa_ab)
eta = pt.as_tensor(d["X"]) @ beta
log_g1, log_g0 = log_phi(eta), log_phi(-eta) # log P(g=1), log P(g=0)
log_r1 = log_r0 = 0.0
if U is not None:
delta = pm.MvNormal("delta", mu=np.asarray(d0, float), cov=np.asarray(D0, float))
eta_r = pt.as_tensor(d["U"]) @ delta[:-1]
sign = np.where(d["r"] == 1, 1.0, -1.0) # P(r=1) = Phi(.), P(r=0) = Phi(-.)
log_r1, log_r0 = log_phi(sign * (eta_r + delta[-1] * d["arc"])), log_phi(sign * eta_r)
log_y1 = pt.switch(negative, pt.log1p(-kappa), 0.0) # a diseased woman missed: 1 - kappa
diseased = log_g1 + log_r1 + log_y1
healthy = log_g0 + log_r0
loglik = pt.switch(positive, diseased + pt.log(kappa), pt.logaddexp(diseased, healthy))
pm.Potential("loglik", pt.sum(d["n"] * loglik))
return model
def nuts(X, r, y, b0, B0, kappa_ab=(1.0, 1.0), U=None, arc=None, d0=None, D0=None, draws: int = 1000,
tune: int = 1000, chains: int = 4, seed: int = 0, cores: int | None = None) -> dict:
"""NUTS on `pymc_model`. Returns the draws with the chains stacked (as in `gibbs`), the max split R-hat over the
parameters and the number of divergent transitions. `cores` defaults to one per chain."""
import pymc as pm
with pymc_model(X, r, y, b0, B0, kappa_ab, U, arc, d0, D0):
idata = pm.sample(draws=draws, tune=tune, chains=chains, cores=cores or chains, random_seed=seed, progressbar=False,
compute_convergence_checks=False)
post = idata.posterior
out, rhats = {}, []
for name in ("beta", "kappa", "delta"):
if name in post:
v = post[name].values.reshape(chains, draws, -1) # (chains, draws, parameters)
rhats += [split_rhat(v[:, :, j]) for j in range(v.shape[2])]
out[name] = v.reshape(chains * draws, -1).squeeze() if name == "kappa" else v.reshape(chains * draws, -1)
out["rhat"] = max(rhats)
out["divergences"] = int(idata.sample_stats["diverging"].values.sum())
return out
+112
View File
@@ -0,0 +1,112 @@
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():
"""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)