function L = logprob(E,Y,B,G,C)
%    LOGPROB Return the log probability of a configuration
%
%  L = LOGPROB(E,Y,B,G) where E is the adjacency matrix, Y is the
%  configuration, B are the node beliefs and G are the edge
%  beliefs.
%
%  L = LOGPROB(E,Y,B,G,C) where C==1 indicates the beliefs are in
%  logspace.


% Jerod Weinman
% jerod@acm.org
    
% $Id: logprob.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/>.

% See Equation (39) in
%
% JS Yedidia, WT Freeman, Y Weiss. Constructing Free Energy
% Approximations and Generalized Belief Propagation Algorithms. IEEE
% Transactions on Information Theory, 2005
  
  
  if nargin<5
	C = 0;
  end;
  
  dg = full(sum(E|E')); % Degree of each node
  
  nx = sub2ind( size(B), Y, 1:size(E,1) );

  if C
	L = -sum( (dg-1) .* B(nx) );
  else
	L = -sum( (dg-1) .* log( B(nx) ) );
  end;
  
  [N0,N1] = find(E);
  
  for e=1:length(N0)
	
	n0 = N0(e);
	n1 = N1(e);
	
	if C
	  L = L + G{n0,n1} (Y(n0),Y(n1));
	else
	  L = L + log( G{n0,n1} (Y(n0),Y(n1)) );
	end;
  end;
 
