%% This is the model to evaluate the OMC mode matching at LHO.  
%% D. Hoak

clear all;
close all;

% There are six optical component positions in the output path (after the BS), with five ROCs.  They are:
%
% SR3, SR2, SRM, OM1, OM2, OMC
%
% (The OMC only has position information, no ROC.)
%
% For each optic we vary the position and ROC (if applicable) with normally-distributed random numbers.
%
% Positions are varied with sigma=0.020 meters, ROC varied with sigma=0.050 meters.
%
% This variability is probably larger than what we might expect, but this is a conservative estimate.

nTrials = 10000;

% initialize some arrays
overlap = zeros(nTrials,1);
optimized_overlap = zeros(nTrials,1);
SR2_move = zeros(nTrials,1);

for i=1:length(overlap)
	pos_variance = randn(6,1)*0.020;
        ROC_variance = randn(5,1)*0.050;

        [overlap(i), optimized_overlap(i), SR2_move(i)] = varyMirrorPositions(pos_variance, ROC_variance);
end

median(overlap)
median(optimized_overlap)
median(SR2_move)

figure(1)
hist(overlap,20)
hold on
grid on
title('Distribution of Overlap','FontSize',14);
xlabel('Mismatch with OMC Waist and Position','FontSize',12);
ylabel('Number of Instances','FontSize',12);

figure(2)
hist(optimized_overlap,20)
hold on
grid on
title('Distribution of Overlap, After SR2 Correction','FontSize',14);
xlabel('Mismatch with OMC Waist and Position','FontSize',12);
ylabel('Number of Instances','FontSize',12);

figure(3)
plot(overlap,optimized_overlap,'k*')
hold on
grid on
title('Initial Mismatch vs Final Mismatch','FontSize',14);
xlabel('Mismatch with OMC','FontSize',12);
ylabel('Mismatch with OMC, After SR2 Correction','FontSize',12);
ylim([min(optimized_overlap)-0.1 1.0])

figure(4)
plot(SR2_move,overlap-optimized_overlap,'k*')
hold on
grid on
title('SR2 Correction and Overlap Recovery','FontSize',14);
xlabel('SR2 Position Change [m]','FontSize',12);
ylabel('Starting Overlap - Final Overlap','FontSize',12);


figure(5)
hist(SR2_move,20)
hold on
grid on
title('Distribution of SR2 Correction','FontSize',14);
xlabel('SR2 Position Change [m]','FontSize',12);
ylabel('Number of Instances','FontSize',12);


%{
figure(101)
plot(zL,overlap_SR3,'b');
hold on
grid on
plot(zL,overlap_SR2,'r');
plot(zL,overlap_SRM,'k');
plot(zL,overlap_OM1,'g');
plot(zL,overlap_OM2,'c');
plot(zL,overlap_OM3,'m');
%plot(zL,overlap_BSAR,'y');
legend('SR3','SR2','SRM','OM1','OM2','OM3','Location','SouthEast')
title('Tolerance of OMC Mode Matching on Optic Position','FontSize',14);
xlabel('Longitudinal Translation (m)','FontSize',12);
ylabel('Overlap With OMC Waist','FontSize',12);
 %}
