%% definisco il segnale 
close all;
clear all;
clc;

x = -2:0.01:2;
x = x';

y = cos(2*pi*2*x).*cos(2*pi*0.5*x);

y_noise =y + randn(length(y),1)*0.05;
figure;
plot(x,y);
hold on
plot(x,y_noise,'r+')
hold off
legend('original','noise','Location','SouthEast')

%% costruisco la base wavelet
close all

l = length(x);
N =  40;
J = 4;
nc = (2*J+1)*(2*N+1);
%f = 2;
A = zeros(l,nc);
A_mh = zeros(l,nc);
c=1;
for j=-J:J
    for n=-N:N
        A(:,c) = 1/sqrt(2^j)*haar_wave((x-2^j*n)/2^j);
        A_mh(:,c) = 1/sqrt(2^j)*mexican_hat((x-2^j*n)/2^j,2);
        c=c+1;
    end
end
figure
subplot(1,2,1)
imagesc(A)
subplot(1,2,2)
imagesc(A_mh)


c = pinv(A'*A+eye(nc)*1e-16)*A'*y_noise;

y_fit=A*c;


c_mh = pinv(A_mh'*A_mh+eye(nc)*1e-16)*A_mh'*y_noise;

y_fit_mh=A_mh*c_mh;



figure;
plot(x,y_noise,'r+','LineWidth',2)
hold on
plot(x,y_fit,'g-','LineWidth',2)
plot(x,y_fit_mh,'c-','LineWidth',2)

hold off
h_legend=legend('NOISE','HAAR','MEXICAN HAT','Location','SouthEast','Fontsize',20);
set(h_legend,'FontSize',14);
legend BOXOFF
ylim([-1.5,2])

dlmwrite('x_wave.txt',x)

dlmwrite('y_noise.txt',y_noise)

dlmwrite('y_haar.txt',y_fit)

dlmwrite('y_mh.txt',y_fit_mh)

errore_original = sum((y-y_noise).^2)
errore_fit_haar = sum((y_fit-y).^2)
errore_fit_mh = sum((y_fit_mh-y).^2)