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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of observed variables and a test for with . The analysis assumes a DAG on , where is a set of latent variables, such that among the observed variables the independences are exactly the d-separations of . 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 over has an edge between and when no set of other observed variables separates them. The edge is when is an ancestor of in , and when neither is an ancestor of the other. In a MAG an arrowhead at thus means " is not an ancestor of ", and a tail at means " is an ancestor of ". Separation in a MAG (m-separation) is d-separation with edges allowed, and it gives the same answers as d-separation in . Two MAGs are Markov equivalent when they give the same separations.
The output is the PAG of the class of the MAG of : 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 , arrowhead at ), B <-> C and A --> D. The symbol * below stands for any mark.
The algorithm
Two definitions are needed. A triple is unshielded when and are edges and and are not adjacent. The set (Possible-D-SEP) of the graph after line L3 holds every node joined to by a path on which every inner triple has a collider at (arrowheads at on both edges) or has and adjacent.
FCI(V, CI)- 1
run the skeleton phase of PC on V, which gives a skeleton C and sepsets - 2
give every edge of C the mark o at both ends - 3
for each unshielded triple a, c, b with c ∉ sepset(a, b), orient a *→ c ←* b - 4
for each edge a - b of C and each x in {a, b} do - 5
for each S ⊆ PDS(x) \ {a, b}, smallest first do - 6
if CI(a, b, S) then delete a - b; sepset(a, b) ← S; go to the next edge - 7
set every mark back to o - 8
for each unshielded triple a, c, b with c ∉ sepset(a, b), orient a *→ c ←* b - 9
repeat - 10
apply R1, R2, R3 and R4 where they match - 11
apply R8, R9 and R10 to the edges a o→ c - 12
until 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 . 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-* cand , are not adjacent, orientb --> c. - R2. If
a --> b *-> cora *-> b --> c, anda *-o c, orienta *-> c. - R3. If
a *-> b <-* c,a *-o d o-* c, and are not adjacent, andd *-o b, orientd *-> b. - R4. A discriminating path for is a path on which is not adjacent to and every node between and is a collider on the path and a parent of . If
b o-* cends such a path, orientb --> cwhen , andα <-> b <-> cotherwise. - R8. If
a --> b --> cora -o b --> c, anda o-> c, orienta --> c. - R9. If
a o-> cand there is an uncovered potentially directed path with and not adjacent, orienta --> c. - R10. If
a o-> c,b --> c <-- t, and there are uncovered potentially directed paths from to and from to whose second nodes are distinct and not adjacent, orienta --> 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 be with latent. The skeleton phase removes , and , each with the empty set as separating set, and leaves . Both unshielded triples are colliders: puts arrowheads at , and puts arrowheads at . FCI returns
A o-> B, B <-> C, C <-o D.
The edge B <-> C says correctly that neither of , causes the other. PC on the same oracle meets two colliders that direct both ways, keeps the first arrow, and returns , a false claim that causes . PC makes 13 calls to the oracle here, and FCI makes 37.
The Possible-D-SEP phase. Let have the arrows and , and the latent variables with children , with children and with children . Its MAG is A --> D, A <-- B, A <-> F, B <-- C, C <-> E, D <-> E, E --> F.
- After line L1 the skeleton still has . The sets that PC tries are subsets of the other neighbours of or of , and none of them works. The empty set and leave open, leaves open, and leaves open, because its colliders and 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 is in through the path : the triple is shielded by the edge , and is a collider on . - Line L6 finds and removes .
- Line L8 orients the colliders again, which gives
A o-> DandE o-> F. The triple is now unshielded, andF <-> A o-> Dmatches R1, so the edge becomesA --> D. In the same wayD <-> E o-> FgivesE --> 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:
- 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.
- Colliders. In every MAG of the class, a node of an unshielded triple is a collider exactly when is outside one (and then every) separating set of and . So line L8 puts arrowheads only where every MAG of the class has them.
- R1 to R3. These rules are sound. An arrowhead at means that 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. is a DAG on , where is the finite set of observed nodes and the latent nodes. There is no selection. The oracle answers for and with the truth of , the d-separation in . This is what a perfect test gives under the causal Markov condition and faithfulness.
The MAG of over has an edge between and exactly when no d-separates them in . The edge is if is an ancestor of in , if is an ancestor of , and otherwise. We cite from Richardson and Spirtes (2002) that is ancestral (no directed cycle, and no with an ancestor of ) and that m-separation in equals d-separation in for sets of observed nodes. Two MAGs are Markov equivalent when they have the same m-separations. The class of is the set of MAGs Markov equivalent to . A MAG here has only the edges and , since there is no selection.
Lemma 1 (meaning of a mark). In a MAG without undirected edges, the edge between and has a tail at exactly when is an ancestor of in the MAG, and an arrowhead at exactly when is not an ancestor of .
Proof. If the edge is , then is an ancestor of . If it is , then is not an ancestor of , or there would be a directed cycle. If it is , then is not an ancestor of by the ancestral property. These are the only edges.
Lemma 2 (termination and the skeleton phase). Lines L1 to L6 stop. No edge of is removed, and every removed pair has with .
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 and are adjacent in , then by definition no subset of separates them, so the oracle never reports one, and the edge stays.
So the final skeleton contains the skeleton of . The converse, that every pair not adjacent in is removed, is the cited Possible-D-SEP theorem: some separating set of the pair lies inside or , 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 .
Lemma 3 (unshielded triples). Let be a MAG in the class of , and let and be non-adjacent with a common neighbour . Let be any set that m-separates and in . Then is a collider on in exactly when . So all MAGs of the class have the same skeleton and the same unshielded colliders.
Proof. The path has only the inner node . If is a collider and , the path is open, since a collider in is in and so in its ancestor set. If is not a collider and , the path is also open. Either case contradicts the separation. So is a collider exactly when . 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 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.
Lemma 4 (collider steps). After line L8, the arrowheads are exactly the arrowheads at the middle nodes of the unshielded colliders of , and every MAG of the class has them.
Proof. Line L8 puts arrowheads at on both edges of an unshielded triple exactly when . By Lemma 2 the recorded set m-separates and in , so by Lemma 3 this holds exactly when is a collider in , and then in every MAG of the class.
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 is any MAG of the class; by soundness, it has every non-circle mark of the current graph.
Lemma 5 (R1). If and , are not adjacent, then every MAG of the class has .
Proof. The triple is unshielded. It is not a collider in : if it were, line L8 would have put an arrowhead at on the edge from , and later rules never turn a mark into a circle, but the mark is a circle. By Lemma 3, is not a collider in either. has the arrowhead at from , so the edge between and has a tail at . A MAG without undirected edges then has .
Lemma 6 (R2). If or , and and are adjacent, then every MAG of the class has an arrowhead at on the edge between and .
Proof. By Lemma 1 it is enough to show that is not an ancestor of in . In the first case, is an ancestor of . If were an ancestor of , it would be an ancestor of , but the arrowhead at on the edge from says it is not. In the second case, is an ancestor of . If were an ancestor of , then would be an ancestor of , but the arrowhead at on the edge from says it is not.
Lemma 7 (R3). If , , and are not adjacent, and is adjacent to , then every MAG of the class has an arrowhead at on the edge between and .
Proof. The triple is unshielded with circles at , so as in Lemma 5 it is not a collider in . So one of its two edges has a tail at , say ; the case is the same. Suppose were an ancestor of . Then would be an ancestor of , but the arrowhead at on the edge from says it is not. So is not an ancestor of , and Lemma 1 gives the arrowhead.
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 applications, where 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 ends.
Theorem. With the oracle above, FCI stops. Its skeleton contains the skeleton of , and every removed pair has a true separating set. If the final skeleton is that of (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.
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 tests, as PC does. Lines L4 to L6 test at most sets for each of at most edges, which is again at most . So the worst case is 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 . The best case is the empty graph, with tests and nothing for lines L4 to L6. The separating sets take 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 on an edge to says that causes , directly or through other variables, in every model of the class.
a <-> bsays that neither causes the other, so a latent variable links them. A circle says nothing. - Weaker than PC without latent variables. When has no latent variables, the output has the skeleton and the colliders of the CPDAG of , but with fewer tails. For it gives
A o-> C <-o B, because the modelA <-> C <-- Bhas 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-> bdoes not say that causes ; it says only that does not cause . - 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HH185A Edit this page History Report an error Markdown