%**************************************************************************
%This function calculates the required magnetic effect of the K adjustment
%shim.
%
%Input:
%gap, undulator gap (m)
%lambda_u, undulator period (m)
%k_shim_dbrel, delta B / B for the k adjust shim
%
%Output:
%k_shim_dgap, gap change required to get the desired K value (m)
%
%Zachary Wolf, 1/14/06

function [k_shim_dgap] = k_shim_calc_dgap(gap, lambda_u, k_shim_dbrel)

%Method
%The line integral of H around neighboring poles is zero.  This gives
%int_gap H dl = Hm Lm
%where Hm is H in the magnet and Lm is the magnet length
%The field in the gap under a pole varies as
%H(y) = (1 / mu0) B0 cosh(2 pi y / lambda_u)
%Amperes law then gives
%int_-g/2^g/2 (1 / mu0) B0 cosh(2 pi y / lambda_u) dy = Hm Lm
%(1 / mu0) B0 (lambda_u / 2 pi) sinh(2 pi y / lambda_u) |_-g/2^g/2 = Hm Lm
%(1 / mu0) B0 (lambda_u / pi) sinh(pi g / lambda_u) = Hm Lm
%B0 sinh(pi g / lambda_u) = mu0 (pi / lambda_u) Hm Lm
%If we change the gap,
%dB0 sinh(pi g / lambda_u) + B0 (pi / lambda_u) cosh(pi g / lambda_u) dg = 0 
%B0 (pi / lambda_u) cosh(pi g / lambda_u) dg = - dB0 sinh(pi g / lambda_u) 
%dg = - (dB0 / B0) (lambda_u / pi) tanh(pi g / lambda_u) 

%Perform the calculation
k_shim_dgap = - k_shim_dbrel * (lambda_u / pi) * tanh(pi * gap / lambda_u);
    
%Done
