%% Sample Frequency Response Modeling
% Collected load speed data given sine wave frequency and amplitude
%wl_meas = max(wl(:,2))
% Low-Gear
% data = [ 
% %   f (Hz)  Av (V)  wl (rad/s) 
%     0.0     2.0     18.4078;
%     1.0     2.0     17.7199;
%     2.0     2.0     16.5268;
%     3.0     2.0     14.8102;
%     4.0     2.0     13.3615;
%     5.0     2.0     12.0710;
%     6.0     2.0     10.5309;
%     7.0     2.0     9.9587;
%     8.0     2.0     8.9665;
%     ];
%
% High-Gear
data = [ 
%   f (Hz)  Av (V)  wl (rad/s) 
    0.0     2.0     3.3066;
    1.0     2.0     3.2494;
    2.0     2.0     3.1374;
    3.0     2.0     2.9596;
    4.0     2.0     2.7709;
    5.0     2.0     2.5895;
    6.0     2.0     2.4458;
    7.0     2.0     2.3448;
    8.0     2.0     2.2158;
    ];
%
%% Calculate frequency response
n = length(data);
% Frequency (Hz)
f = data(2:n,1);
% Gain (rad/s/V): |G(w)| = |wl(w)| / |Vm(w)|
G = abs(data(2:n,3)) ./ abs(data(2:n,2));
% Gain (dB)
Gdb = 20*log10(G);
%
%% Find gain
% Steady-state gain (rad/s/V)
Ke_f = data(1,3) / data(1,2);
Ke_f_db = 20*log10(Ke_f);
%
%% Find time constant
% Min, max, and differential frequencies (Hz)
f_min = min(f);
f_max = max(f);
df = 0.01;
% Interpolation frequency (Hz)
fi = f_min:df:f_max;
% Interpolated gain (rad/s/V)
Gi = interp1(f,G,fi,'linear');
% Interpolated gain (dB)
Gi_db = 20*log10(Gi);
% 3 dB Gain (rad/s/V)
G3_db = Ke_f_db - 3;
% 3 dB Frequency (Hz)
ic = min( find(Gi_db < G3_db) );
fc = fi(ic);
% Experimentally derived time constant (s)
tau_e_f = 1 / (2 * pi * fc);
%
%% Bode plot
semilogx(f,Gdb,'bx',fi,Gi_db,'r-');
axis([0 10 0 5]);
line( [1 fc], [G3_db G3_db], 'LineStyle', ':', 'Color', 'k' );
text( 1.1, 1.55, '|G(\omega_c)' )
line( [fc fc], [0 G3_db], 'LineStyle', ':', 'Color', 'k' );
text( 1.05*fc, 0.5, '\omega_c' )
xlabel('f (Hz)')
ylabel('|G(\omega)|_{dB}');
%
%% Display data
disp( 'SRV02 model parameters derived using manual frequency response: ' )
disp( [ '   Ke_f = ' num2str( Ke_f, 3 ) ' rad/s/V' ] )
disp( [ '   tau_e_f = ' num2str( tau_e_f, 3 ) ' s' ] )