API reference#

Everything listed here is public. Modules, functions, methods and attributes whose names start with an underscore, and names a module does not list in its __all__, are implementation details and may change without notice.

Stability#

causalbase follows semantic versioning from 1.0.0; before that, a minor release may change the API, and the changelog says how. From 1.0.0, within a major version, the names below keep their signatures and meaning. What a minor release may still change is the exact structure learned when two operators or two orders score the same up to rounding, since a faster kernel may sum the same terms in another order; such changes are listed in the changelog. The score of a given structure on given data does not change beyond rounding.

The score objects cache what they compute and are not safe to share between threads; use one per thread, or processes.

Estimators#

Every estimator is importable from causalbase itself. Hyperparameters go to the constructor, fit() learns, and the results end in an underscore. They share one interface: the score’s parameters first (criterion names the score), n_jobs last, fit(X, initial_graph=None), and the same results. Each runs a function of its subpackage, listed below, which returns a SearchResult.

search.GES([criterion, ess, ...])

Learn a causal structure with Greedy Equivalence Search.

search.XGES([criterion, ess, ...])

Learn a causal structure with Extremely Greedy Equivalence Search.

order.OrderSearch([criterion, ess, ...])

Learn a Bayesian network by iterated local search over variable orders.

order.FLOP([criterion, ess, ...])

Learn a Bayesian network with FLOP (Wienöbst, Henckel and Weichwald, 2026).

search.HillClimbing([criterion, ess, ...])

Learn a Bayesian network by hill climbing, or tabu search, over DAGs.

exact.ExactSearch([criterion, ess, ...])

Learn the Bayesian network of highest score, or the best one under a parent limit.

lingam.RCD([method, order, pruning, ...])

Learn a linear non-Gaussian causal model from higher-order cumulants.

Search functions#

search.ges(score[, initial_graph, ...])

Run GES with score and return the learned equivalence class.

search.xges(score[, initial_graph, ...])

Run XGES with score and return the learned equivalence class.

order.order_search(score[, initial_order, ...])

Learn a network by iterated local search over orders, each local search polished by GES.

order.flop(score[, initial_order, max_iter, ...])

Run FLOP: its local search over orders, then its iterated local search.

search.hill_climbing(score[, initial_graph, ...])

Run hill climbing, or tabu search, over DAGs.

exact.exact_search(score[, initial_order, ...])

Find the network of highest score, or the best one under a parent limit.

search.SearchResult(dag, score, n_iter[, ...])

The network a search found, its score, and what it took to find it.

search.Knowledge([required, forbidden])

Adjacencies fixed in advance, by domain knowledge or by design.

Building blocks of the order searches#

order.OrderScorer(score[, max_steps, ...])

Hill climbing restricted to an order, with exact incremental replay.

order.OrderResult(total, parents)

Score of an order and the parent set chosen for every node.

order.InsertionSearch(scorer)

First-improvement insertion local search over orders.

order.IteratedLocalSearch(scorer[, n_swaps, ...])

Iterated insertion search with random-transposition kicks.

order.ILSResult(order, score, iterations, ...)

Best order and score, and the anytime trace (seconds, iteration, best score).

order.pair_polish(score, dag[, n_candidates])

Add parents (singly, or in pairs when no single one helps) until no node improves.

Cumulant methods#

The functions behind RCD. Each takes the statistics, not the data, except rcd_exact(). Cumulants and MomentSums are the dictionaries they pass around, Pruning and LambdaSelection the values of the estimator’s options of the same names.

lingam.moment_sums(x[, order])

Return the moment sums of x, centred on its own mean.

lingam.cumulants_from_sums(client_stats)

Merge the blocks' moment sums and return the pooled covariance and cumulants.

lingam.rcd(stats, *[, method, order, ...])

Find the causal order from the cumulants, then estimate the coefficients.

lingam.rcd_exact(x, *[, order, pruning, ...])

Find the causal order by deflating the data after each source, as HC does.

lingam.exact_order(first, deflate[, order])

Run the order search of rcd_exact() over data held anywhere.

lingam.tau_matrix_3rd(c3, c12, c21)

Return the third-order tau matrix.

lingam.tau_matrix_4th(c4, c13, c31, c22)

Return the fourth-order tau matrix.

lingam.estimate_b_from_cov(causal_order, cov)

Estimate the coefficient matrix B by OLS.

lingam.estimate_b_lasso_from_cov(...[, ...])

Estimate the coefficient matrix B by adaptive Lasso.

lingam.RCDResult(causal_order, coef)

A causal order and the coefficient matrix estimated for it.

Scores#

Score is the interface every search reads; a new score implements it, usually by subclassing FamilyScore, which adds the cache, the batching and the structure prior. Prior names the structure priors of BDeu ("bernoulli" and "tetrad"), ScoreName the scores make_score builds and CONTINUOUS_SCORES those of them that take continuous data. Every search takes every score.

scores.Score(*args, **kwargs)

A decomposable score: a DAG scores the sum of its families' local scores.

scores.FamilyScore(n_vars, expected_parents, *)

A decomposable score whose families are computed once and cached.

scores.BDeuScore(*args, **kwargs)

BDeu local score over a discrete dataset, with a structure prior.

scores.BICScore(data, *[, penalty_discount, ...])

BIC local score over a discrete dataset, memoised per family.

scores.GaussianBICScore(data, *[, ...])

BIC local score of a linear Gaussian model, memoised per family.

scores.BGeScore(data, *[, alpha_mu, ...])

BGe local score of a linear Gaussian model, memoised per family.

scores.make_score(name, data, *[, ess, ...])

Return the score called name over data.

scores.log_likelihood(dag, train, test, *[, ess])

Return the log likelihood of test's rows under dag, its parameters learned from train.

Data#

data.DiscreteDataset(values, cardinalities, ...)

A fully-observed dataset over discrete (categorical) variables.

data.ContinuousDataset(values, names)

A fully-observed dataset over continuous (real-valued) variables.

data.as_discrete(X[, categories])

Return X as a DiscreteDataset, encoding it if needed.

data.as_discrete_sites(sites)

Encode several sites' tables with one shared set of levels per variable.

data.as_continuous(X)

Return X as a ContinuousDataset; array columns are named x0, x1, ....

data.as_continuous_sites(sites)

Return each site's table as a ContinuousDataset, checking they share variables.

Benchmark networks#

Five networks of the Bayesian Network Repository ship with the package, each with one sample of 5000 rows, so that the examples and the tests need no downloads, and fetch_network() downloads 100 samples of each of 226 networks of that repository and of bnRep (see Benchmark networks). Each returns a NetworkBundle whose true structure is already indexed like the columns of its data.

datasets.load_network(name)

Load one of the bundled networks by name.

datasets.list_networks()

Return the bundled networks and their variable counts, smallest first.

datasets.fetch_network(name[, sample, data_home])

Download one sample of a bnlearn or bnRep network, with the network itself.

datasets.list_remote_networks([source])

Return the networks fetch_network() can download, with their variable counts.

datasets.get_data_home([data_home])

Return the folder that caches the networks fetch_network() downloads.

datasets.load_cancer()

Load cancer: 5 variables, 5000 rows.

datasets.load_asia()

Load asia: 8 variables, 5000 rows.

datasets.load_child()

Load child: 20 variables, 5000 rows.

datasets.load_insurance()

Load insurance: 27 variables, 5000 rows.

datasets.load_alarm()

Load alarm: 37 variables, 5000 rows.

datasets.NetworkBundle(name, data, truth, ...)

A network, its true structure, and data sampled from it.

Graphs#

graph.DAG(num_nodes)

A directed acyclic graph over integer nodes 0..num_nodes-1.

graph.PDAG(num_nodes)

A partially directed acyclic graph over integer nodes 0..num_nodes-1.

graph.dag_to_cpdag(dag)

Return the CPDAG of dag: its compelled edges directed, the rest undirected.

graph.moralize(dag)

Moralize a DAG into an undirected moral graph.

graph.mcs_order(adj)

Compute a maximum cardinality search (MCS) ordering.

graph.fill_in(adj, order)

Triangulate a graph using the Tarjan and Yannakakis (1984) fill-in.

graph.maximal_cliques(adj, order)

Extract the maximal cliques of a chordal graph.

graph.treewidth(dag)

Return an upper bound on the treewidth of dag's moral graph.

Metrics#

metrics.shd(g1, g2)

Return the structural Hamming distance between two graphs.

metrics.shd_skeleton(g1, g2)

Count node pairs whose adjacency differs, ignoring edge direction.

metrics.smhd(g1, g2)

Return the structural moral Hamming distance between two DAGs.

metrics.smhd_graphs(m1, m2)

Return the number of node pairs adjacent in exactly one of two undirected graphs.

metrics.edge_scores(true, est)

Return the precision, recall and F1 of est's edges against true.

metrics.graph_record(true, dag, score)

Arcs, score and distances to the true network of a learned DAG.

metrics.EdgeScores(precision, recall, f1, ...)

Precision/recall/F1 of an estimated DAG's edges against the truth.

Networks and sampling#

io.load_bif(path)

Read a BIF (.bif or .bif.gz) file into a DiscreteBN.

io.parse_bif(text[, source])

Parse the text of a BIF file into a DiscreteBN.

io.load_xbif(path)

Parse an XMLBIF (.xbif) file into a DiscreteBN.

io.forward_sample(bn, n, seed)

Draw n i.i.d.

io.DiscreteBN(dag, names, outcomes, ...)

A discrete Bayesian network loaded from an XMLBIF file.

Exceptions#

A cycle in a DAG and reading an estimator’s results before fit raise a CausalBaseError, which also derives from the built-in exception a caller would expect. An invalid argument or input raises ValueError (or ConfigurationError, which is one), and the wrong kind of input TypeError.

exceptions.CausalBaseError

Base class for every error causalbase raises deliberately.

exceptions.ConfigurationError

An argument or setting is invalid.

exceptions.CycleError

An edge would close a directed cycle, or a graph that must be acyclic is not.

exceptions.NotFittedError

An estimator's result was read before fit was called.