Skip to main content

Inference (discrete & continuous) with a Bayesian network in Python

# __author__ = 'Bayes Server'
# __version__= '0.4'

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

from math import sqrt

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

# Launch the JVM

# import the Java modules
from com.bayesserver import *
from com.bayesserver.inference import *

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

network = Network()

# TODO download network from the Bayes Server User Interface (or Bayes Server Online)
# and adjust the following path

variables = network.getVariables()

print("Network has {} variables".format(variables.size()))

# Reference some variables
wasteType = variables.get("Waste type", True)
co2Concentration = variables.get("CO2 concentration", True)
filterEfficiency = variables.get("Filter efficiency", True)
metalsInWaste = variables.get("Metals in waste", True)
metalsEmission = variables.get("Metals emission", True)
lightPenetrability = variables.get("Light penetrability", True)

# Create an inference engine

factory = RelevanceTreeInferenceFactory()
inference = factory.createInferenceEngine(network)
queryOptions = factory.createQueryOptions()

queryOptions.setLogLikelihood(True) # Only set this if you need the log-likelihood
queryOutput = factory.createQueryOutput()

# Set some evidence
evidence = inference.getEvidence()
industrial = wasteType.getStates().get("Industrial", True)
evidence.setState(industrial) # set discrete evidence

# evidence.setStates(wasteType, [0.2, 0.8]) # example of setting soft evidence

evidence.set(co2Concentration, -1.0) # set continuous evidence

queryDistributions = inference.getQueryDistributions()

# How to add a discrete query
filterState = variables.get("Filter state", True)
queryFilterState = Table(filterState)

# How to add a continuous query
queryFilterEfficiency = CLGaussian(filterEfficiency)

# How to add a joint query

queryJoint = CLGaussian([lightPenetrability, metalsEmission])

# Calculate the queries/predictions
inference.query(queryOptions, queryOutput)

# Output the results
print("Log-likelihood: {}".format(queryOutput.getLogLikelihood()))

filterEfficiencyMean = queryFilterEfficiency.getMean(filterEfficiency)
filterEfficiencyVariance = queryFilterEfficiency.getVariance(filterEfficiency)

print("{}, {}".format(filterEfficiencyMean, sqrt(filterEfficiencyVariance)))

for state in filterState.getStates():
print("Filter state: {} {}".format(state.getName(), queryFilterState.get([state])))

print("Joint covariance = {}".format(queryJoint.getCovariance(lightPenetrability, metalsEmission)))