% This program solves a convection-diffusion problem 
% in a square domain [0,1]x[0,1] 

clear; close all; clc


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

% PDE coefficients
disp('Convection velocity is');
velo = [cos(pi/6),sin(pi/6)];
disp(velo);
a = norm(velo); 
nu = cinput('Diffusion coefficient', 0.001);
disp(' ')
sigma = cinput('Reaction coefficient', 1);
disp(' ')
s = cinput('Source term', 0);
disp(' ')

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

example.dom = dom; 
example.velo = velo; 
example.a = a; 
example.nu = nu; 
example.sigma = sigma;
example.s=s;

% Element type
elem = 0; p = 1; 
referenceElement = SetReferenceElement(elem,p); 

%nx = input('Number of elements in each direction (multiple of 5)= ');
%ny = nx;
h=0.002;
nx=2/h;
ny=3/h;
% nx=10;
% ny=10;


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


Pe = a*h/(2*nu);
disp(' ')
disp(strcat('Peclet number: ',num2str(Pe)))

disp(' ')
disp ('The following methods can be used:');
disp ('     [0] Galerkin');
disp ('     [1] Artificial diffusion');
disp ('     [2] SUPG');
disp ('     [3] GLS');
method = input ('Choose a method for solving the problem: ');
example.method = method; 

% SYSTEM RESULTING OF DISCRETIZING THE WEAK FORM
[K,f] = FEM_system(X,T,referenceElement,example);


% BOUNDARY CONDITIONS 
% Boundary conditions are imposed using Lagrange multipliers
nodes_y0 = [1:nx]';                           % Nodes on the boundary y=0
nodes_x1 = [nx+1:nx+1:(ny+1)*(nx+1)]' ;     % Nodes on the boundary x=1
nodes_y1 = [ny*(nx+1)+nx:-1:ny*(nx+1)+2]' ;     % Nodes on the boundary y=1
nodes_x0 = [ny*(nx+1)+1:-(nx+1):nx+2]';     % Nodes on the boundary x=0


gamma1=nodes_x0( X(nodes_x0,2) < 1.5);
gamma2=nodes_x0( X(nodes_x0,2) >= 1.5);
gamma3=nodes_y1;
gamma4=nodes_x1;
gamma5=nodes_y0;

% nodes on which solution is u=1
nodesDir1 = gamma2; 
% nodes on which solution is u=0
nodesDir0 = gamma4;
% Boundary condition matrix
C = [nodesDir1, 2*ones(length(nodesDir1),1);
     nodesDir0, ones(length(nodesDir0),1)];
nDir = size(C,1);
neq  = size(f,1);
A = zeros(nDir,neq);
A(:,C(:,1)) = eye(nDir);
b = C(:,2);


% SOLUTION OF THE LINEAR SYSTEM
% Entire matrix
Ktot = [K A';A zeros(nDir,nDir)];
ftot = [f;b];

sol = Ktot\ftot;
Temp = sol(1:neq);
multip = sol(neq+1:end);


% POSTPROCESS
figure(2), clf
% xx  = reshape(X(:,1), ny+1, nx+1)'; 
% yy  = reshape(X(:,2), ny+1, nx+1)'; 
%  sol = reshape(Temp, ny+1, nx+1)';
xx  = reshape(X(:,1), nx+1, ny+1)'; 
yy  = reshape(X(:,2), nx+1, ny+1)'; 
sol = reshape(Temp, nx+1, ny+1)';

surface(xx,yy,sol,'FaceColor','interp');
set(gca, 'xTick',0:0.25:2, 'yTick',0:0.25:3, 'FontSize',12)
xlabel('x','FontSize',14); 
ylabel('y','FontSize',14); 
zlabel('u','FontSize',14);
grid on; view(3)

