Module contents
Lesson 13 of 28Advanced 120 min

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, GXˉG_{\bar X} removes arrows entering XX and GZ‾G_{\underline Z} removes arrows leaving ZZ. With bidirected edges due to latent confounding, removing arrowheads at XX 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 X,Y,Z,WX,Y,Z,W, Pearl’s do-calculus offers three transformations. Equalities apply where conditionals are defined:

  1. Insert or delete an observation. If (Y⊥Z∣X,W)GXˉ(Y\perp Z\mid X,W)_{G_{\bar X}},

    P(y∣do(x),z,w)=P(y∣do(x),w).P(y\mid do(x),z,w)=P(y\mid do(x),w).
  2. Exchange action and observation. If (Y⊥Z∣X,W)GXˉ,Z‾(Y\perp Z\mid X,W)_{G_{\bar X,\underline Z}},

    P(y∣do(x),do(z),w)=P(y∣do(x),z,w).P(y\mid do(x),do(z),w)=P(y\mid do(x),z,w).
  3. Insert or delete an action. Let Z(W)=Z∖An(W)GXˉZ(W)=Z\setminus An(W)_{G_{\bar X}}. If (Y⊥Z∣X,W)GXˉ,Z(W)‾(Y\perp Z\mid X,W)_{G_{\bar X,\overline{Z(W)}}},

    P(y∣do(x),do(z),w)=P(y∣do(x),w).P(y\mid do(x),do(z),w)=P(y\mid do(x),w).

The third condition removes incoming arrows only for variables in ZZ that are not ancestors of WW in GXˉG_{\bar X}. The checking graph changes between rules: applying them to the original graph can yield false equalities.

InteractiveProofs with the three rules

Start with P(Y | do(X)). Rule 1 inserts or removes an observation; rule 2 exchanges observation and intervention; rule 3 inserts or removes an intervention. The button changes only this conditional expression.

For rule 2: check Y ⟂ X | ∅ in the graph with incoming edges cut at ∅ and outgoing edges cut at X.

XMYU1

Each U is a latent common cause representing a bidirected edge. Dashed edges are cut; orange highlights an active path, if any. Active witness: Y - U1 - X.

No rule has been applied yet.

The sufficient graphical conditions use the assumed graph and conditional equalities on their support. Total probability and the product rule are additional steps: this panel does not invent a sum or claim to derive frontdoor in one expression.

Rule
Current expressionP(Y | do(X))
Graphical conditionNot satisfied
Check each separation in the graph required by the chosen rule.

Justification starts from the SCM and truncated factorization in an expanded DAG. In rule one, after fixing XX, the graphical condition implies conditional independence in the intervened distribution; canceling the distribution of ZZ when conditioning yields the equality. In rule two, after removing outgoing edges from ZZ, separation ensures selection by the mechanism generating ZZ adds no information about YY given X,WX,W; replacing that mechanism by a constant leaves the conditional unchanged. In rule three, factors for intervened variables that can affect WW 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 ZZ, add an independent exogenous indicator II selecting between the original equation of ZZ and constant zz. Under do(X=x)do(X=x), the condition in GXˉ,Z‾G_{\bar X,\underline Z} implies by d-separation Y⊥I∣X,Z,WY\perp I\mid X,Z,W in the augmented graph. With I=0I=0 the conditional is the observational one for ZZ within the intervention on XX; with I=1I=1 it is the conditional after do(Z=z)do(Z=z). Independence equates them when both conditions have support. For a set ZZ use a joint intervention and apply the same argument to its mechanisms.

For rule 3 introduce a vector of exogenous indicators IZI_Z whose “off” and zz values select original mechanisms and constants respectively. The graphical equivalence in Pearl’s proof converts the condition with Z(W)Z(W) into Y⊥IZ∣X,WY\perp I_Z\mid X,W in augmented graph GXˉG_{\bar X}. The ancestor distinction matters: only incoming edges of nodes in ZZ that cannot be ancestors of WW in GXˉG_{\bar X} are cut; cutting all could certify a false equality.

To make the probability step explicit, call Ki(y,w)K_i(y,w) the sum of the truncated factorization over all variables other than Y,WY,W after fixing X=xX=x and indicator IZ=iI_Z=i. With i=zi=z, factors for ZZ are replaced by indicators of their values; with i=apagadoi=\mathrm{apagado} they are retained. The graphical independence obtained by Markov implies

Kz(y,w)∑y′Kz(y′,w)=P(y∣do(x),IZ=z,w)=P(y∣do(x),IZ=apagado,w)=Kapagado(y,w)∑y′Kapagado(y′,w).\frac{K_z(y,w)}{\sum_{y'}K_z(y',w)} =P(y\mid do(x),I_Z=z,w) =P(y\mid do(x),I_Z=\mathrm{apagado},w) =\frac{K_{\mathrm{apagado}}(y,w)}{\sum_{y'}K_{\mathrm{apagado}}(y',w)}.

By definition of the indicators, the first ratio is P(y∣do(x),do(z),w)P(y\mid do(x),do(z),w) and the last is P(y∣do(x),w)P(y\mid do(x),w). This proof uses the graphical equivalence of rule 3 and positive denominators; it does not confuse the observed value of ZZ with the exogenous selector of its mechanism.

Deriving backdoor and frontdoor

If ZZ satisfies backdoor, it is not a descendant of XX and XX and YY are separated by ZZ in GX‾G_{\underline X}. By total probability and rule 2,

P(y∣do(x))=∑zP(y∣do(x),z)P(z∣do(x))=∑zP(y∣x,z)P(z).P(y\mid do(x)) =\sum_z P(y\mid do(x),z)P(z\mid do(x)) =\sum_z P(y\mid x,z)P(z).

The last factor is P(z)P(z) because intervening on XX does not change its nondescendants. Support is required in the strata used.

For frontdoor, let MM be the mediator and assume the three conditions from the previous lesson. First P(m∣do(x))=P(m∣x)P(m\mid do(x))=P(m\mid x) by rule 2, because there is no open backdoor path from XX to MM. Next, rules 2 and 3 allow, in the corresponding mutilated graphs, conversion and removal of the action on XX once MM is fixed:

P(y∣do(x),m)=P(y∣do(x),do(m))=P(y∣do(m)).P(y\mid do(x),m) =P(y\mid do(x),do(m)) =P(y\mid do(m)).

Finally, as XX blocks backdoor paths from MM to YY, the backdoor formula applied to MM gives P(y∣do(m))=∑x′P(y∣m,x′)P(x′)P(y\mid do(m))=\sum_{x'}P(y\mid m,x')P(x'). Substitution yields:

P(y∣do(x))=∑mP(m∣x)∑x′P(y∣m,x′)P(x′).P(y\mid do(x)) =\sum_m P(m\mid x)\sum_{x'}P(y\mid m,x')P(x').

The first equality depends on absence of unblocked confounding between XX and MM; the second requires every directed path from XX to YY to pass through MM and the other frontdoor conditions. A graph change requires every separation to be checked again.

With two time-ordered treatments X1,X2X_1,X_2 and observed intermediate variable LL, in the DAG without unmeasured confounding containing X1→LX_1\to L, X1→X2X_1\to X_2, L→X2L\to X_2, X1→YX_1\to Y, L→YL\to Y and X2→YX_2\to Y, truncated factorization yields

P(y∣do(x1),do(x2))=∑lP(l∣x1)P(y∣x1,l,x2).P(y\mid do(x_1),do(x_2)) =\sum_l P(l\mid x_1)P(y\mid x_1,l,x_2).

Here LL 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 SS of current population VV, Q[S]=PV∖S(S)Q[S]=P_{V\setminus S}(S) is its kernel under intervention on the remaining variables. If the input kernel corresponds to that graph and topological order V1,…,VnV_1,\ldots,V_n is used, the district factor is obtained by multiplying chain-rule ratios for nodes of SS:

Q[S]=∏i:Vi∈SP(vi∣v1,…,vi−1).Q[S]=\prod_{i:V_i\in S}P(v_i\mid v_1,\ldots,v_{i-1}).

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 Q[S]Q[S] for an arbitrary subset.

InteractiveSplit a graph into c-components

Directed arrows stay fixed. Each curved double-headed line represents a latent common cause; two nodes belong to the same district if connected by a chain of bidirected edges. Colors show maximal components.

ABCD

For the current kernel P(A,B,C,D), each factor of a district S is obtained by multiplying conditionals for variables in S in the full topological order. Variables outside S can appear in the conditioning sets.

Q[{A, C}] = P(A) · P(C | A, B)
Q[{B}] = P(B | A)
Q[{D}] = P(D | A, B, C)

Here Q[S] = P(S | do(V∖S)) as a kernel under the assumed semi-Markovian ADMG. The identity holds for maximal districts of the graph and the current kernel, with conditionals defined on their support; it does not claim to work for every subset. Multiplying the factors recovers P(A,B,C,D).

Districts3
Topological orderA, B, C, D
Edit bidirected edges and observe districts and their factors.

ID: decompose, recurse, or declare failure

The ID algorithm takes an acyclic semi-Markovian ADMG and observational distribution and seeks to express P(y∣do(x))P(y\mid do(x)) for action and outcome sets. Each call maintains a graph and a kernel. The presentation by Shpitser and Pearl follows these cases:

  1. If no actions remain, marginalize non-outcome variables.
  2. If nodes are not ancestors of outcomes in the current graph, marginalize them and restrict the problem to ancestors.
  3. After cutting incoming edges of actions, add to actions the nodes no longer ancestral to outcomes.
  4. 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.
  5. If one district remains and the current graph is also one district, declare identification failure in that call.
  6. If the remaining district is a district of the current graph, return its chain-rule factor and marginalize what remains.
  7. 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.

InteractiveThe ID algorithm step by step

Choose an ADMG and follow a real execution of ID for P(Y|do(X)). The drawing retains the original graph; faded nodes and edges are outside the current call’s subgraph. Hidden confounding X↔Y prevents direct adjustment, but M satisfies frontdoor.

XMY
  • Intervention in the call
  • Outcome of the call
  • Directed arrow
  • Latent confounding
Step 1 of 7

Call: ID(Y={Y}, X={X}); depth 0. Decompose G without X into districts and call ID for each.

Incoming kernel
P(X, M, Y)
1. If X is empty, marginalize.
2. Retain the ancestors of Y.
3. Add interventions that do not affect Y.
4. Separate districts of G without X.
5. If all of G is one district, fail.
6. If S is a district of G, factorize.
7. If S is in a larger district, recurse.

A simplified equivalent form: Σ_m P(m|x) Σ_x′ P(y|m,x′)P(x′). The expression constructed by the calls can contain additional sums and quotients; simplification uses graph independences and positive support.

The algorithm operates on the call kernel, which may depend on variables outside the subgraph. Each chain factor is built as a quotient of kernel marginals. Line 3 may introduce auxiliary intervention values: under the assumed graph, the result does not depend on them.

Procedure and numbering: Shpitser and Pearl, Identification of Joint Interventional Distributions, figure 3. Identification depends on the graph and necessary observational probabilities; it does not imply statistical precision or prove causal assumptions.

Active line4
Call depth0
Overall resultIdentified
Follow recursive calls on the current graph and kernel.

Completeness and the bow graph

A hedge is a pair of nested graphical structures certifying nonidentification under appropriate conditions. The bow has X→YX\to Y and X↔YX\leftrightarrow Y: the bidirected arrow represents a latent confounder. For the effect of XX on YY, structures with nodes {X,Y}\{X,Y\} and {Y}\{Y\} provide the canonical example.

A forest CC 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, F′F' is a proper subforest of FF, both share roots RR, FF intersects actions XX and F′F' does not, and RR is among outcome ancestors in GXˉG_{\bar X}. In the bow, FF contains both edges X→YX\to Y and X↔YX\leftrightarrow Y, F′={Y}F'=\{Y\} and the common root is YY.

A concrete construction demonstrates the limitation without relying only on a label. Let U∼Bernoulli⁡(1/2)U\sim\operatorname{Bernoulli}(1/2), independent N∼Bernoulli⁡(q)N\sim\operatorname{Bernoulli}(q), 0<q<10<q<1 and X:=UX:=U. In model A, Y:=X⊕U⊕NY:=X\oplus U\oplus N; in B, Y:=(X∧¬U)⊕NY:=(X\land\neg U)\oplus N. Observationally both have Y=NY=N and the same full-support joint distribution. But under do(X=0)do(X=0), PA(Y=1)=1/2P_A(Y=1)=1/2 and PB(Y=1)=qP_B(Y=1)=q. Both models make causes X,UX,U of YY functionally relevant when q≠1/2q\ne1/2.

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.

[ ]Set up graphs and tablesBrowser
import networkx as nx
import numpy as np
import itertools
[ ]Set up symbolic expressionsBrowser
import sympy as sp
[ ]ADMG, Q factors, and recursive IDBrowser
class 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.

[ ]Four queries and a counterexampleBrowser
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:

[ ]Evaluate the symbolic expressionBrowser
# 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.

[ ]Compare ID with y0Local GPU
# 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]')
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

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

Exercises

ProofAction versus observation
Prove: Assume an expanded acyclic SCM, values with support, and (Y⊥Z∣X,W)GXˉ,Z‾(Y\perp Z\mid X,W)_{G_{\bar X,\underline Z}}. Justify rule 2 using an exogenous indicator that changes the mechanism of ZZ.
The proof will appear here as you work.

Step 1 of 3. What does indicator I do in the augmented model?

ProofDerive frontdoor using rules
Prove: Suppose M intercepts every directed path X→Y, there is no unblocked confounding between X and M, and X blocks backdoor paths between M and Y. The required conditionals have support.
The proof will appear here as you work.

Step 1 of 3. What permits replacing P(m|do(x)) with P(m|x)?

ProofTwo worlds with the same observation
Prove: In the bow X→YX\to Y and X↔YX\leftrightarrow Y, take U∼Bernoulli(1/2)U\sim Bernoulli(1/2) and N∼Bernoulli(q)N\sim Bernoulli(q) independent, 0<q<10<q<1, q≠1/2q\ne1/2, and X:=UX:=U. Compare YA:=X⊕U⊕NY_A:=X\oplus U\oplus N and YB:=(X∧¬U)⊕NY_B:=(X\land\neg U)\oplus N.
The proof will appear here as you work.

Step 1 of 3. What is observed in both models when X=U?

QuizA DAG without latent variables
In the observed graph X→Y with no other variables or latent confounders, is P(y|do(x)) identifiable?
QuizObserved confounder
In Z→X, Z→Y and X→Y with Z observed, what follows for the total effect?
QuizLatent confounding with a mediator
In X↔Y and X→M→Y, with no other edges and with support, is the total effect identifiable?
QuizThe bow
In X→Y and X↔Y, with no other measured variables, what does nonparametric identification say?
QuizAssociation without a causal path
With X↔Y as the only edge and no directed path from X to Y, what is P(y|do(x))?
QuizAn additional isolated variable
Add an observed variable W without edges to X→Y, X↔Y. Does W identify the effect of X on Y?
CodeDistricts and Q factors
Implement districts and the chain factor used by ID. A graph is a dictionary with required keys nodes, directed, and bidirected. nodes is a nonempty tuple of distinct names in topological order; each name is a nonempty string. Each edge collection is a list or tuple of name pairs. Directed edges must respect that order; bidirected edges are unoriented, and loops and unknown endpoints are forbidden. A bow is allowed: a directed arrow and a bidirected edge between the same two nodes. c_components(admg) returns a list of tuples containing maximal districts connected only by bidirected edges. Within and between districts use nodes order; include isolated nodes. q_factor(admg, S, P) receives S, an iterable of names of one complete maximal district, and a positive normalized binary kernel. The optional fixed key is a tuple of names distinct from nodes. Each P key is a binary tuple in fixed + nodes order. For each fixed-variable value, P sums to 1 over nodes. Edges from fixed variables to random nodes are allowed; bidirected edges join only random nodes. The kernel belongs to the current call: it may be a joint distribution or a kernel obtained in a previous call. Preserve all its arguments. For each complete assignment return the product of P(v_i | v_1,...,v_{i-1}, fixed) for v_i in S, using the chain rule applied to this kernel. To calculate each ratio, marginalize nodes after the corresponding index. The result is a dictionary with the same keys as P; it need not sum to 1 over all graph nodes. Raise ValueError for an invalid graph, an S that is not a maximal district, or an incomplete, nonpositive, or unnormalized kernel. Tables are small and no external libraries are needed.
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
Shift+Enter to run