Module contents
Lesson 17 of 28Advanced 95 min

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 YY on treatment TT and controls XX, imagine adding scalar confounder UU. The omitted-variable formula compares coefficients of the two regressions. Partial-R² sensitivity analysis by Cinelli and Hazlett parameterizes unknown associations by

rT=RT∼U∣X2,rY=RY∼U∣T,X2.r_T=R^2_{T\sim U\mid X},\qquad r_Y=R^2_{Y\sim U\mid T,X}.

In terms of the observed regression, with classical OLS standard error ss and dd residual degrees of freedom,

∣β^restringida−β^completa∣=sdrYrT1−rT.|\widehat\beta_{\rm restringida}-\widehat\beta_{\rm completa}| =s\sqrt{d\frac{r_Yr_T}{1-r_T}}.

Derive it as follows. Residualize TT and UU against XX and call those residuals t,ut,u. Also residualize YY and uu against TT and call the results y⊥,u⊥y_\perp,u_\perp. By Frisch–Waugh–Lovell, the coefficient difference is (t⊤u/t⊤t)(u⊥⊤y⊥/u⊥⊤u⊥)(t^\top u/t^\top t)(u_\perp^\top y_\perp/u_\perp^\top u_\perp). The squared correlations are rT=(t⊤u)2/[(t⊤t)(u⊤u)]r_T=(t^\top u)^2/[(t^\top t)(u^\top u)] and rY=(u⊥⊤y⊥)2/[(u⊥⊤u⊥)(y⊥⊤y⊥)]r_Y=(u_\perp^\top y_\perp)^2/[(u_\perp^\top u_\perp)(y_\perp^\top y_\perp)]. Since u⊥⊤u⊥=(1−rT)u⊤uu_\perp^\top u_\perp=(1-r_T)u^\top u and s2=(y⊥⊤y⊥)/(d t⊤t)s^2=(y_\perp^\top y_\perp)/(d\,t^\top t), 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 ss 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

scompleto=s1−rY1−rTdd−1.s_{\rm completo}=s\sqrt{\frac{1-r_Y}{1-r_T}\frac{d}{d-1}}.

The point robustness value is the smallest possible max⁡(rT,rY)\max(r_T,r_Y) 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 f=∣β^∣/(sd)f=|\widehat\beta|/(s\sqrt d) it follows by imposing rT=rY=rr_T=r_Y=r:

RV=f4+4f2−f22.RV=\frac{\sqrt{f^4+4f^2}-f^2}{2}.

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.

InteractiveSensitivity contours

Each curve collects combinations producing the same coefficient if bias acts to reduce it. The movable point is a hypothetical confounder; numbered circles are vertices of formal bounds relative to age.

0.00.01.51.53.03.04.54.56.06.01×2×3×RVR² with treatment (%)R² with outcome (%)
  • 500 $
  • 250 $
  • 0 $
  • -250 $
  • Equal-strength diagonal

NSW-PSID data: OLS of 1978 earnings on treatment, age, education, demographic indicators and 1974 and 1975 earnings. The lesson cell reproduces 2675 observations, coefficient 751.95 $, classical standard error 915.26 $ and 2665 degrees of freedom. The initial classical interval already includes zero: significance RV is zero. Point RV is where the diagonal crosses the zero contour, not proof of causality.

The 1×, 2× and 3× vertices apply the formal bound of Cinelli and Hazlett using age as a benchmark in both models. The confounder is compared after residualizing on covariates; at those vertices the vertical coordinate is an upper bound, not an observed value. This comparison is an assumption about an unmeasured cause. Partial R² values do not indicate bias direction or guarantee the absence of other omitted causes. This is OLS sensitivity, not the prior lesson’s IPW.

1.0 %
1.0 %
Initial OLS coefficient751.95 $
Maximum bias in this direction474.87 $
Adjusted coefficient277.08 $
RV to bring point estimate to zero1.58 %
RV to lose significance at 5%0 %
Move the hypothetical confounder and compare the OLS coefficient with age benchmark bounds.

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 UU 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 RR>1RR>1, the E-value is

E(RR)=RR+RR(RR−1).E(RR)=RR+\sqrt{RR(RR-1)}.

Its interpretation relies on the bound of Ding and VanderWeele: if a,b≥1a,b\ge1 bound relevant unmeasured-confounder associations with treatment and outcome on the risk-ratio scale, a maximum bias factor is B=ab/(a+b−1)B=ab/(a+b-1). If both associations are bounded by the same MM, BB increases in each argument and B≤M2/(2M−1)B\le M^2/(2M-1). To explain RRRR to the null, B≥RRB\ge RR is necessary; solving M2/(2M−1)=RRM^2/(2M-1)=RR yields the earlier root.

More specifically, in each observed-covariate stratum X=xX=x, aa can bound the largest ratio P(U=u∣T=1,x)/P(U=u∣T=0,x)P(U=u\mid T=1,x)/P(U=u\mid T=0,x) across levels of UU. Parameter bb can bound the largest risk ratio for YY across two levels of UU, within each arm and stratum xx. 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 max⁡(a,b)\max(a,b) 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 dd, approximation RR≈exp⁡(0,91d)RR\approx\exp(0{,}91d) 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 Γ≥1\Gamma\ge1 despite equal observed covariates. Conditioning on absolute differences, the upper one-sided signed-rank test uses Tobs=∑iqiI(Δi>0)T_{\rm obs}=\sum_iq_iI(\Delta_i>0) with nonnegative ranks qiq_i.

Under the sharp null of zero individual effect, independent assignment across pairs, and the odds model, each pair’s positive-sign probability lies in [1/(1+Γ),Γ/(1+Γ)][1/(1+\Gamma),\Gamma/(1+\Gamma)]. 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 Γ=1\Gamma=1 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 qiq_i redistribute mass: fraction 1−pi1-p_i keeps the sum and fraction pip_i shifts by qiq_i. At the end, sum mass at values at least TobsT_{\rm obs}. Average tied ranks may be half-integers; doubling them preserves comparison and permits integer indexing. Zero differences are discarded according to the stated convention.

InteractiveIncrease Γ until rejection changes

For each Γ, the curves bound the upper one-sided p-value under assignments compatible with that degree of bias. The vertical scale is logarithmic: do not mistake its bottom for zero.

110⁻510⁻1010⁻1510⁻2010⁻250.051358Γ
  • lower p
  • upper p
  • Threshold 0.05

Rejection at the 0.05 level holds for every assignment allowed by this Γ. This does not show that such hidden bias actually exists.

Published example: 39 disjoint pairs of welders and controls, with T=715 and no tied ranks. The exact calculation uses P(Σᵢ iBᵢ ≥ 715), i=1,…,39, with independent Bᵢ of probability 1/(1+Γ) for the lower bound and Γ/(1+Γ) for the upper. Pairs are conditioned on one treated and one control; Γ bounds the assignment odds ratio within a pair.

This is a one-sided test of the sharp null of zero effect, not a general ATE test or an interval for the effect. Source: Rosenbaum, Design of Observational Studies, §§3.5 y 3.9. As context, Rosenbaum (2007) mentions another tobacco and lung-cancer study insensitive to Γ=5; it is not the study shown or an exact critical threshold.

1.00
Lower p3.124e-7
Upper p3.124e-7
Crossing of 0.05Γ ≈ 4.063
Curves show one-sided p-value bounds under a sharp null and disjoint pairs.

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 Y(0),Y(1)∈[0,1]Y(0),Y(1)\in[0,1], consistency decomposes each potential mean into its observed and missing parts. Write p=P(T=1)p=P(T=1), μ1=E[Y∣T=1]\mu_1=E[Y\mid T=1] and μ0=E[Y∣T=0]\mu_0=E[Y\mid T=0]. Without selection assumptions,

pμ1−(1−p)μ0−p≤E[Y(1)−Y(0)]≤pμ1+(1−p)−(1−p)μ0.p\mu_1-(1-p)\mu_0-p \le E[Y(1)-Y(0)] \le p\mu_1+(1-p)-(1-p)\mu_0.

The unknown part of E[Y(1)]E[Y(1)] belongs to [0,1−p][0,1-p] and that of E[Y(0)]E[Y(0)] to [0,p][0,p]. 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 Y(1)≥Y(0)Y(1)\ge Y(0) implies nonnegative ATE. Monotone increasing selection imposes E[Y(t)∣T=1]≥E[Y(t)∣T=0]E[Y(t)\mid T=1]\ge E[Y(t)\mid T=0] 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 ZZ; it is not by itself classical instrument independence or individual compliance monotonicity.

For example, let a=E[Y(1)∣T=0]a=E[Y(1)\mid T=0] and b=E[Y(0)∣T=1]b=E[Y(0)\mid T=1]. Under monotone increasing selection, a≤μ1a\le\mu_1 and b≥μ0b\ge\mu_0. Expression ATE=p(μ1−b)+(1−p)(a−μ0)ATE=p(\mu_1-b)+(1-p)(a-\mu_0) is then at most μ1−μ0\mu_1-\mu_0; the assumption-free lower bound remains attainable when other restrictions allow it. Adding monotone response also imposes ATE≥0ATE\ge0. If the resulting upper bound is negative, no distribution is compatible with both assumptions and the observed probabilities.

InteractiveFrom bounds to a point, if assumptions permit

The gray segment shows ATEs compatible with the data without optional restrictions; the colored segment shows the set compatible with active assumptions. A point indicates point identification.

BaseCurrent−1.0−0.50.00.51.0E[Y(1) − Y(0)]
  • Without optional assumptions
  • Active assumptions

Set: [−0.4100; 0.5900]. This is a population identification set, not a confidence interval.

Synthetic table of P(T,Y | Z), with P(Z=0)=P(Z=1)=0.5. In each row the columns are (T,Y)=(0,0), (0,1), (1,0), (1,1):

Z0001101100,510,110,130,2510,020,040,540,40

Y and both potential outcomes are binary; consistency is assumed. MTR requires Y(1)≥Y(0) for each person. MTS requires E[Y(a)|T=1]≥E[Y(a)|T=0] for a=0 and 1. MIV requires E[Y(a)|Z=1]≥E[Y(a)|Z=0] for both treatments: it does not claim Z is a valid IV or increases treatment for every person.

The last option requires (Y(0),Y(1)) independent of T, without conditioning on Z; both arms have positive probability. The table’s bounds are sharp solutions of a linear program over P(Y(0),Y(1),T | Z). All 16 states can be checked with the lesson model. Adding restrictions can empty the set. See Manski (1990) y Manski and Pepper (2000).

Lower bound−0.4100
Upper bound0.5900
Width1.0000
Add restrictions to the same observed distribution and detect incompatible combinations.

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.

[ ]nsw downloadBrowser
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.

[ ]cinelli setupBrowser
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))
[ ]cinelli nsw pyodideBrowser
# 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.

[ ]sensitivity examplesBrowser
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.

[ ]rosenbaum nsw 01 pairsBrowser
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.')
[ ]rosenbaum nsw 02 boundsBrowser
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.

[ ]manski boundsBrowser
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.

[ ]Check the builder’s 16 statesBrowser
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.

[ ]manski inferenceBrowser
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.

[ ]Exact coverage in the binomial exampleBrowser
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.

[ ]manski nswBrowser
# `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')
[ ]manski nsw ipwBrowser
# 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.

[ ]Check with PySensemakrLocal GPU
"""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.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofFrom omitted variable to R²
Prove: In OLS with an omitted scalar confounder UU, full rank and positive residual variances, prove the identity for the magnitude of coefficient change using the classical standard error ss and degrees of freedom dd of the restricted regression.
The proof will appear here as you work.

Step 1 of 4. What expression does FWL give for the change when adding U?

NumericPoint E-value
An estimated risk ratio is 2.5. What is its E-value? Round to three decimal places.
NumericInterval E-value
A risk ratio above one has confidence interval limits 1.4 and 4. Calculate the interval E-value to three decimal places.
NumericLower bound without ignorability
Under consistency and binary potential outcomes, P(T=1)=0.4, mean Y among treated is 0.7 and among controls 0.5. Calculate the Manski lower bound for ATE without assuming ignorability.
NumericUpper bound without ignorability
Under consistency and binary potential outcomes, P(T=1)=0.4, treated mean 0.7 and control mean 0.5, calculate the Manski upper bound for ATE without assuming ignorability.
CodeExact p-value bounds
Implement rosenbaum_bounds(differences, gamma) and return exact lower and upper one-sided upper-tail p-value bounds for the signed-rank statistic. differences is a finite vector of treated-minus-control differences from disjoint pairs; gamma is finite and at least one. Omit zero differences; if none remain or inputs are invalid, raise ValueError. Assign tied absolute magnitudes their average rank, calculate the observed sum of positive ranks, and for each p in 1/(1+gamma) and gamma/(1+gamma), exactly calculate the probability that a rank sum weighted by independent Bernoulli variables with parameter p is at least the observed sum. Average ranks are integers or half-integers: you can double them and use a discrete distribution obtained by convolution. This analysis corresponds to a sharp null of no effect in every individual and Rosenbaum’s assignment-bias model; it does not interpret a weak ATE null.
def rosenbaum_bounds(differences, gamma):
  # Calcula rangos y colas exactas para las dos probabilidades extremas.
  raise NotImplementedError
Shift+Enter to run
QuizTwo robustness values
Two regressions have point robustness values of 4% and 30%, calculated under the same definition. What conclusion is supported?
QuizWhat an E-value requires
If an association has E-value E, which statement about two hypothetical confounding associations is correct?
QuizMatching with replacement
One control appears in several pairs. Can you apply Rosenbaum’s independent-sign distribution for disjoint pairs unchanged?

After attempting the numeric exercises, check the calculations:

[ ]Check the numeric exercisesBrowser
print('E-values:', e_value(2.5), e_value_interval(1.4, 4.0))
print('Cotas de Manski:', cotas_manski(.4, .7, .5))