% DCQGV   Straightforward divide and conquer for computing the
%         eigenvalues of a quasiseparable matrix
%
%       [Lam,U]=DCQGV(d,G,v)
%       Computes the eigenvalues of the quasiseparable matrix via divide
%       and conquer.
%
%       d contains the diagonal elements of the quasiseparable matrix
%       G contains the sequence of Givens transformations,
%       REMARK eventhoug this is not strictly necessary, for convenience
%       within the divide make sure that the vector G is of length n,
%       having the last G, w.r.t. the one of length n-1, equal to the identity
%       THIS HAS NO ESSENTIAL MEANING BUT IS NEEDED FOR CONVENIENCE
%       v contains the vector
%      
%       
%       Lam contains the eigenvalues
%       U contains the eigenvectors
%
%
%       Software of the MaSe - Group
%       mase-at-cs.kuleuven.ac.be
%       Revision Date: 13/10/2006




function [lam,U] = DCQGV(d,G,v)

  % Initialize
    n=length(d);

    if n==0
      lam = []; U=[];
      return
    end
    
    
    if n==1
      U=1.0;
      lam=d(1); %*G(1,1);
      return
    end

    if n==2
      %u=u(:);  v=v(:); % Transform them to column vectors
      
      An2=[d(1),G(1,1)*v(1);G(1,1)*v(1),d(2)];
      %diag(d)+triu(u*v',1)+triu(u*v',1)';
      [U,lam]=eig(An2);
      lam=diag(lam);
      return
    end

    U=eye(n);

    if n>2
    
      % Split the problem
      %s=ceil(n/2);
      s=floor(n/2);
      %disp('Splitting at:')
      %disp(s)
    
      % Start the recursive procedure 
      [lam1,U1]=DCQGV(d(1:s),G(:,1:s-1),v(1:s-1));
      [lam2,U2]=DCQGV(d(s+1:n),G(:,s+1:n-1),v(s+1:n-1));
    
      % Prepare the first rank-one adaptation
      % Two times the matrix has to be updated with a rank one update to
      % obtain all the eigenvalues.
      U(1:s,1:s)=U1;
      U(s+1:n,s+1:n)=U2;
    
      % Let us compute now the rank 1 generators of the lower left block
      % Remark that this is a strictly lower triangular block so the
      % indices start one later
      temp=1; %G(2,s-1);
      for i=s-1:n-2
        ug(i-s+2)=G(1,i+1)*temp;
        temp=G(2,i+1)*temp;
      end
      %ug(n-s)=temp; % XXX

      
      % Compute the vector v
      temp=1; %G(2,n-2);
      %vr(s)=v(s);
      for i=s:-1:2
        vg(i)=v(i)*temp;
        temp=temp*G(2,i-1);
      end
      vg(1)=v(1)*temp;
      vg=vg(:);
      ug=ug(:);
      %vg=d(1:s);
      
      %%%%%%%%%%%%%%%%%%%%% CHECK THE CONSTRUCTED MATRICES %%%%%%%%%%
      %ug*vg' %.*prod(G(2,1:s))
      %BLS(G,v)
      %pause
      
      
      % PAY ATTENTION IN THIS MANUSCRIPT THE ROLE OF U and V is SWAPPED
      
      nu=norm(vg);
      nv=norm(ug);
   
      
      c1=nu*nv;    
     
    
      b1=zeros(n,1);
      a1=zeros(n,1);
    
      b1(1:s)=(U1'*vg)./(sqrt(2)*nu);
      b1(s+1:n)=(U2'*ug)./(sqrt(2)*nv);
    
    
      a1=[lam1;lam2];
    
    
      [l1,Q1]=eig_r1diag(a1,b1,c1);

      % Prepare the second rank-one adaptation
  
      c2=-c1;
      b2=zeros(n,1);
      a2=zeros(n,1);
    
      b2(1:s)=b1(1:s);
      b2(s+1:n)=-b1(s+1:n);
    
      b2=Q1'*b2;
        
      a2=l1;
   
    
      [l2,Q2]=eig_r1diag(a2,b2,c2);
   
      lam=l2;

      % Updating U
      
      U=U*Q1*Q2;
    
    end

% end straight


% This is the procedure from Bill Gragg adapted by Ellen
%
%
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [lam,U] = eig_r1diag(a,b,ro)
% a,b columns!! ro number
%
% [lam U] = eig_r1diag(a,b,c):
%
% The elements of lam are the EIGENVALUES and the columns of U are the
% orthonormal EIGENVECTORS, with last elements nonnegative, of the real
% symmetric matrix A = [diag(a) +ro*b* b'], so a diagonal matrix plus a rank-on%e modification.
%
% This code is an addapted version of the program eva written by Gragg which st%arts its iterations at the (iterates
% from the) poles closest to the zeros [3]. 



% begin eig_r1diag

     n = length(a);   U = eye(n); V=[];

   if ro ==0
        lam=a; return 
   end

   if n < 2
        lam = a(n)+ro*b(n)^2;  return
   end

if ro < 0
     a=-a;
     rho=-ro;
else rho=ro;
end

%    Order A = [diag(a) b; b' c] and scale it so b is nonnegative.

     [a p] = sort(-a);   a = - a;   b = b(p);   U = U(:,[p; n]);

     p = find(b < 0);
     if length(p) > 0
        b(p) = - b(p);   U(:,p) = - U(:,p);
     end

%    Deflate A.

%    b-deflation.

     m = 3*(n + 6);   tolb = m*eps*norm(b);

     p = find(b <= tolb);   l = length(p);
     if l > 0
        b(p) = zeros(l,1);
     end

%    Combo-deflation, introduced by Sorensen I believe.  This makes the
%    algorithm much less parallel.  The error analysis does not indicate that
%    anything more than a trivial kind of a-deflation is necessary.  It is
%    entirely conceivable that we need to require only that the poles are
%    all different.  If this is true then we shall, again, progress by going
%    backward!

     p = find(b > 0);   l = length(p);   k = 1;
     while k < l
        i = p(k);      j = p(k+1);   q = [i j]';
        a0 = a(i);     a1 = a(j);    b0 = b(i);     b1 = b(j);
        s = [a0 a1];   s = abs(s);   t = [b0 b1];   t = max([s t]);
        if b0 < b1
           r = b0/b1;
        else
           r = b1/b0;
        end
        d = a0 - a1;   s = d/(r + 1/r);   tolc = 2*eps*t;
        if s <= tolc
           s = r*r;   t = 1 + s;   s = s*d/t;   d = sqrt(t);
           if b0 < b1
              a(q) = [a0-s; a1+s];   b(q) = [0; b1*d];
              cs = 1/d;              sn = r/d;
           else
              a(q) = [a1+s; a0-s];   b(q) = [0; b0*d];
              cs = r/d;              sn = 1/d;
           end
           U(:,q) = U(:,q)*[-cs sn; sn cs];   p = p([1:k-1 k+1:l]');
           l = l - 1;                         k = max(1,k-1);
        else
           k = k + 1;
        end
     end

     lam = [a];

%    Solve the eigenproblem for the ordered and reduced arrow matrix, again
%    called A.  The index k refers to the kth eigenpair lam(p(k)), U(:,p(k)).

     a = a(p);   b = b(p);   p = [p];   n = length(p);   m = 2*(n + 6);

     if n < 2
        lam(p) = a(n)+rho*b(n)^2;   return
     end

     for k = 1:n

%       The index vector q omits reference to the neighboring finite poles.

        if k > 1  &  k < n
           q = [1:k-2 k+1:n];
        else
           if k == 1
              q = 2:n;
           else
              q = 1:n-2;
           end
        end

%       Determine a closest pole, shift, to lam(p(k)).  Shift A.  Compute
%       the initial approximation x to lam(p(k)) - shift.

      
        if k == 1
           shift = a(1);          as = a - shift;             cs = -1/rho;
           t = b(q)./as(q);       u = sqrt(sum(t.*t));   t = b(q).*t;
           s = sum([-t; cs])/2;   t = u*b(1);
           if s > 0
              if s < t
                 r = s/t;   x = b(1)*(r + sqrt(1 + r*r))/u;
              else
                 r = t/s;   x = b(1)*(1 + sqrt(1 + r*r))/r/u;
              end
           else
              if abs(s) < t
                 r = s/t;   x = - b(1)/(r - sqrt(1 + r*r))/u;
              else
                 r = t/s;   x = - b(1)*r/(1 + sqrt(1 + r*r))/u;
              end
           end
%x1=x+shift
        end

        if 1 < k  &  k <= n
           x = sum(a(k-1:k))/2;   t = b.*(b./(a - x));   f = sum([t;1/rho]);
           if f > 0
              shift = a(k);     as = a - shift;   pole = as(k-1);
           else
              shift = a(k-1);   as = a - shift;   pole = as(k);
           end
           cs = -1/rho;    t = b(q)./as(q);     dg = sum(t.*t);
           t = b(q).*t;       g = sum([t; 1/rho]);   alpha = pole*dg - g;
           s = b(k-1:k).^2;   t = pole*g;          beta = sum([s; t]);
           s = flipud(s);     t = s.*as(k-1:k);    f = - sum(t);
           beta = beta/2;     d = alpha*f;         d = sqrt(beta^2 - d);
           if beta > 0
              x = - f/(beta + d);
           else
              x = (d - beta)/alpha;
           end

        end



%       Iterate to compute lam(p(k)).
        param=.1;

        for j = 0:20

%          Compute g, f and the termination tolerance tolt.

           v = as - x;   s = b./v;   t = b.*s;   g = sum([t(q); 1/rho]);

           if k > 1  &  k <= n
              f = g + sum(t(k-1:k));
           else
              %if k == 1
                 f = g + t(1);
              %else
              %   f = g + t(n-1);
              %end
           end


          
%          Compute dg := g' and ddg := g''/2.

           t = s.*s;   dg = sum(t(q));   t = t./v;   ddg = sum(t(q));

%          Compute alpha and beta.

           if k > 1  &  k <= n
              s = sum(b(k-1:k).^2);         d = pole - x;
              t = d - x;                    u = x*d;
              alpha = ddg + (t*dg - g)/u;   beta = dg + (t*g + s)/u;
           else
              alpha = ddg + dg/x;           beta = dg + g/x;
           end


%          Compute the new iterate.

           beta = beta/2;   d = sqrt(beta^2 - alpha*f);
           if beta > 0
              x = x - f/(beta + d);
           else
              x = x + (d - beta)/alpha;
           end

        end

%       Accept the eigenvalue.  Save a - lam(p(k)) = as - x for later use in
%       computing the eigenvectors.

         lam(p(k)) = shift + x;
	 V = [V v];
        
     end

%    Compute the modified vector b.

     e = ones(n,1);   A = e*a' - a*e' + eye(n);   A = [A];
     A = V'./A;         b = sqrt(-(prod(A)))';

%    Compute numerically orthonormal eigenvectors of the modified reduced
%    matrix.  Compute U.

     
    A =  b*e';           V = - A./V;  
    A = sort(V.*V);      t = sqrt(sum(A))';   A = e*t';     V = V./A;
    U(:,p) = U(:,p)*V;

%    Sort (actually merge) and quit.

     [lam p] = sort(-lam);    lam = - lam;
      if ro < 0  
         lam = - lam; 
      end   
      U = U(:,p);

% end eig_r1diag


% References:

% [1] W.B. Gragg, John R. Thornton and Daniel D. Warner, Parallel divide and
%     conquer algorithms for the symmetric tridiagonal eigenvalue problem and
%     bidiagonal singular value problem, in Modeling and Simulation, Volume 23,
%     Part 1 (William G. Vogt and Marvin H. Mickle, editors), pp. 49-56.  Univ.
%     Pittsbugh School of Engineering, 1992.

% [2] Carlos F. Borges and William B. Gragg, A parallel divide and conquer
%     algorithm for the generalized real symmetric definite tridiagonal
%     eigenvalue problem, in Numerical Linear Algebra and Scientific Computing
%     (L. Reichel, A. Ruttan and R.S. Varga, editors).  de Gruyter, Berlin,
%     1993.  To appear.

% [3] Carlos F. Borges and William B. Gragg, Divide and conquer for generalized
%     real symmetric definite tridiagonal eigenproblems, in Proc. Shanghai
%     International Conference on Numerical Linear Algebra and Applications,
%     Shanghai, October 26-30, 1992.  To appear.

% [4] Ming Gu and Stanley C. Eisenstat, A stable and efficient algorithm for
%     the rank-one modification of the symmetric eigenproblem.  SIAM J. Matrix
%     Anal. Appl.  To appear.

% [5] Ming Gu and Stanley C. Eisenstat, A divide-and-conquer algorithm for the
%     symmetric tridiagonal eigenvalue problem.  Research report YALEU/DCS/
%     RR-932.  Department of Computer Science, Yale University, 27 November
%     1992.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [c,s,r] = Givens(x,y);
%
%  computes c,s,r such that
%
%  [c  s] [x] = [r]
%  [-s c] [y]   [0]
%
%  with c*c + s*s = 1;
%
   if (y == 0),
      c = 1; s = 0; r = x;
   else 
      if (abs(x) >= abs(y))
         t = y/x; r = sqrt(1 + t*t);
         c = 1/r;
         s = t*c;
         r = x*r;
      else 
         t = x/y; r = sqrt(1 + t*t);
         s = 1/r;
         c = t*s;
         r = y*r;
      end
   end 
      

    
    
    
