Causal computation in pyAgrum

Causal Inference (a.k.a. do-calculus)

The main entry point for causal inference is pyagrum.causalImpact(), which computes the causal effect of an intervention \(do(X=x)\) on a target variable \(Y\) within a pyagrum.CausalModel, using do-calculus identification.

causalImpact()

Identify and evaluate the causal effect of do(doing) on on, optionally conditioning on knowing.

class pyagrum.CausalImpact(cm, *, on, doing, knowing=None)

Represents the result of a causal identification query P(on | do(doing), knowing).

CausalImpact encodes the identified causal formula (when the effect is identifiable) as an expression tree that can be evaluated numerically. It also records the identification method used and an explanation string.

The identification procedure tries the following strategies in order: d-separation (no effect), backdoor adjustment, frontdoor adjustment, and general do-calculus (ID algorithm).

Notes

You may prefer to use the high-level function pyagrum.causalImpact() instead of constructing a CausalImpact object directly.

CausalImpact(cm, *, on, doing, knowing=None) -> CausalImpact
Parameters:
  • cm (pyagrum.CausalModel) – the causal model.

  • on (str or set of str) – target variable(s) of the query. A single string is automatically converted to a one-element set. Keyword-only.

  • doing (str or set of str) – intervened variable(s) (the do-operator applies to these). A single string is automatically converted to a one-element set. Keyword-only.

  • knowing (str or set of str, optional) – observed variable(s) to condition on. A single string is automatically converted to a one-element set. Default is empty. Keyword-only.

Example

import pyagrum as gum

bn = gum.fastBN("Z->X->Y;Z->Y")
cm = gum.CausalModel(bn)
ci = gum.CausalImpact(cm, on="Y", doing="X")
ci.isIdentified()
# True
ci.explanation()
# "backdoor ['Z'] found."
ci.toLatex()
# 'P\\left(Y \\mid \\text{do}(X)\\right) = \\sum_{Z}{P\\left(Y\\mid X,Z\\right) \\cdot P\\left(Z\\right)}'

Scientific notes

CausalImpact identifies the distribution \(P(Y \mid do(X), Z)\) in a causal model (pyagrum.CausalModel), that is, writes it as a formula of the observational distribution \(P\), then evaluates the formula, each of its terms being computed by exact inference in the observational Bayesian network. The methods are tried in this order.

  1. For a single cause, a single effect and no \(Z\): the back-door adjustment with the set \(W\) given by pyagrum.CausalModel.backDoor (see pyagrum.DoorCriteria for the criteria and the choice of the set), then the front-door adjustment with a non-empty set of mediators \(M\) [1]:

    \[P(y \mid do(x)) = \sum_w P(y \mid x, w)\,P(w), \qquad P(y \mid do(x)) = \sum_m P(m \mid x) \sum_{x'} P(y \mid x', m)\,P(x').\]
  2. If \(Y\) and \(X\) are d-separated by \(Z\) in the causal DAG without the arcs into \(X(Z)\), the variables of \(X\) which are not ancestors of \(Z\) (third rule of the do-calculus), there is no causal effect and the answer is \(P(Y \mid Z)\).

  3. Otherwise, the general algorithms of Shpitser and Pearl. ID [2] handles \(P(Y \mid do(X))\): it restricts the model to the ancestors of \(Y\), adds to \(X\) the variables without effect on \(Y\), and factorizes the query along the c-components [3] (two observed variables are in the same c-component when they are linked by a chain of shared latent parents). IDC [4] handles \(Z \neq \emptyset\): a variable \(z \in Z\) such that \(Y\) and \(z\) are d-separated by \(X \cup Z \setminus \{z\}\) in the graph without the arcs into \(X\) and out of \(z\) is moved into the intervention (second rule of the do-calculus), then

    \[P(y \mid do(x), z) = \frac{P(y, z \mid do(x))}{P(z \mid do(x))},\]

    both terms being computed by ID.

ID and IDC are complete: when they fail, the effect is not identifiable from \(P\) in this causal DAG [2][4]. ID then finds a hedge, a pair of nested c-forests which witnesses the non-identifiability. The CausalImpact is not identified (isIdentified() is false and eval() raises an exception), pyagrum.causalImpact returns no tensor, and the explanation names the c-components of the hedge. The formula is returned as built by the method that succeeded, without simplification.

Methods

cm()

Return the causal model associated with this query.

doing()

Return the NodeIds of the intervened variables.

doingNames()

Return the names of the intervened variables.

eval()

Evaluate the identified causal formula and return the result as a tensor.

explanation()

Return a human-readable explanation of the identification result.

formulaNames()

Return the names of all the variables used by the identified formula: the variables of the query appearing in the formula and the other ones it needs (adjustment set, mediators, summed-out variables).

isIdentified()

Return True if the causal effect was successfully identified.

knowing()

Return the NodeIds of the observed variables.

knowingNames()

Return the names of the observed variables.

latexQuery()

Return a LaTeX string for the original causal query before identification.

on()

Return the NodeIds of the target variables.

onNames()

Return the names of the target variables.

print_ast()

Print the AST of a CausalImpact function in a human readable way.

toDict()

Return the identified causal formula as a JSON-serialisable dictionary.

toLatex()

Return a LaTeX string representation of the causal impact formula.

toString()

Return a string representation of the identified causal formula.

Counterfactual reasoning

counterfactual()

Compute a counterfactual distribution in the twin network of Balke and Pearl.

counterfactualModel()

Build the twin network of Balke and Pearl for a counterfactual query.

class pyagrum.Counterfactual(cm, on, whatif, profile=None, values=None)

Computes a counterfactual distribution in the twin network of Balke and Pearl.

A counterfactual query asks: ‘Given that we observed profile, what would on have been if whatif had been set to the values in values?’

The twin network (pyagrum.counterfactualModel) contains the real world and a copy V* of the whatif variables and of their descendants (the counterfactual world), both worlds sharing the other variables, in particular the parentless ones. The counterfactual distribution is the posterior of the copies of on given the profile (observed in the real world) and the values of the copies of whatif: the abduction, action and prediction steps of Pearl are done by a single exact inference, which keeps the dependencies created by the profile between the shared variables.

Notes

Prefer using the high-level function pyagrum.counterfactual() instead of constructing a Counterfactual object directly.

A causal model with latent variables is refused (pyagrum.InvalidArgument): their distributions, needed for the abduction, are unknown.

Counterfactual(cm, on, whatif, profile=None, values=None) -> Counterfactual
Parameters:
  • cm (pyagrum.CausalModel) – the causal model.

  • on (int | str | set[int | str]) – target variables of the counterfactual query.

  • whatif (int | str | set[int | str]) – variables whose values are changed in the counterfactual scenario.

  • profile (dict of str → str | int) – the factual observation, given as {variable_name: value}, a value being a label (str) or the index of a label (int), as for the evidence. Default is empty.

  • values (dict of str → str | int) – counterfactual values for the whatif variables, given as {variable_name: value} (label or index). If omitted, the full joint distribution over all whatif values is returned.

Example

import pyagrum as gum

bn = gum.fastBN("X->Y->Z")
bn.cpt("X").fillWith([0.4, 0.6])
bn.cpt("Y").fillWith([0.9, 0.1, 0.2, 0.8])
bn.cpt("Z").fillWith([0.7, 0.3, 0.1, 0.9])
cm = gum.CausalModel(bn)
# Y=1 was observed: what would Z have been if X had been 0 ?
cf = gum.Counterfactual(cm, {"Z"}, {"X"}, {"Y": "1"}, {"X": "0"})
print(cf.value())
#
#   Z                │
# 0        │1        │
# ─────────│─────────│
#  0.6400  │ 0.3600  │

Scientific notes

Counterfactual answers the question “given that profile \(e\) was observed, what would the distribution of on \(Y\) have been, had whatif \(X\) been set to \(x'\)?”, written \(P(Y_{x'} \mid e)\). It follows the structural account of counterfactuals [5] (Section 7.1), popularized in [6] (chapter 8), the parentless observed variables of the model playing the role of the exogenous variables \(U\). Its three steps (abduction of \(U\) given \(e\), action \(do(X = x')\), prediction of \(Y\)) are done at once in the twin network of [7] (counterfactualModel):

  • the real world is the observational Bayesian network;

  • the counterfactual world is made of a copy \(V^*\) of each variable of \(X\) and of each of their descendants: \(X^*\) has no parent, any other \(V^*\) has the conditional probability table of \(V\), its parents being the copies of the parents of \(V\) when they exist, the parents themselves otherwise;

  • the other variables, in particular \(U\), are shared by both worlds.

With \(e\) observed in the real world, the exact inference of the twin network gives

\[P(Y_{x'} \mid e) = P(Y^* \mid e, X^* = x') = \sum_u P(u \mid e)\, P(Y^* \mid x', u),\]

where \(P(u \mid e)\) is the joint posterior of the shared variables: the dependence created by the evidence between them is kept. \(X^*\) has no parent and no observed descendant, hence is independent of \(e\); the joint posterior of \((Y^*, X^*)\) divided by the prior of \(X^*\) gives the result for every \(x'\).

Without values, the result is a tensor over \(Y\) and the values of whatif; values selects the counterfactual values. A causal model with latent variables is refused (InvalidArgument): their distributions are unknown.

Implementation limit. The variables with parents keep their conditional probability tables, the same in both worlds: the result is the counterfactual of the structural model only when every variable with parents is a deterministic function of them, all the uncertainty being carried by the parentless variables.

Methods

copyName()

Return the name of the copy of a variable in the twin network.

counterFactualModel()

Build the twin network of Balke and Pearl (see pyagrum.counterfactualModel).

impact()

Return the causal impact P(on* | do(whatif*), profile) in the twin network.

on()

Return the names of the target variables.

originalModel()

Return the original causal model.

profile()

Return the factual evidence used for abduction.

run()

Compute the counterfactual distribution by inference in the twin network.

toString()

Return a string description of the counterfactual query and its result.

twinModel()

Return the twin network of Balke and Pearl used for the computation.

value()

Return the counterfactual distribution as a tensor.

values()

Return the counterfactual assignments for the whatif variables.

whatif()

Return the names of the intervened variables.

References of the members

  • Alexander Balke and Judea Pearl. Probabilistic evaluation of counterfactual queries. In Proceedings of the Twelfth National Conference on Artificial Intelligence (AAAI-94), 230–237. AAAI Press, 1994. URL: https://dblp.org/rec/conf/aaai/BalkeP94.