Question, causal graph and analysis plan
Choose and formalize each project case as an estimand, draw a causal graph, derive adjustment sets and implied independences, test those implications in data, and write a dated pre-analysis plan.
After this lesson you can
- Formulate each question as an ATE, ATT, or local-effect estimand with explicit population and horizon.
- Draw a DAG, derive valid adjustment sets, and identify colliders and mediators.
- Test conditional independences implied by the graph against data.
- Write a pre-analysis plan with a primary specification and robustness tests.
Before you start
The question precedes the estimator
A causal study asks about outcomes under alternative interventions, not only association in a table. Before fitting a model, define unit, population, treatment, comparison, outcome, and horizon. The causal estimand is the population quantity you want to know; the estimator is the rule applied to data to approximate it.
The project covers four cases with different designs. For NSW job training, one possible question is the average effect on 1978 earnings of participation versus nonparticipation among treated people in the available subsample. The unit is the person, outcome is real 1978 earnings, and target population is treated people in that sample. This is an ATT, , not automatically the effect of offering the program to today’s entire population.
Defining participation requires specifying whether assignment, access, or actual attendance is compared. Files distinguish treated and control units, but alone do not justify treating an effect of receipt as the effect of a new offer policy. Consistency requires a sufficiently defined intervention and comparable outcomes across groups; interference is ruled out only if one person’s outcome does not change because of others’ treatment, or if modeled otherwise. These are study assumptions, not facts derived from a column name.
For minimum wage, define fast-food establishments in New Jersey and Pennsylvania before and after the 1992 change studied by Card and Krueger, and ask about employment effects in affected establishments under a concrete comparison. A difference-in-differences design requires parallel counterfactual trends, not individual ignorability. For the tobacco tax, the unit can be a state and the question California’s change in cigarette sales after the 1988 policy relative to its trajectory without it; Abadie, Diamond, and Hainmueller study that case. Synthetic control needs a combination of comparable states and absence of relevant interference.
For education and wages, an instrumental variable can identify a local effect under appropriate relevance, independence, exclusion, and monotonicity. Angrist and Krueger study quarter of birth as an instrument for education. With binary instrument and treatment, LATE concerns those who would change treatment due to the instrument, not the whole population. With education measured in years and a multi-valued instrument, the two-stage interpretation can be a weighted average of marginal effects under additional assumptions; do not automatically label every coefficient a single LATE. Determine units, period, and population before comparing figures.
A graph is a claim
The DAG identification strategy represents causal assumptions, not relationships unambiguously learned from correlation. Consider , , , , and . is a confounder, a mediator, and a collider. For the total effect, adjusting for closes ; adjusting for removes part of the mediated effect and adjusting for opens a selection path. The figure’s nodes are a synthetic model, not observed NSW variables.
The simulation generates 5,000 observations with seed 201: standard normal , Bernoulli with logistic probability of , , , and , with independent normal errors. The expected total change when setting from zero to one is . The bar fits selected variables by least squares and shows sampling variation; it does not represent an effect estimated on program data.
The classical backdoor criterion seeks a set without descendants of that blocks every path from to beginning with an arrow into . In the example, is minimal. Minimal means no proper subset works, not that it is the only possible set or that the covariate is measured well. If an unobserved common cause has and , adjusting only observed variables need not close that path.
D-separation follows a graphical rule: on each path a chain or fork is blocked when its middle node is conditioned on, while a collider blocks the path unless it or a descendant is conditioned on. Every path must be checked, not only the most obvious. The program uses an equivalent formulation: take ancestors of queried nodes, connect each node’s parents, forget directions, and remove conditioned nodes. If no connection remains, the set separates in the given graph.
The classical criterion is sufficient, not an exhaustive list of every set that might identify a causal query with more general methods. In particular, a post-treatment variable requires a different question and may be invalid for the total effect. In an application, graph choice should rely on temporal order and substantive knowledge and include plausible latent causes. A list of available covariates does not prove they suffice.
Under consistency, positivity, and conditional absence of confounding, for a valid discrete set :
The derivation uses among those receiving and to replace with ; the law of total expectation weights by the target distribution. Positivity requires observations of each treatment in relevant strata. For ATT, weight by and require control support for those treated units. If is continuous, the sum becomes an integral. These equalities rely on assumptions rather than proving them.
Implications that can fail
Testable implications are independences imposed by the graph under the Markov condition. Rejecting them can indicate an incompatible graph, measurement problem, misspecified test, or failed assumptions. Failure to reject does not prove independence: a small sample, low power, or cancellations can hide dependence. Even if all observable independences fit, multiple DAGs can share them while differing causally.
As a diagnostic exercise, use a deliberately simplified DAG: age education prior earnings, treatment, and outcome; 1975 earnings treatment and outcome; treatment 1978 earnings. The graph implies age is independent of treatment conditional on education and identifies the minimal set if all omissions are correct. In a real study that is a strong assumption: age may directly affect selection or earnings, and unmeasured confounders may exist.
The example plan also includes age, demographic characteristics, and 1974 and 1975 prior earnings. This broader plan is not presented as the toy graph’s minimal set: it reflects an observational specification needing defense with a more complete DAG. If the diagnostic contradicts the simplified graph, do not erase the result or choose an arrow solely to obtain a favorable value. Review assumptions, record the change, and use independent data if the new model is proposed as confirmatory.
The lab tests that implication in an observational sample of 185 treated NSW units and 2,490 PSID controls. It permutes treatment within each exact education level and uses residual association with age as the statistic. With 999 permutations and seed 201, this lesson’s run produced . Under within-stratum exchangeability, it is evidence against that specific independence; it does not discover the correct arrow or prove all confounding was measured. Data and date are historical and the comparison is not an evaluation of a current program.
Plan before estimating
A pre-analysis plan records estimand, population, data source, assumptions, adjustment set, primary estimator, overlap rule, uncertainty, and sensitivity analysis. Include later changes with date and reason. The lab plan is an example dated locally before this session runs; it is not an independent public registry and does not make an already-known analysis preregistered. If the file exists, the program does not overwrite it.
For NSW, first identify whether participants are compared with experimental controls or PSID. The experimental result can serve as a benchmark under randomization, comparable measurement, and transport conditions to the target population; it is not each person’s individual truth. Observational analysis must also justify no unmeasured confounding and overlap. Trimming can change the population and estimand. Record results inconsistent with the plan as well as favorable ones, and classify decisions made after seeing results as exploratory.
The downloadable plan proposes AIPW for ATT as the primary specification, with logistic propensity and a linear outcome model in controls, and 200 bootstrap replicates per group with fixed seed. It does not trim in the main analysis; as sensitivity it proposes limiting propensity to [0.05, 0.95] and declaring the retained population. Those thresholds are a prior convention of this example, not a positivity guarantee. Report extreme probabilities, unstable results, or failed replicates before interpreting the figure.
The plan does not prove the logistic model, outcome model, or covariate list correct. Double robustness does not eliminate unmeasured confounding either: it requires identification and regularity as well as appropriate specification of at least one component. The experimental benchmark is estimated with uncertainty and subject to its own population and measurement conditions. Comparing two intervals or figures without checking estimands is therefore insufficient to validate a method.
Local laboratory: from graph to plan
The following cells require Python, NetworkX, NumPy, pandas, and DoWhy 0.14. In an isolated environment, install dependencies with python -m pip install "dowhy==0.14" networkx numpy pandas. The first implements d-separation using ancestors, moralization, and path search; it compares every pair and subset of several graphs with NetworkX. For the backdoor criterion it removes arrows leaving treatment, excludes treatment descendants, and enumerates minimal observed-variable sets. Search is exponential: suitable here for small graphs, not thousands of covariates.
"""D-separación por grafo ancestral moralizado y puerta trasera clásica."""
from itertools import combinations
import networkx as nx
def d_separated(graph, x, y, conditioned=()):
x, y, conditioned = set(x), set(y), set(conditioned)
if not nx.is_directed_acyclic_graph(graph):
raise ValueError('Se requiere un DAG')
if not x or not y or not (x | y | conditioned) <= set(graph.nodes) or x & y or x & conditioned or y & conditioned:
raise ValueError('Nodos desconocidos, conjuntos vacíos o solapados')
relevant = x | y | conditioned
for node in tuple(relevant):
relevant |= nx.ancestors(graph, node)
ancestral = graph.subgraph(relevant)
moral = nx.Graph()
moral.add_nodes_from(relevant)
moral.add_edges_from(ancestral.edges)
for node in ancestral:
moral.add_edges_from(combinations(ancestral.predecessors(node), 2))
moral.remove_nodes_from(conditioned)
return not any(nx.has_path(moral, a, b) for a in x for b in y)
def minimal_backdoor_sets(graph, treatment, outcome, observed):
"""Criterio clásico: no descendientes de T y separación en G sin aristas salientes de T."""
if treatment == outcome or treatment not in graph or outcome not in graph:
raise ValueError('Tratamiento y resultado deben ser nodos distintos')
if not nx.is_directed_acyclic_graph(graph): raise ValueError('Se requiere un DAG')
observed = set(observed)
if not observed <= set(graph): raise ValueError('Variables observadas desconocidas')
candidates = sorted(observed - {treatment, outcome} - nx.descendants(graph, treatment))
backdoor = graph.copy()
backdoor.remove_edges_from(list(backdoor.out_edges(treatment)))
minimal = []
for k in range(len(candidates)+1):
for subset in combinations(candidates, k):
if any(set(previous) <= set(subset) for previous in minimal): continue
if d_separated(backdoor, {treatment}, {outcome}, subset): minimal.append(subset)
return minimal
import itertools
import networkx as nx
graphs = [nx.DiGraph([('X','M'),('M','Y')]), nx.DiGraph([('X','C'),('Y','C'),('C','D')]),
nx.DiGraph([('Z','X'),('Z','Y'),('X','M'),('M','Y'),('X','Y'),('X','C'),('Y','C')])]
for graph in graphs:
nodes = list(graph)
for x,y in itertools.permutations(nodes,2):
rest = [v for v in nodes if v not in (x,y)]
for k in range(len(rest)+1):
for z in itertools.combinations(rest,k):
assert d_separated(graph,{x},{y},z) == nx.is_d_separator(graph,{x},{y},set(z)), (x,y,z)
assert minimal_backdoor_sets(graphs[2], 'X', 'Y', graphs[2].nodes) == [('Z',)]
assert d_separated(graphs[1], {'X'}, {'Y'}, set())
assert not d_separated(graphs[1], {'X'}, {'Y'}, {'D'})
print('D-separación coincide con NetworkX; ajuste mínimo: Z; descendiente abre colisionador')npm run lab and open the connection link.Before opening data to estimate effects, the next cell writes a new plan with UTC date and hash. You can save it in your project directory, review and sign it, or register it externally if your protocol requires. Its name contains the date and it is created without overwriting; a local timestamp alone does not prove you have not seen data before.
"""Escribir un plan fechado antes de estimar; no demostrar registro externo."""
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
def write_plan(path):
plan = {
'created_at_utc': datetime.now(timezone.utc).isoformat(),
'scope': 'Ejemplo educativo; no constituye un registro público ni afirma prioridad histórica.',
'question': 'Efecto del programa NSW en ingresos reales de 1978 para participantes de la submuestra Dehejia-Wahba.',
'estimand': 'ATT de la participación en NSW para los tratados de la submuestra, en dólares de 1978.',
'data': 'NSW tratados y controles experimentales, y PSID controles; archivos publicados por Dehejia y Wahba.',
'main': 'AIPW para ATT con propensity logístico y resultado lineal en controles; benchmark diferencia experimental en ingresos de 1978.',
'covariates': ['age','education','black','hispanic','married','nodegree','re74','re75'],
'diagnostics': ['balance y solapamiento','comparación con benchmark experimental','sensibilidad a confusión no medida'],
'inference': 'Bootstrap de 200 réplicas por grupo con semilla 201; reportar intervalos percentiles y réplicas fallidas.',
'overlap': 'Estimación principal sin recorte; sensibilidad con propensity entre 0.05 y 0.95, declarando cambio de población.',
'assumptions': ['consistencia','positividad para tratados','ausencia de confusión no medida en comparación observacional','comparabilidad de medición'],
'changes': 'Cualquier desviación posterior se registra con fecha y motivo, como exploratoria si procede.',
}
content = (json.dumps(plan, ensure_ascii=False, indent=2)+'\n').encode('utf8')
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('xb') as file:
file.write(content)
return hashlib.sha256(content).hexdigest()
project = Path('causal_project')
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
plan_path = project / f'plan_{stamp}.json'
print('Plan creado:', plan_path, 'SHA-256:', write_plan(plan_path))npm run lab and open the connection link.Then the three original Dehejia and Wahba files are downloaded, SHA-256 and sizes verified, and the proposed independence tested without calculating an earnings effect. The reported result concerns this particular NSW/PSID combination and described test; it does not interpret a value as a causal-validity guarantee.
"""Descarga verificable de NSW y PSID de la página de Dehejia y Wahba."""
from pathlib import Path
import hashlib
import urllib.request
import pandas as pd
import numpy as np
FILES = {
'nswre74_treated.txt':'e7b742fe0ff07a0f45e129b4ff108bb9611cd83d53604732c48a8a0a3e20eda3',
'nswre74_control.txt':'a1364cea459d953dc691a667d99194b4ad335d6d550354fe23a5d2dc58d729b5',
'psid_controls.txt':'73ffcdd8feb7f965f8e1de9bfdb80a095542c7a95ce7f56b2e2b2a9716e858cc',
}
BASE = 'https://users.nber.org/~rdehejia/data/'
COLUMNS = ['treat','age','education','black','hispanic','married','nodegree','re74','re75','re78']
def fetch_data(directory):
directory = Path(directory)
directory.mkdir(parents=True, exist_ok=True)
for name, expected in FILES.items():
path = directory / name
if not path.exists():
with urllib.request.urlopen(BASE+name, timeout=60) as response:
data = response.read()
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError(f'Hash inesperado: {name}')
path.write_bytes(data)
if hashlib.sha256(path.read_bytes()).hexdigest() != expected:
raise ValueError(f'Archivo local modificado: {name}')
return directory
def load_data(directory):
directory = fetch_data(directory)
treated, controls, psid = [pd.read_csv(directory / n, sep=r'\s+', header=None, names=COLUMNS)
for n in ('nswre74_treated.txt','nswre74_control.txt','psid_controls.txt')]
if (len(treated),len(controls),len(psid)) != (185,260,2490):
raise ValueError('El número de filas no coincide con la documentación')
if not (treated.treat.eq(1).all() and controls.treat.eq(0).all() and psid.treat.eq(0).all()):
raise ValueError('Indicadores de tratamiento inesperados')
return pd.concat([treated,controls], ignore_index=True), pd.concat([treated,psid], ignore_index=True)
def conditional_permutation(data, draws=999, seed=201):
"""Asociación residual de edad y tratamiento al permutar dentro de educación exacta."""
group = data.groupby('education', sort=True).indices
age = data['age'].to_numpy(float)
treatment = data['treat'].to_numpy(float)
residual_age = np.empty_like(age)
residual_t = np.empty_like(treatment)
for ix in group.values():
residual_age[ix] = age[ix] - age[ix].mean()
residual_t[ix] = treatment[ix] - treatment[ix].mean()
observed = float(np.dot(residual_age, residual_t))
rng = np.random.default_rng(seed)
null = []
for _ in range(draws):
permuted = residual_t.copy()
for ix in group.values(): permuted[ix] = rng.permutation(residual_t[ix])
null.append(float(np.dot(residual_age, permuted)))
pvalue = (1 + sum(abs(x) >= abs(observed) for x in null))/(draws+1)
return observed, pvalue
graph = nx.DiGraph([('age','education'),('education','re75'),('education','treat'),
('education','re78'),('re75','treat'),('re75','re78'),('treat','re78')])
print('Conjuntos mínimos:', minimal_backdoor_sets(graph, 'treat', 're78', graph.nodes))
print('Edad separada del tratamiento dada educación:', d_separated(graph, {'age'}, {'treat'}, {'education'}))
from dowhy import CausalModel
skeleton = pd.DataFrame({name:[0.,1.,2.,3.] for name in graph.nodes})
model = CausalModel(data=skeleton, treatment='treat', outcome='re78', graph=graph)
identified = model.identify_effect(method_name='minimal-adjustment')
reference = set(identified.get_backdoor_variables())
assert reference == {'education','re75'}
print('DoWhy, ajuste mínimo:', sorted(reference))
experimental, observational = load_data(project / 'data')
print('Filas experimental y observacional:', len(experimental), len(observational))
stat,pvalue = conditional_permutation(observational)
print('Permutación: estadístico',round(stat,3),'p',pvalue)npm run lab and open the connection link.To continue in your own project download causal_graph.py, its tests, nsw_data.py, save_plan.py, and run_case.py into one directory. Install the specified dependencies, run python test_causal_graph.py, then python run_case.py --project causal_project. The latter first writes the plan and then downloads data and runs the diagnostic. It does not replace external registration or prevent prior consultation of public results; retain its hash and document that context.
Exercises
def d_separated(G, X, Y, Z):
passProve the adjustment formula above from the law of total expectation using consistency and conditional ignorability. Indicate where positivity is needed and why conditioning on the mediator changes the question. Then check which distribution of corresponds to ATT.