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

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

%
% Order in Ax
%
% Number of time steps
npast = 5000;
At = tfin/npast;
t=[0:At:npast*At];

% Number of subintervals for the first computation
m=4;
Ax = 1/m;

% Reference solution (it is considered as exact)
x=[a:Ax/(2^4):b];
f=sin(x*pi);
g=0;
h=0;
U   = parabolic_im(a,b,m*(2^4),At,npast,f,g,h);
sol = U(1:2^4:m*(2^4)+1,npast+1);

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

m = m0;
% Implicit method
% Computation with different values of Ax
Axs = [];
errores = []; 
for i=0:3
    Ax = 1/m;
    x=[a:Ax:b];
    f=sin(x*pi);
    g=0;
    h=0;
    U = parabolic_im(a,b,m,At,npast,f,g,h);
    aprox = U(1:2^i:m+1,npast+1);
    error = norm(sol-aprox);
    errores = [errores,error];
    Axs = [Axs,Ax];
    m=m*2;
end
error_im = errores;


%Explicit meethod
m = m0;
Axs = [];
errores = []; 
for i=0:3
    Ax = 1/m;
    x=[a:Ax:b];
    f=sin(x*pi);
    g=0;
    h=0;
    U = parabolic_ex(a,b,m,At,npast,f,g,h);
    aprox = U(1:2^i:m+1,npast+1);
    error = norm(sol-aprox);
    errores = [errores,error];
    Axs = [Axs,Ax];
    m=m*2;
end
error_ex = errores;

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

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

p=polyfit(log(Axs),log(error_cn),1);
x=log(Axs(3))+0.125;
y=log(error_cn(3))-0.125;
text(x,y,num2str(p(1),2))

p=polyfit(log(Axs),log(error_ex),1);
x=log(Axs(3))+0.125;
y=log(error_ex(3))-0.125;
text(x,y,num2str(p(1),2))

