function can = canonical_dbn(intra, inter, observed_nodes)
% CANONICAL_DBN Does the DBN have a canonical topology?
% p = canonical_dbn(intra, inter, observed)
%
% The canonical topology is as follows
%   X1 -> X2
%   |     | 
%   v     v
%   Y1    Y2 
% where the Xi's are hidden vectors and not interconnected
% and the Yi's are observed vectors (possibly interconnected).
% i.e., 
% - The parents of an observable variable in slice t must all be in slice t.
% - An observable variable cannot have hidden children.
% - All hidden nodes must be persistent (have a child in the next slice).
% - There can not be any connections between the hidden nodes within a slice.


ss = length(intra);
hidden_nodes = setdiff(1:ss, observed_nodes);
obs = zeros(1,ss); obs(observed_nodes) = 1;
hidden = zeros(1,ss); hidden(hidden_nodes) = 1;
can = 1;

if isempty(hidden)
  fprintf(1, 'must specify some hidden nodes\n');
  can = 0;
end

if isempty(observed_nodes)
  fprintf(1, 'must specify some observed nodes\n');
  can = 0;
end

if ~isequal(intra(hidden_nodes, hidden_nodes), zeros(length(hidden_nodes)))
  fprintf(1, 'hidden nodes have intra connections\n');
  can = 0;
end

for i=1:length(hidden_nodes)
  j = hidden_nodes(i);
  cs = children(inter, j);
  if isempty(cs)
    fprintf(1, 'hidden variable %d is not persistent\n', j);
    can = 0;
  end
  for ci=1:length(cs)
    c = cs(ci);
    if obs(c)
      fprintf(1, 'hidden variable %d connects to observed variable %d in slice 2\n', j, c);
      can = 0;
    end
  end
end

for i=1:length(observed_nodes)
  j = observed_nodes(i);
  cs = children(inter, j);
  for ci=1:length(cs)
    c = cs(ci);
    fprintf(1, 'observed variable %d connects to variable %d in slice 2\n', j, c);
    can = 0;
  end
  cs = children(intra, j);
  for ci=1:length(cs)
    c = cs(ci);
    if hidden(c)
      fprintf(1, 'observed variable %d connects to hidden variable %d in slice 1\n', j, c);
      can = 0;
    end
  end
end




