% 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 equation on [0,1]x[0,1]')
disp(' ')
disp('No source term is considered');

% PDE coefficients
a=cinput('Norm of Convective term',1);
disp('Convection velocity is');
velo = [a*cos(pi/6),a*sin(pi/6)];
disp(velo); 
nu = cinput('Diffusion coefficient', 0.01);

sigma=cinput('Reaction coefficient',1);
neumann=cinput('Neumann boundary value',1);
disp('')

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

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

% Element type
elem = 0; p = 1; 
referenceElement = SetReferenceElement(elem,p); 
disp('')
h = cinput('Spatial mesh size',0.2);

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




 
[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] GLS');
disp ('     [2] SUPG');
method = cinput ('Choose a method for solving the problem: ',1);
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+1]';                           % 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)+1]' ;     % Nodes on the boundary y=1
nodes_x0 = [(ny)*(nx+1)+1:-(nx+1):1]';     % Nodes on the boundary x=0





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

%apply neumann boundary condtion
%fn=neumannBC(X,nodes_x1,neumann);

load gamma4.mat
len=length(r_gamma4);

for i=1:len
    
    
  f(nodes_x1(i))= f(nodes_x1(i))+r_gamma4(i);
    
end

%f=f+fn;

% 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), 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.5:3, 'yTick',0:0.5:3, 'FontSize',12)
xlabel('x','FontSize',14); 
ylabel('y','FontSize',14); 
zlabel('u','FontSize',14);

grid on; view(3)

