function G = addevidence(M,V,Y,T)
% ADDEVIDENCE Add evidence (observations) to a graphical model
%
% G = ADDEVIDENCEFLAT(M,V,Y) where M is the original model, V are
% the nodes whose observed values Y are being added as evidence.
%
%  G = ADDEVIDENCEFLAT(M,V,Y,T) where T is the list of neighbors
%  for each node in the graph.

% Jerod Weinman
% jerod@acm.org
    
% $Id: addevidence.m 1 2009-05-07 13:41:00Z weinman $
 
% Jerod Weinman
% jerod@acm.org
% Copyright 2004, 2008, 2009
 
%    This file is part of Matlab GridCRF.
%
%    Matlab GridCRF is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    Matlab GridCRF is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with Matlab GridCRF.  If not, see <http://www.gnu.org/licenses/>.
    
  if length(V)~=length(Y)
	error('Node and label lists must be the same length');
  end;

  if any(V)<1 || any(V)>M.numNodes
	error('Node index out of range');
  end;
  
  if any(Y)<1 || any(Y)>M.numLabels
	error('Label index out of range');
  end;

  if nargin<4
	T = {};
  end;
  
  L = M.numLabels;
  E = M.adjmat;
  H = M.nodeEnergies; % LxN
  S = M.edgeEnergies; % NxN -> LxL

  for v=1:length(V)
	
	vv = V(v);
	
	if isempty(T)
	  nbr = neighbors(E,vv);
	else
	  nbr = T{vv};
	end;
	
	nbr = mysetdiff(nbr,V); % No need to modify other observations
	
	for uu=nbr(:)'
	  
	  if E(uu,vv)
		psi = S{uu,vv};
		S{uu,vv} = [];
		E(uu,vv) = 0;
	  else
		psi = S{vv,uu}';
		S{vv,uu} = [];
		E(vv,uu) = 0;
	  end;
	  
	  
	  H(:,uu) = H(:,uu) + psi(:,Y(v));
	end;
	
	  p0 = -Inf*ones(L,1);
	  p0(Y(v)) = 0;
	  
	  H(:,vv) = p0;
  end;
  
  G = struct('numNodes', {M.numNodes}, ...
			 'adjmat', {E}, ...
			 'numLabels', {L}, ...
			 'nodeEnergies', {H}, ...
			 'edgeEnergies', {S} );
  
