% Transmission profile through a finite slab 

clear all;
% Parameters of the slab
Lz=20; % length of the slab
R=2000; %transverse size
ell=2; %scattering mean free path
   
tic; %useful to estimate the computation time : toc gives the elapsed time
Nph=1000000; % number of photons (1000000 photons take 4 seconds computing time)
for iph=1:1:Nph
    
% Initial Conditions 
Nsc=0;  % number of scattering events already done
cos_phi = 1; theta=0; % direction of incident propagation
x=0; %initial position along x
y=0; %initial position along y
z=0; % Initial impact with the vapor (NOT the 1st scattering event!)
r=sqrt(x^2+y^2);

% length of the 1st step using an exponential distribution (Beer-Lambert)
step = -ell*log(rand);  % use the inverse function f^(-1) to draw the random number following a distribution f: exp -> log

% The first step is ballistic in forward direction   
z = z+step;
z1=z;

while all(z<=Lz  && z>0  && r<R) % Next scattering event inside the slab
  
    Nsc = Nsc+1;  % add 1 to number of scattering events
    
%     % record the trajectory (optional)
%     X(Nsc) = x;
%     Y(Nsc) = y;
%     Z(Nsc) = z;
    
    % draw a new random direction
    theta = 2*pi*rand;
    cos_phi = -1+2*rand;  % uniform between -1 and 1 (always  check that the distribution is uniform: mistakes often happen with cos, sin etc)
    sin_phi = sqrt(1-cos_phi^2);  % always >0 since phi is between 0 and pi
    
    % length of the next step in an exponential ditribution (Beer-Lambert)
    step = -ell*log(rand);  

    % new position
    x = x + step*sin_phi*cos(theta) ;  
    y = y + step*sin_phi*sin(theta);
    z = z + step*cos_phi;
    r = sqrt(x^2+y^2);

    % record the trajectory 
    X(Nsc) = x;
    Y(Nsc) = y;
    Z(Nsc) = z;
   
end
if z>Lz
Nfinx(iph)=x;
Nfiny(iph)=y;
Nfinz(iph)=z;
Nfinr(iph)=x^2+y^2;
end; 

end;
 
rr=(1:1:R);
pr=hist(Nfinr, rr);
pr(1)=0;
figure('Position', [450 550 400 300]);  
plot(Nfinx, Nfiny, 'o', 'MarkerSize', 1)
axis([-3*Lz 3*Lz -3*Lz 3*Lz])


figure('Position', [100 50 1300 400]);  
subplot(1,2,1), plot(rr, pr./rr), xlabel('r'), ylabel('P(r)/r'), axis([0 10*Lz 0 1.5*pr(2)/rr(2)])
subplot(1,2,2), plot(rr, log(pr./rr)), xlabel('r'), ylabel('log(P(r)/r)'), axis([0 5*Lz -2.5 log(3*pr(2)/rr(2))])


toc

