% Compare the speed of the Boyen-Koller and jtree algorithms for DBNs,
% as a function of network size and approximation accuracy.

BAT = 0;

if BAT
  [intra, inter, node_sizes, onodes, names] = mk_bat_topology;
  ss = length(intra);
  eclass = 1:(2*ss);
  ss = length(intra);
  dnodes = 1:ss;
  bnet = cell(1,4);
  bnet{1} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'jtree');
  bnet{1}.filter_only = 0;
  for i=1:length(bnet{1}.bnodes)
    bnet{1}.bnodes{i} = mk_tabular_node(bnet{1}, i);
  end
  bnet{2} = change_algo(bnet{1}, 'bk', 'exact');
  bnet{3} = change_algo(bnet{1}, 'bk', 'ff');
  clusters = cell(1,2);
  clusters{1} = [stringmatch({'LeftClr', 'RightClr', 'LatAct', 'Xdot', 'InLane'}, names)];
  clusters{2} = [stringmatch({'FwdAct', 'Ydot', 'Stopped', 'EngStatus', 'FBStatus'}, names)];
  bnet{4} = change_algo(bnet{1}, 'bk', clusters);
  C = length(bnet);
else
  water = 1;
  if water
    [intra, inter, node_sizes, onodes] = mk_water_topology;
  else
    [intra, inter, node_sizes, onodes] = mk_cancer_topology(5, 0);
  end
  ss = length(intra);
  dnodes = 1:ss;
  eclass = 1:(2*ss);
  
  bnet = cell(1,5);
  bnet{1} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'jtree');
  bnet{2} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'bk', 'exact');
  bnet{3} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'bk', 'ff');
  if water
    bnet{4} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'bk',  {1:2, 3:6, 7:8});
  else
    bnet{4} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'bk',  {1:3, 4:5});
  end
  bnet{5} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'hmm');

  %bnet = cell(1,2);
  %bnet{1} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'hmm');
  %bnet{2} = mk_dbn(intra, inter, node_sizes, dnodes, eclass, onodes, 'bk', 'exact');

  C = length(bnet);
  for c=1:C
    for i=1:length(bnet{1}.bnodes)
      bnet{c}.bnodes{i} = mk_tabular_node(bnet{c}, i);
    end
    bnet{c}.filter_only = 0;
    bnet{c} = randomize_params(bnet{c}, 0);
  end
end


T = 4;
O = length(bnet{1}.observed_slice);
rand('state',0);
%vals = sample_discrete([0.5 0.5], O, T);
vals = sample_dbn(bnet{1}, T);

ll = zeros(1, C);
t = zeros(1, C);
for c=1:C
  tic; [bnet{c}, ll(c)] = enter_evidence(bnet{c}, vals(onodes,:)); t(c)=toc
end


if BAT
  i = stringmatch('LatAct', names);
else
  i = 1;
end

post = zeros(C, T);
for  c=1:C
  for t=1:T
    marg = marginal_nodes(bnet{c}, i, t);
    post(c,t) = marg.T(2)';
  end
end
post


if 1
  i = 2;
  for t=3:3
    for  c=1:C
      fprintf('t=%d, c=%d\n', t, c);
      marg = marginal_family(bnet{c}, i, t);
      marg.T(:)'
    end
  end
end

