% Script for testing the LMS variations
% Thomas Wilding, SPSC, 2018

clear all; close all; clc;

Ns = 1e4; % number of samples

h  = [0.2 0.6 1 0.8]';  % impulse response of unknown system
Nh = length(h);
N  = Nh;                % adaptive filter order is order of unknown system


%% Test Case 1: LMS, NLMS1, noise-free, zero initial vector
close all

x = randn(1,Ns);
d = filter(h,1,x);

c0 = zeros(1,N);     % initialize with zero vector

[~,~,c]       = vlms(x,d,N,0.01,0,0); % standard LMS as reference
[~,~,c_norm1] = vlms(x,d,N,0.01,0,1); 
[~,~,c_leak]  = vlms(x,d,N,0.01,0.03,2); 
c(:,end)-h
c_norm1(:,end)-h
c_leak(:,end)-h

figure(1)
subplot(211)
plot(c_norm1(1,:),'k'), hold on, plot(c(1,:),':k')
plot(c_norm1(2,:),'b'), plot(c(2,:),':b')
plot(c_norm1(3,:),'m'), plot(c(3,:),':m')
plot(c_norm1(4,:),'r'), plot(c(4,:),':r')
legend('c1[n], NLMS1','c1[n], LMS','Location','southeast')
axis([1 Ns 0 1.1])
title('LMS and NLMS1, noise-free, zero initial vector')

subplot(212)
plot(c_leak(1,:),'k'), hold on, plot(c(1,:),':k')
plot(c_leak(2,:),'b'), plot(c(2,:),':b')
plot(c_leak(3,:),'m'), plot(c(3,:),':m')
plot(c_leak(4,:),'r'), plot(c(4,:),':r')
legend('c1[n], leaky LMS','c1[n], LMS','Location','southeast')
axis([1 Ns 0 1.1])
title('LMS and leaky LMS, noise-free, zero initial vector')

%% Test Case 2: LMS, noisy, random initial vector
d  = d+0.1*randn(1,Ns);
c0 = rand(1,N);

[~,~,c] = vlms(x,d,N,0.01,0,0,c0);
c(:,end)-h

figure(2)
plot(c(1,:),'k')
hold on
plot(c(2,:),'b')
plot(c(3,:),'m')
plot(c(4,:),'r')
axis([1 Ns 0 1.1])
title('LMS, noisy, random initial vector')

%% Test Case 3: NLMS2, noisy, random initial vector
[y,e,c]=vlms(x,d,N,0.01,0.01,1,c0);
c(:,end)-h

figure(3)
plot(c(1,:),'k')
hold on
plot(c(2,:),'b')
plot(c(3,:),'m')
plot(c(4,:),'r')
axis([1 Ns 0 1.1])
title('NLMS2, noisy, random initial vector')

%% Test Case 4: leaky LMS, noisy, random initial vector
[~,~,c] = vlms(x,d,N,0.01,0.02,2,c0);
c(:,end)-h

figure(4)
plot(c(1,:),'k')
hold on
plot(c(2,:),'b')
plot(c(3,:),'m')
plot(c(4,:),'r')
axis([1 Ns 0 1.1])
title('leaky LMS, noisy, random initial vector')

%% Test Case 5: NLMS2, noise-free, zero initial vector
x = [0.25*randn(1,floor(Ns/4)+1) randn(1,floor(3*Ns/4))];
d = filter(h,1,x);

c0 = zeros(1,N);     % initialize with zero vector

[~,~,c]       = vlms(x,d,N,0.01,0,0); % standard LMS as reference
[~,~,c_norm2] = vlms(x,d,N,0.01,0.03,1); 
c(:,end)-h
c_norm2(:,end)-h

figure(5)
plot(c_norm2(1,:),'k'), hold on, plot(c(1,:),':k')
plot(c_norm2(2,:),'b'), plot(c(2,:),':b')
plot(c_norm2(3,:),'m'), plot(c(3,:),':m')
plot(c_norm2(4,:),'r'), plot(c(4,:),':r')
legend('c1[n], NLMS2','c1[n], LMS','Location','best')
axis([1 Ns 0 1.1])
title('LMS and NLMS2, noise-free, zero initial vector')

