Skip to main content

Inference (discrete & continuous) with a Bayesian network from R


source("bayesserver.R")

# TODO update the following path
networkPath <- "C:/ProgramData/Bayes Server 7.7/Sample Networks/Waste.bayes"


# If you are using a licensed version of Bayes Server, uncomment the following line and enter your license key
# licenseBayesServer("license-key-goes-here")

# create a Bayes Server network class and load from an existing file
network <- new(Network)
network$load(networkPath)

variables <- network$getVariables()

print(variables$size())

# reference some variables and states
filterState <- variables$get("Filter state", TRUE)
filterStateIntact <- filterState$getStates()$get("Intact", TRUE)
dustEmission <- variables$get("Dust emission", TRUE)
wasteType <- variables$get("Waste type", TRUE)
wasteTypeIndustrial <- wasteType$getStates()$get("Industrial", TRUE)
wasteTypeHousehold <- wasteType$getStates()$get("Household", TRUE)
metalsInWaste <- variables$get("Metals in waste", TRUE)

# Create an inference engine (this can be re-used for multiple queries)

factory <- new(RelevanceTreeInferenceFactory)
inference <- factory$createInferenceEngine(network)
queryOptions <- factory$createQueryOptions()
queryOutput <- factory$createQueryOutput()

# Add some queries
queryWasteType <- new(Table, wasteType)
queryMetalsInWaste <- new(CLGaussian, metalsInWaste)

queryDistributions <- inference$getQueryDistributions()
queryDistributions$add(queryWasteType)
queryDistributions$add(queryMetalsInWaste)

# Set some evidence
evidence <- inference$getEvidence()
evidence$setState(filterStateIntact)

evidence$set(dustEmission, new( Double, "3.0"))

# Execute the query
inference$query(queryOptions, queryOutput) # note that this can raise an exception (see help for details)

# Read the results of the query

print(queryWasteType$get(toStateArray(wasteTypeIndustrial)))
print(queryWasteType$get(toStateArray(wasteTypeHousehold)))

print(queryMetalsInWaste$getMean(metalsInWaste))
print(queryMetalsInWaste$getVariance(metalsInWaste))