Algorithm Search⌘K

Algorithmresearch

FCI algorithm

Also called fast causal inference.

Extends the PC algorithm to allow latent confounders, and outputs a partial ancestral graph of the features all compatible models share.

Time
O(n^2 2^n) worstΘ(n^2) best
Space
O(n^3) extra
Where
n = the number of observed variables
Properties
deterministicexactofflineiterative
Origin
Peter Spirtes, Clark Glymour, Richard Scheines, 1993

The FCI algorithm (fast causal inference) learns causal structure from conditional independence when some common causes are not measured. Like the PC algorithm, it removes the edge between two variables when some set makes them independent, and then reads directions from the colliders that the removals reveal. Hidden variables make two changes. A pair can need a separating set with variables that are not its neighbours, so FCI searches a larger set called Possible-D-SEP. And an edge can stand for a hidden common cause, so FCI puts a mark at each end of an edge: an arrowhead, a tail, or a circle for "not known". The output is a partial ancestral graph (PAG), the features that all models compatible with the independences share.

In plain words

Suppose some causes in the system were never measured. Two measured variables can then be linked only because a hidden variable drives both. FCI first removes links between variables that some other variables make unrelated, as PC does, but it also searches farther away for those other variables, because hidden causes can hide the separating ones. Then it marks each end of each link. An arrowhead at a variable says that it does not cause the variable at the other end. A tail says that it does cause it. A circle says that the data cannot decide. Arrowheads at both ends say that neither causes the other, so a hidden cause links them.

The problem

The input is a finite set VV of nn observed variables and a test CI(a,b,S)\mathrm{CI}(a, b, S) for a⊥b∣Sa \perp b \mid S with S⊆VS \subseteq V. The analysis assumes a DAG GG on V∪LV \cup L, where LL is a set of latent variables, such that among the observed variables the independences are exactly the d-separations of GG. Unlike PC, FCI does not assume causal sufficiency: latent variables can be common causes of observed ones. This page and the implementation also assume no selection bias. The general algorithm allows it and has three more rules for it.

Many DAGs with latent variables give the same independences, so FCI works with a summary of them. The maximal ancestral graph (MAG) of GG over VV has an edge between aa and bb when no set of other observed variables separates them. The edge is a→ba \to b when aa is an ancestor of bb in GG, and a↔ba \leftrightarrow b when neither is an ancestor of the other. In a MAG an arrowhead at bb thus means "bb is not an ancestor of aa", and a tail at aa means "aa is an ancestor of bb". Separation in a MAG (m-separation) is d-separation with ↔\leftrightarrow edges allowed, and it gives the same answers as d-separation in GG. Two MAGs are Markov equivalent when they give the same separations.

The output is the PAG of the class of the MAG of GG: the common skeleton of the class, with an arrowhead or a tail at an end when every MAG of the class has that mark there, and a circle where two MAGs of the class differ. In text form an edge is written with its two marks, such as A o-> B (circle at AA, arrowhead at BB), B <-> C and A --> D. The symbol * below stands for any mark.

The algorithm

Two definitions are needed. A triple a,c,ba, c, b is unshielded when a−ca - c and c−bc - b are edges and aa and bb are not adjacent. The set PDS(a)\mathrm{PDS}(a) (Possible-D-SEP) of the graph after line L3 holds every node b≠ab \ne a joined to aa by a path on which every inner triple x,y,zx, y, z has a collider at yy (arrowheads at yy on both edges) or has xx and zz adjacent.

  1. FCI(V, CI)
  2. 1run the skeleton phase of PC on V, which gives a skeleton C and sepsets
  3. 2give every edge of C the mark o at both ends
  4. 3for each unshielded triple a, c, b with c ∉ sepset(a, b), orient a *→ c ←* b
  5. 4for each edge a - b of C and each x in {a, b} do
  6. 5for each S ⊆ PDS(x) \ {a, b}, smallest first do
  7. 6if CI(a, b, S) then delete a - b; sepset(a, b) ← S; go to the next edge
  8. 7set every mark back to o
  9. 8for each unshielded triple a, c, b with c ∉ sepset(a, b), orient a *→ c ←* b
  10. 9repeat
  11. 10apply R1, R2, R3 and R4 where they match
  12. 11apply R8, R9 and R10 to the edges a o→ c
  13. 12until no rule applies; return the PAG

Line L1 is lines L1 to L6 of PC. Lines L2 and L3 make a first PAG, used only to compute PDS\mathrm{PDS}. Lines L4 to L6 test sets inside it. Lines L7 and L8 orient the colliders again on the final skeleton. The rules of lines L10 and L11 are those of Zhang (2008), with the edge to change written last:

  • R1. If a *-> b o-* c and aa, cc are not adjacent, orient b --> c.
  • R2. If a --> b *-> c or a *-> b --> c, and a *-o c, orient a *-> c.
  • R3. If a *-> b <-* c, a *-o d o-* c, aa and cc are not adjacent, and d *-o b, orient d *-> b.
  • R4. A discriminating path for bb is a path θ,…,α,b,c\theta, \dots, \alpha, b, c on which θ\theta is not adjacent to cc and every node between θ\theta and bb is a collider on the path and a parent of cc. If b o-* c ends such a path, orient b --> c when b∈sepset(θ,c)b \in \mathrm{sepset}(\theta, c), and α <-> b <-> c otherwise.
  • R8. If a --> b --> c or a -o b --> c, and a o-> c, orient a --> c.
  • R9. If a o-> c and there is an uncovered potentially directed path a,b,θ,…,ca, b, \theta, \dots, c with bb and cc not adjacent, orient a --> c.
  • R10. If a o-> c, b --> c <-- t, and there are uncovered potentially directed paths from aa to bb and from aa to tt whose second nodes are distinct and not adjacent, orient a --> c.

A path is uncovered when every two nodes two steps apart on it are not adjacent, and potentially directed when no edge on it has an arrowhead pointing back or a tail pointing forward. R5 to R7 handle selection bias and are not needed here.

Example

PC fails, FCI does not. Let GG be A→B←L→C←DA \to B \leftarrow L \to C \leftarrow D with LL latent. The skeleton phase removes A−CA - C, A−DA - D and B−DB - D, each with the empty set as separating set, and leaves A−B−C−DA - B - C - D. Both unshielded triples are colliders: A,B,CA, B, C puts arrowheads at BB, and B,C,DB, C, D puts arrowheads at CC. FCI returns

A o-> B, B <-> C, C <-o D.

The edge B <-> C says correctly that neither of BB, CC causes the other. PC on the same oracle meets two colliders that direct B−CB - C both ways, keeps the first arrow, and returns A→B←C←DA \to B \leftarrow C \leftarrow D, a false claim that CC causes BB. PC makes 13 calls to the oracle here, and FCI makes 37.

The Possible-D-SEP phase. Let GG have the arrows C→B→A→DC \to B \to A \to D and E→FE \to F, and the latent variables L1L_1 with children A,FA, F, L2L_2 with children C,EC, E and L3L_3 with children D,ED, E. Its MAG is A --> D, A <-- B, A <-> F, B <-- C, C <-> E, D <-> E, E --> F.

  • After line L1 the skeleton still has D−FD - F. The sets that PC tries are subsets of the other neighbours {A,E}\{A, E\} of DD or of FF, and none of them works. The empty set and {E}\{E\} leave D←A←L1→FD \leftarrow A \leftarrow L_1 \to F open, {A}\{A\} leaves D←L3→E→FD \leftarrow L_3 \to E \to F open, and {A,E}\{A, E\} leaves D←L3→E←L2→C→B→A←L1→FD \leftarrow L_3 \to E \leftarrow L_2 \to C \to B \to A \leftarrow L_1 \to F open, because its colliders EE and AA are in the set.
  • After line L3 the graph is A <-> F, A <-o B, A o-> D, B o-o C, C o-> E, D <-> E, D o-o F, E o-> F. The node BB is in PDS(D)\mathrm{PDS}(D) through the path D,F,A,BD, F, A, B: the triple D,F,AD, F, A is shielded by the edge A−DA - D, and AA is a collider on F,A,BF, A, B.
  • Line L6 finds D⊥F∣{A,B,E}D \perp F \mid \{A, B, E\} and removes D−FD - F.
  • Line L8 orients the colliders again, which gives A o-> D and E o-> F. The triple F,A,DF, A, D is now unshielded, and F <-> A o-> D matches R1, so the edge becomes A --> D. In the same way D <-> E o-> F gives E --> F.

The output is A --> D, A <-> F, A <-o B, B o-o C, C o-> E, D <-> E, E --> F, after 329 calls. Every non-circle mark agrees with the MAG, and the circles are where MAGs of the class differ. Without lines L4 to L6, the output keeps a false edge D <-> F.

Correctness

The proof is in proofs/correctness.md. It is partial. With a perfect oracle it proves:

  1. Termination and skeleton. All phases stop. No edge of the MAG is removed, because adjacent nodes of the MAG are not separated by any set, and each removed pair has a true separating set.
  2. Colliders. In every MAG of the class, a node cc of an unshielded triple a,c,ba, c, b is a collider exactly when cc is outside one (and then every) separating set of aa and bb. So line L8 puts arrowheads only where every MAG of the class has them.
  3. R1 to R3. These rules are sound. An arrowhead at bb means that bb is not an ancestor of the other end, and a tail means that it is. With these readings, R1 avoids a collider that the class does not have, and R2 and R3 avoid an arrowhead at a node that is an ancestor.

Cited, not proved: that the Possible-D-SEP phase removes every edge not in the MAG (Spirtes, Meek and Richardson 1995; Spirtes, Glymour and Scheines 2000), the soundness of R4 and R8 to R10, and the completeness theorem of Zhang (2008): with no selection bias, R1 to R4 and R8 to R10 leave a circle exactly where two MAGs of the class differ. The tests check the full output against the PAG of every class of MAGs on three and four nodes.

Proof: With a perfect oracle for the d-separations among the observed nodes of a DAG with latent nodes and no selection, FCI stops, keeps every edge of the MAG, and every mark that the collider steps and the rules R1 to R3 set is shared by all MAGs of the classpartial

What is proved and what is cited. This file proves termination, that no edge of the true MAG is removed, that every removed pair has a true separating set, that the collider steps put arrowheads only where all MAGs of the class have them, and that R1, R2 and R3 are sound. Four results are cited and not proved here: the properties of the MAG of a DAG (Richardson and Spirtes 2002), that the Possible-D-SEP phase removes every edge that is not in the MAG (Spirtes, Meek and Richardson 1995; Spirtes, Glymour and Scheines 2000), the soundness of R4 and R8 to R10, and the completeness of R1 to R4 with R8 to R10 when there is no selection (Zhang 2008). The tests check the full claim, including completeness, on every MAG with three or four nodes.

Setting. GG is a DAG on V∪LV \cup L, where VV is the finite set of observed nodes and LL the latent nodes. There is no selection. The oracle answers CI(a,b,S)\mathrm{CI}(a, b, S) for a,b∈Va, b \in V and S⊆V∖{a,b}S \subseteq V \setminus \{a, b\} with the truth of (a⊥b∣S)G(a \perp b \mid S)_G, the d-separation in GG. This is what a perfect test gives under the causal Markov condition and faithfulness.

The MAG MM of GG over VV has an edge between aa and bb exactly when no S⊆V∖{a,b}S \subseteq V \setminus \{a, b\} d-separates them in GG. The edge is a→ba \to b if aa is an ancestor of bb in GG, a←ba \leftarrow b if bb is an ancestor of aa, and a↔ba \leftrightarrow b otherwise. We cite from Richardson and Spirtes (2002) that MM is ancestral (no directed cycle, and no a↔ba \leftrightarrow b with aa an ancestor of bb) and that m-separation in MM equals d-separation in GG for sets of observed nodes. Two MAGs are Markov equivalent when they have the same m-separations. The class of MM is the set of MAGs Markov equivalent to MM. A MAG here has only the edges →\to and ↔\leftrightarrow, since there is no selection.

Lemma 1 (meaning of a mark). In a MAG without undirected edges, the edge between aa and cc has a tail at cc exactly when cc is an ancestor of aa in the MAG, and an arrowhead at cc exactly when cc is not an ancestor of aa.

Proof. If the edge is c→ac \to a, then cc is an ancestor of aa. If it is a→ca \to c, then cc is not an ancestor of aa, or there would be a directed cycle. If it is a↔ca \leftrightarrow c, then cc is not an ancestor of aa by the ancestral property. These are the only edges. □\square

Lemma 2 (termination and the skeleton phase). Lines L1 to L6 stop. No edge of MM is removed, and every removed pair {a,b}\{a, b\} has sepset(a,b)=S\mathrm{sepset}(a, b) = S with (a⊥b∣S)G(a \perp b \mid S)_G.

Proof. Lines L1 and L4 to L6 make finitely many tests: each level of line L1 tests subsets of a finite set, the level grows by one each round, and it stops when it passes the largest degree; lines L4 to L6 test the subsets of finite sets once. An edge is removed only when the oracle reports a separation, and that separation is then true and recorded. If aa and bb are adjacent in MM, then by definition no subset of V∖{a,b}V \setminus \{a, b\} separates them, so the oracle never reports one, and the edge stays. □\square

So the final skeleton contains the skeleton of MM. The converse, that every pair not adjacent in MM is removed, is the cited Possible-D-SEP theorem: some separating set of the pair lies inside PDS(a)∖{b}\mathrm{PDS}(a) \setminus \{b\} or PDS(b)∖{a}\mathrm{PDS}(b) \setminus \{a\}, computed on the graph after line L3, and lines L4 to L6 test all subsets of both. The rest of this file assumes that the final skeleton is the skeleton of MM.

Lemma 3 (unshielded triples). Let M′M' be a MAG in the class of MM, and let aa and bb be non-adjacent with a common neighbour cc. Let SS be any set that m-separates aa and bb in M′M'. Then cc is a collider on a,c,ba, c, b in M′M' exactly when c∉Sc \notin S. So all MAGs of the class have the same skeleton and the same unshielded colliders.

Proof. The path a,c,ba, c, b has only the inner node cc. If cc is a collider and c∈Sc \in S, the path is open, since a collider in SS is in SS and so in its ancestor set. If cc is not a collider and c∉Sc \notin S, the path is also open. Either case contradicts the separation. So cc is a collider exactly when c∉Sc \notin S. For the second claim, two nodes are adjacent in a MAG exactly when no set m-separates them: an edge is an open path given every set, and maximality gives the converse. So equivalent MAGs have the same skeleton. Any separating set SS of a non-adjacent pair is a separating set in every MAG of the class, so the first claim gives the same colliders in all of them. □\square

Lemma 4 (collider steps). After line L8, the arrowheads are exactly the arrowheads at the middle nodes of the unshielded colliders of MM, and every MAG of the class has them.

Proof. Line L8 puts arrowheads at cc on both edges of an unshielded triple a,c,ba, c, b exactly when c∉sepset(a,b)c \notin \mathrm{sepset}(a, b). By Lemma 2 the recorded set m-separates aa and bb in MM, so by Lemma 3 this holds exactly when cc is a collider in MM, and then in every MAG of the class. □\square

The rules keep this invariant: every arrowhead and every tail of the current graph is in every MAG of the class. Call such a graph sound. A circle at an end does not claim anything. We now show that R1 to R3 map a sound graph to a sound graph. In each case M′M' is any MAG of the class; by soundness, it has every non-circle mark of the current graph.

Lemma 5 (R1). If a∗ ⁣ ⁣→b∘ ⁣ ⁣− ⁣ ⁣∗ca \mathrel{*\!\!\to} b \mathrel{\circ\!\!-\!\!*} c and aa, cc are not adjacent, then every MAG of the class has b→cb \to c.

Proof. The triple a,b,ca, b, c is unshielded. It is not a collider in MM: if it were, line L8 would have put an arrowhead at bb on the edge from cc, and later rules never turn a mark into a circle, but the mark is a circle. By Lemma 3, bb is not a collider in M′M' either. M′M' has the arrowhead at bb from aa, so the edge between bb and cc has a tail at bb. A MAG without undirected edges then has b→cb \to c. □\square

Lemma 6 (R2). If a→b∗ ⁣ ⁣→ca \to b \mathrel{*\!\!\to} c or a∗ ⁣ ⁣→b→ca \mathrel{*\!\!\to} b \to c, and aa and cc are adjacent, then every MAG of the class has an arrowhead at cc on the edge between aa and cc.

Proof. By Lemma 1 it is enough to show that cc is not an ancestor of aa in M′M'. In the first case, aa is an ancestor of bb. If cc were an ancestor of aa, it would be an ancestor of bb, but the arrowhead at cc on the edge from bb says it is not. In the second case, bb is an ancestor of cc. If cc were an ancestor of aa, then bb would be an ancestor of aa, but the arrowhead at bb on the edge from aa says it is not. □\square

Lemma 7 (R3). If a∗ ⁣ ⁣→b← ⁣ ⁣∗ca \mathrel{*\!\!\to} b \mathrel{\leftarrow\!\!*} c, a∗ ⁣ ⁣− ⁣ ⁣∘d∘ ⁣ ⁣− ⁣ ⁣∗ca \mathrel{*\!\!-\!\!\circ} d \mathrel{\circ\!\!-\!\!*} c, aa and cc are not adjacent, and dd is adjacent to bb, then every MAG of the class has an arrowhead at bb on the edge between dd and bb.

Proof. The triple a,d,ca, d, c is unshielded with circles at dd, so as in Lemma 5 it is not a collider in M′M'. So one of its two edges has a tail at dd, say d→ad \to a; the case d→cd \to c is the same. Suppose bb were an ancestor of dd. Then bb would be an ancestor of aa, but the arrowhead at bb on the edge from aa says it is not. So bb is not an ancestor of dd, and Lemma 1 gives the arrowhead. □\square

Lemma 8 (termination of the rules). If every rule application keeps the graph sound, the loop of lines L9 to L12 stops after at most 2∣E∣2|E| applications, where ∣E∣|E| is the number of edges.

Proof. Each rule in the implementation fires only on a circle and replaces it by an arrowhead or a tail. No step creates a circle. In a sound graph, a mark that is set already has the value of every MAG of the class, so a later rule that sets it again gives the same value. So each application lowers the number of circles by at least one, and there are 2∣E∣2|E| ends. □\square

Theorem. With the oracle above, FCI stops. Its skeleton contains the skeleton of MM, and every removed pair has a true separating set. If the final skeleton is that of MM (cited), then after line L8 and after every application of R1, R2 or R3 the graph is sound: every arrowhead and tail is in every MAG of the class.

Proof. Lemma 2 gives termination of lines L1 to L8 and the claims about the skeleton. Lemma 4 gives soundness after line L8. Lemmas 5 to 7 show that R1 to R3 keep soundness. With the cited soundness of R4 and R8 to R10, Lemma 8 gives termination of the rules. □\square

Cited results. Zhang (2008) proved that R4 and R8 to R10 are sound and that R1 to R4 with R8 to R10, applied until none applies to the correct skeleton with the correct unshielded colliders, leave a circle exactly at the ends where two MAGs of the class differ, when there is no selection. Together with the theorem above, this makes the output the PAG of the class. The test file checks this full claim against the PAG of every class of MAGs on three and four nodes (56 and 2492 MAGs), on all 543 DAGs on four nodes, on 300 random DAGs with latent nodes, and checks soundness on larger graphs.

Complexity

The cost is counted in calls to the test. Line L1 makes at most n(n−1)∑k(n−2k)=n(n−1)2n−2n(n - 1)\sum_{k}\binom{n - 2}{k} = n(n - 1)2^{n - 2} tests, as PC does. Lines L4 to L6 test at most 2⋅2n−22 \cdot 2^{n - 2} sets for each of at most (n2)\binom n2 edges, which is again at most n(n−1)2n−2n(n - 1)2^{n - 2}. So the worst case is O(n22n)O(n^2 2^n) tests. Unlike in PC, this bound does not become polynomial for sparse graphs: in the second example every node has all other nodes in its PDS\mathrm{PDS}. The best case is the empty graph, with (n2)\binom n2 tests and nothing for lines L4 to L6. The separating sets take O(n3)O(n^3) space.

The rules cost no tests. The implementation finds discriminating paths and uncovered potentially directed paths by depth-first search over simple paths, which is short to write but exponential in the worst case.

Properties

  • Exact with an oracle. With a perfect test and no selection bias, the output is the PAG of the class of the true MAG. Part of this is proved here, and the rest is cited.
  • Causal reading of marks. A tail at aa on an edge to bb says that aa causes bb, directly or through other variables, in every model of the class. a <-> b says that neither causes the other, so a latent variable links them. A circle says nothing.
  • Weaker than PC without latent variables. When GG has no latent variables, the output has the skeleton and the colliders of the CPDAG of GG, but with fewer tails. For A→C←BA \to C \leftarrow B it gives A o-> C <-o B, because the model A <-> C <-- B has the same independences.
  • Order dependent with data. As in PC, the skeleton depends on the order of the tests when the tests make errors.

Variants and improvements

  • Selection bias. The full algorithm of Zhang (2008) adds rules R5 to R7 for undirected edges, which appear when the sample was selected on a variable that the causes affect.
  • RFCI. Colombo, Maathuis, Kalisch and Richardson (2012) replace the Possible-D-SEP phase by a few extra tests on the triples that the orientation uses. The output can have extra edges but its marks are still correct as ancestral claims, and it runs much faster. They also proved high-dimensional consistency of FCI and RFCI for sparse graphs.
  • Stable versions. Colombo and Maathuis (2014) gave FCI-stable and conservative versions that do not depend on the order of the variables.
  • Other methods. Greedy equivalence search uses a score but assumes no latent variables. LiNGAM finds a full DAG from non-Gaussian data, also without latent variables.

When to use it

Use FCI when hidden common causes are likely and you want only claims that hold whatever the hidden structure is. The output tells which causal claims the independences support, and which pairs share a hidden cause. For a target effect, a tail or an arrowhead can be enough to choose an adjustment set or to rule one out. If all common causes are measured, PC gives more directed edges for less work. With many variables, use RFCI or limit the size of the conditioning sets.

Pitfalls

  • Circles are not arrows. a o-> b does not say that aa causes bb; it says only that bb does not cause aa.
  • The rules matter. On the 2492 MAGs on four nodes, the output after line L8 without the rules differed from the PAG on 552 of them.
  • Large conditioning sets. The Possible-D-SEP phase tests sets of any size. With data, these tests have little power, and a wrong removal spreads through the rules. The phase is rarely needed in small graphs: it removed an edge for 0 of 3000 random DAGs with one or two latent variables and five or six observed ones, and for 10 of 2362 random MAGs on seven nodes. These rates are measured, not proved.
  • Faithfulness. As in PC, near cancellations of paths make tests remove true edges.
  • Selection bias. The implementation assumes there is none. If the sample is selected on an effect, use the full rule set.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

fci_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fci-algorithm/. The authors are listed in prov/HH185A.jsonl.
"""The FCI algorithm: causal discovery with latent confounders.

The input is a set of observed nodes and a test ci(a, b, S). The output is a
partial ancestral graph (PAG). An edge between a and b has a mark at each
end. mark[(a, b)] is the mark at b on the edge between a and b:

    '>'  arrowhead: b is not an ancestor of a
    '-'  tail:      b is an ancestor of a
    'o'  circle:    the class does not agree

So a -> b has mark[(a, b)] == '>' and mark[(b, a)] == '-', a <-> b has '>'
at both ends, and a o-> b has mark[(b, a)] == 'o' and mark[(a, b)] == '>'.

The rules are R1 to R4 and R8 to R10 of Zhang (2008), which are complete when
there is no selection bias. This module assumes no selection bias.

It also contains m-separation for mixed graphs (directed and bidirected
edges), used as the oracle in the tests, and the construction of the
maximal ancestral graph (MAG) of a DAG with latent nodes.
"""

import itertools
from typing import NamedTuple


class FCIResult(NamedTuple):
    mark: dict       # (a, b) -> mark at b on the edge a *-* b
    sepset: dict     # frozenset({a, b}) -> separating set
    tests: int       # number of calls to the independence test
    pds_removed: list  # edges removed in the Possible-D-SEP phase


# ---------------------------------------------------------------------------
# Graph helpers for oracles


def ancestors_of(parents, nodes):
    seen = set(nodes)
    stack = list(nodes)
    while stack:
        v = stack.pop()
        for p in parents[v]:
            if p not in seen:
                seen.add(p)
                stack.append(p)
    return seen


def m_separated(mark, nodes, xs, ys, zs):
    """m-separation in a mixed graph given by end marks ('>' or '-').

    A walk is open if every collider is an ancestor of zs (or in zs) and every
    non-collider is outside zs. Such a walk exists exactly when an open path
    exists.
    """
    zs = set(zs)
    parents = {v: {u for u in nodes if mark.get((u, v)) == '>' and mark.get((v, u)) == '-'} for v in nodes}
    an_z = ancestors_of(parents, zs)
    nbrs = {v: [u for u in nodes if (u, v) in mark] for v in nodes}
    # state: (node, True if the edge used to reach node has an arrowhead at node)
    start = [(w, mark[(x, w)] == '>') for x in xs if x not in zs for w in nbrs[x]]
    seen = set()
    stack = []
    for st in start:
        if st not in seen:
            seen.add(st)
            stack.append(st)
    while stack:
        v, into = stack.pop()
        if v in ys:
            return False
        for w in nbrs[v]:
            collider = into and mark[(w, v)] == '>'
            if collider and v not in an_z:
                continue
            if not collider and v in zs:
                continue
            st = (w, mark[(v, w)] == '>')
            if st not in seen:
                seen.add(st)
                stack.append(st)
    return True


def m_oracle(mark, nodes):
    return lambda a, b, s: m_separated(mark, nodes, {a}, {b}, s)


def dag_marks(parents):
    """End marks of a DAG given as node -> set of parents."""
    mark = {}
    for v in parents:
        for p in parents[v]:
            mark[(p, v)] = '>'
            mark[(v, p)] = '-'
    return mark


def latent_oracle(parents, observed):
    """d-separation oracle of a DAG, for questions about observed nodes only."""
    nodes = list(parents)
    mark = dag_marks(parents)
    return lambda a, b, s: m_separated(mark, nodes, {a}, {b}, s)


def mag_of_dag(parents, observed):
    """The MAG over the observed nodes of a DAG with latent nodes (no selection).

    a and b are adjacent when no set of other observed nodes d-separates them.
    The edge is a -> b if a is an ancestor of b in the DAG, b -> a in the
    reverse case, and a <-> b otherwise.
    """
    ci = latent_oracle(parents, observed)
    obs = sorted(observed)
    mark = {}
    for a, b in itertools.combinations(obs, 2):
        rest = [v for v in obs if v not in (a, b)]
        if any(ci(a, b, set(s)) for k in range(len(rest) + 1) for s in itertools.combinations(rest, k)):
            continue
        if a in ancestors_of(parents, {b}):
            mark[(a, b)], mark[(b, a)] = '>', '-'
        elif b in ancestors_of(parents, {a}):
            mark[(a, b)], mark[(b, a)] = '-', '>'
        else:
            mark[(a, b)], mark[(b, a)] = '>', '>'
    return mark


# ---------------------------------------------------------------------------
# FCI


def adjacent(mark, a, b):
    return (a, b) in mark


def neighbours(mark, nodes, a):
    return [b for b in nodes if (a, b) in mark]


def orient_unshielded_colliders(mark, nodes, sepset):
    for c in nodes:
        for a, b in itertools.combinations(neighbours(mark, nodes, c), 2):
            if not adjacent(mark, a, b) and c not in sepset[frozenset((a, b))]:
                mark[(a, c)] = '>'
                mark[(b, c)] = '>'


def possible_d_sep(mark, nodes, a):
    """Nodes b with a path from a on which every inner triple <x, y, z> has y a
    collider or x, z adjacent."""
    out = set()
    seen = set()
    stack = []
    for w in neighbours(mark, nodes, a):
        seen.add((a, w))
        stack.append((a, w))
    while stack:
        x, y = stack.pop()
        out.add(y)
        for z in neighbours(mark, nodes, y):
            if z == x or z == a:
                continue
            collider = mark[(x, y)] == '>' and mark[(z, y)] == '>'
            if (collider or adjacent(mark, x, z)) and (y, z) not in seen:
                seen.add((y, z))
                stack.append((y, z))
    out.discard(a)
    return out


def is_pd_edge(mark, u, v):
    """The edge u *-* v can be read as u -> v: no arrowhead at u, no tail at v."""
    return mark[(v, u)] != '>' and mark[(u, v)] != '-'


def uncovered_pd_paths(mark, nodes, a, b):
    """All uncovered potentially directed paths from a to b."""
    out = []

    def extend(path):
        u = path[-1]
        if u == b:
            out.append(list(path))
            return
        for v in neighbours(mark, nodes, u):
            if v in path or not is_pd_edge(mark, u, v):
                continue
            if len(path) >= 2 and adjacent(mark, path[-2], v):
                continue
            path.append(v)
            extend(path)
            path.pop()

    extend([a])
    return out


def discriminating_thetas(mark, nodes, b, c):
    """Pairs (theta, alpha) where some path <theta, ..., alpha, b, c> is
    discriminating for b: every inner node before b is a collider on the path
    and a parent of c, and theta is not adjacent to c."""
    found = []

    def is_parent(x, y):
        return mark.get((x, y)) == '>' and mark.get((y, x)) == '-'

    def extend(path):
        # path = [b, alpha, ..., x], read backwards from b; x must be a collider and a parent of c
        x = path[-1]
        for w in neighbours(mark, nodes, x):
            if w in path or w == c or mark[(w, x)] != '>':
                continue
            if not adjacent(mark, w, c):
                found.append((w, path[1]))
            elif is_parent(w, c) and mark[(x, w)] == '>':
                path.append(w)
                extend(path)
                path.pop()

    for alpha in neighbours(mark, nodes, b):
        if alpha != c and mark[(b, alpha)] == '>' and is_parent(alpha, c):
            extend([b, alpha])
    return found


def apply_rules(mark, nodes, sepset):
    """Zhang's rules R1 to R4 and R8 to R10, until none applies."""
    changed = True
    while changed:  # @line L9
        changed = False
        for b in nodes:
            for c in neighbours(mark, nodes, b):
                for a in neighbours(mark, nodes, b):
                    if a == c:
                        continue
                    # R1: a *-> b o-* c, a and c not adjacent: b -> c
                    if mark[(a, b)] == '>' and mark[(c, b)] == 'o' and not adjacent(mark, a, c):  # @line L10
                        mark[(c, b)], mark[(b, c)] = '-', '>'
                        changed = True
                    # R2: a -> b *-> c or a *-> b -> c, and a *-o c: a *-> c
                    if adjacent(mark, a, c) and mark[(a, c)] == 'o':  # @line L10
                        if (mark[(b, a)] == '-' and mark[(a, b)] == '>' and mark[(b, c)] == '>') or \
                           (mark[(a, b)] == '>' and mark[(c, b)] == '-' and mark[(b, c)] == '>'):
                            mark[(a, c)] = '>'
                            changed = True
        # R3: a *-> b <-* c, a *-o d o-* c, a and c not adjacent, d *-o b: d *-> b
        for b in nodes:
            for a, c in itertools.combinations(neighbours(mark, nodes, b), 2):  # @line L10
                if adjacent(mark, a, c) or mark[(a, b)] != '>' or mark[(c, b)] != '>':
                    continue
                for d in neighbours(mark, nodes, b):
                    if d in (a, c) or not adjacent(mark, a, d) or not adjacent(mark, c, d):
                        continue
                    if mark[(a, d)] == 'o' and mark[(c, d)] == 'o' and mark[(d, b)] == 'o':
                        mark[(d, b)] = '>'
                        changed = True
        # R4: discriminating path <theta, ..., alpha, b, c> for b with b o-* c
        for b in nodes:
            for c in neighbours(mark, nodes, b):
                if mark[(c, b)] != 'o':
                    continue
                for theta, alpha in discriminating_thetas(mark, nodes, b, c):  # @line L10
                    if mark[(c, b)] != 'o':
                        break
                    if b in sepset.get(frozenset((theta, c)), set()):
                        mark[(c, b)], mark[(b, c)] = '-', '>'
                    else:
                        mark[(alpha, b)] = mark[(b, alpha)] = '>'
                        mark[(c, b)] = mark[(b, c)] = '>'
                    changed = True
        # Tail rules on edges a o-> c
        for a in nodes:
            for c in neighbours(mark, nodes, a):
                if not (mark[(c, a)] == 'o' and mark[(a, c)] == '>'):
                    continue
                tail = False
                # R8: a -> b -> c or a -o b -> c
                for b in neighbours(mark, nodes, a):  # @line L11
                    if b != c and adjacent(mark, b, c) and mark[(b, a)] == '-' and mark[(a, b)] in ('>', 'o') \
                            and mark[(c, b)] == '-' and mark[(b, c)] == '>':
                        tail = True
                # R9: uncovered p.d. path <a, b, theta, ..., c> with b and c not adjacent
                if not tail:
                    for b in neighbours(mark, nodes, a):  # @line L11
                        if b == c or adjacent(mark, b, c) or not is_pd_edge(mark, a, b):
                            continue
                        for p in uncovered_pd_paths(mark, nodes, b, c):
                            if a not in p and not adjacent(mark, a, p[1]):
                                tail = True
                                break
                        if tail:
                            break
                # R10: b -> c <- t, uncovered p.d. paths from a to b and to t whose
                # second nodes are distinct and not adjacent
                if not tail:
                    into_c = [b for b in neighbours(mark, nodes, c) if b != a and mark[(c, b)] == '-' and mark[(b, c)] == '>']
                    for b, t in itertools.combinations(into_c, 2):  # @line L11
                        mus = {p[1] for p in uncovered_pd_paths(mark, nodes, a, b) if c not in p}
                        oms = {p[1] for p in uncovered_pd_paths(mark, nodes, a, t) if c not in p}
                        if any(mu != om and not adjacent(mark, mu, om) for mu in mus for om in oms):
                            tail = True
                            break
                if tail:
                    mark[(c, a)] = '-'
                    changed = True
    return mark  # @line L12


def fci(nodes, ci):
    """Run FCI with the independence test ci(a, b, S). Returns an FCIResult."""
    nodes = sorted(nodes)
    adj = {v: set(nodes) - {v} for v in nodes}
    sepset = {}
    tests = 0
    k = 0
    while any(len(adj[a]) - 1 >= k for a in nodes):  # @line L1
        for a in nodes:
            for b in sorted(adj[a]):
                if b not in adj[a] or len(adj[a]) - 1 < k:
                    continue
                for s in itertools.combinations(sorted(adj[a] - {b}), k):
                    tests += 1
                    if ci(a, b, set(s)):  # @line L1
                        adj[a].discard(b)
                        adj[b].discard(a)
                        sepset[frozenset((a, b))] = set(s)
                        break
        k += 1
    mark = {(a, b): 'o' for a in nodes for b in adj[a]}  # @line L2
    orient_unshielded_colliders(mark, nodes, sepset)  # @line L3
    pds = {a: possible_d_sep(mark, nodes, a) for a in nodes}
    removed = []
    for a, b in itertools.combinations(nodes, 2):
        if not adjacent(mark, a, b):
            continue
        done = False
        for x in (a, b):  # @line L4
            cand = sorted(pds[x] - {a, b})
            for size in range(len(cand) + 1):
                for s in itertools.combinations(cand, size):  # @line L5
                    tests += 1
                    if ci(a, b, set(s)):  # @line L6
                        del mark[(a, b)]
                        del mark[(b, a)]
                        sepset[frozenset((a, b))] = set(s)
                        removed.append((a, b))
                        done = True
                        break
                if done:
                    break
            if done:
                break
    for e in mark:
        mark[e] = 'o'  # @line L7
    orient_unshielded_colliders(mark, nodes, sepset)  # @line L8
    apply_rules(mark, nodes, sepset)
    return FCIResult(mark, sepset, tests, removed)


def edge_string(mark, a, b):
    """Text form such as 'A o-> B' of the edge between a and b."""
    left = {'>': '<', '-': '-', 'o': 'o'}[mark[(b, a)]]
    right = {'>': '>', '-': '-', 'o': 'o'}[mark[(a, b)]]
    return f"{a} {left}-{right} {b}"


def pag_edges(mark):
    return sorted(edge_string(mark, a, b) for (a, b) in mark if str(a) < str(b))


if __name__ == "__main__":
    # A -> B <- L -> C <- D with L hidden.
    g = {"A": set(), "L": set(), "D": set(), "B": {"A", "L"}, "C": {"L", "D"}}
    obs = ["A", "B", "C", "D"]
    res = fci(obs, latent_oracle(g, obs))
    print(pag_edges(res.mark), "tests", res.tests)
test_fci_algorithm.py 253 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fci-algorithm/. The authors are listed in prov/HH185A.jsonl.

import itertools
import random

from fci_algorithm import (
    dag_marks, fci, latent_oracle, m_oracle, m_separated, mag_of_dag, pag_edges,
)


def ancestor_sets(mark, nodes):
    parents = {v: {u for u in nodes if mark.get((u, v)) == '>' and mark.get((v, u)) == '-'} for v in nodes}
    anc = {}
    for v in nodes:
        seen, stack = set(), [v]
        while stack:
            x = stack.pop()
            for p in parents[x]:
                if p not in seen:
                    seen.add(p)
                    stack.append(p)
        anc[v] = seen
    return anc


def signature(oracle, nodes):
    sig = []
    for a, b in itertools.combinations(nodes, 2):
        rest = [v for v in nodes if v not in (a, b)]
        for k in range(len(rest) + 1):
            for s in itertools.combinations(rest, k):
                sig.append(oracle(a, b, set(s)))
    return tuple(sig)


def all_mags(n):
    """All maximal ancestral graphs with directed and bidirected edges on n nodes."""
    nodes = list(range(n))
    pairs = list(itertools.combinations(nodes, 2))
    out = []
    for choice in itertools.product(range(4), repeat=len(pairs)):
        mark = {}
        for (u, v), c in zip(pairs, choice):
            if c == 1:
                mark[(u, v)], mark[(v, u)] = '>', '-'
            elif c == 2:
                mark[(u, v)], mark[(v, u)] = '-', '>'
            elif c == 3:
                mark[(u, v)], mark[(v, u)] = '>', '>'
        anc = ancestor_sets(mark, nodes)
        if any(v in anc[v] for v in nodes):
            continue  # directed cycle
        if any(mark[(u, v)] == '>' and mark[(v, u)] == '>' and (u in anc[v] or v in anc[u]) for (u, v) in pairs if (u, v) in mark):
            continue  # almost directed cycle
        ok = True
        for u, v in pairs:
            if (u, v) in mark:
                continue
            rest = [w for w in nodes if w not in (u, v)]
            if not any(m_separated(mark, nodes, {u}, {v}, set(s)) for k in range(len(rest) + 1) for s in itertools.combinations(rest, k)):
                ok = False  # not maximal
                break
        if ok:
            out.append(mark)
    return out


def pag_of_class(members):
    """Marks shared by all MAGs of a class; other marks are circles."""
    pag = {}
    for e in members[0]:
        ms = {m[e] for m in members}
        pag[e] = ms.pop() if len(ms) == 1 else 'o'
    return pag


def mag_classes(n):
    nodes = list(range(n))
    classes = {}
    for m in all_mags(n):
        classes.setdefault(signature(m_oracle(m, nodes), nodes), []).append(m)
    return {sig: pag_of_class(ms) for sig, ms in classes.items()}, classes


CLASSES = {n: mag_classes(n) for n in (3, 4)}


def test_worked_example_with_latent():
    g = {"A": set(), "L": set(), "D": set(), "B": {"A", "L"}, "C": {"L", "D"}}
    obs = ["A", "B", "C", "D"]
    res = fci(obs, latent_oracle(g, obs))
    assert pag_edges(res.mark) == ["A o-> B", "B <-> C", "C <-o D"]


PDS_EXAMPLE = {"A": {"B", "L1"}, "B": {"C"}, "C": {"L2"}, "D": {"A", "L3"}, "E": {"L2", "L3"},
               "F": {"E", "L1"}, "L1": set(), "L2": set(), "L3": set()}


def test_possible_d_sep_phase_removes_an_edge():
    obs = list("ABCDEF")
    res = fci(obs, latent_oracle(PDS_EXAMPLE, obs))
    assert res.pds_removed == [("D", "F")]
    assert res.sepset[frozenset(("D", "F"))] == {"A", "B", "E"}
    assert pag_edges(res.mark) == ["A --> D", "A <-> F", "A <-o B", "B o-o C", "C o-> E", "D <-> E", "E --> F"]
    mag = mag_of_dag(PDS_EXAMPLE, obs)
    assert pag_edges(mag) == ["A --> D", "A <-- B", "A <-> F", "B <-- C", "C <-> E", "D <-> E", "E --> F"]
    for e, m in res.mark.items():
        assert m == 'o' or m == mag[e]


def test_m_separation_matches_dag_d_separation():
    # On DAGs, m-separation is d-separation; compare with the moral-graph method.
    rng = random.Random(5)
    for _ in range(50):
        n = 5
        parents = {v: {u for u in range(v) if rng.random() < 0.4} for v in range(n)}
        mark = dag_marks(parents)
        for a, b in itertools.combinations(range(n), 2):
            rest = [v for v in range(n) if v not in (a, b)]
            for k in range(3):
                for s in itertools.combinations(rest, k):
                    assert m_separated(mark, list(range(n)), {a}, {b}, set(s)) == moral_dsep(parents, a, b, set(s))


def moral_dsep(parents, a, b, s):
    keep, stack = {a, b} | s, [a, b, *s]
    while stack:
        v = stack.pop()
        for p in parents[v]:
            if p not in keep:
                keep.add(p)
                stack.append(p)
    nb = {v: set() for v in keep}
    for v in keep:
        ps = list(parents[v])
        for p in ps:
            nb[v].add(p)
            nb[p].add(v)
        for p, q in itertools.combinations(ps, 2):
            nb[p].add(q)
            nb[q].add(p)
    seen, stack = {a}, [a]
    while stack:
        v = stack.pop()
        if v == b:
            return False
        for w in nb[v]:
            if w not in seen and w not in s:
                seen.add(w)
                stack.append(w)
    return True


def test_number_of_mags_and_classes():
    pags3, classes3 = CLASSES[3]
    pags4, classes4 = CLASSES[4]
    # Counts found by this enumeration (MAGs without undirected edges).
    assert sum(len(c) for c in classes3.values()) == 56
    assert len(classes3) == 11  # on three nodes, the same independence models as DAGs
    assert sum(len(c) for c in classes4.values()) == 2492
    assert len(classes4) == 248  # 185 of them are DAG models


def check_every_mag(n):
    nodes = list(range(n))
    pags, classes = CLASSES[n]
    for sig, members in classes.items():
        want = pag_edges(pags[sig])
        for m in members:
            res = fci(nodes, m_oracle(m, nodes))
            assert pag_edges(res.mark) == want


def test_every_mag_on_three_nodes():
    check_every_mag(3)


def test_every_mag_on_four_nodes():
    check_every_mag(4)


def test_dags_without_latents_four_nodes():
    pags, _ = CLASSES[4]
    nodes = list(range(4))
    pairs = list(itertools.combinations(nodes, 2))
    count = 0
    for choice in itertools.product((0, 1, 2), repeat=6):
        parents = {v: set() for v in nodes}
        for (u, v), c in zip(pairs, choice):
            if c == 1:
                parents[v].add(u)
            elif c == 2:
                parents[u].add(v)
        mark = dag_marks(parents)
        if any(v in s for v, s in ancestor_sets(mark, nodes).items()):
            continue
        count += 1
        oracle = latent_oracle(parents, nodes)
        res = fci(nodes, oracle)
        assert pag_edges(res.mark) == pag_edges(pags[signature(oracle, nodes)])
    assert count == 543


def random_latent_dag(rng, n_obs, n_lat, p):
    names = list(range(n_obs)) + [f"L{i}" for i in range(n_lat)]
    order = names[:]
    rng.shuffle(order)
    parents = {v: set() for v in names}
    for i, j in itertools.combinations(range(len(order)), 2):
        if rng.random() < p:
            parents[order[j]].add(order[i])
    for lat in names[n_obs:]:
        # make each latent a source with at least two observed children
        parents[lat] = set()
    for v in names:
        parents[v] = {u for u in parents[v] if u in names}
    for lat in names[n_obs:]:
        kids = rng.sample(range(n_obs), 2)
        for k in kids:
            parents[k].add(lat)
    return parents


def test_latent_dags_four_observed_against_mag_classes():
    pags, _ = CLASSES[4]
    rng = random.Random(20261114)
    nodes = list(range(4))
    for _ in range(300):
        g = random_latent_dag(rng, 4, rng.choice((1, 2)), 0.35)
        if any(v in s for v, s in ancestor_sets(dag_marks(g), list(g)).items()):
            continue
        oracle = latent_oracle(g, nodes)
        res = fci(nodes, oracle)
        assert pag_edges(res.mark) == pag_edges(pags[signature(oracle, nodes)])


def test_soundness_on_larger_latent_dags():
    # Every non-circle mark of the output must agree with the MAG of the DAG,
    # and the skeleton must be the MAG skeleton. (Soundness check, not completeness.)
    rng = random.Random(99)
    checked = 0
    while checked < 40:
        g = random_latent_dag(rng, rng.choice((5, 6)), rng.choice((1, 2)), 0.3)
        if any(v in s for v, s in ancestor_sets(dag_marks(g), list(g)).items()):
            continue
        obs = [v for v in g if not str(v).startswith("L")]
        mag = mag_of_dag(g, obs)
        res = fci(obs, latent_oracle(g, obs))
        assert set(res.mark) == set(mag)
        for e, m in res.mark.items():
            assert m == 'o' or m == mag[e]
        checked += 1

History

Spirtes, Glymour and Scheines gave the FCI algorithm in Causation, Prediction, and Search (1993). Spirtes, Meek and Richardson (1995) extended it to selection bias. Richardson and Spirtes (2002) put the output on the footing of maximal ancestral graphs. Zhang (2008) added the rules R5 to R10 and proved that the augmented rules are complete, so that each remaining circle is a real ambiguity. Colombo, Maathuis, Kalisch and Richardson (2012) gave the faster RFCI and proved high-dimensional consistency.

References

  1. Peter Spirtes, Clark Glymour and Richard Scheines, Causation, Prediction, and Search, 2nd edition, MIT Press, 2000, Chapter 6 (causal discovery with latent variables, with the FCI algorithm and Possible-D-SEP; general locator)
  2. Peter Spirtes, Christopher Meek and Thomas Richardson, Causal inference in the presence of latent variables and selection bias, Proceedings of the 11th Conference on Uncertainty in Artificial Intelligence (UAI 1995), Morgan Kaufmann, pp. 499 to 506, The whole paper (FCI with selection bias, and the correctness of its skeleton and orientation steps)
  3. Thomas Richardson and Peter Spirtes, Ancestral graph Markov models, The Annals of Statistics 30(4), 2002, pp. 962 to 1030, The whole paper (maximal ancestral graphs, m-separation, and the MAG of a DAG with latent and selection variables)
  4. Jiji Zhang, On the completeness of orientation rules for causal discovery in the presence of latent confounders and selection bias, Artificial Intelligence 172(16-17), 2008, pp. 1873 to 1896, The whole paper (the rules R1 to R10, their soundness, and the completeness of the augmented FCI)
  5. Diego Colombo, Marloes H. Maathuis, Markus Kalisch and Thomas S. Richardson, Learning high-dimensional directed acyclic graphs with latent and selection variables, The Annals of Statistics 40(1), 2012, pp. 294 to 321, The whole paper (the RFCI variant and the consistency of FCI and RFCI in high dimensions)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example