%% IFO LO transfer function
%% load data

LOTF_amp = load('OMC_LO_TF_amp.TXT'); %data taken Nov 4, 2019
LOTF_phase = load('OMC_LO_TF_phase.TXT');
LOTF_ampx = LOTF_amp(:,1); %freq
LOTF_ampy = LOTF_amp(:,2); %amp
LOTF_phy = LOTF_phase(:,2); %phase

LOTFamp = 10.^(LOTF_ampy/20); %dB to power ratio
LOcmplx = LOTFamp.*exp(i.*deg2rad(LOTF_phy)); 
LOOLmag = abs(LOcmplx);
LOOLphase = angle(LOcmplx);

%% Generic common mode board components
CM_comp = zpk(-2.*pi.*[4e3  ], -2*pi.*[40 ], 1);
CM_boost1 = zpk(-2.*pi.*[10  ], -2*pi.*[0 ], 1);
CM_boost2 = zpk(-2.*pi.*[2e3  ], -2*pi.*[20 ], 1);
SLOW_boost = zpk(-2.*pi.*[400  ], -2*pi.*[4 ], 1);
SLOW_filters = zpk(-2.*pi.*[  ], -2*pi.*[100e3 ], 100e3*2*pi);
PZTdriver = zpk(-2.*pi.*[  10 ],...
            -2*pi.*[ 1 400], (1/10)*400*20); %PZTdriver gain = 20
%PFD = zpk(-2.*pi*[],-2.*pi*[0], 1.6*2.*pi); %1.6V/rad, 32deg/V, has to be measured in the lab
PZT = zpk([],[], 10.6e6); %Mephisto PZT calibration Hz/V
PM = zpk(-2*pi*[60],-2*pi*[10], (1/60)*10*.00136); 
flat = zpk([],[], VCXOV2Hz); %Hz/V
oneonf = zpk([],-2*pi*[0], 2*pi ); %phase detection frequency actuation

VCO = zpk(-2*pi*[ 40],-2*pi*[1.6], 281479.*(1/40).*1.6); %Hz/V 80MHz VCO calibration at DC

%% LO stuff

LO_CMgain = 0.56; %-5dB
LO_fastgain = 1; %0dB

common_path = LO_CMgain.*CM_boost1.*CM_boost2; 
fast_path = LO_fastgain.*VCO; 

%OMC RF3 -14.66dBm
LOcal = 1.12/2; %V/2rad 1V readout from RF3_I_NORM_DQ, with factor of 1.12 discrepancy from scope measurement
%scope discrepency calculated QMON at scope vs QMON in control room


LO_TF = LOcal.*common_path.* ( (fast_path) ).*oneonf;

[LOamp, LOphase] = bode(LO_TF, 2*pi*LOTF_ampx); 
LOamp = squeeze(LOamp);
LOphase = squeeze(LOphase);
LOfilter = LOamp.*exp(i.*deg2rad(LOphase));
LOOLmagzpk = abs(LOfilter);
LOOLphasezpk = angle(LOfilter);

LOCLgain = abs(1./(1+LOOLmagzpk));

%% plot LOTF

figure(227);
subplot(2,1,1);
semilogx(LOTF_ampx, 20*log10(LOOLmag),...
    LOTF_ampx, 20*log10(LOOLmagzpk), '--', 'LineWidth', 1.5, 'Color', [0.4940, 0.1840, 0.5560]);
xlabel('Frequency, Hz'), ylabel('Gain, dB');
ylim([-80,60])
xlim([1e2,1e5])
legend('Measured', 'Calculated')
title('LO OMC TF Nov 4, 2019');
grid on;
subplot(2,1,2);
semilogx(LOTF_ampx, rad2deg(LOOLphase),...
    LOTF_ampx, rad2deg(LOOLphasezpk),'--', 'LineWidth', 1.5, 'Color', [0.4940, 0.1840, 0.5560]);
xlabel('Frequency, Hz'), ylabel('Phase, deg.');
xlim([1e2,1e5])
grid on;
