clc
close all
clear all

% Checks 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;
Uex = parabolic_ex(a,b,m*(2^4),At,npast,f,g,h);
Uim = parabolic_im(a,b,m*(2^4),At,npast,f,g,h);
Ucn = parabolic_cn(a,b,m*(2^4),At,npast,f,g,h);
solex = Uex(1:2^4:m*(2^4)+1,npast+1);
solim = Uim(1:2^4:m*(2^4)+1,npast+1);
solcn = Ucn(1:2^4:m*(2^4)+1,npast+1);

m0 = m;

% Explicit method
% Computation with different values of Ax
Axsex = [];
erroresex = []; 
for i=0:3
    Ax = 1/m;
    x=a:Ax:b;
    f=sin(x*pi);
    g=0;
    h=0;
    Uex = parabolic_ex(a,b,m,At,npast,f,g,h);
    aproxex = Uex(1:2^i:m+1,npast+1);
    errorex = norm(solex-aproxex);
    erroresex = [erroresex,errorex];
    Axsex = [Axsex,Ax];
    m=m*2;
end
error_ex = erroresex;

m = m0;
% Implicit method
% Computation with different values of Ax
Axsim = [];
erroresim = []; 
for i=0:3
    Ax = 1/m;
    x=a:Ax:b;
    f=sin(x*pi);
    g=0;
    h=0;
    Uim = parabolic_im(a,b,m,At,npast,f,g,h);
    aproxim = Uim(1:2^i:m+1,npast+1);
    errorim = norm(solim-aproxim);
    erroresim = [erroresim,errorim];
    Axsim = [Axsim,Ax];
    m=m*2;
end
error_im = erroresim;

m = m0;
% Implicit method
% Computation with different values of Ax
Axscn = [];
errorescn = []; 
for i=0:3
    Ax = 1/m;
    x=a:Ax:b;
    f=sin(x*pi);
    g=0;
    h=0;
    Ucn = parabolic_cn(a,b,m,At,npast,f,g,h);
    aproxcn = Ucn(1:2^i:m+1,npast+1);
    errorcn = norm(solcn-aproxcn);
    errorescn = [errorescn,errorcn];
    Axscn = [Axscn,Ax];
    m=m*2;
end
error_cn = errorescn;

% Graphical representation
figure
hold on
grid on
plot(log(Axsex),log(error_ex),'-o','DisplayName','Explicit')
plot(log(Axsim),log(error_im),'-o','DisplayName','Implicit')
plot(log(Axscn),log(error_cn),'-o','DisplayName','Crank-Nicholson')
xlabel('log(\Deltax)')
ylabel('log(Error)')
title('Convergence with constant \Deltat and \Deltax->0')
legend('toggle')

% Least squares approximation
pex=polyfit(log(Axsex),log(error_ex),1);
pim=polyfit(log(Axsim),log(error_im),1);
pcn=polyfit(log(Axscn),log(error_cn),1);
xex=log(Axsex(3))+0.125;
xim=log(Axsim(3))+0.125;
xcn=log(Axscn(3))+0.125;
yex=log(error_ex(3))-0.125;
yim=log(error_im(3))-0.325;
ycn=log(error_cn(3))-0.525;
text(xex,yex,num2str(pex(1),2))
text(xim,yim,num2str(pim(1),2))
text(xcn,ycn,num2str(pcn(1),2))

