% rovnice struny
L     = 1;    % [m]
f     = 3;    % 
eeps  = 1e-6;
maxit = 1e3;

test_type = 'it_cg_preconditioning'; % 'it_methods_comparison', 'it_cg_preconditioning'

switch test_type
  case 'it_methods_comparison'
    C = 20;
    it = nan(6,C);
    for N = 3:C
      h = L/N;
      n = N-1;
      A = spdiags(ones(n,3)*diag([-1 2 -1]),[-1,0,1],n,n);
      b = h^2*f*ones(n,1);
      [x_j,it(1,N)] = it_method(A,b,'jacobi'            ,eeps,maxit);
      [x_g,it(2,N)] = it_method(A,b,'gauss-seidel'      ,eeps,maxit);
      %[x_s,it(3,N)] = it_method(A,b,'sor'               ,eeps,maxit,1.01);
      [x_r,it(4,N)] = it_method(A,b,'richardson'        ,eeps,maxit,0.4);
      [x_d,it(5,N)] = it_method(A,b,'steepest-descent'  ,eeps,maxit);
      [x_c,it(6,N)] = it_method(A,b,'conjugate-gradient',eeps,maxit);
      fprintf('%03d  cond(A)=%3.5e\n',N,condest(A));
    end
    figure(1); hold on;
    plot(1:C,it(1,:),'-b');
    plot(1:C,it(2,:),'-r');
    %plot(1:C,it(3,:),'-m');
    plot(1:C,it(4,:),'-g');
    plot(1:C,it(5,:),'-k');
    plot(1:C,it(6,:),'-y');
    legend(gca, {'jacobi','gauss-seidel','richardson','steepest-descent','conjugate-gradient'},'Location','NorthWest');
    % x = A\b;
    % figure(1); hold on;
    % plot(0:h:L, [0;x;0], '-r');
  case 'it_cg_preconditioning'
    st = 10;
    C  = 20*st;
    it = nan(4,C/st);
    cn = nan(1,C/st);
    for N = st:st:C
      h = L/N;
      n = N-1;
      A = spdiags(ones(n,3)*diag([-1 2 -1]),[-1,0,1],n,n);
      b = h^2*f*ones(n,1);
      for j = 1:n
        A(j,:) = A(j,:) * (1+(j-1)*0.5/n);
        A(:,j) = A(:,j) * (1+(j-1)*0.5/n);
      end
      [x_n,it(1,N/st)] = pcg_(A,b,'none'   ,eeps,maxit);
      [x_j,it(2,N/st)] = pcg_(A,b,'jacobi' ,eeps,maxit);
      [x_c,it(3,N/st)] = pcg_(A,b,'cholinc',eeps,maxit);
      %[x_s,it(4,N/st)] = pcg_(A,b,'ssor'   ,eeps,maxit,1);
      
      tmp = eig(full(A)); cn(1,N/st) = max(tmp)/min(tmp);
    end
    figure(1); hold on;
    plot(cn,it(1,:),'-k');
    plot(cn,it(2,:),'-b');
    plot(cn,it(3,:),'-r');
    %plot(cn,it(4,:),'-r');
    %legend(gca, {'CG','PCG - Jacobi','PCG - Cholinc','PCG - SSOR'},'Location','NorthWest');   % set(gca, 'YScale', 'log');
    legend(gca, {'CG','PCG - Jacobi','PCG - Cholinc'},'Location','NorthWest');   % set(gca, 'YScale', 'log');
end