% pfc_convolution_model
%

%
clear all
close all
tech=1; tf= 500;
w=1:1:tf;
aa=ones(1,tf)*0;a=aa;
e=zeros(1,tf);sm=e;sp=e;spred=e;
v=e;
k=.5;
aq=exp(-tech/2);bq=1-aq;
r=30;
fl=input('fl=1 closed loop / open loop fl= 0 ');
%generating ai
for ii=2+r:1:tf
   v(ii)=v(ii-1)*aq+bq*(1+k*v(ii-r+1));
   if ii <=250;aa(ii)=v(ii)-v(ii-1);end  
end
for jj=1:1:250;a(jj)=aa(jj+r+1);end
%a(1)=0;a(2)=0;a(3)=0;a(4)=0;a(5)=0;
figure(1)
plot(w,v,'k',w,a*10,'r')
grid
zoom
title (' a =  (red)weight of impulse response ')
%validation 
for ii= 250+r:1:tf
   S=0;e(ii)=1;
   for jj= 1:1:250; S= S+a(jj)*e(ii-jj);end
   spred(ii)=S;
   sp(ii)=sp(ii-1)*aq+bq*(e(ii-1)+k*sp(ii-r));
end

%control
tf= 600;w=1:1:tf;
h=100;
sp=zeros(1,tf);e=sp;sm=e;
N=250;
a=a(1:N);
%forced mode
S=0;
a(1)=0;a(2)=0;a(3)=0;a(4)=0;%dealy 
a=a/sum(a);
Sforced=sum(a(1:h));
lh=1-exp(-tech*3*h/1);
% ai are the weigth of the impluse response: very weird shape
% always used by PFC in the level control of drums in steam generation
% where the response is non minimum phase , dealy, high order .etc..!
setpoint=200;
for ii=251:1:tf;
   %process
   if ii>600 pert=0;else;pert=0;end
   S=0;
   for jj=1:1:N;S=S+a(jj)*e(ii-jj);end
   sp(ii)=S+pert;sm(ii)=S;
   %free mode
   S=0;
   for jj=h:1:N;S= S+a(jj)*e(ii+h-jj);end
   Sfree= S;
   %control
   d= (setpoint-sp(ii))*lh-Sfree+sm(ii);;
   if fl==1;e(ii)= d/ Sforced;else;e(ii)=100;end
end
figure(2)
plot(w,sp,'r',w,e,'k')
grid on
zoom

axis([200  tf 0 300])
title(' CONTROL WITH  CONVOLUTION  MODEL ')
if fl==1;text(310 ,75 ,'CLOSED LOOP');end
if fl==0;text(310 ,75 ,'OPEN LOOP');end
text(260 ,250 ,'CV')
text(280 ,125 ,'MV')