% LKB photon box: QND measurement of photon
% rho formulation with 
%      -1- detection efficiency
% February 2016
% pierre.rouchon@mines-paristech.fr
% alain.sarlette@inria.fr
%
clear all;
%% operator for the quantum harmonic oscillator
i=sqrt(-1); Nmax=7; % truncation to Nmax
Ket0=zeros(Nmax+1,1);Ket0(1)=1; % vacuum state
Id=eye(Nmax+1);
N=diag((0:1:Nmax)); % photon  number operator
A=diag( sqrt((1:1:Nmax)),1); %  operator
%%  measurement operators
ph0=pi/7; % dephasing per photon
phR=0; % phase of the second Ramsey pulse
Mg=diag(cos((ph0*(0:1:Nmax)+phR)/2));
Me=diag(sin((ph0*(0:1:Nmax)+phR)/2));
%% measurement imperfections
eta=1/3; % detection efficiency
%% simulation parameter
Niter=300*1.5;
Psi=expm(sqrt(3)*(A'-A))*Ket0; % initial state coherent state with an average of 3 photons
rho=Psi*(Psi'); % initial state (no information) 
%% simulation loop
Pop=zeros(Nmax+1,Niter);y=zeros(1,Niter); % buffer for graphics
for ii=1:Niter
    Pop(:,ii)=diag(rho);
    rhog=Mg*rho*(Mg'); rhoe=Me*rho*(Me');
    if(rand < eta)
        if (rand < trace(rhog))
            y(ii)=-1;
            rho=rhog/trace(rhog);
        else
            y(ii)=1;
            rho=rhoe/trace(rhoe);
        end
    else
        y(ii)=0;
        rho=rhog+rhoe;
    end
    rho=rho/trace(rho);
end
%% graphics
figure(1),clf,
subplot(211);
bar([1:Niter],y);
ylabel('Measurement outcome');
axis([0 Niter+1 -1.02 1.02 ]);
subplot(212);
plot([1:Niter],Pop,'linewidth',2);
legend('0','1','2','3','4','5','6','7');
axis([1 Niter -0.02 1.02 ]);
ylabel('populations');
xlabel('step number');






