%
% This program solves Burgers' equation in 1D

clear; close all; clc

disp(' ')
disp('This program solves Burgers equation u_t + u u_x = 0')
disp('on an interval [a,b]')

% Domain
a = 0; 
b = 1; 

% Mesh
m = 50;  
h = (b-a)/m;
X = (a:h:b)'; 
T = [1:m; 2:m+1]'; 

% Initial condition
p = 0.64;
q = 0.84;
u0 =  []; 

for i = 1:length(X)
   if X(i) < p
       u0 = [u0, 1];
   elseif X(i) >= p && X(i) <= q
       u0 = [u0, 1- (X(i) - p)/(q-p)];
   else
       u0 = [u0 0];
   end
end

u0 = u0';

umax = max(u0) + 0.1;
umin = min(u0) - 0.1;
figure('Name','Initial condition','NumberTitle','off'); clf;
plot(X,u0,[a,b],[0,0],'--','LineWidth',2)
title('Initial condition','FontSize',12)
axis([a,b,umin,umax])
set(gca,'FontSize',12)


% Boundary conditions
uxa = u0(1);
uxb = u0(end);


% Time discretization and numerical diffusion
Tf = 1; 
At = 0.5*h; nTimeSteps = Tf / At; E = 1e-2; 

% Solution 
disp('Explicit method...')
U_ex = burgers_ex(X,T,At,nTimeSteps,u0,uxa,uxb,E);
disp('Implicit method (Picard)...')
U_im = burgers_im(X,T,At,nTimeSteps,u0,uxa,uxb,E);
disp('Implicit method (Newton-Raphson)...')
U_imNR = burgers_imNR(X,T,At,nTimeSteps,u0,uxa,uxb,E);

% Postprocess
npasplot = round(nTimeSteps/20); 
ind = [1:npasplot:nTimeSteps+1,nTimeSteps+1]; 
%
figure('Name','Solution with explicit method','NumberTitle','off'); clf;
plot(X, U_ex(:,ind), [a,b],[0,0],'--', 'LineWidth', 2); 
axis([0,4,min(U_ex(:,1))-0.1,max(U_ex(:,1))+0.1])
%
figure('Name','Solution with implicit method (Picard)','NumberTitle','off'); clf;
plot(X, U_im(:,ind), [a,b],[0,0],'--', 'LineWidth', 2); 
axis([0,4,min(U_im(:,1))-0.1,max(U_im(:,1))+0.1])
%
figure('Name','Solution with implicit method (N-R)','NumberTitle','off'); clf;
plot(X, U_imNR(:,ind), [a,b],[0,0],'--', 'LineWidth', 2); 
axis([0,4,min(U_imNR(:,1))-0.1,max(U_imNR(:,1))+0.1])

% U = U_im; 
% npasplot = round(nTimeSteps/20); 
% figure;
% for i= [1 : npasplot : nTimeSteps,nTimeSteps+1]
%     plot(X, U(:,i) ,[a,b],[0,0],'--', 'LineWidth', 2)
%     title(sprintf('t = %g',(i-1)*At),'FontSize',12)
%     axis([a, b, umin, umax])
%     set(gca,'FontSize',12)
%     pause(0.1)
% end


