function alpha = dirpolya_loo(file,prec,iter)
% alpha = dirpolya_loo(file,prec,iter)
% calculates a LOO solution to the Dirichlet-Multinomial/Polya
% distribution.
% file : file of sparse feature format.
% iter : number of maximum iteration.
% $Id: dirpolya_loo.m,v 1.2 2005/07/04 15:52:43 dmochiha Exp $
N = fmatrix(file)';
F = full(sum(N,1));
H = full(sum(N,2));
I = size(N,1);
K = size(N,2);
T = 100;
alpha = F / I;
thresh = 1.0e-4;
% optional parameters
if nargin > 1
  thresh = prec;
  if nargin > 2
    T = iter;
  end
end
% main
for t = 1:T
  alpha_prev = alpha;
  % a denominator
  z1 = 0;
  alpha0 = sum(alpha);
  for i = 1:I
    z1 = z1 + H(i) / (H(i) - 1 + alpha0);
  end
  for k = 1:K
    fprintf(1,'iteration [%d] : lexicon %4d/%d..\r', t, k, K);
    % a numerator
    z2 = 0;
    [i,j,v] = find(N(:,k));
    for c = v'
      z2 = z2 + c / (c - 1 + alpha(k));
    end
    % update alpha
    alpha(k) = alpha(k) * z2 / z1;
  end
  if converged(alpha_prev,alpha,thresh)
    fprintf(1,'\nconverged.\n');
    break;
  else
    fprintf(1,'\t\t\t\t\tdifference = %g%%\r', ...
	    diff_vec(alpha_prev,alpha) * 100);
  end
end
% $Id: dirpolya_loo.m,v 1.2 2005/07/04 15:52:43 dmochiha Exp $
