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

The first example below uses JPype and the second uses PythonNet.

JPype

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

from jpype import *
from math import sqrt

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

startJVM(getDefaultJVMPath(), "-Djava.class.path=%s" % classpath)

bayesServer = JPackage("com.bayesserver")
bayesServerInference = bayesServer.inference

# Uncomment the following 2 lines and change the license key, if you are using a licensed version
# License = JClass("com.bayesserver.License")
# License.validate("xxx")

network = bayesServer.Network()

network.load("C:\\ProgramData\\Bayes Server 7.14\\Sample Networks\\Waste.bayes")

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 = bayesServerInference.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.set(co2Concentration, java.lang.Double(-1.0))  # set continuous evidence

queryDistributions = inference.getQueryDistributions()

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

# How to add a continuous query
queryFilterEfficiency = bayesServer.CLGaussian(filterEfficiency)
queryDistributions.add(bayesServerInference.QueryDistribution(queryFilterEfficiency))

# How to add a joint query

queryJoint = bayesServer.CLGaussian([lightPenetrability, metalsEmission])
queryDistributions.add(bayesServerInference.QueryDistribution(queryJoint))

# 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)))

shutdownJVM()

PythonNet

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

import clr
import sys
import math

# Tested with Python 2.7 and Bayes Server 6.15

# This example uses the pythonnet package (pip install pythonnet) and the Bayes Server .NET API

sys.path.append("C:\Program Files\Bayes Server\Bayes Server 6.15\API\NET 4.0")

clr.AddReference("BayesServer")
clr.AddReference("BayesServer.Inference")

from System import Nullable, Double
from System.Collections.Generic import List
from BayesServer import *
from BayesServer.Inference import *
from BayesServer.Inference.RelevanceTree import *

# License.Validate("xxx")   # call this with your license key if you are using a licensed version

network = Network()

network.Load("C:\\ProgramData\\Bayes Server 6.15\\Sample Networks\\Waste.bayes")

print("Network has {} variables".format(network.Variables.Count))

# Reference some variables
wasteType = network.Variables["Waste type", True]
co2Concentration = network.Variables["CO2 concentration", True]
filterEfficiency = network.Variables["Filter efficiency", True]
metalsInWaste = network.Variables["Metals in waste", True]
metalsEmission = network.Variables["Metals emission", True]
lightPenetrability = network.Variables["Light penetrability", True]

# Create an inference engine

factory = RelevanceTreeInferenceFactory()
inference = factory.CreateInferenceEngine(network)
queryOptions = factory.CreateQueryOptions()

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

# Set some evidence

industrial = wasteType.States["Industrial", True]
inference.Evidence.SetState(industrial) # set discrete evidence
inference.Evidence.Set(co2Concentration,  Nullable[Double](-1.0))   # set continuous evidence


# How to add a discrete query
filterState = network.Variables["Filter state", True]
queryFilterState = Table(filterState)
inference.QueryDistributions.Add(queryFilterState)

# How to add a continuous query
queryFilterEfficiency = CLGaussian(filterEfficiency)
inference.QueryDistributions.Add(queryFilterEfficiency)

# How to add a joint query
jointVariables = List[Variable]()
jointVariables.Add(lightPenetrability)
jointVariables.Add(metalsEmission)
queryJoint = CLGaussian(jointVariables)
inference.QueryDistributions.Add(queryJoint)

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

# Output the results

print("Log-likelihood: {}".format(queryOutput.LogLikelihood))

filterEfficiencyMean = queryFilterEfficiency.GetMean(filterEfficiency)
filterEfficiencyVariance = queryFilterEfficiency.GetVariance(filterEfficiency)

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

for state in filterState.States:
    print("Filter state: {} {}".format(state.Name,  queryFilterState[[state]]))

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