%
% Checcks the convergence for the parabolic pde with Dirichlet b.c.
%

a = 0;
b = 1;
tfin = 0.1;

%
% Order in At
%
% Number of subintervals
m=50;
Ax = 1/m;
x=[a:Ax:b];
f=sin(x*pi);
g=0;
h=0;
% Number of steps for the first computation
npast = 15;
At = tfin/npast;
t=[0:At:npast*At];

% Reference solution (it is considered as exact)
U   = parabolic_im(a,b,m,At/(2^6),npast*(2^6),f,g,h);
sol = U(:,npast*(2^6)+1);

npast0=npast;
At0=At;
% Implicit method
% Computation with different values of At
Ats = [];
errores = [];
for i=0:4
    U = parabolic_im(a,b,m,At,npast,f,g,h);
    aprox = U(:,npast+1);
    error = norm(sol-aprox);
    errores = [errores,error];
    Ats = [Ats,At];
    At = At/2;
    npast = npast*2;
end
error_im = errores;

At =At0;
npast=npast0;
U   = parabolic_cn(a,b,m,At/(2^6),npast*(2^6),f,g,h);
sol = U(:,npast*(2^6)+1);
% Crank-Nicolson method
% Computation with different values of At
  errores = [];
  for i=0:4
     U = parabolic_cn(a,b,m,At,npast,f,g,h);
     aprox = U(:,npast+1);
     error = norm(sol-aprox);
     errores = [errores,error];
     At = At/2;
     npast = npast*2;
  end
  error_cn = errores;

%Explicit method: We have to change m and/or npast to make it non-oscillating!
m = 15;
Ax = 1/m;
x=[a:Ax:b];
f=sin(x*pi);
g=0;
h=0;
At =At0;
npast=npast0;
U   = parabolic_ex(a,b,m,At/(2^6),npast*(2^6),f,g,h);
sol = U(:,npast*(2^6)+1);
% Computation with different values of At
  errores = [];
  for i=0:4
     U = parabolic_ex(a,b,m,At,npast,f,g,h);
     aprox = U(:,npast+1);
     error = norm(sol-aprox);
     errores = [errores,error];
     At = At/2;
     npast = npast*2;
  end
  error_ex = errores;

% Graphical representation
figure(2),clf
plot(log(Ats),log(error_im),'-o',log(Ats),log(error_cn),'-x',log(Ats),log(error_ex),'-*')
% plot(log(Ats),log(error_im),'-o')
xlabel('log(delta t)')
ylabel('log(Error)')
title('Convergence with constant delta x and delta t->0')
legend('Implicit','Crank-Nicolson','Explicit','Location','Northwest')
%legend('Implicit')

% Least squares approximation
p=polyfit(log(Ats),log(error_im),1);
x=log(Ats(3))+0.125;
y=log(error_im(3))-0.125;
text(x,y,num2str(p(1),2))

  % Least squares approximation
  p=polyfit(log(Ats),log(error_cn),1);
  x=log(Ats(3))+0.125;
  y=log(error_cn(3))-0.125;
  text(x,y,num2str(p(1),2))
  
    % Least squares approximation
  p=polyfit(log(Ats),log(error_ex),1);
  x=log(Ats(3))+0.125;
  y=log(error_ex(3))-0.125;
  text(x,y,num2str(p(1),2))
