
%This program calculates the K change as the gap changes.
%See LCLS-TN-04-8 for a discussion of the calculation.
%Zachary Wolf
%10/20/08

%Input parameters
%g = 0.034;                      %Undulator gap (m)
%lambda_u = 0.054;               %Undulator period (m)
%dK_frac_toler = 0.03 / 2 / 1.57;     %Tolerance on the fractional error on K
%dg_dx = 0;                      %Cant angle (rad)    

%Input parameters
g = 6.8e-3;                      %Undulator gap (m)
lambda_u = 3.0e-2;               %Undulator period (m)
dK_frac_toler = 1.5e-4;          %Tolerance on the fractional error on K
dg_dx = 4.5e-3;                  %Cant angle (rad)    

%Calculate the fractional K change with gap
dK_frac_dg = - coth(pi * g / lambda_u) * (pi / lambda_u);

%Calculate the maximum gap change for K to stay within tolerance
dg_max = abs(dK_frac_toler / dK_frac_dg);

%Calculate the fractional K change with x
dK_frac_dx = dK_frac_dg * dg_dx;

%Calculate the maximum x change for K to stay within tolerance
if abs(dK_frac_dx) > 0
    dx_max = abs(dK_frac_toler / dK_frac_dx);
else
    dx_max = 0;
end

%Calculate the maximum y change for K to stay within tolerance
%B = B0 cosh(2 pi y / lambda_u)
%B0 + dB = B0 cosh(2 pi dy / lambda_u)  %y = 0 gives B0
%1 + (dB / B0) = cosh(2 pi dy / lambda_u)
%1 + (dK / K) = cosh(2 pi dy / lambda_u)
%2 pi dy / lambda_u = cosh^-1(1 + (dK / K))
%dy = (lambda_u / (2 pi)) * cosh^-1(1 + (dK / K))
dy_max = (lambda_u / (2 * pi)) * acosh(1 + dK_frac_toler);

%Print the results
g
lambda_u
dK_frac_dg
dK_frac_toler
dg_max
dg_dx
dK_frac_dx
dx_max
dy_max

%Done
