Causal Model in pyAgrum

Causality in pyAgrum

Causality in pyAgrum primarily involves building a causal model—that is, constructing an (observational) Bayesian network along with a set of latent variables and defining their relationships with observed variables. It also includes the ability to compute causal effects in such models using do-calculus.

pyAgrum provides a set of tools to perform causal inference and estimate causal effects from data. This includes the ability to identify interventions, compute causal impacts, and evaluate the effects of interventions on observed variables.

Note

The causal module can use a LaTeX special arrow (\(\hookrightarrow\)) to compactly represent an intervention. By default, it uses the classical “do” notation. You can change this behavior using the following configuration keys:

pyagrum.config["causal","latexDoPrefix"]="\hookrightarrow("
pyagrum.config["causal","latexDoSuffix"]=")"

A pyagrum.CausalModel pairs a causal DAG with latent (hidden) variables and explicit causal assumptions. It is the entry point for do-calculus reasoning and causal effect identification.

Most of the time, a pyagrum.CausalModel extends a pyagrum.BayesNet: the model then carries the observational CPTs needed to actually evaluate causal effects. It can also be built from a plain named pyagrum.DAG instead, with no BayesNet at all – every structural operation (backdoor/frontdoor, d-separation, toDot, induced sub-models, do-calculus identification) still works, but anything that reads a CPT raises pyagrum.OperationNotAllowed. Check pyagrum.CausalModel.hasObservationalBN() to know which case you are in.

See also

Causal computation in pyAgrum

Functions for computing causal impacts and applying do-calculus.

class pyagrum.CausalModel(*args)

A causal model pairing a causal DAG with an optional observational Bayesian network.

A CausalModel can be built either from a full BayesNet (CPTs available, the classic use case) or from a plain named DAG (structure only, no CPTs – see the third constructor form below and hasObservationalBN()). It adds latent (hidden) variables that represent unobserved common causes between observed variables. The causal DAG includes both observed and latent nodes; when built from a BayesNet, the observational BN contains only the observed ones.

Every structural operation (backdoor/frontdoor, existsArc, toDot, inducedCausalSubModel, do-calculus identification via pyagrum.causalImpact()) works in both cases. Anything that needs actual conditional probabilities (observationalBN(), variable(), evaluating a pyagrum.CausalImpact, pyagrum.counterfactual()) raises pyagrum.OperationNotAllowed when the model has no BayesNet.

CausalModel(bn) -> CausalModel
Parameters:
CausalModel(bn, latents, assumeNonSpurious=False) -> CausalModel
Parameters:
  • bn (pyagrum.BayesNet) – the observational Bayesian network.

  • latents (list of (str, list of str)) – description of latent variables. Each entry is a pair (name, children) where name is the latent variable name and children is the list of observed variable names it affects.

  • assumeNonSpurious (bool) – if True, existing arcs between the children of each latent variable are preserved. Default is False (arcs between affected children are removed as they are assumed to be explained by the latent confounder).

CausalModel(dag, latents=None, assumeNonSpurious=False) -> CausalModel

Build a causal model from a plain (named) DAG, without any BayesNet.

Parameters:
  • dag (pyagrum.DAG) – a named DAG (every node must have a name).

  • latents (list of (str, list of str), optional) – same format as above.

  • assumeNonSpurious (bool) – same meaning as above.

hasObservationalBN() returns False on the resulting model.

CausalModel(cm, bn) -> CausalModel

Build a causal model with the structure of cm (causal DAG, latent variables, spurious arcs) and the parameters of bn, for instance parameters learned from data.

Parameters:

Example

import pyagrum as gum

bn = gum.fastBN("X->Y;X->Z;Y->Z")
cm = gum.CausalModel(bn)
cm.hasObservationalBN()
# True

# a latent confounder U between X and Y (the arc X->Y is removed)
cm = gum.CausalModel(bn, [("U", ["X", "Y"])])
cm.latentVariablesNames()
# {'U'}
cm.existsArc("X", "Y")
# False

# a causal model from a DAG only (no CPTs needed for structural queries)
dag = gum.fastDAG("X->Y->Z")
cm = gum.CausalModel(dag)
cm.hasObservationalBN()
# False
cm.backDoor("X", "Z")
# set()

Scientific notes

A causal model is a causal diagram [1][2]: a DAG whose arcs are direct causal relations, over the observed variables and some latent (unobserved) variables. In pyAgrum a latent variable is a parentless common cause of at least two observed variables, so that the model is semi-Markovian. An intervention \(do(X=x)\) replaces the mechanism of \(X\) by the constant \(x\); without latent variables, its effect is given by the truncated factorization

\[P(v \mid do(x)) = \prod_{V_i \notin X} P(v_i \mid pa_i) \Big|_{X=x},\]

and with latent variables it has to be identified from the observational distribution (pyagrum.CausalImpact).

Two graphs. A CausalModel holds the causal DAG (observed and latent variables), used for every structural question (d-separation, back-door and front-door sets, identification), and the observational Bayesian network (observed variables only), whose CPTs are used to evaluate the identified formulas. They may differ: adding a latent variable removes, in the causal DAG only, the arcs between its children, their dependence being attributed to the latent common cause, unless assumeNonSpurious is true. In the same way, assumeSpurious(x, y) removes the arc \(x \to y\) from the causal DAG and assumeNonSpurious(x, y) puts it back; both require the arc to exist in the observational network.

A model built from a DAG instead of a Bayesian network has no parameters: the structural operations are available, but no formula can be evaluated.

Methods

addLatentVariable()

Add a latent (hidden) variable to the causal model.

assumeNonSpurious()

Mark an arc of the observational Bayesian network as non-spurious (a genuine causal effect): the arc is added to the causal DAG if it is not there.

assumeSpurious()

Mark an arc of the observational Bayesian network as spurious.

backDoor()

Find a backdoor adjustment set between cause and effect.

causalBN()

Deprecated alias for causalDAG.

causalDAG()

Return the full causal DAG, including latent variables.

children()

Return the children of a variable in the causal DAG.

connectedComponents()

Return the weakly connected components of the causal DAG (treating arcs as undirected).

connectedComponentsCount()

number of connected components

connectedComponentsList()

connected components as a dict of sets

existsArc()

Check whether an arc exists in the causal DAG.

frontDoor()

Find a frontdoor adjustment set between cause and effect.

hasObservationalBN()

Whether this model was built from a BayesNet (CPTs available).

idFromName()

Return the NodeId of a variable by name.

idsFromNames()

The ids of nodes given by their names, in a container of the same type.

inducedCausalSubModel()

Return the causal sub-model induced by a subset of observed nodes.

isAssumedSpurious()

Check whether the arc x→y is assumed spurious.

latentVariablesIds()

Return the NodeIds of all latent (hidden) variables in the causal model.

latentVariablesNames()

Return the names of all latent (hidden) variables in the causal model.

nameFromId()

Return the name of a variable by NodeId.

names()

Return the names of all variables in the causal model (observed and latent).

namesFromIds()

The names of nodes given by their ids, in a container of the same type.

observationalBN()

Return the observational Bayesian network underlying the causal model.

parents()

Return the parents of a variable in the causal DAG.

toDot()

Return a Graphviz dot string representing the causal model.

variable()

Return the variable with the given id or name (observed variables only).

Backdoor and frontdoor criteria

class pyagrum.DoorCriteria

Utility class implementing the backdoor and frontdoor criteria on a causal DAG.

All methods are static and take the DAG as their first argument. This class is stateless: it does not store any model.

A backdoor adjustment set Z between X and Y blocks all spurious (non-causal) paths from X to Y while leaving all directed causal paths open.

A frontdoor adjustment set Z between X and Y intercepts every directed path from X to Y, has no open backdoor path from X to Z, and all backdoor paths from Z to Y are blocked by X.

Notes

High-level search for a single valid set is available via pyagrum.CausalModel.backDoor() and pyagrum.CausalModel.frontDoor().

Example

import pyagrum as gum

bn = gum.fastBN("X->Z->Y")
dag = bn.dag()
x, y, z = bn.idFromName("X"), bn.idFromName("Y"), bn.idFromName("Z")
gum.DoorCriteria.satisfiesBackdoorCriterion(dag, x, y, set())
# True
gum.DoorCriteria.enumerateFrontdoorSets(dag, x, y) == [{z}]
# True

Scientific notes

DoorCriteria implements the two graphical criteria of [1] for the effect of a variable \(X\) on a variable \(Y\) in a causal DAG.

  • Back-door: a set \(Z\) satisfies the back-door criterion if no node of \(Z\) is a descendant of \(X\) and \(Z\) blocks every path between \(X\) and \(Y\) that starts with an arc into \(X\) (d-separation of \(X\) and \(Y\) by \(Z\) once the arcs out of \(X\) are removed). Then \(P(y \mid do(x)) = \sum_z P(y \mid x, z)\,P(z)\).

  • Front-door: a non-empty set \(Z\) satisfies the front-door criterion if (i) it intercepts every directed path from \(X\) to \(Y\), (ii) there is no unblocked back-door path from \(X\) to \(Z\), and (iii) every back-door path from \(Z\) to \(Y\) is blocked by \(X\) (checked for each node of \(Z\)). Then \(P(y \mid do(x)) = \sum_z P(z \mid x) \sum_{x'} P(y \mid x', z)\,P(x')\).

Enumeration of the back-door sets. If \(X\) has no parent, the only set returned is the empty one; if \(Y\) is a parent of \(X\), there is none. Otherwise the empty set is tested first, then the candidates are the ancestors of \(X\) or \(Y\) that are neither \(X\), \(Y\), a descendant of \(X\), nor an excluded node (the latent variables, when called from pyagrum.CausalModel). The sets are tried by increasing size and, within a size, in the increasing order of the node ids. With only_minimal (default), a set is kept only if it contains no set already found, so that only minimal sets are returned; max_cardinality bounds their size.

Enumeration of the front-door sets. If \(X\) is a parent of \(Y\), there is none (a direct arc cannot be intercepted). The candidates are the nodes on the directed paths from \(X\) to \(Y\), minus the nodes reached from \(X\) by a back-door path open without conditioning (condition ii), the nodes with a back-door path to \(Y\) not blocked by \(X\) (condition iii) and the excluded nodes; the sets are tried by increasing size and kept when they intercept every directed path (condition i) and, with only_minimal, when no node can be removed. When there is no directed path from \(X\) to \(Y\) (no causal effect), each remaining candidate of the connected component is returned alone.

Which set is used. firstBackdoor and firstFrontdoor return the first set met by the enumeration: a smallest set, ties broken by the node ids. pyagrum.CausalModel.backDoor and frontDoor (used by pyagrum.causalImpact) return the same set. The enumerations return all their sets sorted in the lexicographic order of the node ids (\(\{0, 5\}\) comes before \(\{2\}\)).

Methods

backdoorReach()

Return all nodes reachable from X via a backdoor path without collider.

enumerateBackdoorSets()

Enumerate valid backdoor adjustment sets for the causal effect of X on Y.

enumerateFrontdoorSets()

Enumerate valid frontdoor adjustment sets for the causal effect of X on Y.

existsUnblockedDirectedPath()

Test whether a directed path from X to Y exists that is not blocked by Z.

firstBackdoor()

Return the first valid backdoor adjustment set for the causal effect of X on Y: the sets are tried by increasing size, then by node ids, so that it is a smallest one.

firstFrontdoor()

Return the first valid frontdoor adjustment set for the causal effect of X on Y: the sets are tried by increasing size, then by node ids, so that it is a smallest one.

hasBackdoorPath()

Test whether an open backdoor path from X to Y exists given evidence on Z.

nodesOnDirectedPaths()

Return the set of the intermediate nodes of the directed paths from X to Y.

satisfiesBackdoorCriterion()

Test whether Z satisfies the backdoor criterion for the effect of X on Y.

satisfiesFrontdoorCriterion()

Test whether Z satisfies the frontdoor criterion for the effect of X on Y.