Causal inference in Python

# __author__ = 'Bayes Server'
# __version__= '0.1'

import jpype  # pip install jpype1    (version 1.2.1 or later)
import jpype.imports
from jpype.types import *

classpath = "C:\\Program Files\\Bayes Server\\Bayes Server 9.5\\API\\Java\\bayesserver-9.5.jar"

# Launch the JVM
jpype.startJVM(classpath=[classpath])

# import the Java modules

from com.bayesserver import *
from com.bayesserver.inference import *

network = Network()

network.load('C:\\ProgramData\\Bayes Server 9.5\\Sample Networks\\Causal Inference Simple.bayes')

drug = network.getVariables().get('Drug', True)
drugTrue = drug.getStates().get('True', True)
drugFalse = drug.getStates().get('False', True)

recovered = network.getVariables().get('Recovered', True)
recoveredTrue = recovered.getStates().get('True', True)

factory = RelevanceTreeInferenceFactory()
inference = factory.createInferenceEngine(network)
queryOptions = factory.createQueryOptions()
queryOutput = factory.createQueryOutput()
queryRecovered = Table(recovered)
inference.getQueryDistributions().add(queryRecovered)

print('Non-causal version (incorrect)...')

# First lets calculate P(Recovered=True|Drug=True) - P(Recovered=True|Drug=False)
# without an intervention. i.e. non-causally which will give us the wrong result

inference.getEvidence().setState(drugTrue)
inference.query(queryOptions, queryOutput)

pRecoveredGivenDrugTrue = queryRecovered.get(recoveredTrue)
inference.getEvidence().setState(drugFalse)
inference.query(queryOptions, queryOutput)
pRecoveredGivenDrugFalse = queryRecovered.get(recoveredTrue)

effectivenessNonCausal = pRecoveredGivenDrugTrue - pRecoveredGivenDrugFalse
print('Effectiveness of drug (non-causal) = {:.2%}'.format(effectivenessNonCausal))

print()

print('Causal version...')

# Now lets calculate P(Recovered=True|Do(Drug=True)) - P(Recovered=True|Do(Drug=False))
#  with an intervention. i.e. causally which will give us the correct result

inference.getEvidence().setState(drugTrue, None, InterventionType.DO)
inference.query(queryOptions, queryOutput)
pRecoveredGivenDoDrugTrue = queryRecovered.get(recoveredTrue)

inference.getEvidence().setState(drugFalse, None, InterventionType.DO)
inference.query(queryOptions, queryOutput)
pRecoveredGivenDoDrugFalse = queryRecovered.get(recoveredTrue)

effectivenessCausal = pRecoveredGivenDoDrugTrue - pRecoveredGivenDoDrugFalse
print('Effectiveness of drug (causal) = {:.2%}'.format(effectivenessCausal))

# Expected output:
#
# Non-causal version (incorrect)...
# Effectiveness of drug(non-causal) = -4.91 %
#
# Causal version...
# Effectiveness of drug(causal) = 5.02 %