%% Constrained LMS Algorithm - MC Simulation and Theoretical Model (Program conslms.m)

% Related paper:
% CHEN, J., RICHARD, C., et HONEINE. 
% A novel kernel-based nonlinear unmixing scheme of hyperspectral images.
% ASILOMAR'11, 6-9 November 2011, Pacific Grove.
%
% Related reference:
% CHEN, J., RICHARD, C., BERMUDEZ, J., et HONEINE, P. 
% Variants of non-negative least-mean-square algorithm and analysis. 
% IEEE Transactions on Signal Processing, March 2012.

% This program runs the constrained LMS algorithm in Matlab
% Input signal: AR(1) process with a white Gaussian driving noise
% Input vectors: Tap delay line -> X(n) and X(n-1) correlated

% Last change: February 20, 2012 
% If you have any questions, you may contact
% chen@unice.fr  or  cedric.richard@unice.fr

%% Initialization


clear all
t1 =cputime;
iter=5000;        % number of iterations
runs=10;           % number of Monte Carlo realizations
mu=0.001;          % step-size1


alpha=0.5;           % correlation parameter for the AR(1) input model
q=3/7;               % exponential factor


H=[0.9 0.85 0.8 0.75 0.7 0.65 0.6 0.55 0.5 0.45 0.4 0.35 0.3 0.25 0.2 0.15 0.1 0.05 0 -0.05 -0.1 -0.15 -0.2 -0.25 -0.3 -0.35 -0.4 -0.45 -0.5 -0.55 -0.6]';



% ----------------------------------------------------

%H=H/sqrt(H'*H);       % normalizes H so that |H|=1
[nr,nc]=size(H);      % determines the size of H
N=nr;                 % filter length = length of H
varx=1;               % variance of the input signal
varz=10^(-2);         % variance of the additive measurement noise
mse=zeros(iter,1);    % initializations
emse=zeros(iter,1);             % Excess mean-square error vector
Jex=zeros(iter,1);              % Theoretical EMSE vector
MV=zeros(N,iter);               % Mean weight error vector matrix
MW=zeros(N,iter);               % Mean weight vector matrix
MVt=zeros(N,iter);              % Theoretical mean weight error matrix
VV=zeros(N,N*iter,1);             % Weight error vector correlation matrix
EQ=zeros(runs,1);            % Matrix of squared errors




W0=1*ones(N,1);                 % Initialization of the weight vector W(0)
%W0=W0/sqrt(W0'*W0);
W0 = 10*W0/sum(W0);
%% Correlation coefficient for AR(1) input




%% Loop for Monte Carlo realizations

for r=1:runs,          % loop for realizations
   % r
   W=W0;
   X0=sqrt((1-alpha^2)*varx)*randn(iter+N-1,1); %generates input driving noise
   X1=zeros(iter,1);X1(1,1)=X0(1,1);           %initalizes vector of input samples
   
   for k=2:iter+N-1                  %AR(1) model
   X1(k,1)=alpha*X1(k-1,1)+X0(k,1);
   end
   
   
   %% Loop for iterations within each MC realization

   for n=1:iter,
      X=X1(n:n+N-1,1);                  %generates input vector
      X=flipud(X);
      z=sqrt(varz)*randn(1,1);           %generates additive noise sample
      d=X'*H + z;                       % evaluates desired signal
      y=X'*W;                           % evaluates adaptive filter output
      e=d-y;                            % evaluates error signal
      mse(n,1)=mse(n,1)+e^2;            % accumulates e^2(n)
      emse(n,1)=emse(n,1) + (e-z)^2;    % accumulates (e(n)-z(n))^2
      V=W-H;                            % evaluates weight error vector
%       
%       if n==1000,
%           V21K(runs,1)=V(2,1);
%           V51K(runs,1)=V(5,1);
%       end
%       
%       if n==8000,
%           V28K(runs,1)=V(2,1);
%           V58K(runs,1)=V(5,1);
%       end      
%       
       MW(:,n)=MW(:,n)+W;                % accumulates weight vector
       MV(:,n)=MV(:,n)+V;                % accumulates weight error vector
       VV(:,(n-1)*N+1:n*N)=VV(:,(n-1)*N+1:n*N)+V*V';         % accumulates V(n)*V'(n)
      
%       if  mu > 1/(2*max(abs(e*X))),     % tests if step size satisfies the coefficient constraint 
%           mu
%           mu = 0.9/(2*max(abs(e*X)))    % reduces the step size if necessary
%           n
%       end
       %Gradient = -(X*X'*W-X*d);
       %A = 1*Gradient-Gradient'*W;
 %      W=W+mu*W.*A;
%       W=W+mu*e*diag(W)*X-mu*e*W*y;
       %Wf = W.^(q);
       Wf =sign(W).*(abs(W).^(q));        % the sign operation is required to obtain 
                                          % just the real result (otherwise
                                          % the result might be complex)
       W=W+mu*e*diag(Wf)*X;               % updates adaptive weight vector

   end
end

%% Averaging

MV=MV/runs;                             % evaluates mean weight error vector
MW=MW/runs;                             % evaluates mean weight vector
mse=mse/runs;                           % evaluates MSE
emse=emse/runs;                         % evaluates EMSE
msedb=10*log10(mse);                    % MSE in dB
emsedb=10*log10(emse);                  % EMSE in dB
VV=VV/runs;                             % evaluates E[V(n)*V'(n)]

%% Input autocorrelation matrix R evaluated from theory

%Theoretical input autocorrelation matrix 
R=zeros(N,N);
for l=1:N
R(l,1)=varx*(alpha^(l-1));
end
R=toeplitz(R(:,1));

%% Theoretical Model

% Initialization of mean weight error vector and K(n)

K=zeros(N,N,iter);
MVt=zeros(N,iter);
emset=zeros(iter,1);

MVt(:,1)=W0-H;
K=(W0-H)*(W0-H)';

% Evaluation of the theoretical model

r=zeros(N,1);
ro=zeros(N,1);
s=zeros(N,1);

ro=MVt(:,1) + H;
s= q*((ro.^(q-1)));
r=ro.^q - q*(s.*MVt(:,1));

% for k=1:iter-1
%     ro=MVt(:,k) + H;
%     s= q*((ro.^(q-1)));
%     %r=ro.^q - q*(s.*MVt(:,k));
%     r=ro.^q;
%     Dr=diag(r);
%     Ds=diag(s);
%     %MVt(:,k+1)=MVt(:,k)-mu*Dr*R*MVt(:,k)-mu*Ds*diag(R*MVt(:,k)*MVt(:,k)');
%     MVt(:,k+1)=MVt(:,k)-mu*Dr*R*MVt(:,k);
% end



Dalpha = diag(H);
DRK = diag(R*K);
A= eye(N)-mu*Dalpha*R;
emset(1,1)=trace(R*K);
unc = ones(N,1);
EMv = MVt(:,1);

for k=2:iter

  EMv  = MVt(:,k-1);

 
%-- 1 st order Taylor approximation

 f0 = sign(EMv +H).*abs(EMv +H).^q;
 f1 = q*sign(EMv +H).*abs(EMv +H).^(q-1);

 
 idx=(abs(EMv +H)<0.001);
 f1(idx)=0;


% thres = 1;
 %f1(abs(f1)>thres)= sign(f1(abs(f1)>thres))*thres;
% f1=0;
 
 c1 = f0-f1.*EMv; 
 c2 = f1;
 

 
 MVt(:,k) = MVt(:,k-1) - mu*diag(f0)*R*MVt(:,k-1);%-mu*diag(f0)*diag(R*MVt(:,k-1)*MVt(:,k-1)');
 

%----

Dc1 = diag(c1);
Dc2 = diag(c2);
EDv = diag(MVt(:,k-1));
En= 2*R*K*R + trace(R*K)*R;

P1 = K*R*Dc1;
P2 = K*diag(R*MVt(:,k-1))*Dc2;
P3 = varz*Dc1*R*Dc1;
P4 = varz*Dc1*R*EDv*Dc2;
P5 = varz*Dc2*(R.*K)*Dc2;
P6 = Dc1*En*Dc1;
P7 = Dc1*En*EDv*Dc2;
P8 = Dc2*(En.*K)*Dc2;

K_old=K;
K = K - mu*(P1+P1'+P2+P2')+ mu^2*(P3+P4+P4'+P5+1*P6+P7+P7'+1*P8);

if trace(R*K)>emset(k-1,1)
 %   K = K_old;
end


emset(k,1)= trace(R*K);


end

emsetdb=10*log10(emset);
mset = emset+varz;
msetdb=10*log10(mset);



msedb_f = 10*log10(filter(ones(10,1)/10,1,mse));
emsedb_f = 10*log10(filter(ones(10,1)/10,1,emse));


%% Plotting the results

%----------- Plot section --------------


t=[1:iter]';




figure, hold on
for c=1:1:N
plot(t',MV(c,:)+H(c,1),'b',t', MVt(c,:)+H(c,1),'r');grid on
%plot(t',MW(c,:),'b',t', MVt(c,:)+H(c,1),'r');grid on
end

% 
% figure
% plot(t',MW(3,:),'b',t, MVt(3,:)+H(3,1),'r');grid
% xlabel('E[V(n)]: Blue: Simulations. Red: Theory');
% ylabel('E[V(n)]');
% title('Mean Weight Behavior');

figure
%plot(t,emsedb_f,'b',t,emsetdb,'r');grid
plot(t,emsedb,'b'), hold on, plot(t,emsetdb,'r','linewidth',2);
grid on;
xlabel('iteration','fontsize',14,'Fontname','Times New Roman');
ylabel('{\it{J}}_{emse}','rotation', pi/2,'fontsize',14,'Fontname','Times New Roman');

% figure
% plot(t,msedb_f,'b',t,msetdb,'r');grid
% xlabel('Iterations');
% ylabel('MSE');
% title('Mean Square Error');
% 
% disp('theroetical emse'), disp(emset(end))
% disp('simulated emse'), disp(mean(emse(end-100:end)))
% disp('theroetical mse'), disp(mset(end))
% disp('simulated mse'), disp(mean(mse(end-100:end)))
% tmp=num2str(mu); tmp(2)=[];
% flname=['sys2_crr_mu',tmp,'.mat'];
% save(flname)

%t2 =cputime-t1
