% This code solves   
%  min mu*||H(x)||_*+1/2*||q.*(x-bx)||^2
% where H(x) is a block Hankel matrix formed from x,
% q is the weight matrix, and bx come from measurements: 
% x is m by n*(i+j-1) matrix.
% H(x) is m*i by n*j Hankel matrix.  
%
% The Fenchel dual of this problem is
%  min  sup_x <lambda,H(x)> - 0.5*||q.*(x-bx)||^2
%  s.t.  sigma_max(X) <= mu,
%
% This code solves the dual problem by proximal point algorithm.
%
% Input:  
% q       - m by n*(i+j-1) matrix of zero and ones
% bx      - a m by n*(i+j-1) matrix (measured observations)
% m,n,i,j - parameters
% mu      - regularization parameter
% tol     - termination tolerance 
% init    - 1 initialize all variables at zero
%           2 initialize x at an approximate optimal solution obtained from PADM2
% maxiter - maximum number of iterations
%
% Output: 
% x       - m by n*(i+j-1) matrix, the approximate primal optimal solution
% fval    - approximate primal optimal value
% dval    - approximate dual optimal value
% t       - cputime
% iter    - number of iterations
% gap     - duality gap
%
% Written by Maryam Fazel, Weimin Miao, Ting Kei Pong and Defeng Sun
% Last modified Nov 27, 2012

function [x,fval,dval,t,iter,gap2,iteration,runtime] = rcompletedPPA(q,bx,m,n,i,j,mu,tol,init,maxiter)


fprintf(' start dPPA\n')

tic

meps=1e-8; % machine epsilon

if init == 1
  x = zeros(m,n*(i+j-1));
  lambda = zeros(m*i,n*j);
  iteration = 0;
  runtime = 0;
elseif init == 2
  ADMtol = 0.005;
  ADMiter = 2000;
  [x,lambda,iteration,runtime] = rcompletedPPAinit(q,bx,m,n,i,j,mu,ADMtol,ADMiter); 
end

r = min(i,j);
qx = q.*bx;
tq = 1 - q;

Hankeltime = 0;
HankelAdjtime = 0;
svd_time = 0;

inmaxiter = 1000; % max iter for subproblem
index = 0; % the index for checking the criterion to update c

c = 1;  % c represent lambda in paper, the initial value % The number of iteration increases as c decreases and the cost time in each step increases as c increases.
cmax = 1e8;
rho = 2;  % parameter to update lambda

intolmin = tol*10;
intol = intolmin*40;

Hankeltime0 = clock;
Hx = Hkx(x,m,n,i,j);
Hankeltime = Hankeltime + etime(clock,Hankeltime0);

fbest = inf;
xbest = x;
    
for iter = 1:maxiter  
  if (iter == 1)
    L = 2*c*r + 1;
    s = 1.95/L;
  end
  alpha = 0.3; % parameter for line search 
  
  GZ = lambda - c*Hx;
  
  svd_time0 = clock;
  [R,S,T] = svd(GZ,'econ');
  svd_time = svd_time + etime(clock,svd_time0);
      
  P = R*max(S - mu,0)*T';
          
  GZP = GZ - P;
  HankelAdjtime0 = clock;
  HaGZP = Hkxad(GZP,m,n,i,j); % apply the adjoint of Hankel
  HankelAdjtime = HankelAdjtime + etime(clock,HankelAdjtime0); 

  diffqx = q.*x - qx;
  grad = HaGZP - diffqx; 
  indval = mytrace(Hx,lambda) - c/2*norm(Hx,'fro')^2 + norm(P,'fro')^2/(2*c) - norm(diffqx,'fro')^2/2;
         
  for initer = 1:inmaxiter
    indvalold = indval;
    for ininiter = 1:inmaxiter

      % fprintf('-----line search starts-----\n')
      xmid = x + s*grad; 
              
      Hankeltime0 = clock;
      Hx = Hkx(xmid,m,n,i,j);
      Hankeltime = Hankeltime + etime(clock,Hankeltime0);

      GZ = lambda - c*Hx;
 
      svd_time0 = clock;
      [R,S,T] = svd(GZ,'econ');
      svd_time = svd_time + etime(clock,svd_time0);
              
      P = R*max(S - mu,0)*T';      
      
      diffqx = q.*xmid - qx;
      indval = mytrace(Hx,lambda) - c/2*norm(Hx,'fro')^2 + norm(P,'fro')^2/(2*c) - norm(diffqx,'fro')^2/2;
%       fprintf(' s, ininiter, val, valold, armijoval1, armijoval = %g, %g, %g, %g, %g, %g\n', s, ininiter, indval, indvalold, indval-indvalold, 1e-4*s*norm(grad,'fro')^2)
%       fprintf('!') % show the iteration for line search 
      if (indval-indvalold >= 1e-4*s*norm(grad,'fro')^2)
        % fprintf(' -----line search ends------\n')
        break
      else
        s = s*alpha;
      end
    end
        
    GZP = GZ - P;
    HankelAdjtime0 = clock;
    HaGZP = Hkxad(GZP,m,n,i,j); % apply the adjoint of Hankel
    HankelAdjtime = HankelAdjtime + etime(clock,HankelAdjtime0); 

    grad = HaGZP - diffqx;  
%     fprintf(' ++++++ s=%g, grad=%g, indval=%g, x-xmid=%g\n ',s,norm(grad,'fro'), indval, norm(x-xmid,'fro')')
    if (norm(grad,'fro')<intol) 
      % fprintf(' initer, grad, indiff = %g, %g, %g, %g \n', initer, norm(grad,'fro'), indval-indvalold)
      % fprintf(' *******inner problem is solved!*******\n')
      x = xmid;
      break
    end
    if (ininiter == 1)
      s = s*1.11;
    end
    x = xmid;
    % fprintf('.') % show the iteration for subproblem
  end
  % fprintf('*')

  lambda = GZP;
  hL = HaGZP;
  
  if iter>1
    if max(norm(x-xold,'fro'), norm(lambda-lambdaold,'fro')) < meps % early termination 
      fval = 1/2*norm(diffqx,'fro')^2 + mu*sum(svd(Hx));
      dfeas = norm(tq.*hL,'fro')/max([1,norm(hL,'fro')]);
      dval = -0.5*norm(q.*hL,'fro')^2 - mytrace(qx,hL);
%    fprintf(' iter, fval, dval, dfea, time = %g, %g, %g, %g, %g\n', iter, fval, dval, dfeas, toc)
      gap2 = abs(fval-dval)/max(abs(dval),1);
      fbest = fval;
      xbest = x;
      %fprintf(' early termination \n')
      %fprintf(' iter, fval, dval, time = %g, %g, %g, %g, %g\n', iter, fval, dval, toc)
      %fprintf('.')
      break
    end
  end
  
  fval = 1/2*norm(diffqx,'fro')^2 + mu*sum(svd(Hx));
  dfeas = norm(tq.*hL,'fro')/max([1,norm(hL,'fro')]);
  dval = -0.5*norm(q.*hL,'fro')^2 - mytrace(qx,hL);
  if fbest > fval
    fbest = fval;
    xbest = x;
  end  
%   fprintf(' iter, fval, dval, dfea1, time = %g, %g, %g, %g, %g\n', iter, fval, dval, dfeas, toc)
  gap = abs(fval - dval)/max(abs(dval),1);
  gap2 = abs(fbest - dval)/max(abs(dval),1);
  if max([gap2,dfeas]) < tol
    break
  end
  if gap > tol*10
    alpha = 0.95;
  else
    alpha = 0.98;
  end
  if iter > 1
    relgapold = gap/gapold;
    if intol > intolmin
      relgap_benchmark = gap/gap_benchmark;
      if relgap_benchmark < 1
        crec = c;
        xrec = x;
        Hxrec = Hx;
        lambdarec = lambda;
        gaprec = gap;
      end
      if relgap_benchmark > alpha^(index+1)
        index = index + 1;
        if index == 3
          c = crec;
          x = xrec;
          Hx = Hxrec;
          lambda = lambdarec;
          gap = gaprec;
          gap_benchmark = gaprec;
          index = 0;
          intol = max(intol/2, intolmin);
        else
          if relgapold > alpha
            c = rho*c;
          end
        end
      else
        index = 0;
        crec = c;
        xrec = x;
        Hxrec = Hx;
        lambdarec = lambda;
        gaprec = gap;
        gap_benchmark = gap;
      end
    else
      if relgapold > alpha;
        c = rho*c;
      end
    end
  else
    index = 0;
    crec = c;
    xrec = x;
    Hxrec = Hx;
    lambdarec = lambda;
    gaprec = gap;
    gap_benchmark = gap;
  end
  if c > cmax
    fprintf(' early termination since c exceeds cmax!')
    break;
  end
  gapold = gap;
  xold = x;
  lambdaold = lambda;
end

fval = fbest;
x = xbest;
t = toc;

if (init == 1)
  fprintf('\n Dual PPA terminates, initial =%g\n', init);
elseif (init == 2)
  fprintf('\n Dual PPA terminates, initial =%g, ADMtol=%g\n', init, ADMtol);
end
fprintf('#iter= %g, time= %g\n dobj= %g, pobj= %g\n',iter, t, dval, fval);
fprintf(' Total time for computing the the Hankel operator & its adjoint: %g  %g\n', Hankeltime, HankelAdjtime);
fprintf(' Total time for svd:  %g\n', svd_time);

    


