Sensitivity analysis and partial identification
Quantify sensitivity to unmeasured confounding using partial-R² omitted-variable analysis, E-values, Rosenbaum matched-pair bounds, and Manski partial identification with monotonicity assumptions.
After this lesson you can
- Derive omitted-variable bias using partial R² values and calculate the robustness value.
- Calculate and interpret E-values for risk ratios and approximate standardized mean differences.
- Apply Rosenbaum bounds to disjoint matched pairs and find the Γ that changes significance.
- Calculate Manski bounds and narrow them using monotonicity assumptions.
- Report what confounding would be needed to change a conclusion.
Before you start
How much would have to be missing?
A record shows fewer incidents among teams adopting a security tool. Even after adjusting for prior characteristics, more motivated teams might have adopted earlier and used better procedures. Ignorability with respect to all relevant confounders cannot be verified by observed balance. Instead of asserting no hidden confounding, quantify which associations would be needed to change a conclusion and explain the assumptions supporting the calculation.
Different questions ask how much a regression coefficient changes, what factor could explain a risk ratio, how much assignment bias a matched test tolerates, and what effects are compatible with data without identifying a point. Their parameters are not interchangeable.
Omitted bias expressed through explained variance
In a restricted OLS regression of on treatment and controls , imagine adding scalar confounder . The omitted-variable formula compares coefficients of the two regressions. Partial-R² sensitivity analysis by Cinelli and Hazlett parameterizes unknown associations by
In terms of the observed regression, with classical OLS standard error and residual degrees of freedom,
Derive it as follows. Residualize and against and call those residuals . Also residualize and against and call the results . By Frisch–Waugh–Lovell, the coefficient difference is . The squared correlations are and . Since and , substitution and absolute value yield the identity.
This is an OLS algebraic identity with an adequately ranked matrix. The squares do not determine the change’s sign: to study the worst case reducing a positive coefficient, choose unfavorable orientation. Do not replace with a robust, clustered, or IPW standard error and claim the same exact identity still holds. Turning coefficient difference into causal bias also requires relevant causal and specification assumptions.
For one confounder and an expanded regression with one fewer degree of freedom, its classical standard error is
The point robustness value is the smallest possible that can bring the coefficient to zero in the unfavorable scenario. At that minimum’s boundary the two strengths are equal; if one is larger the other may be smaller. With it follows by imposing :
This differs from the threshold at which an interval stops excluding zero, which depends on the expanded standard error, degrees of freedom, and chosen level. If the original interval already contains zero, that second threshold is zero. An RV does not estimate how much hidden confounding exists.
To scale the axes one can compare an observed covariate chosen for substantive reasons before seeking a persuasive result. A formal comparison must specify which partial regressions and which residual of its bounds apply to. Naively multiplying both R² values of a covariate by the same factor may not yield the correct bound. The figure uses age in the NSW–PSID OLS from the adjustment lesson; that OLS is not the IPW ATT estimate from that lesson.
The E-value for a risk ratio
If an adjusted observed risk ratio is , the E-value is
Its interpretation relies on the bound of Ding and VanderWeele: if bound relevant unmeasured-confounder associations with treatment and outcome on the risk-ratio scale, a maximum bias factor is . If both associations are bounded by the same , increases in each argument and . To explain to the null, is necessary; solving yields the earlier root.
More specifically, in each observed-covariate stratum , can bound the largest ratio across levels of . Parameter can bound the largest risk ratio for across two levels of , within each arm and stratum . Use valid bounds across relevant strata, with appropriate denominators and support. These are conditional associations defined for the bound, not arbitrary odds ratios or marginal correlations.
It is the minimum possible in that scenario, not a claim that both associations must simultaneously exceed the E-value. One may be smaller if the other is sufficiently larger. Nor is it a probability of confounding or a causal proof. Causal interpretation needs consistency, positivity, and sufficient confounding control once relevant factors are included, along with the bound’s assumptions.
For a protective association invert the ratio. For an interval use the limit closest to one; if it already contains one, its E-value is one. An odds ratio is not automatically a risk ratio. For a standardized mean difference , approximation exists under extra distributional and scale-conversion assumptions: report the standard deviation used and present the result as an approximation, not an exact E-value for an arbitrary difference.
Sensitivity of a matched comparison
In disjoint pairs with one treated and one control, the Rosenbaum model allows treatment odds within a pair to differ by up to despite equal observed covariates. Conditioning on absolute differences, the upper one-sided signed-rank test uses with nonnegative ranks .
Under the sharp null of zero individual effect, independent assignment across pairs, and the odds model, each pair’s positive-sign probability lies in . A weighted Bernoulli-sum tail is monotone in each probability: evaluating all at the lower and then upper endpoint yields one-sided p-value bounds. With the exact randomized distribution is recovered. This is not automatically a two-sided test or a test of zero ATE under heterogeneous effects.
Dynamic programming starts with unit mass at sum zero. For each rank redistribute mass: fraction keeps the sum and fraction shifts by . At the end, sum mass at values at least . Average tied ranks may be half-integers; doubling them preserves comparison and permits integer indexing. Zero differences are discarded according to the stated convention.
The upper bound crossing 0.05 indicates when rejection is no longer guaranteed for every assignment allowed by this model; it does not prove hidden bias exists. In NSW the matching lesson reuses controls: its pairs are not disjoint. To use these classical bounds construct pairs without replacement or use a method explicitly handling dependence. Changing matching can change the population studied.
Partial identification and monotonicity
If , consistency decomposes each potential mean into its observed and missing parts. Write , and . Without selection assumptions,
The unknown part of belongs to and that of to . These limits are attainable in this model class and hence are sharp Manski bounds. Their width reflects what is unobserved; it is not a confidence interval or a flaw to hide.
For binary outcomes, monotone response implies nonnegative ATE. Monotone increasing selection imposes for both treatments, a different assumption. A monotone instrumental variable in the sense of Manski and Pepper orders potential means across values of a variable ; it is not by itself classical instrument independence or individual compliance monotonicity.
For example, let and . Under monotone increasing selection, and . Expression is then at most ; the assumption-free lower bound remains attainable when other restrictions allow it. Adding monotone response also imposes . If the resulting upper bound is negative, no distribution is compatible with both assumptions and the observed probabilities.
Adding restrictions narrows the compatible set or can empty it if they contradict the data. Ignorability, consistency, and positivity identify a point in the target population; not every additional assumption combination is compatible with that point. An interval covering a partially identified parameter and a band covering the entire identified set have different guarantees. Imbens and Manski study the first question; the lab separately constructs a conservative simultaneous band.
Coefficient stability does not mean absence of bias
Coefficient stability when adding controls can guide questions, but interpretation depends on how observed and unobserved variables relate to treatment and outcome. Approaches by Altonji, Elder and Taber and Oster use explicit restrictions on selection and fit. A stable coefficient can coexist with unmeasured confounding, and a changing one does not itself reveal which set identifies the effect.
A useful report states population and estimand, model and standard error, point and interval sensitivity separately, hypothetical parameters and substantive benchmarks, and unverified assumptions. Do not select the benchmark for the conclusion it produces.
Lab: sensitivity from scratch
The download reproduces the source and checks of the current adjustment lesson: the trial’s treated units are the same as in the NSW–PSID comparison. A connection is required; on failure the cell does not replace the data.
import asyncio
import io
import numpy as np
import pandas as pd
from pyodide.http import pyfetch
# Misma fuente, columnas y comprobaciones que el MDX vigente de m27-l14.
BASE_NSW = 'https://vincentarelbundock.github.io/Rdatasets/csv/DAAG/'
async def leer_nsw(nombre):
try:
respuesta = await pyfetch(BASE_NSW + nombre)
if not respuesta.ok:
raise RuntimeError(f'HTTP {respuesta.status}')
return pd.read_csv(io.StringIO(await respuesta.string()))
except Exception as error:
raise RuntimeError('No se pudieron descargar los datos NSW; comprueba la conexión.') from error
ensayo,comparacion=await asyncio.gather(leer_nsw('nsw74demo.csv'),leer_nsw('nsw74psid1.csv'))
columnas=['trt','age','educ','black','hisp','marr','nodeg','re74','re75','re78']
ensayo,comparacion=ensayo[columnas],comparacion[columnas]
assert ensayo.shape==(445,10) and comparacion.shape==(2675,10)
assert ensayo.trt.sum()==185 and comparacion.trt.sum()==185
assert not ensayo.isna().any().any() and not comparacion.isna().any().any()
tratados=ensayo.loc[ensayo.trt==1].sort_values(columnas).reset_index(drop=True)
tratados_psid=comparacion.loc[comparacion.trt==1].sort_values(columnas).reset_index(drop=True)
assert np.allclose(tratados,tratados_psid)
print('NSW: 185 tratados y 260 controles; comparación PSID: 185 y 2490.')
print('Los tratados de ambas muestras son los mismos; ingresos reales en dólares de 1982.')First implement OLS sensitivity, including its classical standard error and formal age benchmarks. The results are hypothetical scenarios, not observations of a confounder.
import numpy as np
from scipy.stats import t as student_t
from scipy.optimize import brentq
def residuo(y,matriz):
return [email protected](matriz,y,rcond=None)[0]
def r2_parcial(y,z,controles):
ry,rz=residuo(y,controles),residuo(z,controles)
den=(ry@ry)*(rz@rz)
if den<=0: raise ValueError('Variable residual constante')
return float((ry@rz)**2/den)
def ols_clasico(y,matriz,indice):
if np.linalg.matrix_rank(matriz)<matriz.shape[1]:
raise ValueError('Regresión sin rango completo')
b=np.linalg.lstsq(matriz,y,rcond=None)[0]
r=y-matriz@b;gl=len(y)-matriz.shape[1]
if gl<=1: raise ValueError('Grados de libertad insuficientes')
# FWL proporciona el EE clásico sin invertir X'X, más estable en Pyodide.
control=np.delete(matriz,indice,axis=1)
v=residuo(matriz[:,indice],control)
se=np.sqrt((r@r)/gl/(v@v))
return float(b[indice]),float(se),int(gl)
def ajuste_cinelli(estimate,se,df,r2_y,r2_d):
if not (0<=r2_y<1 and 0<=r2_d<1 and df>1 and se>0):
raise ValueError('R², EE o grados de libertad inválidos')
sesgo=se*np.sqrt(df*r2_y*r2_d/(1-r2_d))
ee=se*np.sqrt((1-r2_y)/(1-r2_d)*df/(df-1))
# Es el escenario que reduce el valor absoluto; el signo no se deduce de R².
return float(estimate-np.sign(estimate)*sesgo),float(ee),float(sesgo)
def robustez_punto(estimate,se,df):
f2=(estimate/se)**2/df
return float(2*f2/(np.sqrt(f2*f2+4*f2)+f2)) if f2 else 0.
def robustez_significacion(estimate,se,df,alpha=.05):
crit=student_t.ppf(1-alpha/2,df-1)
# La referencia del modelo completo usa ya gl−1 y el EE reescalado,
# aun en el límite de fuerza cero del nuevo regresor escalar.
at_zero,ee_zero,_=ajuste_cinelli(estimate,se,df,0.,0.)
if abs(at_zero)/ee_zero<=crit: return 0.
rv=robustez_punto(estimate,se,df)
f=lambda r: abs(ajuste_cinelli(estimate,se,df,r,r)[0])/ajuste_cinelli(estimate,se,df,r,r)[1]-crit
return float(brentq(f,0,rv))
def limite_referencia(rd,ry,kd=1.,ky=1.):
"""Cotas formales de Cinelli-Hazlett, R² comparados antes de incluir Z.
Z se toma ortogonal al espacio de X; kd y ky comparan R² parciales con
los del control de referencia en el espacio X sin dicho control.
"""
if not (0<=rd<1 and 0<=ry<1 and kd>=0 and ky>=0):
raise ValueError('Parámetros fuera del dominio')
rdz=kd*rd/(1-rd)
if rdz>=1 or kd*rd>=1: raise ValueError('Comparación incompatible con R² admisible')
rzx=kd*rd**2/((1-kd*rd)*(1-rd))
if rzx>=1: raise ValueError('Comparación imposible para la correlación parcial')
bound=((np.sqrt(ky)+np.sqrt(rzx))/np.sqrt(1-rzx))**2*ry/(1-ry)
return float(rdz),float(min(1.,bound))# Repite la OLS de m27-l14: sin pesos, con los mismos controles y observaciones.
# No es la sensibilidad exacta del estimador IPW ATT, cuya varianza es distinta.
covariables=['age','educ','black','hisp','marr','nodeg','re74','re75']
x=comparacion[covariables].to_numpy(float)
x=(x-x.mean(axis=0))/x.std(axis=0)
t=comparacion.trt.to_numpy(float)
y=comparacion.re78.to_numpy(float)
D=np.column_stack((np.ones(len(y)),t,x))
estimate,se,df=ols_clasico(y,D,1)
print('OLS NSW-PSID:',round(estimate,2),'EE clásico:',round(se,2),'gl:',df)
print('Valor de robustez de punto:',round(robustez_punto(estimate,se,df),6),
'| para perder significación al 5 %:',round(robustez_significacion(estimate,se,df),6))
# Edad es una variable ya observada. Se calcula su fuerza relativa dejando fuera
# edad del condicionamiento; no es una observación de un confusor desconocido.
controls=np.column_stack((np.ones(len(y)),x[:,1:]))
rd=r2_parcial(t,x[:,0],controls)
ry=r2_parcial(y,x[:,0],np.column_stack((controls,t)))
print('Edad: R² parcial con tratamiento',round(rd,6),'y con resultado',round(ry,6))
without=np.column_stack((controls,t))
b0,s0,df0=ols_clasico(y,without,without.shape[1]-1)
_,_,bias=ajuste_cinelli(b0,s0,df0,ry,rd)
assert np.isclose(bias,abs(b0-estimate),rtol=0,atol=1e-7)
print('Efecto de omitir edad, fórmula y regresiones:',round(bias,4),round(abs(b0-estimate),4))
for k in (1,2,3):
bound_d,bound_y=limite_referencia(rd,ry,k,k)
if bound_y>=1:
print('k=',k,'cota resultado trivial = 1; sin EE ajustado finito')
else:
adjusted,see,change=ajuste_cinelli(estimate,se,df,bound_y,bound_d)
print('k=',k,'cotas R² tratamiento/resultado:',round(bound_d,6),round(bound_y,6),
'| ajuste que reduce el coeficiente:',round(adjusted,2),'| EE clásico:',round(see,2))
print('Estos límites dependen de supuestos hipotéticos, no demuestran la existencia de un confusor.')Now calculate E-values and exact Rosenbaum bounds; differences in the published example come from 39 disjoint pairs. The result is an upper one-sided tail under a sharp null. Ties use average ranks and zero differences are removed; exercise tests separately check this extension.
import numpy as np
from scipy.stats import rankdata, wilcoxon
from scipy.optimize import brentq
def e_value(rr):
"""E-value de una razón de riesgos positiva; invierte valores protectores."""
if not np.isfinite(rr) or rr <= 0:
raise ValueError('La razón de riesgos debe ser positiva y finita')
r = max(rr, 1/rr)
return r + np.sqrt(r*(r-1))
def e_value_interval(lower, upper):
if not (np.isfinite(lower) and np.isfinite(upper) and 0 < lower <= upper):
raise ValueError('Intervalo de razones de riesgos inválido')
if lower <= 1 <= upper:
return 1.0
return e_value(lower if lower > 1 else upper)
def rosenbaum_bounds(differences, gamma):
"""Cotas exactas del p unilateral superior de rangos con signo."""
d = np.asarray(differences, dtype=float)
if d.ndim != 1 or not len(d) or not np.isfinite(d).all():
raise ValueError('Se necesitan diferencias finitas')
if not np.isfinite(gamma) or gamma < 1:
raise ValueError('Gamma debe ser finito y al menos 1')
# Convención Wilcoxon: se descartan las diferencias nulas.
d = d[d != 0]
if not len(d):
raise ValueError('Todas las diferencias son nulas')
# Empates absolutos: rangos medios, que son enteros o semienteros.
ranks2 = np.rint(2*rankdata(abs(d), method='average')).astype(int)
observed = int(ranks2[d > 0].sum())
def upper_tail(p):
mass = np.zeros(int(ranks2.sum())+1)
mass[0] = 1
last = 0
for rank in ranks2:
old = mass.copy()
mass[:last+1] *= 1-p
mass[rank:rank+last+1] += p*old[:last+1]
last += rank
return float(mass[observed:].sum())
return upper_tail(1/(1+gamma)), upper_tail(gamma/(1+gamma))
print('E-value RR=1,8:', e_value(1.8))
print('E-value límite inferior 1,2:', e_value_interval(1.2, 4.0))
print('E-value intervalo que cruza 1:', e_value_interval(0.8, 1.2))
print('E-value RR protector 0,5:', e_value(0.5))
d = 0.32
approx_rr = np.exp(0.91*abs(d))
print('Diferencia estandarizada d=0,32, RR aproximado:', approx_rr)
print('E-value aproximado de d=0,32:', e_value(approx_rr))
# Diferencias del ejemplo de Rosenbaum (2010), secciones 3.5 y 3.9.
published_differences = np.array([
0.148, 0.358, 1.572, 2.526, 0.287, -0.271, 0.494,
0.716, 0.411, 0.988, 1.073, 1.097, 0.491, 0.294,
0.062, 0.417, -0.886, 0.314, 0.178, 0.867, 0.539,
1.791, -0.001, -0.067, 0.779, 0.113, 0.729, 0.374,
0.610, 2.277, 0.303, -0.326, 0.527, 1.203, 0.854,
0.269, 0.683, -0.190, 0.778,
])
print('Número de pares:', len(published_differences))
print('Estadístico T:', rankdata(abs(published_differences))[published_differences > 0].sum())
for gamma in (1, 2, 3, 4):
print(f'Gamma={gamma}: cotas p unilateral=', rosenbaum_bounds(published_differences, gamma))
gcrit = brentq(lambda g: rosenbaum_bounds(published_differences, g)[1] - 0.05, 1, 20)
print('Gamma crítico para p superior=0,05:', gcrit)
print('Comparación SciPy gamma=1:', wilcoxon(published_differences, alternative='greater', method='exact').pvalue)
assert np.isclose(rosenbaum_bounds(published_differences, 2)[1], 0.0006376274, atol=1e-10)
assert np.isclose(rosenbaum_bounds(published_differences, 1)[1],
wilcoxon(published_differences, alternative='greater', method='exact').pvalue)Construct a new NSW–PSID comparison without replacement. Caliper and ordering are illustrative choices examined during development, not a preregistered plan. The procedure discards treated units, changes the represented population, and may leave imbalance; rank analysis also requires justifying its assignment model.
import numpy as np
# Como en m27-l14, se ajusta la propensión con las ocho covariables previas,
# sin usar RE78, y se recorta según 0,05 <= e <= 0,95.
variables = ['age','educ','black','hisp','marr','nodeg','re74','re75']
x = comparacion[variables].to_numpy(dtype=float)
t = comparacion.trt.to_numpy(dtype=int)
y = comparacion.re78.to_numpy(dtype=float)
z = (x-x.mean(axis=0))/x.std(axis=0)
X = np.column_stack([np.ones(len(z)), z])
def sigmoide(a):
return 1/(1+np.exp(-np.clip(a,-30,30)))
def ajustar_propension(X,t):
penalizacion = np.diag([0.0]+[1e-6]*(X.shape[1]-1))
beta = np.zeros(X.shape[1])
for _ in range(50):
e = sigmoide(X@beta)
paso = np.linalg.solve(X.T@((e*(1-e))[:,None]*X)+penalizacion,
X.T@(t-e)-penalizacion@beta)
beta += paso
if np.max(np.abs(paso)) < 1e-8:
break
else:
raise RuntimeError('La regresión logística no convergió')
return sigmoide(X@beta)
e = ajustar_propension(X,t)
eligible = (e >= 0.05) & (e <= 0.95)
treated = np.flatnonzero(eligible & (t == 1))
controls = np.flatnonzero(eligible & (t == 0))
# Primero los tratados con mayor propensión; desempates por índice original.
# Cada control se usa una sola vez, con desempate por índice original.
# Caliper absoluto de 0,05 en propensity: controla la distancia observada,
# pero descarta tratados y no garantiza balance en todas las covariables.
treated = treated[np.lexsort((treated,-e[treated]))]
available = controls.copy()
kept, chosen = [], []
for i in treated:
if len(available) == 0:
break
distances = np.abs(e[available]-e[i])
j = int(np.argmin(distances))
if distances[j] > 0.05:
continue
kept.append(i)
chosen.append(available[j])
available = np.delete(available,j)
cut_count = int((t==1).sum()-len(treated))
unmatched_count = len(treated)-len(kept)
treated = np.asarray(kept,dtype=int)
chosen = np.asarray(chosen,dtype=int)
if not len(treated):
raise RuntimeError('Ningún par satisface el caliper indicado')
assert len(np.unique(chosen)) == len(treated) and np.all(t[chosen] == 0)
pair_differences = y[treated]-y[chosen]
gaps = np.abs(e[treated]-e[chosen])
den = np.sqrt((x[t==1].var(axis=0,ddof=1)+x[t==0].var(axis=0,ddof=1))/2)
smd = (x[treated].mean(axis=0)-x[chosen].mean(axis=0))/den
print('Pares disjuntos, tratados excluidos por recorte y por caliper, controles sin usar:',
len(treated), cut_count, unmatched_count, len(available))
print('Diferencias media, positivas, negativas, cero:',
np.mean(pair_differences), int(np.sum(pair_differences>0)),
int(np.sum(pair_differences<0)), int(np.sum(pair_differences==0)))
print('Distancia propensity mediana y máxima:', np.median(gaps), np.max(gaps))
print('SMD de cada covariable tras emparejar:', dict(zip(variables,np.round(smd,3))))
print('Este análisis corresponde a los tratados retenidos, no al ensayo completo.')from scipy.stats import rankdata
def cotas_rosenbaum(diferencias, gamma):
d = np.asarray(diferencias, dtype=float)
if d.ndim != 1 or not len(d) or not np.isfinite(d).all():
raise ValueError('Las diferencias deben ser un vector finito no vacío')
if not np.isfinite(gamma) or gamma < 1:
raise ValueError('Gamma debe ser finito y al menos 1')
d = d[d != 0]
if not len(d):
raise ValueError('No quedan pares con diferencia no nula')
rangos = np.rint(2*rankdata(abs(d),method='average')).astype(int)
observado = int(rangos[d>0].sum())
def cola(p):
masa = np.zeros(int(rangos.sum())+1)
masa[0] = 1
ultimo = 0
for rango in rangos:
anterior = masa.copy()
masa[:ultimo+1] *= 1-p
masa[rango:rango+ultimo+1] += p*anterior[:ultimo+1]
ultimo += rango
return float(masa[observado:].sum())
return cola(1/(1+gamma)), cola(gamma/(1+gamma))
no_ceros = pair_differences[pair_differences != 0]
rank = rankdata(abs(no_ceros),method='average')
print('Pares con diferencia no nula y rango positivo:', len(no_ceros), rank[no_ceros>0].sum())
for gamma in (1,1.1,1.25,1.5,2):
print(f'Gamma={gamma}: cotas p unilateral superior {cotas_rosenbaum(pair_differences,gamma)}')
print('La prueba es unilateral y contrasta el nulo agudo de ningún efecto individual.')
print('El emparejamiento y los datos no prueban que pares o tratamientos sean aleatorios.')Lab: bounds and estimation
The first cell calculates analytical bounds and, for a table with binary variable Z, solves linear programs over compatible latent distributions. If assumptions conflict, the set is empty: no numerical bound is forced.
import numpy as np
from scipy.optimize import linprog
def cotas_manski(p, mu1, mu0):
if not 0 < p < 1 or not 0 <= mu1 <= 1 or not 0 <= mu0 <= 1:
raise ValueError('Probabilidades o medias fuera del dominio')
a, b = p*mu1, (1-p)*mu0
return a-b-p, a-b+(1-p)
p, mu1, mu0 = .35, .65, .45
L, U = cotas_manski(p, mu1, mu0)
print('Sin supuestos:', (round(L, 4), round(U, 4)))
print('MTR:', (0., round(U,4)))
print('MTS:', (round(L,4), round(mu1-mu0,4)))
print('MTR y MTS:', (0., round(mu1-mu0,4)))
# Distribución condicional P(T,Y|Z), elegida como DGP explícito.
# Las filas son Z, las columnas T y la última dimensión Y.
obs = np.array([[[.51, .11], [.13, .25]],
[[.02, .04], [.54, .40]]])
pz = np.array([.5, .5])
def lp_bounds(obs, pz, mtr=False, mts=False, miv=False, unconfounded=False):
"""Cotas agudas sobre distribución latente P(Y0,Y1,T|Z)."""
cells = [(z, y0, y1, t) for z in range(2) for y0 in range(2)
for y1 in range(2) for t in range(2)]
ae, be = [], []
for z in range(2):
for t in range(2):
for y in range(2):
ae.append([int(zi==z and ti==t and (y1 if ti else y0)==y)
for zi,y0,y1,ti in cells])
be.append(obs[z,t,y])
au, bu = [], []
pt = np.einsum('z,zty->t', pz, obs)
if mts:
for d in range(2):
au.append([pz[z]*(y1 if d else y0)*((1-t)/pt[0]-t/pt[1])
for z,y0,y1,t in cells])
bu.append(0.)
if miv:
for d in range(2):
au.append([(1 if z==0 else -1)*(y1 if d else y0)
for z,y0,y1,t in cells])
bu.append(0.)
if unconfounded:
for v0 in range(2):
for v1 in range(2):
ae.append([pz[z]*int(y0==v0 and y1==v1)*(t/pt[1]-(1-t)/pt[0])
for z,y0,y1,t in cells])
be.append(0.)
domain=[(0,0) if mtr and y1<y0 else (0,None) for z,y0,y1,t in cells]
c=np.array([pz[z]*(y1-y0) for z,y0,y1,t in cells])
sols=[linprog(sign*c, A_eq=np.array(ae), b_eq=be,
A_ub=np.array(au) if au else None, b_ub=bu if au else None,
bounds=domain, method='highs') for sign in (1,-1)]
if not all(s.success for s in sols):
raise ValueError('Supuestos incompatibles con los datos')
return sols[0].fun, -sols[1].fun
for label, options in [
('Sin supuestos', {}), ('MTR', {'mtr':True}),
('MTS', {'mts':True}), ('MIV', {'miv':True}),
('MTR + MTS', {'mtr':True,'mts':True}),
('MTR + MTS + MIV', {'mtr':True,'mts':True,'miv':True}),
('Ignorabilidad', {'unconfounded':True})]:
print(label, np.round(lp_bounds(obs,pz,**options), 6))This cell recalculates the 16 combinations shown by the builder and flags incompatible ones.
import numpy as np
from itertools import product
from scipy.optimize import linprog
# P(T,Y|Z), filas T, columnas Y; P(Z=0)=P(Z=1)=1/2.
observada=np.array([[[.51,.11],[.13,.25]],[[.02,.04],[.54,.40]]])
pz=np.array([.5,.5])
assert np.allclose(observada.sum(axis=(1,2)),1)
def cotas_lp(mtr,mts,miv,ignorabilidad):
# Cada masa corresponde a P(Y0,Y1,T|Z=z); hay 16 en total.
estados=list(product(range(2),repeat=4)) # z,y0,y1,t
Aeq=[]; beq=[]; Aub=[]; bub=[]
for z,t,y in product(range(2),repeat=3):
Aeq.append([int(zz==z and tt==t and (y1 if tt else y0)==y)
for zz,y0,y1,tt in estados])
beq.append(observada[z,t,y])
pt=np.einsum('z,zty->t',pz,observada)
if mts:
for d in (0,1):
Aub.append([pz[z]*(y1 if d else y0)*((1-t)/pt[0]-t/pt[1])
for z,y0,y1,t in estados]);bub.append(0.)
if miv:
for d in (0,1):
Aub.append([(1 if z==0 else -1)*(y1 if d else y0)
for z,y0,y1,t in estados]);bub.append(0.)
if ignorabilidad:
for j,k in product(range(2),repeat=2):
Aeq.append([pz[z]*int(y0==j and y1==k)*(t/pt[1]-(1-t)/pt[0])
for z,y0,y1,t in estados]);beq.append(0.)
limites=[(0,0) if mtr and y1<y0 else (0,None)
for z,y0,y1,t in estados]
c=np.array([pz[z]*(y1-y0) for z,y0,y1,t in estados])
options=dict(A_eq=Aeq,b_eq=beq,A_ub=Aub or None,b_ub=bub or None,
bounds=limites,method='highs')
inferior=linprog(c,**options);superior=linprog(-c,**options)
# Estado 2 indica incompatibilidad; otros errores no deben ocultarse.
if inferior.status==2 and superior.status==2: return None
if not inferior.success or not superior.success:
raise RuntimeError(f'Error del optimizador: {inferior.message}; {superior.message}')
return np.array([inferior.fun,-superior.fun])
def modelo_widget(mtr,mts,miv,ignorabilidad):
# Se copia la tabla de decisiones exacta que emplea el interactivo.
if miv and ignorabilidad: return None
if ignorabilidad: return np.array([305/1122,305/1122])
superior=407/1700 if mts and miv else 305/1122 if mts else 7/20 if miv else 59/100
return np.array([0 if mtr else -41/100,superior])
vacios=0
for mtr,mts,miv,ignorabilidad in product((False,True),repeat=4):
resultado=cotas_lp(mtr,mts,miv,ignorabilidad)
dibujado=modelo_widget(mtr,mts,miv,ignorabilidad)
if resultado is None or dibujado is None:
assert resultado is None and dibujado is None
vacios+=1
salida='vacío'
else:
assert np.allclose(resultado,dibujado,atol=1e-9,rtol=0)
salida=f'[{resultado[0]:.6f}, {resultado[1]:.6f}]'
print(f'MTR={int(mtr)} MTS={int(mts)} MIV={int(miv)} ignorabilidad={int(ignorabilidad)}: {salida}')
assert vacios==4
print('16 combinaciones verificadas, incluidas 4 incompatibles.')Compare the Imbens–Manski interval for the parameter with a conservative simultaneous band for the set. These are asymptotic guarantees under the stated conditions, not exact promises in every sample. IPW is shown in the simulated model with true propensity and its own assumptions.
import numpy as np
from scipy.optimize import brentq
from scipy.stats import norm
def manski_ic(y,t,alpha=.05):
"""IC de Imbens-Manski para el parámetro y banda para el conjunto."""
y,t=np.asarray(y,float),np.asarray(t,float)
if y.ndim!=1 or t.shape!=y.shape or len(y)<2:
raise ValueError('Se esperan vectores del mismo tamaño')
if not np.isin(y,[0,1]).all() or not np.isin(t,[0,1]).all():
raise ValueError('El resultado y el tratamiento deben ser binarios')
# Variables individuales cuyas medias son los extremos sin supuestos.
l=t*y-(1-t)*y-t
u=l+1
lo,hi=l.mean(),u.mean()
se_l=l.std(ddof=1)/np.sqrt(len(y))
se_u=u.std(ddof=1)/np.sqrt(len(y))
max_se=max(se_l,se_u)
if max_se == 0:
raise ValueError('Varianza de los extremos nula')
gap=(hi-lo)/max_se
c=brentq(lambda q:norm.cdf(q+gap)-norm.cdf(-q)-(1-alpha), 0, 4)
ic_parametro=(lo-c*se_l, hi+c*se_u)
z=norm.ppf(1-alpha/2)
banda_conjunto=(lo-z*se_l,hi+z*se_u)
return (lo,hi),ic_parametro,banda_conjunto,c
rng=np.random.default_rng(271701)
n=2000
x=rng.binomial(1,.5,n)
e=.2+.6*x
t=rng.binomial(1,e)
u=rng.uniform(size=n)
y0=u < (.2+.4*x)
y1=u < (.4+.4*x)
y=np.where(t==1,y1,y0).astype(int)
bounds, ic, band, c=manski_ic(y,t)
print('n=',n,'tratados=',int(t.sum()),'ATE poblacional real=0,2 por construcción')
print('Cotas empíricas=',np.round(bounds,6),'IC IM del parámetro=',np.round(ic,6),
'banda simultánea del conjunto=',np.round(band,6),'crítico IM=',round(c,6))
# IPW Hájek con propensiones conocidas del DGP, no estimadas.
w1=t/e;w0=(1-t)/(1-e)
mu1=np.average(y,weights=w1);mu0=np.average(y,weights=w0)
estimate=mu1-mu0
influence=w1*(y-mu1)/w1.mean()-w0*(y-mu0)/w0.mean()
se=influence.std(ddof=1)/np.sqrt(n)
print('IPW Hájek con propensión verdadera=',round(estimate,6),'EE=',round(se,6),
'IC=',np.round([estimate-1.96*se,estimate+1.96*se],6))In this DGP the endpoint’s binomial distribution can be enumerated exactly. The cell shows why covering one parameter does not equal covering both ends of the set.
import numpy as np
from scipy.stats import binom, norm
# En el DGP anterior, la variable del extremo inferior vale -1 con
# probabilidad 0,28 y 0 con probabilidad 0,72. La superior suma uno.
n=2000
k=np.arange(n+1)
prob=binom.pmf(k,n,.28)
lower=-k/n
upper=1-k/n
se=np.sqrt((k/n)*(1-k/n)/(n-1))
true_l,true_u=-.28,.72
c_im=norm.ppf(.95) # diferencia con la raíz IM exacta < precisión numérica aquí
c_band=norm.ppf(.975)
cover_l=lower-c_im*se<=true_l
cover_u=upper+c_im*se>=true_u
cover_set=cover_l&cover_u
cover_set_band=(lower-c_band*se<=true_l)&(upper+c_band*se>=true_u)
cover_theta=(lower-c_im*se<=.2)&(upper+c_im*se>=.2)
print('Probabilidad exacta binomial, límite inferior en IC IM:',round(prob[cover_l].sum(),6))
print('Límite superior en IC IM:',round(prob[cover_u].sum(),6),
'ambos extremos en IC IM:',round(prob[cover_set].sum(),6))
print('Conjunto completo en banda simultánea:',round(prob[cover_set_band].sum(),6),
'ATE=0,2 en IC IM:',round(prob[cover_theta].sum(),6))With the real data above, now define a different binary outcome: positive earnings in 1978. Bounds do not require ignorability, but IPW comparison does. The following intervals are illustrative under a hypothetical i.i.d. sampling model for the observed mixture: NSW and PSID come from different sources with fixed sizes, so the data do not guarantee that model. Inference applicable to the study must respect its sampling design. Low effective sample size among weighted treated units makes the IPW normal approximation especially uncertain.
Combining monotone response and selection may be incompatible with the empirical means used in direct calculation. That incompatibility of the estimated distribution does not by itself prove population assumptions are incompatible: means have sampling uncertainty.
# `comparacion` contiene NSW tratados y PSID-1, descargados en la celda anterior.
import numpy as np
from scipy.optimize import brentq
from scipy.stats import norm
def bounds_ic_binario(y, t, alpha=.05):
y,t=np.asarray(y,float),np.asarray(t,float)
if y.ndim!=1 or t.shape!=y.shape or len(y)<2:
raise ValueError('Vectores incompatibles')
if not np.isin(y,[0,1]).all() or not np.isin(t,[0,1]).all():
raise ValueError('T e Y deben ser binarios')
l=t*y-(1-t)*y-t
lo=l.mean();hi=lo+1
se=l.std(ddof=1)/np.sqrt(len(y))
if se<=0: raise ValueError('Varianza del extremo nula')
c=brentq(lambda z:norm.cdf(z+(hi-lo)/se)-norm.cdf(-z)-(1-alpha),0,4)
return (lo,hi),(lo-c*se,hi+c*se),(lo-norm.ppf(1-alpha/2)*se,hi+norm.ppf(1-alpha/2)*se),c
t = comparacion.trt.to_numpy(dtype=int)
y = (comparacion.re78.to_numpy(dtype=float)>0).astype(int)
assert len(y)==2675 and t.sum()==185
p=t.mean();mu1=y[t==1].mean();mu0=y[t==0].mean()
cotas, ic_param, banda, critico = bounds_ic_binario(y,t)
print('NSW/PSID n=',len(y),'tratados=',int(t.sum()),'Y=1 si RE78>0')
print('P(T=1), medias por brazo:', np.round([p,mu1,mu0],6))
print('Cotas Manski:',np.round(cotas,6), 'IC IM del ATE:',np.round(ic_param,6),
'banda simultánea del conjunto:',np.round(banda,6), 'c=',round(critico,6))
print('MTR:',np.round([0,cotas[1]],6),'MTS positiva:',np.round([cotas[0],mu1-mu0],6))
if mu1>=mu0:
print('MTR+MTS:',np.round([0,mu1-mu0],6))
else:
print('MTR+MTS incompatibles con las medias observadas')# Misma especificación de propensión que m27-l14: se ajusta con covariables
# anteriores y no usa el resultado. El objetivo aquí es ATE, no ATT.
covariables=['age','educ','black','hisp','marr','nodeg','re74','re75']
x=comparacion[covariables].to_numpy(dtype=float)
X=np.column_stack((np.ones(len(x)), (x-x.mean(axis=0))/x.std(axis=0)))
pen=np.diag([0.]+[1e-6]*(X.shape[1]-1))
def fit_propensity(X,t):
beta=np.zeros(X.shape[1])
for _ in range(50):
e=1/(1+np.exp(-np.clip(X@beta,-30,30)))
H=X.T@((e*(1-e))[:,None]*X)+pen
paso=np.linalg.solve(H,X.T@(t-e)-pen@beta)
beta+=paso
if np.max(abs(paso))<1e-8: break
else: raise RuntimeError('No converge la propensión')
e=1/(1+np.exp(-np.clip(X@beta,-30,30)))
if not ((e>0)&(e<1)).all(): raise ValueError('Propensiones fuera de (0,1)')
return beta,e
beta,e=fit_propensity(X,t)
w1=t/e; w0=(1-t)/(1-e)
mu1w=np.average(y,weights=w1); mu0w=np.average(y,weights=w0)
ate_ipw=mu1w-mu0w
fixed=w1*(y-mu1w)/w1.mean()-w0*(y-mu0w)/w0.mean()
# Sandwich conjunto: propensión estimada y medias Hájek, con penalización
# fija; X se estandariza en la muestra antes del ajuste, como en m27-l14.
# La penalización es minúscula: su dependencia de la escala se desprecia en
# esta aproximación asintótica. Una inferencia útil requiere atender al diseño
# y al solapamiento; un bootstrap que reajuste todo no corrige por sí solo
# la falta de soporte ni garantiza validez con pesos extremos.
grad1=-np.sum((w1*(1-e)*(y-mu1w))[:,None]*X,axis=0)/w1.sum()
grad0=np.sum((w0*e*(y-mu0w))[:,None]*X,axis=0)/w0.sum()
H=(X.T@((e*(1-e))[:,None]*X)+pen)/len(y)
scores=X*(t-e)[:,None]-(pen@beta)[None,:]/len(y)
[email protected](H,grad1-grad0)
se_ipw=influence.std(ddof=1)/np.sqrt(len(y))
ci_ipw=[ate_ipw-1.96*se_ipw,ate_ipw+1.96*se_ipw]
ess1=w1.sum()**2/np.sum(w1*w1);ess0=w0.sum()**2/np.sum(w0*w0)
print('ATE IPW Hájek:',round(ate_ipw,6),'EE sandwich conjunto:',round(se_ipw,6),
'IC 95% aproximado:',np.round(ci_ipw,6))
print('Propensión min/max:',np.round([e.min(),e.max()],6),
'ESS tratado/control:',np.round([ess1,ess0],2))
print('IC i.i.d. aproximado; identificación IPW exige ignorabilidad y solapamiento.')Comparison with a library
This local cell compares formulas with PySensemakr 0.0.8. Install that version and dependencies in your environment. It downloads the same NSW–PSID sample and requires a connection. The tested version emits a numerical warning when calculating the point robustness value: the warning is displayed and the result checked rather than hidden.
"""Compara las fórmulas con PySensemakr en los mismos datos NSW-PSID."""
import importlib.metadata as metadata
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
import sensemakr
print('PySensemakr', metadata.version('PySensemakr'))
url = 'https://vincentarelbundock.github.io/Rdatasets/csv/DAAG/nsw74psid1.csv'
data = pd.read_csv(url)
covariates = ['age', 'educ', 'black', 'hisp', 'marr', 'nodeg', 're74', 're75']
design = sm.add_constant(data[['trt'] + covariates])
model = sm.OLS(data['re78'], design).fit()
beta = float(model.params['trt'])
se = float(model.bse['trt'])
dof = int(model.df_resid)
x, y = 0.01, 0.02
bias = se * np.sqrt(dof*x*y/(1-x))
adjusted = beta - np.sign(beta)*bias
adjusted_se = se*np.sqrt((1-y)/(1-x)*dof/(dof-1))
f = abs(beta/se)/np.sqrt(dof)
rv = (np.sqrt(f**4+4*f*f)-f*f)/2
library_adjusted = float(np.asarray(sensemakr.adjusted_estimate(
r2dz_x=x,r2yz_dx=y,estimate=beta,se=se,dof=dof,reduce=True)).squeeze())
library_se = float(np.asarray(sensemakr.adjusted_se(
r2dz_x=x,r2yz_dx=y,se=se,dof=dof)).squeeze())
with warnings.catch_warnings(record=True) as notices:
warnings.simplefilter('always', RuntimeWarning)
library_rv = float(np.asarray(sensemakr.robustness_value(
t_statistic=beta/se,dof=dof)).squeeze())
for notice in notices:
print('Aviso de la biblioteca:', str(notice.message))
np.testing.assert_allclose([adjusted,adjusted_se,rv],
[library_adjusted,library_se,library_rv],rtol=1e-10)
print('OLS NSW-PSID:', round(beta,4),'EE clásico:',round(se,4),'gl:',dof)
print('rT, rY:',x,y,'coeficiente orientado hacia cero:',round(adjusted,4))
print('EE ajustado:',round(adjusted_se,4),'RV del punto:',round(rv,6))
print('PySensemakr y fórmulas propias coinciden.')npm run lab and open the connection link.Exercises
Step 1 of 4. What expression does FWL give for the change when adding U?
def rosenbaum_bounds(differences, gamma):
# Calcula rangos y colas exactas para las dos probabilidades extremas.
raise NotImplementedErrorAfter attempting the numeric exercises, check the calculations:
print('E-values:', e_value(2.5), e_value_interval(1.4, 4.0))
print('Cotas de Manski:', cotas_manski(.4, .7, .5))