Causal discovery I: conditional independence, PC, FCI and GES
Conditional independences constrain causal graphs under Markov and faithfulness. Study equivalence classes, stable PC, latent-aware FCI, score-based GES, their limits, and Sachs signaling data.
After this lesson you can
- Characterize Markov equivalence and construct a DAG’s CPDAG.
- Implement PC with partial-correlation tests and Meek rules.
- Explain faithfulness and construct a cancellation that misleads PC.
- Interpret FCI output and its claims about latent variables.
- Compare PC and GES on simulated and Sachs data with structural metrics.
Before you start
- 27Causal Markov condition and truncated factorizationCollider biasStructural causal modelSemi-Markovian models and ADMGs
- 14d-separationScore-based structure learningBayesian information criterion
- 05Fisher z-transformationThe multiple testing problem
- 13Reproducing kernel Hilbert spaceReproducing property
A service’s hidden network
A service records latency, database load, retries, and errors. If two metrics change together, the first may cause the second, the reverse may occur, or both may respond to a third. What part of that graph can be recovered by looking only at logs?
The answer depends on a distinction. An observed independence restricts graphs compatible with data; a causal arrow also requires assumptions about how those data are generated, selected, and measured. Even infinitely many observations can leave multiple structures implying exactly the same independences.
Markov, faithfulness, and equivalence
The causal Markov assumption says DAG d-separations imply distributional independences. Faithfulness also requires the converse: every distributional independence must correspond to d-separation in the true graph. It does not follow from Markov: two paths can cancel their effects. Causal sufficiency means no common cause of included variables is missing; selection, measurement error, and cycles also matter.
Two DAGs are Markov equivalent if they imply the same d-separations. Verma and Pearl’s theorem characterizes the class by the same skeleton and the same unshielded colliders with and nonadjacent. A CPDAG represents the class: an arrow appears if it has that direction in every DAG; an unmarked line represents a reversible direction within the class.
Do not choose each line’s direction independently: a combination may introduce a cycle or new collider. The explorer enumerates all orientations compatible with the skeleton and colliders of the DAG you draw.
Why the characterization works
The direction from the same independences to the same skeleton and colliders can be understood locally. Adjacent nodes cannot be d-separated by a set excluding endpoints; nonadjacent DAG nodes admit some separating set. In an unshielded triple, the middle node belongs to relevant separating sets for a chain or fork and not for a collider. Thus a skeleton or collider difference changes some independence.
The converse requires a global result. Edge is covered when . Reversing it preserves the class: if , the two factors can be rewritten as without changing others. In positive distributions this preserves factorizations and, by completeness of DAG d-separation, implied independences.
We also use a combinatorial lemma that does not assume equivalence: if two DAGs share skeleton and unshielded colliders but differ in an orientation, the first has a covered edge pointing oppositely in the second. The construction chooses a minimal head in topological order and then a maximal disagreeing tail; equal colliders force the needed parent equality. Its detailed proof appears in the formalized lemma. Reversing that edge leaves the graph acyclic, preserves skeleton and colliders, and removes one disagreement. Finite induction reaches the second DAG; each reversal preserves d-separations. This proves the remaining direction without assuming equivalence.
PC: from independences to a partial graph
The PC algorithm starts with a complete graph. For each adjacent pair it tests conditional independence given a selection of neighbors. If it finds separating set for and , it removes the edge and stores . It begins with empty sets and increases size while candidates remain; then orients for each unshielded triple whose center is absent from its endpoints’ separating set.
Meek rules propagate orientations avoiding extra colliders or cycles. For example, if and is not adjacent to , orient : the alternative creates new collider . The implementation uses R1, R2, and R3 to a fixed point; R4 can apply with compatible prior knowledge, as the exercise shows. Rules require an extendable pattern: contradictory sample tests can produce a result that is not a valid CPDAG.
Another forced orientation appears if remains undirected but directed path already exists: choosing would close a cycle. A rule applied to a valid pattern does not guarantee correctness for every partially directed matrix. Noisy-test separating sets may imply incompatible colliders; the lab stops orientation and explains what remains available.
Stable PC freezes neighbors at the start of each conditioning-set size and deletes edges after that level. This makes the skeleton independent of variable order for identical test responses, but does not automatically resolve all finite-sample orientation conflicts. Cost depends strongly on degree and separator size: dense graphs may need combinatorially many tests. Colombo and Maathuis analyze order dependence.
With an exact independence oracle, an acyclic causal DAG, Markov and faithfulness, causal sufficiency, no selection, and complete search of relevant sets, PC recovers the true class CPDAG. This is a population guarantee. The teaching implementation detects some contradictions and cycles, but does not generally verify that an empirical pattern has a consistent extension.
What an independence test means
For i.i.d. Gaussian data, conditional independence is equivalent to zero partial correlation. If has variables and is residual correlation, the Fisher test approximately uses
It requires and a nonsingular correlation matrix. The two-sided p-value compares with that reference. In PC, a p-value greater than is a decision not to reject, not proof of independence. With little data, a true edge can disappear for lack of power. Repeated tests and earlier decisions change global graph properties.
One way to calculate is to regress and separately on and correlate residuals. Another is to invert the correlation matrix of : if its inverse is , then . Equivalence of zero partial correlation and conditional independence uses joint Gaussianity; outside it uncorrelated residuals may still depend nonlinearly.
For discrete variables, the test compares observed and expected frequencies within strata; sparse tables weaken its approximation and discretization changes the question. Kernel tests such as KCI allow nonlinear relationships under their conditions but require a kernel, regularization, and null-distribution approximation. They are not independence oracles.
If and respectively have and categories and each observed stratum has full support, the aggregate test has degrees of freedom, summed across strata. With missing combinations or very small expected frequencies, that count and approximation may fail. Conditioning on more variables multiplies strata and reduces available data in each.
Shah and Peters establish a deeper limit: for a broad class of absolutely continuous distributions with continuous conditioning, a test with uniform finite-sample size control cannot obtain nontrivial power against alternatives in that class. This does not prohibit useful tests under extra models, smoothness assumptions, or discrete conditioning.
Cancellation that fools an oracle
Let , and have independent Gaussian noises and positive variances. If and , then : although the DAG contains and . The distribution satisfies Markov for that DAG but not faithfulness. With an independence oracle, PC removes the direct edge at the first level. Near cancellation, small correlation needs more data for comparable power.
Latents, FCI, and uncertain endpoints
If an unmeasured common cause exists, PC’s causal sufficiency fails. The FCI algorithm permits latent variables and selection under its assumptions and uses extra tests to obtain a PAG, representing a class of maximal ancestral graphs. A circle endpoint means its mark is unidentified in that class; an arrowhead at indicates, in the relevant ancestral framework, that is not an ancestor of the other endpoint. A bidirected edge may be compatible with latent confounding but does not identify the number or mechanism of hidden causes.
An ancestral graph restricts edge marks to respect ancestry; its separation criterion for mixed paths is m-separation. A path is active if each interior noncollider lies outside the conditioned set and each collider, recognized by two incoming arrowheads, belongs to the conditioned set or has a descendant in it. Two sets are m-separated when no active path joins them. The graph is maximal if every nonadjacent pair can be separated by an admissible set. The PAG summarizes shared marks across such graphs, as developed by Zhang.
FCI begins with an adjacency search and performs extra tests with candidates not necessarily limited to PC’s immediate neighbors. It then applies PAG orientation rules. Marks are common properties of the represented class under algorithm assumptions; a circle is not a hidden arrow to complete at convenience. Selection effects also change endpoint interpretation, so state whether they are allowed.
FCI does not eliminate the need for Markov, faithfulness, and suitable tests. A PAG estimated with sampling error does not prove hidden variables exist or do not exist. For time series, consecutive rows may be dependent: model lags and dependence rather than treating each instant as i.i.d.
Search by score
GES searches equivalence classes, not arbitrary orientations. In a greedy phase it adds relations via valid operators while improving score; then removes relations while improvement remains possible. A score-equivalent criterion gives the same value to DAGs in one class. Under score-consistency and model-representation conditions, Chickering’s asymptotic result concerns that class search, not arbitrary greedy hill climbing over DAGs.
In the usual formulation, with a fixed number of variables, growing sample, a distribution admitting a perfect DAG map, an equivalent and locally consistent score, and suitable complete operators, GES consistently recovers the corresponding class. That does not promise every arrow of a particular DAG or automatically describe finite-sample behavior.
For a linear Gaussian model, one score to maximize is
The first part rewards fit and the second penalizes parameters. The restricted lab search enumerates representatives only for small graphs and limits parent count: it permits experiments with equivalent scores but does not inherit all full GES guarantees. Hybrid methods combine, for example, initial independence-based selection with score search; results depend on both phases.
In local Gaussian regression with an intercept and node-specific variance, maximized log likelihood depends on residual sum of squares. These intercepts and variances contribute the same number of parameters for all DAGs on the same variables; the lab removes their common terms and retains the per-edge penalty. Equal scores for equivalent representatives are checked numerically with a second log-density evaluation.
How to compare graphs
Structural Hamming distance or SHD counts graph differences under a stated convention: a reversal can count as one operation or two. Structural intervention distance (SID) measures discrepancies in interventional inferences between ordered pairs under its definition, not simply differing edges, and need not be symmetric. A CPDAG contains reversible directions; comparing it with a DAG by arbitrarily orienting lines can turn legitimate uncertainty into a supposed error. PAG–DAG comparison needs a specific convention, not standard SID applied unchanged.
A simulated benchmark reveals errors relative to its generating graph, but conclusions depend on density, noise, sizes, and mechanism. If variances systematically grow with causal order, a method may exploit that accidental clue. Change scales and mechanisms before generalizing.
Cell signaling: Sachs
Sachs and colleagues used cell measurements and molecular perturbations to study a signaling network. The bnlearn replication publishes a consensus network and separate datasets; the network is a scientific reference, not an undisputed account of every condition. The lab uses 853 cells and 11 variables in one condition, without mixing samples from other interventions as if they were one i.i.d. distribution. It is observational with respect to measured nodes, but not unstimulated: it received α-CD3 and α-CD28. Mooij and colleagues’ condition table distinguishes this sample from those adding specific inhibitors.
Compare the learned skeleton with the network’s 17 adjacencies and distinguish common, missing, and extra ones. Changing , transforming, or discretizing data changes tests and may change the graph; none of these comparisons alone validates causal directions. The local experiment also compares the custom PC skeleton with causal-learn on the same data.
Lab
The first experiment implements Fisher Z and stable PC, then explores a restricted class search with a Gaussian score. Simulated data have a known DAG: they measure recovery in that mechanism, not a guarantee for every application.
In the reproducible four-node sample, restricted search ends with five adjacencies versus four in the mechanism. The last insertion improves the score in that sample but adds a relation to the true skeleton. This illustrates finite-sample variation, not proof that insertion is always wrong. The program prints each step so you can check it and change the seed.
Stable PC from scratch
Run the cells in order. The working matrix represents an undirected edge with two true entries and an arrow with one. Detectable orientation contradictions and directed cycles are rejected, but the code does not certify every resulting pattern has a consistent extension. Seed and mechanism appear in the final cell.
from itertools import combinations
import numpy as np
from math import erfc, sqrt
def fisher_z(data, x, y, condicion=()):
"""p bilateral para independencia gaussiana condicional, n > |S|+3."""
data = np.asarray(data, dtype=float)
if data.ndim != 2 or not np.isfinite(data).all():
raise ValueError('Se requiere una matriz finita de observaciones')
n, p = data.shape
s = tuple(condicion)
if x == y or x in s or y in s or len(set(s)) != len(s):
raise ValueError('Variables de prueba y condición deben ser distintas')
cols = (x, y, *s)
if any(i < 0 or i >= p for i in cols) or n <= len(s)+3:
raise ValueError('Índices o grados de libertad inválidos')
cov = np.corrcoef(data[:, cols], rowvar=False)
if not np.isfinite(cov).all() or np.linalg.matrix_rank(cov) < len(cols):
raise ValueError('Matriz de correlación singular')
inv = np.linalg.inv(cov)
r = -inv[0, 1] / np.sqrt(inv[0, 0] * inv[1, 1])
if not np.isfinite(r) or abs(r) >= 1:
raise ValueError('Correlación parcial degenerada')
z = np.sqrt(n - len(s) - 3) * np.arctanh(r)
return erfc(abs(z) / sqrt(2))def skeleton(p, independence, alpha=0.01):
"""Congela adyacencias por nivel; guarda el primer separador hallado."""
if not 0 < alpha < 1:
raise ValueError('alpha debe pertenecer a (0,1)')
graph = np.ones((p, p), dtype=bool)
np.fill_diagonal(graph, False)
separators, trace = {}, []
depth = 0
while True:
frozen = [set(np.flatnonzero(graph[i])) for i in range(p)]
pairs = [(i, j) for i in range(p) for j in range(i+1, p) if graph[i, j]]
if not any(max(len(frozen[i]-{j}), len(frozen[j]-{i})) >= depth for i,j in pairs):
break
remove = []
for i, j in pairs:
candidates = set(combinations(sorted(frozen[i]-{j}), depth))
candidates.update(combinations(sorted(frozen[j]-{i}), depth))
for s in sorted(candidates):
pvalue = float(independence(i, j, s))
if not 0 <= pvalue <= 1:
raise ValueError('El test debe devolver un p-valor entre 0 y 1')
trace.append((depth, i, j, s, pvalue))
if pvalue > alpha:
remove.append((i, j))
separators[i, j] = s
break
for i, j in remove:
graph[i, j] = graph[j, i] = False
depth += 1
return graph, separators, tracedef adjacent(g, x, y):
return bool(g[x, y] or g[y, x])
def undirected(g, x, y):
return bool(g[x, y] and g[y, x])
def directed(g, x, y):
return bool(g[x, y] and not g[y, x])
def has_path(g, start, end):
reached, todo = {start}, [start]
while todo:
node = todo.pop()
for other in range(len(g)):
if directed(g, node, other) and other not in reached:
if other == end:
return True
reached.add(other)
todo.append(other)
return False
def orient(g, proposals):
"""Aplica orientaciones propuestas y detecta conflictos y ciclos."""
for x, y in proposals:
if (y, x) in proposals or directed(g, y, x):
raise ValueError('Orientaciones contradictorias; patrón empírico no resoluble')
for x, y in sorted(proposals):
if undirected(g, x, y):
if has_path(g, y, x):
raise ValueError('La orientación crearía un ciclo dirigido')
g[y, x] = False
def orient_colliders(graph, separators):
"""Triple no escudado x-y-z: colisionador si y no está en Sep(x,z)."""
g = np.array(graph, dtype=bool, copy=True)
proposals, triples = set(), []
for y in range(len(g)):
for x, z in combinations(np.flatnonzero(graph[y]), 2):
if not adjacent(graph, x, z):
key = tuple(sorted((int(x), int(z))))
if key not in separators:
raise ValueError('Falta un conjunto separador')
if y not in separators[key]:
proposals.update(((int(x), y), (int(z), y)))
triples.append((int(x), y, int(z)))
orient(g, proposals)
return g, triplesdef meek(g, r4=False):
"""Cierre R1-R3. R4 es opcional para información previa compatible."""
g = np.array(g, dtype=bool, copy=True)
p = len(g)
history = []
while True:
proposals, reasons = set(), {}
for a in range(p):
for b in range(p):
if a == b or not undirected(g, a, b):
continue
rule = None
# c -> a - b, c no adyacente a b.
if any(directed(g, c, a) and not adjacent(g, c, b) for c in range(p)):
rule = 'R1'
# a -> ... -> b, a - b.
elif has_path(g, a, b):
rule = 'R2'
else:
# a-c, a-d, c->b<-d, c y d no adyacentes.
cs = [c for c in range(p) if undirected(g, a, c) and directed(g, c, b)]
if any(not adjacent(g, c, d) for c, d in combinations(cs, 2)):
rule = 'R3'
# a-b, a-d, a adyacente a c, d->c->b, d y b no adyacentes.
elif r4 and any(undirected(g, a, d) and adjacent(g, a, c)
and directed(g, d, c) and directed(g, c, b)
and not adjacent(g, d, b)
for c in range(p) for d in range(p)):
rule = 'R4'
if rule:
proposals.add((a, b))
reasons[a, b] = rule
if not proposals:
break
orient(g, proposals)
history.extend((a, b, reasons[a, b]) for a, b in sorted(proposals))
return g, history
def pc(data, alpha=0.01):
data = np.asarray(data, dtype=float)
skel, seps, trace = skeleton(data.shape[1], lambda x, y, s: fisher_z(data, x, y, s), alpha)
pattern, triples = orient_colliders(skel, seps)
graph, changes = meek(pattern)
return graph, skel, seps, trace, triples, changes
def labels(g, names):
return [f'{names[i]} {"--" if undirected(g, i, j) else "->" if directed(g, i, j) else "<-"} {names[j]}'
for i in range(len(g)) for j in range(i+1, len(g)) if adjacent(g, i, j)]random = np.random.default_rng(2725)
e = random.normal(size=(4000, 5))
a, c = e[:, 0], e[:, 2]
b = .9*a + .8*c + e[:, 1]
d = .8*b + e[:, 3]
f = .7*c + .8*d + e[:, 4]
data = np.column_stack([a, b, c, d, f])
graph, skel, seps, trace, triples, changes = pc(data)
print('Nombres: A, B, C, D, E; n=4000, semilla 2725, alpha=0.01')
print('Aristas:', labels(graph, list('ABCDE')))
print('Separadores:', {f'{"ABCDE"[i]}{"ABCDE"[j]}': ''.join('ABCDE'[k] for k in s) for (i,j),s in seps.items()})
print('Colisionadores:', triples, '; reglas:', changes, '; contrastes:', len(trace))Restricted class search
This example uses at most five nodes and two parents. It enumerates representatives compatible with that limit and explores additions and deletions, deduplicating by skeleton and colliders. The parent limit can omit class representatives; this is a teaching simplification, not the complete implementation with GES guarantees. The score removes constants common to all graphs.
import numpy as np
from itertools import combinations, product
from math import log, pi
# DAG explícito: 0→1, 0→2, 1→3, 2→3. Varianzas de ruido distintas.
rng = np.random.default_rng(272501)
X = np.zeros((400, 4))
X[:, 0] = rng.normal(0, 1.2, len(X))
X[:, 1] = .8*X[:, 0] + rng.normal(0, .8, len(X))
X[:, 2] = -.7*X[:, 0] + rng.normal(0, 1.1, len(X))
X[:, 3] = .9*X[:, 1] + .75*X[:, 2] + rng.normal(0, .7, len(X))
print('Simulación:', X.shape, 'DAG: 0→1, 0→2, 1→3, 2→3')# Un DAG es una tupla de máscaras de padres: dag[j] contiene los padres de j.
# El prototipo limita nodos y padres; no recibe la garantía general de GES.
MAX_NODOS, MAX_PADRES = 5, 2
def aristas(dag):
p = len(dag)
return frozenset((i, j) for j in range(p) for i in range(p)
if (dag[j] >> i) & 1)
def valido(dag):
p = len(dag)
if p > MAX_NODOS or any(not isinstance(m, (int, np.integer)) or m < 0 or
m >= (1 << p) or (m >> j) & 1 or
int(m).bit_count() > MAX_PADRES
for j, m in enumerate(dag)):
return False
pendientes = set(range(p))
while pendientes:
listos = [j for j in pendientes if not any((dag[j] >> i) & 1 for i in pendientes)]
if not listos:
return False
pendientes.difference_update(listos)
return True
def firma(dag):
if not valido(dag):
raise ValueError('DAG inválido o fuera de los límites de la búsqueda')
E = aristas(dag)
esqueleto = tuple(sorted((min(i,j), max(i,j)) for i,j in E))
vecinas = set(esqueleto)
colisionadores = []
for j in range(len(dag)):
padres = [i for i in range(len(dag)) if (i,j) in E]
for a,b in combinations(padres, 2):
if (min(a,b), max(a,b)) not in vecinas:
colisionadores.append((a,j,b))
return esqueleto, tuple(sorted(colisionadores))
def equivalentes(dag):
objetivo = firma(dag)
p = len(dag)
esqueleto = objetivo[0]
for opciones in product((0,1), repeat=len(esqueleto)):
padres = [0]*p
for (i,j), invertir in zip(esqueleto, opciones):
origen, destino = (j,i) if invertir else (i,j)
padres[destino] |= 1 << origen
candidato = tuple(padres)
if valido(candidato) and firma(candidato) == objetivo:
yield candidato
def bic_gauss(datos, dag):
if not valido(dag):
raise ValueError('DAG inválido o fuera de los límites')
n, p = datos.shape
if len(dag) != p or n <= MAX_PADRES+1:
raise ValueError('Dimensiones insuficientes')
puntuacion = 0.
for j in range(p):
padres = [i for i in range(p) if (dag[j] >> i) & 1]
Z = np.column_stack([np.ones(n), datos[:, padres]])
beta, _, rango, _ = np.linalg.lstsq(Z, datos[:, j], rcond=None)
if rango != Z.shape[1]:
raise ValueError('Regresión singular')
residuos = datos[:, j] - Z @ beta
var = float(residuos @ residuos / n)
if not np.isfinite(var) or var <= 0:
raise ValueError('Varianza residual inválida')
# Constantes por nodo excluidas: son iguales para todos los grafos.
puntuacion += -.5*n*log(var) - .5*len(padres)*log(n)
return puntuacion
def vecinos_clase(dag, modo):
"""Añade o quita un arco a todas las extensiones válidas de la clase."""
p = len(dag)
vistos = {}
for rep in equivalentes(dag):
E = aristas(rep)
for i in range(p):
for j in range(p):
if i == j:
continue
if modo == 'adelante' and ((i,j) in E or (j,i) in E):
continue
if modo == 'atras' and (i,j) not in E:
continue
nuevo = list(rep)
if modo == 'adelante':
nuevo[j] |= 1 << i
else:
nuevo[j] &= ~(1 << i)
nuevo = tuple(nuevo)
if valido(nuevo):
vistos.setdefault(firma(nuevo), nuevo)
return vistos
def buscar_clases(datos):
dag = tuple(0 for _ in range(datos.shape[1]))
actual = bic_gauss(datos, dag)
historial = [('inicio', firma(dag), actual)]
for modo in ('adelante', 'atras'):
while True:
candidatos = vecinos_clase(dag, modo)
puntuados = [(bic_gauss(datos, d), f, d) for f,d in candidatos.items()]
if not puntuados:
break
mejor, clave, propuesta = max(puntuados, key=lambda v: v[0])
if mejor <= actual + 1e-9:
break
dag, actual = propuesta, mejor
historial.append((modo, clave, actual))
return dag, historial
print('Búsqueda por representantes de clases preparada.')# BIC por suma directa de log-densidades normales de los residuos explícitos.
def bic_independiente(datos, dag):
n,p = datos.shape
loglik = 0.
total_padres = 0
for j in range(p):
pp = [i for i in range(p) if (i,j) in aristas(dag)]
Z = np.column_stack([np.ones(n), datos[:, pp]])
coef = np.linalg.lstsq(Z, datos[:,j], rcond=None)[0]
err = datos[:,j] - Z@coef
sigma = np.sqrt(np.mean(err**2))
loglik += np.sum(-.5*(err/sigma)**2 - log(sigma) - .5*log(2*pi))
total_padres += len(pp)
# Retira también parámetros comunes de media y varianza por nodo.
return loglik - .5*(total_padres+2*p)*log(n)
def bic_absoluto(datos, dag):
n,p = datos.shape
return bic_gauss(datos, dag)-.5*n*p*(1+log(2*pi)) - p*log(n)
verdadero = (0, 1, 1, 6)
assert valido(verdadero)
assert not valido((2,1,0,0)) # 0→1→0
assert not valido((1,0,0,0)) # bucle propio
miembros = list(equivalentes(verdadero))
assert len(miembros) > 0 and all(valido(d) and firma(d)==firma(verdadero) for d in miembros)
for d in miembros:
np.testing.assert_allclose(bic_absoluto(X,d), bic_independiente(X,d), atol=1e-8, rtol=0)
np.testing.assert_allclose(bic_gauss(X,d), bic_gauss(X,verdadero), atol=1e-8, rtol=0)
print('DAG verdaderos equivalentes dentro del límite de padres:', len(miembros))
print('BIC coincide con suma de log-densidades y entre representantes hasta 1e-8.')estimado, historial = buscar_clases(X)
assert all(valido(d) for d in equivalentes(estimado))
assert all(historial[i+1][2] > historial[i][2] for i in range(len(historial)-1))
print('Pasos de búsqueda:', len(historial)-1)
for fase, clave, score in historial:
print(fase, 'adyacencias:', clave[0], 'colisionadores:', clave[1], 'BIC relativo:', round(score,4))
print('Firma verdadera:', firma(verdadero), '; firma aprendida:', firma(estimado))Compare structures without inventing orientations
This cell’s skeleton SHD counts one operation per missing or extra adjacency and ignores reversals. Both mechanisms have different sizes and densities, but one sample of each cannot estimate recovery rates. If PC detects an orientation conflict, only its skeleton is retained and the issue reported.
# Comparación de esqueletos, no de orientaciones: una adyacencia falsa
# o ausente cuenta una operación; una inversión de flecha no cuenta.
def pares_esqueleto(dag):
return set(firma(dag)[0])
def shd_esqueleto(real, estimado):
return len(real ^ estimado)
def comparar_algoritmos(datos, real, etiqueta):
correcto = pares_esqueleto(real)
esqueleto_pc, separadores_pc, traza_pc = skeleton(
datos.shape[1], lambda x,y,s: fisher_z(datos,x,y,s), alpha=.01)
try:
grafo_pc, _, _, _, _, _ = pc(datos, alpha=.01)
estado_pc = 'orientación completada'
except ValueError as error:
estado_pc = 'orientación no resoluble: ' + str(error)
pares_pc = {(i,j) for i in range(datos.shape[1])
for j in range(i+1,datos.shape[1]) if esqueleto_pc[i,j]}
estimado, _ = buscar_clases(datos)
pares_ges = pares_esqueleto(estimado)
posibles = datos.shape[1]*(datos.shape[1]-1)//2
print(etiqueta, 'nodos:', datos.shape[1], 'aristas reales:', len(correcto),
'densidad:', round(len(correcto)/posibles, 3))
print('PC: adyacencias', sorted(pares_pc), 'SHD esqueleto',
shd_esqueleto(correcto,pares_pc), '|', estado_pc)
print('Búsqueda por clases: adyacencias', sorted(pares_ges), 'SHD esqueleto',
shd_esqueleto(correcto,pares_ges))
print('Una muestra por grafo: no estima tasas de recuperación ni supremacía.')
# Tres nodos, un solo arco; muestra y varianzas explícitas.
rng_3 = np.random.default_rng(272502)
X3 = np.zeros((400,3))
X3[:,0] = rng_3.normal(0,1.4,len(X3))
X3[:,1] = .9*X3[:,0] + rng_3.normal(0,.8,len(X3))
X3[:,2] = rng_3.normal(0,.7,len(X3))
verdad_3 = (0,1,0) # 0→1; nodo 2 aislado
assert valido(verdad_3) and valido(verdadero)
comparar_algoritmos(X3, verdad_3, 'Grafo disperso')
comparar_algoritmos(X, verdadero, 'Grafo más denso')An observational Sachs sample
Run this cell locally with dependencies specified in the comment. It downloads specific versions of bnlearn files and checks hashes; if they change, comparison stops. Only skeleton discrepancies against the reference are shown; FCI marks remain PAG endpoints rather than becoming supposedly known directions.
"""Comparar PC, FCI y GES sobre los datos observacionales de Sachs.
Instala con `python -m pip install numpy scipy pandas causal-learn==0.1.4.8`.
Descarga los datos de bnlearn; no necesita archivos de Oryon Learn.
La red de consenso es una referencia, no una verdad definitiva.
"""
from itertools import combinations
from urllib.request import urlopen
from io import BytesIO
from hashlib import sha256
from importlib.metadata import version
import numpy as np
import pandas as pd
from scipy.stats import norm
from causallearn.search.ConstraintBased.PC import pc
from causallearn.search.ConstraintBased.FCI import fci
from causallearn.search.ScoreBased.GES import ges
URL = 'https://www.bnlearn.com/book-crc/code/'
NOMBRES = ['Raf', 'Mek', 'Plcg', 'PIP2', 'PIP3', 'Erk', 'Akt', 'PKA', 'PKC', 'P38', 'Jnk']
HASHES = {
'sachs.data.txt.gz': '3b65a3c4fe642d8f9f9562fe798edbafd5aaefe80caecd7f9ec5dea2fbe86d03',
'sachs.discretised.txt.gz': '38f9dc827808948fb76dc20ce8bec7bcad2f5e903eeea5627701d8d0cb2ddeb6',
}
def descargar(nombre):
with urlopen(URL + nombre, timeout=45) as respuesta:
contenido = respuesta.read()
if sha256(contenido).hexdigest() != HASHES[nombre]:
raise ValueError('El archivo cambió; revisar la fuente antes de continuar')
tabla = pd.read_csv(BytesIO(contenido), sep=r'\s+', compression='gzip')
if list(tabla.columns) != NOMBRES or tabla.shape != (853, 11):
raise ValueError('Formato inesperado de los datos Sachs')
return tabla
original = descargar('sachs.data.txt.gz')
discreta = descargar('sachs.discretised.txt.gz')
X = original.to_numpy(dtype=float)
if not np.isfinite(X).all():
raise ValueError('Valores faltantes en el archivo crudo')
Z = np.column_stack([pd.Categorical(discreta[c]).codes for c in NOMBRES]).astype(int)
print('Versiones: causal-learn', version('causal-learn'), 'numpy', version('numpy'),
'scipy', version('scipy'), 'pandas', version('pandas'))
print('Muestra observacional:', X.shape, 'tres niveles por variable:',
[int(np.unique(Z[:, j]).size) for j in range(Z.shape[1])])
# Red de consenso descrita por bnlearn. No se equipara a la verdad completa.
aristas = [('PKC','PKA'), ('PKC','Raf'), ('PKA','Raf'),
('PKC','Mek'), ('PKA','Mek'), ('Raf','Mek'),
('Mek','Erk'), ('PKA','Erk'), ('Erk','Akt'), ('PKA','Akt'),
('PKC','P38'), ('PKA','P38'), ('PKC','Jnk'), ('PKA','Jnk'),
('Plcg','PIP3'), ('Plcg','PIP2'), ('PIP3','PIP2')]
consenso = {frozenset(e) for e in aristas}
assert len(consenso) == 17
def esqueleto(grafo):
m = grafo.graph
return {frozenset((NOMBRES[i], NOMBRES[j]))
for i in range(len(NOMBRES)) for j in range(i+1, len(NOMBRES))
if m[i,j] != 0 or m[j,i] != 0}
def comparar(grafo):
e = esqueleto(grafo)
return {'adyacencias': len(e), 'comunes': len(e & consenso),
'extra': len(e-consenso), 'faltantes': len(consenso-e),
'diferencia_esqueleto': len(e ^ consenso)}
def pc_esqueleto_propio(datos, alpha):
"""PC-stable esqueleto con Fisher-Z; no orienta el grafo."""
n, p = datos.shape
corr = np.corrcoef(datos, rowvar=False)
vecinos = [set(range(p)) - {i} for i in range(p)]
profundidad = 0
tests = 0
while True:
congelados = [s.copy() for s in vecinos]
borrar = set()
hubo_candidatos = False
for i in range(p):
for j in sorted(x for x in congelados[i] if x > i):
grupos = [sorted(congelados[i]-{j}), sorted(congelados[j]-{i})]
conjuntos = set()
for grupo in grupos:
conjuntos.update(combinations(grupo, profundidad))
if conjuntos:
hubo_candidatos = True
for S in sorted(conjuntos):
sub = corr[np.ix_([i,j,*S], [i,j,*S])]
inv = np.linalg.inv(sub)
r = -inv[0,1]/np.sqrt(inv[0,0]*inv[1,1])
if not np.isfinite(r) or abs(r) >= 1 or n-len(S)-3 <= 0:
raise ValueError('Fisher-Z indefinido')
pvalor = 2*norm.sf(abs(np.sqrt(n-len(S)-3)*np.arctanh(r)))
tests += 1
if pvalor > alpha:
borrar.add((i,j))
break
for i,j in borrar:
vecinos[i].remove(j)
vecinos[j].remove(i)
if not hubo_candidatos:
break
profundidad += 1
edges = {frozenset((NOMBRES[i],NOMBRES[j])) for i in range(p) for j in vecinos[i] if i<j}
return edges, tests
print('\nFisher-Z en escala cruda: sensibilidad a alpha')
for alpha in (.01, .05, .1):
aprendido = pc(X, alpha=alpha, indep_test='fisherz', stable=True,
show_progress=False, verbose=False)
propio, n_tests = pc_esqueleto_propio(X, alpha)
diferencia = propio ^ esqueleto(aprendido.G)
print('PC', alpha, comparar(aprendido.G), 'tests propios', n_tests,
'diferencia esqueleto propio-biblioteca', len(diferencia))
if diferencia:
print('Pares distintos:', sorted(tuple(sorted(e)) for e in diferencia))
print('\nOtras elecciones de test y escala')
pc_log = pc(np.log1p(X), alpha=.05, indep_test='fisherz', stable=True,
show_progress=False, verbose=False)
pc_discreto = pc(Z, alpha=.05, indep_test='chisq', stable=True,
show_progress=False, verbose=False)
print('PC log(1+x), Fisher-Z:', comparar(pc_log.G))
print('PC discretización del benchmark, chi-cuadrado:', comparar(pc_discreto.G))
pag, _ = fci(X, independence_test_method='fisherz', alpha=.05,
verbose=False, show_progress=False, node_names=NOMBRES)
print('FCI crudo Fisher-Z:', comparar(pag))
print('FCI extremos de cada arista:', [str(e) for e in pag.get_graph_edges()])
record = ges(X, score_func='local_score_BIC')
print('GES BIC gaussiano:', comparar(record['G']))
print('El conteo es solo de adyacencias; no mide orientación ni SID.')
print('El supuesto gaussiano lineal puede fallar; la red de consenso no es verdad exhaustiva.')npm run lab and open the connection link.Exercises
Step 1 of 3. What form do the parents of a covered edge u→v take?
Step 1 of 3. What remains after substituting M in the equation for Y?
def meek_rules(pdag):
"""Devuelve el cierre de las cuatro reglas sin modificar pdag."""
raise NotImplementedErrorAfter solving the exercises, check chain orientations and cancellation:
from itertools import product
# Cada bit orienta una arista de la cadena 0−1−2−3.
admisibles = []
for bits in product((0, 1), repeat=3):
E = {(i, i+1) if bit == 0 else (i+1, i)
for i, bit in enumerate(bits)}
hay_colisionador = any((j-1, j) in E and (j+1, j) in E for j in (1, 2))
if not hay_colisionador:
admisibles.append(sorted(E))
print('Orientaciones sin colisionador:', len(admisibles), admisibles)
assert len(admisibles) == 4
efecto_directo, a, c = -1, 1, 1
efecto_total = efecto_directo + a*c
assert efecto_total == 0
print('Coeficiente de X al sustituir M:', efecto_total)