%pfc_split_range
clear 
close 
tf=2500;w=1:1:tf;tech=1;
taum=50;am=exp(-tech/taum);bm=1-am; 
tau1=25;a1=exp(-tech/tau1);b1=1-a1;
tau2=10;a2=exp(-tech/tau2);b2=1-a2;
k1=1;k2=-.5;%gains process
%pfc
h=40;trbf=160;lh=1-exp(-tech*3*h/trbf);%----------------trbf
%bfh=1-af^h;bmh=1-am^h;
A1=-k1*taum/(tau1-taum);B1=k1-A1;
A2=-k2*taum/(tau2-taum);B2=k2-A2;
bmh=1-am^h;b1h=1-a1^h;b2h=1-a2^h;
%variables
u=zeros(1,tf);e1=u;e2=u;z=u;
sp1=u;sp2=u;sp=u;sm11=u;sm12=u;sm21=u;sm22=u;cons=u;
for ii=2:1:tf
   if ii<300;pert=0;else;pert=120;end
   if ii>700;pert=-50;end
   %process
   if ii>1800;pert= 85;end
   sp2(ii)=sp2(ii-1)*a2+b2*k2*e2(ii-1);
   sp1(ii)=sp1(ii-1)*a1+b1*k1*e1(ii-1);
   sp(ii)=sp(ii-1)*am+bm*(sp1(ii)*1+sp2(ii)*1+pert*1);
   z(ii)=sp(ii)-sp(ii-1);
   cons(ii)=100;
   if ii>1300;cons(ii)=60;end
   %---controller 1
   sm11(ii)=sm11(ii-1)*am+bm*A1*(e1(ii-1));
   sm12(ii)=sm12(ii-1)*a1+b1*B1*(e1(ii-1));
   d=( cons(ii)-sp(ii))*lh +sm11(ii)*bmh+sm12(ii)*b1h+(sm21(ii)*bmh+sm22(ii)*b2h);
   %attention here : feed forward from controller 2!
   e1(ii)=d/(A1*bmh+B1*b1h);
   %--controller 2
   sm21(ii)=sm21(ii-1)*am+bm*A2*(e2(ii-1));
   sm22(ii)=sm22(ii-1)*a2+b2*B2*(e2(ii-1));
   d=( cons(ii)-sp(ii))*lh +sm21(ii)*bmh+sm22(ii)*b2h+(sm11(ii)*bmh+sm12(ii)*b1h);
    %attention here : feed forward from controller 1!
   e2(ii)=d/(A2*bmh+B2*b2h);
   %supervisor decision
   if e1(ii)>=0 & e2(ii)<0;e2(ii)=0;end
   if e2(ii)>=0 & e1(ii)<0;e1(ii)=0;end
   % crucial !____________________ ___________________________________if not clasical huge problem !!
   if e1(ii)>0 & e2(ii)>0 & e1(ii-1)>=0;e2(ii)=0;end
   if e1(ii)>0 & e2(ii)>0 & e2(ii-1)>=0;e1(ii)=0;end
end
plot( w,sp,'r',w,e2, 'k',w,e1,'b',w,cons,'r');
grid
zoom
title ('SPLIT RANGE WITH ALTERNATE CONTROL ,cv r,cons r / e1 b / e2 k ') 
text(580,110,'CV')
text(1100,157,'MV')
text(60,50,'CV')
text(60,110,'MV1')
text(1100,5,'sec')
axis([1 tf 0 200])