%% dwt1demo2
% approximation and details for multi-resolution analysis
% uses wavelet tool box

% S. Allen Broughton - 3 November 2010
%% define and plot signal
t =2*pi*(0:1023)/1024;
t = t';
X = sin(8*t)+0.25*cos(100*t)+0.4*cos(30*t);
noise = 0.1*(2*rand(size(t))-1);
X = X+noise;
figure(1)
plot(t,X)
axis tight

%% set up dwt mode 
dwtmode('per')
wn = 'haar' 

% compute levels
%% level 1
[CA1,CD1] = dwt(X,wn);
Z1 = zeros(size(CA1));
A1 = idwt(CA1,Z1,wn);
D1 = idwt(Z1,CD1,wn);
figure(2)
subplot(2,1,1)
plot(t,A1,t,D1)
title('approximation and details, A1 and D1')
axis tight
subplot(2,1,2)
plot(t,A1+D1)
title('approximation plus details, A1+D1')
axis tight

%% level2
[CA2,CD2] = dwt(CA1,wn);
Z2 = zeros(size(CA2));
A2 = idwt(idwt(CA2,Z2,wn),Z1,wn);
D2 = idwt(idwt(Z2,CD2,wn),Z1,wn);
figure(3)
subplot(2,1,1)
title('approximation and details, A2,D2, and D1')
plot(t,A2,t,D2,t,D1);
axis tight
subplot(2,1,2)
plot(t,A2+D2+D1)
title('approximation plus details, A2+D2+D1')
axis tight


%% level3
[CA3,CD3] = dwt(CA2,wn);
Z3 = zeros(size(CA3)); 
A3 = idwt(idwt(idwt(CA3,Z3,wn),Z2,wn),Z1,wn);
D3 = idwt(idwt(idwt(Z3,CD3,wn),Z2,wn),Z1,wn);
figure(4)
subplot(2,1,1)
title('approximation and details, A3,D3,D2, and D1')
plot(t,A3,t,D3,t,D2,t,D1);
axis tight
subplot(2,1,2)
plot(t,A3+D3+D2+D1)
title('approximation plus details, A3+D3+D2+D1')
axis tight
%% demonstrate perfect reconstruction
E1 = X-(A1+D1); E1'*E1
E2 = X-(A2+D2+D1); E2'*E2
E3 = X-(A3+D3+D2+D1); E3'*E3
eX = X'*X;

%% compute energy levels percents

lev1energydist = (100/eX)*[A1,D1]'*[A1,D1]
lev2energydist = (100/eX)*[A2,D2,D1]'*[A2,D2,D1]
lev3energydist = (100/eX)*[A3,D3,D2,D1]'*[A3,D3,D2,D1]




