Structural causal models and causal graphs
Structural causal models encode mechanisms in causal DAGs. Derive the do operator and truncated factorization, distinguish intervention from conditioning, study colliders and the ladder of causation, and link graphs with potential outcomes using SWIGs.
After this lesson you can
- Write an SCM, draw its graph, and sample observational and interventional distributions.
- Compute P(Y | do(x)) by truncated factorization and compare it with P(Y | X = x) under confounding.
- Explain Simpson’s and Berkson’s paradoxes with graphs and choose the table answering a causal question.
- Classify real questions on the three rungs of the ladder of causation.
- Translate potential-outcome ignorability assumptions into d-separation in a SWIG.
Before you start
One table, two explanations
Two teams use different tools to fix bugs. The aggregate rate favors one tool, but the reverse holds when separating by difficulty. Which should be adopted? The table alone is insufficient: difficulty may precede the choice and affect both tool and outcome, or it may be a downstream variable changed by the tool itself.
In the first case, comparing within difficulty categories and weighting by a common population can answer a causal question under suitable assumptions. In the second, artificially imposing the same distribution of the intermediate variable changes the intervention. A graph makes the difference between those stories explicit; observed data do not automatically decide which is correct.
If is a prior confounder, the common mixture is . If is a mediator, treatment is unconfounded, and the other model assumptions hold, the total effect uses because the intervention can also change the composition of . A comparison fixing asks a different question, which needs its own definition and identification.
Equations describing mechanisms
A structural causal model or SCM specifies for each endogenous variable an equation
where are its parents and captures exogenous causes. If the graph is acyclic, a topological order lets us solve equations one by one. Arrows represent causal inputs to mechanisms, not merely associations. A distribution requires both the equations and the joint distribution of noise terms.
The causal Markov condition, under appropriate assumptions for an acyclic SCM with independent noise, implies that each variable is independent of its nondescendants given its parents. In the discrete case this gives the observational factorization
A Bayesian network can factorize a distribution without its arrows having causal meaning. A single observational distribution may be compatible with several causal graphs: choosing between them requires substantive knowledge, additional restrictions, or interventions.
The Markov implication goes from model to independences. It does not claim every observed independence must appear through d-separation: particular parameter choices can produce cancellations. The additional faithfulness assumption rules out such coincidences but still does not by itself turn a distribution into a unique causal explanation.
Intervening is not conditioning
The do operator represents an external intervention. In the equation for is replaced by the constant , its incoming arrows are removed, and the remaining mechanisms are preserved. This autonomy is an assumption about the intervention; not every real action changes just one equation.
In a causally sufficient discrete acyclic SCM with independent exogenous noise and conditionals defined for the necessary configurations, the post-intervention distribution is the truncated factorization
The factor generating has been removed; the remaining parents are evaluated at the fixed value. An intervention on multiple nodes removes all their factors. With latent confounders or dependent noise, simply multiplying observed-variable conditionals may give an incorrect distribution; an expanded graph or suitable identification method must represent that dependence.
For example, in , , , if is prior and consistency, absence of unmeasured confounding, and positivity hold,
By contrast, weights using . Observing selects units with different causes of ; fixing it breaks that incoming dependence. Conditioning on suitable observed parents of can identify the total effect in the causally sufficient DAG, provided there is support for the required values.
A soft intervention changes a mechanism without necessarily fixing the variable. For example, it may replace with a new probabilistic rule and preserve the other factors. Its effect corresponds to that specific policy. Invariance of the other mechanisms must be justified: merely shifting a distribution does not prove which equation changed.
In practice, formulate the intervention before calculating: is a tool replaced for every incident, is its use offered, or is the probability of adopting it increased? Each changes a different rule. The analysis must also decide what happens with noncompliance and units for which the proposed action is impossible.
Chains, forks, and colliders
In a chain , transmits part of the effect; conditioning on generally does not answer the total-effect question. In the fork , is a common cause; under the previous assumptions adjusting for it can close the confounding path. In the collider , conditioning on or certain descendants can open an association between its causes, even if they were independent before selection.
Collider bias appears, for example, when analyzing only accepted articles if acceptance depends on both novelty and rigor. It can also arise when studying only surviving companies or active customers if inclusion depends on variables related to exposure and outcome. The direction and size of bias depend on the mechanism; selection does not always imply negative correlation.
In the article example, if selection rewards the sum of novelty and rigor, an article with little novelty needs more rigor to exceed the same threshold. Among accepted articles a negative association can appear that does not exist in the generated population. This does not imply increasing novelty reduces rigor: dependence is created by restricting the sample.
In Berkson’s paradox, suppose and independent , with . The conditional normal distribution gives
Use and . These formulas condition on an exact value of using its conditional distribution; filtering by is another selection and needs another calculation. In this Gaussian model both mechanisms produce negative association, not a universal rule for every filter.
The birth-weight paradox illustrates the danger of conditioning on a variable affected by several causes: interpreting a comparison by weight requires specifying exposure, possible common causes, selection, and estimand. An observed reversal alone does not prove the mechanism.
Three kinds of questions
The ladder of causation distinguishes association , intervention , and counterfactuals such as or . The first question describes what is observed; the second changes a rule; the third combines outcomes from alternative worlds for the same units.
The causal hierarchy theorem formalizes conditions under which information at a lower level does not generically determine information at a higher level. It does not say every causal query is impossible to identify: a graph and additional assumptions can identify a particular intervention from observations.
Two examples clarify the limit. Let be equally likely Bernoulli. Models and have the same observational distribution , but under their probabilities of differ. Now take independent equally likely Bernoulli variables and and compare with : their observational distributions and those of every intervention on agree, but in the first always and in the second never. These examples use different graphs and do not prove nonidentification under a known causal graph.
A bridge to potential outcomes: SWIG
A single-world intervention graph or SWIG represents a specific intervention by splitting the treated node into its random half and fixed value. In , , , the graph for preserves the random half of , feeds the fixed value into the mechanism of , and labels the outcome . Under the corresponding SWIG Markov property, d-separation leads to .
Moving from that independence to an observable formula also requires consistency and positivity in the relevant population. A SWIG for one value does not automatically represent the joint distribution of and ; claims combining both worlds may need additional assumptions. Richardson and Robins develop this connection between intervention graphs and potential outcomes.
The languages complement each other: an SCM defines by solving its equations after replacing that of with , while the SWIG encodes independences in that intervened world. Joint distributions across worlds may need additional restrictions; they do not follow from just any SWIG considered alone.
Probabilistic DAGs provide factorization and d-separation; the meaning of surgery adds causal assumptions. An acyclic graph allows mechanisms to be ordered. In distribution shift problems, distinguishing which mechanism changes helps formulate a transport hypothesis that can be tested.
Lab: build an SCM
This implementation represents binary variables with probability tables, independent uniform noise for each variable, and an explicit topological order. Exact enumeration multiplies the tables; a hard intervention creates a copy with the equation replaced and a soft intervention replaces a table without changing its parents.
import itertools
import numpy as np
class SCM:
"""Red binaria acíclica con un ruido uniforme independiente por nodo.
specs es una lista ordenada de (nombre, padres, probabilidades). Padres
aparecen antes que el nodo. La tabla sigue orden lexicográfico de bits,
de modo que, con padres [A,B], índices 0,1,2,3 corresponden a 00,01,10,11.
"""
def __init__(self, specs):
self.specs = []
visited = set()
for name, parents, probabilities in specs:
parents = tuple(parents)
prob = np.asarray(probabilities, dtype=float)
if (not isinstance(name, str) or not name or name in visited
or len(set(parents)) != len(parents)
or any(parent not in visited for parent in parents)
or prob.shape != (2**len(parents),)
or not np.isfinite(prob).all() or np.any((prob < 0) | (prob > 1))):
raise ValueError('Especificación inválida o no ordenada topológicamente')
self.specs.append((name, parents, tuple(float(p) for p in prob)))
visited.add(name)
if not self.specs:
raise ValueError('El modelo no puede estar vacío')
self.names = tuple(node[0] for node in self.specs)
def intervene(self, assignments):
"""Devuelve una copia y sustituye cada ecuación intervenida por una constante."""
if not isinstance(assignments, dict) or not set(assignments).issubset(self.names):
raise ValueError('La intervención contiene nodos desconocidos')
if any(value not in (0, 1) for value in assignments.values()):
raise ValueError('Las intervenciones duras deben ser binarias')
specs = [(name, (), (float(assignments[name]),)) if name in assignments
else (name, parents, prob) for name, parents, prob in self.specs]
return SCM(specs)
def soft(self, replacements):
"""Sustituye tablas conservando padres; no modifica el modelo original."""
if not isinstance(replacements, dict) or not set(replacements).issubset(self.names):
raise ValueError('La intervención contiene nodos desconocidos')
return SCM([(name, parents, replacements.get(name, prob))
for name, parents, prob in self.specs])
def sample(self, n, seed):
if not isinstance(n, int) or n <= 0:
raise ValueError('n debe ser un entero positivo')
rng = np.random.default_rng(seed)
data = {}
for name, parents, prob in self.specs:
index = np.zeros(n, dtype=int)
for parent in parents:
index = 2*index + data[parent]
data[name] = (rng.random(n) < np.asarray(prob)[index]).astype(int)
return data
def probability(self, event):
"""Enumeración exacta del producto de tablas, sin regularización."""
if not isinstance(event, dict) or not set(event).issubset(self.names) or any(v not in (0, 1) for v in event.values()):
raise ValueError('Evento inválido')
total = 0.0
for values in itertools.product((0, 1), repeat=len(self.names)):
row = dict(zip(self.names, values))
if any(row[k] != v for k, v in event.items()):
continue
mass = 1.0
for name, parents, prob in self.specs:
index = 0
for parent in parents:
index = 2*index + row[parent]
p = prob[index]
mass *= p if row[name] == 1 else 1-p
total += mass
return total
def conditional(self, event, given):
if set(event) & set(given):
raise ValueError('Evento y condición deben usar nodos distintos')
den = self.probability(given)
if den <= 0:
raise ValueError('Condición de probabilidad cero')
return self.probability({**event, **given}) / den
scm = SCM([
('Z', (), (.4,)),
('X', ('Z',), (.2, .8)),
('Y', ('Z', 'X'), (.1, .6, .5, .9)),
('R', ('Y',), (.25, .75)),
])
print('Orden:', scm.names, '| masa total:', round(scm.probability({}), 12))
print('P(Y=1|X=1):', round(scm.conditional({'Y':1}, {'X':1}), 6))
print('P(Y=1|do(X=1)):', round(scm.intervene({'X':1}).probability({'Y':1}), 6))
print('P(Y=1|do(X=0)):', round(scm.intervene({'X':0}).probability({'Y':1}), 6))
np.testing.assert_allclose(scm.conditional({'Y':1}, {'X':1}), 9/11)
np.testing.assert_allclose(scm.intervene({'X':1}).probability({'Y':1}), .72)
np.testing.assert_allclose(scm.intervene({'X':0}).probability({'Y':1}), .26)Compare truncated factorization and sampling after intervening. Monte Carlo error quantifies sample variation; a soft policy produces another distribution that must not be confused with fixing X.
# La factorización truncada conserva el mecanismo de Z y de Y y elimina P(X|Z).
p_do1 = sum(scm.probability({'Z': z}) * scm.conditional({'Y': 1}, {'X': 1, 'Z': z}) for z in (0, 1))
assert np.isclose(p_do1, .72)
draw = scm.intervene({'X': 1}).sample(80_000, 2031)
observed = draw['Y'].mean()
mc_se = np.sqrt(p_do1*(1-p_do1)/len(draw['Y']))
assert abs(observed-p_do1) < 5*mc_se
print('Factorización truncada:', round(p_do1, 6))
print('Muestreo con do(X=1):', round(observed, 6), '| EE Monte Carlo:', round(mc_se, 6))
print('Diferencia causal media para Y binaria:', round(p_do1-scm.intervene({'X':0}).probability({'Y':1}), 6))
# Intervención blanda: cambia P(X=1|Z), conserva la dependencia de Z.
soft_scm = scm.soft({'X': (.35, .65)})
print('P(Y=1) observacional:', round(scm.probability({'Y':1}), 6))
print('P(Y=1) bajo política blanda:', round(soft_scm.probability({'Y':1}), 6))
np.testing.assert_allclose(soft_scm.probability({'Y':1}), .469)
np.testing.assert_allclose(scm.probability({'Y':1}), .448)
assert scm.specs[1][1] == ('Z',) and scm.intervene({'X':1}).specs[1][1] == ()
assert soft_scm.specs[1][1] == ('Z',) and scm.specs[1][2] == (.2, .8)
print('Modelo original intacto; la intervención blanda conserva los padres.')In a local installation with NetworkX and Matplotlib you can check d-separation and draw the surgery. The graph is a starting assumption: a library finding a blocked path does not confirm the mechanism in data.
# Comprobación de caminos con NetworkX 3.6.1 o una versión compatible.
import networkx as nx
import matplotlib.pyplot as plt
graph = nx.DiGraph([('Z', 'X'), ('Z', 'Y'), ('X', 'Y')])
assert nx.is_directed_acyclic_graph(graph)
backdoor = graph.copy()
backdoor.remove_edges_from(list(backdoor.out_edges('X')))
print('Camino trasero abierto sin Z:', not nx.is_d_separator(backdoor, {'X'}, {'Y'}, set()))
print('Camino trasero bloqueado al condicionar Z:', nx.is_d_separator(backdoor, {'X'}, {'Y'}, {'Z'}))
intervened = graph.copy()
intervened.remove_edges_from(list(intervened.in_edges('X')))
print('Flechas tras do(X):', sorted(intervened.edges()))
collider = nx.DiGraph([('A','C'), ('B','C')])
assert nx.is_d_separator(collider, {'A'}, {'B'}, set())
assert not nx.is_d_separator(collider, {'A'}, {'B'}, {'C'})
print('Colisionador bloqueado sin C y abierto al condicionar C:', True)
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
pos = {'Z':(.5,1), 'X':(0,0), 'Y':(1,0)}
for ax, g, title in zip(axes, [graph, intervened], ['Modelo supuesto', 'Cirugía do(X)']):
nx.draw_networkx(g, pos=pos, ax=ax, node_color='#c8ddf0', arrows=True)
ax.set_title(title)
ax.set_axis_off()
plt.tight_layout()
plt.show()npm run lab and open the connection link.The following optional example uses locally installed DoWhy. The library was unavailable in the preparation environment, so this snippet was not run here. The model and graph are assumptions of the example, and the specific estimate varies with the sample.
# Ejemplo opcional para una instalación local que YA tenga DoWhy.
# No se instaló ni se ejecutó en el entorno de preparación de la lección.
import numpy as np
import pandas as pd
import networkx as nx
from dowhy import CausalModel
rng = np.random.default_rng(1011)
z = rng.normal(size=5000)
x = .8*z + rng.normal(size=5000)
y = 2*x + 1.4*z + rng.normal(size=5000)
data = pd.DataFrame({'Z':z, 'X':x, 'Y':y})
graph = nx.DiGraph([('Z', 'X'), ('Z', 'Y'), ('X', 'Y')])
model = CausalModel(data=data, treatment='X', outcome='Y',
graph='\n'.join(nx.generate_gml(graph)))
estimand = model.identify_effect()
estimate = model.estimate_effect(estimand, method_name='backdoor.linear_regression',
control_value=0, treatment_value=1)
print(estimand)
print('Estimación ajustada del efecto de fijar X en 1 frente a 0:', estimate.value)
print('El SCM simulado tiene efecto poblacional 2; el ajuste depende del grafo supuesto.')
Lab: Simpson and selection
Data from Charig and colleagues compare kidney-stone treatments in historical cohorts. The table is reproduced with counts in Bottou and colleagues. Aggregate rates and those standardized by size answer different comparisons; cohorts come from different periods and size adjustment does not prove the absence of other differences.
In each size category the observed rate favors open surgery, while the aggregate rate favors the percutaneous procedure. Check denominators as well as percentages: the proportions of small and large cases differ between treatments. The following standardization applies the same mixture to both groups, but interpreting it as an intervention effect requires assumptions these counts do not guarantee.
import numpy as np
# Tablas I y II de Charig et al. (1986), BMJ 292:879-882.
# Columnas: piedra <2 cm, piedra >=2 cm. Filas: abierta, percutánea.
exitos = np.array([[81, 192], [234, 55]])
pacientes = np.array([[87, 263], [270, 80]])
tasas = exitos / pacientes
pesos = pacientes.sum(axis=0) / pacientes.sum()
brutas = exitos.sum(axis=1) / pacientes.sum(axis=1)
estandarizadas = tasas @ pesos
print("Tasas por tamaño (filas abierta, percutánea):")
print(np.round(tasas, 6))
print("Pesos comunes (población conjunta):", np.round(pesos, 6))
print("Tasas brutas:", np.round(brutas, 6))
print("Abierta menos percutánea, bruto:", round(brutas[0] - brutas[1], 6))
print("Tasas estandarizadas:", np.round(estandarizadas, 6))
print("Abierta menos percutánea, estandarizado:",
round(estandarizadas[0] - estandarizadas[1], 6))Now generate a Gaussian collider and compare the full sample with the sample selected by a threshold. The theoretical correlation corresponds to filtering on a noisy sum, not to exact conditioning in the earlier proof.
import numpy as np
# Modelo explícito: X, Y y E son normales estándar independientes;
# U = X + Y + E y seleccionamos S = 1 si U > 0.
generador = np.random.default_rng(111)
n = 20_000
x, y, e = generador.normal(size=(3, n))
u = x + y + e
seleccion = u > 0
def pendiente(a, b):
"""Pendiente OLS con intercepto, desde sumas centradas."""
ac, bc = a - a.mean(), b - b.mean()
return ac @ bc / (ac @ ac)
def correlacion(a, b):
ac, bc = a - a.mean(), b - b.mean()
return (ac @ bc) / np.sqrt((ac @ ac) * (bc @ bc))
# Como Var(U)=3, E[U | U>0]^2=6/pi y
# Cov(X,Y | U>0)=-2/(3*pi), Var(X | U>0)=1-2/(3*pi).
rho_teorica = -2 / (3 * np.pi - 2)
# Ajustar U como regresor también abre el colisionador: por normalidad,
# E[Y | X,U] = (U-X)/2. La pendiente parcial de X es -1/2.
matriz = np.column_stack((np.ones(n), x, u))
coef = np.linalg.lstsq(matriz, y, rcond=None)[0]
print("N total y seleccionado:", n, int(seleccion.sum()))
print("Correlación completa:", round(correlacion(x, y), 4))
print("Correlación seleccionada:", round(correlacion(x[seleccion], y[seleccion]), 4))
print("Correlación teórica seleccionada:", round(rho_teorica, 4))
print("Pendiente completa Y~X:", round(pendiente(x, y), 4))
print("Pendiente seleccionada Y~X:", round(pendiente(x[seleccion], y[seleccion]), 4))
print("Pendiente teórica seleccionada:", round(rho_teorica, 4))
print("Coeficientes Y~1+X+U:", np.round(coef, 4))
print("Pendientes parciales teóricas de X y U: -0.5, 0.5")Exercises
Step 1 of 3. What changes when applying do(X=x)?
Step 1 of 3. What are Cov(X,C), Cov(Y,C), and Var(C)?
In the next two numeric exercises use this binary SCM: , , and . Its noise terms are independent and precedes . Calculate both probabilities before running the checking cell.
import numpy as np
p_z = np.array([0.5, 0.5])
p_x1 = np.array([0.2, 0.8])
p_y1_x1 = np.array([0.4, 0.8])
p_x = np.sum(p_z*p_x1)
p_z_given_x1 = p_z*p_x1/p_x
observado = np.sum(p_y1_x1*p_z_given_x1)
intervenido = np.sum(p_y1_x1*p_z)
print('P(Z | X=1):', p_z_given_x1)
print('P(Y=1 | X=1), P(Y=1 | do(X=1)):', observado, intervenido)def intervene(scm, assignments):
# Crea una copia independiente y sustituye las ecuaciones intervenidas.
raise NotImplementedError