Negative Controls, E-values and Quantitative Bias Analysis
Every observational estimate ends with the same sentence: residual confounding cannot be excluded. Today you replace that sentence with numbers. A negative control outcome detects confounding the models missed. An E-value says how strong an unmeasured confounder would have to be to explain the result away. Quantitative bias analysis uses evidence about the confounder, here a chart-review substudy that measured frailty, to estimate what the result would be with it adjusted for.
By the end of today you can
- choose a negative control outcome that shares the suspected confounders but cannot be affected by the treatment
- use negative controls to detect bias, not to "calibrate" it away
- compute E-values correctly for protective effects and for the CI limit closest to 1
- correct for an unmeasured confounder with parameters from a validation substudy, including misclassification
- report the uncertainty of the bias parameters with a probabilistic bias analysis
Today's 5.5-hour plan
In this lesson
28.1 A negative control outcome (45 min)
A negative control outcome is an outcome the treatment cannot affect but that shares the suspected confounders. Hospitalization for any cause is driven by frailty, and Renavex does not prevent it (apart from a sliver through prevented kidney failure). If starters and non-starters were truly comparable, the adjusted "effect" of Renavex on hospitalization would be 1.
def add_hospitalization(t, con):
"""hosp24: any hospitalization in the 24 months after time zero (the negative control outcome)."""
con.register("tt", t[["person_id", "trial", "t0"]])
h = con.sql(f"""
SELECT tt.person_id, tt.trial, count(ev.event_date) > 0 AS hosp24
FROM tt LEFT JOIN read_csv('{D}/rwe_events.csv') ev
ON ev.person_id = tt.person_id AND ev.event = 'hospitalization'
AND ev.event_date >= tt.t0 AND ev.event_date < tt.t0 + INTERVAL 24 MONTH
GROUP BY 1, 2""").df()
out = t.merge(h, on=["person_id", "trial"], how="left")
out["hosp24"] = out.hosp24.astype(int)
return out
"""Day 28.1: a negative control outcome. Renavex cannot prevent hospital stays for other causes; frailty
causes them. If the 'effect' on hospitalization is not 1, something unmeasured differs between groups."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.bias import add_hospitalization # noqa: E402
from corridor.db import connect # noqa: E402
from corridor.dr import OUTCOME_FORMULA, aipw, outcome_model # noqa: E402
from corridor.ps import fit_ps # noqa: E402
from corridor.tte import load # noqa: E402
t = add_hospitalization(load(), connect())
_, e = fit_ps(t)
print(f"{'outcome within 24 months':<34}{'starters':>9}{'others':>8}{'AIPW ratio (ATT)':>18} 95% CI")
res = {}
for y, label in (("kf24", "kidney failure"), ("death24", "death"), ("hosp24", "hospitalization (negative control)")):
q1, q0 = outcome_model(t, OUTCOME_FORMULA.replace("kf24", y))
r = res[y] = aipw(t[y], t.start, e, q1, q0, t.person_id, "att")
print(f"{label:<34}{t[y][t.start == 1].mean():>9.1%}{t[y][t.start == 0].mean():>8.1%}{r['rr']:>18.2f} {r['lo']:.2f}-{r['hi']:.2f}")
cal = res["kf24"]["rr"] / res["hosp24"]["rr"]
print(f"\n'calibrated' kidney failure ratio (divide by the negative control's): {cal:.2f}")
outcome within 24 months starters others AIPW ratio (ATT) 95% CI
kidney failure 4.0% 1.7% 0.80 0.60-1.06
death 7.5% 8.4% 0.95 0.78-1.16
hospitalization (negative control) 25.8% 27.0% 0.95 0.86-1.06
'calibrated' kidney failure ratio (divide by the negative control's): 0.84
The negative control gives 0.95 (0.86 to 1.06): starters were hospitalized 5% less than comparable non-starters, for reasons that are not Renavex. That fits the DAG (Day 21): doctors start Renavex less often in frail patients, and frailty is not in the data. The interval includes 1, so this is a signal, not proof, but it is a signal in the expected direction.
Dividing the kidney failure ratio by the negative control's ("calibration") gives 0.84. That correction assumes the unmeasured confounder affects kidney failure exactly as it affects hospitalization, which is rarely true. Use a negative control to detect bias and estimate its direction. Correct only with a model of the confounder (28.3).
28.2 E-values (35 min)
The E-value (VanderWeele and Ding) is the minimum strength of association, on the risk ratio scale, that an unmeasured confounder would need with both the treatment and the outcome to fully explain away an estimate. For a ratio RR > 1 it is RR + √(RR × (RR − 1)); invert protective ratios first. A second E-value for the confidence limit closest to 1 tells you what would move the interval to include 1.
def e_value(rr, lo=None, hi=None):
"""VanderWeele & Ding's E-value for a risk ratio, and for the CI limit closest to 1 (1 if the CI
includes 1). Protective ratios are inverted first."""
def ev(r):
r = 1 / r if r < 1 else r
return r + np.sqrt(r * (r - 1))
point = ev(rr)
if lo is None:
return point
if lo <= 1 <= hi:
return point, 1.0
return point, ev(hi if rr < 1 else lo)
"""Day 28.2: E-values - how strong would an unmeasured confounder have to be to explain the estimate away?"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.bias import add_hospitalization, e_value # noqa: E402
from corridor.db import connect # noqa: E402
from corridor.dr import OUTCOME_FORMULA, aipw, outcome_model # noqa: E402
from corridor.ps import fit_ps # noqa: E402
from corridor.tte import load # noqa: E402
t = add_hospitalization(load(), connect())
_, e = fit_ps(t)
print(f"{'estimate':<36}{'ratio':>7} 95% CI E-value (point) E-value (CI)")
for y, label in (("kf24", "kidney failure, starters (AIPW)"), ("death24", "death, starters (AIPW)")):
q1, q0 = outcome_model(t, OUTCOME_FORMULA.replace("kf24", y))
r = aipw(t[y], t.start, e, q1, q0, t.person_id, "att")
ep, ec = e_value(r["rr"], r["lo"], r["hi"])
print(f"{label:<36}{r['rr']:>7.2f} {r['lo']:.2f}-{r['hi']:.2f} {ep:>15.2f}{ec:>14.2f}")
r = (0.62, 0.44, 0.89)
print(f"{'kidney failure, everyone (AIPW ATE)':<36}{r[0]:>7.2f} {r[1]:.2f}-{r[2]:.2f} {e_value(*r)[0]:>15.2f}{e_value(*r)[1]:>14.2f}")
estimate ratio 95% CI E-value (point) E-value (CI)
kidney failure, starters (AIPW) 0.80 0.60-1.06 1.82 1.00
death, starters (AIPW) 0.95 0.78-1.16 1.29 1.00
kidney failure, everyone (AIPW ATE) 0.62 0.44-0.89 2.61 1.50
To explain away the kidney failure estimate in starters (0.80), a confounder would need risk ratios of 1.82 with both starting Renavex and kidney failure, beyond the measured covariates. Its interval already includes 1, so the CI's E-value is 1. The ATE (0.62) would need a confounder of 2.61; to bring its interval to 1, 1.50.
Is 1.82 large? Compare it with the measured confounders. A 10 mL/min lower eGFR has an odds ratio near 4.8 with kidney failure and near 1.9 with starting (Day 21), so an unmeasured factor of that size is not impossible. The E-value does not say whether such a confounder exists. It says how strong one would have to be, so that people who know the clinical area can judge.
28.3 Quantitative bias analysis with a validation substudy (50 min)
Frailty is not in the extract, but it was recorded for a random 1,000 people by chart review. That is enough to estimate the two quantities the bias depends on:
- p1, p0: the prevalence of frailty in starters and in (weighted) non-starters;
- RR(U,Y): the risk ratio between frailty and the outcome, adjusted for the measured confounders.
The bias factor for a binary confounder is (p1 (RR − 1) + 1) / (p0 (RR − 1) + 1). Divide the estimate by it to correct. The chart review is imperfect (sensitivity 0.85, specificity 0.95), so correct the prevalences for misclassification first: p = (p_observed + specificity − 1) / (sensitivity + specificity − 1).
def bias_factor(rr_ud, p1, p0):
"""Bias in a risk ratio from a binary confounder U with prevalence p1 in the treated and p0 in the
(weighted) untreated, and risk ratio rr_ud between U and the outcome."""
return (p1 * (rr_ud - 1) + 1) / (p0 * (rr_ud - 1) + 1)
def misclassification_correct(p_obs, se, sp):
"""True prevalence from a prevalence measured with sensitivity se and specificity sp (clipped to [0, 1])."""
return float(np.clip((p_obs + sp - 1) / (se + sp - 1), 0, 1))
ADJ = "egfr10 + albuminuria + age10 + male + qc + nephrology_care + heart_failure + copd + prior_stays"
def load_substudy(t):
"""Person-trials of the 1,000 people in the frailty chart-review substudy (frail_cfs5 = CFS >= 5)."""
import duckdb
s = duckdb.sql(f"SELECT * FROM read_csv('{D}/rwe_frailty_substudy.csv')").df()
return t.reset_index().merge(s, on="person_id").set_index("index")
def substudy_parameters(sub, outcome, w):
"""Bias parameters from the substudy: frailty prevalence in starters and in weighted non-starters,
and the frailty-outcome risk ratio in non-starters adjusted for the measured confounders (Poisson GLM)."""
import statsmodels.api as sm
import statsmodels.formula.api as smf
w = np.asarray(w)
s, n = (sub.start == 1).to_numpy(), (sub.start == 0).to_numpy()
p1 = sub.frail_cfs5[s].mean()
p0 = np.average(sub.frail_cfs5[n], weights=w[n])
m = smf.glm(f"{outcome} ~ frail_cfs5 + {ADJ}", sub[n], family=sm.families.Poisson()).fit()
return float(p1), float(p0), float(np.exp(m.params["frail_cfs5"]))
"""Day 28.3: simple quantitative bias analysis for unmeasured frailty, with parameters from the
chart-review substudy (1,000 people; frailty recorded with sensitivity 0.85 and specificity 0.95)."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.bias import (add_hospitalization, bias_factor, load_substudy, misclassification_correct, # noqa: E402
substudy_parameters)
from corridor.db import connect # noqa: E402
from corridor.dr import OUTCOME_FORMULA, aipw, outcome_model # noqa: E402
from corridor.ps import fit_ps, weights # noqa: E402
from corridor.tte import load # noqa: E402
t = add_hospitalization(load(), connect())
_, e = fit_ps(t)
w = weights(e, t.start, "att")
sub = load_substudy(t)
ws = w[sub.index.to_numpy()]
print(f"substudy: {sub.person_id.nunique()} people, {len(sub):,} person-trials, {int(sub.start.sum())} starts")
print(f"{'outcome':<16}{'p1':>6}{'p0':>6}{'p1*':>6}{'p0*':>6}{'RR(U,Y)':>9}{'bias':>7}{'observed':>10}{'corrected':>11}")
for y in ("hosp24", "kf24", "death24"):
p1, p0, rr_ud = substudy_parameters(sub, y, ws)
c1, c0 = misclassification_correct(p1, 0.85, 0.95), misclassification_correct(p0, 0.85, 0.95)
b = bias_factor(rr_ud, c1, c0)
q1, q0 = outcome_model(t, OUTCOME_FORMULA.replace("kf24", y))
rr = aipw(t[y], t.start, e, q1, q0, t.person_id, "att")["rr"]
print(f"{y:<16}{p1:>6.3f}{p0:>6.3f}{c1:>6.3f}{c0:>6.3f}{rr_ud:>9.2f}{b:>7.3f}{rr:>10.2f}{rr / b:>11.2f}")
print("p1, p0: recorded frailty in starters and in ATT-weighted non-starters; * = corrected for misclassification")
substudy: 890 people, 9,247 person-trials, 103 starts
outcome p1 p0 p1* p0* RR(U,Y) bias observed corrected
hosp24 0.126 0.169 0.095 0.149 1.66 0.968 0.95 0.98
kf24 0.126 0.169 0.095 0.149 3.05 0.916 0.80 0.87
death24 0.126 0.169 0.095 0.149 1.23 0.988 0.95 0.96
p1, p0: recorded frailty in starters and in ATT-weighted non-starters; * = corrected for misclassification
Of the 1,000 substudy people, 890 were in at least one trial (103 starts). After correcting for misclassification, 9.5% of starters were frail against 14.9% of weighted non-starters. Frailty raises the risk of hospitalization by 66%, so the negative control's bias factor is 0.968, and the corrected negative control is 0.98, close to 1. Frailty explains the negative control signal. That is evidence the bias analysis is about the right confounder.
For kidney failure, the substudy estimates a frailty risk ratio of 3.05, and the correction moves the estimate from 0.80 to 0.87. Hold that thought: 3.05 is based on the 30 people in the substudy who had kidney failure.
28.4 Probabilistic bias analysis (35 min)
A single corrected number hides two kinds of uncertainty: the substudy's parameters are estimates, and so is the original ratio. Probabilistic bias analysis samples both: resample substudy people, recompute p1, p0 and RR(U,Y), correct for misclassification, draw the observed ratio from its sampling distribution, correct, and repeat 500 times.
def probabilistic_qba(rr, se_log, sub, outcome, w, reps=2000, seed=2028, se=0.85, sp=0.95):
"""Probabilistic bias analysis: resample substudy people (parameter uncertainty), correct the
prevalences for misclassification, divide a random draw of the observed ratio (sampling error)
by the bias factor. Returns the corrected ratios."""
rng = np.random.default_rng(seed)
people = sub.person_id.unique()
idx = {p: i for p, i in sub.groupby("person_id").indices.items()}
out = []
for _ in range(reps):
rows = np.concatenate([idx[p] for p in rng.choice(people, len(people))])
b = sub.iloc[rows]
p1, p0, rr_ud = substudy_parameters(b, outcome, w[rows])
p1, p0 = misclassification_correct(p1, se, sp), misclassification_correct(p0, se, sp)
out.append(np.exp(np.log(rr) + rng.normal(0, se_log)) / bias_factor(rr_ud, p1, p0))
return np.array(out)
"""Day 28.4: probabilistic bias analysis - carry the substudy's uncertainty into the corrected estimate."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.bias import add_hospitalization, load_substudy, probabilistic_qba # noqa: E402
from corridor.db import connect # noqa: E402
from corridor.dr import OUTCOME_FORMULA, aipw, outcome_model # noqa: E402
from corridor.ps import fit_ps, weights # noqa: E402
from corridor.tte import load # noqa: E402
t = add_hospitalization(load(), connect())
_, e = fit_ps(t)
w = weights(e, t.start, "att")
sub = load_substudy(t)
print(f"{'outcome':<10}{'observed (95% CI)':>22}{'bias-corrected median (95% simulation interval)':>50}")
for y in ("hosp24", "kf24"):
q1, q0 = outcome_model(t, OUTCOME_FORMULA.replace("kf24", y))
r = aipw(t[y], t.start, e, q1, q0, t.person_id, "att")
c = probabilistic_qba(r["rr"], r["se_log"], sub, y, w[sub.index.to_numpy()], reps=500)
lo, med, hi = np.quantile(c, [0.025, 0.5, 0.975])
print(f"{y:<10}{r['rr']:>9.2f} ({r['lo']:.2f}-{r['hi']:.2f}){med:>27.2f} ({lo:.2f}-{hi:.2f})")
outcome observed (95% CI) bias-corrected median (95% simulation interval)
hosp24 0.95 (0.86-1.06) 0.99 (0.88-1.10)
kf24 0.80 (0.60-1.06) 0.89 (0.63-1.30)
The negative control centres on 0.99 (0.88 to 1.10), consistent with no effect once frailty is accounted for. Kidney failure's corrected interval is wide, 0.89 (0.63 to 1.30), wider than the uncorrected 0.60 to 1.06: the substudy knows little about frailty and kidney failure. Honest bias analysis often makes intervals wider. That is the point: they now include the uncertainty about the bias.
Why it matters at work: "residual confounding cannot be ruled out" no longer satisfies reviewers. The CDA-AMC reporting guidance asks for the expected direction and size of each bias. Negative controls, E-values and QBA are how you give them. In a submission, a validation substudy is often the strongest answer you can give to an unmeasured confounder.
Where you'll meet this: the sensitivity section of RWE studies;
EValueandepisensrin R; FDA and EMA RWE guidance on bias; Lash, Fox and Fink's Applying Quantitative Bias Analysis to Epidemiologic Data
28.5 Truth check (30 min)
The generator knows everyone's frailty. Add the true frailty to both models and compare:
"""Day 28 truth check: what would adjusting for the TRUE frailty have done, and where is the truth?
Also: the substudy's frailty-outcome risk ratios next to the same ratios in all 9,805 people."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
import statsmodels.api as sm # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.bias import ADJ, add_hospitalization # noqa: E402
from corridor.db import connect # noqa: E402
from corridor.dr import OUTCOME_FORMULA, aipw, outcome_model # noqa: E402
from corridor.ps import PS_FORMULA, fit_ps # noqa: E402
from corridor.truth import TRUTH # noqa: E402
from corridor.tte import load # noqa: E402
t = add_hospitalization(load(), connect())
f = duckdb.sql(f"SELECT person_id, (frailty > 1.6)::INT AS frail FROM read_csv('{TRUTH}/rwe_truth.csv')").df()
t = t.merge(f, on="person_id")
tr = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/rwe_sequential_truth.csv')").df()
d = t.assign(trial=t.trial.astype(int)).merge(tr, on=["person_id", "trial"]).query("start == 1")
print(f"{'outcome':<10}{'as analysed':>12}{'+ true frailty':>16}{'truth':>8}")
for y in ("kf24", "death24", "hosp24"):
out = []
for extra in ("", " + frail"):
_, e = fit_ps(t, PS_FORMULA + extra)
q1, q0 = outcome_model(t, OUTCOME_FORMULA.replace("kf24", y) + extra)
out.append(aipw(t[y], t.start, e, q1, q0, None, "att")["rr"])
true = f"{d[y + '_start'].mean() / d[y + '_no_start'].mean():>8.2f}" if y != "hosp24" else f"{'1 (~)':>8}"
print(f"{y:<10}{out[0]:>12.2f}{out[1]:>16.2f}{true}")
print(f"\ntrue frailty: starters {t.frail[t.start == 1].mean():.3f}, non-starters {t.frail[t.start == 0].mean():.3f}")
n = t[t.start == 0]
print("frailty-outcome risk ratio in non-starters, all 9,805 people (true frailty), clustered 95% CI:")
for y in ("kf24", "death24", "hosp24"):
m = smf.glm(f"{y} ~ frail + {ADJ}", n, family=sm.families.Poisson()).fit(
cov_type="cluster", cov_kwds={"groups": pd.factorize(n.person_id)[0]})
lo, hi = np.exp(m.conf_int().loc["frail"])
print(f" {y:<10}{np.exp(m.params['frail']):.2f} ({lo:.2f}-{hi:.2f}) people with the outcome: {n[n[y] == 1].person_id.nunique():,}")
outcome as analysed + true frailty truth
kf24 0.80 0.79 0.77
death24 0.95 0.96 0.90
hosp24 0.95 1.00 1 (~)
true frailty: starters 0.082, non-starters 0.147
frailty-outcome risk ratio in non-starters, all 9,805 people (true frailty), clustered 95% CI:
kf24 0.99 (0.65-1.52) people with the outcome: 258
death24 1.22 (1.03-1.45) people with the outcome: 1,003
hosp24 1.80 (1.68-1.93) people with the outcome: 2,981
Adjusting for true frailty moves the negative control exactly to 1.00, confirming the diagnosis of 28.1–28.4. It barely moves kidney failure (0.80 to 0.79), because in the whole extract frailty has no association with kidney failure (risk ratio 0.99). The substudy's 3.05 was a chance finding from 30 people, and the simple correction of 28.3 moved kidney failure the wrong way (0.80 to 0.87, truth 0.77). The probabilistic interval (0.63 to 1.30) was honest about how little the substudy knew.
Two lessons. A bias analysis is only as good as its parameters, so report their sources and uncertainty. And the remaining gap for death (0.95–0.96 against a true 0.90) is not frailty either: some other confounding remains. The lab eGFR is a noisy snapshot of true kidney function, so part of the confounding by kidney function is still there after adjustment.
28.6 E-values done wrong (20 min)
Bug of the day. The E-value formula, pasted from the paper, applied to the protective AIPW ATE:
"""Day 28 bug of the day: two ways to get an E-value wrong for a protective effect."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.bias import e_value # noqa: E402
rr, lo, hi = 0.62, 0.44, 0.89 # AIPW ATE, Day 25
def naive(r):
return r + np.sqrt(r * (r - 1)) # the formula, pasted from the paper
with np.errstate(invalid="ignore"):
print(f"formula applied to 0.62 directly: {naive(rr)}")
print(f"... and to the CI limit far from 1 (0.44 -> 1/0.44): {naive(1 / lo):.2f}")
print(f"correct: point {e_value(rr, lo, hi)[0]:.2f}, CI {e_value(rr, lo, hi)[1]:.2f} (from the limit closest to 1, 0.89)")
formula applied to 0.62 directly: nan
... and to the CI limit far from 1 (0.44 -> 1/0.44): 3.97
correct: point 2.61, CI 1.50 (from the limit closest to 1, 0.89)
Applied to 0.62 directly, the formula takes the square root of a negative number and returns nan, which a report template prints as an empty cell. The second error is subtler: computing the CI's E-value from the limit far from 1 (0.44) gives 3.97 and makes the result look 2.6 times more robust than it is (1.50). Protective ratios are inverted first, and the CI's E-value always uses the limit closest to 1. tests/test_days_27_29.py checks both.
Try it (15 min). Build a tipping-point table for the kidney failure estimate: for confounders with risk ratios 1.5 to 10 with the outcome and prevalences from 0% to 10% in starters (15% in non-starters), what would the corrected ratio be? Which combinations reach 1?
Solution
"""Day 28 try it: a tipping-point table - which confounders would move the kidney failure estimate to 1?"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.bias import bias_factor # noqa: E402
rr = 0.80 # AIPW, effect in starters
p0 = 0.15 # prevalence in weighted non-starters
print(f"corrected ratio for observed {rr} (U less common in starters; p0 = {p0})")
print(f"{'RR(U,Y)':>9}" + "".join(f"{'p1 = ' + format(p1, '.2f'):>12}" for p1 in (0.10, 0.05, 0.0)))
for rr_ud in (1.5, 2, 3, 5, 10):
print(f"{rr_ud:>9}" + "".join(f"{rr / bias_factor(rr_ud, p1, p0):>12.2f}" for p1 in (0.10, 0.05, 0.0)))
print("\nand if U were MORE common in starters (p1 = 0.30, p0 = 0.15):")
print("".join(f" RR(U,Y) {r}: {rr / bias_factor(r, 0.30, 0.15):.2f}" for r in (1.5, 2, 3)))
corrected ratio for observed 0.8 (U less common in starters; p0 = 0.15)
RR(U,Y) p1 = 0.10 p1 = 0.05 p1 = 0.00
1.5 0.82 0.84 0.86
2 0.84 0.88 0.92
3 0.87 0.95 1.04
5 0.91 1.07 1.28
10 0.99 1.30 1.88
and if U were MORE common in starters (p1 = 0.30, p0 = 0.15):
RR(U,Y) 1.5: 0.75 RR(U,Y) 2: 0.71 RR(U,Y) 3: 0.65
To reach 1, a confounder needs a risk ratio of about 3 with kidney failure and to be absent from starters while present in 15% of non-starters, or a risk ratio of 5 with a prevalence gap of 10 points. If the confounder were more common in starters, the true effect would be even stronger. A tipping-point table lets a clinical reviewer find the plausible region on their own.
28.7 Mini-project: the sensitivity section (45 min)
Write the sensitivity section of the RWE report to docs/m3_sensitivity.md: the main estimates, their E-values, the substudy's bias parameters, the corrected estimates, and a paragraph of interpretation.
"""Day 28 mini-project: the sensitivity analysis section of the RWE report, as docs/m3_sensitivity.md."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.bias import (add_hospitalization, bias_factor, e_value, load_substudy, # noqa: E402
misclassification_correct, substudy_parameters)
from corridor.db import ROOT, connect # noqa: E402
from corridor.dr import OUTCOME_FORMULA, aipw, outcome_model # noqa: E402
from corridor.ps import fit_ps, weights # noqa: E402
from corridor.tte import load # noqa: E402
t = add_hospitalization(load(), connect())
_, e = fit_ps(t)
w = weights(e, t.start, "att")
sub = load_substudy(t)
res = {}
for y in ("kf24", "death24", "hosp24"):
q1, q0 = outcome_model(t, OUTCOME_FORMULA.replace("kf24", y))
r = aipw(t[y], t.start, e, q1, q0, t.person_id, "att")
p1, p0, rr_ud = substudy_parameters(sub, y, w[sub.index.to_numpy()])
b = bias_factor(rr_ud, misclassification_correct(p1, 0.85, 0.95), misclassification_correct(p0, 0.85, 0.95))
res[y] = (r, e_value(r["rr"], r["lo"], r["hi"]), rr_ud, b)
lines = ["# Sensitivity to unmeasured confounding", "",
"Effect of starting Renavex in the people who started it (AIPW), 24 months.", "",
"| Outcome | Ratio (95% CI) | E-value (point / CI) | Frailty-outcome RR (substudy) | Frailty-corrected ratio |",
"|---|---|---|---|---|"]
names = {"kf24": "Kidney failure", "death24": "Death", "hosp24": "Hospitalization (negative control)"}
for y, (r, (ep, ec), rr_ud, b) in res.items():
lines.append(f"| {names[y]} | {r['rr']:.2f} ({r['lo']:.2f}-{r['hi']:.2f}) | {ep:.2f} / {ec:.2f} | {rr_ud:.2f} | {r['rr'] / b:.2f} |")
r = res["hosp24"][0]
lines += ["", f"The negative control outcome suggests residual confounding of modest size (ratio {r['rr']:.2f}, "
f"95% CI {r['lo']:.2f}-{r['hi']:.2f}), consistent with starters being less frail. Correcting for frailty "
"with parameters from the chart-review substudy moves the negative control towards 1. "
f"An unmeasured confounder would need risk ratios of {res['kf24'][1][0]:.2f} with both starting Renavex "
"and kidney failure to explain the point estimate away; the confidence interval already includes 1."]
open(os.path.join(ROOT, "docs", "m3_sensitivity.md"), "w", encoding="utf-8").write("\n".join(lines) + "\n")
print("\n".join(lines))
# Sensitivity to unmeasured confounding
Effect of starting Renavex in the people who started it (AIPW), 24 months.
| Outcome | Ratio (95% CI) | E-value (point / CI) | Frailty-outcome RR (substudy) | Frailty-corrected ratio |
|---|---|---|---|---|
| Kidney failure | 0.80 (0.60-1.06) | 1.82 / 1.00 | 3.05 | 0.87 |
| Death | 0.95 (0.78-1.16) | 1.29 / 1.00 | 1.23 | 0.96 |
| Hospitalization (negative control) | 0.95 (0.86-1.06) | 1.28 / 1.00 | 1.66 | 0.98 |
The negative control outcome suggests residual confounding of modest size (ratio 0.95, 95% CI 0.86-1.06), consistent with starters being less frail. Correcting for frailty with parameters from the chart-review substudy moves the negative control towards 1. An unmeasured confounder would need risk ratios of 1.82 with both starting Renavex and kidney failure to explain the point estimate away; the confidence interval already includes 1.
Add, by hand, one sentence the generated paragraph cannot know: the substudy's frailty–kidney failure estimate rests on 30 people, so the corrected kidney failure ratio is uncertain (probabilistic interval 0.63 to 1.30).
Check it in R (by hand; the EValue package on CRAN computes the same quantities):
# Day 28: E-values and the bias factor by hand in R (the EValue package on CRAN does the same).
e_value <- function(rr) { rr <- ifelse(rr < 1, 1 / rr, rr); rr + sqrt(rr * (rr - 1)) }
bias_factor <- function(rr_ud, p1, p0) (p1 * (rr_ud - 1) + 1) / (p0 * (rr_ud - 1) + 1)
cat(sprintf("E-value, kidney failure ATT 0.80: %.2f; ATE 0.62: %.2f, its CI limit 0.89: %.2f\n",
e_value(0.797), e_value(0.62), e_value(0.89)))
fix <- function(p, se = 0.85, sp = 0.95) (p + sp - 1) / (se + sp - 1)
cat(sprintf("hospitalization: bias factor %.3f, corrected ratio %.2f\n",
bias_factor(1.66, fix(0.126), fix(0.169)), 0.953 / bias_factor(1.66, fix(0.126), fix(0.169))))
E-value, kidney failure ATT 0.80: 1.82; ATE 0.62: 2.61, its CI limit 0.89: 1.50
hospitalization: bias factor 0.968, corrected ratio 0.98
28.8 Save your work
python -m pytest -q
git add .
git commit -m "Day 28: negative controls, E-values and quantitative bias analysis"
Day 28 checklist
- I choose a negative control outcome that shares the suspected confounders but cannot be affected by the treatment
- I use negative controls to detect bias, not to "calibrate" it away
- I compute E-values correctly for protective effects and for the CI limit closest to 1
- I correct for an unmeasured confounder with parameters from a validation substudy, including misclassification
- I report the uncertainty of the bias parameters with a probabilistic bias analysis
Bloc français (30 min)
Thème : l'analyse de sensibilité.
L'issue témoin négative, l'hospitalisation, ne peut pas être modifiée par le Renavex. Pourtant, son rapport de risques ajusté est de 0,95 : il reste un facteur de confusion non mesuré, probablement la fragilité. La valeur E indique la force minimale qu'un tel facteur devrait avoir pour expliquer entièrement le résultat. L'analyse de biais quantitative utilise une sous-étude de validation pour corriger l'estimation.
| Français | English |
|---|---|
| l'issue témoin négative | the negative control outcome |
| la confusion résiduelle | residual confounding |
| le facteur de confusion non mesuré | the unmeasured confounder |
| la valeur E | the E-value |
| l'analyse de biais quantitative | quantitative bias analysis |
| la sous-étude de validation | the validation substudy |
| la fragilité | frailty |
| l'erreur de classification | misclassification |
| la sensibilité / la spécificité | sensitivity / specificity |
| le facteur de biais | the bias factor |
| le point de bascule | the tipping point |
| l'analyse probabiliste | probabilistic analysis |
Exercices
- Translate: "Frailty explains the signal from the negative control."
- Translate: « Une analyse de biais n'est valable que si ses paramètres le sont. »
- In three French sentences, explain what an E-value of 1.82 means for the kidney failure estimate.
Réponses
- La fragilité explique le signal de l'issue témoin négative.
- "A bias analysis is only as valid as its parameters."
- Example: Pour annuler l'effet estimé, un facteur de confusion non mesuré devrait multiplier par 1,82 le risque d'insuffisance rénale. Il devrait aussi être associé au début du Renavex avec la même force. Les cliniciens peuvent juger si un tel facteur est plausible.