% The APF output circuit simulation program
%
% -----------------------------------------------------------------------------------
%
% (C) 2017, Krzysztof Sozanski, Digital Signal Processing in Power Electronics Control 
% Circuits, second edition, Springer-Verlag, London, 2017. 
% 
% -----------------------------------------------------------------------------------
%
%
  clear all; close all;
  line_thickness=2; font_size=18;
  R=8; % oversampling ratio
  NM=2^8; % number of samples per line period
  NP= 100; % number of predios 
  fs=50*NM*R; % sampling frequency
  Ts=1/fs;
  N=NM*R*NP;
  L_C=0.6e-3; R_C=0.1;
  %% ----- Analog transfer function --------
  num_s=[1]; 
  den_s=[L_C R_C]; 
  tf(num_s,den_s)     % check the transfer function
  %% -------- Bilinear Transform ------------
  [num_d den_d]=bilinear(num_s,den_s,fs)
  % check the digital transfer function
  tf(num_d,den_d,Ts) 
  tf(num_d,den_d,Ts,'variable','z^-1')
  % check the frequency response of RL  
  figure('Name','Freq. resp.','NumberTitle','off');
  freqz(num_d,den_d); 
  title('Freq. response');
  %% algorithm delay
  Nop=R*50; % number of samples for algorithm dealy
  aop=1;
  bop=zeros(1,Nop+1); bop(1,Nop+1)=1;
  %% step response
  t=(0:N-1)*Ts;
  x_step=ones(1,N); % step
  i_C_step=filter(bop,aop,x_step);
  i_C_step=filter(num_d,den_d,i_C_step);
  figure('Name','Step response','NumberTitle','off');
    plot(t,i_C_step,'r','LineWidth',line_thickness); 
    set(gca,'Xlim',[0 0.05]);
    set(gca,'FontSize',[font_size],'FontWeight','d'),
    ylabel('i_C(t)'); grid on; 
    xlabel('Time [s]');
    print('APF_out_step.pdf','-dpdf');
  %% impulse response
  x_imp=[1 zeros(1,(N-1))]; % impulse
  i_C_imp=filter(bop,aop,x_imp);
  i_C_imp=filter(num_d,den_d,i_C_imp);
  % frequency response
  i_C_freq=fft(i_C_imp);
  %% Frequency response
  f=(0:N-1)*fs/N;
  i_C_freq_abs_db=20*log10(abs(i_C_freq));
  figure('Name','Frequency response','NumberTitle','off');
    plot(f,i_C_freq_abs_db,'r','LineWidth',line_thickness);  
    set(gca,'Xlim',[0 500]);grid on;
    set(gca,'FontSize',[font_size],'FontWeight','d'),
    ylabel('|I_C(e^{j\omegaT})|'); 
    xlabel('Frequency [Hz]');
    print('APF_out_freq.pdf','-dpdf');
    