%% Clear Workspace and Close figures
clear; close all; clc;

%% Intialize Laplace variable
s = zpk('s');

addpath('./mat/');

% Time Domain Signal
% Let's first define the number of sample and the sampling time.

N  = 10000; % Number of Sample
dt = 0.001; % Sampling Time [s]

t = dt*(0:1:N-1)'; % Time vector [s]



% We generate of signal that consist of:
% - a white noise with an RMS value equal to =anoi=
% - two sinusoidal signals

% The parameters are defined below.

asig = 0.1; % Amplitude of the signal [V]
fsig = 10;  % Frequency of the signal [Hz]

ahar = 0.5; % Amplitude of the harmonic [V]
fhar = 50;  % Frequency of the harmonic [Hz]

anoi = 1e-3; % RMS value of the noise



% The signal $x$ is generated with the following code and is shown in figure [[fig:time_domain_x_zoom]].

x = anoi*randn(N, 1) + asig*sin((2*pi*fsig)*t) + ahar*sin((2*pi*fhar)*t);

figure;
plot(t, x);
xlabel('Time [s]');
ylabel('Amplitude');
xlim([0, 1]);

% Estimation of the magnitude of a deterministic signal
% Let's compute the PSD of the signal using the =blackmanharris= window.

nx = length(x);
na = 8;
win = blackmanharris(floor(nx/na));

[pxx, f] = pwelch(x, win, 0, [], 1/dt);



% Normalization of the PSD.

CG = sum(win)/(nx/na);
NG = sum(win.^2)/(nx/na);
fbin = f(2) - f(1);

pxx_norm = pxx*(NG*fbin/CG^2);



% We determine the frequency bins corresponding to the frequency of the signals.

isig = round(fsig/fbin)+1;
ihar = round(fhar/fbin)+1;



% The theoretical RMS value of the signal is:

srmt = asig/sqrt(2); % Theoretical value of signal magnitude



% And we estimate the RMS value of the signal by either integrating the PSD around the frequency of the signal or by just taking the maximum value.

srms = sqrt(sum(pxx(isig-5:isig+5)*fbin)); % Signal spectrum integrated
srmsp = sqrt(pxx_norm(isig) * NG*fbin/CG^2); % Maximum read off spectrum

% Estimation of the noise level
% The noise level can also be computed using the integration method.

% The theoretical RMS noise value is.

nth = anoi/sqrt(max(f)) % Theoretical value [V/sqrt(Hz)]



% We can estimate this RMS value by integrating the PSD at frequencies where the power of the noise signal is above the power of the other signals.

navg = sqrt(mean(pxx_norm([ihar+10:end]))) % pwelch output averaged
