% The following script calculates the optimal OMC sening matrix, based on
% the followint 4 measurement or conditions:
%
%  1) A+B = 2 (the sum signal gain is arbitrary set,
%              this just rolls into the calibration)
%  2) The signal to shot noise is maximal in the SUM channel
%  3) There is no signal in the NULL channel
%  4) The shot noise in NULL must be equal to the shot noise in SUM
%  We define and measure:
%     g = PD_A/PD_B coherent signal amplitude ratio
%     h = PD_A/PD_B shot noise signal amplitude ratio
% 
%
%   M=[A,B;
%      C,D]
%
%   [SUM;    =    M  *   [PD_A;
%    NULL]                PD_B]
%
%  Solution:
%
%   A=(2*g)/(h^2 + g);
%   B=2-A
%   C=sqrt((A^2*h^2+B^2)/(h^2+g^2));
%   D=-g*C;
%
% in the script below I use the following convention:
% single letter:symbolic, double letters: numerical


gg=1.0323; % measured coherent signal amplitude ratio A/B
hh=1.0134; % measured shot noise amplitude ratio A/B 


syms g % coherent signal amplitude ratio A/B
syms h % shot noise amplitude ratio A/B 
syms A
B=2-A;
SNR2=(A*g+B)^2 / ((A*h)^2+B^2);
SNR2d=diff(SNR2,A);

sol2=solve(SNR2d==0,A);
sol=sol2(2);

% sol = (2*g)/(h^2 + g)

%evaluate numerical values

AA=(2*gg)/(hh^2 + gg);
BB=2-AA;
CC=sqrt((AA^2*hh^2+BB^2)/(hh^2+gg^2));
DD=-gg*CC;

MM=[AA,BB;CC,DD]


% verification tests
SUM_signal=AA*gg+BB;
SUM_noise=sqrt(AA^2*hh^2+BB^2);
NULL_signal=CC*gg+DD;
NULL_noise=sqrt(CC^2*hh^2+DD^2);

sumGain=AA+BB
NULL_signal
shotNoiseRatio=NULL_noise/SUM_noise


% veryfy max SNR
AAA=0:0.0001:2;
BBB=2-AAA;
SNR___=sqrt((AAA*gg+BBB).^2 ./ ((AAA*hh).^2+BBB.^2));

plot(AAA,SNR___,AAA,ones(size(AAA))*(SUM_signal/SUM_noise),[AA,AA],[1,(SUM_signal/SUM_noise)]);
grid on
xlabel('A matrix element');
ylabel('SNR');


