Skip to main content

Impact analysis in Python

# __author__ = 'Bayes Server'
# __version__= '0.2'

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

classpath = "lib/bayesserver-10.8.jar" # TODO download the Bayes Server Java API, and adjust the path

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

# import the Java modules
from com.bayesserver import Network
from com.bayesserver.inference import DefaultEvidence
from com.bayesserver.analysis import Impact, ImpactOptions, ImpactSubsetMethod
from jpype import java

# Uncomment the following line and change the license key, if you are using a licensed version
# License.validate("xxx")

# TODO download network from the Bayes Server User Interface (or Bayes Server Online)
# and adjust the following path
network_path = 'networks/Waste.bayes'

network = Network()
network.load(network_path)

variables = network.getVariables()

# discrete
burning_regimen = variables.get('Burning Regimen', True)
waste_type = variables.get('Waste type', True)
filter_state = variables.get('Filter state', True)

# continuous
filter_efficiency = variables.get('Filter efficiency', True)
dust_emission = variables.get('Dust emission', True)
metals_in_waste = variables.get('Metals in waste', True)
co2_concentration = variables.get('CO2 concentration', True)
light_penetrability = variables.get('Light penetrability', True)
metals_emission = variables.get('Metals emission', True)

filter_state_intact = filter_state.getStates().get('Intact', True)
waste_type_industrial = waste_type.getStates().get('Industrial', True)

evidence = DefaultEvidence(network)
evidence.set(light_penetrability, java.lang.Double(0.2))
evidence.set(co2_concentration, java.lang.Double(-1.0))
evidence.setState(waste_type_industrial)

options = ImpactOptions()
options.setSubsetMethod(ImpactSubsetMethod.EXCLUDE)
options.setMaxEvidenceSubsetSize(1)

evidence_to_analyse = [light_penetrability, co2_concentration, waste_type]

output = Impact.calculate(
network,
filter_state,
filter_state_intact,
evidence,
java.util.Arrays.asList(evidence_to_analyse),
options
)

print('P(Intact) (all evidence) = {}'.format(output.getHypothesis().getStateProbabilityAll()))
print('P(Intact) (no evidence) = {}'.format(output.getHypothesis().getStateProbabilityNone()))

print()

for item in output.getItems():
print(','.join([str(b) for b in item.getEvidenceFlags()]))
print('\tP(Intact)\t{}'.format(item.getStateProbability()))

# Expected output...

# P(Intact)(all evidence) = 0.8806625135255
# P(Intact)(no evidence) = 0.95

# False, True, True
# P(Intact) 0.95
# True, False, True
# P(Intact) 0.447566691128873
# True, True, False
# P(Intact) 0.858460027839224