%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MIT MAS622j/1.126J Fall 2008, Problem Set 3 
%
% (for Problem 3(g))
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
N = 6; 
dag = zeros(N,N);
A = 1; B = 2; C = 3; D = 4; E = 5; F = 6; 
dag(A,B) = 1;
dag(A,C) = 1;
dag(B,D) = 1;
dag(B,E) = 1;
dag(E,F) = 1;
dag(C,F) = 1;

false= 1; true= 2;
ns = 2*ones(1,N); % binary nodes
names = {'A', 'B', 'C', 'D', 'E', 'F'};

% Set up the topology of the Bayes Net
bnet = mk_bnet(dag, ns, 'names', names, 'discrete', 1:N);

% Display the graph: download graph_draw from the link on the class webpage
graph_draw(bnet.dag, 'node_labels', names);

% Set up conditional probability tables for each node 
bnet.CPD{A} = tabular_CPD(bnet, A, [1/2  1/2]);
bnet.CPD{B} = tabular_CPD(bnet, B, [1/4  1/2  3/4  1/2]);
bnet.CPD{C} = tabular_CPD(bnet, C, [1/2  3/4  1/2  1/4]);
bnet.CPD{D} = tabular_CPD(bnet, D, [3/4  3/5  1/4  2/5]);
bnet.CPD{E} = tabular_CPD(bnet, E, [1/5  1/3  4/5  2/3]);
bnet.CPD{F} = tabular_CPD(bnet, F, [4/5  3/5  3/5  4/5  1/5  2/5  2/5  1/5]);

% Choose an inference engine
engine = jtree_inf_engine(bnet);

% First, compute P(B=true)
evidence = cell(1,N);
[engine, ll] = enter_evidence(engine, evidence);

m = marginal_nodes(engine, B);
disp(sprintf('p(B) = %g', m.T(true))); 

% Second, compute P(B=true|F=true)
evidence = cell(1,N);
evidence{F} = true;
[engine, ll] = enter_evidence(engine, evidence);

m = marginal_nodes(engine, B);
disp(sprintf('p(B|F) = %g', m.T(true))); 

