Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 GG 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 a→c←ba \to c \leftarrow b 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 VV of nn variables and a test CI(a,b,S)\mathrm{CI}(a, b, S) that says whether a⊥b∣Sa \perp b \mid S. The analysis assumes that the joint distribution is Markov and faithful to an unknown DAG GG on VV: a⊥b∣Sa \perp b \mid S holds exactly when SS d-separates aa and bb in GG. This rules out hidden common causes of the variables in VV (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 a→c←ba \to c \leftarrow b with aa and bb not adjacent. Independence tests cannot separate equivalent DAGs, so the best possible output is the class of GG. It is drawn as its CPDAG (completed partially directed acyclic graph): the common skeleton, with the edge a→ba \to b directed when every DAG of the class has it, and undirected otherwise. The output is the CPDAG of GG.

The algorithm

  1. PC(V, CI)
  2. 1G ← complete undirected graph on V; k ← 0
  3. 2while some node a has |adj(a)| - 1 ≥ k do
  4. 3for each ordered adjacent pair (a, b) with |adj(a)| - 1 ≥ k do
  5. 4for each S ⊆ adj(a) \ {b} with |S| = k do
  6. 5if CI(a, b, S) then delete a - b; sepset(a, b) ← S; go to the next pair
  7. 6k ← k + 1
  8. 7for each pair a, b not adjacent, with a common neighbour c do
  9. 8if c ∉ sepset(a, b) then orient a → c ← b
  10. 9repeat for each undirected edge b - c
  11. 10R1: if a → b for some a not adjacent to c
  12. 11R2: or b → a → c for some a
  13. 12R3: or b - a1, b - a2, a1 → c ← a2 for some non-adjacent a1, a2
  14. 13then orient b → c
  15. 14until 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 GG have the arrows A→BA \to B, A→CA \to C, B→DB \to D, C→DC \to D and D→ED \to E, and use the d-separation oracle of GG as the test.

  • Level 0. Every pair is dependent without conditioning, so no edge goes.
  • Level 1. A⊥E∣DA \perp E \mid D, B⊥C∣AB \perp C \mid A, B⊥E∣DB \perp E \mid D and C⊥E∣DC \perp E \mid D remove four edges.
  • Level 2. A⊥D∣{B,C}A \perp D \mid \{B, C\} removes A−DA - D. Now the largest neighbourhood is {B,C,E}\{B, C, E\} of DD, so level 3 does not run.

The skeleton is A−BA - B, A−CA - C, B−DB - D, C−DC - D, D−ED - E. The pair B,CB, C has the common neighbour D∉sepset(B,C)={A}D \notin \mathrm{sepset}(B, C) = \{A\}, so B→D←CB \to D \leftarrow C. The pair A,DA, D has the common neighbours BB and CC, both in sepset(A,D)\mathrm{sepset}(A, D), and the pairs B,EB, E and C,EC, E have DD in their separating sets, so no other collider appears. R1 with B→D−EB \to D - E and BB, EE not adjacent gives D→ED \to E. The output is

A−B,A−C,B→D←C,D→E.A - B, \quad A - C, \quad B \to D \leftarrow C, \quad D \to E.

The class has three DAGs: AA can be the source of both edges at AA, or B→A→CB \to A \to C, or C→A→BC \to A \to B. The fourth choice, B→A←CB \to A \leftarrow C, 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:

  1. Skeleton. No edge of GG is removed, since adjacent nodes are d-connected given every set. For non-adjacent aa and bb, one of them, say bb, is not a descendant of the other, and then pa(a)\mathrm{pa}(a) d-separates them. As pa(a)\mathrm{pa}(a) stays inside the current adj(a)∖{b}\mathrm{adj}(a) \setminus \{b\}, the loop tests it by level ∣pa(a)∣|\mathrm{pa}(a)| at the latest.
  2. V-structures. The separating set of aa and bb blocks the path a−c−ba - c - b. It contains cc if cc is a non-collider on that path and does not contain cc if cc is a collider. So line L8 finds exactly the v-structures of GG.
  3. Soundness of R1 to R3. If a DAG of the class had c→bc \to b, 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. GG is a DAG on the finite set VV of nn nodes, and PP is a distribution on VV. The causal Markov condition says that each dd-separation (a⊥b∣S)G(a \perp b \mid S)_G implies a⊥b∣Sa \perp b \mid S in PP. Faithfulness says the converse: each independence a⊥b∣Sa \perp b \mid S in PP implies (a⊥b∣S)G(a \perp b \mid S)_G. Together, a⊥b∣Sa \perp b \mid S holds in PP exactly when SS d-separates aa and bb in GG. The oracle answers the test of line L5 with the truth in PP. 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 a→c←ba \to c \leftarrow b with aa and bb not adjacent. The class of GG is the set of DAGs Markov equivalent to GG.

Lemma 1 (local Markov property). If aa and bb are not adjacent in GG and bb is not a descendant of aa, then pa(a)\mathrm{pa}(a) d-separates aa and bb.

Proof. Take a path from aa to bb. If its first arrow is p→ap \to a, then p∈pa(a)p \in \mathrm{pa}(a) is a non-collider on the path, p≠bp \ne b, and pp is in the conditioning set, so the path is blocked. Otherwise the path starts a→ca \to c. It cannot be directed all the way to bb, since bb is not a descendant of aa. So there is a first node dd where the direction turns, →d←\to d \leftarrow, and dd is a descendant of aa. If dd or one of its descendants were in pa(a)\mathrm{pa}(a), then aa would be its own ancestor, which is a cycle. So the collider dd blocks the path. □\square

Lemma 2 (skeleton). Line L1 to line L6 stop, and at the end two nodes are adjacent exactly when they are adjacent in GG. 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. An edge is removed only when the oracle reports a⊥b∣Sa \perp b \mid S, and then (a⊥b∣S)G(a \perp b \mid S)_G by faithfulness. Adjacent nodes of GG are d-connected given every set, since the single edge is a path with no inner node. So no edge of GG is removed, and at all times adj(a)\mathrm{adj}(a) contains the neighbours of aa in GG.

Let aa and bb be non-adjacent in GG. As GG is acyclic, bb is not a descendant of aa, or aa is not a descendant of bb; by symmetry say the first. By Lemma 1, pa(a)\mathrm{pa}(a) separates them, and pa(a)⊆adj(a)∖{b}\mathrm{pa}(a) \subseteq \mathrm{adj}(a) \setminus \{b\} at all times. Let k0=∣pa(a)∣k_0 = |\mathrm{pa}(a)|. Suppose the edge a−ba - b is still present at the start of level k0k_0. Then ∣adj(a)∣−1≥k0|\mathrm{adj}(a)| - 1 \ge k_0, so the loop of line L2 runs level k0k_0, and line L3 visits the ordered pair (a,b)(a, b) unless the edge has gone already. Line L4 then reaches S=pa(a)S = \mathrm{pa}(a) unless an earlier set removes the edge. Either way the edge is gone after level k0k_0.

So after level qq, where qq is the largest degree in GG, the graph is the skeleton of GG. Then ∣adj(a)∣−1<q+1|\mathrm{adj}(a)| - 1 < q + 1 for every aa, and the loop stops after at most q+1q + 1 levels. Each level makes finitely many tests. □\square

Lemma 3 (v-structures). Let aa and bb be non-adjacent with a common neighbour cc in the skeleton. Then c∉sepset(a,b)c \notin \mathrm{sepset}(a, b) exactly when a→c←ba \to c \leftarrow b in GG.

Proof. Let S=sepset(a,b)S = \mathrm{sepset}(a, b). By Lemma 2, SS d-separates aa and bb in GG, so the path a−c−ba - c - b is blocked by SS. If cc is a collider on it, the path is blocked only if c∉Sc \notin S (and no descendant of cc is in SS). If cc is a non-collider, the path is blocked only if c∈Sc \in S. □\square

So after line L8 the graph has the skeleton of GG, and the arrows are exactly the v-structures of GG. Since the class of GG 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 GG is an arrow pair in it. Then each of R1, R2 and R3 adds an arrow with the same property.

Proof. Let DD be any DAG of the class. By the hypothesis, DD has every current arrow. The edge b−cb - c that the rule orients is undirected. The v-structures of DD are those of GG, and their arrows are arrows of the current graph. So no v-structure of DD uses the edge between bb and cc. We show b→cb \to c in DD.

  • R1: a→b−ca \to b - c with aa and cc not adjacent. If c→bc \to b in DD, then a→b←ca \to b \leftarrow c is a v-structure of DD that uses the edge b−cb - c. That is impossible, so b→cb \to c.
  • R2: b→a→cb \to a \to c and b−cb - c. If c→bc \to b in DD, then b→a→c→bb \to a \to c \to b is a cycle in DD. So b→cb \to c.
  • R3: b−a1b - a_1, b−a2b - a_2, a1→c←a2a_1 \to c \leftarrow a_2, a1a_1 and a2a_2 not adjacent, and b−cb - c. Suppose c→bc \to b in DD. If b→a1b \to a_1 in DD, then a1→c→b→a1a_1 \to c \to b \to a_1 is a cycle, so a1→ba_1 \to b in DD. In the same way a2→ba_2 \to b. Then a1→b←a2a_1 \to b \leftarrow a_2 is a v-structure of DD, so of GG, so it is an arrow pair of the current graph. But b−a1b - a_1 is undirected, a contradiction. So b→cb \to c. □\square

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 GG and the v-structures of GG as arrows, and every arrow in it has the same direction in all DAGs of the class of GG. 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. □\square

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 kk each ordered pair (a,b)(a, b) tests at most (n−2k)\binom{n - 2}{k} sets. The proof of correctness shows that the loop stops after level qq, the largest degree in GG. So the number of tests is at most

n(n−1)∑k=0q(n−2k),n(n - 1)\sum_{k=0}^{q}\binom{n - 2}{k},

which is O(nq+2)O(n^{q + 2}) for a fixed qq and is reached up to a constant on the complete DAG, with n(n−1)2n−2n(n - 1)2^{n - 2} tests. The best case is the empty graph: level 0 removes all edges with (n2)\binom n2 tests. The separating sets take O(n3)O(n^3) space, and the orientation phase takes polynomial time in nn. A test with data costs extra: the Gaussian test of the implementation inverts a (k+2)×(k+2)(k + 2) \times (k + 2) matrix per test after one pass over the data.

Properties

  • Exact with an oracle. With a perfect test, the output is the CPDAG of GG 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 α\alpha 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 SS. Gaussian data use Fisher's zz 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 B=0.8A+eB = 0.8A + e, C=−0.7A+eC = -0.7A + e, D=0.6B+0.6C+eD = 0.6B + 0.6C + e, E=0.9D+eE = 0.9D + e and unit noises, Cov⁡(A,D)=0.06\operatorname{Cov}(A, D) = 0.06. With 500 samples and level α=0.01\alpha = 0.01, PC returned a wrong class in 49 of 50 runs, and with 2000 samples in 48 of 50. In a typical run it removes A−DA - D at level 0 with the empty set and then returns A→B←DA \to B \leftarrow D, A→C←DA \to C \leftarrow D. With C=0.7A+eC = 0.7A + e 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 α\alpha. 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.

pc_algorithm.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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)
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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