% This program solves a convection problem 
% in a square domain [-0.5,0.5]x[-0.5,0.5] 

clear; close all; clc


disp(' ')
disp('This program solves a convection-diffusion-reaction equation in [0,2]x[0,3] ')

dom = [0,2,0,3]; 

% Element type
disp(' ')
elem = 0; 

p = cinput('Element Degress',1); 
referenceElement = SetReferenceElement(elem,p); 





hh = cinput('Spatial mesh size',0.1);

nx=(dom(2)-dom(1))/hh;
ny=(dom(4)-dom(3))/hh;

[X,T] = CreateMesh(dom,nx,ny,referenceElement);
figure; PlotMesh(T,X,'b-');

disp(' ')
disp('The following velocity fields can be considered');
disp('   [1] v(x,y) = (-x,-y)');
disp('   [2] v(x,y) = (1,0)');
disp('   [3] v(x,y) = (1,1)/sqrt(2)'); 
velo = cinput('Choose the convection field to be used on the computation',1); 
Conv = ComputeVelocity(X,velo);

nu = cinput('Diffusion coefficient nu', 0.01);

sigma = cinput('Reaction', 1);



% Method used for solving the problem
disp(' ')
disp ('The problem can be solved using one of the following methods: ');

disp ('    [1] Crank-Nicolson + Galerkin')
disp ('    [2] R22 + Galerkin')
method = cinput('Method = ',1);

figure(1); hold on; 
quiver(X(:,1),X(:,2),Conv(:,1),Conv(:,2))
plot(dom([1,2,2,1,1]), dom([3,3,4,4,3]), 'k')
axis equal


% Time discretization
tEnd = cinput('End time', 2*pi);
nStep = cinput('Numnber of time-steps', 110);
dt = tEnd / nStep; 
Courant = sqrt(Conv(1)^2+Conv(2)^2)*dt/hh; 
disp(['Courant number: ', num2str(Courant)]); 


tic;%tic1
t1=clock;
% Initial condition
u0 = InitialCondition(X); 

xx  = reshape(X(:,1), p*nx+1, p*ny+1)'; 
yy  = reshape(X(:,2), p*nx+1, p*ny+1)'; 
u0_dib = reshape(u0, p*nx+1, p*ny+1)';  
figure(2); clf; 
surface(xx,yy,u0_dib,'FaceColor','interp');
set(gca,'FontSize',16)
grid on
view(3)

figure(3); clf;
[C,h]=contour(xx,yy,u0_dib,[-0.1,-0.01,0.1:0.1:1.0]);
clabel(C,h,'FontSize',12);
axis equal; axis(dom);
set(gca,'FontSize',16,'XTick',0:0.25:2,'YTick',0:0.25:3)


[M,K,C,f] = FEM_matrices(X,T,Conv,referenceElement,nu); 

u=Method(M,C,K,dt,method,sigma,f,X,velo,nStep,u0);



disp(['total time for the code:',num2str(etime(clock,t1))]); 

figure(4);
disp('start movie')

for n=1:size(u,2)
   clf;
uu = reshape(u(:,n), p*nx+1, p*ny+1)';  
surface(xx,yy,uu,'FaceColor','interp');
set(gca,'FontSize',16)
grid on
view(3)
pause(0.1)
end

 


