% The jitter calculation
%
% -----------------------------------------------------------------------------------
%
% (C) 2017, Krzysztof Sozanski, Digital Signal Processing in Power Electronics Control 
% Circuits, second edition, Springer-Verlag, London, 2017. 
% 
% -----------------------------------------------------------------------------------
%
clear all; close all; 
N=2^14;  fs=6400; Ts=1/fs; font=10;
f=500; fkoh=round(f/(fs/N))*fs/N; % koherent signal sampling frequency
t=(0:N-1)*Ts; A_jitter=0.01*Ts;
tjitter=randn(1,N)*A_jitter; % normal (or Gaussian) distribution
A_jitter_rms=(sum(tjitter.^2)/N)^0.5; % RMS value of jiitter
SNR_calc=-20*log10(A_jitter_rms*2*pi*fkoh); % SNR from equation
wej_jitter=1.0*sin(2*pi*fkoh*(t+tjitter)); % signal with jitter
wej=1.0*sin(2*pi*fkoh*t); % signal without jitter
w_wej=fft(wej)/N*2; w_wej_jitter=fft(wej_jitter)/N*2;
w_wej_dB=20*log10(abs(w_wej)+eps); 
w_wej_jitter_dB=20*log10(abs(w_wej_jitter)+eps);
f=(0:N-1)*fs/N;
%% SNR from spectrum
n=round(fkoh/(fs/N)); % find number of signal bin
SNR=20*log10((sum(abs(w_wej([1:n, n+2:(N/2-1)]).^2)))^0.5);
C = num2str(-SNR,'%3.2f'); 
SNR_jitter=-20*log10((sum(abs(w_wej_jitter([1:n, n+2:(N/2-1)]).^2)))^0.5);
A = num2str(SNR_jitter,'%3.2f'); B = num2str(SNR_calc,'%3.2f');
figure('Name','Spectra','NumberTitle','off')
subplot(211),plot(f,w_wej_dB,'r','linewidth',2); grid on;
set(gca,'fontsize',font); title('(a)'); ylabel('Magnitude [dB]'), 
axis([0 fs/2 -320 0]); 
text(700,-75,['\it SNR \rm = ',C,' dB'],'FontSize',font);
subplot(212),plot(f,w_wej_jitter_dB,'linewidth',2); grid on;
set(gca,'fontsize',10);   title('(b)'); ylabel('Magnitude [dB]'), 
xlabel('Frequency [Hz]'); axis([0 fs/2 -100 0]);
text(700,-15,['\it SNR \rm = ',A,' dB'],'FontSize',font);
text(700,-35,['\it SNR_{calc} \rm = ',B,' dB'],'FontSize',font);
D = num2str(A_jitter_rms*1e6,'%3.2f');
text(700,-60,['\it \Delta t\rm_{rms}  = ',D,' \mus'],'FontSize',font);
print('jitter_matlab.pdf','-dpdf');  