% set some basic constants in SI units 
% speed of light in vacuum
c = 299792458;
% magnetic constant
mu_0 = 4e-7*pi;
% electric constant
epsilon_0 = 1/(mu_0*c^2);
% characteristic impedance of vacuum
Z_0 = mu_0*c;
% Newtonian constant of gravitation
G = 6.6742e-11;
% Planck constant
h = 6.6260693e-34;
hbar = 1.05457168e-34;
% elementary charge
e = 1.60217653e-19;
% electron mass
m_e = 9.1093826e-31;
% proton mass 
m_p = 1.67262171e-27;
% fine-structure constant
alpha = 7.297352568e-3;
% Avogadro constant
N_A = 6.0221415e23;
% molar gas constant
R = 8.314472;
% Boltzmann constant
k_B = 1.3806505e-23;
% (unified) atomic mass unit
u = 1.66053886e-27;

%% constants given in the exercise
% undulator gap
gap = [8 16]*1e-3;
% pole tip field
B_tip = 1.5;
% undulator period
lambda_u = 15e-3;
% electron energy in eV
E_eV = 3.2e9;
% electron mass * c^2 in eV
m_e_eV = m_e / e * c^2;
% beam current
I_beam = 0.5;
% beam size
sigma_x = 20e-6;
% undulator length
L_u = 5;


%% calculations
% Lorentz factor
gamma = E_eV / m_e_eV
% number of undulator periods
N_periods = round(L_u / lambda_u)
% magnetic field amplitude on axis
B_0 = B_tip ./ cosh(pi * gap / lambda_u)
% undulator parameter
K = (e * B_0 * lambda_u) / (2 * pi * m_e * c)
% photon wavelength 
lambda = lambda_u / (2 * gamma^2) * (1 + K.^2 / 2)
% photon energy
E_gamma = h * c ./ lambda
% photon energy in eV
E_gamma_eV = E_gamma / e
% Bessel function factor
Q(1,K)
% photon flux
Ndot = 1.43e14 * N_periods * I_beam * Q(1,K)
% diffraction-limited source size
sigma_r = 1/(4*pi) * sqrt(lambda * L_u)
% effective source size
sigma_x_eff = sqrt(sigma_x^2 + sigma_r.^2)
% divergence: diffraction limit
sigma_rprime = sqrt(lambda/L_u)
% effective divergence
sigma_xprime_eff = sigma_rprime
% brilliance
B = Ndot ./ (4 * pi^2 * sigma_x_eff.^2 .* sigma_xprime_eff.^2)
% brilliance in commonly used units of flux / mm^2 mrad^2
B_common_units = B / 1e12