The do-calculus, the ID algorithm and completeness of identification
Do-calculus transforms interventions using three graphical rules. Derive backdoor and frontdoor, study semi-Markovian models and districts, implement ID, examine hedges, and discuss transportability.
After this lesson you can
- State and justify the three rules of do-calculus using truncated factorization.
- Derive backdoor and frontdoor formulas step by step using do-calculus.
- Decompose an ADMG into c-components and calculate Q factors.
- Implement ID and apply it to graphs with latent confounders.
- Recognize a hedge and explain nonidentification of the corresponding effect.
Before you start
A question more general than backdoor
You have seen two ways to express an intervention through observations. If neither applies directly, is the effect impossible to identify or does it merely need a more elaborate derivation? The answer depends on the graph and model class. Causal calculus transforms expressions under justified conditions; the ID algorithm decides identification of a precise family of queries and builds a formula when one exists.
Identification is not estimation: even a correct formula can contain conditionals with little support and produce highly unstable estimates.
Mutilated graphs and three rules
In a causal DAG, removes arrows entering and removes arrows leaving . With bidirected edges due to latent confounding, removing arrowheads at also removes incident bidirected edges. Check separations in an expanded DAG with latent causes or using m-separation in the mixed graph; treating a bidirected edge as an ordinary directed arrow is insufficient.
For disjoint sets , Pearl’s do-calculus offers three transformations. Equalities apply where conditionals are defined:
-
Insert or delete an observation. If ,
-
Exchange action and observation. If ,
-
Insert or delete an action. Let . If ,
The third condition removes incoming arrows only for variables in that are not ancestors of in . The checking graph changes between rules: applying them to the original graph can yield false equalities.
Justification starts from the SCM and truncated factorization in an expanded DAG. In rule one, after fixing , the graphical condition implies conditional independence in the intervened distribution; canceling the distribution of when conditioning yields the equality. In rule two, after removing outgoing edges from , separation ensures selection by the mechanism generating adds no information about given ; replacing that mechanism by a constant leaves the conditional unchanged. In rule three, factors for intervened variables that can affect are retained in the test graph; separation of the others permits summing and eliminating their factors. Pearl’s source formally derives the rules and their full assumptions; an isolated example does not establish general validity.
To examine rule 2 for a single node , add an independent exogenous indicator selecting between the original equation of and constant . Under , the condition in implies by d-separation in the augmented graph. With the conditional is the observational one for within the intervention on ; with it is the conditional after . Independence equates them when both conditions have support. For a set use a joint intervention and apply the same argument to its mechanisms.
For rule 3 introduce a vector of exogenous indicators whose “off” and values select original mechanisms and constants respectively. The graphical equivalence in Pearl’s proof converts the condition with into in augmented graph . The ancestor distinction matters: only incoming edges of nodes in that cannot be ancestors of in are cut; cutting all could certify a false equality.
To make the probability step explicit, call the sum of the truncated factorization over all variables other than after fixing and indicator . With , factors for are replaced by indicators of their values; with they are retained. The graphical independence obtained by Markov implies
By definition of the indicators, the first ratio is and the last is . This proof uses the graphical equivalence of rule 3 and positive denominators; it does not confuse the observed value of with the exogenous selector of its mechanism.
Deriving backdoor and frontdoor
If satisfies backdoor, it is not a descendant of and and are separated by in . By total probability and rule 2,
The last factor is because intervening on does not change its nondescendants. Support is required in the strata used.
For frontdoor, let be the mediator and assume the three conditions from the previous lesson. First by rule 2, because there is no open backdoor path from to . Next, rules 2 and 3 allow, in the corresponding mutilated graphs, conversion and removal of the action on once is fixed:
Finally, as blocks backdoor paths from to , the backdoor formula applied to gives . Substitution yields:
The first equality depends on absence of unblocked confounding between and ; the second requires every directed path from to to pass through and the other frontdoor conditions. A graph change requires every separation to be checked again.
With two time-ordered treatments and observed intermediate variable , in the DAG without unmeasured confounding containing , , , , and , truncated factorization yields
Here follows the first action and precedes the second. The formula does not authorize indiscriminate adjustment for every post-treatment variable in a single-treatment regression.
Latents, districts, and Q factors
A semi-Markovian model permits latent common causes between observed variables while preserving acyclicity of the directed structure. The latent projection is represented by an acyclic directed mixed graph or ADMG, with directed and bidirected arrows. Two nodes can have both a directed and bidirected edge; a simple directed graph alone cannot represent this combination.
C-components or districts are connected components when traversing only bidirected edges. For district of current population , is its kernel under intervention on the remaining variables. If the input kernel corresponds to that graph and topological order is used, the district factor is obtained by multiplying chain-rule ratios for nodes of :
Support conditions matter when evaluating ratios. In a recursive ID call the input may be an already transformed kernel: factors are constructed from that current kernel, not blindly replaced with original conditionals. The formula does not automatically identify for an arbitrary subset.
ID: decompose, recurse, or declare failure
The ID algorithm takes an acyclic semi-Markovian ADMG and observational distribution and seeks to express for action and outcome sets. Each call maintains a graph and a kernel. The presentation by Shpitser and Pearl follows these cases:
- If no actions remain, marginalize non-outcome variables.
- If nodes are not ancestors of outcomes in the current graph, marginalize them and restrict the problem to ancestors.
- After cutting incoming edges of actions, add to actions the nodes no longer ancestral to outcomes.
- If the graph remaining without actions has several districts, recursively solve each factor and multiply them before marginalizing nodes that are neither outcome nor action.
- If one district remains and the current graph is also one district, declare identification failure in that call.
- If the remaining district is a district of the current graph, return its chain-rule factor and marginalize what remains.
- If strictly contained in another district, construct the larger district’s kernel from the current kernel and recurse within it.
Order matters. The failure step does not justify calling two arbitrary implementation sets a “hedge”: a graphical witness must satisfy the definitions of relevant forests and roots.
Completeness and the bow graph
A hedge is a pair of nested graphical structures certifying nonidentification under appropriate conditions. The bow has and : the bidirected arrow represents a latent confounder. For the effect of on , structures with nodes and provide the canonical example.
A forest has one bidirected district and each node has at most one directed child within the forest; its roots have no directed children in it. In a hedge, is a proper subforest of , both share roots , intersects actions and does not, and is among outcome ancestors in . In the bow, contains both edges and , and the common root is .
A concrete construction demonstrates the limitation without relying only on a label. Let , independent , and . In model A, ; in B, . Observationally both have and the same full-support joint distribution. But under , and . Both models make causes of functionally relevant when .
For this class of queries and models, ID is sound and complete: it returns a correct functional when identified and signals failure when the distribution is not identified. Completeness of do-calculus refers to the same problem and class, not every counterfactual question or combination of studies. Shpitser clarifies that an old corollary characterizing hedges was incorrect as stated; this does not invalidate ID’s soundness or completeness. The explicit bow construction does not depend on repeating that corollary.
Conditional identification and transport
IDC extends reasoning to conditional queries; applying ID to a numerator and dividing is insufficient without checking the relevant conditions and support. Transportability asks whether data from one population, perhaps including interventions, and data from another recover an effect in the target population. A selection diagram must specify which mechanisms may change. Combining sources also requires documenting variables and interventions available in each source; see Bareinboim and Pearl.
Logical resolution offers an analogy: a rewrite rule helps only if its premises are checked. Distribution shift reminds us transporting an effect requires more than observing a sample difference. Documenting each assumption makes research auditable.
Lab: ID from scratch
Implement an ADMG with separate directed and bidirected edges, and a kernel retaining external axes of recursive calls. To keep the lab runnable in the browser, tables are binary, small, and strictly positive; the graphical algorithm is not conceptually limited to those sizes.
import networkx as nx
import numpy as np
import itertoolsimport sympy as spclass ADMG:
"""Grafo mixto acíclico: separa las flechas y las aristas bidirigidas."""
def __init__(self, nodes, directed=(), bidirected=()):
self.nodes = tuple(nodes)
if len(set(self.nodes)) != len(self.nodes) or not self.nodes:
raise ValueError('Nodos vacíos o duplicados')
self.directed = nx.DiGraph()
self.bidirected = nx.Graph()
self.directed.add_nodes_from(self.nodes)
self.bidirected.add_nodes_from(self.nodes)
for graph, edges in ((self.directed, directed), (self.bidirected, bidirected)):
for a, b in edges:
if a not in self.nodes or b not in self.nodes or a == b:
raise ValueError('Arista inválida')
graph.add_edge(a, b)
if not nx.is_directed_acyclic_graph(self.directed):
raise ValueError('Las aristas dirigidas deben ser acíclicas')
def subgraph(self, nodes):
nodes = set(nodes)
order = tuple(v for v in self.nodes if v in nodes)
if len(order) != len(nodes):
raise ValueError('Nodos desconocidos')
return ADMG(order, self.directed.subgraph(nodes).edges(), self.bidirected.subgraph(nodes).edges())
def districts(self):
return [set(c) for c in nx.connected_components(self.bidirected)]
def ancestors(self, nodes):
result = set(nodes)
for v in nodes:
result.update(nx.ancestors(self.directed, v))
return result
def after_do(self, nodes):
nodes = set(nodes)
# Las aristas con punta en cualquier nodo intervenido desaparecen.
return ADMG(self.nodes, ((a,b) for a,b in self.directed.edges if b not in nodes),
((a,b) for a,b in self.bidirected.edges if a not in nodes and b not in nodes))
class Kernel:
"""Tabla sobre ejes globales y expresión SymPy sin evaluar los sumatorios."""
def __init__(self, array, expression, axes, symbols):
self.array = np.asarray(array, dtype=float)
self.expression = expression
self.axes = axes
self.symbols = symbols
def sum_out(self, names):
names = [v for v in self.axes if v in set(names)]
array, expression = self.array, self.expression
for name in names:
array = array.sum(axis=self.axes.index(name), keepdims=True)
expression = sp.Sum(expression, (self.symbols[name], 0, 1))
return Kernel(array, expression, self.axes, self.symbols)
def __mul__(self, other):
return Kernel(self.array*other.array, self.expression*other.expression, self.axes, self.symbols)
def __truediv__(self, other):
if np.any(other.array <= 0):
raise ValueError('Condicional sin soporte: no se divide por cero')
return Kernel(self.array/other.array, self.expression/other.expression, self.axes, self.symbols)
def source_kernel(nodes, table):
"""P observacional positiva, en orden topológico de nodos binarios."""
axes = tuple(nodes)
table = np.asarray(table, dtype=float)
if table.shape != (2,)*len(axes) or not np.isfinite(table).all() or np.any(table <= 0) or not np.isclose(table.sum(), 1):
raise ValueError('La tabla conjunta debe ser positiva, binaria y normalizada')
symbols = {v: sp.Symbol(v, integer=True, nonnegative=True) for v in axes}
base = sp.IndexedBase('p')
return Kernel(table, base[tuple(symbols[v] for v in axes)], axes, symbols)
def chain_factors(kernel, graph):
"""P(v_i | v_<i) del KERNEL ACTUAL, reteniendo índices externos."""
order = list(nx.topological_sort(graph.directed))
factors = {}
for i, name in enumerate(order):
numerator = kernel.sum_out(order[i+1:])
denominator = kernel.sum_out(order[i:])
factors[name] = numerator / denominator
return factors
def q_factor(kernel, graph, component):
"""Factor Q de un distrito completo del grafo y kernel actuales."""
component = set(component)
if component not in graph.districts():
raise ValueError('S debe ser un distrito completo del grafo actual')
factors = chain_factors(kernel, graph)
order = list(nx.topological_sort(graph.directed))
selected = [factors[v] for v in order if v in component]
result = selected[0]
for term in selected[1:]:
result = result * term
return result
class IdentificationFailure(Exception):
def __init__(self, graph_nodes, district):
self.graph_nodes = set(graph_nodes)
self.district = set(district)
super().__init__('ID no identifica la consulta: revisa la estructura testigo local')
def identify(y, x, kernel, graph, trace=None):
"""Algoritmo ID de Shpitser-Pearl en DAG mixto semimarkoviano binario.
La tabla usa ejes globales para conservar como argumentos libres los valores
externos de intervenciones en llamadas recursivas. Se asume soporte positivo.
"""
if trace is None:
trace = []
y, x, nodes = set(y), set(x), set(graph.nodes)
if not y or y & x or not (x | y).issubset(nodes):
raise ValueError('Objetivo e intervención incompatibles')
if not x:
trace.append('1: sin intervención')
return kernel.sum_out(nodes - y)
ancestors = graph.ancestors(y)
if ancestors != nodes:
trace.append('2: restringir a ancestros')
return identify(y, x & ancestors, kernel.sum_out(nodes - ancestors), graph.subgraph(ancestors), trace)
w = (nodes - x) - graph.after_do(x).ancestors(y)
if w:
trace.append('3: agregar intervenciones irrelevantes')
return identify(y, x | w, kernel, graph, trace)
remaining = graph.subgraph(nodes - x)
parts = remaining.districts()
if len(parts) > 1:
trace.append('4: multiplicar distritos')
terms = [identify(part, nodes - part, kernel, graph, trace) for part in parts]
result = terms[0]
for term in terms[1:]:
result = result * term
return result.sum_out(nodes - x - y)
if not parts:
raise ValueError('La intervención elimina todos los nodos de resultado')
district = parts[0]
graph_districts = graph.districts()
if len(graph_districts) == 1:
trace.append('5: fallo de identificación')
raise IdentificationFailure(nodes, district)
if district in graph_districts:
trace.append('6: distrito completo')
return q_factor(kernel, graph, district).sum_out(district - y)
container = next((part for part in graph_districts if district < part), None)
if container is None:
raise RuntimeError('No se encontró el distrito contenedor')
trace.append('7: factorizar kernel y recursar en distrito contenedor')
return identify(y, x & container, q_factor(kernel, graph, container), graph.subgraph(container), trace)Test observed adjustment, frontdoor, a graph with observed and latent confounders, and bow. Compare each functional with the known intervention in the SCM generating the table. The trace records applied branches; failure returns a local structure not automatically identified with a complete hedge.
def probability_binary(v, p):
return p if v else 1-p
def read_entry(result, fixed):
# Una dimensión eliminada del resultado tiene tamaño uno: la consulta
# no depende de ese índice y admite ambos valores por broadcasting.
index = tuple(fixed.get(v, 0) if result.array.shape[i] > 1 else 0
for i, v in enumerate(result.axes))
return float(result.array[index])
def example_confounded():
# Z común observado, X y Y binarias; todo el soporte es positivo.
table = np.zeros((2,2,2))
for z,x,y in itertools.product(range(2), repeat=3):
table[z,x,y] = probability_binary(z,.4)*probability_binary(x,.2+.6*z)*probability_binary(y,.1+.3*x+.4*z)
graph = ADMG(('Z','X','Y'), [('Z','X'),('Z','Y'),('X','Y')])
return graph, table
def example_frontdoor():
# U oculto, Bernoulli(1/2), y ruidos independientes en cada ecuación.
table = np.zeros((2,2,2))
for u,x,m,y in itertools.product(range(2), repeat=4):
table[x,m,y] += .5*probability_binary(x,.25+.5*u)*probability_binary(m,.2+.6*x)*probability_binary(y,.1+.4*m+.4*u)
graph = ADMG(('X','M','Y'), [('X','M'),('M','Y')], [('X','Y')])
return graph, table
def example_nested():
# Confusión observada W y latente U, además del mediador M.
table = np.zeros((2,2,2,2))
for w,u,x,m,y in itertools.product(range(2), repeat=5):
table[w,x,m,y] += (probability_binary(w,.4)*.5*probability_binary(x,.15+.25*w+.35*u)
* probability_binary(m,.2+.6*x)*probability_binary(y,.05+.3*m+.25*u+.2*w))
graph = ADMG(('W','X','M','Y'), [('W','X'),('W','Y'),('X','M'),('M','Y')], [('X','Y')])
return graph, table
cases = [('Ajuste', example_confounded(), [.26,.56]),
('Frontdoor', example_frontdoor(), [.38,.62]),
('Mixto anidado', example_nested(), [.315,.495])]
for label, (graph, table), target in cases:
kernel = source_kernel(graph.nodes, table)
trace = []
result = identify({'Y'}, {'X'}, kernel, graph, trace)
calculated = [read_entry(result, {'X':x, 'Y':1}) for x in (0,1)]
np.testing.assert_allclose(calculated, target, atol=1e-10)
print(label, '| distritos:', [sorted(v) for v in graph.districts()])
print('P(Y=1 | do(X=0,1)):', np.round(calculated,6), '| cálculo directo:', target)
print('Traza ID:', ' / '.join(trace))
if label == 'Frontdoor':
assert any(step.startswith('7:') for step in trace)
# La factorización Q usa la conjunta observacional, incluidos índices X.
factors = [q_factor(kernel, graph, district) for district in graph.districts()]
reconstructed = factors[0].array
for factor in factors[1:]:
reconstructed = reconstructed*factor.array
np.testing.assert_allclose(reconstructed, table)
print('Producto de factores Q reconstruye P:', np.allclose(reconstructed, table))
print('Expresión SymPy:', result.expression)
independent = ADMG(('X','Y'))
independent_table = np.outer([.5,.5],[.7,.3])
independent_result = identify({'Y'},{'X'},source_kernel(independent.nodes, independent_table),independent,[])
np.testing.assert_allclose([read_entry(independent_result,{'X':x,'Y':1}) for x in (0,1)], [.3,.3])
print('Sin camino causal, ambas intervenciones devuelven P(Y=1)=0,3.')
# Simulación independiente de las dos cirugías para el modelo frontdoor.
sim_rng = np.random.default_rng(13131)
sim_n = 50000
for x, truth in enumerate((.38,.62)):
u = sim_rng.random(sim_n)<.5
m = sim_rng.random(sim_n)<(.2+.6*x)
simulated = (sim_rng.random(sim_n)<(.1+.4*m+.4*u)).mean()
se = np.sqrt(truth*(1-truth)/sim_n)
assert abs(simulated-truth)<5*se
print('Simulación do(X=',x,'): P(Y=1)=',round(simulated,5),'| EE Monte Carlo=',round(se,5))
bow = ADMG(('X','Y'), [('X','Y')], [('X','Y')])
bow_table = np.array([[.4,.1],[.4,.1]])
try:
identify({'Y'}, {'X'}, source_kernel(bow.nodes,bow_table), bow, [])
except IdentificationFailure as failure:
print('Bow no identificable. Estructura recursiva local:', sorted(failure.graph_nodes), sorted(failure.district))
else:
raise AssertionError('El bow debe activar el fallo de identificación')
# Ambos SCM siguen el bow y tienen P(X,Y) idéntica y positiva. Con q=0,2,
# do(X=0) da 0,5 en Y=X xor U xor N y 0,2 en Y=(X and not U) xor N.
q = .2
tables = [np.zeros((2,2)) for _ in range(2)]
intervention = [0., 0.]
for u,n in itertools.product((0,1), repeat=2):
weight = .5*probability_binary(n,q)
x = u
ys = (x ^ u ^ n, (x & (1-u)) ^ n)
for j in (0,1):
tables[j][x,ys[j]] += weight
intervention[0] += weight*(0 ^ u ^ n)
intervention[1] += weight*((0 & (1-u)) ^ n)
np.testing.assert_allclose(tables[0], tables[1])
np.testing.assert_allclose(intervention, [.5,.2])
assert np.all(tables[0] > 0)
print('Bow: ambas conjuntas observadas:', tables[0].tolist(), '| P(Y=1|do(X=0)):', intervention)Now evaluate the symbolic tree returned for frontdoor directly on the observational distribution, independently of the algorithm’s matrix calculations:
# Evalúa la expresión SymPy en la tabla observacional, de modo independiente
# de los cálculos matriciales realizados en las llamadas recursivas.
graph_sym, table_sym = example_frontdoor()
kernel_sym = source_kernel(graph_sym.nodes, table_sym)
result_sym = identify({'Y'}, {'X'}, kernel_sym, graph_sym, [])
expanded_sym = result_sym.expression.doit()
p_sym = sp.IndexedBase('p')
mapping_sym = {p_sym[i,j,k]: float(table_sym[i,j,k])
for i,j,k in itertools.product((0,1),repeat=3)}
values_sym = []
for value_x in (0,1):
evaluated = expanded_sym.subs({kernel_sym.symbols['X']:value_x,
kernel_sym.symbols['Y']:1}).xreplace(mapping_sym)
values_sym.append(float(evaluated))
np.testing.assert_allclose(values_sym[-1], read_entry(result_sym, {'X':value_x,'Y':1}))
print('Evaluación directa SymPy del funcional frontdoor:', np.round(values_sym,6))Lab: compare identifiers
In your own local environment, install versions y0==0.2.11 and dowhy==0.14 and their dependencies. The following cells are self-contained and do not depend on files from the previous lab. The y0 identifier receives a mixed graph; evaluation traverses the returned tree and compares it numerically with known interventions in the same SCMs.
# Laboratorio local autocontenido. Requiere y0 0.2.11 instalado en el entorno.
import itertools
from math import prod
from y0.dsl import Variable, Probability, Product, Sum, Fraction
from y0.graph import NxMixedGraph
from y0.algorithm.identify import Identification, identify
from y0.algorithm.identify.utils import Unidentifiable
X, M, Y, Z = map(Variable, ('X', 'M', 'Y', 'Z'))
front_graph = NxMixedGraph.from_edges(nodes=[X,M,Y], directed=[(X,M),(M,Y)], undirected=[(X,Y)])
back_graph = NxMixedGraph.from_edges(nodes=[Z,X,Y], directed=[(Z,X),(Z,Y),(X,Y)], undirected=[])
bow_graph = NxMixedGraph.from_edges(nodes=[X,Y], directed=[(X,Y)], undirected=[(X,Y)])
def y0_id(graph):
return identify(Identification.from_parts(outcomes={Y}, treatments={X}, graph=graph))
expr_front = y0_id(front_graph)
expr_back = y0_id(back_graph)
print('y0 frontdoor:', expr_front.to_y0())
print('y0 backdoor:', expr_back.to_y0())
try:
y0_id(bow_graph)
except Unidentifiable:
print('y0 bow: no identificable')
else:
raise AssertionError('Se esperaba no identificación en bow')
# SCM idéntico al del laboratorio propio: U~Bern(.5), X|U=(.25,.75),
# M|X=(.2,.8), P(Y=1|M,U)=.1+.4 M+.4 U. U no figura en las tablas.
def bern(v,p):
return p if v else 1-p
front_table = {}
for u,x,m,y in itertools.product((0,1),repeat=4):
key=(x,m,y)
front_table[key] = front_table.get(key,0.)+.5*bern(x,.25+.5*u)*bern(m,.2+.6*x)*bern(y,.1+.4*m+.4*u)
back_table = {}
for z,x,y in itertools.product((0,1),repeat=3):
back_table[(z,x,y)] = bern(z,.4)*bern(x,.2+.6*z)*bern(y,.1+.3*x+.4*z)
def mass(table, names, assignment):
return sum(p for values,p in table.items()
if all(values[names.index(name)] == value for name,value in assignment.items()))
def evaluate(expression, table, names, env):
"""Evalúa el árbol de y0 sobre la tabla, respetando el alcance de cada suma."""
if isinstance(expression, Probability):
children = {v.name:env[v.name] for v in expression.children}
parents = {v.name:env[v.name] for v in expression.parents}
denominator = mass(table,names,parents)
if denominator <= 0:
raise ValueError('Condicional sin soporte')
return mass(table,names,{**children,**parents})/denominator
if isinstance(expression, Product):
return prod(evaluate(e,table,names,env) for e in expression.expressions)
if isinstance(expression, Sum):
ranges = sorted(v.name for v in expression.ranges)
return sum(evaluate(expression.expression,table,names,{**env,**dict(zip(ranges,bits))})
for bits in itertools.product((0,1),repeat=len(ranges)))
if isinstance(expression, Fraction):
return evaluate(expression.numerator,table,names,env)/evaluate(expression.denominator,table,names,env)
raise TypeError(f'Expresión no admitida: {type(expression).__name__}')
front = [evaluate(expr_front,front_table,('X','M','Y'),{'X':x,'Y':1}) for x in (0,1)]
back = [evaluate(expr_back,back_table,('Z','X','Y'),{'X':x,'Y':1}) for x in (0,1)]
for got, expected in zip(front, [.38,.62]):
assert abs(got-expected)<1e-12
for got, expected in zip(back, [.26,.56]):
assert abs(got-expected)<1e-12
print('y0 evaluado en P, frontdoor:', front, '| ID propio y cirugía: [0.38, 0.62]')
print('y0 evaluado en P, ajuste:', back, '| ID propio y cirugía: [0.26, 0.56]')npm run lab and open the connection link.In this particular DoWhy interface, encoding a bidirected edge using two opposite arcs of an DiGraph creates a cycle and the identifier rejects it. That does not prove the frontdoor effect is unidentifiable: it is a limitation of that representation. The first example, with observed confounder, does permit comparison of the adjustment expression.
# Comprobación local autocontenida con DoWhy 0.14 y NetworkX.
import networkx as nx
from dowhy.causal_identifier.id_identifier import identify_effect_id
graph = nx.DiGraph([('Z','X'),('Z','Y'),('X','Y')])
print('DoWhy, ajuste observado:', identify_effect_id(graph, ['X'], ['Y']))
# Dos arcos opuestos NO son un ADMG para este identificador: crean un ciclo.
# Esta prueba documenta el límite de la representación, no una prueba de que
# el efecto frontdoor sea no identificable, pues y0 sí lo identifica.
bidirected_as_cycle = nx.DiGraph([('X','M'),('M','Y'),('X','Y'),('Y','X')])
try:
identify_effect_id(bidirected_as_cycle, ['X'], ['Y'])
except Exception as exc:
if str(exc) != 'The graph must be a directed acyclic graph (DAG).':
raise
print('DoWhy: dos arcos opuestos rechazados como ciclo; no usar para representar X↔Y.')
else:
raise AssertionError('La versión probada no rechazó esta representación cíclica')npm run lab and open the connection link.Exercises
Step 1 of 3. What does indicator I do in the augmented model?
Step 1 of 3. What permits replacing P(m|do(x)) with P(m|x)?
Step 1 of 3. What is observed in both models when X=U?
def c_components(admg):
"""Distritos máximos, ordenados como los nodos del grafo."""
raise NotImplementedError
def q_factor(admg, S, P):
"""Factor del distrito S para el kernel binario actual."""
raise NotImplementedError