% function OptBetaLogPost   2005/2/23
%
% ytrue:n x 1 traininglabel�Cpost: gg x n Posterior prob., expF: n x gg Weight matrix
% beta�Coptimal beta  f:n x gg weak classifier
%
% expFnew: n x gg new weights for training pixels

function  [beta, expFnew] = OptBetaLogPos(ytrue, f, expF);

[n gg] = size(expF); expFnew = zeros(n, gg);      % expF(i,k) = exp(F(i,k))
f = f'; f2 = f .* f;

% sum of f with correctely-classified pixels
num1 = 0; for i = 1:n; num1 = num1 + f(i, ytrue(i)); end

% Iterative calculation of beta of classifier F + beta f
beta = 0; delta = 1; p = zeros(n, gg);
while abs(delta) > 10^(-8)
 expbf = exp(beta*f); expFc = expF .* expbf;
 for i = 1:n
  p(i, :) = expFc(i, :) ./ sum( expFc(i, :) );    % p(i,k): posterior prob.
 end % i
 tmp   = f  .* p;
 num2  = sum( sum( tmp ) );
 den1  = sum( sum( f2 .* p) );
 den2  = sum( (sum(tmp')) .^ 2 );
 delta = (num1 - num2)/(den1 - den2); beta = beta + delta;
 fprintf('RealOptLogPost: beta = %f, delta = %f\n', beta, delta)
end

expFnew = p;                  %  return renewed posterior prob.
