Techniqueadvanced
Rosenbaum sensitivity analysis
Also called Rosenbaum bounds.
Asks how strong an unmeasured confounder, measured by a bound Gamma on the odds of treatment in matched pairs, would have to be to explain away a finding.
Rosenbaum sensitivity analysis asks how much hidden bias would be needed to change the conclusion of a matched observational study. Matching on measured covariates, as in propensity score matching, removes only measured differences, and the test of no effect assumes ignorability: within a matched pair, each unit was equally likely to be the treated one. The analysis replaces this assumption by a weaker one. Two units in the same pair may differ in their odds of treatment by a factor of at most , because of a covariate nobody measured. For each it computes the smallest and the largest p-value that any such bias could produce. The value of at which the largest p-value crosses the level is the sensitivity value: a measure of how strong the hidden bias would have to be to explain the finding away.
In plain words
In a matched study, each smoker is paired with a nonsmoker who is alike in age, job and so on. If the pairs were truly alike, a coin toss decided which one of each pair smoked, and the usual test applies. But some unmeasured trait might make one person of the pair more likely to smoke.
So we ask: suppose that trait could make one person up to times more likely (in odds) to smoke than the other. In the worst case, how large could the p-value be? We try until the worst case is no longer significant. If a hidden trait would need to multiply the odds of smoking by 5 to explain the result, the result is hard to explain away. If 1.1 is enough, it is fragile.
When it applies
- The data are matched pairs (or matched sets) from an observational study, with one treated and one control unit per pair, matched on the measured covariates.
- The test statistic is a sum over pairs of a nonnegative score times the indicator that the treated unit did better: the signed-rank statistic, the sign test, McNemar's test for binary outcomes, and others of the same form.
- The null hypothesis is Fisher's sharp null of no effect for any unit. Then the two responses of each pair are fixed numbers, and only the question of which unit was treated is random, as in a permutation test.
- The question is how much unmeasured confounding the conclusion can bear. The analysis does not estimate the hidden bias; the data have no information about it.
The template
The model. Let be the probability that unit is treated, and suppose , with an unmeasured and . Two units with the same measured then have odds of treatment whose ratio is between and . In a pair with exactly one treated unit, the chance that it is unit is
and with this lies in . The pairs are independent. is a randomized experiment within pairs.
The bound. Under the sharp null, the treated-minus-control difference of pair is a fixed number, so is fixed and only its sign is random. Take a statistic with fixed scores that depend only on the . Let and be the same sum with independent signs, positive with probability and . Then for every assignment law allowed by the model and every ,
Proof. In pair the sign is positive with some probability , independently over pairs. Take independent uniforms and set the sign of pair positive when . Then for each , and is nondecreasing in each indicator because . So on every outcome of the uniforms, which gives the two inequalities. Both bounds are attained: by the law in which, in every pair, the unit with the larger response has the higher odds (for ) or the lower odds (for ) by the factor .
The tests check both claims, by enumerating every vertex of and every assignment for small designs in exact arithmetic.
ROSENBAUM-BOUNDS(D[1..S], Γ) ▷ pair differences, treated minus control- 1
drop the pairs with D_s = 0; let n be the number left - 2
q ← SCORES(|D_1|, ..., |D_n|) ▷ hole: ranks, all ones, or another nonnegative score - 3
t ← Σ_{s : D_s > 0} q_s ▷ the observed statistic - 4
p⁺ ← Γ / (1 + Γ); p⁻ ← 1 / (1 + Γ) - 5
law⁺ ← law of Σ_s B_s q_s, B_s ~ Bernoulli(p⁺) independent ▷ a subset-sum dynamic program - 6
law⁻ ← the same with p⁻ - 7
return (Pr_{law⁻}[≥ t], Pr_{law⁺}[≥ t]) ▷ bounds on the one-sided p-value SENSITIVITY-VALUE(D, α)- 8
find by bisection the Γ ≥ 1 at which the upper bound of L7 equals α
The holes are SCORES, the level , and the grid of values to report. Line L5 is the dynamic program of the signed-rank test with weights and in place of : for each score, , scanning downward. With ranks doubled to keep midranks integral, it takes operations. For large the normal approximation uses the mean and the variance . The upper bound is nondecreasing in , by the same coupling, so the bisection in line L8 is valid. For a two-sided test, double the one-sided bound in the direction of the observed effect.
Classic examples
- Smoking and lung cancer, binary outcome. Hammond (1964) matched 36,975 heavy smokers to nonsmokers. In 122 pairs exactly one man died of lung cancer, and in 110 of them it was the smoker. With all scores 1, is McNemar's count of 110 out of 122 discordant pairs, and the bounds are binomial tails: . At this is below ; at the exact upper bound is 0.0232, and at it is 0.0969. The exact sensitivity value at is about 5.47. An unmeasured trait would have to raise the odds of smoking more than five-fold, and nearly decide who dies, to explain the result. (Published analyses quote 0.03 at and 0.10 at , which match the normal approximation with a continuity correction.)
- Signed ranks, continuous outcome. Take the ten pair differences of the signed-rank test example: . The zero is dropped, and . At both bounds are , the exact one-sided Wilcoxon p-value. At the p-value can be anywhere in , and at in . The sensitivity value at is about 1.11: a small hidden bias could explain this finding.
- The sign test. With all scores 1 on continuous differences, the bound is a binomial tail, as for the sign test and the binomial test. On the ten differences above, 6 of 9 nonzero signs are positive, and the bound at is already , because the sign test ignores that the three negative differences are small. Different scores give different sensitivity values for the same data, so choose the score before the analysis.
- Cornfield's argument. Cornfield and coauthors (1959) argued that a hidden cause that explains a risk ratio of 9 for smoking and lung cancer must be at least 9 times more common in smokers. This was the first sensitivity analysis, and Rosenbaum's model makes it a statement about p-values in a matched design.
Variations
- Amplification. Rosenbaum and Silber (2009) write as a pair : an unmeasured that raises the odds of treatment by and the odds of a positive pair difference by has the same worst case as . For example, corresponds to . This answers the objection that the worst case assumes predicts the outcome perfectly.
- Matched sets and strata. With one treated unit and several controls per set, or several treated units, the bounds are no longer two simple Bernoulli laws. Rosenbaum's book gives bounds and a normal approximation that uses the extreme allocation in each set.
- Point estimates and intervals. Inverting the test for each shift in gives, for each , an interval of Hodges-Lehmann estimates and a confidence interval that widens as grows.
- Explicit covariate models. Rosenbaum and Rubin (1983) model a binary unobserved covariate with given effects on treatment and outcome, and report the estimate for each choice. Bounds for weighting estimators, such as the marginal sensitivity model for inverse probability weighting, use the same idea of a bounded odds ratio.
Pitfalls
- Reading as a probability. is a bound on an odds ratio within pairs, not the chance that a confounder exists. A sensitivity value of 5.47 says what the bias would need to be, not how likely it is.
- Reading the upper bound as the p-value. The true p-value is somewhere between the two bounds. The upper bound is attained only if the hidden trait both shifts the odds of treatment by the full factor in every pair and lines up perfectly with which unit had the larger response.
- A large study is not a robust study. Sample size moves the p-value at , but the sensitivity value is limited by the size and the consistency of the effect. Two studies with the same tiny p-value can have very different sensitivity values.
- Only the sharp null. The bounds are for the hypothesis of no effect for every unit. They say nothing directly about the size of the effect without the inversion described above.
- The normal approximation. For the ten pairs of the example, at the exact upper bound is 0.182 and the normal approximation without a continuity correction gives 0.157; at the numbers are 0.331 and 0.280. The approximation can err in either direction; compute the exact law when is small. These are measured values.
- Bias from measured covariates. The model assumes that matching removed all measured differences. Pairs with poor matches on add bias that the analysis attributes to .
- Choosing the score after seeing the data. Trying the sign test, the signed-rank test and others, and reporting the one with the largest sensitivity value, overstates robustness.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rosenbaum-sensitivity-analysis/. The authors are listed in prov/4KS2ZT.jsonl.
"""Rosenbaum bounds for matched pairs.
In pair s the treated-minus-control difference is d[s]. Under the sharp null
of no effect and a hidden bias of at most gamma (the odds of treatment of the
two units in a pair differ by a factor of at most gamma), the chance that the
unit with the larger response is the treated one lies in
[1 / (1 + gamma), gamma / (1 + gamma)]. A statistic of the form sum q_s * 1[d_s > 0]
with q_s >= 0 is then bounded in law by the same sum with independent Bernoulli
signs at the two ends. Every bound is a one-sided p-value for the alternative
that treatment raises the response. With int or Fraction inputs the results are exact.
"""
import math
from collections.abc import Callable, Sequence
from fractions import Fraction
def doubled_midranks(values: Sequence) -> list[int]:
"""2 x (midrank of each value), in input order; doubling keeps tied midranks integral."""
n = len(values)
order = sorted(range(n), key=lambda i: values[i])
r2 = [0] * n
i = 0
while i < n:
j = i
while j + 1 < n and values[order[j + 1]] == values[order[i]]:
j += 1
for k in range(i, j + 1):
r2[order[k]] = i + j + 2
i = j + 1
return r2
def bernoulli_sum_law(q: Sequence[int], p) -> list:
"""law[v] = Pr[sum_s B_s q_s = v] for independent B_s ~ Bernoulli(p). Cost: Theta(len(q) * sum(q))."""
total = sum(q)
law = [0] * (total + 1)
law[0] = 1
top = 0
for qs in q:
top += qs
for v in range(top, -1, -1):
stay = law[v] * (1 - p)
law[v] = stay + (law[v - qs] * p if v >= qs else 0)
return law
def signed_rank_bounds(d: Sequence, gamma=1) -> tuple:
"""Bounds on the one-sided signed-rank p-value under hidden bias at most gamma.
Returns (t, p_low, p_high), where t is the signed-rank statistic W+ (the sum of
the ranks of |d_s| over the pairs with d_s > 0, midranks for ties, zero
differences dropped). For every assignment law allowed by the model,
p_low <= Pr[W+ >= t] <= p_high. gamma = 1 gives the exact Wilcoxon p-value twice.
Cost: Theta(n^3) arithmetic operations for n nonzero pairs.
"""
if gamma < 1:
raise ValueError("gamma must be at least 1")
kept = [v for v in d if v != 0] # @line L1
q2 = doubled_midranks([abs(v) for v in kept]) # @line L2
t2 = sum(r for r, v in zip(q2, kept) if v > 0) # @line L3
p_hi = Fraction(gamma) / (1 + Fraction(gamma)) if not isinstance(gamma, float) else gamma / (1 + gamma) # @line L4
p_lo = 1 - p_hi
up = bernoulli_sum_law(q2, p_hi) # @line L5
lo = bernoulli_sum_law(q2, p_lo) # @line L6
return Fraction(t2, 2), sum(lo[t2:]), sum(up[t2:]) # @line L7
def sign_test_bounds(k: int, n: int, gamma=1) -> tuple:
"""Bounds on Pr[K >= k] for binary outcomes (McNemar): n discordant pairs, k of them with the event in the treated unit.
Returns (p_low, p_high) = upper tails of Binomial(n, 1/(1+gamma)) and Binomial(n, gamma/(1+gamma)).
"""
if gamma < 1 or not 0 <= k <= n:
raise ValueError("need gamma >= 1 and 0 <= k <= n")
p = Fraction(gamma) / (1 + Fraction(gamma)) if not isinstance(gamma, float) else gamma / (1 + gamma)
def tail(pr):
return sum(math.comb(n, j) * pr**j * (1 - pr) ** (n - j) for j in range(k, n + 1))
return tail(1 - p), tail(p)
def normal_upper_bound(d: Sequence, gamma: float = 1.0) -> float:
"""Normal approximation to p_high: the bounding sum has mean p sum q and variance p (1 - p) sum q^2."""
kept = [v for v in d if v != 0]
if not kept:
return 1.0
q = [r / 2 for r in doubled_midranks([abs(v) for v in kept])]
t = sum(r for r, v in zip(q, kept) if v > 0)
p = gamma / (1 + gamma)
mean = p * sum(q)
sd = math.sqrt(p * (1 - p) * sum(r * r for r in q))
z = (t - mean) / sd
return 0.5 * math.erfc(z / math.sqrt(2.0))
def sensitivity_value(upper: Callable[[float], float], alpha: float = 0.05, hi: float = 1000.0, tol: float = 1e-6) -> float:
"""The Gamma at which the upper p-value bound reaches alpha, found by bisection.
upper(gamma) must be nondecreasing in gamma. Returns 1.0 if upper(1) > alpha
(not significant even without bias) and hi if upper(hi) <= alpha.
"""
if upper(1.0) > alpha: # @line L8
return 1.0
if upper(hi) <= alpha:
return hi
a, b = 1.0, hi
while b - a > tol * a:
mid = (a + b) / 2
if upper(mid) <= alpha:
a = mid
else:
b = mid
return (a + b) / 2
test_rosenbaum_sensitivity_analysis.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rosenbaum-sensitivity-analysis/. The authors are listed in prov/4KS2ZT.jsonl.
import itertools
import math
import random
from fractions import Fraction as Fr
import pytest
from rosenbaum_sensitivity_analysis import (
bernoulli_sum_law,
doubled_midranks,
normal_upper_bound,
sensitivity_value,
sign_test_bounds,
signed_rank_bounds,
)
# The example of the page (the same differences as the signed-rank test page).
EX = [Fr(18, 10), Fr(-6, 10), Fr(31, 10), Fr(24, 10), Fr(-13, 10), Fr(9, 10), Fr(22, 10), 0, Fr(15, 10), Fr(-4, 10)]
def wplus(d):
kept = [v for v in d if v != 0]
r2 = doubled_midranks([abs(v) for v in kept])
return Fr(sum(r for r, v in zip(r2, kept) if v > 0), 2)
def test_worked_example():
t, lo, hi = signed_rank_bounds(EX, 1)
assert t == 38 and lo == hi == Fr(19, 512)
t, lo, hi = signed_rank_bounds(EX, Fr(3, 2))
assert lo == Fr(19712, 1953125) and hi == Fr(201933, 1953125)
t, lo, hi = signed_rank_bounds(EX, 2)
assert lo == Fr(67, 19683) and hi == Fr(3584, 19683)
g = sensitivity_value(lambda x: float(signed_rank_bounds(EX, Fr(x))[2]), 0.05)
assert abs(g - 1.1133) < 1e-3
g10 = sensitivity_value(lambda x: float(signed_rank_bounds(EX, Fr(x))[2]), 0.10)
assert abs(g10 - 1.4775) < 1e-3
# the sign test on the same differences: 6 of 9 signs positive
assert sign_test_bounds(6, 9, 1) == (Fr(130, 512), Fr(130, 512))
# exercise 2 of the page
assert sign_test_bounds(9, 10, 1)[1] == Fr(11, 1024)
assert sign_test_bounds(9, 10, 2)[1] == Fr(6144, 59049)
def test_hammond_binary_pairs():
"""110 of 122 discordant pairs had the lung cancer death in the smoker."""
lo, hi = sign_test_bounds(110, 122, 1)
assert lo == hi and hi < Fr(1, 10**20)
_, hi5 = sign_test_bounds(110, 122, 5)
_, hi6 = sign_test_bounds(110, 122, 6)
assert 0.023 < hi5 < 0.0235 and 0.096 < hi6 < 0.098
g = sensitivity_value(lambda x: float(sign_test_bounds(110, 122, Fr(x))[1]), 0.05)
assert 5.4 < g < 5.5
def test_gamma_one_is_the_exact_signed_rank_p_value():
rng = random.Random(1)
for _ in range(300):
n = rng.randint(0, 9)
d = [rng.randint(-4, 4) for _ in range(n)]
t, lo, hi = signed_rank_bounds(d, 1)
kept = [v for v in d if v != 0]
a = [abs(v) for v in kept]
count = 0
for signs in itertools.product((1, -1), repeat=len(kept)):
if wplus([s * v for s, v in zip(signs, a)]) >= t:
count += 1
assert lo == hi == Fr(count, 2 ** len(kept))
def exact_tail(r1, r2, pi, t_obs):
"""Pr[W+ >= t_obs] when unit 1 of pair s is treated with probability pi[s], under the sharp null."""
total = Fr(0)
for z in itertools.product((0, 1), repeat=len(pi)):
pr = Fr(1)
for zs, p in zip(z, pi):
pr *= p if zs else 1 - p
d = [(a - b) if zs else (b - a) for zs, a, b in zip(z, r1, r2)]
if wplus(d) >= t_obs:
total += pr
return total
def test_bounds_against_enumeration_of_worst_case_assignments():
rng = random.Random(2026)
for _ in range(80):
n = rng.randint(1, 6)
r1 = [rng.randint(0, 5) for _ in range(n)]
r2 = [rng.randint(0, 5) for _ in range(n)]
z_obs = [rng.randint(0, 1) for _ in range(n)]
d_obs = [(a - b) if z else (b - a) for z, a, b in zip(z_obs, r1, r2)]
gamma = Fr(rng.randint(2, 8), 2)
lo_p, hi_p = 1 / (1 + gamma), gamma / (1 + gamma)
t, lo, hi = signed_rank_bounds(d_obs, gamma)
tails = [exact_tail(r1, r2, pi, t) for pi in itertools.product((lo_p, hi_p), repeat=n)]
assert max(tails) == hi and min(tails) == lo
# an interior law also stays inside the bounds
pi = [lo_p + (hi_p - lo_p) * Fr(rng.randint(0, 10), 10) for _ in range(n)]
assert lo <= exact_tail(r1, r2, pi, t) <= hi
def test_sign_test_bounds_against_enumeration():
rng = random.Random(4)
for _ in range(100):
n = rng.randint(1, 7)
k = rng.randint(0, n)
gamma = Fr(rng.randint(2, 9), 2)
lo_p, hi_p = 1 / (1 + gamma), gamma / (1 + gamma)
tails = []
for pi in itertools.product((lo_p, hi_p), repeat=n):
tail = Fr(0)
for z in itertools.product((0, 1), repeat=n):
if sum(z) >= k:
pr = Fr(1)
for zs, p in zip(z, pi):
pr *= p if zs else 1 - p
tail += pr
tails.append(tail)
assert (min(tails), max(tails)) == sign_test_bounds(k, n, gamma)
def test_monotone_in_gamma():
rng = random.Random(9)
for _ in range(100):
d = [rng.randint(-5, 9) for _ in range(rng.randint(1, 12))]
prev_lo, prev_hi = None, None
for g in (1, Fr(5, 4), Fr(3, 2), 2, 3, 5):
_, lo, hi = signed_rank_bounds(d, g)
assert lo <= hi
if prev_hi is not None:
assert hi >= prev_hi and lo <= prev_lo
prev_lo, prev_hi = lo, hi
def test_law_moments_match_normal_approximation_inputs():
rng = random.Random(12)
for _ in range(100):
q = [rng.randint(1, 12) for _ in range(rng.randint(1, 10))]
p = Fr(rng.randint(1, 9), 10)
law = bernoulli_sum_law(q, p)
assert sum(law) == 1
mean = sum(v * w for v, w in enumerate(law))
var = sum(v * v * w for v, w in enumerate(law)) - mean * mean
assert mean == p * sum(q) and var == p * (1 - p) * sum(x * x for x in q)
def test_normal_approximation_is_close_for_moderate_n():
rng = random.Random(1)
d = [round(rng.gauss(0.3, 1), 1) for _ in range(40)]
for g in (1.0, 1.5, 2.0):
exact = float(signed_rank_bounds([Fr(str(v)) for v in d], Fr(g))[2])
assert abs(normal_upper_bound(d, g) - exact) < 0.03
def test_float_gamma_and_errors():
_, lo, hi = signed_rank_bounds([float(v) for v in EX], 2.0)
assert math.isclose(hi, 3584 / 19683, rel_tol=1e-12)
assert math.isclose(lo, 67 / 19683, rel_tol=1e-12)
with pytest.raises(ValueError):
signed_rank_bounds(EX, Fr(1, 2))
with pytest.raises(ValueError):
sign_test_bounds(5, 4, 2)
assert signed_rank_bounds([0, 0], 3) == (0, 1, 1)
assert sensitivity_value(lambda g: 0.5, 0.05) == 1.0
assert sensitivity_value(lambda g: 0.0, 0.05, hi=50.0) == 50.0
Exercises
- Show that if , then , and that both ends are reached.
- For 10 discordant pairs with 9 events in the treated unit, compute the upper bound of the one-sided p-value at and by hand.
- Explain why the bound needs every score to be nonnegative, and give a statistic with a negative score for which it fails.
- Use the code to find the sensitivity value at for the ten differences of the example. (It is about 1.48.)
References
- Paul R. Rosenbaum, Sensitivity analysis for certain permutation inferences in matched observational studies, Biometrika 74(1), 1987, pp. 13 to 26 (the model with the bound Gamma and the bounds on the p-values of sign-score statistics)
- Paul R. Rosenbaum, Observational Studies, second edition, Springer, 2002, Chapter 4, Sensitivity to Hidden Bias, pp. 105 to 170 (the model, matched pairs, the signed-rank and McNemar bounds, and the smoking example)
- Paul R. Rosenbaum and Jeffrey H. Silber, Amplification of sensitivity analysis in matched observational studies, Journal of the American Statistical Association 104(488), 2009, pp. 1398 to 1405 (Gamma written as a pair of effects on treatment and on outcome)
- Jerome Cornfield, William Haenszel, E. Cuyler Hammond, Abraham M. Lilienfeld, Michael B. Shimkin and Ernst L. Wynder, Smoking and lung cancer, recent evidence and a discussion of some questions, Journal of the National Cancer Institute 22(1), 1959, the article starting on p. 173 (the first sensitivity argument for an unmeasured cause)
- E. Cuyler Hammond, Smoking in relation to mortality and morbidity, Journal of the National Cancer Institute 32(5), 1964, the article starting on p. 1161 (the matched smokers and nonsmokers of the example)
- Paul R. Rosenbaum and Donald B. Rubin, Assessing sensitivity to an unobserved binary covariate in an observational study with binary outcome, Journal of the Royal Statistical Society Series B 45(2), 1983, pp. 212 to 218 (a sensitivity model with an explicit unobserved covariate)
- Guido W. Imbens and Donald B. Rubin, Causal Inference for Statistics, Social, and Biomedical Sciences, Cambridge University Press, 2015, Chapter 22 (sensitivity analysis and bounds), Section 22.5 on the Rosenbaum approach
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 4KS2ZT Edit this page History Report an error Markdown