import os
for v_ in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
os.environ[v_] = "1" # nutpie runs chains as threads: a BLAS pool per chain would fight over the cores
import logging
import sys
import time
import warnings
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import nutpie
import pymc as pm
import pytensor.tensor as pt
from scipy import integrate, linalg, special, stats
RANDOM_SEED = 134
rng = np.random.default_rng(RANDOM_SEED)
az.style.use("arviz-variat")
logging.getLogger("pymc").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning, module="arviz")
sys.modules.pop("jax", None) # arviz leaves a lazy jax stub that makes matplotlib import all of JAX
T_START = time.time()
BLUE, ORANGE, AQUA, PURPLE, RED = "#2a78d6", "#eb6834", "#1baf7a", "#8c5ac8", "#c8384e"
INK, MUTED, LIGHT = "#222222", "#8a8984", "#d9d8d3"
print(f"PyMC {pm.__version__}, ArviZ {az.__version__}")
PyMC 6.3.2, ArviZ 1.3.0
The setting
A retailer has been testing a new in-store display format, and the head of retail media has to decide by the end of the quarter whether to roll it out to every store. Rolling out costs real money in fixtures and staff time, and pulling it back later costs more. She has two kinds of evidence, and they disagree.
The first is a proper randomised test. Fifty stores were split at random: 24 got the display, 26 did not. Randomisation means the comparison is clean, and the difference in sales lift is about 0.24 index points. Fifty stores is also a small test, though, and the standard error is close to 0.45, so the honest reading is "somewhere between harmful and very good".
The second is everything else. In the past year regional managers put the same display into about 3,400 of 5,000 other stores on their own judgement. That record is a hundred times larger and its difference in means is 1.6 index points, with a standard error of a few hundredths. The trouble is how managers chose. They put displays where they expected the store to do well, and what they expected came from things the data warehouse does not hold: a new housing estate, a competitor closing down the road, a store manager with a good team. That unmeasured local demand also drives sales, so the observational comparison mixes the display's effect with the managers' foresight.
Three tempting answers are all wrong in instructive ways. Ignoring the observational record throws away a hundred times more data. Pooling the two as if both were randomised lets the big confounded study swamp the trial. And a sensitivity analysis on the observational record alone can only say how wrong it might be, because without the trial nothing in the data measures the confounding. What she wants is a single model with a dial: at one end the trial alone, at the other full pooling, and in between a statement of how much she trusts the observational regression to look like the causal one, with an answer for every setting.
That is the idea of Causal-ICM (Dimitriou, Fong, Tarp, Diaz-Ordaz & Lehmann 2026, Bayesian Nonparametric Sensitivity Analysis for Unmeasured Confounding in Data Fusion, arXiv 2611.37514). The experimental response surface $\mu_e(x, a)$ and the observational outcome regression $\mu_o(x, a)$ are modelled as two Gaussian processes that share a latent function. Their prior correlation $\rho$ is the dial. It builds on multi-task GPs (Bonilla, Chai & Williams 2008; Alvarez, Rosasco & Lawrence 2012), on GPs for causal effects (Alaa & van der Schaar 2017), and on the Outcome Sensitivity Model of Bonvini et al. (2022), which bounds the gap between observational and causal regressions where Causal-ICM puts a prior on it. The data-fusion literature it joins (Kallus, Puli & Shalit 2018; Colnet et al. 2024; Lin, Tarp & Evans 2025) asks the same question from the frequentist side: how much to borrow from a study you cannot fully trust.
This notebook continues E107, where a hidden confounder could only be described by sensitivity parameters the data never learn. Here a trial sits beside the confounded study, and the confounding becomes something the data can see.
| part | question | tool |
|---|---|---|
| A | What do the two studies say on their own? | simulation from the paper's design; difference in means |
| B | How do we write "the observational regression is roughly causal"? | the Causal-ICM prior; prior draws of the bias at several $\rho$ |
| C | What does each setting of the dial imply? | the paper's closed-form posterior in NumPy; the same model in PyMC on an HSGP basis, refitted along $\rho$ |
| D | What does the trial learn about the bias itself? | the posterior of the confounding bias against the truth |
| E | Can a bigger observational study overrule the trial? | posterior sd of the effect as the observational study grows |
| F | Can the data choose $\rho$? | a prior on $\rho$ and NUTS |
A · Two studies, one question
We use the data-generating process of the paper's simulation study, which reads naturally as the store story. Each store has an observed covariate $X$ (last year's standardised sales index) and an unobserved one $U$ (local demand), both standard normal and independent. In the observational record a manager runs the display with probability $\operatorname{expit}(1 + 0.8X + U)$. In the trial a coin decides. In both, sales lift is
$$Y = 0.2\,A + X + U + \varepsilon, \qquad \varepsilon \sim \mathcal N(0, 1),$$
so the true effect is 0.2 index points in every store. We centre $Y$ on its pooled mean and standardise $X$ with the trial's mean and sd, as the paper does; neither changes the effect.
TAU_TRUE = 0.2
N_O, N_E = 5000, 50
def simulate_observational(n, rng):
x, u = rng.normal(size=n), rng.normal(size=n)
a = rng.binomial(1, special.expit(1.0 + 0.8 * x + 1.0 * u))
y = TAU_TRUE * a + x + u + rng.normal(size=n)
return x, a, y
def simulate_trial(n, rng):
x, u = rng.normal(size=n), rng.normal(size=n)
a = rng.binomial(1, 0.5, size=n)
y = TAU_TRUE * a + x + u + rng.normal(size=n)
return x, a, y
Xo_raw, Ao, Yo_raw = simulate_observational(N_O, rng)
Xe_raw, Ae, Ye_raw = simulate_trial(N_E, rng)
Y_CENTRE = np.r_[Yo_raw, Ye_raw].mean()
X_MEAN, X_SD = Xe_raw.mean(), Xe_raw.std(ddof=1)
Yo, Ye = Yo_raw - Y_CENTRE, Ye_raw - Y_CENTRE
xo, xe = (Xo_raw - X_MEAN) / X_SD, (Xe_raw - X_MEAN) / X_SD
def diff_in_means(y, a):
d = y[a == 1].mean() - y[a == 0].mean()
se = np.sqrt(y[a == 1].var(ddof=1) / (a == 1).sum() + y[a == 0].var(ddof=1) / (a == 0).sum())
return d, se
def ols_effect(y, a, x):
"""Effect of a in a regression of y on (1, a, x), with its classical se."""
D = np.column_stack([np.ones_like(x), a, x])
beta, res, *_ = np.linalg.lstsq(D, y, rcond=None)
s2 = ((y - D @ beta) ** 2).sum() / (len(y) - 3)
return beta[1], np.sqrt(s2 * np.linalg.inv(D.T @ D)[1, 1])
for label, (y, a, x) in {"trial": (Ye, Ae, xe), "observational": (Yo, Ao, xo)}.items():
d, se = diff_in_means(y, a)
b, seb = ols_effect(y, a, x)
print(f"{label:>13}: n = {len(y):>5} ({int(a.sum())} with display) | difference in means "
f"{d:5.2f} (se {se:.2f}) | adjusted for X {b:5.2f} (se {seb:.2f})")
trial: n = 50 (24 with display) | difference in means 0.24 (se 0.45) | adjusted for X 0.28 (se 0.45) observational: n = 5000 (3442 with display) | difference in means 1.59 (se 0.05) | adjusted for X 1.02 (se 0.04)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), sharey=True)
for ax, (title, x, a, y) in zip(axes, [("observational record, 5,000 stores", xo, Ao, Yo),
("randomised trial, 50 stores", xe, Ae, Ye)]):
for arm, col, lab in [(0, BLUE, "no display"), (1, ORANGE, "display")]:
m = a == arm
ax.scatter(x[m], y[m], s=6 if len(x) > 100 else 22, alpha=0.25 if len(x) > 100 else 0.9,
color=col, label=lab, lw=0)
ax.set_title(title)
ax.set_xlabel("last year's sales index $x$ (standardised)")
axes[0].set_ylabel("sales lift $y$ (centred)")
axes[0].legend(markerscale=2, loc="upper left");

The two studies tell different stories. The trial's difference in means is about 0.24 with a standard error of about 0.45, so it cannot tell a useless display from a great one. Adjusting for last year's sales index barely changes it. The observational record says 1.6, and adjusting for $X$ only brings it down to about 1.0, with a standard error of 0.04. That is five times the truth, measured very precisely. In the left panel the orange stores sit higher everywhere along $x$, because managers picked stores with high $U$, and no regression on $x$ can see $U$.
A naive analyst who pools both studies into one regression gets an answer dominated by the 5,000 confounded stores. We will see that answer again in a moment as one end of the dial.
B · A prior that says "roughly causal"
Fix a treatment arm $a$ and drop it from the notation. Causal-ICM writes the two regression functions with two independent latent GPs $u_1, u_2 \sim \mathrm{GP}(0, k)$:
$$\mu_e(x) = m + u_1(x), \qquad \mu_o(x) = m + \rho\, u_1(x) + \sqrt{1-\rho^2}\; u_2(x).$$
Both functions have the same marginal prior, and their correlation at every $x$ is $\rho$; the coregionalisation matrix of the intrinsic coregionalisation model is $B = \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix}$. The trial informs $\mu_e$, the observational record informs $\mu_o$, and $\rho$ decides how much one tells us about the other. At $\rho = 1$ the two are the same function (full pooling); at $\rho = 0$ they are unrelated (trial only). The arm-specific confounding bias is $d(x) = \mu_o(x) - \mu_e(x)$, and the prior implies
$$d(x) = (\rho - 1)\,u_1(x) + \sqrt{1-\rho^2}\,u_2(x), \qquad \operatorname{sd}\{d(x)\} = \eta\sqrt{2(1-\rho)},$$
with $\eta^2 = k(x, x)$ the GP's signal variance. That formula is the most useful way to talk about $\rho$ with a stakeholder: it turns a correlation into "how many index points of bias do you consider plausible".
Following the paper, the kernel is squared exponential and its hyperparameters come from the trial alone, so that the confounded data cannot tune the prior that is supposed to protect against them. Per arm, the lengthscale is the median pairwise distance between the trial's covariates, $\eta^2$ is the trial outcomes' variance, the noise variance comes from the residuals of a straight-line fit, and the prior mean $m$ is the trial arm's mean outcome.
hyp = {}
for a in (0, 1):
x, y = xe[Ae == a], Ye[Ae == a]
ell = np.median(np.abs(x[:, None] - x[None, :])[np.triu_indices(len(x), 1)])
resid = y - np.polyval(np.polyfit(x, y, 1), x)
hyp[a] = dict(ell=ell, eta2=y.var(ddof=1), sig2=resid.var(ddof=2), m=y.mean())
print(f"arm {a}: lengthscale {ell:.2f}, signal sd {np.sqrt(hyp[a]['eta2']):.2f}, "
f"noise sd {np.sqrt(hyp[a]['sig2']):.2f}, prior mean {hyp[a]['m']:.2f} "
f"(trial n = {len(x)}, observational n = {(Ao == a).sum()})")
for r in (0.5, 0.9, 0.99):
sds = [np.sqrt(hyp[a]["eta2"] * 2 * (1 - r)) for a in (0, 1)]
print(f"rho = {r:4}: prior sd of the bias d(x) is {sds[0]:.2f} (no display), {sds[1]:.2f} (display)")
arm 0: lengthscale 1.00, signal sd 1.93, noise sd 1.96, prior mean -0.47 (trial n = 26, observational n = 1558) arm 1: lengthscale 1.16, signal sd 1.22, noise sd 1.09, prior mean -0.23 (trial n = 24, observational n = 3442) rho = 0.5: prior sd of the bias d(x) is 1.93 (no display), 1.22 (display) rho = 0.9: prior sd of the bias d(x) is 0.86 (no display), 0.54 (display) rho = 0.99: prior sd of the bias d(x) is 0.27 (no display), 0.17 (display)
With 24 and 26 stores per arm these settings are rough, and they differ between the arms: the control arm happens to have a larger outcome variance and noise estimate. We keep them as the paper prescribes and come back to the cost in the summary.
The prior bias scale shows how the dial reads. At $\rho = 0.5$ a store's observational regression may sit about 1.2 to 1.9 index points away from the causal surface; at $\rho = 0.9$, about 0.5 to 0.9; at $\rho = 0.99$, about 0.2 to 0.3. In our world the managers' foresight biases the observational regression by about 0.3 index points in the display arm and about 0.6 in the other (part D works these out). Set against signal sds of 1.2 and 1.9, those biases correspond to a $\rho$ of about 0.95 to 0.97. Keep that number in mind, because it will turn out to sit right on top of the decision. In practice nobody would know it, which is the point of a sensitivity curve.
A Hilbert-space basis for PyMC
The paper's posterior is in closed form because everything is Gaussian. To put the same model in
PyMC we need a representation that samples quickly with 5,050 rows. A Hilbert-space GP
approximation (Solin & Särkkä 2020; Riutort-Mayol et al. 2023; E05) writes each latent function
as $u(x) \approx \sum_{j=1}^{M} \phi_j(x)\,\sqrt{S(\sqrt{\lambda_j})}\,\beta_j$ with fixed sine
basis functions on $[-L, L]$, the kernel's spectral density $S$, and standard normal
coefficients $\beta_j$. This is what pm.gp.HSGP.prior_linearized builds; we write the
few lines out because the same basis feeds a NumPy check. With fixed hyperparameters the model
is linear and Gaussian in the $\beta$s, so NUTS has an easy job, and so does a conjugate update.
M_BASIS = 30
L_BOX = 1.5 * max(np.abs(xo).max(), np.abs(xe).max())
LAMBDA = (np.pi * np.arange(1, M_BASIS + 1) / (2 * L_BOX)) ** 2
def basis(x):
j = np.arange(1, M_BASIS + 1)
return np.sqrt(1 / L_BOX) * np.sin(np.pi * j * (x[:, None] + L_BOX) / (2 * L_BOX))
def sqrt_psd(ell, eta2):
return np.sqrt(eta2 * np.sqrt(2 * np.pi) * ell * np.exp(-0.5 * ell**2 * LAMBDA))
SQRT_PSD = np.stack([sqrt_psd(hyp[a]["ell"], hyp[a]["eta2"]) for a in (0, 1)]) # (arm, basis)
PHI_E, PHI_O = basis(xe), basis(xo)
PRIOR_MEAN = np.array([hyp[0]["m"], hyp[1]["m"]])
NOISE_SD = np.sqrt(np.array([hyp[0]["sig2"], hyp[1]["sig2"]]))
# how good is the approximation? compare the implied kernel with the exact one on a grid
grid = np.linspace(xo.min(), xo.max(), 200)
for a in (0, 1):
Kh = (basis(grid) * SQRT_PSD[a] ** 2) @ basis(grid).T
Kx = hyp[a]["eta2"] * np.exp(-0.5 * (grid[:, None] - grid[None, :]) ** 2 / hyp[a]["ell"] ** 2)
print(f"arm {a}: largest kernel error on the data range {np.abs(Kh - Kx).max() / hyp[a]['eta2']:.1e} "
f"of the signal variance (L = {L_BOX:.1f}, M = {M_BASIS})")
arm 0: largest kernel error on the data range 3.3e-04 of the signal variance (L = 6.0, M = 30) arm 1: largest kernel error on the data range 2.8e-03 of the signal variance (L = 6.0, M = 30)
Thirty basis functions on a box 1.5 times the data range reproduce the exact kernel to within a few parts in a thousand of its variance, which is far below anything we will read off the posterior.
C · The sensitivity curve
The paper's closed form
Proposition 3.1 and Corollary 3.3 of the paper give the posterior of $\mu_e$ given both studies for any $\rho$. With $\Sigma_e = k(X_e, X_e) + \sigma^2 I$, the observational residual $r_o = y_o - \rho\, k(X_o, X_e)\Sigma_e^{-1} y_e$, its covariance $\Sigma_{eo} = k(X_o, X_o) - \rho^2 k(X_o, X_e)\Sigma_e^{-1}k(X_e, X_o) + \sigma^2 I$ and $q(x) = k(x, X_o) - k(x, X_e)\Sigma_e^{-1}k(X_e, X_o)$,
$$m_{e\mid D}(x) = \underbrace{k(x, X_e)\Sigma_e^{-1}y_e}_{\text{trial only}} + \underbrace{\rho\, q(x)\,\Sigma_{eo}^{-1} r_o}_{\text{shift from the observational data}}, \qquad V_{e\mid D}(x) = V_{e\mid D_e}(x) - \rho^2\, q(x)\,\Sigma_{eo}^{-1} q(x)^\top .$$
The decomposition is the paper's headline: the posterior mean is the trial-only answer plus a shift that is proportional to $\rho$ and to what the observational outcomes say that the trial did not already predict. We need the effect averaged over the trial's stores (the target population is the trial population, as in the paper), so we apply the same formulas to the whole vector of trial covariates and average, which needs the posterior covariance across points as well. The code below does that with exact kernels and Cholesky solves, one arm at a time.
def rbf(x1, x2, a):
return hyp[a]["eta2"] * np.exp(-0.5 * (x1[:, None] - x2[None, :]) ** 2 / hyp[a]["ell"] ** 2)
def exact_fusion(rho, xo_=xo, ao_=Ao, yo_=Yo, return_surfaces=False):
"""Causal-ICM data-fusion posterior (paper, Prop 3.1 / Cor 3.3) for the effect averaged over
the trial's covariates. Returns its mean and variance."""
means, covs = [], []
for a in (0, 1):
Xa, ya = xe[Ae == a], Ye[Ae == a] - hyp[a]["m"]
Xb, yb = xo_[ao_ == a], yo_[ao_ == a] - hyp[a]["m"]
ce = linalg.cho_factor(rbf(Xa, Xa, a) + hyp[a]["sig2"] * np.eye(len(Xa)))
Keo, Kse = rbf(Xa, Xb, a), rbf(xe, Xa, a)
Seo = rbf(Xb, Xb, a) - rho**2 * Keo.T @ linalg.cho_solve(ce, Keo) + hyp[a]["sig2"] * np.eye(len(Xb))
r_o = yb - rho * Keo.T @ linalg.cho_solve(ce, ya)
Q = rbf(xe, Xb, a) - Kse @ linalg.cho_solve(ce, Keo)
co = linalg.cho_factor(Seo)
means.append(hyp[a]["m"] + Kse @ linalg.cho_solve(ce, ya) + rho * Q @ linalg.cho_solve(co, r_o))
covs.append(rbf(xe, xe, a) - Kse @ linalg.cho_solve(ce, Kse.T) - rho**2 * Q @ linalg.cho_solve(co, Q.T))
if return_surfaces:
return means, covs
w = np.full(len(xe), 1 / len(xe))
return w @ (means[1] - means[0]), w @ covs[1] @ w + w @ covs[0] @ w
t0 = time.time()
RHO_FINE = np.r_[np.linspace(0, 0.9, 10), np.linspace(0.92, 0.98, 4), 0.99, 0.995, 1.0]
exact = np.array([exact_fusion(r) for r in RHO_FINE])
ex_mean, ex_sd = exact[:, 0], np.sqrt(exact[:, 1])
print(f"closed form on {len(RHO_FINE)} values of rho in {time.time() - t0:.0f} s")
for r, m, s in zip(RHO_FINE, ex_mean, ex_sd):
if r in (0.0, 0.5, 0.8, 0.9, 0.95, 0.98, 0.99, 1.0):
print(f" rho = {r:5.3f}: effect {m:5.2f}, 95% interval [{m - 1.96 * s:5.2f}, {m + 1.96 * s:5.2f}]")
closed form on 17 values of rho in 15 s rho = 0.000: effect 0.24, 95% interval [-0.60, 1.08] rho = 0.500: effect 0.28, 95% interval [-0.55, 1.11] rho = 0.800: effect 0.36, 95% interval [-0.43, 1.16] rho = 0.900: effect 0.46, 95% interval [-0.29, 1.20] rho = 0.980: effect 0.73, 95% interval [ 0.19, 1.26] rho = 0.990: effect 0.83, 95% interval [ 0.40, 1.26] rho = 1.000: effect 0.99, 95% interval [ 0.88, 1.10]
At $\rho = 0$ the posterior is the trial alone, an effect of about 0.24 with a 95% interval from about $-0.6$ to $1.1$. At $\rho = 1$ it is full pooling, about 0.99 with an interval of about $\pm 0.11$ that misses the truth by a mile. In between, the curve is flat for a long stretch and then bends sharply in the last few hundredths before 1: at $\rho = 0.9$ the estimate is still about 0.46, at 0.99 it is 0.83. Almost all the action happens when we claim the two surfaces are nearly identical, which matches what the paper reports for its own data.
The same model in PyMC
The closed form works because the hyperparameters are fixed and everything is Gaussian. A PyMC
version is worth having for two reasons. It is the starting point for anything the closed form
cannot do, such as learning hyperparameters, a non-Gaussian outcome or a prior on $\rho$
(part F). And it is an independent check of the algebra. We put $\rho$ in a pm.Data
container, compile the model once with nutpie, and refit at several values of $\rho$ by
swapping the data, the trick from E33 and E132. Both arms live in one model, indexed by the
arm dimension, and the effect averaged over the trial's stores is a deterministic.
with pm.Model(coords={"arm": ["no display", "display"], "basis": np.arange(M_BASIS)}) as fusion:
rho = pm.Data("rho", 0.9)
b1 = pm.Normal("b1", 0, 1, dims=("arm", "basis"))
b2 = pm.Normal("b2", 0, 1, dims=("arm", "basis"))
w1, w2 = b1 * SQRT_PSD, b2 * SQRT_PSD
u1_e = (PHI_E * w1[Ae]).sum(axis=1)
u1_o = (PHI_O * w1[Ao]).sum(axis=1)
u2_o = (PHI_O * w2[Ao]).sum(axis=1)
pm.Normal("y_e", PRIOR_MEAN[Ae] + u1_e, NOISE_SD[Ae], observed=Ye)
pm.Normal("y_o", PRIOR_MEAN[Ao] + rho * u1_o + pt.sqrt(1 - rho**2) * u2_o, NOISE_SD[Ao], observed=Yo)
pm.Deterministic("ate", PRIOR_MEAN[1] - PRIOR_MEAN[0] + (PHI_E.mean(axis=0) * (w1[1] - w1[0])).sum())
t0 = time.time()
compiled = nutpie.compile_pymc_model(fusion)
print(f"compiled in {time.time() - t0:.0f} s")
RHO_PYMC = [0.0, 0.5, 0.8, 0.9, 0.95, 0.99, 1.0]
pymc_fits = {}
for r in RHO_PYMC:
t0 = time.time()
tr = nutpie.sample(compiled.with_data(rho=np.array(r)), chains=4, draws=1000, seed=RANDOM_SEED,
progress_bar=False)
ate = tr.posterior["ate"]
pymc_fits[r] = ate.values.ravel()
print(f"rho = {r:4}: effect {float(ate.mean()):5.2f} (sd {float(ate.std()):.2f}), "
f"r_hat {float(az.rhat(ate)):.3f}, bulk ESS {float(az.ess(ate)):5.0f}, "
f"divergences {int(tr.sample_stats['diverging'].sum())}, {time.time() - t0:4.1f} s")
compiled in 7 s
rho = 0.0: effect 0.23 (sd 0.43), r_hat 1.001, bulk ESS 4923, divergences 0, 16.3 s
rho = 0.5: effect 0.28 (sd 0.42), r_hat 1.000, bulk ESS 3161, divergences 0, 18.9 s
rho = 0.8: effect 0.36 (sd 0.40), r_hat 1.001, bulk ESS 1559, divergences 0, 11.3 s
rho = 0.9: effect 0.45 (sd 0.38), r_hat 1.001, bulk ESS 1379, divergences 0, 11.5 s
rho = 0.95: effect 0.58 (sd 0.34), r_hat 1.000, bulk ESS 1689, divergences 0, 10.8 s
rho = 0.99: effect 0.82 (sd 0.22), r_hat 1.001, bulk ESS 3369, divergences 0, 10.0 s
rho = 1.0: effect 0.99 (sd 0.06), r_hat 1.001, bulk ESS 4864, divergences 0, 6.0 s
Each fit takes 10 to 30 seconds under nutpie with no divergences, $\hat R$ of 1.00 and a bulk ESS above 1,300 for the effect. The posterior means and sds match the closed form to about 0.01 at every $\rho$, which is what we expect from an HSGP that reproduces the kernel this well and from Monte Carlo error of a few thousandths. From here on we trust both and use whichever is cheaper.
The observational record alone
For comparison we also need the analysis an analyst without the trial could do. With observational data only, the paper's Corollary 3.2 gives the causal posterior at a point as $\mathcal N\big(m + \rho\{m_o(x) - m\},\ (1-\rho^2)k(x,x) + \rho^2 V_o(x)\big)$, where $m_o, V_o$ are the ordinary GP posterior of the observational regression. The bias prior never meets any data, so the dial is the only thing that moves the answer. Here the hyperparameters come from the observational data (the paper does the same), and the prior mean is the observational mean outcome in both arms.
def obs_only(rho):
hyp_o, means, covs = {}, [], []
m_all = Yo.mean()
sub = rng.choice(N_O, 800, replace=False) # median distance on a subsample
for a in (0, 1):
x, y = xo[Ao == a], Yo[Ao == a] - m_all
xs = xo[sub][Ao[sub] == a]
ell = np.median(np.abs(xs[:, None] - xs[None, :])[np.triu_indices(len(xs), 1)])
eta2 = Yo[Ao == a].var(ddof=1)
sig2 = (y - np.polyval(np.polyfit(x, y, 1), x)).var(ddof=2)
k = lambda p, q: eta2 * np.exp(-0.5 * (p[:, None] - q[None, :]) ** 2 / ell**2)
c = linalg.cho_factor(k(x, x) + sig2 * np.eye(len(x)))
Ksx = k(xe, x)
mo = Ksx @ linalg.cho_solve(c, y)
Vo = k(xe, xe) - Ksx @ linalg.cho_solve(c, Ksx.T)
means.append(m_all + rho * mo)
covs.append((1 - rho**2) * k(xe, xe) + rho**2 * Vo)
w = np.full(len(xe), 1 / len(xe))
return w @ (means[1] - means[0]), w @ covs[1] @ w + w @ covs[0] @ w
RHO_OBS = np.r_[np.linspace(0, 0.9, 10), 0.92, 0.94, 0.96, 0.98, 0.99, 1.0]
obs_curve = np.array([obs_only(r) for r in RHO_OBS])
for r, (m, v) in zip(RHO_OBS, obs_curve):
if r in (0.5, 0.9, 0.96, 0.98, 1.0):
print(f"observational only, rho = {r:4}: effect {m:5.2f}, 95% interval "
f"[{m - 1.96 * np.sqrt(v):5.2f}, {m + 1.96 * np.sqrt(v):5.2f}]")
observational only, rho = 0.5: effect 0.50, 95% interval [-2.36, 3.36] observational only, rho = 0.9: effect 0.90, 95% interval [-0.55, 2.35] observational only, rho = 0.96: effect 0.96, 95% interval [ 0.03, 1.89] observational only, rho = 0.98: effect 0.98, 95% interval [ 0.31, 1.64] observational only, rho = 1.0: effect 1.00, 95% interval [ 0.90, 1.09]
def tipping_point(rhos, means, sds):
"""Smallest rho at which the lower end of the 95% interval is above zero (interpolated)."""
lo = means - 1.96 * sds
above = np.flatnonzero(lo > 0)
if len(above) == 0:
return np.nan
i = above[0]
if i == 0:
return rhos[0]
return np.interp(0, [lo[i - 1], lo[i]], [rhos[i - 1], rhos[i]])
tp_fusion = tipping_point(RHO_FINE, ex_mean, ex_sd)
tp_obs = tipping_point(RHO_OBS, obs_curve[:, 0], np.sqrt(obs_curve[:, 1]))
cover = RHO_FINE[np.abs(ex_mean - TAU_TRUE) <= 1.96 * ex_sd]
print(f"tipping point: data fusion rho* = {tp_fusion:.3f}; observational only rho* = {tp_obs:.3f}")
print(f"the data-fusion 95% interval contains the true 0.2 for rho up to {cover.max():.3f}")
fig, axes = plt.subplots(1, 2, figsize=(12, 4.3))
for ax, ylim, (title, rr, mm, ss, tp, col) in zip(axes, [(-3.0, 3.6), (-1.3, 1.6)], [
("observational record alone", RHO_OBS, obs_curve[:, 0], np.sqrt(obs_curve[:, 1]), tp_obs, PURPLE),
("trial + observational record (data fusion)", RHO_FINE, ex_mean, ex_sd, tp_fusion, BLUE)]):
ax.fill_between(rr, mm - 1.96 * ss, mm + 1.96 * ss, color=col, alpha=0.2, lw=0)
ax.plot(rr, mm, color=col, lw=2, label="closed form, mean and 95%")
ax.axhline(TAU_TRUE, color=INK, ls="--", lw=1, label="true effect 0.2")
ax.axhline(0, color=MUTED, lw=0.8)
if np.isfinite(tp):
ax.axvline(tp, color=MUTED, ls=":", lw=1.2)
ax.text(tp - 0.01, ylim[1] - 0.15, f"tipping point\n$\\rho^*$ = {tp:.2f}", ha="right", va="top", color=MUTED, fontsize=9)
ax.set_title(title)
ax.set_xlabel(r"prior correlation $\rho$ (trust in the observational regression)")
ax.set_ylim(*ylim)
axes[0].set_ylabel("average effect of the display (index points)")
for r in RHO_PYMC:
q = np.quantile(pymc_fits[r], [0.025, 0.5, 0.975])
axes[1].errorbar(r, q[1], yerr=[[q[1] - q[0]], [q[2] - q[1]]], fmt="o", color=ORANGE, ms=4, capsize=2,
label="PyMC (HSGP, NUTS)" if r == 0 else None)
axes[1].legend(loc="lower right", fontsize=8);
tipping point: data fusion rho* = 0.963; observational only rho* = 0.958 the data-fusion 95% interval contains the true 0.2 for rho up to 0.980

The left panel is what a careful analyst with only the observational record could produce. Its point estimate is the observational answer scaled down by $\rho$, and its interval is set almost entirely by the bias prior, because nothing in those data measures the bias. The conclusion "the display works" needs $\rho$ above about 0.96, a claim that the managers' choices hardly confounded anything.
The right panel adds the 50-store trial. At the left end it is the trial: wide, and centred near the true 0.2. As $\rho$ grows the observational record pulls the estimate up and the interval in, slowly at first and then fast. The lower end crosses zero at $\rho^* \approx 0.96$, and the interval still contains the true effect up to about 0.98. The PyMC fits (orange) sit on the closed form everywhere.
The two tipping points nearly coincide, which is a useful surprise. Adding the trial did not move the threshold. What it changed is the meaning of the curve below the threshold. Without the trial, every $\rho$ below 0.96 gives a centre between 0 and 1 that only the prior chose; with it, that stretch of the curve is anchored on randomised evidence. And part B worked out that the biases in this world correspond to a $\rho$ of about 0.95 to 0.97. The truth sits right at the tipping point.
The decision reads off the curve. If the head of retail media believes the observational regression could be off by more than about a third of an index point in either arm (the prior bias sd at $\rho = 0.96$ is 0.35 to 0.55 here), the evidence does not establish that the display works, however large the observational record is. A stakeholder can argue with that sentence, which is more than a single pooled number allows.
D · What the trial says about the bias
With observational data alone the confounding bias is unidentified: its posterior is its prior. With a trial it becomes something the data can estimate. Proposition 3.6 of the paper gives the posterior of $d(x, a) = \mu_o(x, a) - \mu_e(x, a)$ in closed form; its difference between arms, $D(x) = d(x, 1) - d(x, 0)$, is exactly the gap between the observational contrast and the causal one. We have the surfaces already, so we compute it from samples of the PyMC fits at two settings of the dial.
In our simulation we also know the true bias. The observational regression is $\mu_o(x, a) = 0.2a + x + E[U \mid X = x, A = a]$, while the causal surface has $E[U] = 0$ in its place, so $d(x, a) = E[U \mid x, a]$, which we compute by one-dimensional quadrature over $U$ using the propensity model.
def true_bias(x_std, a):
x_raw = x_std * X_SD + X_MEAN
def num(u):
p = special.expit(1.0 + 0.8 * x_raw + u)
return u * (p if a == 1 else 1 - p) * stats.norm.pdf(u)
def den(u):
p = special.expit(1.0 + 0.8 * x_raw + u)
return (p if a == 1 else 1 - p) * stats.norm.pdf(u)
return integrate.quad(num, -8, 8)[0] / integrate.quad(den, -8, 8)[0]
x_grid = np.linspace(-2.2, 2.2, 45)
D_true = np.array([true_bias(x, 1) - true_bias(x, 0) for x in x_grid])
print(f"true bias in the treatment contrast D(x): {D_true.min():.2f} to {D_true.max():.2f}")
for a in (0, 1):
d_a = np.array([true_bias(x, a) for x in xe])
print(f"arm {a}: true bias d(x, a) from {d_a.min():5.2f} to {d_a.max():5.2f} over the trial's stores, "
f"rms {np.sqrt(np.mean(d_a**2)):.2f}; implied rho = 1 - rms^2 / (2 eta^2) = "
f"{1 - np.mean(d_a**2) / (2 * hyp[a]['eta2']):.3f}")
PHI_G = basis(x_grid)
def bias_draws(r, n_keep=1000):
tr = nutpie.sample(compiled.with_data(rho=np.array(r)), chains=4, draws=n_keep // 4 * 2,
seed=RANDOM_SEED + 1, progress_bar=False)
b1 = az.extract(tr, var_names=["b1"]).values # (arm, basis, sample)
b2 = az.extract(tr, var_names=["b2"]).values
out = 0.0
for a, sgn in ((1, 1), (0, -1)):
w1, w2 = b1[a] * SQRT_PSD[a][:, None], b2[a] * SQRT_PSD[a][:, None]
u1, u2 = PHI_G @ w1, PHI_G @ w2
d = (r - 1) * u1 + np.sqrt(1 - r**2) * u2 # mu_o - mu_e
out = out + sgn * d
return out # (grid, sample)
fig, ax = plt.subplots(figsize=(7.5, 4))
for r, col in ((0.95, ORANGE), (0.5, BLUE)):
D = bias_draws(r)
lo, mid, hi = np.quantile(D, [0.05, 0.5, 0.95], axis=1)
ax.fill_between(x_grid, lo, hi, color=col, alpha=0.2, lw=0)
ax.plot(x_grid, mid, color=col, lw=2, label=f"posterior, $\\rho$ = {r} (median, 90%)")
prior_sd = np.sqrt(sum(2 * (1 - r) * hyp[a]["eta2"] for a in (0, 1)))
print(f"rho = {r}: prior sd of D(x) {prior_sd:.2f}; posterior median of D at x = 0 "
f"{np.interp(0, x_grid, mid):.2f}, 90% interval [{np.interp(0, x_grid, lo):.2f}, "
f"{np.interp(0, x_grid, hi):.2f}]")
ax.plot(x_grid, D_true, color=INK, ls="--", lw=1.5, label="true bias")
ax.axhline(0, color=MUTED, lw=0.8)
ax.set_xlabel("last year's sales index $x$ (standardised)")
ax.set_ylabel(r"bias in the treatment contrast $D(x)$")
ax.legend(fontsize=9);
true bias in the treatment contrast D(x): 0.83 to 0.90
arm 0: true bias d(x, a) from -0.77 to -0.32 over the trial's stores, rms 0.57; implied rho = 1 - rms^2 / (2 eta^2) = 0.957
arm 1: true bias d(x, a) from 0.12 to 0.51 over the trial's stores, rms 0.31; implied rho = 1 - rms^2 / (2 eta^2) = 0.967
rho = 0.95: prior sd of D(x) 0.72; posterior median of D at x = 0 0.40, 90% interval [-0.36, 1.13]
rho = 0.5: prior sd of D(x) 2.28; posterior median of D at x = 0 0.43, 90% interval [-0.62, 1.51]

The true bias in the treatment contrast is between about 0.83 and 0.90 index points across the stores: the observational regression overstates the display's effect by four times the effect itself. Arm by arm, the bias is negative without the display (managers held the display back from stores they expected to struggle) and positive with it. Their root-mean-square sizes give the $\rho$ of about 0.95 to 0.97 that part B promised.
The posteriors are the setback of this example. Both bands contain the truth almost everywhere, and at $\rho = 0.95$ the band sits above zero for stores a little below average, so the data do see a bias of the right sign. Neither posterior is sharp, though. At $\rho = 0.5$ the prior allows a bias of about $\pm 3.7$ (90%), and 50 trial stores cut that to a band 2 to 4 points wide whose median wanders between 0.15 and 1.4. At $\rho = 0.95$ the prior is tighter, and the median sits at a quarter to three quarters of the true value. A trial of 24 and 26 stores pins down each arm's causal surface only loosely, and the bias inherits that uncertainty.
This is still the practical payoff of data fusion over a sensitivity analysis of one study. The observational-only analysis in part C had to assume a bias scale. With the trial in hand the bias has a posterior, and its width is set by the size of the trial, which a measurement team can buy more of. The third exercise at the end shows what a bigger trial does.
E · A bigger observational study cannot overrule the trial
A natural worry with any borrowing scheme is that a huge observational study will eventually drown the trial, whatever we say about trust. Causal-ICM has two guarantees against that. The shift in the posterior mean caused by the observational data stays of order $\rho\sqrt{V_{e\mid D_e}}$ however large $n_o$ grows (Proposition 3.4), and the posterior variance can fall at most by a factor $1-\rho^2$ below the trial-only variance (Proposition 3.5, from Dimitriou et al. 2026):
$$(1-\rho^2)\, V_{e\mid D_e}(x) \;\le\; V_{e\mid D}(x) \;\le\; V_{e\mid D_e}(x).$$
To see it we draw fresh observational records of increasing size from the same world, keep the same 50-store trial, and compute the posterior of the average effect. On the HSGP basis the model is a conjugate linear-Gaussian regression in 60 coefficients per arm, so even 200,000 stores take a fraction of a second: the posterior precision is $I + G^\top G/\sigma^2$, where $G$ stacks the trial rows $[\Phi_e S, 0]$ and the observational rows $[\rho\,\Phi_o S, \sqrt{1-\rho^2}\,\Phi_o S]$.
def conjugate_fusion(rho, xo_, ao_, yo_):
"""Posterior mean and variance of the trial-population effect on the HSGP basis."""
phi_o = basis(xo_)
mean, var = PRIOR_MEAN[1] - PRIOR_MEAN[0], 0.0
c_avg = PHI_E.mean(axis=0)
for a, sgn in ((1, 1), (0, -1)):
S = SQRT_PSD[a]
Ge = np.hstack([PHI_E[Ae == a] * S, np.zeros(((Ae == a).sum(), M_BASIS))])
Go = np.hstack([rho * phi_o[ao_ == a] * S, np.sqrt(1 - rho**2) * phi_o[ao_ == a] * S])
G = np.vstack([Ge, Go])
y = np.r_[Ye[Ae == a], yo_[ao_ == a]] - PRIOR_MEAN[a]
prec = np.eye(2 * M_BASIS) + G.T @ G / NOISE_SD[a] ** 2
C = np.linalg.inv(prec)
mu = C @ G.T @ y / NOISE_SD[a] ** 2
c = np.r_[c_avg * S, np.zeros(M_BASIS)]
mean += sgn * c @ mu
var += c @ C @ c
return mean, var
# sanity check against the closed form on the actual data
for r in (0.5, 0.95):
print(f"rho = {r}: HSGP conjugate {conjugate_fusion(r, xo, Ao, Yo)[0]:.3f} vs exact {exact_fusion(r)[0]:.3f}")
N_GRID = [100, 300, 1000, 3000, 10_000, 30_000, 100_000, 200_000]
RHO_SWEEP = [0.5, 0.8, 0.95, 1.0]
big_x, big_a, big_y = simulate_observational(max(N_GRID), np.random.default_rng(RANDOM_SEED + 2))
big_x = (big_x - X_MEAN) / X_SD
big_y = big_y - Y_CENTRE
sweep = {r: np.array([conjugate_fusion(r, big_x[:n], big_a[:n], big_y[:n]) for n in N_GRID]) for r in RHO_SWEEP}
trial_only_mean, trial_only_var = conjugate_fusion(0.0, xo, Ao, Yo)
print(f"trial only: mean {trial_only_mean:.2f}, sd {np.sqrt(trial_only_var):.3f}")
for r in RHO_SWEEP:
print(f"rho = {r:4}: sd at n_o = 200,000 is {np.sqrt(sweep[r][-1, 1]):.3f} "
f"(floor sqrt(1 - rho^2) x trial sd = {np.sqrt((1 - r**2) * trial_only_var):.3f}); "
f"mean {sweep[r][-1, 0]:.2f}")
rho = 0.5: HSGP conjugate 0.278 vs exact 0.278
rho = 0.95: HSGP conjugate 0.570 vs exact 0.570
trial only: mean 0.24, sd 0.429 rho = 0.5: sd at n_o = 200,000 is 0.424 (floor sqrt(1 - rho^2) x trial sd = 0.371); mean 0.28 rho = 0.8: sd at n_o = 200,000 is 0.404 (floor sqrt(1 - rho^2) x trial sd = 0.257); mean 0.37 rho = 0.95: sd at n_o = 200,000 is 0.339 (floor sqrt(1 - rho^2) x trial sd = 0.134); mean 0.59 rho = 1.0: sd at n_o = 200,000 is 0.009 (floor sqrt(1 - rho^2) x trial sd = 0.000); mean 1.04
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
cols = dict(zip(RHO_SWEEP, [BLUE, AQUA, ORANGE, RED]))
for r in RHO_SWEEP:
sd = np.sqrt(sweep[r][:, 1])
axes[0].plot(N_GRID, sd, "o-", color=cols[r], ms=4, label=f"$\\rho$ = {r}")
if r < 1:
axes[0].axhline(np.sqrt((1 - r**2) * trial_only_var), color=cols[r], ls=":", lw=1)
axes[1].plot(N_GRID, sweep[r][:, 0], "o-", color=cols[r], ms=4, label=f"$\\rho$ = {r}")
axes[0].axhline(np.sqrt(trial_only_var), color=INK, lw=1, ls="--", label="trial only")
axes[0].set_xscale("log")
axes[0].set_yscale("log")
axes[0].set_xlabel("stores in the observational record $n_o$")
axes[0].set_ylabel("posterior sd of the average effect")
axes[0].set_title("dotted: the floor $\\sqrt{1-\\rho^2}$ x trial-only sd")
axes[1].axhline(TAU_TRUE, color=INK, ls="--", lw=1)
axes[1].axhline(trial_only_mean, color=MUTED, lw=1)
axes[1].set_xscale("log")
axes[1].set_xlabel("stores in the observational record $n_o$")
axes[1].set_ylabel("posterior mean of the average effect")
axes[1].legend(fontsize=9);

Full pooling ($\rho = 1$) behaves like any consistent estimator of the wrong thing: its sd falls like $1/\sqrt{n_o}$, to about 0.01 at 200,000 stores, while its mean settles near 1.0, five times the truth. Every $\rho < 1$ flattens out instead, and well above its floor. At $\rho = 0.95$ the sd stops at about 0.34 against a floor of 0.13; at $\rho = 0.5$ it barely moves from the trial's 0.43. The paper states the floor pointwise, and for the average effect it holds here with room to spare. The means level off as well, at about 0.28 for $\rho = 0.5$ and 0.59 for $\rho = 0.95$, so the observational shift is bounded as Proposition 3.4 says. Bounded is not the same as harmless: at $\rho = 0.95$ the bounded shift still moves the answer by 0.35 index points, almost twice the true effect.
For a measurement team this is the property that makes the method usable in a meeting. Nobody can win the argument by bringing a bigger observational dataset; they have to argue about $\rho$, which is an argument about confounding.
F · Letting the trial vote on $\rho$
The paper treats $\rho$ as a sensitivity parameter and reports the whole curve. Part D suggests something more: with a trial, the bias is partly identified, so the data carry some information about $\rho$ itself. In PyMC that is one line, a prior on $\rho$ instead of a fixed value. We use a uniform prior on $[0, 1]$ and keep everything else as before. This goes beyond the paper, and the result depends on the GP hyperparameters, which we still fix from the 50 trial stores.
with pm.Model(coords={"arm": ["no display", "display"], "basis": np.arange(M_BASIS)}) as learn_rho:
rho = pm.Uniform("rho", 0.0, 1.0)
b1 = pm.Normal("b1", 0, 1, dims=("arm", "basis"))
b2 = pm.Normal("b2", 0, 1, dims=("arm", "basis"))
w1, w2 = b1 * SQRT_PSD, b2 * SQRT_PSD
u1_e = (PHI_E * w1[Ae]).sum(axis=1)
u1_o = (PHI_O * w1[Ao]).sum(axis=1)
u2_o = (PHI_O * w2[Ao]).sum(axis=1)
pm.Normal("y_e", PRIOR_MEAN[Ae] + u1_e, NOISE_SD[Ae], observed=Ye)
pm.Normal("y_o", PRIOR_MEAN[Ao] + rho * u1_o + pt.sqrt(1 - rho**2) * u2_o, NOISE_SD[Ao], observed=Yo)
pm.Deterministic("ate", PRIOR_MEAN[1] - PRIOR_MEAN[0] + (PHI_E.mean(axis=0) * (w1[1] - w1[0])).sum())
t0 = time.time()
idata_rho = pm.sample(tune=2000, draws=3000, random_seed=RANDOM_SEED, progressbar=False)
print(f"sampled in {time.time() - t0:.0f} s with nutpie, "
f"{int(idata_rho.sample_stats['diverging'].sum())} divergences, "
f"{idata_rho.posterior.attrs.get('tuning_steps', '?')} tuning steps")
print(az.summary(idata_rho, var_names=["rho", "ate"], ci_kind="eti", ci_prob=0.95, round_to=2))
sampled in 52 s with nutpie, 0 divergences, 2000 tuning steps
mean sd eti95_lb eti95_ub ess_bulk ess_tail r_hat mcse_mean \
rho 0.75 0.21 0.17 0.98 267.61 396.11 1.01 0.01
ate 0.39 0.41 -0.43 1.15 1505.09 2002.74 1.00 0.01
mcse_sd
rho 0.01
ate 0.01 rho_draws = idata_rho.posterior["rho"].values.ravel()
ate_draws = idata_rho.posterior["ate"].values.ravel()
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
axes[0].hist(rho_draws, bins=40, range=(0, 1), density=True, color=BLUE, alpha=0.7)
axes[0].axhline(1, color=MUTED, ls="--", lw=1, label="uniform prior")
axes[0].set_xlabel(r"$\rho$")
axes[0].set_title(r"posterior of $\rho$")
axes[0].legend(fontsize=9)
bins = np.linspace(-1.2, 1.8, 60)
axes[1].hist(ate_draws, bins=bins, density=True, color=BLUE, alpha=0.6, label=r"$\rho$ learned")
axes[1].hist(pymc_fits[0.0], bins=bins, density=True, histtype="step", color=INK, lw=1.5, label="trial only")
axes[1].hist(pymc_fits[1.0], bins=bins, density=True, histtype="step", color=RED, lw=1.5, label="full pooling")
axes[1].axvline(TAU_TRUE, color=INK, ls="--", lw=1)
axes[1].set_xlabel("average effect of the display")
axes[1].set_title("posterior of the effect")
axes[1].legend(fontsize=9);
print(f"P(rho > 0.95 | data) = {(rho_draws > 0.95).mean():.2f}; "
f"P(effect > 0 | data): learned rho {(ate_draws > 0).mean():.2f}, "
f"trial only {(pymc_fits[0.0] > 0).mean():.2f}, full pooling {(pymc_fits[1.0] > 0).mean():.2f}")
P(rho > 0.95 | data) = 0.11; P(effect > 0 | data): learned rho 0.83, trial only 0.70, full pooling 1.00

The posterior of $\rho$ climbs towards 1 and then falls away in the last few hundredths. It peaks around 0.9, puts most of its mass between 0.6 and 0.99, and gives $\rho > 0.95$ a probability of only about 0.11. The data rule out the one setting they can rule out, full pooling, because a bias of zero cannot reconcile the trial with the observational record. Below that they cannot do much. Biases of 0.3 to 0.6 index points per arm fit a wide range of $\rho$ when the signal variance is this large, and a 50-store trial cannot tell 0.85 from 0.95. The sampler found this harder than the fixed-$\rho$ fits: $\rho$ has a bulk ESS of a couple of hundred, enough for the picture but not for its tails.
The effect's posterior is the useful summary. Averaging over what the data say about $\rho$, it is centred around 0.4 with a 95% interval from about $-0.4$ to $1.2$, much closer to the trial than to full pooling, and it contains the truth. The probability that the display helps at all is about 0.83, against 0.70 from the trial alone and 1.00 from full pooling.
In a world where the right answer sits on the tipping point, the model has done the honest thing: it borrows a little and refuses to be certain. The caveat is the one from part B. How strongly the data speak about $\rho$ depends on the GP's signal variance, which sets the bias scale for a given $\rho$, and we fixed it from 50 stores. A fuller model would learn the hyperparameters from the trial jointly, and then the prior on $\rho$ deserves the same care as any other prior on a quantity that one study alone cannot identify. For the rollout decision, show this posterior next to the sensitivity curve of part C, never instead of it.
Summary
- Pooling a small trial with a large confounded study gives a confident wrong answer. The 5,000-store observational record, adjusted for the measured covariate, says the display is worth about 1.0 index points with an sd of 0.04; the truth is 0.2. Full pooling ($\rho = 1$) reproduces that answer. Limit: the bias here is large by construction (the paper's design).
- Causal-ICM turns trust into a single, explainable dial. With the trial in the model, the effect moves smoothly from the trial-only 0.24 (95% interval about $-0.6$ to $1.1$) at $\rho = 0$ to full pooling at $\rho = 1$, with most of the movement above 0.9. The interval leaves zero at $\rho^* \approx 0.96$, almost where the observational record alone puts it; the trial anchors the curve below that point on randomised evidence. The true biases correspond to $\rho$ of about 0.95 to 0.97, right on the threshold. The prior bias sd $\eta\sqrt{2(1-\rho)}$ translates $\rho$ into index points. Limit: hyperparameters are fixed from 24 to 26 trial stores per arm.
- The PyMC model reproduces the paper's closed form. An HSGP basis with 30 functions per
latent GP matches the exact kernel to a few parts in a thousand, and nutpie refits along $\rho$ (one
compilation,
with_data) agree with the closed form to about 0.01 with no divergences. - The trial makes the confounding bias learnable, loosely. At both $\rho = 0.5$ and $\rho = 0.95$ the posterior of the bias in the treatment contrast contains the true 0.83 to 0.90, but its median wanders from a quarter of the truth to more than it. Limit: the width is set by the size of the trial.
- A bigger observational study cannot overrule the trial. For any $\rho < 1$ the posterior sd of the effect stops falling well above its floor of $\sqrt{1-\rho^2}$ times the trial's (0.34 at $\rho = 0.95$ with 200,000 stores, against a floor of 0.13) and the shift in the mean levels off, while full pooling converges to the wrong value with an sd of 0.01.
- With a prior on $\rho$ the data rule out full pooling and little else. The posterior of $\rho$ peaks near 0.9 and drops in the last few hundredths; the effect's posterior (about 0.4, probability 0.83 that the display helps) stays close to the trial's and contains the truth. Limit: this goes beyond the paper, and it rests on the fixed signal variance.
Try it yourself
- A world where borrowing pays. Set the confounder's effect on treatment to zero in
simulate_observational(replace1.0 * uby0.0 * u) and rerun parts C and F. Where is the tipping point now, how much narrower than the trial's is the interval at $\rho = 0.95$, and where does the posterior of $\rho$ go? - Learn the hyperparameters. Give the lengthscale and signal sd of each arm priors (for
example
pm.InverseGammaandpm.HalfNormal) and learn them from the trial rows only, using the cut-feedback idea of E130 so that the observational rows cannot tune them. How do the sensitivity curve and the posterior of $\rho$ change? - Buy a bigger trial. Set
N_E = 500and rerun. How much do the bias posteriors of part D tighten, does the tipping point move, and does the posterior of $\rho$ in part F start to separate 0.85 from 0.95? This is the calculation behind the question a measurement team actually faces: is another test worth more than another year of observational data?
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 206 s