# Causal Inference¶

## Credal Network Transformation¶

Any object of class `StructuralCausalModel`

can be converted into an equivalent
credal network using the methods `toVCredal`

and `toHCredal`

for a vertex and a
constraints specification. The input is a collection of BayesianFactors` which
are the empirical distributions.

```
// convert the causal models into credal networks
SparseModel vcredal = causalModel.toVCredal(bnet.getFactors());
SparseModel hcredal = causalModel.toHCredal(bnet.getFactors());
```

## Inference engine¶

First the exact and approximate inferences engines should be set up. For this
create instances of classes `CredalCausalVE`

and `CredalCausalAproxLP`

as shown
in the following code snippet.

```
// set up the exact inference engine
CredalCausalVE infExact = new CredalCausalVE(causalModel, bnet.getFactors());
// set up the approximate inference engine
CredalCausalApproxLP infApprox = new CredalCausalApproxLP(causalModel, bnet.getFactors());
```

Alternatively, engines can be instantiated from a credal network.

```
// set up the exact inference engine
CredalCausalVE infExact = new CredalCausalVE(vcredal);
// set up the approximate inference engine
CredalCausalAproxLP infApprox = new CredalCausalAproxLP(hcredal);
```

## Causal Effects¶

Let us consider the causal effect of on a variable \(X_3\) of a variable \(X_1 = 1\), that is, \(P(X_3|do(X_1=1))\). This can be calculated with the exact inference engine as follows.

```
// set up and run a causal query
VertexFactor resExact = (VertexFactor) infExact
.causalQuery()
.setTarget(x[3])
.setIntervention(x[1],1)
.run();
```

Alternatively, for an approximate solution:

```
// set up and run a causal query
IntervalFactor resApprox = (IntervalFactor) infApprox
.causalQuery()
.setTarget(x[3])
.setIntervention(x[1],1)
.run();
```

## Conuterfactuals¶

Credici also allows counterfactual queries (in a twin graph) such as \(P(X_3'|do(X'_1=1), X'_1=0)\). The exact computation of this query can be done as follows.

```
// exact inference
resExact = (VertexFactor) infExact
.counterfactualQuery()
.setTarget(x[3])
.setIntervention(x[1],1)
.setEvidence(x[1], 0)
.run();
```

On the other hand, using the approximate engine:

```
// set up and run a counterfactual query
resApprox = (IntervalFactor) infApprox
.counterfactualQuery()
.setTarget(x[3])
.setIntervention(x[1],1)
.setEvidence(x[1], 0)
.run();
```