Algorithmadvanced
PC algorithm
Also called Peter-Clark algorithm, Spirtes-Glymour algorithm.
Learns the Markov equivalence class of a causal DAG by deleting edges by conditional independence tests of growing size, then orienting colliders and further edges.
- Time
- O(n^2 2^n) worstΘ(n^2) best
- Space
- O(n^3) extra
- Where
- n = the number of variables; q = the largest number of neighbours of a node in the true DAG
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter Spirtes, Clark Glymour, 1991
The PC algorithm learns causal structure from conditional independence. It assumes the data come from an unknown directed acyclic graph whose d-separations are exactly the conditional independences of the distribution. It starts from the complete undirected graph and removes the edge between two variables as soon as some set of their neighbours makes them independent, trying sets of size 0, then 1, then 2, and so on. Then it directs the colliders that the removal steps reveal, and directs more edges by three rules that avoid new colliders and cycles. Data alone cannot tell apart DAGs with the same independences, so the output is a partially directed graph that stands for the whole class. The algorithm is the standard constraint-based method of Bayesian network structure learning.
In plain words
If two variables become unrelated once you hold some other variables fixed, then neither causes the other directly, so the link between them goes. The algorithm checks the links with small sets of other variables first, and it only looks among the variables still linked to one of the pair, which keeps the work small when there are few links. Then it reads directions from patterns: if two unlinked variables are both linked to a third, and that third variable was not part of what made them unrelated, both point into it. A few more rules then push those directions further. Links whose direction the data cannot decide stay without direction.
The problem
The input is a finite set of variables and a test that says whether . The analysis assumes that the joint distribution is Markov and faithful to an unknown DAG on : holds exactly when d-separates and in . This rules out hidden common causes of the variables in (causal sufficiency) and exact cancellations of paths.
Two DAGs are Markov equivalent when they have the same d-separations. By Verma and Pearl (1990), this holds exactly when they have the same skeleton (the undirected graph of their edges) and the same v-structures, the triples with and not adjacent. Independence tests cannot separate equivalent DAGs, so the best possible output is the class of . It is drawn as its CPDAG (completed partially directed acyclic graph): the common skeleton, with the edge directed when every DAG of the class has it, and undirected otherwise. The output is the CPDAG of .
The algorithm
PC(V, CI)- 1
G ← complete undirected graph on V; k ← 0 - 2
while some node a has |adj(a)| - 1 ≥ k do - 3
for each ordered adjacent pair (a, b) with |adj(a)| - 1 ≥ k do - 4
for each S ⊆ adj(a) \ {b} with |S| = k do - 5
if CI(a, b, S) then delete a - b; sepset(a, b) ← S; go to the next pair - 6
k ← k + 1 - 7
for each pair a, b not adjacent, with a common neighbour c do - 8
if c ∉ sepset(a, b) then orient a → c ← b - 9
repeat for each undirected edge b - c - 10
R1: if a → b for some a not adjacent to c - 11
R2: or b → a → c for some a - 12
R3: or b - a1, b - a2, a1 → c ← a2 for some non-adjacent a1, a2 - 13
then orient b → c - 14
until no rule applies; return G
Lines L1 to L6 find the skeleton and remember a separating set for each removed pair. Lines L7 and L8 orient the v-structures. Lines L9 to L13 apply the rules of Meek (1995) until none applies. R1 avoids a new v-structure, R2 avoids a cycle, and R3 combines the two. A fourth rule of Meek is needed only when background knowledge directs extra edges, and the plain PC algorithm does not use it.
Example
Let have the arrows , , , and , and use the d-separation oracle of as the test.
- Level 0. Every pair is dependent without conditioning, so no edge goes.
- Level 1. , , and remove four edges.
- Level 2. removes . Now the largest neighbourhood is of , so level 3 does not run.
The skeleton is , , , , . The pair has the common neighbour , so . The pair has the common neighbours and , both in , and the pairs and have in their separating sets, so no other collider appears. R1 with and , not adjacent gives . The output is
The class has three DAGs: can be the source of both edges at , or , or . The fourth choice, , would add a v-structure. The implementation makes 64 calls to the oracle on this graph.
Correctness
The proof is in proofs/correctness.md. It assumes a perfect oracle under the causal Markov condition and faithfulness. In outline:
- Skeleton. No edge of is removed, since adjacent nodes are d-connected given every set. For non-adjacent and , one of them, say , is not a descendant of the other, and then d-separates them. As stays inside the current , the loop tests it by level at the latest.
- V-structures. The separating set of and blocks the path . It contains if is a non-collider on that path and does not contain if is a collider. So line L8 finds exactly the v-structures of .
- Soundness of R1 to R3. If a DAG of the class had , R1 would give it a v-structure that the class does not have, R2 a cycle, and R3 both. So every arrow of the output is in every DAG of the class.
The converse, that each edge left undirected takes both directions inside the class, is the completeness theorem of Meek (1995). It is cited, not proved, and the tests check it exhaustively on three and four nodes.
Proof: With a perfect independence oracle for a distribution that is Markov and faithful to a DAG G, the PC algorithm stops and returns the skeleton and the v-structures of G, and every edge that the Meek rules direct has the same direction in every DAG Markov equivalent to Gfull
Setting. is a DAG on the finite set of nodes, and is a distribution on . The causal Markov condition says that each -separation implies in . Faithfulness says the converse: each independence in implies . Together, holds in exactly when d-separates and in . The oracle answers the test of line L5 with the truth in . Two DAGs are Markov equivalent when they have the same d-separations. By Verma and Pearl (1990), this holds exactly when they have the same skeleton and the same v-structures, that is, the same triples with and not adjacent. The class of is the set of DAGs Markov equivalent to .
Lemma 1 (local Markov property). If and are not adjacent in and is not a descendant of , then d-separates and .
Proof. Take a path from to . If its first arrow is , then is a non-collider on the path, , and is in the conditioning set, so the path is blocked. Otherwise the path starts . It cannot be directed all the way to , since is not a descendant of . So there is a first node where the direction turns, , and is a descendant of . If or one of its descendants were in , then would be its own ancestor, which is a cycle. So the collider blocks the path.
Lemma 2 (skeleton). Line L1 to line L6 stop, and at the end two nodes are adjacent exactly when they are adjacent in . Every removed pair has with .
Proof. An edge is removed only when the oracle reports , and then by faithfulness. Adjacent nodes of are d-connected given every set, since the single edge is a path with no inner node. So no edge of is removed, and at all times contains the neighbours of in .
Let and be non-adjacent in . As is acyclic, is not a descendant of , or is not a descendant of ; by symmetry say the first. By Lemma 1, separates them, and at all times. Let . Suppose the edge is still present at the start of level . Then , so the loop of line L2 runs level , and line L3 visits the ordered pair unless the edge has gone already. Line L4 then reaches unless an earlier set removes the edge. Either way the edge is gone after level .
So after level , where is the largest degree in , the graph is the skeleton of . Then for every , and the loop stops after at most levels. Each level makes finitely many tests.
Lemma 3 (v-structures). Let and be non-adjacent with a common neighbour in the skeleton. Then exactly when in .
Proof. Let . By Lemma 2, d-separates and in , so the path is blocked by . If is a collider on it, the path is blocked only if (and no descendant of is in ). If is a non-collider, the path is blocked only if .
So after line L8 the graph has the skeleton of , and the arrows are exactly the v-structures of . Since the class of shares the skeleton and the v-structures, every arrow at this point has the same direction in every DAG of the class.
Lemma 4 (soundness of the Meek rules). Suppose every arrow of the current graph has the same direction in every DAG of the class, and every v-structure of is an arrow pair in it. Then each of R1, R2 and R3 adds an arrow with the same property.
Proof. Let be any DAG of the class. By the hypothesis, has every current arrow. The edge that the rule orients is undirected. The v-structures of are those of , and their arrows are arrows of the current graph. So no v-structure of uses the edge between and . We show in .
- R1: with and not adjacent. If in , then is a v-structure of that uses the edge . That is impossible, so .
- R2: and . If in , then is a cycle in . So .
- R3: , , , and not adjacent, and . Suppose in . If in , then is a cycle, so in . In the same way . Then is a v-structure of , so of , so it is an arrow pair of the current graph. But is undirected, a contradiction. So .
Theorem (termination and correctness). With a perfect oracle under the causal Markov condition and faithfulness, the PC algorithm stops. Its output has the skeleton of and the v-structures of as arrows, and every arrow in it has the same direction in all DAGs of the class of . No DAG of the class has a v-structure that is not an arrow pair of the output.
Proof. Lemma 2 gives termination of the first phase and the skeleton. Lemma 3 gives the v-structures. Each pass of the loop of line L9 either directs at least one of the finitely many undirected edges or stops, so the loop stops. Lemma 4 and induction over the arrows added show that every arrow has the same direction in the whole class.
What is cited, not proved here. The theorem shows that each directed edge of the output is directed in the CPDAG (the edges on which the whole class agrees). The converse, that each edge left undirected by R1 to R3 takes both directions in DAGs of the class, is the completeness theorem of Meek (1995). With it, the output is exactly the CPDAG. The tests check this converse by exhaustive enumeration for all 25 DAGs on three nodes and all 543 DAGs on four nodes, and on 25 random DAGs with five to seven nodes against an enumeration of their classes.
What does not follow. The theorem assumes a perfect oracle. With statistical tests on finite data, errors in early tests change the later conditioning sets and orientations. Consistency of PC with tests at a suitable level, also when the number of variables grows with the sample size, is a theorem of Kalisch and Bühlmann (2007) for Gaussian data, and is cited, not proved here.
Complexity
The cost is counted in calls to the test. At level each ordered pair tests at most sets. The proof of correctness shows that the loop stops after level , the largest degree in . So the number of tests is at most
which is for a fixed and is reached up to a constant on the complete DAG, with tests. The best case is the empty graph: level 0 removes all edges with tests. The separating sets take space, and the orientation phase takes polynomial time in . A test with data costs extra: the Gaussian test of the implementation inverts a matrix per test after one pass over the data.
Properties
- Exact with an oracle. With a perfect test, the output is the CPDAG of for any order of the nodes.
- Order dependent with data. With statistical tests, the skeleton depends on the order in which line L3 visits the pairs, because a removal changes the neighbourhoods used later. The PC-stable variant of Colombo and Maathuis (2014) removes this dependence.
- Not a score. PC returns one graph and no measure of fit or uncertainty. The tests at level do not control the error rate of the whole graph.
Variants and improvements
- PC-stable. Colombo and Maathuis (2014) fix the neighbourhoods at the start of each level, so the skeleton does not depend on the order of the variables. They also give conservative and majority rules that make the v-structure step order independent.
- High dimensions. Kalisch and Bühlmann (2007) proved that PC with Gaussian partial correlation tests at a suitable level is uniformly consistent for sparse DAGs whose number of nodes grows like a power of the sample size. This is cited, not proved here.
- Hidden variables. If some common causes are not measured, PC can give wrong arrows. The FCI algorithm extends PC to that case and returns a partial ancestral graph.
- Score-based search. Greedy equivalence search searches the same space of classes with a score instead of tests.
- Full orientation. With non-Gaussian noise in a linear model, LiNGAM finds the whole DAG, not only its class.
- Tests. Discrete data use a chi-squared test of independence or a G-test within each cell of . Gaussian data use Fisher's for the partial correlation, as in the implementation. Kernel tests cover non-linear dependence.
When to use it
Use PC when there are many variables, the true graph is sparse, all common causes are measured, and a reliable conditional independence test is available. Its cost grows with the degree of the graph, not with the number of DAGs, so it handles hundreds of variables when degrees are small. If hidden confounders are likely, use FCI. If a score such as the BIC is natural for the model and the number of variables is moderate, GES often gives a more stable answer.
Pitfalls
- Near-violations of faithfulness. Faithfulness fails when two paths cancel exactly, and finite samples also suffer when they nearly cancel. In the example graph with the linear Gaussian model , , , and unit noises, . With 500 samples and level , PC returned a wrong class in 49 of 50 runs, and with 2000 samples in 48 of 50. In a typical run it removes at level 0 with the empty set and then returns , . With it recovered the true class in 48 of 50 runs at both sizes. These rates are measured on the implementation, not proved.
- Error propagation. A wrong removal at a low level changes later neighbourhoods and separating sets, and a wrong separating set gives wrong arrows, which R1 to R3 then spread.
- Conflicting colliders. With data, two v-structures can direct the same edge both ways. The implementation keeps the first arrow; other programs mark the edge as bidirected. Either choice must be reported.
- Multiple tests. PC makes many tests at the same level . The level is a tuning parameter, not the error rate of the graph; see false discovery rate for methods that control errors over many tests.
- Causal reading. The output is causal only under causal sufficiency, the Markov condition and faithfulness. Undirected edges carry no causal direction.
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/pc-algorithm/. The authors are listed in prov/MTZ8ME.jsonl.
"""The PC algorithm for learning the Markov equivalence class of a DAG.
A DAG is given as a dict that maps each node to the set of its parents.
The algorithm sees the distribution only through a test ci(a, b, S) that
returns True when a and b are independent given the set S. With a
d-separation oracle for a DAG G, the output is the CPDAG of G: the skeleton
of G, with an edge directed exactly when all DAGs Markov equivalent to G
direct it the same way.
The output graph is a pair (adj, arrows): adj maps each node to its set of
neighbours, and (u, v) in arrows means u -> v. An adjacent pair with no
arrow in either direction is an undirected edge.
"""
import itertools
import math
from typing import NamedTuple
class PCResult(NamedTuple):
adj: dict # node -> set of neighbours in the output graph
arrows: set # (u, v) for each directed edge u -> v
sepset: dict # frozenset({a, b}) -> the set S that separated a and b
tests: int # number of calls to the independence test
def ancestors(parents, nodes):
"""The nodes and all their ancestors."""
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 d_separated(parents, xs, ys, zs):
"""True if zs d-separates xs from ys in the DAG.
Uses the moral graph of the ancestral set of xs, ys and zs (Lauritzen):
zs d-separates xs and ys exactly when zs separates them there.
"""
xs, ys, zs = set(xs), set(ys), set(zs)
keep = ancestors(parents, xs | ys | zs)
nb = {v: set() for v in keep}
for v in keep:
ps = [p for p in parents[v] if p in keep]
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 = set(xs - zs)
stack = list(seen)
while stack:
v = stack.pop()
if v in ys:
return False
for w in nb[v]:
if w not in seen and w not in zs:
seen.add(w)
stack.append(w)
return True
def dsep_oracle(parents):
"""A perfect independence test for any distribution faithful to the DAG."""
return lambda a, b, s: d_separated(parents, {a}, {b}, s)
def is_undirected(adj, arrows, u, v):
return v in adj[u] and (u, v) not in arrows and (v, u) not in arrows
def orient(arrows, u, v):
arrows.add((u, v))
def meek_rules(adj, arrows):
"""Apply Meek's rules R1 to R3 until no undirected edge can be oriented."""
changed = True
while changed: # @line L9
changed = False
for b in sorted(adj):
for c in sorted(adj[b]):
if not is_undirected(adj, arrows, b, c):
continue
into_b = [a for a in adj[b] if (a, b) in arrows]
# R1: a -> b - c with a and c not adjacent gives b -> c.
r1 = any(a not in adj[c] and a != c for a in into_b) # @line L10
# R2: b -> a -> c with b - c gives b -> c.
r2 = any((b, a) in arrows and (a, c) in arrows for a in adj[b]) # @line L11
# R3: b - a1, b - a2, a1 -> c <- a2, a1 and a2 not adjacent, gives b -> c.
cand = [a for a in adj[b] if is_undirected(adj, arrows, b, a) and (a, c) in arrows]
r3 = any(a2 not in adj[a1] for a1, a2 in itertools.combinations(cand, 2)) # @line L12
if r1 or r2 or r3:
orient(arrows, b, c) # @line L13
changed = True
return arrows
def pc(nodes, ci):
"""Run the PC algorithm with the independence test ci(a, b, S)."""
nodes = sorted(nodes)
adj = {v: set(nodes) - {v} for v in nodes} # @line L1
sepset = {}
tests = 0
k = 0 # @line L1
while any(len(adj[a]) - 1 >= k for a in nodes): # @line L2
for a in nodes:
for b in sorted(adj[a]): # @line L3
if b not in adj[a] or len(adj[a]) - 1 < k:
continue
for s in itertools.combinations(sorted(adj[a] - {b}), k): # @line L4
tests += 1
if ci(a, b, set(s)): # @line L5
adj[a].discard(b)
adj[b].discard(a)
sepset[frozenset((a, b))] = set(s) # @line L5
break
k += 1 # @line L6
arrows = set()
for c in nodes:
for a, b in itertools.combinations(sorted(adj[c]), 2): # @line L7
if b in adj[a]:
continue
if c not in sepset[frozenset((a, b))]: # @line L8
for u in (a, b):
if (c, u) not in arrows:
orient(arrows, u, c) # @line L8
meek_rules(adj, arrows)
return PCResult(adj, arrows, sepset, tests) # @line L14
def cpdag_edges(adj, arrows):
"""The output as (sorted list of directed edges, sorted list of undirected edges)."""
directed = sorted(arrows)
undirected = sorted((u, v) for u in adj for v in adj[u] if u < v and is_undirected(adj, arrows, u, v))
return directed, undirected
def gaussian_ci_test(data, alpha=0.01):
"""Fisher z test of zero partial correlation for rows of real data.
data: list of rows (lists of floats), columns are the variables 0..p-1.
Returns ci(a, b, S) for use with pc().
"""
n = len(data)
p = len(data[0])
mean = [sum(r[j] for r in data) / n for j in range(p)]
cov = [[sum((r[i] - mean[i]) * (r[j] - mean[j]) for r in data) / (n - 1) for j in range(p)] for i in range(p)]
def inv(m):
q = len(m)
a = [row[:] + [1.0 if i == j else 0.0 for j in range(q)] for i, row in enumerate(m)]
for c in range(q):
piv = max(range(c, q), key=lambda r: abs(a[r][c]))
a[c], a[piv] = a[piv], a[c]
pv = a[c][c]
a[c] = [v / pv for v in a[c]]
for r in range(q):
if r != c:
f = a[r][c]
a[r] = [x - f * y for x, y in zip(a[r], a[c])]
return [row[q:] for row in a]
def ci(a, b, s):
idx = [a, b] + sorted(s)
prec = inv([[cov[i][j] for j in idx] for i in idx])
r = -prec[0][1] / math.sqrt(prec[0][0] * prec[1][1])
r = max(-0.9999999, min(0.9999999, r))
z = 0.5 * math.log((1 + r) / (1 - r)) * math.sqrt(n - len(s) - 3)
pval = math.erfc(abs(z) / math.sqrt(2))
return pval > alpha
return ci
if __name__ == "__main__":
g = {"A": set(), "B": {"A"}, "C": {"A"}, "D": {"B", "C"}, "E": {"D"}}
res = pc(g, dsep_oracle(g))
print("tests", res.tests)
print("sepsets", {tuple(sorted(k)): sorted(v) for k, v in res.sepset.items()})
print("cpdag", cpdag_edges(res.adj, res.arrows))
test_pc_algorithm.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pc-algorithm/. The authors are listed in prov/MTZ8ME.jsonl.
import itertools
import math
import random
from pc_algorithm import cpdag_edges, d_separated, dsep_oracle, gaussian_ci_test, pc
EXAMPLE = {"A": set(), "B": {"A"}, "C": {"A"}, "D": {"B", "C"}, "E": {"D"}}
def all_dags(n):
"""Every DAG on nodes 0..n-1, as parent dicts."""
pairs = list(itertools.combinations(range(n), 2))
out = []
for choice in itertools.product((0, 1, 2), repeat=len(pairs)):
parents = {v: set() for v in range(n)}
for (u, v), c in zip(pairs, choice):
if c == 1:
parents[v].add(u)
elif c == 2:
parents[u].add(v)
if is_acyclic(parents):
out.append(parents)
return out
def is_acyclic(parents):
state = {}
def visit(v):
if state.get(v) == 1:
return False
if state.get(v) == 2:
return True
state[v] = 1
ok = all(visit(p) for p in parents[v])
state[v] = 2
return ok
return all(visit(v) for v in parents)
def edges(parents):
return {(p, v) for v in parents for p in parents[v]}
def dsep_signature(parents):
nodes = sorted(parents)
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(d_separated(parents, {a}, {b}, set(s)))
return tuple(sig)
def cpdag_from_class(dags):
"""Directed edges shared by all DAGs of the class; the other edges are undirected."""
common = set.intersection(*(edges(d) for d in dags))
skel = {frozenset(e) for e in edges(dags[0])}
undirected = sorted(tuple(sorted(e)) for e in skel if not any(set(e) == {u, v} for u, v in common))
return sorted(common), undirected
def v_structures(parents):
out = set()
for c in parents:
for a, b in itertools.combinations(sorted(parents[c]), 2):
if a not in parents[b] and b not in parents[a]:
out.add((a, c, b))
return out
def test_worked_example():
res = pc(EXAMPLE, dsep_oracle(EXAMPLE))
sep = {tuple(sorted(k)): sorted(v) for k, v in res.sepset.items()}
assert sep == {("A", "E"): ["D"], ("B", "C"): ["A"], ("B", "E"): ["D"], ("C", "E"): ["D"], ("A", "D"): ["B", "C"]}
directed, undirected = cpdag_edges(res.adj, res.arrows)
assert directed == [("B", "D"), ("C", "D"), ("D", "E")]
assert undirected == [("A", "B"), ("A", "C")]
assert res.tests == 64
def check_all_dags(n, n_dags, n_classes):
dags = all_dags(n)
assert len(dags) == n_dags
classes = {}
for d in dags:
classes.setdefault(dsep_signature(d), []).append(d)
assert len(classes) == n_classes
for members in classes.values():
want = cpdag_from_class(members)
for d in members:
res = pc(d, dsep_oracle(d))
assert cpdag_edges(res.adj, res.arrows) == want
def test_all_dags_on_three_nodes():
check_all_dags(3, 25, 11)
def test_all_dags_on_four_nodes():
check_all_dags(4, 543, 185)
def random_dag(rng, n, p):
order = list(range(n))
rng.shuffle(order)
parents = {v: set() for v in range(n)}
for i, j in itertools.combinations(range(n), 2):
if rng.random() < p:
parents[order[j]].add(order[i])
return parents
def markov_class_by_orientation(parents):
"""All DAGs with the skeleton and v-structures of the DAG (Verma and Pearl)."""
skel = sorted(tuple(sorted(e)) for e in edges(parents))
vs = v_structures(parents)
out = []
for bits in itertools.product((0, 1), repeat=len(skel)):
cand = {v: set() for v in parents}
for (u, v), bit in zip(skel, bits):
if bit:
cand[v].add(u)
else:
cand[u].add(v)
if is_acyclic(cand) and v_structures(cand) == vs:
out.append(cand)
return out
def test_random_dags_against_class_enumeration():
rng = random.Random(20261114)
checked = 0
while checked < 25:
g = random_dag(rng, rng.choice((5, 6, 7)), 0.35)
if len(edges(g)) > 11:
continue
res = pc(g, dsep_oracle(g))
assert cpdag_edges(res.adj, res.arrows) == cpdag_from_class(markov_class_by_orientation(g))
checked += 1
def test_number_of_tests_bound():
rng = random.Random(7)
for _ in range(30):
n = rng.choice((5, 6, 7, 8))
g = random_dag(rng, n, 0.3)
q = max(len(g[v]) + sum(v in g[w] for w in g) for v in g)
res = pc(g, dsep_oracle(g))
bound = n * (n - 1) * sum(math.comb(n - 2, k) for k in range(q + 1))
assert res.tests <= bound
def test_relabelling_gives_same_class():
rng = random.Random(11)
for _ in range(20):
g = random_dag(rng, 6, 0.4)
perm = list(range(6))
rng.shuffle(perm)
h = {perm[v]: {perm[p] for p in g[v]} for v in g}
a = pc(g, dsep_oracle(g))
b = pc(h, dsep_oracle(h))
da, ua = cpdag_edges(a.adj, a.arrows)
db, ub = cpdag_edges(b.adj, b.arrows)
assert sorted((perm[u], perm[v]) for u, v in da) == db
assert sorted(tuple(sorted((perm[u], perm[v]))) for u, v in ua) == ub
def sample_example(seed, n, c_coef):
# Linear Gaussian model on the example graph, nodes A..E = 0..4.
rng = random.Random(seed)
rows = []
for _ in range(n):
a = rng.gauss(0, 1)
b = 0.8 * a + rng.gauss(0, 1)
c = c_coef * a + rng.gauss(0, 1)
d = 0.6 * b + 0.6 * c + rng.gauss(0, 1)
e = 0.9 * d + rng.gauss(0, 1)
rows.append([a, b, c, d, e])
return rows
def test_gaussian_data_measured():
# Measured, not proved: 48 of 50 seeds recover the CPDAG at n = 500 and at n = 2000.
want = ([(1, 3), (2, 3), (3, 4)], [(0, 1), (0, 2)])
hits = 0
for seed in range(10):
res = pc(range(5), gaussian_ci_test(sample_example(seed, 500, 0.7), alpha=0.01))
hits += cpdag_edges(res.adj, res.arrows) == want
assert hits >= 9
def test_near_unfaithful_example_fails():
# With C = -0.7 A the two paths from A to D nearly cancel (Cov(A, D) = 0.06),
# so the level-0 test removes A - D and the orientations go wrong.
res = pc(range(5), gaussian_ci_test(sample_example(0, 500, -0.7), alpha=0.01))
assert 3 not in res.adj[0]
assert cpdag_edges(res.adj, res.arrows) != ([(1, 3), (2, 3), (3, 4)], [(0, 1), (0, 2)])
History
Spirtes and Glymour published the PC algorithm in 1991 in Social Science Computer Review. The name comes from their first names, Peter and Clark. Earlier constraint-based methods, such as the SGS algorithm, tested every subset of the other variables for each pair, which is exponential even for sparse graphs. PC restricts the tests to subsets of current neighbours of growing size. Verma and Pearl (1990) had characterized Markov equivalence by skeletons and v-structures, and Meek (1995) proved that the orientation rules are sound and complete. Spirtes, Glymour and Scheines described the algorithm and its correctness in Causation, Prediction, and Search (1993, second edition 2000). Kalisch and Bühlmann (2007) proved high-dimensional consistency, and Colombo and Maathuis (2014) made the algorithm order independent.
References
- Peter Spirtes and Clark Glymour, An algorithm for fast recovery of sparse causal graphs, Social Science Computer Review 9(1), 1991, pp. 62 to 72, The whole paper (the PC algorithm and its cost for sparse graphs)
- Peter Spirtes, Clark Glymour and Richard Scheines, Causation, Prediction, and Search, 2nd edition, MIT Press, 2000, Chapter 5 (discovery algorithms for causally sufficient structures, with the PC algorithm, its correctness and its complexity; general locator)
- Christopher Meek, Causal inference and causal explanation with background knowledge, Proceedings of the 11th Conference on Uncertainty in Artificial Intelligence (UAI 1995), Morgan Kaufmann, pp. 403 to 410, The whole paper (the orientation rules, their soundness, and their completeness for the output of the v-structure step)
- Thomas Verma and Judea Pearl, Equivalence and synthesis of causal models, Proceedings of the 6th Conference on Uncertainty in Artificial Intelligence (UAI 1990), pp. 220 to 227; also in Uncertainty in Artificial Intelligence 6, North-Holland, 1991, pp. 255 to 270, The whole paper (two DAGs are Markov equivalent exactly when they have the same skeleton and the same v-structures)
- Markus Kalisch and Peter Bühlmann, Estimating high-dimensional directed acyclic graphs with the PC-algorithm, Journal of Machine Learning Research 8, 2007, pp. 613 to 636, The whole paper (uniform consistency of PC with Gaussian partial correlation tests for sparse DAGs whose number of nodes grows with the sample size)
- Diego Colombo and Marloes H. Maathuis, Order-independent constraint-based causal structure learning, Journal of Machine Learning Research 15(116), 2014, pp. 3921 to 3962, The whole paper (the order dependence of PC on finite data, and the PC-stable variant)
Where this leads
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 MTZ8ME Edit this page History Report an error Markdown