% This program solves a convection problem 
% in a square domain [0,2]x[0,3] 

clear; close all; clc   


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

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

% Element type
disp(' ')
elem = 0; p = 2; 
referenceElement = SetReferenceElement(elem,p); 

%nx = cinput('Number of elements in each direction',20);
h=0.2;
nx=2/h;
ny=3/h; 
[X,T] = CreateMesh(dom,nx,ny,referenceElement);
nNodes = length(X);

disp(' ')
disp('The velocity field considered is');
disp('   [1] v(x,y) = (-x,-y)');

Conv = [-X(:,1), -X(:,2)];
nu = cinput('Choose viscosity',1);
sigma = cinput('Choose reaction',1);
s=cinput('Choose source term', 0);

% Time discretization
tEnd = cinput('End time', 3);
nStep = cinput('Numnber of time-steps', 120);
dt = tEnd / nStep; 

Courant = (13^0.5)*dt/h; 
disp(['Courant number: ', num2str(Courant)]); 

[M,Ka,C,K] = FEM_matrices(X,T,Conv,referenceElement); 
%[Mout,Cout] = Boundary_matrices(X,T,Conv,referenceElement,velo);

% Boundary conditions (Lagrange multipliers)
[ADir,bDir,nDir,gamma2] = BoundaryConditions(X,nx,ny,p);
zDir= zeros(nDir);

% Initial Condition
u0 = InitialCondition(X);

% Initializing the variable matrix
u = zeros(nNodes,nStep);
u(:,1) = u0;

% Solvers
method = 1;
[A,B] = discretization(M,K,C,dt,method,nu,sigma);
 
for n=1:nStep
 if method == 1 %CN
    du = [A , ADir' ; ADir  zDir]\[B*u(:,n) ; bDir];

    u(:,n+1) = u(:,n) + du(1:nNodes,1);
 elseif method == 2 %Pade R22
    ADir2 = [ADir 0*ADir;0*ADir ADir];
    bDir2 = [bDir; bDir];
    nDir = length(bDir2);
    zDir = zeros(nDir,nDir);
    
    
    
    du = [A , ADir2' ; ADir2  zDir]\[B*u(:,n) ; bDir2];
    du = du(1:nNodes,1);
    u(:,n+1) = u(:,n) + du(1:nNodes,1);
 end
end

% Ploting the results
ploting(X,u,nStep,nx,ny,p);





























