%% run_Parab_IE_CG_TriP1.m 
% Parabolic eqn: Implicit Euler + Continuous Galerkin P1 on a triangular mesh  
% James Liu, ColoState; 2012/07--2017/02 

% clc;  
clear all;  close all;
format compact;  format long e;

%% Setting up the problem 
xa = 0;  xb = 1;  yc = 0;  yd = 1;
BndryDescMat = [xa,yc,xb,yc, 0,-1;...
                xb,yc,xb,yd, 1, 0;... 
                xb,yd,xa,yd, 0, 1;...
                xa,yd,xa,yc,-1, 0];
% "0" for convenience 
EqnBIC = EqnBIC_Parab_Ex11eatsinsin;
BndryCondType = [0;1;1;1;1];

%% Discretization: Mesh generation and preparation 
% disp('Generating & preparing a uniform triangular mesh ...');
n = 16 
nx = n;  ny = n;
TriMesh = RectDom_TriMesh_GenUnfm(xa,xb,nx,yc,yd,ny,2);
TriMesh = TriMesh_Enrich1(TriMesh);
TriMesh = TriMesh_Enrich2(TriMesh,BndryDescMat);
TriMesh = TriMesh_Enrich3(TriMesh,BndryDescMat);

%% Setting up Gaussian quadratures 
GAUSSQUAD = SetGaussQuad(5,25,13);

%% Sorting out boundary edges: Dirichlet, Neumann 
DirichletEdge = find(BndryCondType(TriMesh.BndryEdge+1)==1);
NeumannEdge   = find(BndryCondType(TriMesh.BndryEdge+1)==2);

%% Timing 
T = EqnBIC.T;  
NT = n;  MT = NT;  Deltat = T/NT;  tm = (0:NT)*Deltat;
tyme.T = T;  tyme.NT = NT;  tyme.MT = MT; 
tyme.Deltat = Deltat;  tyme.tm = tm;

%% Assembling and solving 
disp('Solving parabolic BIVP: IE + CG(TriP1)...');

sln = Parab_IE_CG_TriP1_AsmSlv(EqnBIC,...
  TriMesh,tyme,DirichletEdge,NeumannEdge,GAUSSQUAD);

%% Retrieving 
NumerCntrnT = sln(1:TriMesh.NumNds,MT+1);

%% Converting 
NumerCntrnT_P0Em = TriMesh_ConvCP1toP0(TriMesh,NumerCntrnT);

%% 
LMCR = Parab_IE_CG_TriP1_LMCR(EqnBIC,TriMesh,tyme,sln,GAUSSQUAD);

% %% Projecting the exact concentration at final time (assuming known) 
% ProjCntrnT = WG_TriP0P0RT0_ProjScaFxn1(...
%   TriMesh,GAUSSQUAD,EqnBIC.fxnc,T*(MT/NT));

%% Presenting numerical and graphical results 
[min(NumerCntrnT), max(NumerCntrnT)]
% show_TriMesh_ScaEm_ClrImg(TriMesh, ProjCntrnT.em, ...
%   12, 'Projected concentration');
show_TriMesh_ScaNd_trisurf(TriMesh, NumerCntrnT, ...
  21, 'Numerical concentration');
show_TriMesh_ScaEm_ClrImg(TriMesh, NumerCntrnT_P0Em, ...
  22, 'Numerical concentration');
show_TriMesh_ScaEm_ClrImg(TriMesh, LMCR(:,NT), ...
  23, 'Elementwise LMCR at final time');

return;