%run_ai.m ====> Approximate Inverse Preconditioners' GMRES test
%_______________________________________________
%HERE spai2  => SPAI preocnditioner
%     waz_t  => Factorized SPAI
%     def_no => Deflation

if ~exist('matrix1.mat'); error('Get matrix1.mat FIRST'); end
if ~exist('spai2.m'); error('Get spai2.m FIRST'); end
if ~exist('gmrest_k.m'); error('Get gmrest_k.m FIRST'); end
   help run_ai
warning off MATLAB:flops:UnavailableFunction
    
iprob=input('ch5 : which test matrix (0-3) ? ')
 eval(['load matrix' num2str(iprob)])
   Matrix, n=size(A,1); nnzA=nnz(A); nnzAp=floor(nnzA/n);

rand('state',4210)
rhs = rand(n,1); if iprob==3;rhs = rhs+i*rand(n,1); end

disp('_______________________________No Prec: Ax=b___________')
[x0,res0]= gmrest_k(A,rhs,50,[],[],1.0e-6,4);
     l0=length(res0);

disp('_______________________________SPAI____________________')
 P2=spai2(A,nnzAp,0.4);
[xa,resa]=gmrest_k(A,rhs,50,P2,[],1.0e-6,4);
      la=length(resa);
nnz_SPAI=nnz(P2)

disp('_______________________________WAZ_ (AINV)_____________')
 [P2 P1]=waz_t(A,nnzAp,0.4/10);
[xb,resb]=gmrest_k(A,rhs,50,P2',P1,1.0e-6,4);
      lb=length(resb);
nnz_WAZT=nnz(P2)+nnz(P1)

hold off
  res0=res0/res0(1); resa=resa/resa(1); resb=resb/resb(1); 
  
semilogy(l0,res0(end),'r*',1:l0,res0,'r-','markersize',12), hold on 
semilogy(la,resa(end),'bd',1:la,resa,'b-','markersize',12), hold on 
semilogy(lb,resb(end),'ms',1:lb,resb,'m-','markersize',12)
 legend( '1','No precond', ...
         '2','SPAI', ...
         '3','WAZ\_T', 0)
 hold off, axis tight
 xlabel(['Test matrix' num2str(iprob) ': Cgce steps']); ylabel('Residuals')
 s=text(100,0.01,Matrix);set(s,'Fontsize',12,'Color','b')
