% Slightly larger example of a Markov Random Field
%
% 1 - 2 - 3
% |   |   |
% 4 - 5 - 6
% |   |   |
% 7 - 8 - 9

R = 3; C = 3; N = R*C;
H = reshape(1:N, [R C]); % H(i,j) = k means hidden node i,j has number k
arity = 2;
ns = arity*ones(1,N);

% Create the undirected graph
G = zeros(N,N);
for r=1:R
  for c=1:C
    if r>1,  G(H(r,c), H(r-1,c)) = 1; end % north
    if c<C,  G(H(r,c), H(r,c+1)) = 1; end % east
    if r<R,  G(H(r,c), H(r+1,c)) = 1; end % south
    if c>1,  G(H(r,c), H(r,c-1)) = 1; end % west
  end
end

% Create the unique pairwise potentials
T = {};
cliques = {};
k = 1;
GG = triu(G); % so we don't get 1->4 and 4->1
for i=1:N
  hood = find(GG(i,:));
  for j=hood
    cliques{k} = [i j];
    dom = cliques{k};
    T{k} = mk_table(dom, ns(dom));
    T{k}.T = myrand(ns(dom));
    k = k + 1;
  end
end
P = length(T); % num. pairs

bigT = mk_table(1:N, ns);
for i=1:P
  bigT = multiply_by_table(bigT, T{i});
end

% soft evidence
% phi(i) = Pr(X(i), ev(i)) = Pr(ev(i) | X(i)) Prior(X(i))
ev = cell(1,N);
for i=1:N
  ev{i} = mk_table(i, ns(i));
  ev{i}.T = normalise(ones(1,ns(i))); % uniform by default (acts like hidden)
end
ev{1}.T = [0.3 0.7]; % node 1 is observed 
for i=1:N
  bigT = multiply_by_table(bigT, ev{i});
end

bigT = normalize_table(bigT);
m = marginalize_table(bigT, 2);
T1 = m.T(:)';



dag = zeros(N,N);
dnodes = 1:N;
eclass = 1:N;
onodes = [];
bnet = mk_bnet(dag, ns, dnodes, 'jtree', eclass, onodes, G, cliques);
for i=1:N
  bnet.bnodes{i} = mk_input_node(bnet, i);
end
for i=1:P
  bnet.clpot{i} = T{i};
end
bnet = compile_params(bnet);

obs = [];
vals = [];
soft_obs = 1;
soft_vals = { ev{1}.T };
[bnet, ll] = enter_evidence(bnet, obs, vals, soft_vals, soft_obs);
m = marginal_nodes(bnet, 2);
T2 = m.T(:)';

assert(approxeq(T1, T2))
