% This program solves the 2D cavity flow Stokes problem 


clear; close all; clc

addpath('Func_ReferenceElement')

dom = [0,1,0,1]; 

% Element type and interpolation degree
% (0: quadrilaterals, 1: triangles, 11: triangles with bubble function)
elemV = 1; degreeV = 1; degreeP = 1;
% elemV = 1; degreeV = 2; degreeP = 1;
% elemV = 11; degreeV = 1;  degreeP = 1; 

%----------------------------------------------------------------
GLS =1;   %1 =on   %2=off
%----------------------------------------------------------------
if elemV == 11
    elemP = 1; 
else
    elemP = elemV; 
end
 
   



referenceElement = SetReferenceElementStokes(elemV,degreeV,elemP,degreeP); 

nx=20;     % nx = cinput('Number of elements in each direction',20);
ny = nx; 
adapted = 1; 
[X,T,XP,TP] = CreateMeshes(dom,nx,ny,referenceElement,adapted);
nu=1;
h=(1/nx);
tau=(1/12)*(h^2/nu);
figure; PlotMesh(T,X,elemV,'b-');
figure; PlotMesh(TP,XP,elemP,'r-');


% Matrices arising from the discretization
if GLS ==0
 [K,G,f] = StokesSystem(X,T,XP,TP,referenceElement);
elseif GLS ==1
[K,G,f,L,fP] = StokesSystem_stable(X,T,XP,TP,referenceElement,tau);
end 

[ndofP,ndofV] = size(G); 

[dofDir,valDir,dofUnk,confined] = BC_red(X,dom,ndofV); 
nunkV = length(dofUnk); 
if confined
   nunkP = ndofP-1;
   disp(' ')
   disp('Confined flow. Pressure on lower left corner is set to zero');
   G(1,:) = [];
   if GLS ==1
   L(1,:) = [];
   L(:,1) = [];
   fP(1,:) = [];
   end 
else 
    nunkP = ndofP;
end

f = f - K(:,dofDir)*valDir; 
Kred = K(dofUnk,dofUnk); 
Gred = G(:,dofUnk); 
fred = f(dofUnk); 


if GLS==0
  A = [Kred   Gred'; 
      Gred   zeros(nunkP)]; 
  b = [fred; zeros(nunkP,1)];

elseif GLS ==1
  A = [Kred   Gred'; 
       Gred   L]; 
  b = [fred; fP];
end 



sol = A\b; 

velo = zeros(ndofV,1);
velo(dofDir) = valDir; 
velo(dofUnk) = sol(1:nunkV); 
velo = reshape(velo,2,[])'; 
pres = sol(nunkV+1:end); 
if confined
    pres = [0; pres]; 
end

nPt = size(X,1); 
figure; 
quiver(X(1:3:nPt,1),X(1:3:nPt,2),velo(1:3:nPt,1),velo(1:3:nPt,2));
hold on 
plot(dom([1,2,2,1,1]),dom([3,3,4,4,3]),'k')
xlim([0 1]);  ylim([0 1])   %axis equal; axis tight
title('Velocity Field','FontSize',16)
 
PlotStreamlines(X,velo,dom); 

if degreeP == 0
    PlotResults(X,T,pres,referenceElement.elemP,referenceElement.degreeP)
else
    PlotResults(XP,TP,pres,referenceElement.elemP,referenceElement.degreeP)
end
title('Pressure Distribution','FontSize',16)


