Module contents
Lesson 23 of 28Advanced 110 min

Counterfactuals, probabilities of causation and mediation

Structural counterfactuals connect alternative worlds using abduction, action, and prediction. Study twin networks, identification limits, probabilities of causation, and natural and controlled mediation effects.

After this lesson you can

  • Calculate SCM counterfactuals using abduction, action, and prediction.
  • Construct a twin network and examine its counterfactual independences.
  • Show observationally and interventionally equivalent models can disagree on counterfactuals.
  • Calculate Tian–Pearl bounds for probabilities of necessity and sufficiency.
  • Estimate natural direct and indirect effects and discuss mediation assumptions.

Before you start

The incident occurred; what with the patch?

A server suffered an incident and did not receive a patch. Asking what incident rate a patching policy would produce is a population intervention question. Asking whether that same incident would have occurred with the patch requires linking the observed world to another that was never observed. More than a difference in rates is needed: a structure must connect both worlds.

InteractiveAbduction, action, and prediction

Known structural model: X=Uₓ; Z=1+2X+U𝓏; Y=3+0.5X+1.5Z+Uᵧ. The noises are independent standard normals. Observing all three variables determines each noise in this model.

Uₓ = 1.0X1.0U𝓏 = 0.0Z3.0Uᵧ = 0.0Y8.0Observed world
1. Abduction

Abduction. From the observation we infer Uₓ=1.0, U𝓏=0.0 and Uᵧ=0.0. This inversion uses all three equations and the complete observation.

This is an individual answer conditional on the chosen model. Different structural functions or missing observations could yield a different or uncertain counterfactual inference.

1.0
3.0
8.0
-1.0
U of X1.0
U of Z0.0
U of Y0.0
Counterfactual Ypending
Observe how evidence fixes noises and how they propagate in the alternative world.

Abduction, action, and prediction

A structural causal model assigns each variable an equation and a joint distribution of exogenous disturbances UU. The structural counterfactual Yx(u)Y_x(u) is the value of YY after replacing the equation for XX with X=xX=x, retaining the unit’s same uu. Given evidence E=eE=e proceed in three steps:

  1. Abduction: update P(U∣E=e)P(U\mid E=e) using the equations and probability model.
  2. Action: replace the equation for XX with the hypothetical value; do not change remaining equations or resample a new individual.
  3. Prediction: propagate values of UU compatible with the evidence through the intervened model and average if abduction leaves uncertainty.

For example, consider X=UXX=U_X, M=2X+UMM=2X+U_M and Y=X+3M+UYY=X+3M+U_Y. If X=x′X=x', M=mM=m and Y=yY=y are observed, the equations fix UM=m−2x′U_M=m-2x' and UY=y−x′−3mU_Y=y-x'-3m. Under do(X=x)do(X=x), Mx=m+2(x−x′)M_x=m+2(x-x') and Yx=y+7(x−x′)Y_x=y+7(x-x'). Seven is the total effect through both paths in this model. If only some variables are observed, evidence may leave a distribution of noise terms rather than one vector.

In discrete models multiple exogenous configurations may explain the same observation. Exact abduction weights them by posterior probability; sampling must condition on evidence and retain the same noise terms under intervention. Rejection with few accepted cases may be inefficient; it does not turn posterior uncertainty into a known individual value.

A network for two worlds

A twin network duplicates endogenous variables: one copy follows factual equations and the other follows intervened equations. Both share the same exogenous variables. Evidence enters the factual copy and do(X=x)do(X=x) replaces the relevant equation in the hypothetical copy. The shared connection lets us calculate, for example, P(Yx=0∣X=0,Y=1)P(Y_x=0\mid X=0,Y=1) under the specified SCM.

This construction links potential outcomes with structural equations: YxY_x and Yx′Y_{x'} use different fixed values of XX but the same UU. Twin-network independences are read from the augmented graph and also depend on observed variables; they must not be assumed because copies have different labels. A particular model determines cross-world coupling, but data may not determine that model.

In the preceding linear example, if noises are mutually independent and UMU_M is nondegenerate, XX is independent of Mx=2x+UMM_x=2x+U_M. Yet MM and MxM_x still share UMU_M even conditioning on XX: they are not independent because they belong to separate copies. Also knowing M=mM=m fixes UMU_M by the equation and determines MxM_x in that model.

Same interventions, another individual history

Counterfactual identification requires all models compatible with available information to answer identically. Let U∼Unif⁡(0,1)U\sim\operatorname{Unif}(0,1) and XX independent of UU. In two SCMs, Y1=1{U<0.7}Y_1=1\{U<0.7\}; in the first Y0=1{U<0.3}Y_0=1\{U<0.3\} and in the second Y0=1{U>0.7}Y_0=1\{U>0.7\}. The factual outcome is Y=YXY=Y_X.

Both models give P(Y=1∣do(X=1))=0.7P(Y=1\mid do(X=1))=0.7 and P(Y=1∣do(X=0))=0.3P(Y=1\mid do(X=0))=0.3, and the same observational distribution if they use the same distribution of XX. Yet among treated units with Y=1Y=1, the probability of Y0=0Y_0=0 is 4/74/7 in the first and 11 in the second. Coupling of Y0Y_0 with Y1Y_1 changes, not their marginals. The first model satisfies monotonicity Y1≥Y0Y_1\ge Y_0; the second does not.

InteractiveSame interventions, different counterfactuals

The bands decompose the same population by its two potential outcomes. Both models have the same experimental rates and observational distribution, but may disagree on who would have responded without treatment.

Model A: aligned thresholds30 %40 %30 %Model B: opposite thresholds70 %30 %Each band sums to 100%
  • (Y₀,Y₁) = (0,0)
  • (0,1): benefit
  • (1,0): harm
  • (1,1)

Explicit model: U uniform on [0,1], independent X Bernoulli(1/2), and Y=Yₓ. In both, Y₀=1{U<p₀}. In A, Y₁=1{U<p₁}; in B, Y₁=1{U>1−p₁}. Thus P(Y=1|do(X=0))=30.0 % and P(Y=1|do(X=1))=70.0 % in both. P(X,Y) also agrees because X is independent of U.

The probability of necessity PN=P(Y₀=0 | X=1,Y=1) is the fraction of type (0,1) among treatment responders; PNS is the proportion of that type in the population. Under this randomized design, PN bounds are max(0,p₁−p₀)/p₁ and min(1,(1−p₀)/p₁); the two models attain the endpoints. Imposing monotonicity Y₁≥Y₀ when p₁≥p₀ removes the harm type and leaves the lower endpoint; if p₁<p₀ that monotonicity conflicts with the marginals. Bounds do not identify an individual response.

The two SCMs specify the cross-world coupling absent from separate distributions. See Tian y Pearl (2000).

0.30
0.70
PN aligned model57.1 %
PN opposite model100.0 %
PN bounds[57.1 %; 100.0 %]
PNS aligned / opposite40.0 % / 70.0 %
Compare compatible couplings and their probabilities of necessity.

Monotonicity, independent noises, or an additive-noise structural family can restrict that coupling. These are mechanism assumptions, not general consequences of knowing both interventional distributions. Even when an assumption identifies a population mean, uncertainty can remain about one unit’s counterfactual with partial evidence.

Necessity and sufficiency

For binary X,YX,Y, define Y1,Y0Y_1,Y_0 as outcomes under treatment and control. The probabilities of causation are

PN=P(Y0=0∣X=1,Y=1),PS=P(Y1=1∣X=0,Y=0),PNS=P(Y1=1,Y0=0).\begin{aligned} PN&=P(Y_0=0\mid X=1,Y=1),\\ PS&=P(Y_1=1\mid X=0,Y=0),\\ PNS&=P(Y_1=1,Y_0=0). \end{aligned}

PN asks about necessity among treated units with outcome; PS about sufficiency among controls without outcome; PNS about the fraction for whom treatment changes 00 to 11. Conditions require positive denominators. They are not interchangeable and must be interpreted according to the meaning of Y=1Y=1.

Let p1=P(Y1=1)p_1=P(Y_1=1) and p0=P(Y0=1)p_0=P(Y_0=1) be identified here by interventions. With only these two marginals, sharp Tian–Pearl PNS bounds are

max⁡(0,p1−p0)≤PNS≤min⁡(p1,1−p0).\max(0,p_1-p_0)\le PNS\le\min(p_1,1-p_0).

The lower bound follows because p1−p0p_1-p_0 subtracts the harmed type from the benefited type; the upper bound cannot exceed either marginal forming the intersection. Interventional data alone generally do not determine PN or PS conditional on factual treatment.

With compatible observational data from the same population, q11=P(X=1,Y=1)>0q_{11}=P(X=1,Y=1)>0, q00=P(X=0,Y=0)>0q_{00}=P(X=0,Y=0)>0 and r=P(Y=1)r=P(Y=1), we also obtain

max⁡(0,r−p0q11)≤PN≤min⁡(1,1−p0−q00q11),max⁡(0,p1−rq00)≤PS≤min⁡(1,p1−q11q00).\max\left(0,\frac{r-p_0}{q_{11}}\right) \le PN\le \min\left(1,\frac{1-p_0-q_{00}}{q_{11}}\right), \quad \max\left(0,\frac{p_1-r}{q_{00}}\right) \le PS\le \min\left(1,\frac{p_1-q_{11}}{q_{00}}\right).

Data and interventions must be consistent and refer to the same population; otherwise an interval must not be forced. With XX jointly independent of (Y0,Y1)(Y_0,Y_1), PN and PS equal PNS divided by p1p_1 and 1−p01-p_0 respectively. In the previous example, if P(X=1)=1/2P(X=1)=1/2, q11=q00=0.35q_{11}=q_{00}=0.35 and r=0.5r=0.5, PN and PS lie between 4/74/7 and 11, and PNS between 0.40.4 and 0.70.7.

Observational information can also narrow PNS bounds. If q10=P(X=1,Y=0)q_{10}=P(X=1,Y=0) and q01=P(X=0,Y=1)q_{01}=P(X=0,Y=1), sharp endpoints with both data sources are

LPNS=max⁡(0,p1−p0,r−p0,p1−r),UPNS=min⁡(p1,1−p0,q11+q00,p1−p0+q10+q01).\begin{aligned} L_{\rm PNS}&=\max(0,p_1-p_0,r-p_0,p_1-r),\\ U_{\rm PNS}&=\min(p_1,1-p_0,q_{11}+q_{00}, p_1-p_0+q_{10}+q_{01}). \end{aligned}

The lab verifies these endpoints using linear programming over the unknown joint distribution of (X,Y0,Y1)(X,Y_0,Y_1). The program imposes marginals, factual table, and consistency; it does not assume independence between XX and potential outcomes.

If Y1≥Y0Y_1\ge Y_0 for every unit, the harmed type disappears and PNS=p1−p0PNS=p_1-p_0. Monotonicity is a substantive assumption; observing a positive average effect does not verify it. These probabilities inform attribution under a defined model and population; they do not themselves turn a statistical conclusion into a legal or medical decision.

Direct and indirect effects

With mediator MM, write MxM_x and Yx,mY_{x,m} for potential outcomes. The controlled direct effect fixes the same value mm for everyone:

CDE(m)=E[Y1,m−Y0,m].CDE(m)=E[Y_{1,m}-Y_{0,m}].

Natural effects instead use the mediator each unit would take under another treatment. One decomposition of the total effect is

TE=E[Y1,M1−Y0,M0],NDEpuro=E[Y1,M0−Y0,M0],NIEtotal=E[Y1,M1−Y1,M0],TE=NDEpuro+NIEtotal.\begin{aligned} TE&=E[Y_{1,M_1}-Y_{0,M_0}],\\ NDE_{\rm puro}&=E[Y_{1,M_0}-Y_{0,M_0}],\\ NIE_{\rm total}&=E[Y_{1,M_1}-Y_{1,M_0}],\\ TE&=NDE_{\rm puro}+NIE_{\rm total}. \end{aligned}

One can also first move from M0M_0 to M1M_1 holding X=0X=0 fixed, then change XX with M1M_1: this gives NIEpuro+NDEtotalNIE_{\rm puro}+NDE_{\rm total}. Both sums yield the same total, but with interaction their components need not coincide. CDE fixes a chosen MM value; NDE uses the individual counterfactual distribution M0M_0 or M1M_1.

InteractiveDecompose the total effect

Each bar measures an average effect in Y units. The two natural effects shown sum to the total; changing the order redistributes the interaction between them. Controlled effects fix M at the same value for all units.

Total effect1.98Pure direct0.70Total indirect1.28Controlled m=00.40Controlled m=11.00Controlled m=21.600Average change in Y

Explicit SCM: X is Bernoulli(1/2), M=0.5+αX+Uₘ and Y=βX+γM+δXM+Uᵧ. The zero-mean normal errors are independent of each other and X. Bars are exact model expectations, without a simulated sample.

Let M₀ and M₁ be the mediators under X=0 and X=1. Changing X first gives pure direct E[Y(1,M₀)−Y(0,M₀)]=β+0.5δ and total indirect E[Y(1,M₁)−Y(1,M₀)]=α(γ+δ). Changing the mediator first gives pure indirect αγ and total direct β+δ(0.5+α). Both sums are β+αγ+δ(0.5+α). The controlled direct effect is β+δm.

Here independent errors give the SCM’s cross-world conditions and no mediator confounder is affected by X. In real data, identifying natural effects requires additional assumptions, including positivity and appropriate absence of confounding; it does not follow solely from observing X, M and Y. See Pearl (2001).

0.8
0.4
1.0
0.6
Decomposition order
Total effect1.98
Natural direct0.70
Natural indirect1.28
Change interaction and compare two natural decompositions and controlled effects.

For a discrete mediator and prior covariates CC, one version of Pearl’s mediation formula is

E[Yx,Mx′]=∑cP(c)∑mE[Y∣X=x,M=m,C=c]P(M=m∣X=x′,C=c).E[Y_{x,M_{x'}}] =\sum_cP(c)\sum_m E[Y\mid X=x,M=m,C=c]P(M=m\mid X=x',C=c).

Identification requires consistency, positivity, and no-confounding conditions for treatment–outcome, treatment–mediator, and mediator–outcome given appropriate covariates, together with cross-world independence justifying combination of Yx,mY_{x,m} with Mx′M_{x'}. An acyclic SCM with independent noises, observed covariates blocking those confounding paths, and no treatment-affected mediator–outcome confounders provides a sufficient set of conditions. Randomizing XX alone does not guarantee them. If a mediator confounder is affected by XX, the simple natural formula may fail even when adjusting observed variables.

Interventional indirect effects replace the individual mediator from another world with a draw from a policy-defined mediator distribution; they change the estimand and may be identified under different assumptions. Semiparametric mediation estimators use outcome and assignment models and may include influence corrections, but robustness properties depend on the specific formulation: they do not replace causal assumptions.

For example, for ψ=E[Y1,M0]\psi=E[Y_{1,M_0}], let e(c)=P(X=1∣C=c)e(c)=P(X=1\mid C=c), ga(m∣c)=P(M=m∣X=a,C=c)g_a(m\mid c)=P(M=m\mid X=a,C=c), μ1(m,c)=E[Y∣X=1,M=m,C=c]\mu_1(m,c)=E[Y\mid X=1,M=m,C=c] and η(c)=∑mμ1(m,c)g0(m∣c)\eta(c)=\sum_m\mu_1(m,c)g_0(m\mid c). Assume 0<e(C)<10<e(C)<1 and g1(m∣C)>0g_1(m\mid C)>0 where g0(m∣C)>0g_0(m\mid C)>0. A score whose expectation is ψ\psi under the true models is

η(C)+1{X=1}e(C)g0(M∣C)g1(M∣C){Y−μ1(M,C)}+1{X=0}1−e(C){μ1(M,C)−η(C)}.\eta(C)+\frac{1\{X=1\}}{e(C)} \frac{g_0(M\mid C)}{g_1(M\mid C)} \{Y-\mu_1(M,C)\} +\frac{1\{X=0\}}{1-e(C)} \{\mu_1(M,C)-\eta(C)\}.

The first residual corrects the outcome model among treated units and reweights their mediator toward the control distribution; the second corrects mediator integration using controls. Replace functions with estimates and average the score; with cross-fitting and regularity conditions, standard errors can be built from its influence. For example, if μ1\mu_1 and g0g_0 are correct, both residuals have mean zero even if other denominator models are incorrect, provided denominators remain bounded away from zero and weights are integrable. The direct effect is ψ\psi minus the identified mean of Y0,M0Y_{0,M_0}. Full multiple robustness and inference conditions require specifying the estimator, as in Tchetgen Tchetgen and Shpitser (2012); no combination of statistical models by itself repairs a false causal assumption.

Lab: counterfactuals and mediation

Cells compute exact probabilities from explicit models alongside reproducible simulations. Queries answer within the given SCM; a program computing them does not prove the SCM describes the real system.

Start with exact noise abduction in a fully observed linear SCM; then intervene and propagate.

[ ]engine 01 additiveBrowser
# Un SCM lineal con variables observadas sin error.
# X=U_X; Z=2X+U_Z; Y=3Z-X+U_Y.
def contrafactual_lineal(x, z, y, x_nuevo):
    u_x = x
    u_z = z - 2*x
    u_y = y - 3*z + x
    z_nuevo = 2*x_nuevo + u_z
    y_nuevo = 3*z_nuevo - x_nuevo + u_y
    return {'ruidos': (u_x, u_z, u_y), 'X': x_nuevo,
            'Z': z_nuevo, 'Y': y_nuevo}

observado = (1., 5., 8.)
alternativo = contrafactual_lineal(*observado, 0.)
factual = contrafactual_lineal(*observado, observado[0])
assert alternativo['ruidos'] == (1., 3., -6.)
assert alternativo['Z'] == 3 and alternativo['Y'] == 3
assert (factual['X'], factual['Z'], factual['Y']) == observado
print('Ruidos inferidos:', alternativo['ruidos'])
print('Con do(X=0): Z =', alternativo['Z'], ', Y =', alternativo['Y'])

Now build a binary engine with tables and uniform noises. Tables match the probability representation from the SCM lesson; threshold orientation specifies cross-world coupling.

[ ]engine 02 discreteBrowser
import numpy as np

class SCMContrafactual:
    """SCM binario acíclico, tablas de l11 y ruido uniforme compartido.

    specs contiene (nodo, padres, P(nodo=1|padres)) en orden topológico.
    reverse contiene pares (nodo, índice de padres): allí se usa U>=1-p
    en vez de U<p. Cambia el acoplamiento entre mundos, no las tablas.
    Los ruidos de nodos distintos son independientes en este modelo.
    """
    def __init__(self, specs, reverse=()):
        self.specs, seen = [], set()
        for name, parents, probabilities in specs:
            parents, prob = tuple(parents), np.asarray(probabilities, float)
            if (not isinstance(name,str) or not name or name in seen
                or len(set(parents)) != len(parents)
                or any(p not in seen for p in parents)
                or prob.shape != (2**len(parents),)
                or not np.isfinite(prob).all() or np.any((prob<0)|(prob>1))):
                raise ValueError('Modelo o tabla inválidos')
            self.specs.append((name, parents, prob))
            seen.add(name)
        if not self.specs:
            raise ValueError('El modelo no puede estar vacío')
        self.names = tuple(name for name, _, _ in self.specs)
        valid = {(name, i) for name, _, probs in self.specs for i in range(len(probs))}
        self.reverse = set(reverse)
        if not self.reverse <= valid:
            raise ValueError('Acoplamiento inverso no reconocido')

    def ruido(self, n, seed):
        if not isinstance(n, int) or n <= 0:
            raise ValueError('n debe ser entero positivo')
        rng = np.random.default_rng(seed)
        return {name: rng.random(n) for name in self.names}

    def evaluar(self, u, do=None):
        do = {} if do is None else do
        if not isinstance(do,dict) or not set(do)<=set(self.names) or any(v not in (0,1) for v in do.values()):
            raise ValueError('Intervención inválida')
        if not isinstance(u,dict) or set(u)!=set(self.names):
            raise ValueError('Es necesario un ruido por nodo')
        sizes = {len(v) for v in u.values()}
        if len(sizes)!=1 or any(np.ndim(v)!=1 or not np.isfinite(v).all() or np.any((v<0)|(v>=1)) for v in u.values()):
            raise ValueError('Los ruidos deben ser vectores uniformes válidos')
        n = sizes.pop()
        result = {}
        for name, parents, prob in self.specs:
            if name in do:
                result[name] = np.full(n, do[name], dtype=int)
                continue
            idx = np.zeros(n,dtype=int)
            for parent in parents:
                idx = 2*idx + result[parent]
            p = prob[idx]
            reverse = np.isin(idx, [i for node,i in self.reverse if node==name])
            result[name] = np.where(reverse, u[name]>=1-p, u[name]<p).astype(int)
        return result

    def abducir(self, evidencia, n, seed):
        if not isinstance(evidencia,dict) or not set(evidencia)<=set(self.names) or any(v not in (0,1) for v in evidencia.values()):
            raise ValueError('Evidencia inválida')
        u = self.ruido(n, seed)
        factual = self.evaluar(u)
        mask = np.ones(n, dtype=bool)
        for key, value in evidencia.items():
            mask &= factual[key] == value
        if not np.any(mask):
            raise ValueError('Ninguna muestra compatible; comprueba soporte o aumenta n')
        return {key:value[mask] for key,value in u.items()}, int(mask.sum())

    def gemela(self, u, do):
        """Dos mundos, mismas realizaciones exógenas."""
        return self.evaluar(u), self.evaluar(u, do)

Use the same noise in the factual network and both intervened networks to compare models A and B. Simulated frequencies approximate known probabilities; they do not replace them.

[ ]engine 03 twinBrowser
# Mismas tablas y, por tanto, mismas marginales observadas e intervenidas.
# B invierte la orientación del umbral de Y cuando X=0.
specs = [('X', (), (.5,)), ('Y', ('X',), (.3, .7))]
modelo_a = SCMContrafactual(specs)
modelo_b = SCMContrafactual(specs, reverse={('Y', 0)})
for nombre, modelo in [('A',modelo_a), ('B',modelo_b)]:
    u = modelo.ruido(120_000, 272123)
    factual, y0_mundo = modelo.gemela(u, {'X':0})
    _, y1_mundo = modelo.gemela(u, {'X':1})
    factual1 = (factual['X']==1)&(factual['Y']==1)
    pn_gemela = np.mean(y0_mundo['Y'][factual1]==0)
    pns_gemela = np.mean((y0_mundo['Y']==0)&(y1_mundo['Y']==1))
    # Abducción por rechazo, seguida de acción y predicción.
    posterior, aceptadas = modelo.abducir({'X':1, 'Y':1}, 120_000, 272123)
    pn_abduccion = np.mean(modelo.evaluar(posterior, {'X':0})['Y']==0)
    assert pn_abduccion == pn_gemela
    se = np.sqrt(pn_gemela*(1-pn_gemela)/aceptadas)
    tabla_obs = np.array([[np.mean((factual['X']==x)&(factual['Y']==y))
                           for y in (0,1)] for x in (0,1)])
    print(nombre, 'P(Y=1|do X=0):', round(y0_mundo['Y'].mean(),4),
          'P(Y=1|do X=1):', round(y1_mundo['Y'].mean(),4),
          'PN:', round(pn_gemela,4), 'PNS:', round(pns_gemela,4),
          'aceptadas:', aceptadas, 'EE Monte Carlo:', round(se,5))
    print('Tabla observacional P(X,Y), filas X y columnas Y:\n', np.round(tabla_obs,4))
    np.testing.assert_allclose(tabla_obs,[[.35,.15],[.15,.35]],atol=.01,rtol=0)
    exacto = 4/7 if nombre == 'A' else 1.
    assert abs(pn_gemela-exacto) < 5*se + 1e-12
print('Valores exactos por longitudes de intervalo: PN A=4/7, B=1; PNS A=0,4, B=0,7.')

Load the linear optimizer that will verify bounds.

[ ]engine 04 importBrowser
from scipy.optimize import linprog
from itertools import product

Calculate bounds with observational and interventional data and verify endpoints as linear programs. Probabilities are treated as exactly known, without sampling uncertainty.

[ ]engine 05 boundsBrowser
def cotas_causacion(p0, p1, observada):
    """Cotas de Tian y Pearl y verificación con LP sobre (X,Y0,Y1).

    observada[x,y]=P(X=x,Y=y). Ambos estudios apuntan a la misma población.
    Las probabilidades de entrada se tratan como exactas, no como estimaciones
    con incertidumbre muestral. Devuelve None para PN o PS si su condición
    factual tiene probabilidad cero.
    """
    obs = np.asarray(observada, dtype=float)
    if (obs.shape != (2,2) or not np.isfinite(obs).all()
        or np.any(obs<0) or not np.isclose(obs.sum(),1,atol=1e-12,rtol=0)
        or not np.isfinite(p0) or not np.isfinite(p1)
        or not 0<=p0<=1 or not 0<=p1<=1):
        raise ValueError('Probabilidades inválidas')
    p00,p01,p10,p11 = obs.ravel()
    py = p01+p11
    # P(X=x,Y=y) = P(X=x,Y_x=y), por consistencia.
    states = list(product((0,1),repeat=3))
    A = np.asarray([[1]*8, [y0 for x,y0,y1 in states],
        [y1 for x,y0,y1 in states]] + [
        [int(x==xx and (y0 if x==0 else y1)==yy) for x,y0,y1 in states]
        for xx,yy in product((0,1),repeat=2)],float)
    b = np.r_[1.,p0,p1,obs.ravel()]
    feasible = linprog(np.zeros(8), A_eq=A, b_eq=b, bounds=(0,None), method='highs')
    if not feasible.success:
        raise ValueError('Datos experimentales y observados incompatibles')
    formulas = {
        'PNS': (max(0.,p1-p0,py-p0,p1-py),
                min(p1,1-p0,p11+p00,p1-p0+p10+p01)),
        'PN': None if p11==0 else (max(0.,(py-p0)/p11),min(1.,(1-p0-p00)/p11)),
        'PS': None if p00==0 else (max(0.,(p1-py)/p00),min(1.,(p1-p11)/p00))}
    objetivos = {
        'PNS': [int(y0==0 and y1==1) for x,y0,y1 in states],
        'PN': [int(x==1 and y0==0 and y1==1) for x,y0,y1 in states],
        'PS': [int(x==0 and y0==0 and y1==1) for x,y0,y1 in states]}
    denominadores = {'PNS':1.,'PN':p11,'PS':p00}
    for key, formula in formulas.items():
        if formula is None:
            continue
        obj = np.asarray(objetivos[key],float)
        lo = linprog(obj,A_eq=A,b_eq=b,bounds=(0,None),method='highs')
        hi = linprog(-obj,A_eq=A,b_eq=b,bounds=(0,None),method='highs')
        if not lo.success or not hi.success:
            raise RuntimeError('No se resolvió la comprobación de cotas')
        lp = (lo.fun/denominadores[key], -hi.fun/denominadores[key])
        np.testing.assert_allclose(formula,lp,atol=1e-8,rtol=0)
    return formulas

# Tabla 2 hipotética de Tian y Pearl (2000), no un estudio real.
obs = np.array([[972,28],[998,2]],dtype=float)/2000
cotas = cotas_causacion(.014,.016,obs)
for nombre in ('PNS','PN','PS'):
    print(nombre, 'cotas:', cotas[nombre])
np.testing.assert_allclose(cotas['PNS'], [.002,.016],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas['PN'], [1.,1.],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas['PS'], [.001/.486,.015/.486],atol=1e-10,rtol=0)

# Ejercicio adicional con selección: P(Y1=1)=0,7, P(Y0=1)=0,3.
obs_2 = np.array([[.15,.15],[.05,.65]])
cotas_2 = cotas_causacion(.3,.7,obs_2)
print('Ejemplo adicional:',cotas_2)
np.testing.assert_allclose(cotas_2['PN'], [10/13,11/13],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas_2['PNS'], [.5,.6],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas_2['PS'], [0,1/3],atol=1e-10,rtol=0)

# La primera tabla supone X independiente de (Y0,Y1) para los dos modelos A/B.
cotas_ab = cotas_causacion(.3,.7,[[.35,.15],[.15,.35]])
np.testing.assert_allclose(cotas_ab['PN'], [4/7,1],atol=1e-10,rtol=0)
print('Cotas PN de ambos modelos:',cotas_ab['PN'])

# Compatibilidad y condiciones de probabilidad cero.
try:
    cotas_causacion(0.,0.,[[0.,0.],[0.,1.]])
    raise AssertionError('Una tabla incompatible debe rechazarse')
except ValueError:
    pass
assert cotas_causacion(.5,.5,[[.5,.5],[0.,0.]])['PN'] is None
print('Datos incompatibles rechazados y PN indefinida con P(X=1,Y=1)=0.')

Implement the plug-in mediation formula for binary variables and compare with model-generated nested worlds. The reported standard error concerns paired differences, not a general causal interval.

[ ]mediation 01 functionsBrowser
import numpy as np

def mediacion_formula(a, m, y):
    """Fórmula plug-in de PNDE y TNIE para tratamiento y mediador binarios."""
    a, m, y = np.asarray(a), np.asarray(m), np.asarray(y, float)
    if a.ndim != 1 or m.shape != a.shape or y.shape != a.shape or len(a) == 0:
        raise ValueError('Se requieren tres vectores de igual longitud')
    if not np.isfinite(y).all() or not np.isin(a, [0,1]).all() or not np.isin(m, [0,1]).all():
        raise ValueError('Tratamiento y mediador deben ser binarios y resultado finito')
    p = np.empty(2)
    ip = np.empty((2, len(a)))
    q = np.empty((2, 2))
    iq = np.empty((2, 2, len(a)))
    for j in (0,1):
        sel = a == j
        if not sel.any():
            raise ValueError('Falta un grupo de tratamiento')
        p[j] = np.mean(m[sel])
        ip[j] = sel * (m-p[j]) / sel.mean()
        for k in (0,1):
            cell = sel & (m == k)
            if not cell.any():
                raise ValueError('Falta soporte en una celda tratamiento-mediador')
            q[j,k] = np.mean(y[cell])
            iq[j,k] = cell * (y-q[j,k]) / cell.mean()
    nde = (q[1,0]-q[0,0])*(1-p[0]) + (q[1,1]-q[0,1])*p[0]
    nie = (q[1,1]-q[1,0])*(p[1]-p[0])
    if_nde = ((1-p[0])*(iq[1,0]-iq[0,0]) + p[0]*(iq[1,1]-iq[0,1])
              + (q[1,1]-q[0,1]-q[1,0]+q[0,0])*ip[0])
    if_nie = ((p[1]-p[0])*(iq[1,1]-iq[1,0])
              + (q[1,1]-q[1,0])*(ip[1]-ip[0]))
    return {'nde':float(nde), 'nie':float(nie), 'p':p, 'q':q,
            'if_nde':if_nde, 'if_nie':if_nie}

def comparar_mundos(estimado, directo, indirecto):
    """Compara en las mismas unidades; incluye la covarianza pareada."""
    salida = []
    for key, diff in [('nde', directo), ('nie', indirecto)]:
        promedio = float(np.mean(diff))
        dif_estimadores = estimado[key] - promedio
        infl = estimado['if_'+key]-(diff-promedio)
        se = float(np.std(infl, ddof=1)/np.sqrt(len(diff)))
        salida.append((estimado[key], promedio, dif_estimadores, se))
    return salida

def imprimir_comparacion(nombre, r, direct, indirect):
    print(nombre)
    for nombre_efecto, (formula, nested, dif, se) in zip(
            ('PNDE','TNIE'), comparar_mundos(r, direct, indirect)):
        print(nombre_efecto, 'fórmula', round(formula,6),
              'mundos', round(nested,6), 'diferencia', round(dif,6),
              'EE Monte Carlo pareado', round(se,6))
    print('TE fórmula:', round(r['nde']+r['nie'],6))

In the first model change the treatment–mediator interaction. Without interaction on the linear scale, the coefficient product equals the relevant indirect effect; with interaction distinguish the decompositions.

[ ]mediation 02 linearBrowser
# SCM lineal, dos versiones sobre el mismo ruido y las mismas unidades.
rg = np.random.default_rng(272123)
n = 12000
A = rg.integers(0, 2, n)
um = rg.random(n)
M0, M1 = (um < .2).astype(float), (um < .6).astype(float)
M = np.where(A == 1, M1, M0)
eps = rg.normal(0, .2, n)
for delta in (0., .5):
    def f(a, m):
        return 1 + .3*a + .4*m + delta*a*m + eps
    Y = f(A, M)
    r = mediacion_formula(A, M, Y)
    directo = f(1, M0)-f(0, M0)
    indirecto = f(1, M1)-f(1, M0)
    imprimir_comparacion('Interacción delta = '+str(delta), r, directo, indirecto)
    beta = np.linalg.lstsq(np.column_stack([np.ones(n), A, M]), Y, rcond=None)[0]
    producto = (r['p'][1]-r['p'][0])*beta[2]
    print('Producto de regresión sin interacción:', round(float(producto),6))
    if delta == 0:
        print('Población: PNDE 0,3; TNIE 0,16; TE 0,46; producto 0,16')
    else:
        print('Población: PNDE 0,4; TNIE 0,36; TE 0,76; producto omitido 0,28')
        print('Alternativa: TNDE 0,6; PNIE 0,16; CDE(0) 0,3; CDE(1) 0,8')

In the binary SCM retain the same noise across worlds and compare the formula with simulated counterfactuals. Complete knowledge is available only because we construct the model here.

[ ]mediation 03 binaryBrowser
# Modelo binario del plan general. Ambos ruidos uniformes son independientes;
# se comparten entre mundos, tal como especifica este SCM concreto.
rg_b = np.random.default_rng(272124)
n_b = 12000
Ab = rg_b.integers(0,2,n_b)
umb, uyb = rg_b.random(n_b), rg_b.random(n_b)
Mb0 = (umb < .25).astype(float)
Mb1 = (umb < .75).astype(float)
Mb = np.where(Ab == 1, Mb1, Mb0)
def q_bin(a,m):
    return .1 + .2*a + .2*m + .3*a*m
def y_bin(a,m):
    return (uyb < q_bin(a,m)).astype(float)
Yb = y_bin(Ab, Mb)
rb = mediacion_formula(Ab, Mb, Yb)
imprimir_comparacion('Resultado binario, interacción en riesgo', rb,
                     y_bin(1,Mb0)-y_bin(0,Mb0),
                     y_bin(1,Mb1)-y_bin(1,Mb0))
print('Población: PNDE 0,275; TNIE 0,25; TE 0,525')
print('Alternativa: TNDE 0,425; PNIE 0,1; CDE(m) 0,2+0,3m')
print('Producto de coeficientes a A=0: 0,5×0,2=0,1, es PNIE, no TNIE.')

Finally use a logistic relationship without interaction in the index. Nonlinearity can make the coefficient product differ from the indirect effect on the probability scale.

[ ]mediation 04 logitBrowser
# En escala logit no hay término A*M; en riesgo la relación es no lineal.
rg_l = np.random.default_rng(272125)
n_l = 12000
Al = rg_l.integers(0,2,n_l)
uml, uyl = rg_l.random(n_l), rg_l.random(n_l)
Ml0 = (uml < .2).astype(float)
Ml1 = (uml < .6).astype(float)
Ml = np.where(Al == 1, Ml1, Ml0)
sigmoid = lambda z: 1/(1+np.exp(-z))
def y_logit(a,m):
    return (uyl < sigmoid(-2+.8*a+1.2*m)).astype(float)
Yl = y_logit(Al, Ml)
rl = mediacion_formula(Al, Ml, Yl)
imprimir_comparacion('Resultado Bernoulli con predictor logit', rl,
                     y_logit(1,Ml0)-y_logit(0,Ml0),
                     y_logit(1,Ml1)-y_logit(1,Ml0))
q = sigmoid(np.array([[-2., -.8], [-1.2, 0.]]))
truth_nde = (q[1]-q[0])@np.array([.8,.2])
truth_nie = (q[1,1]-q[1,0])*.4
print('Población en riesgo PNDE/TNIE/TE:',
      round(float(truth_nde),6), round(float(truth_nie),6),
      round(float(truth_nde+truth_nie),6))
print('Producto 0,4×1,2=0,48 es en índice logit, no una diferencia de riesgos.')

In local Python install dowhy, numpy, pandas, networkx and scikit-learn. Fit an invertible additive model and compare counterfactual_samples with manual abduction of residuals from the fitted model. Agreement depends on the assumed graph and mechanisms; it does not prove they are the only ones compatible with data.

[ ]Counterfactual with DoWhy GCMLocal GPU
"""Comparación local de contrafactuales con DoWhy-GCM.

Instala dowhy, numpy, pandas, networkx y scikit-learn en tu entorno local.
El modelo ajustado es una suposición; conocer los datos no lo identifica por sí solo.
"""
import numpy as np
import pandas as pd
import networkx as nx
from dowhy import gcm

rg = np.random.default_rng(272123)
n = 4000
x = rg.normal(size=n)
m = 2*x + rg.normal(size=n)
y = .5*x + 3*m + rg.normal(size=n)
training = pd.DataFrame({'X':x, 'M':m, 'Y':y})
graph = nx.DiGraph([('X','M'),('X','Y'),('M','Y')])
model = gcm.InvertibleStructuralCausalModel(graph)
model.set_causal_mechanism('X',gcm.EmpiricalDistribution())
model.set_causal_mechanism('M',gcm.AdditiveNoiseModel(gcm.ml.create_linear_regressor()))
model.set_causal_mechanism('Y',gcm.AdditiveNoiseModel(gcm.ml.create_linear_regressor()))
gcm.fit(model,training)

observada = training.iloc[[3]].copy()
x_actual = float(observada['X'].iloc[0])
x_alterno = x_actual + 1
cf = gcm.counterfactual_samples(model, {'X':lambda _:x_alterno}, observed_data=observada)

# Abducción manual con los mecanismos ajustados, no con coeficientes verdaderos.
# Para Y, DoWhy ordena alfabéticamente los padres: M, X.
pm = model.causal_mechanism('M').prediction_model
py = model.causal_mechanism('Y').prediction_model
fm = lambda value: float(pm.predict(np.array([[value]])).ravel()[0])
fy = lambda mediator, value: float(py.predict(np.array([[mediator,value]])).ravel()[0])
m_actual = float(observada['M'].iloc[0])
y_actual = float(observada['Y'].iloc[0])
u_m = m_actual-fm(x_actual)
u_y = y_actual-fy(m_actual,x_actual)
m_alterno = fm(x_alterno)+u_m
y_alterno = fy(m_alterno,x_alterno)+u_y
np.testing.assert_allclose([m_alterno,y_alterno],cf[['M','Y']].to_numpy().ravel(),atol=1e-10,rtol=0)
print('Observación:', observada.to_dict(orient='records')[0])
print('Ruidos abducidos bajo los mecanismos ajustados:', u_m, u_y)
print('do(X =',x_alterno,'):',cf.to_dict(orient='records')[0])
print('Predicción manual M, Y:',m_alterno,y_alterno)
print('La coincidencia es condicional al grafo y a los mecanismos ajustados.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofPreserve the noise
Prove: In the SCM Y=α+βX+UY=\alpha+\beta X+U, with constant coefficient and exact observations X=x′X=x' and Y=yY=y, prove that Yx=y+β(x−x′)Y_x=y+\beta(x-x'). Assume the intervention replaces the equation for X and preserves U.
The proof will appear here as you work.

Step 1 of 3. What value of U is compatible with the observation?

ProofMonotonicity and types
Prove: Let Y0,Y1Y_0,Y_1 be binary and Y1≥Y0Y_1\ge Y_0 for every unit. Prove that PNS=P(Y1=1)−P(Y0=1)PNS=P(Y_1=1)-P(Y_0=1).
The proof will appear here as you work.

Step 1 of 3. Which potential-response types does monotonicity allow?

NumericA bound with observational data
In a compatible population, P(Y₁=1)=0.7 and P(Y₀=1)=0.3. Also P(X=1,Y=1)=0.25, P(X=0,Y=0)=0.25 and P(Y=1)=0.5. Calculate the Tian–Pearl lower bound for PN without assuming exogeneity.
NumericThe other PN bound
With the same probabilities as in the previous exercise, calculate the Tian–Pearl upper bound for PN.
CodeDiscrete mediation formula
Implement natural_effects(scm, x, x_prime) for two treatment levels and a discrete mediator with K categories. scm['mediator'] is a 2×K matrix of P(M=m | A=a), and scm['outcome'] is a 2×K matrix of E[Y | A=a,M=m]; both have rows a=0,1. Return a dictionary with nde, nie, and te for the pure natural direct effect, total natural indirect effect, and their sum. Validate dimensions, finite numbers, normalized nonnegative probabilities, and treatment levels. For distinct exposures require positive common support on the union of active categories and raise ValueError if absent; if x=x_prime return zero. This contract uses a sufficient condition somewhat stronger than necessary for some directional formulas. The formula identifies causal effects only under the mediation assumptions explained in the lesson.
import numpy as np

def natural_effects(scm, x, x_prime):
  """Calcula NDE puro, NIE total y TE con la fórmula de mediación."""
  raise NotImplementedError('Implementa la fórmula')
Shift+Enter to run
QuizA future policy
What quantity answers how much the population incident rate would change if everyone received the patch?
QuizAn observed incident
An unpatched server suffered an incident. What is needed to ask whether that same incident would have occurred with the patch?
QuizAn alternative explanation
You want to describe what a system would predict for the same case if one input differed. What should be made explicit?
QuizTwo perfect trials
Two trials exactly identify outcome rates under treatment and control. What follows about individual necessity without other data or assumptions?
QuizFixing the mediator
A policy holds the mediator at m for everyone and compares X=1 with X=0. What is the estimand?
QuizA post-treatment confounder
Treatment changes a variable affecting both mediator and outcome. What follows from applying the simple natural formula without more?

Check the two numeric bounds after solving them:

[ ]Necessity bounds exerciseBrowser
p0, p1, q11, q00, r = .3, .7, .25, .25, .5
inferior = max(0., (r-p0)/q11)
superior = min(1., (1-p0-q00)/q11)
assert abs(inferior-.8)<1e-12 and abs(superior-1)<1e-12
print('Cotas de PN:', inferior, superior)