% ident_repimpuls
clear all
close all
tf=900; w=1:1:tf;
tech=1;
tau1 = 1;
a1=exp(-tech/tau1);b1=1-a1;
tau2 = 2;
a2=exp(-tech/tau2);b2=1-a2;
tau3 = 2.5;
a3=exp(-tech/tau3);b3=1-a3;
u=zeros(1,tf); e=u;sp=u;
sp1=u;sm=u;sp3=sp;sp2=sp1;
lambda=0.9;
%this identification method does not decrease a criterion based
% on a state distance  like least square but!
%it is a lyapunov function L= sum ( am -ap)^2 where am is a parameter
%of the convolution
%so you do not know ap process  but you know that L goes to zero
%extensively used in steam drum level problems where the order of the model has
%no sense !
% great idea

N=250;
for j=1:1:N; am(j)=0;
   if j==1;L(1)=lambda;else;L(j)=L(j-1)*0.95;end
end
Am=[am(1:1:N)];LA=[L(1:1:N)];
for ii=N+10:1:tf
   e(ii)=e(ii-1)*.7+.15*sign(sin(2*pi*ii/(400-ii*0.1)));

   if ii<110; e(ii)=0;end
   sp1(ii)=sp1(ii-1)*a1+b1*e(ii-1);
   sp2(ii)=sp2(ii-1)*a2+b2*sp1(ii);
   sp3(ii)=sp3(ii-1)*a3+b3*sp2(ii);
   %ident
   for j=1:1:N; eq(j)=e(ii-j);end% astuce .§
   EE= [eq(1:1:N)];
   %%------
   %E=EE.*LA;
   E=EE;
   sm(ii)=Am*EE';
   eps=sm(ii)-sp3(ii);
   d=1/(.01+EE*EE');
   Am=Am-lambda*eps*E*d;

   %DS(ii)=(Am-Ap)*(Am-Ap)';
end
figure(1)
plot( w, e,'b',w,sp3,'r',w,sm,'k');%,w,c1,'m')
grid
zoom
x=1:1:N;
figure(2)
plot(x,Am,'r')
grid
zoom
break
sm=u;e=u;
for ii=N+10:1:250
     % e(ii)=e(ii-1)*.85+.15*sign(sin(2*pi*ii/(900-ii*0.2)));
   e(ii)= 0;
   if ii>110; e(ii)=100;end
   sp1(ii)=sp1(ii-1)*a1+b1*e(ii-1);
   sp2(ii)=sp2(ii-1)*a2+b2*sp1(ii);
   sp3(ii)=sp3(ii-1)*a3+b3*sp2(ii);
   for j=1:1:N; eq(j)=e(ii-j);end% astuce .§
   EE= [eq(1:1:N)];
   sm(ii)=Am*EE';
   end
figure(1)
plot( w, e,'b',w,sp3,'r',w,sm,'k');%,w,c1,'m')
grid
zoom
figure(2)
plot( w, e,'b',w,sp3,'r',w,sm,'k');%,w,sm,'k');%,w,c1,'m')
grid
zoom
break
x=1:1:N;
figure
plot(x,Am,'r')
grid
zoom

%break
%u=zeros(1,N);sp=u;sp1=u;smm=u;ap=u;
%EE=ones(1,N);
%for ii=70:1:N;
% 
%    sp1(ii)=sp1(ii-1)*a1+b1*1;
%    sp(ii)=sp(ii-1)*a2+b2*sp1(ii-1);
%    ap(ii)=sp(ii)-sp(ii-1);
%    smm(ii)=Am*EE;
%end%

% ww=1:1:N;
%figure(2)
%%lot(ww, ap,'r',ww,smm,'k')
%g%rid
%zoom

  
   