Skip to main content

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


% There are a number of ways you can tell Matlab about the Bayes Server API
% Here is one way. For more information please see the Matlab Java help
bayesVersion = '7.24'; % TODO change to the version you are using
networkPath = ['C:\ProgramData\Bayes Server ', bayesVersion, '\Sample Networks\Waste.bayes']; % TODO update to the path of the Bayes Server sample network Waste.bayes
jarPath = ['C:\Program Files\Bayes Server\Bayes Server ', bayesVersion, '\API\Java\BayesServer-', bayesVersion, '.jar']; % TODO update to the path of the Bayes Server jar
javaaddpath(jarPath);


import com.bayesserver.*;
import com.bayesserver.inference.*;

% For licensed software, uncomment the following line, and replace the text with your license key
% License.validate('license-key-goes-here');

% load an existing network
network = Network();
network.load(networkPath);

disp(['Network has ', num2str(network.getNodes.size), ' nodes']);

filterState = network.getVariables().get('Filter state', true);
filterStateIntact = filterState.getStates().get('Intact', true);
dustEmission = network.getVariables().get('Dust emission', true);
wasteType = network.getVariables().get('Waste type', true);
wasteTypeIndustrial = wasteType.getStates().get('Industrial', true);
wasteTypeHousehold = wasteType.getStates().get('Household', true);

inference = RelevanceTreeInference(network); % once created this inference engine can be reused for many queries
queryOptions = RelevanceTreeQueryOptions();
queryOutput = RelevanceTreeQueryOutput();

% Add a query
queryWasteType = Table(wasteType);
inference.getQueryDistributions().add(queryWasteType);

% Set some evidence
evidence = inference.getEvidence();
evidence.setState(filterStateIntact);
evidence().set(dustEmission, java.lang.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
disp(queryWasteType.get(toJavaArray(wasteTypeIndustrial)));
disp(queryWasteType.get(toJavaArray(wasteTypeHousehold)));