File size: 13,139 Bytes
78e2a75 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | """
Algorithm adapters: run each causal discovery algorithm with timeout handling.
All algorithms take a pandas DataFrame (integer-encoded discrete data) and return
an adjacency matrix (np.ndarray) representing the learned graph.
"""
import numpy as np
import pandas as pd
import signal
import time
import traceback
import logging
from functools import wraps
logger = logging.getLogger(__name__)
class TimeoutError(Exception):
pass
def timeout_handler(signum, frame):
raise TimeoutError("Algorithm timed out")
def run_with_timeout(func, timeout_sec, *args, **kwargs):
"""Run a function with a timeout (Unix only, uses SIGALRM)."""
old_handler = signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(timeout_sec)
try:
result = func(*args, **kwargs)
signal.alarm(0)
return result
except TimeoutError:
logger.warning(f"Timeout after {timeout_sec}s")
raise
finally:
signal.signal(signal.SIGALRM, old_handler)
signal.alarm(0)
def safe_run(algo_name, func, timeout_sec, *args, **kwargs):
"""Run algorithm with timeout and exception handling.
Returns:
(adjmat, runtime, status): adjacency matrix, time in seconds, status string
"""
start = time.time()
try:
adjmat = run_with_timeout(func, timeout_sec, *args, **kwargs)
runtime = time.time() - start
return adjmat, runtime, 'success'
except TimeoutError:
runtime = time.time() - start
logger.warning(f"{algo_name}: TIMEOUT after {runtime:.1f}s")
return None, runtime, 'timeout'
except Exception as e:
runtime = time.time() - start
logger.error(f"{algo_name}: ERROR after {runtime:.1f}s: {e}")
logger.debug(traceback.format_exc())
return None, runtime, f'error: {str(e)[:100]}'
# ============================================================
# CONSTRAINT-BASED ALGORITHMS (causal-learn)
# ============================================================
def run_pc_discrete(df, alpha=0.01, stable=True):
"""PC algorithm for discrete data using G-squared test."""
from causallearn.search.ConstraintBased.PC import pc
from causallearn.utils.cit import gsq
data = df.values.astype(int)
cg = pc(data, alpha=alpha, indep_test=gsq, stable=stable,
show_progress=False)
# Extract adjacency matrix from GeneralGraph
adj = cg.G.graph # numpy array
return _causallearn_graph_to_adjmat(adj)
def run_fci(df, alpha=0.05, depth=4):
"""FCI algorithm - outputs PAG. We extract the directed edges."""
from causallearn.search.ConstraintBased.FCI import fci
from causallearn.utils.cit import gsq
data = df.values.astype(int)
g, edges = fci(data, independence_test_method=gsq, alpha=alpha,
depth=depth, show_progress=False)
adj = g.graph
return _causallearn_pag_to_adjmat(adj)
# ============================================================
# SCORE-BASED ALGORITHMS (causal-learn)
# ============================================================
def run_ges_causallearn(df, score_func='local_score_BDeu'):
"""GES algorithm from causal-learn."""
from causallearn.search.ScoreBased.GES import ges
data = df.values.astype(int)
record = ges(data, score_func=score_func, maxP=None,
parameters=None)
adj = record['G'].graph
return _causallearn_graph_to_adjmat(adj)
def run_boss(df, score_func='local_score_BDeu'):
"""BOSS (Best Order Score Search) algorithm."""
from causallearn.search.PermutationBased.BOSS import boss
data = df.values.astype(int)
cg = boss(data, score_func=score_func,
parameters=None)
adj = cg.graph
return _causallearn_graph_to_adjmat(adj)
def run_grasp(df, score_func='local_score_BDeu', depth=3):
"""GRaSP (Greedy relaxation of Sparsest Permutation) algorithm."""
from causallearn.search.PermutationBased.GRaSP import grasp
data = df.values.astype(int)
cg = grasp(data, score_func=score_func, depth=depth,
parameters=None)
adj = cg.graph
return _causallearn_graph_to_adjmat(adj)
# ============================================================
# SCORE-BASED ALGORITHMS (pgmpy)
# ============================================================
def run_ges_pgmpy(df, scoring_method='bicscore'):
"""GES algorithm from pgmpy."""
from pgmpy.estimators import ExhaustiveSearch, HillClimbSearch, BicScore, BDeuScore
# Use HillClimbSearch as proxy since pgmpy doesn't have native GES
# We'll use the tabu search for better exploration
scoring = BicScore(df) if scoring_method == 'bicscore' else BDeuScore(df)
hc = HillClimbSearch(df)
best_model = hc.estimate(scoring_method=scoring, max_indegree=4,
max_iter=100000, epsilon=0.0001)
return _pgmpy_model_to_adjmat(best_model, sorted(df.columns))
def run_hc(df, scoring_method='bicscore', max_indegree=3, max_iter=100000):
"""Hill-Climbing algorithm."""
from pgmpy.estimators import HillClimbSearch, BicScore, BDeuScore
scoring = BicScore(df) if scoring_method == 'bicscore' else BDeuScore(df)
hc = HillClimbSearch(df)
best_model = hc.estimate(scoring_method=scoring, max_indegree=max_indegree,
max_iter=max_iter, epsilon=0.0001)
return _pgmpy_model_to_adjmat(best_model, sorted(df.columns))
def run_tabu(df, scoring_method='bicscore', tabu_length=100, max_indegree=3, max_iter=100000):
"""Tabu Search algorithm."""
from pgmpy.estimators import HillClimbSearch, BicScore, BDeuScore
scoring = BicScore(df) if scoring_method == 'bicscore' else BDeuScore(df)
hc = HillClimbSearch(df)
best_model = hc.estimate(scoring_method=scoring, max_indegree=max_indegree,
max_iter=max_iter, epsilon=0.0001,
tabu_length=tabu_length)
return _pgmpy_model_to_adjmat(best_model, sorted(df.columns))
def run_mmhc(df, scoring_method='bdeuscore', significance_level=0.01):
"""Max-Min Hill-Climbing (MMHC) hybrid algorithm."""
from pgmpy.estimators import MmhcEstimator, BDeuScore, BicScore
mmhc = MmhcEstimator(df)
scoring = BDeuScore(df) if scoring_method == 'bdeuscore' else BicScore(df)
best_model = mmhc.estimate(scoring_method=scoring,
significance_level=significance_level)
return _pgmpy_model_to_adjmat(best_model, sorted(df.columns))
def run_k2(df, max_parents=3):
"""K2 algorithm (requires node ordering - we use alphabetical as default).
We run with multiple random orderings and take the best-scoring result.
"""
from pgmpy.estimators import HillClimbSearch, K2Score
scoring = K2Score(df)
hc = HillClimbSearch(df)
best_model = hc.estimate(scoring_method=scoring, max_indegree=max_parents,
max_iter=100000, epsilon=0.0001)
return _pgmpy_model_to_adjmat(best_model, sorted(df.columns))
# ============================================================
# CONVERSION UTILITIES
# ============================================================
def _causallearn_graph_to_adjmat(graph_matrix):
"""Convert causal-learn's graph representation to standard adjacency matrix.
causal-learn encoding:
graph[i,j] = -1 and graph[j,i] = 1 means i -> j
graph[i,j] = -1 and graph[j,i] = -1 means i -- j (undirected)
graph[i,j] = 1 and graph[j,i] = 1 means i <-> j (bidirected)
Our encoding:
adj[i,j] = 1 and adj[j,i] = 0 means i -> j
adj[i,j] = 1 and adj[j,i] = 1 means i -- j (undirected)
"""
n = graph_matrix.shape[0]
adj = np.zeros((n, n), dtype=int)
for i in range(n):
for j in range(n):
if i == j:
continue
if graph_matrix[i, j] == -1 and graph_matrix[j, i] == 1:
# i -> j (tail at i, arrowhead at j)
adj[i, j] = 1
elif graph_matrix[i, j] == -1 and graph_matrix[j, i] == -1:
# i -- j (undirected)
adj[i, j] = 1
adj[j, i] = 1
elif graph_matrix[i, j] == 1 and graph_matrix[j, i] == 1:
# i <-> j (bidirected) - treat as undirected for CPDAG comparison
adj[i, j] = 1
adj[j, i] = 1
return adj
def _causallearn_pag_to_adjmat(pag_matrix):
"""Convert PAG (from FCI) to adjacency matrix.
PAG encoding in causal-learn:
1 = arrowhead (>), -1 = tail (-), 2 = circle (o)
We extract: definite directed edges and definite adjacencies.
"""
n = pag_matrix.shape[0]
adj = np.zeros((n, n), dtype=int)
for i in range(n):
for j in range(n):
if i == j:
continue
# i -> j: tail at i (-1), arrowhead at j (1)
if pag_matrix[i, j] == -1 and pag_matrix[j, i] == 1:
adj[i, j] = 1
# i -- j or i o-o j or i o-> j: treat as undirected edge
elif pag_matrix[i, j] != 0 and pag_matrix[j, i] != 0:
adj[i, j] = 1
adj[j, i] = 1
return adj
def _pgmpy_model_to_adjmat(model, node_names):
"""Convert pgmpy DAGModel to adjacency matrix."""
n = len(node_names)
node_idx = {name: i for i, name in enumerate(node_names)}
adj = np.zeros((n, n), dtype=int)
for parent, child in model.edges():
if parent in node_idx and child in node_idx:
adj[node_idx[parent], node_idx[child]] = 1
return adj
# ============================================================
# ALGORITHM REGISTRY
# ============================================================
ALGORITHM_POOL = {
'PC_discrete': {
'func': run_pc_discrete,
'kwargs': {'alpha': 0.01, 'stable': True},
'library': 'causal_learn',
'output_type': 'cpdag',
'family': 'constraint',
},
'FCI': {
'func': run_fci,
'kwargs': {'alpha': 0.05, 'depth': 4},
'library': 'causal_learn',
'output_type': 'pag',
'family': 'constraint',
},
'GES': {
'func': run_ges_causallearn,
'kwargs': {'score_func': 'local_score_BDeu'},
'library': 'causal_learn',
'output_type': 'cpdag',
'family': 'score',
},
'BOSS': {
'func': run_boss,
'kwargs': {'score_func': 'local_score_BDeu'},
'library': 'causal_learn',
'output_type': 'cpdag',
'family': 'permutation',
},
'GRaSP': {
'func': run_grasp,
'kwargs': {'score_func': 'local_score_BDeu', 'depth': 3},
'library': 'causal_learn',
'output_type': 'cpdag',
'family': 'permutation',
},
'HC': {
'func': run_hc,
'kwargs': {'scoring_method': 'bicscore', 'max_indegree': 3, 'max_iter': 100000},
'library': 'pgmpy',
'output_type': 'dag',
'family': 'score',
},
'Tabu': {
'func': run_tabu,
'kwargs': {'scoring_method': 'bicscore', 'tabu_length': 100, 'max_indegree': 3, 'max_iter': 100000},
'library': 'pgmpy',
'output_type': 'dag',
'family': 'score',
},
'MMHC': {
'func': run_mmhc,
'kwargs': {'scoring_method': 'bdeuscore', 'significance_level': 0.01},
'library': 'pgmpy',
'output_type': 'dag',
'family': 'hybrid',
},
'K2': {
'func': run_k2,
'kwargs': {'max_parents': 3},
'library': 'pgmpy',
'output_type': 'dag',
'family': 'score',
},
}
def run_algorithm(algo_name, df, timeout_sec=600):
"""Run a single algorithm on a dataset.
Returns:
dict with keys: adjmat, runtime, status, output_type
"""
if algo_name not in ALGORITHM_POOL:
raise ValueError(f"Unknown algorithm: {algo_name}")
algo = ALGORITHM_POOL[algo_name]
func = algo['func']
kwargs = algo['kwargs'].copy()
adjmat, runtime, status = safe_run(
algo_name, func, timeout_sec, df, **kwargs
)
return {
'adjmat': adjmat,
'runtime': runtime,
'status': status,
'output_type': algo['output_type'],
'family': algo['family'],
}
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
# Quick test on Asia
from causal_selection.data.generator import load_bn_model, sample_dataset
model = load_bn_model('asia')
df = sample_dataset(model, 1000, seed=0)
print(f"Testing on ASIA (N=1000)...")
for algo_name in ALGORITHM_POOL:
result = run_algorithm(algo_name, df, timeout_sec=60)
status = result['status']
runtime = result['runtime']
if result['adjmat'] is not None:
n_edges = result['adjmat'].sum()
print(f" {algo_name:15s}: {status:10s} {runtime:6.2f}s edges={n_edges}")
else:
print(f" {algo_name:15s}: {status:20s} {runtime:6.2f}s")
|