%
% 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
% u0 =  [zeros(size(X(X<1))); 0.5*ones(size(X(X>=1)))]; 
u0=[];
for i=1:size(X)
    if X(i)<0.64
        u0(i)=1;
    elseif X(i)>0.84
        u0(i)=0;
    else
        u0(i)=1-(X(i)-0.64)/(0.84-0.64);
    end
    %u0 = [1;1-(X(0.64<=X & X<=0.84)-0.64)/(0.84-0.64);0]; 
end
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 = 0.3; 
At = 0.005; nTimeSteps = Tf / At; E = 1e-2; 
% At = 0.05; nTimeSteps = Tf / At; E = 1e-2; 
% At = 0.1; nTimeSteps = Tf / At; E = 1e-2; 
% At = 0.005; nTimeSteps = Tf / At; E = 1e-4; 

% 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 t=0.3','NumberTitle','off'); clf;
plot(X, U_ex(:,60), [a,b],[0,0],'--', 'LineWidth', 2); 
figure('Name','Solution with explicit method, t=0.15','NumberTitle','off'); clf;
plot(X, U_ex(:,30), [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


