Inference and computation / E130

Don't let the bad part leak: cutting feedback, the cut posterior, and a dial between cut and full

Type
Advanced worked example - read, run, modify
Data
Real: HPV prevalence and cervical cancer incidence in 13 populations (Maucort-Boulch, Franceschi and Plummer 2008; the table Plummer 2015 used for the cut function, here from the R package aistats2020smi, MIT licence). Simulated: a twin of that table with known prevalences, in three worlds (the cancer model lacks a source of scatter; the cancer model is right; the cancer model has the wrong curve)
You will learn
Why a joint posterior lets a wrong module rewrite a right one, and which way that leak runs · the two-stage plug-in, and how much uncertainty it hides · the cut posterior as multiple imputation, with hundreds of nutpie refits · why one sampler with the feedback term deleted does not give the cut posterior · semi-modular inference: a dial between cut and full, and choosing it with the ELPD of the trusted module's data · which posterior predictive check shows the leak and which two do not · when to repair the model instead of cutting it

The question

An epidemiologist wants two things from two sources of data. From a survey in each of 13 populations she wants the prevalence of high-risk human papillomavirus (HPV) among women aged 55 to 64. From the cancer registries of the same populations she wants the relation between that prevalence and the incidence of cervical cancer. The survey is a designed sample: so many women tested, so many positive, a binomial count with nothing to argue about. The relation is another matter. It is an ecological regression across 13 very different countries, with a functional form chosen for convenience, and nobody would stake much on its details.

The model for the survey is one module; the regression for the registry counts is a second one, and it takes the first module's unknown prevalences as its covariate. Bayesian inference says what to do with two modules that share a parameter: write the joint model and condition on everything. The joint posterior then uses the cancer counts to sharpen the prevalences, which is the point of joint modelling when the model is right. When the second module is wrong, the same mechanism lets it overwrite what the survey said, with great confidence, and the estimate that depended only on a binomial count now depends on a regression nobody believed. Liu, Bayarri and Berger (2009) argued for analysing such models module by module for this reason, and the BUGS software has a cut function for it, which the OpenBUGS manual describes as "a kind of valve": prior information flows down through it, likelihood information is prevented from flowing back up (see also Lunn et al. 2009). Plummer (2015) showed that the algorithm behind that function does not converge to a well-defined limiting distribution, with this very table of 13 populations as his example. Jacob, Murray, Holmes and Robert (2017) asked when a modular answer should be preferred to the joint one and proposed to decide by prediction. Carmona and Nicholls (2020) put a dial between the two, semi-modular inference.

This is one of four notebooks on inference under a wrong model (E130 to E133). E131 trusts the likelihood less by raising it to a power, and E132 averages posteriors over bootstrap copies of the data. Both make intervals wider, and both make the same point: a wider interval around a wrong centre is still around a wrong centre. Cutting is a different tool. It does not widen anything. It stops a part of the model we do not trust from moving a part we do. (E102 used a cut in passing, when its propensity model was not allowed to see the outcome; here the cut is the subject.)

The methods, all on one question, are these: the full joint posterior; the two-stage plug-in, which estimates the prevalences from the survey and feeds the point estimates to the regression; the cut posterior, which feeds it the survey's whole posterior, one draw at a time; semi-modular inference with a dial between cut and full, and a rule for setting the dial; and, as the alternative to all of them, repairing the second module and fitting jointly.

The real table cannot tell us which answer is right, because nobody knows the 13 true prevalences. So most of the work happens on a simulated twin of the table in which we do know them, and in which the cancer model is wrong in a named way, or right, as we choose. Every method is scored on repeated datasets from the twin: how far its prevalence estimates are from the truth, and how often its 90% intervals contain it.

part question tool
1 What are the two modules, and which has more to say? the table; information per population
2 What does the joint posterior do to the prevalences? NUTS, a failed fit, an exact check by quadrature
3 Is the joint answer better or worse than the survey's own? a twin with known prevalences, 100 datasets in each of two worlds
4 Can we see the leak without knowing the truth? three posterior predictive checks
5 What should the regression be given, if not feedback? plug-in, cut by multiple imputation, a sampler that fails
6 Is there something between cut and full? the semi-modular dial, set by the survey's ELPD
7 What if we repair the regression instead? a negative binomial module; a third world
8 Who wins, at what cost? the scoreboard
9 What does all this say about the real table? every method on the 13 populations
10 Which method for which situation? survey size against the leak; a table of everything measured

Each step closes with a short box, The choice: what we kept, what we rejected, and what would change our mind.

import os

for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ.setdefault(name, "1")  # before NumPy: one BLAS thread per chain

import logging
import time
import warnings

import arviz as az
import matplotlib.pyplot as plt
import nutpie
import numpy as np
import pandas as pd
import pymc as pm
import pytensor.tensor as pt
import xarray as xr
from scipy import special, stats

from pymc_challenges import data
from pymc_challenges.scoreboard import Scoreboard

RANDOM_SEED = 130
az.style.use("arviz-variat")
plt.rcParams.update({"axes.labelsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9})
logging.getLogger("pymc").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
pd.set_option("display.width", 170)
pd.set_option("display.max_columns", 30)
pd.set_option("display.float_format", lambda v: f"{v:.3g}")
T_START = time.time()

INK, MUTED, LIGHT, GRID = "#222222", "#8a8a8a", "#d9d9d9", "#e1e0d9"
BLUE, ORANGE, AQUA, YELLOW, MAGENTA, GREEN, VIOLET, RED = (
    "#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948")
CI = 0.90
Q = [0.05, 0.95]


def tidy(ax, grid="y"):
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(False)
    if grid:
        ax.grid(axis=grid, color=GRID, lw=0.6)
    ax.set_axisbelow(True)

1 · The table and its two modules

The data are four numbers for each of 13 populations: how many women the HPV survey tested and how many were positive for a high-risk type, and how many cases of cervical cancer the population's registry recorded over how many woman-years. The sources give the populations no names, so we number them in the order of the table.

data.describe("e130_hpv")
hpv = data.load("e130_hpv")
Z, N, Y, T = (hpv[c].to_numpy() for c in ("hpv_positive", "survey_size", "cancer_cases", "woman_years"))
J = len(hpv)
POP = hpv["population"].to_numpy()
OFF = np.log(T / 1000.0)                        # cancer rates are per 1,000 woman-years

show = hpv.set_index("population")
show["prevalence_%"] = 100 * Z / N
show["cases_per_1000_wy"] = 1000 * Y / T
print(show.round(2).to_string())
print(f"\n{Z.sum()} positive among {N.sum():,} women surveyed; {Y.sum():,} cancer cases in {T.sum():,} woman-years")
e130_hpv: One row per population (13, unnamed in the source, numbered in its order): population, hpv_positive (women positive for high-risk HPV in the prevalence survey), survey_size (women surveyed), cancer_cases (cervical cancer cases in the population's cancer registry), woman_years (woman-years of follow-up behind those cases).
  source: HPV prevalence and cervical cancer incidence in 13 populations, women aged 55-64: the table of Maucort-Boulch, Franceschi & Plummer (2008, Cancer Epidemiol Biomarkers Prev 17, 717-720) that Plummer (2015, Statistics and Computing 25, 37-43) uses for the cut function, as the data frame `HPV` of the R package aistats2020smi (Carmona & Nicholls, code of 'Semi-Modular Inference', AISTATS 2020). Licence, as read in https://github.com/chriscarmona/aistats2020smi on 2026-11-24: DESCRIPTION 'License: MIT + file LICENSE'; LICENSE.md 'MIT License / Copyright (c) 2021 aistats2020smi authors / Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction'. Checked number for number against `plummer_data` of the R package bettertogether (Jacob; 'License: GPL v2'). DERIVED by tools/build_e130_hpv.py (the four vectors read out of the R source and renamed; the url is that R file, not a table) - keep the cached file in data/ (md5 369f4bbcb8ec72697e2f636319767fc7).
  url:    https://raw.githubusercontent.com/chriscarmona/aistats2020smi/25242d8b75a16dffa4285b5628bbf210d0a9dfb0/R/HPV.R
            hpv_positive  survey_size  cancer_cases  woman_years  prevalence_%  cases_per_1000_wy
population                                                                                       
1                      7          111            16        26983          6.31               0.59
2                      6           71           215       250930          8.45               0.86
3                     10          162           362       829348          6.17               0.44
4                     10          188            97       157775          5.32               0.61
5                      1          145            76       150467          0.69               0.51
6                      1          215            62       352445          0.47               0.18
7                     10          166           710       553066          6.02               1.28
8                      4           37            56        26751          10.8               2.09
9                     35          173           133        75815          20.2               1.75
10                     0          143            28       150302             0               0.19
11                    10          229            62       354993          4.37               0.17
12                     8          696           413      3683043          1.15               0.11
13                     4           93           194       507218           4.3               0.38

106 positive among 2,429 women surveyed; 2,424 cancer cases in 7,119,136 woman-years

The two halves of the table are very unequal in size. The surveys found 106 positive women in all, between none and 35 per population. The registries recorded 2,424 cancers, from 16 to 710 per population. Keep that imbalance in mind; it decides most of what follows.

Module 1, the survey. In population $j$, $Z_j$ of $N_j$ women are positive, and $Z_j \sim \text{Binomial}(N_j, \varphi_j)$ with prevalence $\varphi_j$. With a uniform prior the posterior is a Beta distribution in closed form, $\varphi_j \mid Z_j \sim \text{Beta}(1 + Z_j,\, 1 + N_j - Z_j)$, separately for each population. The model has one free parameter per count, so it cannot fit badly; its only assumption is that the women tested are a fair sample of the population.

Module 2, the registry. The $Y_j$ cancers in $T_j$ thousand woman-years are $Y_j \sim \text{Poisson}(\mu_j)$ with $\log \mu_j = \theta_1 + \theta_2\,\varphi_j + \log T_j$: the log of the cancer rate is a straight line in the prevalence, with intercept $\theta_1$ and slope $\theta_2$, and all that separates two populations with the same prevalence is Poisson noise. We keep the vague priors of the literature, $\theta_1, \theta_2 \sim \mathcal N(0, 1000)$ (variance 1000, as in Jacob et al. 2017).

Joined. The joint posterior multiplies the two modules,

$$p(\varphi, \theta \mid Z, Y) \;\propto\; \underbrace{p(\varphi)\,p(Z \mid \varphi)}_{\text{module 1}} \;\times\; \underbrace{p(\theta)\,p(Y \mid \varphi, \theta)}_{\text{module 2}},$$

and if we integrate $\theta$ out, what it says about the prevalences is the survey's posterior times one more factor:

$$p(\varphi \mid Z, Y) \;\propto\; p(\varphi \mid Z)\;\times\; p(Y \mid \varphi), \qquad p(Y \mid \varphi) = \int p(Y \mid \varphi, \theta)\,p(\theta)\,d\theta .$$

The factor $p(Y \mid \varphi)$ is the feedback: how well the cancer counts can be explained when the prevalences are $\varphi$. Everything in this notebook is about that one factor: keeping it (the full posterior), deleting it (the cut), or raising it to a power between 0 and 1 (the dial).

Module 2 given the prevalences

If the prevalences were known, module 2 would be an ordinary Poisson regression with two coefficients and 2,400 cases, and its posterior would be close to Gaussian. We will need that conditional posterior $p(\theta \mid \varphi, Y)$ hundreds of thousands of times, so we write it directly: Newton's method for the mode, the curvature there for the covariance (a Laplace approximation). Part 5 checks it against NUTS.

PRIOR_SD = np.sqrt(1000.0)


def conditional_laplace(phi, Y, off=OFF, start=None, iters=25):
    """Mode and covariance of theta given phi and Y, for any batch: phi (..., J) -> (..., 2) and (..., 2, 2)."""
    phi = np.asarray(phi, float)
    Y = np.broadcast_to(np.asarray(Y, float), phi.shape)
    off = np.broadcast_to(off, phi.shape)
    if start is None:                                     # a common rate and no slope
        start = np.stack([np.log(Y.sum(-1) / np.exp(off).sum(-1)), np.zeros(phi.shape[:-1])], axis=-1)
    theta = np.array(np.broadcast_to(start, phi.shape[:-1] + (2,)), float)
    for it in range(iters + 1):
        mu = np.exp(theta[..., :1] + theta[..., 1:] * phi + off)
        s0 = mu.sum(-1) + 1 / PRIOR_SD**2                 # the 2 x 2 information matrix, entry by entry
        s1 = (mu * phi).sum(-1)
        s2 = (mu * phi**2).sum(-1) + 1 / PRIOR_SD**2
        det = s0 * s2 - s1**2
        if it == iters:
            break
        g0 = (Y - mu).sum(-1) - theta[..., 0] / PRIOR_SD**2
        g1 = ((Y - mu) * phi).sum(-1) - theta[..., 1] / PRIOR_SD**2
        step = np.stack([(s2 * g0 - s1 * g1) / det, (s0 * g1 - s1 * g0) / det], axis=-1)
        theta += np.clip(step, [-2.0, -10.0], [2.0, 10.0])   # damped: a Poisson Newton step can overshoot
    cov = np.stack([np.stack([s2, -s1], -1), np.stack([-s1, s0], -1)], -2) / det[..., None, None]
    return theta, cov


def conditional_draws(phi, Y, rng, off=OFF, start=None, iters=25):
    """One draw of theta from the Laplace approximation of p(theta | phi, Y) for every row of phi."""
    mode, cov = conditional_laplace(phi, Y, off, start, iters)
    l11 = np.sqrt(cov[..., 0, 0])
    l21 = cov[..., 0, 1] / l11
    l22 = np.sqrt(cov[..., 1, 1] - l21**2)
    e = rng.standard_normal(mode.shape)
    return mode + np.stack([l11 * e[..., 0], l21 * e[..., 0] + l22 * e[..., 1]], axis=-1)


A_REAL, B_REAL = 1 + Z, 1 + N - Z                           # module 1 alone: Beta(a, b) for each population
PHI_HAT = A_REAL / (A_REAL + B_REAL)                        # its posterior means
plug_mode, plug_cov = conditional_laplace(PHI_HAT, Y)
print(f"module 2 given the survey's point estimates: intercept {plug_mode[0]:.2f}, slope {plug_mode[1]:.1f} "
      f"(sd {np.sqrt(plug_cov[1, 1]):.2f})")
module 2 given the survey's point estimates: intercept -1.76, slope 14.9 (sd 0.35)

Which module has more to say about a prevalence?

Before fitting anything we can ask how much each module claims to know about $\varphi_j$. For the survey the Fisher information is $N_j / \big(\varphi_j (1 - \varphi_j)\big)$. For the registry, with the line known, it is $\theta_2^2\,\mu_j$: a Poisson count of $\mu_j$ cases fixes the log rate to within $1/\sqrt{\mu_j}$, and a slope of $\theta_2$ turns that into $1/(\theta_2 \sqrt{\mu_j})$ on the prevalence. We evaluate both at the survey's estimates and the slope just printed.

info_survey = N / (PHI_HAT * (1 - PHI_HAT))
info_registry = plug_mode[1] ** 2 * Y
info = pd.DataFrame({"sd of prevalence, survey alone (%)": 100 / np.sqrt(info_survey),
                     "sd the registry would allow (%)": 100 / np.sqrt(info_registry),
                     "information ratio, registry / survey": info_registry / info_survey}, index=pd.Index(POP, name="population"))
print(info.round(2).T.to_string())
print(f"\nmedian information ratio: {np.median(info_registry / info_survey):.0f}")

fig, ax = plt.subplots(figsize=(8.6, 4.6))
lo, hi = stats.beta.ppf(Q[0], A_REAL, B_REAL), stats.beta.ppf(Q[1], A_REAL, B_REAL)
rate_lo, rate_hi = stats.gamma.ppf(Q[0], Y + 0.5) / T * 1000, stats.gamma.ppf(Q[1], Y + 0.5) / T * 1000
ax.errorbar(100 * PHI_HAT, 1000 * Y / T, xerr=100 * np.array([PHI_HAT - lo, hi - PHI_HAT]),
            yerr=np.array([1000 * Y / T - rate_lo, rate_hi - 1000 * Y / T]), fmt="o", ms=5, color=BLUE, ecolor=MUTED, elinewidth=1)
for j in range(J):
    ax.annotate(str(POP[j]), (100 * PHI_HAT[j], 1000 * Y[j] / T[j]), xytext=(5, 5), textcoords="offset points", fontsize=8, color=INK)
grid_phi = np.linspace(0, 0.3, 50)
ax.plot(100 * grid_phi, np.exp(plug_mode[0] + plug_mode[1] * grid_phi), color=ORANGE, lw=1.3,
        label=f"module 2 fitted to the survey's estimates (slope {plug_mode[1]:.0f})")
ax.set_yscale("log")
ax.set_xlabel("HPV prevalence, survey alone (%), with 90% interval")
ax.set_ylabel("cancer cases per 1,000 woman-years")
ax.set_title("Thirteen populations: wide in prevalence, narrow in rate, and off the line", loc="left")
ax.legend(frameon=False, fontsize=9, loc="lower right")
tidy(ax, grid="both");
population                             1    2    3    4    5    6    7    8    9    10   11   12   13
sd of prevalence, survey alone (%)   2.43 3.49 1.97  1.7 0.96 0.65 1.92  5.5 3.07 0.69 1.41 0.43 2.32
sd the registry would allow (%)      1.68 0.46 0.35 0.68 0.77 0.85 0.25  0.9 0.58 1.27 0.85 0.33 0.48
information ratio, registry / survey 2.09   58 30.9 6.22 1.55 0.58 57.8 37.4 27.7  0.3 2.71 1.67   23

median information ratio: 6
Figure

The horizontal bars are wide and the vertical ones are hard to see. The survey leaves a typical prevalence uncertain by about two percentage points; the registry, if the line is taken at its word, would pin the same prevalence to well under one. The information ratio is above 1 in eleven of the thirteen populations and above 20 in six of them. Only in populations 6 and 10, where the survey found one positive woman or none, does the survey claim more than the registry.

And the points do not lie on the line. Population 7 has the third highest cancer rate and an unremarkable prevalence; population 5 has almost no HPV in the survey (one woman in 145) and a cancer rate in the middle of the range. Module 2 says such gaps can only be Poisson noise, which with hundreds of cases is tiny, or else the prevalences are not what the survey says.

That is which way the leak runs. Feedback flows towards the module that claims less precision, from the one that claims more. Reliability does not enter the formula: the joint posterior cannot know that the binomial model is solid and the straight line is a guess.

The choice. The two modules exactly as in Jacob et al. (2017), who take them from Plummer's example, priors included, so that the numbers can be compared with theirs. Rejected for now: a more careful module 2. That is the right thing to do when we can (part 7), but the question of this notebook is what to do with a module we know is rough and cannot or will not repair. What would change our mind: registry counts so small that the information ratio fell below one; module 2 would then have little to say about the prevalences, and the choice between joint and cut would hardly matter.

2 · The joint posterior, and a fit that looks fine and is not

The joint model is a few lines of PyMC, and the obvious thing to do with it is to call pm.sample. We do that five times, changing only the seed.

def textbook_model(Z, N, Y, off=OFF):
    with pm.Model(coords={"population": POP, "coef": ["intercept", "slope"]}) as model:
        phi = pm.Beta("phi", 1.0, 1.0, dims="population")
        theta = pm.Normal("theta", 0.0, PRIOR_SD, dims="coef")
        pm.Binomial("survey", N, phi, observed=Z, dims="population")
        pm.Poisson("cases", pt.exp(theta[0] + theta[1] * phi + off), observed=Y, dims="population")
    return model


rows = []
for seed in range(RANDOM_SEED, RANDOM_SEED + 5):
    with textbook_model(Z, N, Y):
        idata = pm.sample(random_seed=seed, progressbar=False)
    slope = idata.posterior["theta"].sel(coef="slope")
    negative = (slope.mean("draw") < 0).to_numpy()
    rows.append({"seed": seed, "slope, mean of each chain": " ".join(f"{v:7.1f}" for v in slope.mean("draw").to_numpy()),
                 "chains with a negative slope": int(negative.sum()),
                 "largest r_hat": max(float(az.rhat(idata.posterior)[v].max()) for v in ("phi", "theta")),
                 "divergences": int(idata.sample_stats["diverging"].sum()),
                 "prevalence 9 (%)": f"{100 * float(idata.posterior['phi'].sel(population=9).mean()):.1f}",
                 "all 13 prevalences (%)": "{:.1f} to {:.1f}".format(*np.sort(100 * idata.posterior["phi"].mean(("chain", "draw")).to_numpy())[[0, -1]])})
default_runs = pd.DataFrame(rows).set_index("seed")
N_NEGATIVE = int(default_runs["chains with a negative slope"].sum())
N_UNANIMOUS = int((default_runs["chains with a negative slope"] == 4).sum())
print(default_runs.to_string())
print(f"\n{N_NEGATIVE} of {4 * len(default_runs)} chains end with a negative slope; in {N_UNANIMOUS} of {len(default_runs)} runs all four do")
            slope, mean of each chain  chains with a negative slope  largest r_hat  divergences prevalence 9 (%) all 13 prevalences (%)
seed                                                                                                                                   
130    -110.4    23.9  -110.3  -106.6                             3           1.57            0              5.9             4.7 to 5.9
131    -105.7    24.4  -111.1  -113.3                             3            1.6            0              5.8             4.7 to 5.8
132    -109.5  -111.0  -106.4  -113.1                             4           1.03            0              3.7             3.5 to 6.2
133    -111.1    23.9  -113.4  -107.4                             3            1.6            0              6.0             4.8 to 6.0
134    -109.3  -112.4  -110.7  -110.8                             4           1.03            0              3.7             3.5 to 6.2

17 of 20 chains end with a negative slope; in 2 of 5 runs all four do

Most chains come back with a slope near $-110$: more HPV, much less cancer. When a run has chains of both kinds, r_hat is far above 1 and we are warned. When all four chains agree on the negative slope, very little warns us: r_hat is about 1.03, which many analyses would wave through, and there is not one divergent transition. Such a run reports that the prevalence in population 9, where the survey found 35 positive women among 173 (20%), is under 4%, and that all thirteen prevalences lie within a few points of each other.

The joint posterior has two modes. A steep negative slope with thirteen nearly equal prevalences can reproduce the cancer counts, as a moderate positive slope with spread-out prevalences can, and the sampler's default starting point (every prevalence at 50%) happens to roll into the first. To find out how much of the posterior each mode holds we need an answer that does not depend on a sampler. The structure of the model gives one. Given $\theta$, the 13 prevalences are independent, so the marginal posterior of $\theta$ is a product of 13 one-dimensional integrals, which we do by quadrature for every $\theta$ on a grid.

C0 = Z.sum() / N.sum()                                     # pooled prevalence, to centre the slope
QUAD_U = np.linspace(-9.5, 2.5, 400)                       # quadrature nodes for one prevalence, on the logit scale
QUAD_PHI = special.expit(QUAD_U)
QUAD_LOGW = np.log(np.gradient(QUAD_PHI))


def log_marginal_theta(level, slope, Z, N, Y, dial=1.0, off=OFF, thin=1):
    """log of p(theta) times the integral over phi of p(Z | phi) p(Y | phi, theta)^dial, on a grid.

    `level` is the log rate at the pooled prevalence, theta1 + theta2 * C0: the posterior is far less
    tilted in (level, slope) than in (theta1, theta2), so a rectangular grid wastes fewer points.
    `thin` keeps every thin-th quadrature node, for a quick look."""
    phi = QUAD_PHI[::thin]
    out = np.zeros((len(level), len(slope)))
    log_binomial = Z[:, None] * np.log(phi) + (N - Z)[:, None] * np.log1p(-phi) + QUAD_LOGW[::thin]
    for j in range(len(Z)):
        log_mu = level[:, None, None] + slope[None, :, None] * (phi - C0) + off[j]
        out += special.logsumexp(dial * (Y[j] * log_mu - np.exp(log_mu)) + log_binomial[j], axis=2)
    theta1 = level[:, None] - slope[None, :] * C0
    return out - 0.5 * (theta1**2 + slope[None, :] ** 2) / PRIOR_SD**2


# a wide, coarse grid, to weigh the two modes against each other
level, slope = np.linspace(-2.5, 1.0, 141), np.linspace(-220.0, 80.0, 151)
wide = log_marginal_theta(level, slope, Z, N, Y)
LOG10_NEGATIVE = (special.logsumexp(wide[:, slope < 0]) - special.logsumexp(wide[:, slope > 0])) / np.log(10)
k_neg = np.unravel_index(wide[:, slope < 0].argmax(), wide[:, slope < 0].shape)
print(f"highest point with a negative slope: slope {slope[slope < 0][k_neg[1]]:.0f}, "
      f"log density {wide[:, slope < 0].max() - wide.max():.0f} below the highest point overall")
print(f"posterior mass with a negative slope: 10^{LOG10_NEGATIVE:.0f} of the total")

# a fine grid around the main mode, for the exact marginal of the slope
level, slope = np.linspace(-1.85, -0.85, 101), np.linspace(10.0, 42.0, 129)
fine = log_marginal_theta(level, slope, Z, N, Y)
p = np.exp(fine - fine.max())
p /= p.sum()
theta1 = level[:, None] - slope[None, :] * C0
EXACT = {"intercept mean": (p * theta1).sum(), "slope mean": (p.sum(0) * slope).sum()}
EXACT["intercept sd"] = np.sqrt((p * theta1**2).sum() - EXACT["intercept mean"] ** 2)
EXACT["slope sd"] = np.sqrt((p.sum(0) * slope**2).sum() - EXACT["slope mean"] ** 2)
print(f"exact joint posterior: intercept {EXACT['intercept mean']:.2f} (sd {EXACT['intercept sd']:.2f}), "
      f"slope {EXACT['slope mean']:.1f} (sd {EXACT['slope sd']:.1f}); "
      f"mass on the edges of the fine grid {p[[0, -1]].sum() + p[:, [0, -1]].sum():.0e}")
highest point with a negative slope: slope -106, log density -85 below the highest point overall
posterior mass with a negative slope: 10^-36 of the total
exact joint posterior: intercept -2.35 (sd 0.09), slope 24.1 (sd 2.8); mass on the edges of the fine grid 2e-05

The mode the sampler preferred holds a share of the posterior with about 35 zeros after the decimal point. The posterior is, for every practical purpose, the other mode: a slope near 24. So the clean runs above were clean descriptions of a place where the posterior is not. r_hat compares chains with each other, and four chains that fall into the same hole agree perfectly.

This is failure 1, and it is a failure of computation that the leak itself creates. Module 2 ties each prevalence to the line so tightly that the posterior is a thin curved sheet, and from a poor start the sampler lands on whichever fold is nearest.

A model with a dial, started where the survey puts it

The repair has two parts, and both will be needed again. First we write the joint model with module 2's log-likelihood multiplied by a number dial: at 1 it is the joint model, near 0 it is almost the survey alone, and in between it is the power posterior that part 6 is about. Second we control where the sampler starts. nutpie compiles a model once and swaps its data with with_data, which makes a refit cost a few hundredths of a second, but the starting point is fixed at compile time. So each parameter is written as a location plus a scale times a raw variable, with the location and scale passed in as data: the raw variables start near zero, which is then wherever we say. We start at the survey's estimates with a small dial, and walk up the dial, starting each fit at the posterior mean and spread of the one before. The priors are those of the textbook model, written as densities of the raw variables.

def dial_model(Z, N, Y, off=OFF, repaired=False):
    """The joint model with module 2 to the power `dial`; located and scaled through pm.Data."""
    n = len(Z)
    with pm.Model() as model:
        Zd, Nd, Yd, od = pm.Data("Z", Z), pm.Data("N", N), pm.Data("Y", Y), pm.Data("off", off)
        loc_phi, scale_phi = pm.Data("loc_phi", np.zeros(n)), pm.Data("scale_phi", np.ones(n))
        loc_theta, scale_theta = pm.Data("loc_theta", np.zeros(2)), pm.Data("scale_theta", np.ones(2))
        raw_phi = pm.Flat("raw_phi", shape=n)
        raw_theta = pm.Flat("raw_theta", shape=2)
        phi = pm.Deterministic("phi", pm.math.invlogit(loc_phi + scale_phi * raw_phi))
        theta = pm.Deterministic("theta", loc_theta + scale_theta * raw_theta)
        # uniform prior on phi (log phi + log(1 - phi) is the Jacobian of the logit) and N(0, 1000) on theta
        pm.Potential("prior", pt.sum(pt.log(phi) + pt.log1p(-phi)) - 0.5 * pt.sum(theta**2) / PRIOR_SD**2)
        pm.Binomial("survey", Nd, phi, observed=Zd)
        log_mu = theta[0] + theta[1] * phi + od
        if repaired:                                       # part 7: a negative binomial module 2
            tau = pm.HalfNormal("tau", 1.0)
            pm.NegativeBinomial("cases", mu=pt.exp(log_mu), alpha=1 / tau**2, observed=Yd)
        else:
            dial = pm.Data("dial", 1.0)
            pm.Potential("cases", dial * pt.sum(Yd * log_mu - pt.exp(log_mu)))
    return model


def survey_start(Z, N, Y, off=OFF):
    """Start where module 1 puts the prevalences, and where module 2 puts the line given those."""
    p = (Z + 0.5) / (N + 1.0)
    mode, cov = conditional_laplace(p, Y, off)
    return dict(loc_phi=special.logit(p), scale_phi=np.sqrt(1 / (Z + 0.5) + 1 / (N - Z + 0.5)),
                loc_theta=mode, scale_theta=3 * np.sqrt(np.diag(cov)))


def sample(compiled, Z, N, Y, start, dial=None, off=OFF, draws=250, tune=250, seed=0, **kwargs):
    """NUTS on a compiled model with the data, the dial and the start swapped in: four chains."""
    values = dict(Z=Z, N=N, Y=Y, off=off, **start)
    if dial is not None:
        values["dial"] = np.array(float(dial))
    return nutpie.sample(compiled.with_data(**values), draws=draws, tune=tune, chains=4, cores=4, seed=seed,
                         progress_bar=False, low_rank_modified_mass_matrix=True, **kwargs)


def unpack(trace, keep=False):
    """Draws as arrays (the four chains stacked), the number of divergences and r_hat of the slope."""
    out = {name: trace.posterior[name].to_numpy().reshape(-1, *trace.posterior[name].shape[2:])
           for name in ("phi", "theta", "tau") if name in trace.posterior}
    out["divergences"] = int(trace.sample_stats["diverging"].sum())
    out["rhat_slope"] = float(az.rhat(trace.posterior["theta"].to_numpy()[..., 1]))
    if keep:
        out["posterior"] = trace.posterior
    return out


def diagnose(fit):
    """Largest r_hat and smallest bulk ESS of a fit that kept its posterior."""
    rhat, ess = az.rhat(fit["posterior"]), az.ess(fit["posterior"])
    return {"largest r_hat": max(float(rhat[v].max()) for v in ("phi", "theta")),
            "smallest ESS, prevalences": float(ess["phi"].min()), "smallest ESS, line": float(ess["theta"].min())}


def walk(compiled, Z, N, Y, dial, off=OFF, seed=0, keep=False, **kwargs):
    """Fit at each value of the dial in turn, each fit started at the posterior of the one before."""
    start, out = survey_start(Z, N, Y, off), []
    for k, value in enumerate(dial):
        fit = unpack(sample(compiled, Z, N, Y, start, value, off, seed=seed + k, **kwargs), keep)
        logit_phi = special.logit(fit["phi"])
        start = dict(loc_phi=logit_phi.mean(0), scale_phi=logit_phi.std(0),
                     loc_theta=fit["theta"].mean(0), scale_theta=fit["theta"].std(0))
        out.append(fit)
    return out


t0 = time.time()
COMPILED = nutpie.compile_pymc_model(dial_model(Z, N, Y))
print(f"compiled once in {time.time() - t0:.0f} s")

DIAL = np.array([0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1.0])
t0 = time.time()
REAL = walk(COMPILED, Z, N, Y, DIAL, seed=RANDOM_SEED, draws=1000, tune=500, keep=True)
print(f"seven fits up the dial in {time.time() - t0:.1f} s")
print(pd.DataFrame([{"dial": d, "divergences": f["divergences"], **diagnose(f)} for d, f in zip(DIAL, REAL)]).round(3).to_string(index=False))
FULL_REAL = REAL[-1]
print(f"\njoint posterior by NUTS: intercept {FULL_REAL['theta'][:, 0].mean():.2f} (sd {FULL_REAL['theta'][:, 0].std():.2f}), "
      f"slope {FULL_REAL['theta'][:, 1].mean():.1f} (sd {FULL_REAL['theta'][:, 1].std():.1f}); "
      f"by quadrature: {EXACT['intercept mean']:.2f} ({EXACT['intercept sd']:.2f}), {EXACT['slope mean']:.1f} ({EXACT['slope sd']:.1f})")
compiled once in 5 s
seven fits up the dial in 0.9 s
 dial  divergences  largest r_hat  smallest ESS, prevalences  smallest ESS, line
0.001            2              1                   4.54e+03            3.66e+03
0.003            0              1                   3.84e+03            4.85e+03
 0.01            0              1                   4.23e+03            4.06e+03
 0.03            0              1                   4.18e+03            4.87e+03
  0.1            0              1                    3.3e+03            3.08e+03
  0.3            0              1                   2.48e+03            2.06e+03
    1            0              1                   1.35e+03            1.22e+03

joint posterior by NUTS: intercept -2.35 (sd 0.09), slope 24.1 (sd 2.8); by quadrature: -2.35 (0.09), 24.1 (2.8)

At the top of the dial NUTS and the quadrature agree on the intercept and the slope to the digits shown, the chains mix (r_hat at 1.00, more than a thousand effective draws; the low-rank mass matrix of nutpie matters here, because the prevalences and the line are strongly correlated), and the seven fits together take a second or less. The few divergent transitions are at the smallest setting, where the line is barely constrained. We now have the joint posterior, and can look at what it does.

def forest(ax, rows, labels, colors, truth=None, pops=POP):
    """Mean and 90% interval of each population's prevalence (%), one line per method. rows: lists of (mean, lo, hi)."""
    offsets = np.linspace(-0.27, 0.27, len(rows)) if len(rows) > 1 else [0.0]
    for (mean, lo, hi), label, color, dy in zip(rows, labels, colors, offsets):
        y = np.arange(len(pops)) + dy
        ax.hlines(y, 100 * lo, 100 * hi, color=color, lw=2.2, alpha=0.85)
        ax.plot(100 * mean, y, "o", ms=4, color=color, label=label)
    if truth is not None:
        ax.plot(100 * truth, np.arange(len(pops)), "|", ms=16, mew=1.6, color=INK, label="truth")
    ax.set_yticks(np.arange(len(pops)), [f"population {p}" for p in pops])
    ax.invert_yaxis()
    ax.set_xlabel("HPV prevalence (%)")
    tidy(ax, grid="x")


def beta_row(a, b):
    return a / (a + b), stats.beta.ppf(Q[0], a, b), stats.beta.ppf(Q[1], a, b)


def draws_row(draws):
    return draws.mean(0), *np.quantile(draws, Q, axis=0)


fig, ax = plt.subplots(figsize=(9.2, 5.6))
forest(ax, [beta_row(A_REAL, B_REAL), draws_row(FULL_REAL["phi"])], ["module 1 alone (the survey)", "joint posterior"], [BLUE, ORANGE])
ax.plot(100 * Z / N, np.arange(J) - 0.27, "x", ms=5, color=INK, label="survey share positive")
ax.legend(frameon=False, fontsize=9, loc="lower right")
ax.set_title("What the cancer counts do to the survey's prevalences (real table)", loc="left")

width_ratio = (stats.beta.ppf(Q[1], A_REAL, B_REAL) - stats.beta.ppf(Q[0], A_REAL, B_REAL)) / np.diff(np.quantile(FULL_REAL["phi"], Q, axis=0), axis=0)[0]
shift = (FULL_REAL["phi"].mean(0) - PHI_HAT) / np.sqrt(A_REAL * B_REAL / (A_REAL + B_REAL) ** 2 / (A_REAL + B_REAL + 1))
print(f"joint intervals are narrower than the survey's by a factor of {np.median(width_ratio):.1f} (median; from {width_ratio.min():.1f} to {width_ratio.max():.1f})")
print("shift of the centre, in survey standard deviations:", " ".join(f"{s:+.1f}" for s in shift))
print(f"population 9: survey {100 * Z[8] / N[8]:.1f}%, module 1 alone {100 * PHI_HAT[8]:.1f}%, joint {100 * FULL_REAL['phi'][:, 8].mean():.1f}% "
      f"(90% interval {100 * np.quantile(FULL_REAL['phi'][:, 8], 0.05):.1f} to {100 * np.quantile(FULL_REAL['phi'][:, 8], 0.95):.1f})")
joint intervals are narrower than the survey's by a factor of 2.1 (median; from 0.7 to 3.8)
shift of the centre, in survey standard deviations: +0.1 -0.1 -0.2 +1.1 +5.5 +1.7 +2.3 +0.0 -2.7 +1.6 -1.3 -1.1 +0.2
population 9: survey 20.2%, module 1 alone 20.6%, joint 12.4% (90% interval 10.4 to 14.5)
Figure

The joint posterior moves the prevalences and tightens them. Population 9, which the survey puts at 20%, comes out at 12%, with an interval that excludes everything the survey's own interval contains. Population 5, where one woman in 145 was positive, comes out at over 6%. The typical interval is half as wide as the survey's. The cancer counts have not merely informed the prevalences; in several populations they have overruled the survey.

Is that good or bad? If the straight line and the Poisson noise are right, it is exactly what should happen: 2,400 cancers know more than 106 positive tests. If they are wrong, the survey was right and the joint posterior has replaced it with something worse and more confident. The table cannot say which, because nobody knows the true prevalences.

The choice. The joint posterior of the real table is the fit at the top of the dial, checked against quadrature. Rejected: the default pm.sample, whose answer depends on the seed and can be unanimously wrong; and constraining the slope to be positive, which removes the mode we happened to find without telling us whether others remain. What would change our mind: nothing about the fit; about its meaning, a table with known prevalences, which is what we build next.

3 · A twin with a known answer

The twin keeps the design of the real table: the same 13 survey sizes and the same woman-years. We choose the truth. The 13 true prevalences are round numbers close to the survey's estimates, from 1% to 20%. The true line has intercept $-1.6$ and slope 13. And the cancer counts are generated in one of two ways.

  • The scatter world (module 2 is wrong). The log rate of population $j$ is the line plus $0.6\,\varepsilon_j$ with $\varepsilon_j \sim \mathcal N(0, 1)$: populations differ in screening, in smoking, in how complete their registry is, and none of that is HPV prevalence. Module 2 has no such term. This is the misspecification we name: a source of scatter between populations that the Poisson regression does not have. The values $-1.6$, 13 and 0.6 are close to what a model that does have the term estimates from the real table (part 7).
  • The right world (module 2 is right). The same line and no extra scatter: the cancer counts are Poisson around it, exactly as module 2 says.

In both worlds the survey is binomial around the true prevalences, so module 1 is always right. We draw 100 datasets from each world. For single fits we keep one dataset of the scatter world on the bench: the one whose cancer rates stray from the true line by the median amount among the 100, so that it is typical in the one respect that defines its world.

PHI_TRUE = np.array([0.07, 0.10, 0.07, 0.06, 0.015, 0.01, 0.065, 0.13, 0.20, 0.01, 0.05, 0.013, 0.05])
THETA_TRUE = np.array([-1.6, 13.0])
SCATTER = 0.6
REPS = 100            # datasets per world
S = 1000              # draws per fit on repeated datasets: 4 chains of 250
ETAS = np.array([0.003, 0.01, 0.03, 0.1, 0.3, 1.0])     # the dial on repeated datasets
ETA_GRID = np.concatenate([[0.0], ETAS])                    # with 0, the cut, in front


def log_rate_line(phi):
    return THETA_TRUE[0] + THETA_TRUE[1] * phi


def simulate(rng, reps, scatter=0.0, log_rate=log_rate_line, survey_scale=1):
    """`reps` twins of the table: survey counts and cancer counts, the design of the real table."""
    Zs = rng.binomial(N * survey_scale, PHI_TRUE, size=(reps, J))
    Ys = rng.poisson(np.exp(log_rate(PHI_TRUE) + scatter * rng.standard_normal((reps, J)) + OFF))
    return Zs, Ys


SIM = {"scatter": simulate(np.random.default_rng([RANDOM_SEED, 1]), REPS, SCATTER),
       "right": simulate(np.random.default_rng([RANDOM_SEED, 2]), REPS)}
# the bench: the dataset whose cancer rates stray from the true line by the median amount
strays = np.std(np.log(1000 * np.maximum(SIM["scatter"][1], 0.5) / T) - log_rate_line(PHI_TRUE), axis=1)
BENCH_ID = int(np.argmin(np.abs(strays - np.median(strays))))
ZB, YB = SIM["scatter"][0][BENCH_ID], SIM["scatter"][1][BENCH_ID]
AB, BB = 1 + ZB, 1 + N - ZB
print(f"bench: dataset {BENCH_ID} of the scatter world; its log rates stray from the true line with sd {strays[BENCH_ID]:.2f} "
      f"(over the 100 datasets: {np.quantile(strays, 0.05):.2f} to {np.quantile(strays, 0.95):.2f})")
print(pd.DataFrame({"true prevalence (%)": 100 * PHI_TRUE, "bench: survey positive": ZB, "of": N,
                    "true rate per 1,000 on the line": np.exp(log_rate_line(PHI_TRUE)),
                    "bench: cases per 1,000": 1000 * YB / T}, index=pd.Index(POP, name="population")).round(2).T.to_string())
bench: dataset 62 of the scatter world; its log rates stray from the true line with sd 0.56 (over the 100 datasets: 0.38 to 0.78)
population                        1    2    3    4    5    6    7    8    9    10   11   12   13
true prevalence (%)                7   10    7    6  1.5    1  6.5   13   20    1    5  1.3    5
bench: survey positive             8    9    8   12    2    4    7    7   29    2   11   14    5
of                               111   71  162  188  145  215  166   37  173  143  229  696   93
true rate per 1,000 on the line  0.5 0.74  0.5 0.44 0.25 0.23 0.47 1.09 2.72 0.23 0.39 0.24 0.39
bench: cases per 1,000          0.82 0.49 0.39 0.35 0.21 0.27 0.24 1.98 5.71 0.13 0.77 0.09 0.19

On the bench dataset we fit the two extremes: module 1 alone, which is thirteen Beta distributions, and the joint posterior, reached by walking up the dial as before. From here on a scoreboard keeps the time and memory of each method on this one dataset; its error and coverage will come from all 100.

sb = Scoreboard(truth={"phi": np.tile(PHI_TRUE, (REPS, 1))}, ci_prob=CI)
ESS = {}
M_FULL, M_PLUG, M_CUT, M_CUT_L = ("full joint posterior", "two-stage plug-in", "cut posterior, nested NUTS",
                                   "cut posterior, Laplace second stage")
M_SMI, M_SMI_W, M_FIX = "semi-modular, dial 0.01", "semi-modular, dial set by WAIC", "joint, module 2 repaired"

with sb.track(M_FULL):
    BENCH = walk(COMPILED, ZB, N, YB, DIAL, seed=RANDOM_SEED + 10, draws=1000, tune=500, keep=True)
FULL_BENCH = BENCH[-1]
ESS[M_FULL] = diagnose(FULL_BENCH)["smallest ESS, prevalences"]
print(pd.DataFrame([{"dial": d, "divergences": f["divergences"], **diagnose(f)} for d, f in zip(DIAL, BENCH)]).round(3).to_string(index=False))

fig, ax = plt.subplots(figsize=(9.2, 5.6))
forest(ax, [beta_row(AB, BB), draws_row(FULL_BENCH["phi"])], ["module 1 alone (the survey)", "joint posterior"], [BLUE, ORANGE], truth=PHI_TRUE)
ax.legend(frameon=False, fontsize=9, loc="lower right")
ax.set_title("The bench dataset of the scatter world: here we know who is right", loc="left")

inside = lambda lo, hi: int(((lo <= PHI_TRUE) & (PHI_TRUE <= hi)).sum())
print(f"\ntruth inside the 90% interval: module 1 alone {inside(*beta_row(AB, BB)[1:])} of 13 populations, "
      f"joint posterior {inside(*draws_row(FULL_BENCH['phi'])[1:])} of 13")
 dial  divergences  largest r_hat  smallest ESS, prevalences  smallest ESS, line
0.001           14              1                   5.32e+03            3.28e+03
0.003            0              1                   6.06e+03            4.62e+03
 0.01            0              1                   5.26e+03            4.13e+03
 0.03            0              1                   3.83e+03            3.59e+03
  0.1            0              1                   3.23e+03            2.99e+03
  0.3            0              1                   1.85e+03            1.68e+03
    1            1              1                        971                 879

truth inside the 90% interval: module 1 alone 12 of 13 populations, joint posterior 4 of 13
Figure

With the truth marked, the picture of part 2 can be judged. The survey's intervals are wide and they contain the true prevalence in all but one population. The joint posterior's are narrow and miss it in most. This is one dataset; the claim needs all of them.

Every fit the two worlds need

The cell below does the sampling for most of the notebook. For each of the 200 datasets it walks up a dial of six values, ending at the joint posterior, with one compiled model and with_data: 1,200 fits, each with four chains of 250 draws after 250 warm-up steps. It also fits the repaired model of part 7 to each dataset, so that everything is ready when we want it.

Part 2 taught us not to take a joint fit on trust, so each one is checked twice. If r_hat of the slope is above 1.05 the fit is run again with a longer warm-up. And the fit is compared with a coarse, wide version of the quadrature of part 2: if it sits where the density is more than $e^{10}$ below the best point of the grid, it is in a minor mode, and the fits of that dataset are restarted from the grid's best point.

t0 = time.time()
COMPILED_FIX = nutpie.compile_pymc_model(dial_model(Z, N, Y, repaired=True))
print(f"repaired model compiled in {time.time() - t0:.0f} s")


CHECK_LEVEL, CHECK_SLOPE = np.linspace(-3.0, 1.5, 46), np.linspace(-150.0, 150.0, 31)


def mode_check(fit, Z, N, Y, dial=1.0):
    """How far below the best density on a coarse, wide grid does the fit sit (in log units), and where is the best?"""
    grid = log_marginal_theta(CHECK_LEVEL, CHECK_SLOPE, Z, N, Y, dial, thin=2)
    slope = fit["theta"][:, 1]
    near = np.abs(CHECK_SLOPE - slope.mean()) <= max(3 * slope.std(), 10.0)       # the grid columns the fit covers
    k = np.unravel_index(grid.argmax(), grid.shape)
    best = np.array([CHECK_LEVEL[k[0]] - CHECK_SLOPE[k[1]] * C0, CHECK_SLOPE[k[1]]])
    return (grid.max() - grid[:, near].max() if near.any() else np.inf), best


def start_at(theta, Z, N, Y, dial=1.0, off=OFF):
    """A start at a given line, with each prevalence where its posterior given that line puts it."""
    log_mu = theta[0] + theta[1] * QUAD_PHI + off[:, None]
    log_w = dial * (Y[:, None] * log_mu - np.exp(log_mu)) + Z[:, None] * np.log(QUAD_PHI) + (N - Z)[:, None] * np.log1p(-QUAD_PHI) + QUAD_LOGW
    w = special.softmax(log_w, axis=1)
    mean = (w * QUAD_U).sum(1)
    return dict(loc_phi=mean, scale_phi=np.sqrt((w * QUAD_U**2).sum(1) - mean**2), loc_theta=theta, scale_theta=np.array([0.1, 2.0]))


GAP = 10.0            # a fit sitting where the density is e^10 below the best found is in the wrong place


def run_world(Zs, Ys, seed, dial=ETAS, repaired=True, Ns=N):
    """The NUTS fits of one world: the powered posterior at every value of the dial, and the repaired model."""
    reps = len(Zs)
    run = {"phi": {float(d): np.empty((S, reps, J)) for d in dial}, "theta_full": np.empty((S, reps, 2)),
           "divergences": 0, "rhat_slope": np.empty(reps), "rerun": [], "restarted": [], "unresolved": []}
    if repaired:
        run["fix"] = {"phi": np.empty((S, reps, J)), "theta": np.empty((S, reps, 2)), "tau": np.empty((S, reps)), "divergences": 0}
    for r in range(reps):
        fits = walk(COMPILED, Zs[r], Ns, Ys[r], dial, seed=seed + 100 * r)
        if fits[-1]["rhat_slope"] > 1.05:                          # chains disagree: the same fit with a longer warm-up
            run["rerun"].append(r)
            fits[-1] = unpack(sample(COMPILED, Zs[r], Ns, Ys[r], start_at(fits[-1]["theta"].mean(0), Zs[r], Ns, Ys[r]), 1.0,
                                     seed=seed + 100 * r + 90, tune=1000))
        if mode_check(fits[-1], Zs[r], Ns, Ys[r])[0] > GAP:        # the joint fit is in a minor mode: go back down the dial
            run["restarted"].append(r)
            for k, d in enumerate(dial):
                gap, best = mode_check(fits[k], Zs[r], Ns, Ys[r], d)
                if gap > GAP:
                    fits[k] = unpack(sample(COMPILED, Zs[r], Ns, Ys[r], start_at(best, Zs[r], Ns, Ys[r], d), d, seed=seed + 100 * r + 60 + k, tune=400))
            if mode_check(fits[-1], Zs[r], Ns, Ys[r])[0] > GAP:
                run["unresolved"].append(r)
        for d, fit in zip(dial, fits):
            run["phi"][float(d)][:, r] = fit["phi"]
            run["divergences"] += fit["divergences"]
        run["theta_full"][:, r] = fits[-1]["theta"]
        run["rhat_slope"][r] = fits[-1]["rhat_slope"]
        if repaired:
            fit = unpack(sample(COMPILED_FIX, Zs[r], Ns, Ys[r], survey_start(Zs[r], Ns, Ys[r]), seed=seed + 100 * r + 50,
                                tune=400, target_accept=0.95))
            for name in ("phi", "theta", "tau"):
                run["fix"][name][:, r] = fit[name]
            run["fix"]["divergences"] += fit["divergences"]
    return run


def add_second_stage(run, Zs, Ys, rng, Ns=N):
    """Module 1 alone (dial 0), the plug-in, and for every value of the dial theta given each draw of phi."""
    a, b = 1 + Zs, 1 + Ns - Zs
    run["phi"][0.0] = rng.beta(a, b, size=(S, *a.shape))
    phi_hat = a / (a + b)
    mode, _ = conditional_laplace(phi_hat, Ys)
    run["theta"] = {d: conditional_draws(phi, Ys, rng, start=mode, iters=12) for d, phi in run["phi"].items()}
    run["theta_plug"] = conditional_draws(np.broadcast_to(phi_hat, (S, *phi_hat.shape)), Ys, rng, start=mode, iters=2)
    return run


RUN = {}
for k, world in enumerate(SIM):
    t0 = time.time()
    RUN[world] = add_second_stage(run_world(*SIM[world], seed=1000 * (k + 1)), *SIM[world], np.random.default_rng([RANDOM_SEED, 10 + k]))
    run = RUN[world]
    print(f"{world:8s} world: {REPS} datasets, {REPS * (len(ETAS) + 1)} fits in {time.time() - t0:3.0f} s; divergent transitions: "
          f"{run['divergences']} of {REPS * S * len(ETAS):,} draws up the dial, {run['fix']['divergences']} of {REPS * S:,} in the repaired model")
    print(f"         joint fits rerun with a longer warm-up: {len(run['rerun'])}, of which r_hat of the slope is still above 1.05: "
          f"{int((run['rhat_slope'] > 1.05).sum())}; found in a minor mode and restarted: {len(run['restarted'])}, still there: {len(run['unresolved'])}")
print(f"bench dataset: the joint fit sits {mode_check(FULL_BENCH, ZB, N, YB)[0]:.1f} log units below the best density on the coarse grid; "
      f"real table: {mode_check(FULL_REAL, Z, N, Y)[0]:.1f}")
repaired model compiled in 5 s
scatter  world: 100 datasets, 700 fits in  48 s; divergent transitions: 82 of 600,000 draws up the dial, 1 of 100,000 in the repaired model
         joint fits rerun with a longer warm-up: 5, of which r_hat of the slope is still above 1.05: 1; found in a minor mode and restarted: 1, still there: 0
right    world: 100 datasets, 700 fits in  48 s; divergent transitions: 16 of 600,000 draws up the dial, 3 of 100,000 in the repaired model
         joint fits rerun with a longer warm-up: 0, of which r_hat of the slope is still above 1.05: 0; found in a minor mode and restarted: 0, still there: 0
bench dataset: the joint fit sits 0.0 log units below the best density on the coarse grid; real table: 0.0

A fit costs a few hundredths of a second, checks included, so fourteen hundred of them are affordable. A handful of joint fits in the scatter world needed the longer warm-up (one still has an r_hat a little above 1.05 after it), and one had walked into a minor mode and was restarted from the grid. The right world gave no trouble. The walk up the dial is a good recipe for this posterior and not a guarantee, which is why the check stays in.

Now the comparison of part 2 can be made with numbers. For each world we score module 1 alone and the joint posterior on the $100 \times 13$ prevalences: the root mean squared error of the posterior mean (in percentage points), the share of 90% intervals that contain the truth, and their mean width.

def interval_score(draws, truth):
    """Error of the posterior mean, coverage and width of the central 90% interval, over all scalars."""
    lo, hi = np.quantile(draws, Q, axis=0)
    error = draws.mean(0) - truth
    return {"rmse": float(np.sqrt(np.mean(error**2))), "bias": float(error.mean()),
            "coverage": float(np.mean((lo <= truth) & (truth <= hi))), "width": float((hi - lo).mean())}


def prevalence_table(methods):
    """methods: {label: function of a world's run returning draws (S, reps, J)}; error and width in percentage points."""
    rows = {}
    for world in ("scatter", "right"):
        for label, pick in methods.items():
            sc = interval_score(pick(RUN[world]), PHI_TRUE)
            rows[(world, label)] = {"RMSE (points)": 100 * sc["rmse"], "coverage of 90% intervals": sc["coverage"], "mean width (points)": 100 * sc["width"]}
    return pd.DataFrame(rows).T


first = prevalence_table({"module 1 alone": lambda run: run["phi"][0.0], "joint posterior": lambda run: run["phi"][1.0]})
print(first.round(2).to_string())

fig, axes = plt.subplots(1, 2, figsize=(12, 3.9), sharey=True)
grid_z = np.linspace(-9, 9, 400)
for ax, world, title in zip(axes, ("scatter", "right"), ("Scatter world: module 2 is wrong", "Right world: module 2 is right")):
    for d, label, color in ((0.0, "module 1 alone", BLUE), (1.0, "joint posterior", ORANGE)):
        draws = RUN[world]["phi"][d]
        z = ((draws.mean(0) - PHI_TRUE) / draws.std(0)).ravel()
        ax.hist(np.clip(z, -9, 9), bins=np.linspace(-9, 9, 55), density=True, histtype="stepfilled", alpha=0.45, color=color,
                label=f"{label}: sd {z.std():.1f}")
    ax.plot(grid_z, stats.norm.pdf(grid_z), color=INK, lw=1.1, label="standard normal")
    ax.set_xlabel("(posterior mean - truth) / posterior sd")
    ax.set_title(title, loc="left")
    ax.legend(frameon=False, fontsize=9)
    tidy(ax)
axes[0].set_ylabel("density over 1,300 prevalences");
                         RMSE (points)  coverage of 90% intervals  mean width (points)
scatter module 1 alone            2.42                       0.91                 6.85
        joint posterior           3.18                       0.39                 2.75
right   module 1 alone            2.46                       0.91                 6.83
        joint posterior           1.25                       0.88                 3.33
Figure

The two worlds give opposite verdicts, and both are large.

In the scatter world the joint posterior is worse than the survey alone on every count. Its error is a third larger, its intervals are 40% as wide, and they contain the truth 40% of the time where they should contain it 90% of the time. The histogram on the left shows the same thing in units of the posterior's own standard deviation: an honest posterior puts the truth about one standard deviation from its centre, and the joint posterior routinely puts it three or more away (the bars at the two ends collect everything beyond nine). Module 1 alone is what it should be, at 91%.

In the right world the joint posterior halves the error of the survey alone, with intervals half as wide that still cover 88% of the time. The cut is not free. Refusing the feedback when the feedback is sound throws away most of what the table knows about prevalence.

So neither answer is safe as a default, and the rest of the notebook is about the three things one can do: find out which world we are in (part 4), take a position between the two (part 6), or repair module 2 so that the joint posterior can be trusted (part 7).

The choice. Score every method on prevalences, in both worlds, on 100 datasets each. Rejected: judging by one dataset (the bench is typical by construction and still one draw), and judging only in the world where module 2 is wrong, which would make cutting look free. What would change our mind: a twin whose survey sizes or case counts were far from the real table's; part 10 varies the survey size to see how the verdict moves.

4 · Seeing the leak without knowing the truth

On the real table there is no truth to compare with. What we have are posterior predictive checks: draw parameters from a posterior, simulate new data from them, and ask whether the observed data look like the simulated ones. There are two datasets (survey counts, cancer counts) and two posteriors we might draw from (the joint one, and the one with feedback cut), so four checks, of which three are worth running. For each we use a $\chi^2$ discrepancy, the sum over populations of (observed - expected)$^2$ / variance, computed for the observed and the replicated counts at every posterior draw. The check reports how often the replicated discrepancy is the larger one; a value below 0.05 means the observed counts fit worse than almost anything the posterior would generate.

  • Cancer counts under the joint posterior. The natural check of module 2, the suspect.
  • Survey counts under the joint posterior. A check of whether the joint fit still agrees with module 1's own data.
  • Cancer counts under the cut posterior. The prevalences come from the survey alone, the line from module 2 given each draw of them (part 5 builds this posterior; here we only use it). This looked to us like the check that would point at module 2: hold the prevalences where the trusted data put them and see whether the regression can live with that.

In the twin we know which world each dataset comes from, so we can ask of each check the question that matters: does it fire when module 2 is wrong, and stay quiet when module 2 is right?

def check_cases(phi, theta, Y, rng):
    """Posterior predictive p-value of the chi-square discrepancy of the cancer counts, per dataset."""
    mu = np.exp(theta[..., :1] + theta[..., 1:] * phi + OFF)
    replicated = rng.poisson(mu)
    return (((replicated - mu) ** 2 / mu).sum(-1) >= ((Y - mu) ** 2 / mu).sum(-1)).mean(0)


def check_survey(phi, Z, rng, Ns=N):
    """The same for the survey counts."""
    expected, variance = Ns * phi, Ns * phi * (1 - phi)
    replicated = rng.binomial(Ns, phi)
    return (((replicated - expected) ** 2 / variance).sum(-1) >= ((Z - expected) ** 2 / variance).sum(-1)).mean(0)


rng = np.random.default_rng([RANDOM_SEED, 20])
CHECKS = {}
for world in ("scatter", "right"):
    Zs, Ys = SIM[world]
    run = RUN[world]
    CHECKS[world] = {"cancer counts, joint posterior": check_cases(run["phi"][1.0], run["theta_full"], Ys, rng),
                     "survey counts, joint posterior": check_survey(run["phi"][1.0], Zs, rng),
                     "cancer counts, cut posterior": check_cases(run["phi"][0.0], run["theta"][0.0], Ys, rng)}
flagged = pd.DataFrame({(world, kind): {name: (np.mean(p < 0.05) if kind == "flagged at 0.05" else np.median(p)) for name, p in CHECKS[world].items()}
                        for world in CHECKS for kind in ("flagged at 0.05", "median p")})
print(flagged.round(2).to_string())
                                       scatter                    right         
                               flagged at 0.05 median p flagged at 0.05 median p
cancer counts, joint posterior            0.07     0.27               0     0.52
survey counts, joint posterior             0.9        0               0     0.48
cancer counts, cut posterior                 1        0               1        0

The table has one row that separates the worlds and two that do not, and the one that works is not the one we expected.

Cancer counts under the joint posterior almost never flag anything, in either world. This is the check that most analysts would run first, and it is nearly blind. The joint fit has thirteen prevalences to adjust and has adjusted them until the cancer counts sit on the line. The misfit of module 2 has not gone away; it has been moved into the prevalences, where this check does not look.

Cancer counts under the cut posterior flag every dataset in both worlds, so they tell us nothing either. The expectation was wrong, and the reason is worth a sentence. With the prevalences drawn from the survey alone, each draw puts the populations at slightly wrong places along the line, and with hundreds of cases per population a small error in prevalence is a large one in Poisson terms. The check cannot tell a wrong regression from a right regression fed noisy covariates.

Survey counts under the joint posterior are what separates the worlds. When module 2 is right, the prevalences it helps to estimate still agree with the survey, and the check passes. When module 2 is wrong, the prevalences have been dragged to where the survey counts become improbable, and the check flags most datasets. The leak shows up in the predictive check of the module that is being leaked into.

The figure shows the three checks on the bench dataset, population by population.

def predictive_band(replicated, scale):
    lo, hi = np.quantile(replicated / scale, Q, axis=0)
    return lo, hi


def check_figure(Zs, Ns, Ys, phi_full, theta_full, phi_cut, theta_cut, rng, title):
    """Observed counts against 90% predictive intervals, per population, for the three checks."""
    fig, axes = plt.subplots(1, 3, figsize=(13.6, 4.3))
    x = np.arange(len(Zs))
    mu = lambda phi, theta: np.exp(theta[:, :1] + theta[:, 1:] * phi + OFF)
    panels = [("Survey counts, joint posterior", rng.binomial(Ns, phi_full), Ns / 100, 100 * Zs / Ns, "share positive (%)", ORANGE),
              ("Cancer counts, joint posterior", rng.poisson(mu(phi_full, theta_full)), T / 1000, 1000 * Ys / T, "cases per 1,000 woman-years", ORANGE),
              ("Cancer counts, cut posterior", rng.poisson(mu(phi_cut, theta_cut)), T / 1000, 1000 * Ys / T, "cases per 1,000 woman-years", BLUE)]
    outside = {}
    for ax, (name, replicated, scale, observed, ylabel, color) in zip(axes, panels):
        lo, hi = predictive_band(replicated, scale)
        ax.vlines(x, lo, hi, color=color, lw=5, alpha=0.45, label="90% predictive interval")
        miss = (observed < lo) | (observed > hi)
        ax.plot(x[~miss], observed[~miss], "o", ms=5, color=INK, label="observed, inside")
        ax.plot(x[miss], observed[miss], "o", ms=6, mfc="white", mec=RED, mew=1.8, label="observed, outside")
        ax.set_xticks(x, POP)
        ax.set_xlabel("population")
        ax.set_ylabel(ylabel)
        ax.set_title(name, loc="left", fontsize=11)
        if "Cancer" in name:
            ax.set_yscale("log")
        tidy(ax)
        outside[name] = int(miss.sum())
    axes[0].legend(frameon=False, fontsize=8.5, loc="upper left")
    fig.suptitle(title, x=0.01, ha="left", fontsize=12)
    return outside


rng = np.random.default_rng([RANDOM_SEED, 21])
phi_cut_bench = rng.beta(AB, BB, size=(4000, J))
theta_cut_bench = conditional_draws(phi_cut_bench, YB, rng)
outside = check_figure(ZB, N, YB, FULL_BENCH["phi"], FULL_BENCH["theta"], phi_cut_bench, theta_cut_bench, rng,
                       "Three predictive checks on the bench dataset (scatter world)")
print("populations whose observed count falls outside the 90% predictive interval:", outside)
print("p-values on the bench:", {name: round(float(p[BENCH_ID]), 3) for name, p in CHECKS["scatter"].items()})
populations whose observed count falls outside the 90% predictive interval: {'Survey counts, joint posterior': 2, 'Cancer counts, joint posterior': 0, 'Cancer counts, cut posterior': 4}
p-values on the bench: {'cancer counts, joint posterior': 0.422, 'survey counts, joint posterior': 0.068, 'cancer counts, cut posterior': 0.0}
Figure

In the left panel a couple of populations have a survey count outside what the joint posterior predicts, and several more sit at the edge of their interval. The p-value of the whole check on this dataset is a little above 0.05, just short of the conventional line: the bench is typical in its scatter, and one dataset is still one dataset. Over the hundred, the check flags nine in ten. In the middle panel every cancer count sits inside a narrow interval: the joint fit reproduces the suspect module's data well. On the right, under the cut, the intervals are much wider, because they carry the survey's uncertainty about each prevalence, and several populations still fall outside.

One caution on what the working check does and does not say. It says that the two modules disagree about the prevalences. It does not say which one is wrong. That part comes from outside the data: module 1 has one free parameter per count and a designed sample behind it, and module 2 is a straight line through thirteen countries. If the survey itself were unrepresentative, the same check would fire and the blame would lie the other way.

The choice. To detect a leak, check the trusted module's data against the joint posterior. Rejected: the check of the suspect module's data under the joint posterior (flags almost nothing in either world) and under the cut posterior (flags everything in both). What would change our mind: a module 1 with few parameters per data point, which could then misfit for reasons of its own and make its check ambiguous.

5 · Module 2 without feedback: plug-in, cut, and a sampler that fails

Suppose we decide that the cancer counts shall not touch the prevalences. Module 1 then stands alone, and the question is what to give module 2 in place of the feedback loop.

The two-stage plug-in gives it a number: the survey's posterior mean of each prevalence, as if it were data. Module 2 becomes an ordinary regression, $p(\theta \mid \hat\varphi, Y)$.

The cut posterior gives it the survey's whole posterior, and nothing comes back:

$$p_{\text{cut}}(\varphi, \theta) \;=\; p(\varphi \mid Z)\;\, p(\theta \mid \varphi, Y).$$

To draw from it, draw prevalences from module 1, then draw $\theta$ from module 2 given those prevalences, and repeat with a fresh draw of the prevalences each time. It is multiple imputation with the prevalences as the imputed values, and Plummer (2015) uses it as the gold standard. Each imputation needs its own short MCMC run of module 2, which sounds expensive and, with a compiled model and with_data, is not: one run of 150 warm-up steps and 20 draws, of which we keep the last.

def module2_model(phi, Y, off=OFF):
    with pm.Model() as model:
        phi_d, Yd = pm.Data("phi", phi), pm.Data("Y", Y)
        theta = pm.Normal("theta", 0.0, PRIOR_SD, shape=2)
        pm.Poisson("cases", pt.exp(theta[0] + theta[1] * phi_d + off), observed=Yd)
    return model


COMPILED2 = nutpie.compile_pymc_model(module2_model(PHI_HAT, Y))


def nested_cut(phis, Y, seed):
    """One draw of theta for each row of phis, each from its own short NUTS run of module 2."""
    out = np.empty((len(phis), 2))
    for k, phi in enumerate(phis):
        trace = nutpie.sample(COMPILED2.with_data(phi=phi, Y=Y), draws=20, tune=150, chains=1, cores=1, seed=seed + k, progress_bar=False)
        out[k] = trace.posterior["theta"].to_numpy()[0, -1]
    return out


M_IMPUTE = 400
rng = np.random.default_rng([RANDOM_SEED, 30])
phi_hat_bench = AB / (AB + BB)
with sb.track(M_PLUG):
    phi_module1 = rng.beta(AB, BB, size=(4000, J))
    plug_trace = nutpie.sample(COMPILED2.with_data(phi=phi_hat_bench, Y=YB), draws=1000, tune=500, chains=4, cores=4, seed=RANDOM_SEED, progress_bar=False)
theta_plug_bench = plug_trace.posterior["theta"].to_numpy().reshape(-1, 2)
with sb.track(M_CUT):
    phi_imputed = rng.beta(AB, BB, size=(M_IMPUTE, J))
    theta_nested = nested_cut(phi_imputed, YB, seed=RANDOM_SEED)
with sb.track(M_CUT_L):
    phi_cut_l = rng.beta(AB, BB, size=(4000, J))
    theta_cut_l = conditional_draws(phi_cut_l, YB, rng)
nested_seconds = sb.table().loc[M_CUT, "seconds"]
print(f"{M_IMPUTE} imputations, each with its own NUTS run: {nested_seconds:.1f} s, {1000 * nested_seconds / M_IMPUTE:.0f} ms per run")

mode_b, cov_b = conditional_laplace(phi_hat_bench, YB)
summary = lambda d: {"mean": d.mean(), "sd": d.std(), "5%": np.quantile(d, 0.05), "95%": np.quantile(d, 0.95)}
slopes = pd.DataFrame({
    "plug-in, NUTS": summary(theta_plug_bench[:, 1]),
    "plug-in, Laplace": {"mean": mode_b[1], "sd": np.sqrt(cov_b[1, 1]), "5%": mode_b[1] - 1.645 * np.sqrt(cov_b[1, 1]), "95%": mode_b[1] + 1.645 * np.sqrt(cov_b[1, 1])},
    f"cut, {M_IMPUTE} nested NUTS runs": summary(theta_nested[:, 1]),
    "cut, Laplace on the same imputations": summary(conditional_draws(phi_imputed, YB, rng)[:, 1]),
    "cut, Laplace on 4,000 imputations": summary(theta_cut_l[:, 1]),
    "joint posterior": summary(FULL_BENCH["theta"][:, 1])}).T
print("\nthe slope on the bench dataset (truth 13):")
print(slopes.round(2).to_string())
400 imputations, each with its own NUTS run: 5.4 s, 14 ms per run

the slope on the bench dataset (truth 13):
                                      mean   sd   5%  95%
plug-in, NUTS                         19.6 0.36   19 20.1
plug-in, Laplace                      19.6 0.36 18.9 20.1
cut, 400 nested NUTS runs             17.3 4.03 11.1 24.8
cut, Laplace on the same imputations  17.3 4.04 10.8 24.9
cut, Laplace on 4,000 imputations     17.3 4.17 10.9 24.6
joint posterior                       29.3 3.49 24.1 35.5

Three things in this table.

The plug-in and the cut roughly agree on where the slope is and disagree about how well it is known. The plug-in's standard deviation is about a tenth of the cut's. That gap is the uncertainty of the prevalences, which the plug-in threw away when it replaced thirteen posteriors by thirteen numbers. On this dataset it matters: the cut's 90% interval contains the true slope of 13 and the plug-in's does not. A two-stage analysis that passes point estimates forward reports the precision the second stage would have if the first stage had been exact.

The Laplace shortcut of part 1 reproduces both NUTS answers: the plug-in to the digits shown, and the cut on the very same imputations to within Monte Carlo error. So for the repeated datasets, where 400 NUTS runs per dataset would be too many, the second stage uses the Laplace draw. That is a property of this module 2 (two coefficients, thousands of cases); with a second module that is not nearly Gaussian, the nested runs are the method and their cost is what the scoreboard shows.

And the joint posterior puts the slope somewhere else again, far above the truth, with an interval that excludes both the truth and everything the plug-in allows.

Why not one sampler with the feedback switched off?

The nested scheme is clumsy: a sampler inside a loop. The tempting alternative is a single chain that alternates two updates, the prevalences from the survey alone (ignoring the cancer counts) and then $\theta$ from module 2 given the current prevalences. This is, in essence, what the cut function of BUGS does. The trouble is in the formula. Written as one density, the cut posterior is

$$p_{\text{cut}}(\varphi, \theta) \;\propto\; p(\varphi)\,p(Z \mid \varphi)\; \frac{p(\theta)\,p(Y \mid \varphi, \theta)}{p(Y \mid \varphi)},$$

the joint posterior divided by the feedback term. That term is an integral over $\theta$ which changes with $\varphi$ and has no closed form, so the density cannot be handed to NUTS, and deleting a term from a log-density (or stopping a gradient) does not divide by it. For the alternating chain the consequence is subtle. If the update of $\theta$ were an exact draw from $p(\theta \mid \varphi, Y)$ the chain would be the nested scheme. With a Metropolis or NUTS step instead, $\theta$ only moves part of the way towards its new conditional before the prevalences change again, and where it ends up on average depends on how big the steps are. We can watch that happen: one Metropolis step for $\theta$ after each refresh of the prevalences, with four step sizes.

def naive_cut(step, inner, Y, a, b, mode, cov, iters, chains=1000, seed=0):
    """Alternate: phi from module 1; then `inner` random-walk Metropolis steps on theta given phi."""
    rng = np.random.default_rng(seed)
    chol = np.linalg.cholesky(cov)

    def log_post(theta, phi):
        log_mu = theta[:, :1] + theta[:, 1:] * phi + OFF
        return (Y * log_mu - np.exp(log_mu)).sum(-1) - 0.5 * (theta**2).sum(-1) / PRIOR_SD**2

    theta = np.tile(mode, (chains, 1))
    for _ in range(iters):
        phi = rng.beta(a, b, size=(chains, len(a)))
        current = log_post(theta, phi)
        for _ in range(inner):
            proposal = theta + step * rng.standard_normal((chains, 2)) @ chol.T
            proposed = log_post(proposal, phi)
            accept = np.log(rng.random(chains)) < proposed - current
            theta = np.where(accept[:, None], proposal, theta)
            current = np.where(accept, proposed, current)
    return theta


NAIVE = {}
for step in (0.3, 1.0, 2.4, 6.0):
    NAIVE[f"one step of size {step:g}"] = naive_cut(step, 1, YB, AB, BB, mode_b, cov_b, iters=500, seed=RANDOM_SEED)[:, 1]
NAIVE["40 steps of size 2.4"] = naive_cut(2.4, 40, YB, AB, BB, mode_b, cov_b, iters=120, seed=RANDOM_SEED)[:, 1]
naive_table = pd.DataFrame({name: summary(d) for name, d in NAIVE.items()}).T
print("slope from the alternating chain (step sizes in units of the plug-in posterior's spread):")
print(naive_table.round(2).to_string())

fig, axes = plt.subplots(1, 2, figsize=(12.6, 4.2))
ax = axes[0]
grid_s = np.linspace(0, 48, 500)
for label, d, color in (("two-stage plug-in", theta_plug_bench[:, 1], MAGENTA), ("cut posterior", theta_cut_l[:, 1], BLUE),
                        ("joint posterior", FULL_BENCH["theta"][:, 1], ORANGE)):
    dens = stats.gaussian_kde(d)(grid_s)
    ax.plot(grid_s, dens / dens.max(), color=color, lw=1.8, label=f"{label}: {d.mean():.1f} (sd {d.std():.1f})")
ax.vlines(THETA_TRUE[1], 0, 1.08, color=INK, lw=1, ls="--", label="truth")
ax.set_xlabel(r"slope $\theta_2$")
ax.set_ylabel("density, scaled to the same height")
ax.set_ylim(0, 1.55)
ax.set_title("Three answers for the slope (bench dataset)", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=9, loc="upper left", ncol=2)
tidy(ax)
ax = axes[1]
steps = [0.3, 1.0, 2.4, 6.0]
ax.plot(steps, [NAIVE[f"one step of size {s:g}"].std() for s in steps], "o-", color=RED, label="alternating chain, one Metropolis step")
ax.axhline(NAIVE["40 steps of size 2.4"].std(), color=RED, lw=1, ls=":", label="alternating chain, 40 steps")
ax.axhline(theta_cut_l[:, 1].std(), color=BLUE, lw=1.6, label="cut posterior (multiple imputation)")
ax.axhline(theta_plug_bench[:, 1].std(), color=MAGENTA, lw=1.6, label="two-stage plug-in")
ax.set_xscale("log")
ax.set_xticks(steps, [f"{s:g}" for s in steps])
ax.minorticks_off()
ax.set_xlabel("Metropolis step size (in units of the plug-in posterior's spread)")
ax.set_ylabel("posterior sd of the slope")
ax.set_ylim(0, None)
ax.set_title("One chain, feedback deleted: the answer follows the tuning", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=9)
tidy(ax);
slope from the alternating chain (step sizes in units of the plug-in posterior's spread):
                      mean   sd   5%  95%
one step of size 0.3  16.7 0.66 15.6 17.7
one step of size 1    16.7  1.1 14.8 18.5
one step of size 2.4  16.6 1.67 14.1 19.4
one step of size 6    16.5 2.48 12.6 20.7
40 steps of size 2.4  17.3 3.71 11.5 23.7
Figure

The alternating chain gives a different posterior for every step size, and none of them is the cut posterior. With small steps it is less than twice as wide as the plug-in: $\theta$ never catches up with the prevalences, so in effect it sees their average. With large steps it widens, and only with many steps per refresh, when each update has time to forget the previous prevalences, does it come close to the cut posterior, at which point it is the nested scheme. Nothing in the chain's own output would reveal this; each run looks stationary. This is the behaviour behind Plummer's (2015) result that the algorithm in OpenBUGS has no well-defined limit, and it is why the cut posterior is computed here by imputation. (There are alternatives to nesting: Plummer proposes tempered transitions to improve the single chain, and the unbiased MCMC with couplings of Jacob, O'Leary and Atchadé can target the cut posterior.)

The slope on all the datasets

The bench dataset is one draw. The table scores the three answers for the slope, whose true value is 13 in both worlds, over the 100 datasets of each.

def slope_table(methods):
    rows = {}
    for world in ("scatter", "right"):
        for label, pick in methods.items():
            sc = interval_score(pick(RUN[world])[..., 1], THETA_TRUE[1])
            rows[(world, label)] = {"RMSE": sc["rmse"], "bias": sc["bias"], "coverage of 90% intervals": sc["coverage"], "mean width": sc["width"]}
    return pd.DataFrame(rows).T


print(slope_table({"two-stage plug-in": lambda run: run["theta_plug"], "cut posterior": lambda run: run["theta"][0.0],
                   "joint posterior": lambda run: run["theta_full"]}).round(2).to_string())


def exact_slope(theta, Z, N, Y):
    """Mean and central 90% interval of the slope under the joint posterior, by quadrature on a grid placed by the draws."""
    centre = theta[:, 0] + theta[:, 1] * C0
    level = np.linspace(centre.mean() - 7 * centre.std(), centre.mean() + 7 * centre.std(), 41)
    slope = np.linspace(theta[:, 1].mean() - 7 * theta[:, 1].std(), theta[:, 1].mean() + 7 * theta[:, 1].std(), 81)
    grid = log_marginal_theta(level, slope, Z, N, Y, thin=2)
    mass = np.exp(grid - grid.max()).sum(0)
    mass /= mass.sum()
    return (mass * slope).sum(), *np.interp(Q, np.cumsum(mass), slope)


exact = np.array([exact_slope(RUN["right"]["theta_full"][:, r], SIM["right"][0][r], N, SIM["right"][1][r]) for r in range(REPS)])
print(f"\nright world, joint posterior of the slope by quadrature: bias {exact[:, 0].mean() - THETA_TRUE[1]:+.2f}, "
      f"coverage of the exact 90% interval {np.mean((exact[:, 1] <= THETA_TRUE[1]) & (THETA_TRUE[1] <= exact[:, 2])):.2f}")
                           RMSE  bias  coverage of 90% intervals  mean width
scatter two-stage plug-in  4.77 -1.71                       0.09        1.13
        cut posterior      4.87 -2.81                       0.56        6.61
        joint posterior    10.7  8.51                       0.17        9.58
right   two-stage plug-in  2.13 -1.47                        0.2        1.24
        cut posterior       2.9 -2.67                       0.52         5.9
        joint posterior    1.69 -0.56                        0.8        4.82
right world, joint posterior of the slope by quadrature: bias -0.57, coverage of the exact 90% interval 0.79

Read the right world first, where module 2 is correct and any failure belongs to the method. The plug-in's intervals contain the true slope in a fifth of the datasets: the price of pretending the prevalences are known. The cut posterior's intervals are five times wider and still reach only about half, because its slope is biased towards zero. This is the old errors-in-variables effect: the imputed prevalences are the true ones plus survey noise, a regression on noisy covariates flattens, and without feedback nothing corrects it. Carmona and Nicholls (2020) discuss it under the name dilution. The joint posterior, which uses the cancer counts to sharpen the prevalences, has the smallest error and the best coverage. At 80% that coverage is still short of 90%, and the quadrature of part 2 gives the same figure, so the shortfall belongs to this posterior with its thirteen populations and not to the sampler. For module 2 as for module 1, cutting has a price when the module is right.

In the scatter world no row is honest about the slope. The plug-in is worst. The cut covers a little over half the time, since it still believes that module 2's noise is Poisson and it is not. And the joint posterior has by far the largest error, more than twice the others': the prevalences it bent to fit the cancer counts no longer span the range they should, and the slope absorbs the difference. Cutting protects module 1 from module 2. It does not repair module 2.

The choice. If module 2 must be kept as it is, pass it the whole posterior of the prevalences, by imputation. Rejected: the plug-in (its intervals for the slope are five times too narrow), and a single chain with the feedback term deleted (its answer depends on the step size). What would change our mind: surveys so large that the prevalences were effectively known; plug-in and cut would then coincide.

6 · The dial: semi-modular inference

Full and cut are the two ends of something. Carmona and Nicholls (2020) fill in the middle with a two-step recipe that reuses everything we have. First, fit the prevalences with module 2's likelihood raised to a power $\eta$ between 0 and 1,

$$p_{\eta}(\varphi, \tilde\theta \mid Z, Y) \;\propto\; p(\varphi)\,p(Z \mid \varphi)\;\, p(\tilde\theta)\,p(Y \mid \varphi, \tilde\theta)^{\eta},$$

so that the cancer counts speak about the prevalences with a fraction $\eta$ of their voice. The $\tilde\theta$ in this fit is a throwaway copy of the line, there only to carry the feedback. Second, discard it, and draw the real $\theta$ from module 2 at full strength given each draw of the prevalences, exactly as in the cut. At $\eta = 0$ this is the cut posterior and at $\eta = 1$ it is the joint posterior. The power is the dial of part 2: the walk up the dial that we used to reach the joint posterior safely was computing the first step of this recipe all along.

The figure shows the whole dial on the bench dataset. Each small panel is one population: the posterior of its prevalence as the dial goes from 0 to 1, with the truth as a dashed line. The axis is stretched near zero because that is where things happen.

def waic_survey(phi, Z, Ns=N):
    """WAIC estimate of the ELPD of the survey, one term per woman: phi (S, ..., J) -> (...)."""
    log_lik = np.stack([np.log(phi), np.log1p(-phi)])                      # a positive woman, a negative woman
    lppd = special.logsumexp(log_lik, axis=1) - np.log(log_lik.shape[1])
    penalty = log_lik.var(axis=1, ddof=1)
    return (np.stack([Z, Ns - Z]) * (lppd - penalty)).sum(axis=(0, -1))


def dial_figure(fits, Zs, Ns, Ys, rng, title, truth=None, slope_truth=None):
    """The new plot: every prevalence, the slope and the survey's ELPD against the dial."""
    a, b = 1 + Zs, 1 + Ns - Zs
    x = np.concatenate([[0.0], DIAL])
    phi_cut = rng.beta(a, b, size=(4000, len(Zs)))
    phis = [phi_cut] + [f["phi"] for f in fits]
    slopes = [conditional_draws(phi, Ys, rng)[:, 1] for phi in phis]
    elpd = np.array([waic_survey(phi, Zs, Ns) for phi in phis])
    fig, axes = plt.subplots(3, 5, figsize=(14.2, 7.6), sharex=True)

    def ribbon(ax, draws, color, scale=1.0):
        lo, hi = np.quantile(np.stack(draws), Q, axis=1) * scale
        mid_lo, mid_hi = np.quantile(np.stack(draws), [0.25, 0.75], axis=1) * scale
        ax.fill_between(x, lo, hi, color=color, alpha=0.22, lw=0)
        ax.fill_between(x, mid_lo, mid_hi, color=color, alpha=0.35, lw=0)
        ax.plot(x, [d.mean() * scale for d in draws], "o-", ms=3, lw=1.4, color=color)

    for j, ax in enumerate(axes.flat[: len(Zs)]):
        ribbon(ax, [phi[:, j] for phi in phis], BLUE, 100)
        if truth is not None:
            ax.axhline(100 * truth[j], color=INK, lw=1, ls="--")
        ax.set_title(f"population {POP[j]}: {Zs[j]} of {Ns[j]}", loc="left", fontsize=9.5)
        ax.set_ylim(0, None)
        tidy(ax)
    ax = axes.flat[len(Zs)]
    ribbon(ax, slopes, ORANGE)
    if slope_truth is not None:
        ax.axhline(slope_truth, color=INK, lw=1, ls="--")
    ax.set_title(r"slope $\theta_2$ (second stage)", loc="left", fontsize=9.5)
    tidy(ax)
    ax = axes.flat[len(Zs) + 1]
    ax.plot(x, elpd - elpd[0], "o-", ms=3, lw=1.4, color=GREEN)
    ax.plot(x[elpd.argmax()], (elpd - elpd[0]).max(), "o", ms=9, mfc="none", mec=GREEN, mew=1.6)
    ax.set_title("survey ELPD, relative to the cut", loc="left", fontsize=9.5)
    tidy(ax)
    for ax in axes.flat:
        ax.set_xscale("symlog", linthresh=1e-3, linscale=0.6)
        ax.set_xticks([0, 1e-3, 1e-2, 1e-1, 1], ["0", ".001", ".01", ".1", "1"])
        ax.tick_params(labelsize=8)
        ax.minorticks_off()
    for ax in axes[2]:
        ax.set_xlabel(r"dial $\eta$   (0 = cut, 1 = full)")
    for ax in axes[:, 0]:
        ax.set_ylabel("prevalence (%)")
    fig.suptitle(title, x=0.01, ha="left", fontsize=12.5)
    return x, elpd, slopes


rng = np.random.default_rng([RANDOM_SEED, 40])
x_dial, elpd_bench, slopes_bench = dial_figure(
    BENCH, ZB, N, YB, rng, truth=PHI_TRUE, slope_truth=THETA_TRUE[1],
    title="The module-1 posterior as the dial turns from cut to full (bench dataset; bands 50% and 90%, dashed = truth)")
print(pd.DataFrame({"survey ELPD (WAIC), relative to the cut": elpd_bench - elpd_bench[0], "slope, mean": [d.mean() for d in slopes_bench],
                    "slope, sd": [d.std() for d in slopes_bench]}, index=pd.Index([f"{d:g}" for d in x_dial], name="dial")).round(2).T.to_string())
dial                                       0  0.001  0.003  0.01  0.03  0.1  0.3     1
survey ELPD (WAIC), relative to the cut    0   0.13   0.53  0.98  1.44 0.94 0.22 -0.61
slope, mean                             17.2   18.2   19.2  21.2  23.2 25.8 27.9  29.3
slope, sd                               4.03    4.2   3.92  3.75  3.78 3.51 3.53  3.49
Figure

Read a panel from left to right. At 0 the band is the survey's own posterior. As the dial rises the band narrows and its centre slides towards wherever the line wants that population to be: for some populations that is towards the dashed truth, for others away from it and out the other side. The movement is well under way at a dial of 0.01 and mostly complete by 0.3. A module with 2,400 cases needs only a few per cent of its voice to out-shout a survey with a hundred positives, and that is why the axis had to be stretched.

How far to turn it

The dial needs a setting, and the setting should not come from the truth. The proposal of Carmona and Nicholls is to choose $\eta$ by predictive performance, and Jacob et al. (2017) argue for the same kind of criterion: score the candidate posteriors by how well they predict data, and since the quantity we are protecting is the prevalence, score them on the trusted module's data. Our score is the expected log predictive density (ELPD) of the survey: how well the posterior of the prevalences predicts the test result of a woman it has not seen. It is estimated by WAIC with one term per woman surveyed (a PSIS leave-one-out estimate, the default of ArviZ, gives nearly the same numbers and is checked below). The last panel of the figure shows it for the bench dataset.

In the twin this rule can itself be tested, because the true prevalences give the true ELPD of any posterior in closed form: a new woman in population $j$ is positive with probability $\varphi^*_j$, and the posterior predicts her with its mean.

def true_elpd(phi, Ns=N):
    """Exact expected log predictive density of a new survey of the same size, from the true prevalences."""
    mean = phi.mean(0)
    return (Ns * (PHI_TRUE * np.log(mean) + (1 - PHI_TRUE) * np.log1p(-mean))).sum(-1)


def set_dial(world):
    """Score every setting of the dial by the survey's WAIC, dataset by dataset, and keep the draws at the best one."""
    run, (Zs, Ys) = RUN[world], SIM[world]
    waic = np.stack([waic_survey(run["phi"][d], Zs) for d in ETA_GRID])          # (dial, dataset)
    truth = np.stack([true_elpd(run["phi"][d]) for d in ETA_GRID])
    pick = waic.argmax(0)
    run["phi_pick"] = np.stack([run["phi"][ETA_GRID[k]][:, r] for r, k in enumerate(pick)], axis=1)
    run["theta_pick"] = np.stack([run["theta"][ETA_GRID[k]][:, r] for r, k in enumerate(pick)], axis=1)
    return {"waic": pick, "oracle": truth.argmax(0), "waic_curve": waic, "true_curve": truth}


PICK = {world: set_dial(world) for world in ("scatter", "right")}
dial_rows = {}
for world in PICK:
    waic, truth = PICK[world]["waic_curve"], PICK[world]["true_curve"]
    for k, d in enumerate(ETA_GRID):
        sc = interval_score(RUN[world]["phi"][d], PHI_TRUE)
        dial_rows[(world, d)] = {"RMSE (points)": 100 * sc["rmse"], "coverage": sc["coverage"], "width (points)": 100 * sc["width"],
                                 "WAIC - cut": (waic[k] - waic[0]).mean(), "true ELPD - cut": (truth[k] - truth[0]).mean(),
                                 "datasets choosing it": int((PICK[world]["waic"] == k).sum())}
dial_table = pd.DataFrame(dial_rows).T
print(dial_table.round(2).to_string())

fig, axes = plt.subplots(1, 3, figsize=(13.6, 4.1))
for world, color, label in (("scatter", RED, "scatter world (module 2 wrong)"), ("right", GREEN, "right world")):
    sub = dial_table.loc[world]
    axes[0].plot(ETA_GRID, sub["RMSE (points)"], "o-", color=color, label=label)
    axes[1].plot(ETA_GRID, sub["coverage"], "o-", color=color, label=label)
    axes[2].bar(np.arange(len(ETA_GRID)) + (0.2 if world == "right" else -0.2), sub["datasets choosing it"], width=0.4, color=color, alpha=0.8, label=label)
axes[1].axhline(CI, color=INK, lw=1, ls="--")
for ax, title, ylabel in zip(axes[:2], ("Error of the prevalences against the dial", "Coverage of their 90% intervals"),
                             ("RMSE (percentage points)", "coverage")):
    ax.set_xscale("symlog", linthresh=3e-3, linscale=0.6)
    ax.set_xlim(-0.0008, 1.6)
    ax.set_xticks(ETA_GRID, [f"{d:g}" for d in ETA_GRID])
    ax.minorticks_off()
    ax.set_xlabel(r"dial $\eta$")
    ax.set_ylabel(ylabel)
    ax.set_title(title, loc="left", fontsize=11)
    tidy(ax)
axes[0].set_ylim(0, None)
axes[1].set_ylim(0, 1)
axes[0].legend(frameon=False, fontsize=9)
axes[2].set_xticks(np.arange(len(ETA_GRID)), [f"{d:g}" for d in ETA_GRID])
axes[2].set_xlabel(r"dial $\eta$ chosen by the survey's WAIC")
axes[2].set_ylabel("datasets, of 100")
axes[2].set_title("Where the rule sets the dial", loc="left", fontsize=11)
tidy(axes[2]);
               RMSE (points)  coverage  width (points)  WAIC - cut  true ELPD - cut  datasets choosing it
scatter 0               2.42      0.91            6.85           0                0                     9
        0.003            2.3      0.92            6.68        0.28             0.24                    15
        0.01            2.24       0.9            6.39        0.51             0.33                    27
        0.03            2.27      0.86            5.84        0.33            -0.05                    36
        0.1             2.51      0.74            4.88       -2.15            -2.91                     8
        0.3             2.83      0.56            3.73       -8.21             -9.1                     3
        1               3.18      0.39            2.75       -14.5            -15.2                     2
right   0               2.46      0.91            6.83           0                0                     0
        0.003           2.33      0.92            6.67        0.31             0.27                     0
        0.01            2.19      0.93            6.48         0.7             0.71                     0
        0.03             1.9      0.93            6.02        1.51             1.54                     1
        0.1             1.54      0.94            5.17        2.57             2.61                     6
        0.3             1.32      0.94            4.24        3.37             3.36                    17
        1               1.25      0.88            3.33        3.74             3.61                    76
Figure

The first two panels are the dial's whole story in the two worlds. In the right world, turning the dial up reduces the error steadily and the intervals stay honest all the way: full is best. In the scatter world the error falls a little at first, bottoms out near 0.01, and from 0.1 on is above the cut's, while coverage starts to slide at about 0.03 and then collapses. So there is a small gain to be had from a small dial even when module 2 is wrong, since a weak pull towards a roughly right line helps more than it hurts, and a large loss from a large one.

The third panel shows what the rule does with that. In the right world it sends three quarters of the datasets to the top of the dial and nearly all the rest to 0.1 or 0.3. In the scatter world it keeps almost nine in ten at 0.03 or below. It is a noisy rule, though: the differences in ELPD between neighbouring settings are fractions of a unit, and a few datasets of the scatter world are sent to 0.3 or 1. The next cell scores the result, and checks the WAIC against the two things it stands in for.

picked = prevalence_table({"module 1 alone (dial 0)": lambda run: run["phi"][0.0], "dial fixed at 0.01": lambda run: run["phi"][0.01],
                           "dial set by WAIC": lambda run: run["phi_pick"], "joint posterior (dial 1)": lambda run: run["phi"][1.0]})
print(picked.round(2).to_string())
for world in PICK:
    agree = np.mean(np.abs(PICK[world]["waic"] - PICK[world]["oracle"]) <= 1)
    regret = (PICK[world]["true_curve"].max(0) - PICK[world]["true_curve"][PICK[world]["waic"], np.arange(REPS)]).mean()
    print(f"{world:8s}: WAIC picks the setting with the best true ELPD, or its neighbour, in {agree:.0%} of datasets; "
          f"mean loss of true ELPD against the best setting {regret:.2f}")


def loo_survey(phi, Z, Ns=N):
    """PSIS-LOO of the survey with ArviZ, one term per woman (women of a population with the same result share a term)."""
    counts = np.concatenate([Z, Ns - Z])
    keep = counts > 0
    log_lik = np.concatenate([np.log(phi), np.log1p(-phi)], axis=1)[:, keep].reshape(4, -1, int(keep.sum()))
    tree = xr.DataTree.from_dict({"posterior": xr.Dataset({"x": (("chain", "draw"), np.zeros(log_lik.shape[:2]))}),
                                  "log_likelihood": xr.Dataset({"survey": (("chain", "draw", "cell"), log_lik)})})
    loo = az.loo(tree, pointwise=True, var_name="survey")
    return float((loo.elpd_i.to_numpy() * counts[keep]).sum()), float(loo.pareto_k.max())


loo_bench = [loo_survey(f["phi"], ZB) for f in BENCH]
exact_cut = (ZB * np.where(ZB > 0, np.log(np.maximum(AB - 1, 1e-300) / (AB + BB - 1)), 0.0) + (N - ZB) * np.log((BB - 1) / (AB + BB - 1))).sum()
log_mu = lambda phi, theta: theta[:, :1] + theta[:, 1:] * phi + OFF
lppd_cases = [float((special.logsumexp(stats.poisson.logpmf(YB, np.exp(log_mu(f["phi"], conditional_draws(f["phi"], YB, rng)))), axis=0) - np.log(len(f["phi"]))).sum())
              for f in BENCH]
print("\nbench dataset, along the dial (ELPD relative to the exact leave-one-woman-out value of the cut):")
print(pd.DataFrame({"survey ELPD, WAIC": elpd_bench[1:] - exact_cut, "survey ELPD, PSIS-LOO": [v - exact_cut for v, _ in loo_bench],
                    "largest Pareto k": [k for _, k in loo_bench], "log predictive density of the cancer counts": lppd_cases},
                   index=pd.Index([f"{d:g}" for d in DIAL], name="dial")).round(2).to_string())
print(f"dial 0 (the cut): WAIC {elpd_bench[0]:.2f}, exact leave-one-woman-out {exact_cut:.2f}")
                                  RMSE (points)  coverage of 90% intervals  mean width (points)
scatter module 1 alone (dial 0)            2.42                       0.91                 6.85
        dial fixed at 0.01                 2.24                        0.9                 6.39
        dial set by WAIC                   2.25                       0.87                 5.99
        joint posterior (dial 1)           3.18                       0.39                 2.75
right   module 1 alone (dial 0)            2.46                       0.91                 6.83
        dial fixed at 0.01                 2.19                       0.93                 6.48
        dial set by WAIC                   1.35                       0.89                 3.63
        joint posterior (dial 1)           1.25                       0.88                 3.33
scatter : WAIC picks the setting with the best true ELPD, or its neighbour, in 62% of datasets; mean loss of true ELPD against the best setting 0.64
right   : WAIC picks the setting with the best true ELPD, or its neighbour, in 95% of datasets; mean loss of true ELPD against the best setting 0.31

bench dataset, along the dial (ELPD relative to the exact leave-one-woman-out value of the cut):
       survey ELPD, WAIC  survey ELPD, PSIS-LOO  largest Pareto k  log predictive density of the cancer counts
dial                                                                                                          
0.001               0.23                   0.15              0.54                                        -75.9
0.003               0.64                   0.55              0.44                                        -74.4
0.01                1.09                   1.03              0.27                                        -70.5
0.03                1.54                   1.47              0.48                                        -65.3
0.1                 1.04                   0.99              0.43                                        -58.4
0.3                 0.32                   0.29              0.49                                        -51.8
1                  -0.51                  -0.52              0.27                                        -46.5
dial 0 (the cut): WAIC -443.38, exact leave-one-woman-out -443.48

Three checks on the rule, and then its result.

WAIC and PSIS-LOO agree to within a tenth or two of a unit along the whole dial on the bench dataset, and at dial 0, where the posterior is a Beta and leaving one woman out can be done exactly, the WAIC is within a tenth of the exact value. In the twin the WAIC's choice lands on or next to the setting with the best true ELPD in six of ten datasets of the scatter world and nearly all of the right world, and loses half a unit of true ELPD on average when measured against the best setting. And the last column shows what happens if the dial is scored on the other module's data: the cancer counts are predicted better and better as the dial rises, in this dataset from the scatter world where rising is the wrong thing to do. Scoring the dial on the suspect module's data rewards the leak, for the same reason that the check on those data was blind in part 4.

As for the result: in the right world the dial set by WAIC recovers nine tenths of the joint posterior's gain over the survey alone. In the scatter world its error is a little below the cut's and its coverage a few points below 90%, because the few datasets sent far up the dial are badly served. A dial fixed at 0.01 does as well in the scatter world and gives up most of the gain in the right one. The data-driven dial is an insurance policy: close to the better of cut and full in each of these two worlds, without knowing which world it is in.

The choice. Set the dial by the survey's ELPD, estimated by WAIC over women. Rejected: a fixed dial (there is no single good value: the useful range depends on how much louder module 2 is than module 1), and scoring on the cancer counts (it always turns the dial up). What would change our mind: surveys with so few women that the ELPD could not tell neighbouring settings apart at all; the choice would then be noise, and the cut would be the honest default.

rng = np.random.default_rng([RANDOM_SEED, 41])
with sb.track(M_SMI):
    fits = walk(COMPILED, ZB, N, YB, DIAL[:3], seed=RANDOM_SEED + 20, draws=1000, tune=500, keep=True)
    theta_smi = conditional_draws(fits[-1]["phi"], YB, rng)
ESS[M_SMI] = diagnose(fits[-1])["smallest ESS, prevalences"]
with sb.track(M_SMI_W):
    fits = walk(COMPILED, ZB, N, YB, DIAL, seed=RANDOM_SEED + 30, draws=1000, tune=500, keep=True)
    scores = [waic_survey(rng.beta(AB, BB, size=(4000, J)), ZB)] + [waic_survey(f["phi"], ZB) for f in fits]
    best = int(np.argmax(scores))
    theta_smi_w = conditional_draws(fits[best - 1]["phi"] if best > 0 else rng.beta(AB, BB, size=(4000, J)), YB, rng)
ESS[M_SMI_W] = diagnose(fits[best - 1])["smallest ESS, prevalences"] if best > 0 else np.nan
print(f"bench dataset: WAIC sets the dial at {np.concatenate([[0.0], DIAL])[best]:g}")
bench dataset: WAIC sets the dial at 0.03

7 · Repair the module instead

Everything so far has kept module 2 as it was and limited the damage. E131 and E132 both ended on the same advice: if the problem has a name, put the name in the model. The scatter world's problem has one. Populations differ in cancer risk for reasons other than HPV, so the counts are overdispersed around the line. The smallest repair is a negative binomial in place of the Poisson:

$$Y_j \sim \text{NegBinomial}\big(\mu_j,\ \alpha = 1/\tau^2\big), \qquad \tau \sim \text{HalfNormal}(1),$$

whose variance is $\mu_j + \tau^2 \mu_j^2$, so that $\tau$ is roughly the standard deviation of the log rate around the line beyond Poisson noise, and $\tau = 0$ is the Poisson model. Note that the repair names the problem without copying the simulator: the twin's extra scatter is lognormal, the negative binomial's is gamma. The module is then fitted jointly, feedback and all. The repaired model was fitted to every dataset in part 3; here are the real table, the bench, and the scores.

fix_real = unpack(sample(COMPILED_FIX, Z, N, Y, survey_start(Z, N, Y), seed=RANDOM_SEED, draws=1000, tune=500, target_accept=0.95), keep=True)
with sb.track(M_FIX):
    fix_bench = unpack(sample(COMPILED_FIX, ZB, N, YB, survey_start(ZB, N, YB), seed=RANDOM_SEED + 1, draws=1000, tune=500, target_accept=0.95), keep=True)
ESS[M_FIX] = diagnose(fix_bench)["smallest ESS, prevalences"]
for label, fit in (("real table", fix_real), ("bench dataset", fix_bench)):
    d = diagnose(fit)
    print(f"{label:13s}: tau {fit['tau'].mean():.2f} (90% interval {np.quantile(fit['tau'], 0.05):.2f} to {np.quantile(fit['tau'], 0.95):.2f}), "
          f"intercept {fit['theta'][:, 0].mean():.2f}, slope {fit['theta'][:, 1].mean():.1f} (sd {fit['theta'][:, 1].std():.1f}); "
          f"{fit['divergences']} divergences, r_hat {d['largest r_hat']:.3f}, ESS {d['smallest ESS, prevalences']:.0f}")
for world in RUN:
    tau = RUN[world]["fix"]["tau"].mean(0)
    print(f"{world:8s} world: posterior mean of tau over the 100 datasets, median {np.median(tau):.2f} (5% to 95%: {np.quantile(tau, 0.05):.2f} to {np.quantile(tau, 0.95):.2f})")

methods_phi = {"module 1 alone": lambda run: run["phi"][0.0], "joint posterior": lambda run: run["phi"][1.0],
               "joint, module 2 repaired": lambda run: run["fix"]["phi"]}
methods_slope = {"cut posterior": lambda run: run["theta"][0.0], "joint posterior": lambda run: run["theta_full"],
                 "joint, module 2 repaired": lambda run: run["fix"]["theta"]}
print("\nprevalences:")
print(prevalence_table(methods_phi).round(2).to_string())
print("\nslope:")
print(slope_table(methods_slope).round(2).to_string())
real table   : tau 0.56 (90% interval 0.35 to 0.84), intercept -1.44, slope 13.2 (sd 4.1); 0 divergences, r_hat 1.002, ESS 3417
bench dataset: tau 0.48 (90% interval 0.26 to 0.77), intercept -2.09, slope 19.6 (sd 4.5); 0 divergences, r_hat 1.002, ESS 3360
scatter  world: posterior mean of tau over the 100 datasets, median 0.56 (5% to 95%: 0.35 to 0.74)
right    world: posterior mean of tau over the 100 datasets, median 0.11 (5% to 95%: 0.07 to 0.20)

prevalences:
                                  RMSE (points)  coverage of 90% intervals  mean width (points)
scatter module 1 alone                     2.42                       0.91                 6.85
        joint posterior                    3.18                       0.39                 2.75
        joint, module 2 repaired           2.18                       0.89                 6.03
right   module 1 alone                     2.46                       0.91                 6.83
        joint posterior                    1.25                       0.88                 3.33
        joint, module 2 repaired           1.31                       0.93                 4.14

slope:
                                  RMSE  bias  coverage of 90% intervals  mean width
scatter cut posterior             4.87 -2.81                       0.56        6.61
        joint posterior           10.7  8.51                       0.17        9.58
        joint, module 2 repaired  3.72  -1.1                       0.88        11.3
right   cut posterior              2.9 -2.67                       0.52         5.9
        joint posterior           1.69 -0.56                        0.8        4.82
        joint, module 2 repaired  1.77 -0.86                       0.84        5.72

On the real table the repaired model estimates a scatter $\tau$ clearly above zero, about 0.56 on the log scale: by its own account a population's cancer rate typically sits a factor of 1.7 above or below the line, where the Poisson model allowed a few per cent. (The twin's intercept, slope and scatter were set near this fit.) In the twin, the typical estimate of $\tau$ is 0.56 in the scatter world and 0.11 in the right world, and the two ranges do not overlap. That makes it a fourth diagnostic, and a more direct one than any predictive check: fit the model that has the term and see whether the term is needed.

The scores are the best so far in the scatter world and close to the best in the right one. In the scatter world the repaired joint model has a smaller error on the prevalences than the survey alone and honest intervals, because it takes from the cancer counts what they can actually support. Its slope is the only one with coverage near 90%. In the right world it gives up very little against the plain joint posterior.

A failure nobody named

That comparison flatters the repair, since we repaired exactly the fault we had built in. So here is a third world with a different fault. In the curve world the counts are Poisson with no extra scatter, but the log rate is not linear in the prevalence: it is linear in the logarithm of the prevalence, so that it rises steeply among the low-prevalence populations and flattens among the high ones. Module 2's straight line is wrong in shape, and the negative binomial repair does not name that. Fifty datasets, with every method of the notebook.

def log_rate_curve(phi):
    return THETA_TRUE[0] + THETA_TRUE[1] * 0.05 + 0.85 * (np.log(phi + 0.01) - np.log(0.06))


REPS_CURVE = 50
SIM["curve"] = simulate(np.random.default_rng([RANDOM_SEED, 3]), REPS_CURVE, log_rate=log_rate_curve)
t0 = time.time()
RUN["curve"] = add_second_stage(run_world(*SIM["curve"], seed=3000), *SIM["curve"], np.random.default_rng([RANDOM_SEED, 13]))
run = RUN["curve"]
print(f"curve world: {REPS_CURVE} datasets in {time.time() - t0:.0f} s; divergences {run['divergences']} up the dial, {run['fix']['divergences']} repaired; "
      f"joint fits rerun {len(run['rerun'])}, with r_hat still above 1.05 {int((run['rhat_slope'] > 1.05).sum())}, in a minor mode and restarted "
      f"{len(run['restarted'])}, still there {len(run['unresolved'])}; tau, median over datasets {np.median(run['fix']['tau'].mean(0)):.2f}")
print("true rate per 1,000 woman-years, curve:", np.exp(log_rate_curve(PHI_TRUE)).round(2))
print("                              and line:", np.exp(log_rate_line(PHI_TRUE)).round(2))
PICK["curve"] = set_dial("curve")
curve_methods = {"module 1 alone": lambda run: run["phi"][0.0], "dial fixed at 0.01": lambda run: run["phi"][0.01],
                 "dial set by WAIC": lambda run: run["phi_pick"], "joint posterior": lambda run: run["phi"][1.0],
                 "joint, module 2 repaired": lambda run: run["fix"]["phi"]}
curve_rows = {}
for label, pick in curve_methods.items():
    sc = interval_score(pick(run), PHI_TRUE)
    curve_rows[label] = {"RMSE (points)": 100 * sc["rmse"], "coverage of 90% intervals": sc["coverage"], "mean width (points)": 100 * sc["width"]}
rng = np.random.default_rng([RANDOM_SEED, 22])
print(pd.DataFrame(curve_rows).T.round(2).to_string())
print("dial set by WAIC, datasets per setting:", dict(zip([f"{d:g}" for d in ETA_GRID], np.bincount(PICK["curve"]["waic"], minlength=len(ETA_GRID)))))
print(f"survey counts under the joint posterior flag {np.mean(check_survey(run['phi'][1.0], SIM['curve'][0], rng) < 0.05):.0%} of the datasets at 0.05; "
      f"cancer counts under the joint posterior {np.mean(check_cases(run['phi'][1.0], run['theta_full'], SIM['curve'][1], rng) < 0.05):.0%}")
curve world: 50 datasets in 19 s; divergences 5 up the dial, 4 repaired; joint fits rerun 0, with r_hat still above 1.05 0, in a minor mode and restarted 0, still there 0; tau, median over datasets 0.28
true rate per 1,000 woman-years, curve: [0.49 0.65 0.49 0.44 0.18 0.15 0.47 0.79 1.12 0.15 0.39 0.17 0.39]
                              and line: [0.5  0.74 0.5  0.44 0.25 0.23 0.47 1.09 2.72 0.23 0.39 0.24 0.39]
                          RMSE (points)  coverage of 90% intervals  mean width (points)
module 1 alone                     2.54                        0.9                 6.86
dial fixed at 0.01                 2.36                       0.91                 6.66
dial set by WAIC                   2.13                       0.77                 4.97
joint posterior                    2.12                       0.56                 3.33
joint, module 2 repaired            1.9                       0.88                 5.46
dial set by WAIC, datasets per setting: {'0': np.int64(0), '0.003': np.int64(1), '0.01': np.int64(3), '0.03': np.int64(8), '0.1': np.int64(16), '0.3': np.int64(9), '1': np.int64(13)}
survey counts under the joint posterior flag 18% of the datasets at 0.05; cancer counts under the joint posterior 0%

Three results here are not what the title of the notebook would predict.

The joint posterior with the wrong curve has a smaller error on the prevalences than the survey alone. A straight line through a curve is still a decent summary of it, and pulling noisy survey estimates towards a decent summary reduces their error. What the wrong module destroys is the intervals: they are half as wide as the survey's and contain the truth 56% of the time. In the scatter world the leak cost accuracy and honesty; here it costs only honesty. "Module 2 is wrong" does not by itself mean that the joint estimate is further from the truth.

The two diagnostics we built are weaker against this fault. The survey check of part 4 flags fewer than one dataset in five. And the survey's ELPD, which judges a posterior by how well its mean predicts one more test result, sees the smaller error and not the narrow intervals: it turns the dial to 0.1 or beyond in three quarters of the datasets, and the dial set by WAIC ends with the joint posterior's error and coverage of 77%. The insurance policy of part 6 has an exclusion: a wrong module that improves the centre and spoils the spread.

And the repair, which names scatter and not curvature, still works. It reads the lack of fit as overdispersion (its $\tau$ is near 0.3 although the simulator has no extra scatter at all), and a module that admits it fits loosely pulls on the prevalences loosely. Its error is the smallest of the five and its coverage is 88%. An overdispersion term is a cheap way of telling a module how much to trust itself, and it bought protection against a fault it did not describe.

The choice. When module 2 can be given a term that lets it admit its own lack of fit, fit that model jointly: it was the best row in two worlds and close to it in the third. Rejected: nothing; cut and dial remain the tools for a module we cannot or may not change (someone else's simulator, a model fixed by a protocol, a likelihood too costly to elaborate). What would change our mind: a fault that overdispersion cannot absorb, such as a module 2 that is biased in the same direction for every population. Exercise 2 builds one.

8 · The scoreboard

Every method now has a row. Time, memory and effective sample size are from one run on the bench dataset, as a user would run it, without the few seconds each model takes to compile. For the joint posterior that run is the whole walk up the dial, since that is what it took to reach it safely. Error, coverage and width are for the prevalences over the 100 datasets of the scatter world, the world the question is about. The plug-in and the two cut rows share one answer for the prevalences (module 1 alone); they differ in what they do next and in what it costs.

def scored_draws(run, target):
    """The draws each method is scored on, for the prevalences or for the line."""
    if target == "phi":
        return {M_FULL: run["phi"][1.0], M_PLUG: run["phi"][0.0], M_CUT: run["phi"][0.0], M_CUT_L: run["phi"][0.0],
                M_SMI: run["phi"][0.01], M_SMI_W: run["phi_pick"], M_FIX: run["fix"]["phi"]}
    return {M_FULL: run["theta_full"], M_PLUG: run["theta_plug"], M_CUT_L: run["theta"][0.0],
            M_SMI: run["theta"][0.01], M_SMI_W: run["theta_pick"], M_FIX: run["fix"]["theta"]}


for name, draws in scored_draws(RUN["scatter"], "phi").items():
    sb.score(name, {"phi": draws}, ess=ESS.get(name))
board = sb.table()
board
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
full joint posterior 0.834 0.593 0.0161 971 1.16e+03 0.0318 0.393 0.0275
two-stage plug-in 0.039 0.723 0.00283 NaN NaN 0.0242 0.912 0.0685
cut posterior, nested NUTS 5.41 0.725 0.00256 NaN NaN 0.0242 0.912 0.0685
cut posterior, Laplace second stage 0.0135 0.608 0.00157 NaN NaN 0.0242 0.912 0.0685
semi-modular, dial 0.01 0.212 0.915 0.0122 5.19e+03 2.45e+04 0.0224 0.902 0.0639
semi-modular, dial set by WAIC 0.539 0.934 0.0194 4.41e+03 8.18e+03 0.0225 0.869 0.0599
joint, module 2 repaired 0.158 0.866 0.00247 3.36e+03 2.13e+04 0.0218 0.893 0.0603
sb.plot(columns=("seconds", "ess_per_s", "rmse", "coverage", "width"), highlight=[M_CUT, M_CUT_L, M_FIX]);
Figure

Coverage splits the rows in two. The joint posterior with the Poisson module is at 40%; everything that removes the feedback, turns it down to one per cent, or repairs the module is at or near 90%. The dial set by WAIC is a few points lower, pulled down by the datasets where the rule turned it too far. Error has the same order with smaller gaps: the repaired model first, then the two dial rows, then the survey alone, and the joint posterior last.

Time is small everywhere and still worth reading. The survey alone costs nothing, and the plug-in one fit of a two-parameter model. The cut posterior by nested NUTS is the most expensive row by an order of magnitude, 400 separate runs, and its Laplace twin shows that the cost belongs to the generic method and not to the idea: when the second stage is nearly Gaussian the cut is almost free. The joint posterior and the dial set by WAIC cost about half a second because each is a walk of seven fits. ESS per second is reported for the rows whose prevalences come from NUTS; the Beta draws of module 1 are independent, and we do not present them as an ESS.

The second table adds what the first cannot show: the right world, and the slope.

def world_board(world, target):
    reps = len(SIM[world][0])
    truth = {"phi": np.tile(PHI_TRUE, (reps, 1))} if target == "phi" else {"slope": np.full(reps, THETA_TRUE[1])}
    other = Scoreboard(truth=truth, ci_prob=CI)
    for name, draws in scored_draws(RUN[world], target).items():
        other.score(name, {"phi": draws} if target == "phi" else {"slope": draws[..., 1]})
    return other.table()[["rmse", "coverage", "width"]]


BOARDS = {(world, target): world_board(world, target) for world in ("scatter", "right") for target in ("phi", "slope")}
both = pd.concat({f"{world} world, {'prevalences' if target == 'phi' else 'slope'}": BOARDS[(world, target)]
                  for world in ("scatter", "right") for target in ("phi", "slope")}, axis=1).reindex(board.index)
print(both.round(3).to_string())
                                    scatter world, prevalences                scatter world, slope                right world, prevalences                right world, slope               
                                                          rmse coverage width                 rmse coverage width                     rmse coverage width               rmse coverage width
method                                                                                                                                                                                     
full joint posterior                                     0.032    0.393 0.028                 10.7     0.17  9.58                    0.013    0.875 0.033               1.69      0.8  4.82
two-stage plug-in                                        0.024    0.912 0.069                 4.77     0.09  1.13                    0.025    0.912 0.068               2.13      0.2  1.24
cut posterior, nested NUTS                               0.024    0.912 0.069                  NaN      NaN   NaN                    0.025    0.912 0.068                NaN      NaN   NaN
cut posterior, Laplace second stage                      0.024    0.912 0.069                 4.87     0.56  6.61                    0.025    0.912 0.068                2.9     0.52   5.9
semi-modular, dial 0.01                                  0.022    0.902 0.064                 5.24     0.46  6.38                    0.022    0.927 0.065                2.4     0.65  5.71
semi-modular, dial set by WAIC                           0.023    0.869  0.06                 5.06     0.42  6.24                    0.013    0.894 0.036                1.7     0.81  4.83
joint, module 2 repaired                                 0.022    0.893  0.06                 3.72     0.88  11.3                    0.013    0.934 0.041               1.77     0.84  5.72

The nested-NUTS row has no entry for the slope: 400 runs for each of 200 datasets were not made, and the Laplace row stands in for it on the strength of part 5.

Read across the two worlds, no row except the last is good everywhere. The joint posterior is the best unrepaired row in the right world and the worst in the scatter world, for the prevalences and for the slope. The cut is honest about the prevalences in both worlds and pays for it in the right world with twice the error, and its slope is diluted in both. The plug-in adds false precision to the cut. The dial set by WAIC follows the cut where the cut is better and the joint posterior where that is better, for the prevalences and for the slope alike, so in the scatter world its slope is no more honest than the cut's. The repaired joint model is at or near the top of all four blocks, and the only row whose slope has honest intervals in the scatter world.

9 · Back to the real table

With the twin's lessons in hand we return to the 13 populations. We run the working check of part 4, set the dial with the survey's ELPD, and put every method's answer side by side.

rng = np.random.default_rng([RANDOM_SEED, 50])
p_survey_real = float(check_survey(FULL_REAL["phi"], Z, rng))
p_cases_real = float(check_cases(FULL_REAL["phi"], FULL_REAL["theta"], Y, rng))
print(f"real table, joint posterior: predictive p-value of the survey counts {p_survey_real:.3f}, of the cancer counts {p_cases_real:.3f}")

x_dial, elpd_real, slopes_real = dial_figure(REAL, Z, N, Y, rng, title="The real table: prevalences, slope and survey ELPD as the dial turns from cut to full")
best_real = int(np.argmax(elpd_real))
loo_real = [loo_survey(f["phi"], Z) for f in REAL]
print(pd.DataFrame({"survey ELPD (WAIC), relative to the cut": elpd_real - elpd_real[0],
                    "PSIS-LOO, relative to the cut's WAIC": [np.nan] + [v - elpd_real[0] for v, _ in loo_real],
                    "slope, mean": [d.mean() for d in slopes_real], "slope, sd": [d.std() for d in slopes_real]},
                   index=pd.Index([f"{d:g}" for d in x_dial], name="dial")).round(2).T.to_string())
print(f"\nthe survey's ELPD is highest at a dial of {x_dial[best_real]:g}; at the joint posterior it is {elpd_real[0] - elpd_real[-1]:.1f} lower than at the cut")
real table, joint posterior: predictive p-value of the survey counts 0.002, of the cancer counts 0.300
dial                                       0  0.001  0.003  0.01  0.03   0.1   0.3     1
survey ELPD (WAIC), relative to the cut    0  -0.06      0  0.23 -0.22 -1.81 -5.99 -9.79
PSIS-LOO, relative to the cut's WAIC     NaN  -0.18  -0.16  0.15 -0.32 -1.92 -6.03 -9.79
slope, mean                             13.6     14   14.7  16.3  18.6  20.3  22.6  24.1
slope, sd                               2.54   2.59   2.81  2.74   2.5  2.68  2.74  2.81

the survey's ELPD is highest at a dial of 0.01; at the joint posterior it is 9.8 lower than at the cut
Figure

The check that separated the worlds in the twin fires on the real table: the survey counts are improbable under the joint posterior (a p-value of a few thousandths), while the cancer counts look fine, the signature of the scatter world. The survey's ELPD is flat from the cut up to a dial of 0.01, within a few tenths of a unit that the twin has taught us not to read, and falls steadily after that; at the joint posterior it is ten units lower, about the gap Jacob et al. (2017) report for these data with a different predictive score. The dial says: at most one per cent of module 2's voice. And the repaired model of part 7 found a scatter of more than half a unit on the log scale. Three diagnostics, one conclusion: on this table the Poisson regression is not to be trusted with the prevalences.

phi_cut_real = rng.beta(A_REAL, B_REAL, size=(4000, J))
chosen = REAL[best_real - 1]["phi"] if best_real > 0 else phi_cut_real
real_slopes = pd.DataFrame({
    "two-stage plug-in": {"mean": plug_mode[1], "sd": np.sqrt(plug_cov[1, 1]), "5%": plug_mode[1] - 1.645 * np.sqrt(plug_cov[1, 1]), "95%": plug_mode[1] + 1.645 * np.sqrt(plug_cov[1, 1])},
    "cut posterior": summary(slopes_real[0]),
    f"semi-modular, dial {x_dial[best_real]:g} (set by WAIC)": summary(slopes_real[best_real]),
    "joint posterior": summary(FULL_REAL["theta"][:, 1]),
    "joint, module 2 repaired": summary(fix_real["theta"][:, 1])}).T
print("the slope on the real table:")
print(real_slopes.round(2).to_string())

fig, ax = plt.subplots(figsize=(9.6, 6.4))
forest(ax, [beta_row(A_REAL, B_REAL), draws_row(chosen), draws_row(fix_real["phi"]), draws_row(FULL_REAL["phi"])],
       ["module 1 alone (cut, plug-in)", f"semi-modular, dial {x_dial[best_real]:g}", "joint, module 2 repaired", "joint posterior"],
       [BLUE, AQUA, VIOLET, ORANGE])
ax.legend(frameon=False, fontsize=9, loc="lower right")
ax.set_title("Four answers for the 13 prevalences (real table)", loc="left")
moved = np.abs(fix_real["phi"].mean(0) - PHI_HAT) / np.sqrt(A_REAL * B_REAL / (A_REAL + B_REAL) ** 2 / (A_REAL + B_REAL + 1))
print(f"\nrepaired model against the survey alone: largest shift of a prevalence {moved.max():.1f} survey standard deviations (population {POP[moved.argmax()]}); "
      f"intervals narrower by a factor of {np.median((stats.beta.ppf(Q[1], A_REAL, B_REAL) - stats.beta.ppf(Q[0], A_REAL, B_REAL)) / np.diff(np.quantile(fix_real['phi'], Q, axis=0), axis=0)[0]):.2f} (median)")
the slope on the real table:
                                       mean   sd   5%  95%
two-stage plug-in                      14.9 0.35 14.3 15.4
cut posterior                          13.6 2.54 9.96 18.2
semi-modular, dial 0.01 (set by WAIC)  16.3 2.74   12 21.1
joint posterior                        24.1  2.8 19.9 29.2
joint, module 2 repaired               13.2  4.1 6.99 20.4

repaired model against the survey alone: largest shift of a prevalence 0.9 survey standard deviations (population 7); intervals narrower by a factor of 1.09 (median)
Figure

For the prevalences, three of the four answers are close. The survey alone, the dial at its chosen setting and the repaired joint model agree to within about one of the survey's standard deviations for every population, and only the unrepaired joint posterior stands apart, with its narrow intervals in other places. For population 9 the three give 19% to 21%, with an interval of roughly 15% to 25%, as the survey said.

For the slope the choice of method matters more than any interval. The joint posterior says 24, the cut, the plug-in and the repaired model say 13 to 15, and the dial at its chosen setting a little more. The plug-in's interval is a seventh as wide as the cut's. The twin tells us how to read these: the joint value is inflated by the leak, the plug-in's precision is false, the cut's value is somewhat diluted and its interval too narrow for a Poisson module that is not Poisson, and the repaired model's slope, 13 with a standard deviation of 4, is the one whose intervals held up in both worlds where the slope has a true value. What the epidemiologist should report is that last line, and the survey's own prevalences.

The choice. On the real table: the survey's prevalences (or the repaired model's, which barely differ), and the repaired model's slope. Rejected: the joint posterior of the textbook model, on three diagnostics; the plug-in's interval for the slope. What would change our mind: evidence that the surveys were not fair samples of their populations. Every method here trusts module 1, and none of them can check it.

10 · When to reach for which

Part 1 said that the leak runs from the module that claims more precision into the one that claims less. That makes the size of the survey the quantity to vary: with bigger surveys module 1 can defend itself. We multiply every survey size by 4, 16, 64 and 256, keep the cancer counts as they are, and compare the joint posterior with the survey alone on 30 datasets per setting in each world (a shorter walk up the dial is enough here, because larger surveys make the joint posterior easier to sample).

SCALES = [1, 4, 16, 64, 256]
SHORT_DIAL = np.array([0.01, 0.1, 1.0])
REPS_SIZE = 30
size_rows = {}
t0 = time.time()
stray = restarted = unresolved = 0
for w, world in enumerate(("scatter", "right")):
    for scale in SCALES:
        if scale == 1:                                     # the 100 datasets we already have
            cut_draws, full_draws = RUN[world]["phi"][0.0], RUN[world]["phi"][1.0]
        else:
            Zs, Ys = simulate(np.random.default_rng([RANDOM_SEED, 60 + w, scale]), REPS_SIZE, SCATTER if world == "scatter" else 0.0, survey_scale=scale)
            run = run_world(Zs, Ys, seed=5000 * (w + 1) + scale, dial=SHORT_DIAL, repaired=False, Ns=N * scale)
            stray += int((run["rhat_slope"] > 1.05).sum())
            restarted += len(run["restarted"])
            unresolved += len(run["unresolved"])
            full_draws = run["phi"][1.0]
            cut_draws = np.random.default_rng([RANDOM_SEED, 70 + w, scale]).beta(1 + Zs, 1 + N * scale - Zs, size=(S, REPS_SIZE, J))
        cut_score, full_score = interval_score(cut_draws, PHI_TRUE), interval_score(full_draws, PHI_TRUE)
        size_rows[(world, scale)] = {"survey alone, RMSE (points)": 100 * cut_score["rmse"], "joint, RMSE (points)": 100 * full_score["rmse"],
                                     "error ratio, joint / survey alone": full_score["rmse"] / cut_score["rmse"],
                                     "survey alone, coverage": cut_score["coverage"], "joint, coverage": full_score["coverage"]}
size_table = pd.DataFrame(size_rows).T
print(f"{2 * (len(SCALES) - 1) * REPS_SIZE} more datasets in {time.time() - t0:.0f} s; joint fits with r_hat of the slope above 1.05 after a rerun: {stray}, "
      f"in a minor mode and restarted: {restarted}, unresolved: {unresolved}")
print(size_table.round(2).to_string())

fig, axes = plt.subplots(1, 2, figsize=(12.4, 4.1))
for world, color, label in (("scatter", RED, "scatter world (module 2 wrong)"), ("right", GREEN, "right world")):
    sub = size_table.loc[world]
    axes[0].plot(SCALES, sub["error ratio, joint / survey alone"], "o-", color=color, label=label)
    axes[1].plot(SCALES, sub["joint, coverage"], "o-", color=color, label=f"joint posterior, {label}")
axes[1].plot(SCALES, size_table.loc["scatter"]["survey alone, coverage"], "o--", color=BLUE, label="survey alone, scatter world")
axes[0].axhline(1, color=INK, lw=1, ls="--")
axes[1].axhline(CI, color=INK, lw=1, ls="--")
for ax, title, ylabel in zip(axes, ("Error of the joint posterior relative to the survey alone", "Coverage of 90% intervals for the prevalences"),
                             ("RMSE ratio (below 1: joint is better)", "coverage")):
    ax.set_xscale("log", base=4)
    ax.set_xticks(SCALES, [f"x{s}" for s in SCALES])
    ax.set_xlabel("survey sizes, relative to the real table")
    ax.set_ylabel(ylabel)
    ax.set_title(title, loc="left", fontsize=11)
    ax.legend(frameon=False, fontsize=9)
    tidy(ax)
axes[0].set_ylim(0, None)
axes[1].set_ylim(0, 1);
240 more datasets in 34 s; joint fits with r_hat of the slope above 1.05 after a rerun: 0, in a minor mode and restarted: 0, unresolved: 0
             survey alone, RMSE (points)  joint, RMSE (points)  error ratio, joint / survey alone  survey alone, coverage  joint, coverage
scatter 1                           2.42                  3.18                               1.31                    0.91             0.39
        4                           1.15                  2.46                               2.14                    0.91             0.39
        16                           0.6                  1.61                                2.7                     0.9             0.47
        64                          0.32                  0.99                               3.08                    0.87             0.56
        256                         0.16                  0.48                               3.05                    0.91             0.69
right   1                           2.46                  1.25                               0.51                    0.91             0.88
        4                           1.19                  0.77                               0.64                     0.9              0.9
        16                          0.55                  0.44                               0.79                    0.91             0.91
        64                          0.31                  0.27                               0.87                    0.89             0.91
        256                         0.16                  0.14                               0.92                    0.91             0.89
Figure

The two curves on the left move in opposite directions, and both argue for cutting as surveys grow. In the right world the joint posterior's advantage shrinks towards nothing: once the surveys are large they know the prevalences as well as the cancer counts do, and there is little left to borrow. In the scatter world the joint posterior's relative error grows with the survey size, from 1.3 times the survey's at the real sizes to three times at 64 and 256 times the real sizes, where it levels off. The survey alone gets better with every woman tested; the joint posterior stays pinned near what a wrong module 2 dictates, and its coverage (right panel) recovers slowly, to 70% at the largest sizes. So a larger trusted dataset does not make the joint fit safe. It makes the cut cheaper when the suspect module is right, and the leak more costly, in relative terms, when it is wrong.

The last figure collects what was measured. One row per situation, one column per method; each cell shows the coverage of the 90% intervals and the error relative to the best method of the row.

COLUMNS = [(M_FULL, "full joint\nposterior"), (M_PLUG, "two-stage\nplug-in"), (M_CUT_L, "cut\nposterior"),
           (M_SMI, "semi-modular,\ndial 0.01"), (M_SMI_W, "semi-modular,\ndial by WAIC"), (M_FIX, "joint, module 2\nrepaired")]


def verdict(coverage, relative_error):
    if coverage < 0.75:
        return "bad"
    if coverage < 0.85:
        return "partial"
    return "good" if relative_error <= 1.15 else "wide"


def grid_row(table):
    best = table["rmse"].min()
    cells = []
    for method, _ in COLUMNS:
        if method not in table.index or np.isnan(table.loc[method, "rmse"]):
            cells.append(("not run", "none"))
        else:
            cov, rel = table.loc[method, "coverage"], table.loc[method, "rmse"] / best
            cells.append((f"{cov:.0%}\n(error x{rel:.2f})", verdict(cov, rel)))
    return cells


cells = {"module 2 lacks scatter:\nprevalences": grid_row(BOARDS[("scatter", "phi")]),
         "module 2 lacks scatter:\nslope": grid_row(BOARDS[("scatter", "slope")]),
         "module 2 has the wrong curve:\nprevalences": grid_row(world_board("curve", "phi")),
         "module 2 is right:\nprevalences": grid_row(BOARDS[("right", "phi")]),
         "module 2 is right:\nslope": grid_row(BOARDS[("right", "slope")])}

SHADE = {"good": "#cdeedd", "wide": "#d5e5f8", "partial": "#fbe7b3", "bad": "#f8cfcc", "none": "#f1f0ec"}
fig, ax = plt.subplots(figsize=(13.2, 6.2))
for i, (row, values) in enumerate(cells.items()):
    ax.text(-0.6, i, row, ha="right", va="center", fontsize=9.5, color=INK, linespacing=1.3)
    for j, (text, kind) in enumerate(values):
        ax.add_patch(plt.Rectangle((j - 0.47, i - 0.44), 0.94, 0.88, fc=SHADE[kind], ec="white", lw=1.5))
        ax.text(j, i, text, ha="center", va="center", fontsize=9, color=INK if kind != "none" else MUTED, linespacing=1.35)
for j, (_, col) in enumerate(COLUMNS):
    ax.text(j, -0.62, col, ha="center", va="bottom", fontsize=9.5, fontweight="bold", color=INK, linespacing=1.2)
used = {kind for values in cells.values() for _, kind in values}
for k, (kind, text) in enumerate([item for item in (("good", "honest and sharp"), ("wide", "honest, less sharp"), ("partial", "somewhat overconfident"),
                                                    ("bad", "overconfident"), ("none", "not run here")) if item[0] in used]):
    ax.add_patch(plt.Rectangle((-1.9 + 1.55 * k, len(cells) - 0.32), 0.22, 0.22, fc=SHADE[kind], ec="white"))
    ax.text(-1.9 + 1.55 * k + 0.3, len(cells) - 0.21, text, va="center", fontsize=9, color=INK)
ax.set_xlim(-2.6, len(COLUMNS) - 0.5)
ax.set_ylim(len(cells) + 0.05, -1.45)
ax.axis("off")
ax.set_title("When to reach for which: every situation in this notebook against every method", loc="left");
Figure

Green is honest and sharp: coverage of at least 85% with an error within 15% of the row's best. Blue is honest and less sharp. Amber is somewhat overconfident (coverage between 75% and 85%), red is overconfident (below 75%). The counting error of a coverage from 100 datasets is a few points.

Read down the columns. The joint posterior is green only where module 2 is right, and red wherever it is wrong. The plug-in is red in both rows for the slope. The cut is honest about the prevalences in every row and never sharp where sharpness was available, and its slope is red in both worlds. The small fixed dial behaves like a slightly better cut. The dial set by WAIC is green for the prevalences where either the cut or the joint posterior is, amber in the curve world, where it turned too far, and no more honest than the cut about the slope when module 2 is wrong. The repaired model is the only column that is never red, and its one amber cell is a slope for which even the correct joint model reaches no more than 80%.

In practice the order of work is this. Fit the joint model, and check the trusted module's data against it. A failed check means a leak. A passed check is weaker evidence, since in the curve world it passed four times in five, so in either case give the suspect module a term that lets it admit its lack of fit, fit that model jointly, and see whether the term is needed. If the module cannot be changed, cut: the trusted module's parameters from its own data, the suspect module's by imputation, never by plugging in point estimates, and with the knowledge that the suspect module's own parameters are not thereby made trustworthy. Turn a dial up from the cut only as far as the trusted module's ELPD supports, expect that to be a short way when the suspect module has much more data, and remember that the ELPD judges centres, not intervals.

Summary

  • The leak runs from the module that claims more precision into the one that claims less. On the real table the registries hold 2,424 cancers and the surveys 106 positive women. The joint posterior moved the prevalence of population 9 from the survey's 20% to 12% and made the typical interval half as wide. Limit: which module is reliable is not in the likelihood; it has to be known from outside.
  • The joint posterior of the textbook model is also hard to sample. With default settings most chains settled in a mode holding about $10^{-36}$ of the posterior, and runs in which all four chains did so had r_hat near 1.03 and no divergences. Quadrature gave the exact answer; walking up a dial from the survey's estimates reached it, with a quadrature check that caught one stray fit among several hundred.
  • Wrong module, wrong prevalences; right module, better prevalences. Over 100 datasets of a twin with known prevalences, the joint posterior's 90% intervals covered 40% when module 2 lacked a source of scatter, with an error a third larger than the survey's. When module 2 was right, the joint posterior halved the survey's error with honest intervals. The cut is not free.
  • The leak is visible in the trusted module's predictive check. Survey counts checked against the joint posterior flagged nine in ten datasets of the scatter world and none of the right world. The check of the cancer counts under the joint posterior flagged almost nothing in either, and under the cut posterior it flagged everything in both, which was not what we expected. Limit: the check shows a conflict, not which side is wrong, and against a wrong curve it fired in fewer than one dataset in five.
  • Plug-in hides uncertainty, and one chain with the feedback deleted is not the cut. The plug-in's interval for the slope was five times too narrow and held the truth in a fifth of the datasets or fewer. An alternating chain gave a different spread for every step size. The cut posterior by imputation took 400 nutpie refits of about a hundredth of a second each. Limit: the cut's slope is diluted towards zero even when module 2 is right (coverage near 50%), and cutting does nothing for a module 2 that is wrong.
  • A dial between cut and full, set by the survey's ELPD, is an insurance policy with an exclusion. It chose the top of the dial for three quarters of the datasets of the right world and 0.03 or less for almost nine in ten of the scatter world, and ended close to the better of cut and full in both. Limit: the ELPD of single test results judges centres and not intervals; with a wrong curve it turned the dial up and coverage fell to 77%.
  • Repairing the module beat every way of containing it. A negative binomial module 2, fitted jointly, had the smallest error in the two worlds where module 2 was wrong, including one whose fault (a wrong curve) it does not name, and coverage of 88% or more for the prevalences in all three. On the real table it estimates a scatter of about 0.56 on the log scale and a slope of 13, against 24 from the textbook joint model.

Try it yourself

  1. A sharper check. The check of part 4 uses the survey twice: to fit the joint posterior and to test it. Remove that by leaving one survey out at a time: fit the joint model with population $j$'s survey count masked (give it a survey size of zero), predict the count from the cancer data and the other twelve surveys, and compare with what was observed. Thirteen walks up the dial per dataset. Does it flag more of the scatter world's datasets than the 0.05 rule of part 4, and how many of the right world's?
  2. A fault that scatter cannot absorb. Build a fourth world in which every registry misses 30% of the cases in populations whose true prevalence is above 6%, and none elsewhere. Run run_world on 50 datasets. Does the negative binomial repair still give honest intervals for the prevalences? What does its $\tau$ look like, and which of the checks sees the problem?
  3. One run for the cut. The cut posterior is the joint posterior divided by $p(Y \mid \varphi)$, and conditional_laplace gives a Laplace estimate of that integral for any $\varphi$: the joint log-density at the conditional mode plus half the log-determinant of the covariance. Add its negative as a pm.Potential to dial_model (the mode has to be found inside the graph: a fixed number of Newton steps written in PyTensor will do) and sample once. Do the prevalences match the Beta posteriors, and the slope the cut posterior of part 5?
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 195 s