%**************************************************************************
%This function calculates Keff.
%
%Input:
%gamma, electron beam Lorentz factor
%slope, slope of the slippage as a function of z linear fit (dimensionless)
%
%Output:
%k_eff, effective K value for the undulator (dimensionless)
%
%Zachary Wolf, 4/1/04, 12/27/05, 6/28/10

%Calculations
%
%Fit slippage at peaks:
%define slope of slippage at peak fields vs z := slope
%
%The slope defines Keff:
%(1/2) (1/gamma^2) (1 + (1/2) Keff^2) = slope
%(1 + (1/2) Keff^2) = 2 gamma^2 slope
%Keff^2 = 2 (2 gamma^2 slope - 1)
%Keff = sqrt(2 (2 gamma^2 slope - 1))
%
%Motivation:
%For pure sinusoidal field
%by = B0 cos(2 pi z / lambda_u)
%x' = - (q / gamma m vz) int by dz
%x' = - (q / gamma m vz) (B0 lambda_u/ 2 pi) sin(2 pi z / lambda_u)
%x' = (Kx / gamma) sin(2 pi z / lambda_u)    (define Kx)
%Kx := - q B0 lambda_u / m vz 2 pi        (can approximate vz by v, or c)
%Similarly, for added By, with no Bz
%y' = (Ky / gamma) sin(2 pi z / lambda_u + phi)
%
%Slippage:
%slip = (1/2) int (1/gamma^2 + x'^2 + y'^2) d_z
%slip = (1/2) int (1/gamma^2 + (Kx^2/gamma^2) sin^2(k z) + (Ky^2/gamma^2) sin^2(k z + phi)) d_z
%sin^2(k z) = (1/2) (1 - cos(2 k z))
%slip = (1/2) (1/gamma^2) z + (1/2) (Kx^2/gamma^2) (1/2) z - (1/2) (Kx^2/gamma^2) (1/2) int cos(2 k z) dz
%        + (1/2) (Ky^2/gamma^2) (1/2) z - (1/2) (Ky^2/gamma^2) (1/2) int cos(2 k z + 2 phi) dz
%slip = (1/2) (1/gamma^2) (1 + (1/2) Kx^2 + (1/2) Ky^2) z - (1/4) (Kx^2/gamma^2) (1/2k) sin(2 k z)
%        - (1/4) (Ky^2/gamma^2) (1/2k) sin(2 k z + 2 phi)
%
%At the field peaks:
%by = B0 cos(2 pi z / lambda_u) = B0 cos(k z)
%at the peaks, k z = 0, pi, 2 pi, ...
%slip_peak = (1/2) (1/gamma^2) (1 + (1/2) Kx^2 + (1/2) Ky^2) z
%        - (1/4) (Ky^2/gamma^2) (1/2k) sin(2 phi)  %(constant)
%
%Slope of slippage at peaks vs z:
%slope = (1/2) (1/gamma^2) (1 + (1/2) Kx^2 + (1/2) Ky^2)
%Define Keff to preserve this form
%slope = (1/2) (1/gamma^2) (1 + (1/2) Keff^2)
%
%Determine Beff from Keff:
%Kx = - q B0x lambda_u / m vz 2 pi
%Ky = - q B0y lambda_u / m vz 2 pi
%Keff = sqrt(Kx^2 + Ky^2)
%       - q sqrt(B0x^2 + B0y^2) lambda_u / m vz 2 pi
%Keff := - q Beff lambda_u / m vz 2 pi
%Beff = Keff (m vz 2 pi / (- q) lambda_u)
%
%Radiation wavelength:
%radiation has slippage = lambda_r when delta_z = lambda_u
%delta slippage / delta z = lambda_r / lambda_u
%slope = lambda_r / lambda_u
%lambda_r = lambda_u slope
%lambda_r = (1/2) (1/gamma^2) (1 + (1/2) Keff^2) lambda_u

function [k_eff] = k_calc_keff(gamma, slope)

%Physical constants
global Q_ELEC;               %Electron charge (C)
global M_ELEC;               %Electron mass (kg)
global C_LIGHT;              %Speed of light (m/s)

%Calculate Keff
k_eff = sqrt(2 * (2 * gamma^2 * slope - 1));

%Done