% Example LEP-WEB17-1e: Maximum Mixedness Model with Asymmetric RTD
%

zspan = [0 2.52]; % Range for the independent variable
y0 = [1 0 0 0.99]; % Initial values for the dependent variables
k1=1;
k2=1;
[z,y]=ode45(@(z,y)ODEfun(z,y,k1,k2),zspan,y0);
tiledlayout(2,2)
set (gcf,'Position',[0,0.1,700,500])
nexttile
plot(z,y(:,1),z,y(:,2),z,y(:,3),'LineWidth',1.5);
xlabel('z (mins)')
ylabel('Concentration')
leg=legend('C_Abar','C_Bbar','C_Cbar','Location','NorthEast');
axis([0 2.52 0 1])
grid on
leg.ItemTokenSize=[10,10];
title('Concentration profile')
p=size(y);
Cao =  1;
for i=1:p(1,1)
   X(i)=1-y(i,1)/Cao;  
   ra(i) =  -k1*y(i,1);
   rb(i) =  k1*y(i,1)-k2*y(i,2);
   rc(i) =  k2*y(i,2);
end
nexttile
plot(z,X(1:p(1,1)),'LineWidth',1.5)
xlabel('z(mins)')
ylabel('Conversion')
leg=legend('Xbar','Location','NorthEast');
leg.ItemTokenSize=[10,10];
title('Conversion profile')
axis([0 2.52 0 1])
grid on
nexttile
plot(z,-ra(1:p(1,1)),z,-rb(1:p(1,1)),z,-rc(1:p(1,1)),'LineWidth',1.5)
xlabel('z(mins)')
ylabel('Rate')
leg=legend('-r_A','-r_B','-r_C','Location','NorthEast');
leg.ItemTokenSize=[10,10];
title('Rate profile')
axis([0 2.52 -3 3])
grid on

%

function dYfuncvecdz = ODEfun(z,Yfuncvec,k1,k2); 
Ca= Yfuncvec(1);
Cb= Yfuncvec(2);
Cc= Yfuncvec(3);
F= Yfuncvec(4);
% Explicit equations
ra= -k1*Ca;
rb= k1*Ca- k2*Cb;
rc= k2*Cb;
Cao = 1;
lam = 2.52 - z;
Cbo = 0;
Cco = 0;
E1=-2.104*(2.52 - z).^4 + 4.167*(2.52 - z).^3 - 1.596*(2.52 - z).^2 + 0.353*(2.52 - z) - 0.004;
E2=-2.104*(2.52 - z).^4 + 17.037*(2.52 - z).^3 - 50.247*(2.52 - z).^2 + 62.964*(2.52 - z) - 27.402;
if lam<=1.26
    E=E1;
else
  E=E2;
end 
EF=E/(1-F);
% Differential equations
dCadz =   -(-ra+(Ca-Cao)*EF) ;
dCbdz =   -(-rb+(Cb-Cbo)*EF) ; 
dCcdz =  -(-rc+(Cc-Cco)*EF) ; 
dFdz =  -E;
dYfuncvecdz=[dCadz;dCbdz;dCcdz;dFdz];
end