ocelot.cpbd package

Submodules

ocelot.cpbd.beam module

definition of particles, beams and trajectories

class ocelot.cpbd.beam.Beam(x=0, xp=0, y=0, yp=0)

Bases: object

property dg
property emit_xn
property emit_yn
property g
len()
property p
properties = ['g', 'dg', 'emit_xn', 'emit_yn', 'p', 'pz', 'px', 'py']
property px
property py
property pz
sizes()
to_array(nslice=100, window_len=None)
class ocelot.cpbd.beam.BeamArray(nslice=0)

Bases: ocelot.cpbd.beam.Beam

add_chirp(chirp=0, order=1, s0=None)

adds energy chirp of given “order” to the beam around “center” position [m] chirp = dE/E0/ds[um]**order = dg/g0/s[um]**order so that g_new = g0 + dg = g0 + g0 (s-s0)**order * chirp

add_chirp_poly(coeff, s0=None)

The method adds a polynomial energy chirp to the beam object.

coeff — coefficients for the chirp s0 — the point with respect to which the chirp will be introduced

The expression for the chirp:

E = E0((g0 + coeff[0])/g0 +

  • coeff[1]*(s - s0))**1 / 1! / ((speed_of_light * 1e-15)**1 * g0) +

  • coeff[2]*(s - s0))**2 / 2! / ((speed_of_light * 1e-15)**2 * g0) +

  • coeff[3]*(s - s0))**3 / 3! / ((speed_of_light * 1e-15)**3 * g0) + …

… + coeff[n]*(s - s0))**n / n! / ((speed_of_light * 1e-15)**n * g0))

where coeff[n] is represented in [1/fs**n] The convention for the coeff is introduced for convenient treatment this with respect to a radiation chirp in order to easily satisfy the resonant condition along the whole bunch in the case of linear electron bunch chirp. Here is the expresion:

2*dw/dt = (w0/g0) * dg/dt

@author: Andrei Trebushinin

add_wake(tube_radius=0.005, tube_len=1, conductivity=36600000.0, tau=7.1e-15, roughness=6e-07, d_oxid=5e-09)
center(s)
charge()
cleanup()
cut_empty_I(thresh=0.01)
equidist()
get_E()
get_s(s)
idx_max()
len()
params()
pk()
set_E(E_GeV)
smear(sw)
sort()
start_at_0()
to_array(*args, **kwargs)
class ocelot.cpbd.beam.Particle(x=0.0, y=0.0, px=0.0, py=0.0, s=0.0, p=0.0, tau=0.0, E=0.0, q=0.0)

Bases: object

particle to be used for tracking

class ocelot.cpbd.beam.ParticleArray(n=0)

Bases: object

array of particles of fixed size; for optimized performance (x, x’ = px/p0),(y, y’ = py/p0),(ds = c*tau, p = dE/(p0*c)) p0 - momentum

class LostParticleRecorder(n)

Bases: object

Stores information about particles that are getting lost.

Attributes:

lost_particles: List of indices of deleted particle. Notes: The indices of the initial ParticleArray are used. lp_to_pos_hist: Histogram of number of lost particles to position s. [(pos, num of lost particles), …]

add(inds, position)
array2ex_list(p_list)
array2list()
delete_particles(inds, record=True)

Deletes particles from the particle array via index. :param inds: Indices that will be removed from the particle array. :param record: If record is true the deleted particles will be saved in self.lost_particle_recorder. :return:

list2array(p_list)
property n
p()
px()
py()
rescale2energy(energy)

Method to rescale beam coordinates with new energy

Parameters

energy – new energy

Returns

rm_particle(index)

Method removes a “bad” particle with particular “index”. :param index: :return:

rm_tails(xlim, ylim, px_lim, py_lim)

Method removes particles outside range [-xlim, +xlim], [-px_lim, +px_lim] …

size()
property t
tau()
thin_out(nth=10, n0=0)

Method to thin out the particle array in n-th times. Means every n-th particle will be saved in new Particle array

Parameters
  • nth – 10, every n-th particle will be taken to new Particle array

  • n0 – start from n0 particle

Returns

New ParticleArray

x()
y()
class ocelot.cpbd.beam.SliceParameters

Bases: object

class ocelot.cpbd.beam.Trajectory

Bases: object

add(ct, x, y, xp, yp, z, s)
last()
class ocelot.cpbd.beam.Twiss(beam=None)

Bases: object

class - container for twiss parameters

ocelot.cpbd.beam.beam_matching(particles, bounds, x_opt, y_opt, remove_offsets=True)

Beam matching function, the beam is centered in the phase space

Parameters
  • particles – ParticleArray

  • bounds – [start, stop] in rms of sigmas in longitudinal direction

  • x_opt – [alpha, beta, mu (phase advance)]

  • y_opt – [alpha, beta, mu (phase advance)]

  • remove_offsets – True, remove offsets in transverse planes

Returns

transform ParticleArray (the same object)

ocelot.cpbd.beam.convmode(A, B, mode)
ocelot.cpbd.beam.convmode_py(A, B, mode)
ocelot.cpbd.beam.ellipse_from_twiss(emit, beta, alpha)
ocelot.cpbd.beam.gauss_from_twiss(emit, beta, alpha)
ocelot.cpbd.beam.generate_beam(E, I=5000, l_beam=3e-06, **kwargs)

Generates BeamArray object accepts arguments with the same names as BeamArray().parameters() I - current in Amps E - beam ebergy in GeV

dE - rms energy spread in GeV emit_x, emit_n(both normalized), emit_xn, etc. shape - beam shape (‘gaussian’ of ‘flattop’) l_beam [m] - beam length in meters l_window [m] - window length in um

by default: l_beam * 2 if flattop,

l_beam * 6 if gaussian,

nslice - number of slices in the beam

ocelot.cpbd.beam.generate_parray(sigma_x=0.0001, sigma_px=2e-05, sigma_y=None, sigma_py=None, sigma_tau=0.001, sigma_p=0.0001, chirp=0.01, charge=5e-09, nparticles=200000, energy=0.13, tau_trunc=None, tws=None)

Method to generate ParticleArray with gaussian distribution.

Note: in ParticleArray, {x, px} and {y, py} are canonical coordinates. {tau, p} is not, to make it canonical

the sign of “tau” should be flipped.

Parameters
  • sigma_x – std(x), x is horizontal cartesian coordinate.

  • sigma_px – std(px), ‘px’ is conjugate momentum canonical momentum px/p0.

  • sigma_y – std(y), y is vertical cartesian coordinate.

  • sigma_py – std(py), ‘py’ is canonical momentum py/p0.

  • sigma_tau – std(tau), “tau” = c*t

  • sigma_p – std(p), ‘p’ is canonical momentum E/(c*p0)

  • chirp – energy chirp [unitless], linear correlation - p_i += chirp * tau_i/sigma_tau

  • charge – beam charge in [C], 5e-9 by default

  • nparticles – namber of particles, 200k by default

  • energy – beam energy in [GeV], 0.13 [GeV]

  • tau_trunc – None, if not [float] - truncated gauss distribution in “tau” direction.

  • tws – None, if Twiss obj - the beam is matched to twiss params.

Returns

ParticleArray

ocelot.cpbd.beam.get_current(p_array, num_bins=200, **kwargs)

Function calculates beam current from particleArray.

Parameters
  • p_array – particleArray

  • charge

    • None, OBSOLETE, charge of the one macro-particle.

    If None, charge of the first macro-particle is used

  • num_bins – number of bins

:return s, I - (np.array, np.array) - beam positions [m] and currents in [A]

ocelot.cpbd.beam.get_envelope(p_array, tws_i=<ocelot.cpbd.beam.Twiss object>, bounds=None)

Function to calculate twiss parameters form the ParticleArray

Parameters
  • p_array – ParticleArray

  • tws_i – optional, design Twiss,

  • bounds – optional, [left_bound, right_bound] - bounds in units of std(p_array.tau())

Returns

Twiss()

ocelot.cpbd.beam.global_slice_analysis(parray, nparts_in_slice=5000, smooth_param=0.01, filter_base=2, filter_iter=2)

Function to calculate slice parameters

Parameters
  • parray – ParticleArray

  • nparts_in_slice – 5000, nparticles in the slice

  • smooth_param – 0.01, smoothing parameters to calculate the beam current: smooth_param = m_std * np.std(p_array.tau())

  • filter_base – 2, filter parameter in the func: simple_filter

  • filter_iter – 2, filter parameter in the func: simple_filter

Returns

SliceParameters,

ocelot.cpbd.beam.global_slice_analysis_extended(parray, Mslice, Mcur, p, iter)

Function to calculate slice parameters

Parameters
  • parray – ParticleArray

  • Mslice – 5000, nparticles in the slice

  • Mcur – 0.01, smoothing parameters to calculate the beam current: smooth_param = m_std * np.std(p_array.tau())

  • p – 2, filter parameter in the func: simple_filter

  • iter – 2, filter parameter in the func: simple_filter

Returns

s, I, ex, ey, me, se, gamma0, emitxn, emityn

ocelot.cpbd.beam.interp1(x, y, xnew, k=1)
ocelot.cpbd.beam.m_from_twiss(Tw1, Tw2)
ocelot.cpbd.beam.moments(x, y, cut=0)
ocelot.cpbd.beam.parray2beam(parray, step=1e-07)

reads ParticleArray() returns BeamArray() step [m] - long. size ob bin to calculate distribution parameters

ocelot.cpbd.beam.recalculate_ref_particle(p_array)
ocelot.cpbd.beam.s2cur_auxil(A, xiA, C, N, I)
ocelot.cpbd.beam.s2cur_auxil_py(A, xiA, C, N, I)
ocelot.cpbd.beam.s_to_cur(A, sigma, q0, v)

Function to calculate beam current

Parameters
  • A – s-coordinates of particles

  • sigma – smoothing parameter

  • q0 – bunch charge

  • v – mean velocity

Returns

[s, I]

ocelot.cpbd.beam.simple_filter(x, p, iter)
ocelot.cpbd.beam.slice_analysis(z, x, xs, M, to_sort)

returns: <x>, <xs>, <x^2>, <x*xs>, <xs^2>, np.sqrt(<x^2> * <xs^2> - <x*xs>^2) based on M particles in moving window Sergey, check please

ocelot.cpbd.beam.slice_analysis_py(z, x, xs, M, to_sort)

returns: <x>, <xs>, <x^2>, <x*xs>, <xs^2>, np.sqrt(<x^2> * <xs^2> - <x*xs>^2) based on M particles in moving window Sergey, check please

ocelot.cpbd.beam.slice_analysis_transverse(parray, Mslice, Mcur, p, iter)
ocelot.cpbd.beam.sortrows(x, col)
ocelot.cpbd.beam.waterbag_from_twiss(emit, beta, alpha)

ocelot.cpbd.beam_params module

class ocelot.cpbd.beam_params.EbeamParams(lattice, tws0, coupling=0.01, nsuperperiod=1)

Bases: object

integrals_id()
ocelot.cpbd.beam_params.I2_ID(L, h0)
ocelot.cpbd.beam_params.I3_ID(L, h0)
ocelot.cpbd.beam_params.I4_ID(L, h0, lu)
ocelot.cpbd.beam_params.I5_ID(L, h0, lu, beta_xc, Dx0, Dxp0)
ocelot.cpbd.beam_params.radiation_integrals(lattice, twiss_0, nsuperperiod=1)

ocelot.cpbd.chromaticity module

ocelot.cpbd.chromaticity.DZ(lattice, energy)
ocelot.cpbd.chromaticity.calculate_sex_strength(lattice, tws_0, ksi, ksi_comp, nsuperperiod)

compensation with two families

ocelot.cpbd.chromaticity.chromaticity(lattice, tws_0, nsuperperiod=1)
ocelot.cpbd.chromaticity.compensate_chromaticity(lattice, ksi_x_comp=0, ksi_y_comp=0, nsuperperiod=1)

old chromaticity compensation with 2 sextupole families

ocelot.cpbd.chromaticity.edge_chromaticity(lattice, tws_0)
ocelot.cpbd.chromaticity.edge_chromaticity_old(lattice, tws_0)
ocelot.cpbd.chromaticity.natural_chromaticity(lattice, tws_0, nsuperperiod=1)
ocelot.cpbd.chromaticity.sextupole_chromaticity(lattice, tws0, nsuperperiod=1)
ocelot.cpbd.chromaticity.sextupole_id(lattice)

ocelot.cpbd.coord_transform module

S.Tomin and I.Zagorodnov, 2017, DESY/XFEL

ocelot.cpbd.coord_transform.xp_2_xxstg_mad(xp, xxstg, gamref)
ocelot.cpbd.coord_transform.xxstg_2_xp_mad(xxstg, xp, gamref)

ocelot.cpbd.csr module

@ authors Martin Dohlus DESY, 2015, Sergey Tomin XFEL, 2016

class ocelot.cpbd.csr.CSR

Bases: ocelot.cpbd.physics_proc.PhysProc

coherent synchrotron radiation Attributes:

self.step = 1 [in Navigator.unit_step] - step of the CSR kick applying for beam (ParticleArray) self.sigma_min = 1.e-4 - minimal sigma if gauss filtering applied self.traj_step = 0.0002 [m] - trajectory step or, other words, integration step for calculation of the CSR-wake self.apply_step = 0.0005 [m] - step of the calculation CSR kick, to calculate average CSR kick

CSR_K1(i, traj, NdW, gamma=None)
Parameters
  • i – index of the trajectories points for the convolution kernel is calculated;

  • traj – trajectory. traj[0,:] - longitudinal coordinate, traj[1,:], traj[2,:], traj[3,:] - rectangular coordinates, traj[4,:], traj[5,:], traj[6,:] - tangential unit vectors

  • NdW – list [N, dW], NdW[0] is number of mesh points, NdW[1] = dW > 0 is increment. Mesh = Mesh = (-N:0) * dW

  • gamma

Returns

K0_fin_inf(i, traj, w_range, gamma)

Radiative interaction is coming from the infinite straight line that is assumed before the specified CSR region and it is calculated analytically

Parameters
  • i

  • traj

  • w_range

  • gamma

Returns

K0_inf_anf(i, traj, wmin)
Parameters
  • i – index of the trajectories points for the convolution kernel is calculated;

  • traj – trajectory. traj[0,:] - longitudinal coordinate, traj[1,:], traj[2,:], traj[3,:] - rectangular coordinates, traj[4,:], traj[5,:], traj[6,:] - tangential unit vectors

  • wmin – the first coordinate of the mash

Returns

K0_inf_inf(i, traj, w_range)

Radiative interaction is coming from the infinite straight line that is assumed before the specified CSR region and it is calculated analytically

Parameters
  • i

  • traj

  • w_range

Returns

apply(p_array, delta_s)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

finalize(*args, **kwargs)

the method is called at the end of tracking

Returns

plot_wake(p_array, lam_K1, itr_ra, s1, st)

Method to plot CSR wakes on each step and save pictures in the working folder. Might be time-consuming.

Parameters
  • p_array

  • lam_K1

  • itr_ra

  • s1

  • st

Returns

prepare(lat)

calculation of trajectory in rectangular coordinates calculation of the z_csr_start :param lat: Magnetic Lattice :return: self.csr_traj: trajectory. traj[0,:] - longitudinal coordinate,

traj[1,:], traj[2,:], traj[3,:] - rectangular coordinates, traj[4,:], traj[5,:], traj[6,:] - tangential unit vectors

class ocelot.cpbd.csr.K0_fin_anf

Bases: object

K0_0_jit(i, traj0, traj1, traj2, traj3, gamma, s, n, R, w, wmin)
K0_1_jit(indx, j, R, n, traj4, traj5, traj6, w, gamma)
K0_fin_anf_np(i, traj, wmin, gamma)
K0_fin_anf_numexpr(i, traj, wmin, gamma)
K0_fin_anf_opt(i, traj, wmin, gamma)
estimate_start_index(i, traj, w_min, beta, i_min=1000, n_test=10)

This method estimates the index of the first trajectory point from which CSR effects should be computed.

This method can significantly reduce the computing time of CSR effects by pre-discaring regions of the reference trajectory which do not influence the CSR calculation (i.e. the points where w <= wmin). This is performed by testing the w <= wmin condition for a subset of n_test equally-spaced points along the reference trajectory. The index of the last tested trajectory point in which w <= wmin is returned.

iint

Iteration index

trajndarray

Reference trajectory along which CSR forces are calculated

w_minfloat

Leftmost edge of the longitudinal bunch binning.

betafloat

Relativistic factor.

i_minint

Minimum iteration index. When i<i_min, no estimation of the starting index is performed (0 is returned).

n_testint

Number of points along the trajectory in which to test whether they should be taken into account for the CSR calculation.

The estimated start index, which is always <= than the real one.

class ocelot.cpbd.csr.Smoothing

Bases: object

Q2EQUI(q, BS_params, SBINB, NBIN)

input BIN = bin boundaries BIN(N_BIN, 2), in time or space Q_BIN = charges per bin Q_BIN(N_BIN) BS_params = binning and smoothing parameters binning………………….. X_QBIN = length or charge binning 0… 1 = length…charge N_BIN = number of bins M_BIN = multiple binning(with shifted bins) smoothing………………… IP_method = 0 / 1 / 2 for rectangular / triangular / gauss SP = ? parameter for gauss sigma_min = minimal sigma, if IP_method == 2 step_unit = if positive –> step=integer * step_unit output z1, z2, Nz = equidistant mesh(Nz meshlines) charge_per_step = charge per step, charge_per_step(1:Nz) bins might overlapp!

q_per_step_ip2_py(N_BIN, Q_BIN, BIN0, BIN1, NSIG, RMS, step, Nz, z1)
class ocelot.cpbd.csr.SubBinning(x_qbin, n_bin, m_bin)

Bases: object

p_per_subbins_py(s, SBINB, K_BIN)
subbin_bound(q, s, x_qbin, n_bin, m_bin)
input

q = array/scalar with charges of macro particles (sorted) s = longitudinal vector (time or space) (sorted) B_params = binning parameters

[X_QBIN,N_BIN,M_BIN] X_QBIN = length or charge binning

0 … 1 = length … charge

N_BIN = number of bins M_BIN = multiple binning (with shifted bins)

output

SBINB = array with subbin boundaries NBIN = particles per subbin

particles are sorted! all particles are valid

ocelot.cpbd.csr.csr_convolution(a, b)
ocelot.cpbd.csr.nextpow2(p)

Mimic matlab function nextpow2

Parameters

p

Returns

ocelot.cpbd.csr.sample_0(i, a, b)
ocelot.cpbd.csr.sample_1(i, a, b, c)

ocelot.cpbd.elements module

definition of magnetic lattice linear dimensions in [m]

class ocelot.cpbd.elements.Aperture(xmax=inf, ymax=inf, dx=0, dy=0, type='rect', eid=None)

Bases: ocelot.cpbd.elements.Element

xmax - half size in horizontal plane in [m], ymax - half size in vertical plane in [m], type - “rect” or “elliptical”.

class ocelot.cpbd.elements.Bend(l=0.0, angle=0.0, k1=0.0, k2=0.0, e1=0.0, e2=0.0, tilt=0.0, gap=0.0, h_pole1=0.0, h_pole2=0.0, fint=0.0, fintx=None, eid=None)

Bases: ocelot.cpbd.elements.Element

bending magnet l - length of magnet in [m], angle - angle of bend in [rad], k1 - strength of quadrupole lens in [1/m^2], k2 - strength of sextupole lens in [1/m^3], tilt - tilt of lens in [rad], e1 - the angle of inclination of the entrance face [rad], e2 - the angle of inclination of the exit face [rad]. fint - fringe field integral fintx - allows (fintx > 0) to set fint at the element exit different from its entry value. gap - the magnet gap [m], NOTE in MAD and ELEGANT: HGAP = gap/2 h_pole1 - the curvature (1/r) of the entrance face h_pole1 - the curvature (1/r) of the exit face

class ocelot.cpbd.elements.Cavity(l=0.0, v=0.0, phi=0.0, freq=0.0, vx_up=0, vy_up=0, vxx_up=0, vxy_up=0, vx_down=0, vy_down=0, vxx_down=0, vxy_down=0, eid=None)

Bases: ocelot.cpbd.elements.Element

Standing wave RF cavity v - voltage [GV] freq - frequency [Hz] phi - phase in [deg] vx_{up/down}, vy_{up/down} - zero order kick of a {up/down}stream coupler vxx_{up/down}, vxy_{up/down} - first order kick a {up/down}stream coupler

class ocelot.cpbd.elements.CouplerKick(v=0.0, phi=0.0, freq=0.0, vx=0.0, vy=0.0, vxx=0.0, vxy=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

Coupler Kick element for Cavity v - voltage [GV] freq - frequency [Hz] phi - phase in [deg] vx, vy - zero order kick of a stream coupler vxx, vxy - first order kick a stream coupler

class ocelot.cpbd.elements.Drift(l=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

drift - free space l - length of drift in [m]

class ocelot.cpbd.elements.Edge(l=0.0, angle=0.0, k1=0.0, edge=0.0, tilt=0.0, dtilt=0.0, dx=0.0, dy=0.0, h_pole=0.0, gap=0.0, fint=0.0, pos=1, eid=None)

Bases: ocelot.cpbd.elements.Bend

class ocelot.cpbd.elements.Element(eid=None)

Bases: object

Element is a basic beamline building element Accelerator optics elements are subclasses of Element Arbitrary set of additional parameters can be attached if necessary

class ocelot.cpbd.elements.Hcor(l=0.0, angle=0.0, eid=None)

Bases: ocelot.cpbd.elements.RBend

horizontal corrector, l - length of magnet in [m], angle - angle of bend in [rad],

class ocelot.cpbd.elements.Marker(eid=None)

Bases: ocelot.cpbd.elements.Element

class ocelot.cpbd.elements.Matrix(l=0.0, delta_e=0, eid=None, **kwargs)

Bases: ocelot.cpbd.elements.Element

Matrix element

l = 0 - m, length of the matrix element r = np.zeros((6, 6)) - R - elements, first order t = np.zeros((6, 6, 6)) - T - elements, second order delta_e = 0 - GeV, energy gain along the matrix element

class ocelot.cpbd.elements.Monitor(l=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

class ocelot.cpbd.elements.Multipole(kn=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

kn - list of strengths

class ocelot.cpbd.elements.Octupole(l=0.0, k3=0.0, tilt=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

octupole k3 - strength of octupole lens in [1/m^4], l - length of lens in [m].

class ocelot.cpbd.elements.Pulse

Bases: object

class ocelot.cpbd.elements.Quadrupole(l=0.0, k1=0, k2=0.0, tilt=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

quadrupole l - length of lens in [m], k1 - strength of quadrupole lens in [1/m^2], k2 - strength of sextupole lens in [1/m^3], tilt - tilt of lens in [rad].

class ocelot.cpbd.elements.RBend(l=0.0, angle=0.0, k1=0.0, k2=0.0, e1=None, e2=None, tilt=0.0, gap=0, h_pole1=0.0, h_pole2=0.0, fint=0.0, fintx=None, eid=None)

Bases: ocelot.cpbd.elements.Bend

rectangular bending magnet, l - length of magnet in [m], angle - angle of bend in [rad], k1 - strength of quadrupole lens in [1/m^2], k2 - strength of sextupole lens in [1/m^3], tilt - tilt of lens in [rad], e1 - the angle of inclination of the entrance face [rad], e2 - the angle of inclination of the exit face [rad]. fint - fringe field integral fintx - allows (fintx > 0) to set fint at the element exit different from its entry value. gap - the magnet gap [m], NOTE in MAD and ELEGANT: HGAP = gap/2 h_pole1 - the curvature (1/r) of the entrance face h_pole1 - the curvature (1/r) of the exit face

class ocelot.cpbd.elements.SBend(l=0.0, angle=0.0, k1=0.0, k2=0.0, e1=0.0, e2=0.0, tilt=0.0, gap=0, h_pole1=0.0, h_pole2=0.0, fint=0.0, fintx=None, eid=None)

Bases: ocelot.cpbd.elements.Bend

sector bending magnet, l - length of magnet in [m], angle - angle of bend in [rad], k1 - strength of quadrupole lens in [1/m^2], k2 - strength of sextupole lens in [1/m^3], tilt - tilt of lens in [rad], e1 - the angle of inclination of the entrance face [rad], e2 - the angle of inclination of the exit face [rad]. fint - fringe field integral fintx - allows (fintx > 0) to set fint at the element exit different from its entry value. gap - the magnet gap [m], NOTE in MAD and ELEGANT: HGAP = gap/2 h_pole1 - the curvature (1/r) of the entrance face h_pole1 - the curvature (1/r) of the exit face

class ocelot.cpbd.elements.Sequence(l=0, refer=0)

Bases: object

class ocelot.cpbd.elements.Sextupole(l=0.0, k2=0.0, tilt=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

sextupole l - length of lens in [m], k2 - strength of sextupole lens in [1/m^3].

class ocelot.cpbd.elements.Solenoid(l=0.0, k=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

l - length in m, k - strength B0/(2B*rho)

class ocelot.cpbd.elements.TDCavity(l=0.0, freq=0.0, phi=0.0, v=0.0, tilt=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

Transverse deflecting cavity - by default kick in horizontal plane

l - length [m] v - voltage [GV/m] freq - frequency [Hz] phi - phase in [deg] tilt - tilt of cavity in [rad]

class ocelot.cpbd.elements.TWCavity(l=0.0, v=0.0, phi=0.0, freq=0.0, eid=None)

Bases: ocelot.cpbd.elements.Element

Traveling wave cavity v - voltage [GV] freq - frequency [Hz] phi - phase in [deg]

class ocelot.cpbd.elements.Undulator(lperiod=0.0, nperiods=0, Kx=0.0, Ky=0.0, field_file=None, eid=None)

Bases: ocelot.cpbd.elements.Element

lperiod - undulator period in [m];

nperiod - number of periods;

Kx - undulator paramenter for vertical field;

Ky - undulator parameter for horizantal field;

field_file - absolute path to magnetic field data;

mag_field - None by default, the magnetic field map function - (Bx, By, Bz) = f(x, y, z) eid - id of undulator.

validate()
class ocelot.cpbd.elements.UnknownElement(l=0, kick=0, xsize=0, ysize=0, volt=0, lag=0, harmon=0, refer=0, vkick=0, hkick=0, eid=None)

Bases: ocelot.cpbd.elements.Element

l - length of lens in [m]

class ocelot.cpbd.elements.Vcor(l=0.0, angle=0.0, eid=None)

Bases: ocelot.cpbd.elements.RBend

horizontal corrector, l - length of magnet in [m], angle - angle of bend in [rad],

class ocelot.cpbd.elements.XYQuadrupole(l=0.0, x_offs=0.0, y_offs=0.0, k1=0.0, tilt=0.0, eid=None)

Bases: ocelot.cpbd.elements.SBend

Quadrupole with offsets (linear element). The element is to test a transport feature and it is not tested.

l - length of magnet in [m], k1 - strength of quadrupole lens in [1/m^2], x_offs - offset in horizontal direction in [m] y_offs - offset in vertical direction in [m] tilt - tilt of lens in [rad],

ocelot.cpbd.elements.survey(lat, ang=0.0, x0=0, z0=0)

ocelot.cpbd.errors module

module for misalignment error generation Sergey Tomin

class ocelot.cpbd.errors.Errors

Bases: object

ocelot.cpbd.errors.create_copy(lattice, nsuperperiods)
ocelot.cpbd.errors.errors_seed(lattice, er_list)
ocelot.cpbd.errors.normal(loc=0.0, scale=1.0, size=None)

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2]_, is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]_.

Note

New code should use the normal method of a default_rng() instance instead; please see the random-quick-start.

locfloat or array_like of floats

Mean (“centre”) of the distribution.

scalefloat or array_like of floats

Standard deviation (spread or “width”) of the distribution. Must be non-negative.

sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

outndarray or scalar

Drawn samples from the parameterized normal distribution.

scipy.stats.normprobability density function, distribution or

cumulative density function, etc.

Generator.normal: which should be used for new code.

The probability density for the Gaussian distribution is

\[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },\]

where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance.

The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x - \sigma\) [2]_). This implies that normal is more likely to return samples lying close to the mean, rather than those far away.

1

Wikipedia, “Normal distribution”, https://en.wikipedia.org/wiki/Normal_distribution

2

P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.

Draw samples from the distribution:

>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

Verify the mean and the variance:

>>> abs(mu - np.mean(s))
0.0  # may vary
>>> abs(sigma - np.std(s, ddof=1))
0.1  # may vary

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
>>> plt.show()

Two-by-four array of samples from N(3, 6.25):

>>> np.random.normal(3, 2.5, size=(2, 4))
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],   # random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]])  # random
ocelot.cpbd.errors.tgauss(mu=0, sigma=1, trunc=2, num=1)
ocelot.cpbd.errors.tgauss_old(mu=0, sigma=1, trunc=2)

ocelot.cpbd.field_map module

class ocelot.cpbd.field_map.FieldMap(field_file, xyz_units='mm', format='flat')

Bases: object

read(field_file)
ocelot.cpbd.field_map.length_array(xyz_array)
ocelot.cpbd.field_map.read_flat_file(field_file, sCom='#')
ocelot.cpbd.field_map.read_tabular_file(field_file)

ocelot.cpbd.high_order module

ocelot.cpbd.high_order.H23(vec_x, h, k1, k2, beta=1.0, g_inv=0.0)

{x, px}, {y, py}, {sigma, ps} sigma = s - ct ps = (E - E0)/(p0*c) H2 = (px**2 + py**2)/2 + (h**2 + k1)*x**2/2 - (k1*y**2)/2 - (h*pt*x)/beta H3 = (h*x - ps/beta)*(px**2 + py**2)/2 + (2*h*k1 + k2)*(x**3)/6 - (h*k1 + k2)*(x*y**2)/2 - ps/(beta*gamma**2*(1. + beta)) H23 = H2 + H3 :param vec_x: [x, px, y, py, sigma, psigma] :param h: curvature :param k1: quadrupole strength :param k2: sextupole strength :param beta: = 1, velocity :param g_inv: 1/gamma, by default 0. :return: [x’, px’, y’, py’, sigma’, psigma’]

ocelot.cpbd.high_order.arcline(SREin, Delta_S, dS, R_vect)

Martin Dohlus DESY, 2015

Parameters
  • SREin – trajectory. traj[0,:] - longitudinal coordinate (s), traj[1,:],traj[2,:],traj[3,:] - rectangular coordinates, (x, y, z) traj[4,:],traj[5,:],traj[6,:] - tangential unit vectors, (x’, y’, z’)

  • Delta_S

  • dS

  • R_vect – radius

Returns

ocelot.cpbd.high_order.fringe_ent(h, k1, e, h_pole=0.0, gap=0.0, fint=0.0)

Calculate first and second order matrices for edge focusing element. Note: the first order (R) is shown here in the sake of completeness but it is duplicated

in r_matrix.py module and used from there in optics.py

Parameters
  • h – curvature (1/r) of the bend in [1/m]

  • k1 – strength of quadrupole component of the dipole in [1/m^2],

  • e – the angle of inclination of the entrance face [rad],

  • h_pole – the curvature (1/r) of the entrance face

  • gap – the magnet gap [m], NOTE in MAD and ELEGANT: HGAP = gap/2

  • fint – fringe field integral

Returns

R, T. First and second order matrices (6, 6), (6, 6, 6)

ocelot.cpbd.high_order.fringe_ext(h, k1, e, h_pole=0.0, gap=0.0, fint=0.0)

Calculate first and second order matrices for edge focusing element. Note: the first order (R) is shown here in the sake of completeness but it is duplicated

in r_matrix.py module and used from there in optics.py

Parameters
  • h – curvature (1/r) of the bend in [1/m]

  • k1 – strength of quadrupole component of the dipole in [1/m^2],

  • e – the angle of inclination of the exit face [rad],

  • h_pole – the curvature (1/r) of the exit face

  • gap – the magnet gap [m], NOTE in MAD and ELEGANT: HGAP = gap/2

  • fint – fringe field integral

Returns

R, T. First and second order matrices (6, 6), (6, 6, 6)

ocelot.cpbd.high_order.moments(bx, by, Bx, By, Bz, dzk)

mx = v/(dz/dt)*e/p*(y’*Bz - By*(1.+x’^2) + x’*y’*Bx)*dz my = -v/(dz/dt)*e/p*(x’*Bz - Bx*(1.+y’^2) + x’*y’*By)*dz :param bx: x’ = dx/dz :param by: y’ = dy/dz :param Bx: horizontal component of mag field :param By: vertical component of mag field :param Bz: longitudinal component of mag field :param dzk: dz*e/p; dz - step, e - charge, p - momentum :return: mx, my

ocelot.cpbd.high_order.moments_py(bx, by, Bx, By, Bz, dzk)

mx = v/(dz/dt)*e/p*(y’*Bz - By*(1.+x’^2) + x’*y’*Bx)*dz my = -v/(dz/dt)*e/p*(x’*Bz - Bx*(1.+y’^2) + x’*y’*By)*dz :param bx: x’ = dx/dz :param by: y’ = dy/dz :param Bx: horizontal component of mag field :param By: vertical component of mag field :param Bz: longitudinal component of mag field :param dzk: dz*e/p; dz - step, e - charge, p - momentum :return: mx, my

ocelot.cpbd.high_order.rk_field(rparticles, s_start, s_stop, N, energy, mag_field, long_dynamics=True)

Method to track particles through mag field

Parameters
  • rparticles – initial coordinates of the particles shape (6xN), N number of particles (e.g. ParticleArray.rparticles)

  • s_start

  • s_stop

  • N – number of points on the trajectory

  • energy – in GeV

  • mag_field – must be function e.g. lambda x, y, z: (Bx, By, Bz)

  • long_dynamics – True, if True, includes longitudinal dynamics, otherwise only transverse

Returns

ocelot.cpbd.high_order.rk_field_scipy(y0, l, N, energy, mag_field)
ocelot.cpbd.high_order.rk_track_in_field(y0, s_stop, N, energy, mag_field, s_start=0.0)

Runge-Kutta solver of the exact trajectory equations in the fixed coordinate system {X, Y, Z]}. X, Y - transverse coordinates, Z - longitudinal.

Trajectory equations: x’’ = v/(dz/dt)*e/p*(y’*Bz - By*(1.+x’^2) + x’*y’*Bx) y’’ = -v/(dz/dt)*e/p*(x’*Bz - Bx*(1.+y’^2) + x’*y’*By) v/(dz/dt) = sqrt(1 + y’^2 + x’^2) z’ is not needed in the initial conditions and z’ is not used for SR calculation

therefore z’ can be arbitrary defined in the returning array. z’ = dE/(ps*c)

Parameters
  • y0 – array n*6; initial coordinates of n particles [x0, x0’=dx/dz, y0, y0=dy/dz, 0, dE0/pc, x1, x1’, y1, y1’, 0, dE1/pc, … xn, xn’, yn, yn’, 0, dEn/pc]

  • s_stop – longitudinal coordinate of stop

  • N – number of steps

  • energy – energy of particle in [GeV]

  • mag_field – function. Bx, By, Bz = mag_field(X, Y, Z)

  • s_start – starting longitudinal coordinate

Returns

array with length N*9- coordinates and magnetic fields on the trajectory [x, x’, y, y’, z, dE/pc, Bx, By, Bz, … xn, xn’, yn, yn’, zn, zn’, Bxn, Byn, Bzn]

ocelot.cpbd.high_order.scipy_track_in_field(y0, l, N, energy, mag_field)
ocelot.cpbd.high_order.sym_map(z, X, h, k1, k2, energy=0.0)
ocelot.cpbd.high_order.t_nnn(L, h, k1, k2, energy=0)
ocelot.cpbd.high_order.t_nnn_mad(L, h, k1, k2, energy=0)

Universal function to return second order matrix. Here are used the following set of variables: x, px/p0, y, py/p0, tau, dE/(p0c). See https://nbviewer.jupyter.org/github/ocelot-collab/ocelot/blob/master/demos/ipython_tutorials/2_tracking.ipynb

Parameters
  • L – length in [m]

  • h – curvature (1/r) of the bend in [1/m]

  • k1 – strength of quadrupole component in [1/m^2],

  • k2 – strength of sextupole component in [1/m^3],

  • energy – energy in [GeV]

Returns

second order matrix, numpy array with shape = (6, 6, 6)

ocelot.cpbd.high_order.t_nnn_transport(L, h, k1, k2, energy=0)

here is used the following set of variables: x, dx/ds, y, dy/ds, delta_l, dp/p0 :param L: :param angle: :param k1: :param k2: :return:

ocelot.cpbd.high_order.track_und_weave(y0, z, kz, kx, Kx, energy)
ocelot.cpbd.high_order.track_und_weave_openmp(u, l, N, kz, kx, Kx, energy)
ocelot.cpbd.high_order.verlet(vec_x, step, h, k1, k2, beta=1.0, g_inv=0.0)

q_{n+1} = q_{n} + h * dH(p_{n}, q_{n+1})/dp p_{n+1} = p_{n} - h * dH(p_{n}, q_{n+1})/dq

ocelot.cpbd.high_order.verlet1O(vec_x, step, h, k1, k2, beta=1.0, g_inv=0.0)

q_{n+1} = q_{n} + h * dH(p_{n}, q_{n+1})/dp p_{n+1} = p_{n} - h * dH(p_{n}, q_{n+1})/dq

ocelot.cpbd.io module

ocelot.cpbd.io.beam2input(beam)
ocelot.cpbd.io.cell2input(lattice, split=False)
ocelot.cpbd.io.create_var_name(objects)
ocelot.cpbd.io.element_def_string(element)
ocelot.cpbd.io.elements2input(lattice)
ocelot.cpbd.io.find_drifts(lat)
ocelot.cpbd.io.find_obj_and_create_name(lat, types)
ocelot.cpbd.io.find_objects(lat, types)

Function finds objects by types and adds it to list if object is unique. :param lat: MagneticLattice :param types: types of the Elements :return: list of elements

ocelot.cpbd.io.get_elements(lattice)
ocelot.cpbd.io.lat2input(lattice, tws0=None)

returns python input string for the lattice in the lat object

ocelot.cpbd.io.load_particle_array(filename, print_params=False)

Universal function to load beam file, *.ast (ASTRA), *.fmt1 (CSRTrack) or *.npz format

Note that downloading ParticleArray from the astra file (.ast) and saving it back does not give the same distribution. The difference arises because the array of particles does not have a reference particle, and in this case the first particle is used as a reference.

Parameters

filename – path to file, filename.ast or filename.npz

Returns

ParticleArray

ocelot.cpbd.io.load_particle_array_from_npz(filename, print_params=False)

Load beam file in npz format and return ParticleArray

Parameters

filename

Returns

ocelot.cpbd.io.matrix_def_string(element, params)
ocelot.cpbd.io.pprinting(element, element_type, params)
ocelot.cpbd.io.print_elements(elements_dict)
ocelot.cpbd.io.rem_drifts(lat)
ocelot.cpbd.io.save_particle_array(filename, p_array)

Universal function to save beam file, *.ast (ASTRA), *.fmt1 (CSRTrack) or *.npz format

Note that downloading ParticleArray from the astra file (.ast) and saving it back does not give the same distribution. The difference arises because the array of particles does not have a reference particle, and in this case the first particle is used as a reference.

Parameters

filename – path to file, filename.ast or filename.npz

Returns

ParticleArray

ocelot.cpbd.io.save_particle_array2npz(filename, p_array)
ocelot.cpbd.io.sort_elements(elements)
ocelot.cpbd.io.twiss2input(tws)
ocelot.cpbd.io.write_lattice(lattice, tws0=None, file_name='lattice.py', remove_rep_drifts=True, power_supply=False)

saves lattice as python imput file lattice - MagneticLattice file_name - name of the file remove_rep_drifts - if True, remove the drifts with the same lengths from the lattice drifts definition

ocelot.cpbd.io.write_power_supply_id(lattice, lines=[])

ocelot.cpbd.magnetic_lattice module

class ocelot.cpbd.magnetic_lattice.CouplerKickUtil

Bases: ocelot.cpbd.magnetic_lattice.EndElements

static add(lattice)
static check(lattice)

if there are CouplerKicks on the ends of Cavities return True, else False

suffix_1 = '_ck1'
suffix_2 = '_ck2'
static update_first(ckick, cavity)
static update_last(ckick, cavity)
class ocelot.cpbd.magnetic_lattice.EdgeUtil

Bases: ocelot.cpbd.magnetic_lattice.EndElements

static add(lattice)
static check(lattice)

if there are edges on the ends of dipoles return True, else False

static name_suffix_1()
static name_suffix_2()
suffix_1 = '_e1'
suffix_2 = '_e2'
static update_first(edge, bend)
static update_last(edge, bend)
class ocelot.cpbd.magnetic_lattice.EndElements

Bases: object

static add(lattice)
static check(lattice)
suffix_1 = '_1'
suffix_2 = '_2'
static update_first(end_element, body)
static update_last(end_element, body)
class ocelot.cpbd.magnetic_lattice.MagneticLattice(sequence, start=None, stop=None, method=<ocelot.cpbd.optics.MethodTM object>)

Bases: object

sequence - list of the elements, start - first element of lattice. If None, then lattice starts from first element of sequence, stop - last element of lattice. If None, then lattice stops by last element of sequence, method = MethodTM() - method of the tracking.

find_indices(element)
get_sequence_part(start, stop)
update_endings(lat_index, element, body_elements, element_util)
update_transfer_maps()
ocelot.cpbd.magnetic_lattice.exclude_zero_length_element(cell, elem_type=[<class 'ocelot.cpbd.elements.UnknownElement'>, <class 'ocelot.cpbd.elements.Marker'>], except_elems=[])

Exclude zero length elements some types in elem_type

Parameters
  • cell – list, sequence of elements

  • elem_type – list, types of Elements which should be excluded

  • except_elems – list, except elements

Returns

list, new sequence of elements

ocelot.cpbd.magnetic_lattice.flatten(*n)
ocelot.cpbd.magnetic_lattice.lattice_format_converter(elements)
Parameters

elements – lattice in the format: [[elem1, center_pos1], [elem2, center_pos2], [elem3, center_pos3], … ]

Returns

lattice in the format: [elem1, drift1, elem2, drift2, elem3, drift3, …]

ocelot.cpbd.magnetic_lattice.merge_drifts(cell)

Merge neighboring Drifts in one Drift

Parameters

cell – list of element

Returns

new list of elements

ocelot.cpbd.magnetic_lattice.merger(lat, remaining_types=[], remaining_elems=[], init_energy=0.0)

Function to compress the lattice excluding elements by type or by individual elements

Parameters
  • lat – MagneticLattice

  • remaining_types – list, the type of the elements which needed to be untouched others will be “compress” to Matrix element e.g. [Monitor, Quadrupole, Bend, Hcor]

  • remaining_elems – list of elements (ids (str) or object)

  • init_energy – initial energy

Returns

New MagneticLattice

ocelot.cpbd.match module

ocelot.cpbd.match.closed_orbit(lattice, eps_xy=1e-07, eps_angle=1e-07, energy=0)
ocelot.cpbd.match.match(lat, constr, vars, tw, verbose=True, max_iter=1000, method='simplex', weights=<function weights_default>, vary_bend_angle=False, min_i5=False)

Function to match twiss parameters

Parameters
  • lat – MagneticLattice

  • constr

    dictionary, constrains. Example: ‘periodic’:True - means the “match” function tries to find periodic solution at the ends of lattice:

    constr = {elem1:{‘beta_x’:15, ‘beta_y’:2}, ‘periodic’:True}

    ”hard” constrains on the end of elements (elem1, elem2):

    constr = {elem1:{‘alpha_x’:5, ‘beta_y’:5}, elem2:{‘Dx’:0 ‘Dyp’:0, ‘alpha_x’:5, ‘beta_y’:5}}

    or mixture of “soft” and hard constrains:

    constr = {elem1:{‘alpha_x’:[“>”, 5], ‘beta_y’:5}, elem2:{‘Dx’:0 ‘Dyp’:0, ‘alpha_x’:5, ‘beta_y’:[“>”, 5]}}

    in case one needs global control on beta function, the constrains can be written following way.

    constr = {elem1:{‘alpha_x’:5, ‘beta_y’:5}, ‘global’: {‘beta_x’: [‘>’, 10]}}

  • vars – list of elements e.g. vars = [QF, QD] or it can be initial twiss parameters: vars = [[tws0, ‘beta_x’], [tws0, ‘beta_y’], [tws0, ‘alpha_x’], [tws0, ‘alpha_y’]]

  • tw – initial Twiss

  • verbose – allow print output of minimization procedure

  • max_iter

  • method – string, available ‘simplex’, ‘cg’, ‘bfgs’

  • weights

    function returns weights, for example def weights_default(val):

    if val == ‘periodic’: return 10000001.0 if val == ‘total_len’: return 10000001.0 if val in [‘Dx’, ‘Dy’, ‘Dxp’, ‘Dyp’]: return 10000002.0 if val in [‘alpha_x’, ‘alpha_y’]: return 100007.0 if val in [‘mux’, ‘muy’]: return 10000006.0 if val in [‘beta_x’, ‘beta_y’]: return 100007.0 return 0.0001

  • vary_bend_angle – False, allow to vary “angle” of the dipoles instead of the focusing strength “k1”

  • min_i5 – minimization of the radiation integral I5. Can be useful for storage rings.

Returns

result

ocelot.cpbd.match.match_beam(lat, constr, vars, p_array, navi, verbose=True, max_iter=1000, method='simplex', weights=<function weights_default>, vary_bend_angle=False, min_i5=False)

Function to match twiss paramters

Parameters
  • lat – MagneticLattice

  • constr – dict in format {elem1:{‘beta_x’:15, ‘beta_y’:2}, ‘periodic’:True} try to find periodic solution or constr = {elem1:{‘alpha_x’:5, ‘beta_y’:5}, elem2:{‘Dx’:0 ‘Dyp’:0, ‘alpha_x’:5, ‘beta_y’:5} and so on.

  • vars – lsit of elements e.g. vars = [QF, QD]

  • p_array – initial ParticleArray

  • navi – Navigator with added PhysProcess if needed

  • verbose – allow print output of minimization procedure

  • max_iter

  • method – string, available ‘simplex’, ‘cg’, ‘bfgs’

  • weights

    function returns weights, for example def weights_default(val):

    if val == ‘periodic’: return 10000001.0 if val == ‘total_len’: return 10000001.0 if val in [‘Dx’, ‘Dy’, ‘Dxp’, ‘Dyp’]: return 10000002.0 if val in [‘alpha_x’, ‘alpha_y’]: return 100007.0 if val in [‘mux’, ‘muy’]: return 10000006.0 if val in [‘beta_x’, ‘beta_y’]: return 100007.0 return 0.0001

  • vary_bend_angle – False, allow to vary “angle” of the dipoles instead of the focusing strength “k1”

  • min_i5 – minimization of the radiation integral I5. Can be useful for storage rings.

Returns

result

ocelot.cpbd.match.match_matrix(lat, beam, varz, target_matrix)
ocelot.cpbd.match.match_tunes(lat, tw0, quads, nu_x, nu_y, ncells=1, print_proc=0)
ocelot.cpbd.match.weights_default(val)

ocelot.cpbd.moga module

ocelot.cpbd.optics module

class ocelot.cpbd.optics.CavityTM(v=0, freq=0.0, phi=0.0)

Bases: ocelot.cpbd.optics.TransferMap

map4cav(X, E, V, freq, phi, z=0)
class ocelot.cpbd.optics.CorrectorTM(angle_x=0.0, angle_y=0.0, r_z_no_tilt=None, t_mat_z_e=None)

Bases: ocelot.cpbd.optics.SecondTM

kick(X, z, l, angle_x, angle_y, energy)
kick_b(z, l, angle_x, angle_y)
class ocelot.cpbd.optics.CouplerKickTM(v=0, freq=0.0, phi=0.0, vx=0.0, vy=0.0)

Bases: ocelot.cpbd.optics.TransferMap

kick(X, v, phi, energy)
kick_b(v, phi, energy)
class ocelot.cpbd.optics.KickTM(angle=0.0, k1=0.0, k2=0.0, k3=0.0, nkick=1)

Bases: ocelot.cpbd.optics.TransferMap

kick(X, l, angle, k1, k2, k3, energy, nkick=1)

does not work for dipole

kick_apply(X, l, angle, k1, k2, k3, energy, nkick, dx, dy, tilt)
class ocelot.cpbd.optics.MethodTM(params=None)

Bases: object

The class creates a transfer map for elements that depend on user-defined parameters (“parameters”). By default, the parameters = {“global”: TransferMap}, which means that all elements will have linear transfer maps. You can also specify different transfer maps for any type of element.

# use linear matrices for all elements except Sextupole which will have nonlinear kick map (KickTM) method = MethodTM() method.global_method = TransferMap method.params[Sextupole] = KickTM

# All elements are assigned matrices of the second order. # For elements for which there are no matrices of the second order are assigned default matrices, e.g. linear matrices. method2 = MethodTM() method2.global_method = SecondTM

create_tm(element)
set_tm(element, method)
class ocelot.cpbd.optics.MultipoleTM(kn)

Bases: ocelot.cpbd.optics.TransferMap

kick(X, kn)
class ocelot.cpbd.optics.Navigator(lattice)

Bases: object

Navigator defines step (dz) of tracking and which physical process will be applied during each step. lattice - MagneticLattice Attributes:

unit_step = 1 [m] - unit step for all physics processes

Methods:
add_physics_proc(physics_proc, elem1, elem2)

physics_proc - physics process, can be CSR, SpaceCharge or Wake, elem1 and elem2 - first and last elements between which the physics process will be applied.

activate_apertures(start=None, stop=None)

activate apertures if thea exist in the lattice from

Parameters
  • start – element, activate apertures starting form element ‘start’ element

  • stop – element, activate apertures up to ‘stop’ element

Returns

add_physics_proc(physics_proc, elem1, elem2)

Method adds Physics Process.

Parameters
  • physics_proc – PhysicsProc, e.g. SpaceCharge, CSR, Wake …

  • elem1 – the element in the lattice where to start applying the physical process.

  • elem2 – the element in the lattice where to stop applying the physical process, can be the same as starting element.

Returns

check_overjump(dz, processes, phys_steps)
check_proc_bounds(dz, proc_list, phys_steps, active_process)
get_next()
get_phys_procs()

method return list of all physics processes which were added

Returns

list, list of PhysProc(s)

get_proc_list()
go_to_start()
hard_edge_step(dz)
remove_used_processes(processes)

in case physics processes are applied and do not more needed they are removed from table

Parameters

processes – list of processes are about to apply

Returns

None

reset_position()

method to reset Navigator position. :return:

class ocelot.cpbd.optics.ProcessTable(lattice)

Bases: object

add_physics_proc(physics_proc, elem1, elem2)
searching_kick_proc(physics_proc, elem1)

function finds kick physics process. Kick physics process applies kick only once between two elements with zero length (e.g. Marker) or at the beginning of the element if it is the same element, others physics processes are applied during finite lengths. :return:

class ocelot.cpbd.optics.PulseTM(kn)

Bases: ocelot.cpbd.optics.TransferMap

mul_parray(rparticles, energy=0.0)
class ocelot.cpbd.optics.RungeKuttaTM(s_start=0, npoints=200)

Bases: ocelot.cpbd.optics.TransferMap

class ocelot.cpbd.optics.RungeKuttaTrTM(s_start=0, npoints=200)

Bases: ocelot.cpbd.optics.RungeKuttaTM

THe same method as RungeKuttaTM but only transverse dynamics is included, longitudinal dynamics is skipped

class ocelot.cpbd.optics.SecondOrderMult

Bases: object

The class includes three different methods for transforming the particle coordinates:

  1. NUMBA module - DEACTIVATED, because new numpy implementation shows higher performance.

    Slightly faster than NUMPY for simulations with a large number of time steps. Uses full matrix multiplication.

  2. NUMPY module

    Base method to be used. Uses full matrix multiplication.

numba_apply(X, R, T)
numpy_apply(X, R, T)
class ocelot.cpbd.optics.SecondTM(r_z_no_tilt, t_mat_z_e)

Bases: ocelot.cpbd.optics.TransferMap

t_apply(R, T, X, dx, dy, tilt, U5666=0.0)
class ocelot.cpbd.optics.TWCavityTM(l=0, v=0, phi=0, freq=0)

Bases: ocelot.cpbd.optics.TransferMap

f_entrance(z, V, E, phi=0.0)
f_exit(z, V, E, phi=0.0)
tw_cavity_R_z(z, V, E, freq, phi=0.0)
Parameters
  • z – length

  • de – delta E

  • f – frequency

  • E – initial energy

Returns

matrix

class ocelot.cpbd.optics.TransferMap

Bases: object

TransferMap is a basic linear transfer map for all elements.

apply(prcl_series)
Parameters

prcl_series – can be list of Particles [Particle_1, Particle_2, … ] or ParticleArray

Returns

None

map_x_twiss(tws0)
mul_p_array(rparticles, energy=0.0)
class ocelot.cpbd.optics.UndulatorTestTM(lperiod, Kx, ax=0, ndiv=10)

Bases: ocelot.cpbd.optics.TransferMap

map4undulator(u, z, lperiod, Kx, ax, energy, ndiv)
ocelot.cpbd.optics.fodo_parameters(betaXmean=36.0, L=10.0, verbose=False)
ocelot.cpbd.optics.get_map(lattice, dz, navi)
ocelot.cpbd.optics.lattice_transfer_map(lattice, energy)

Function calculates transfer maps, the first and second orders (R, T), for the whole lattice. Second order matrices are attached to lattice object: lattice.T_sym - symmetric second order matrix lattice.T - second order matrix lattice.R - linear R matrix

Parameters
  • lattice – MagneticLattice

  • energy – the initial electron beam energy [GeV]

Returns

R - matrix

ocelot.cpbd.optics.merge_maps(t_maps)
ocelot.cpbd.optics.periodic_twiss(tws, R)

initial conditions for a periodic Twiss solution

ocelot.cpbd.optics.sym_matrix(T)
ocelot.cpbd.optics.trace_obj(lattice, obj, nPoints=None)

track object through the lattice obj must be Twiss or Particle

ocelot.cpbd.optics.trace_z(lattice, obj0, z_array)

Z-dependent tracer (twiss(z) and particle(z)) usage: twiss = trace_z(lattice,twiss_0, [1.23, 2.56, …]) , to calculate Twiss params at 1.23m, 2.56m etc.

ocelot.cpbd.optics.transfer_map_rotation(R, T, tilt)
ocelot.cpbd.optics.transfer_maps_mult(Ra, Ta, Rb, Tb)

cell = [A, B] Rc = Rb * Ra :param Ra: :param Ta: :param Rb: :param Tb: :param sym_flag: :return:

ocelot.cpbd.optics.transfer_maps_mult_py(Ra, Ta, Rb, Tb)

cell = [A, B] Rc = Rb * Ra :param Ra: :param Ta: :param Rb: :param Tb: :param sym_flag: :return:

ocelot.cpbd.optics.transform_vec_ent(X, dx, dy, tilt)
ocelot.cpbd.optics.transform_vec_ext(X, dx, dy, tilt)
ocelot.cpbd.optics.twiss(lattice, tws0=None, nPoints=None)

twiss parameters calculation

Parameters
  • lattice – lattice, MagneticLattice() object

  • tws0 – initial twiss parameters, Twiss() object. If None, try to find periodic solution.

  • nPoints – number of points per cell. If None, then twiss parameters are calculated at the end of each element.

Returns

list of Twiss() objects

ocelot.cpbd.optics.twiss_fast(lattice, tws0=None)

twiss parameters calculation

Parameters
  • lattice – lattice, MagneticLattice() object

  • tws0 – initial twiss parameters, Twiss() object. If None, try to find periodic solution.

  • nPoints – number of points per cell. If None, then twiss parameters are calculated at the end of each element.

Returns

list of Twiss() objects

ocelot.cpbd.optics.unsym_matrix(T)

ocelot.cpbd.orbit_correction module

class ocelot.cpbd.orbit_correction.LInfinityNorm(epsilon_x=0.001, epsilon_y=0.001)

Bases: ocelot.cpbd.orbit_correction.OrbitSVD

apply(resp_matrix, orbit, weights=None)
class ocelot.cpbd.orbit_correction.MICADO(epsilon_x=0.001, epsilon_y=0.001, epsilon_ksi=1e-05)

Bases: ocelot.cpbd.orbit_correction.OrbitSVD

Iterative method based on CERN-ISR-MA/73-17, 1973. Strategy: 1. each corrector is tested singly. For each corrector we have residual vector: r = b + A * x.

Corrector (x_j) and column A_j (response matrix) which correspond to minimum residual are exchanged with first position.

  1. Two correctors are tested. the first one which is defined from step 1 and second one iteratively is tested

    j = 2, … n

The iteration is stopped when the peak-to-peak amplitude of the residual vector is smaller than a fixed value given in advance.

apply(resp_matrix, orbit, weights=None)
solver_lstsq(resp_matrix, orbit, weights)
solver_svd(resp_matrix, orbit, weights)
static swap_columns(m, col1, col2)

method to swap columns in matrix m :param m: matrix :param col1: index :param col2: index :return:

class ocelot.cpbd.orbit_correction.NewOrbit(lattice, rm_method=None, disp_rm_method=None, empty=False)

Bases: ocelot.cpbd.orbit_correction.Orbit

class ocelot.cpbd.orbit_correction.Orbit(lattice, rm_method=None, disp_rm_method=None, empty=False)

Bases: object

combine_matrices(mat1, mat2)
Parameters
  • mat1

  • mat2

Returns

correction(alpha=0, beta=0, p_init=None, print_log=True)

Method to find corrector kicks using SVD. bpm weights are ignored for a moment but everything ready to immplement.

Parameters
  • alpha – 0 - 1, trade off between orbit and dispersion correction, 0 - only orbit, 1 - only dispersion

  • epsilon_x – cut s-matrix diag for x-plane, if s[i] < s_max * epsilon: s_inv[i] = 0. else s_inv[i] = 1/s[i]

  • epsilon_y – cut s-matrix diag for y-plane, if s[i] < s_max * epsilon: s_inv[i] = 0. else s_inv[i] = 1/s[i]

  • beta – weight for suppress large kicks

  • p_init – particle initial conditions. Removed in that version.

  • print_log

Returns

create_bpms(bpm_list=None)

Search bpm in the lattice and create list of bpms :param lattice: class MagneticLattice :return: self.bpms - list of BPMs (class BPM)

create_correctors(cor_list=None)

Search correctors (horizontal and vertical) in the lattice and create list of hcors and list of vcors :param lattice: class MagneticLattice :return:

get_dispersion()
get_orbit()
get_ref_orbit()
setup_disp_response_matrix()
setup_response_matrix()
class ocelot.cpbd.orbit_correction.OrbitSVD(epsilon_x=0.001, epsilon_y=0.001)

Bases: object

apply(resp_matrix, orbit, weights=None)
ocelot.cpbd.orbit_correction.change_corrector(corrector, lattice)
ocelot.cpbd.orbit_correction.change_quad_position(quad, lattice, dx=0.0, dy=0.0)
ocelot.cpbd.orbit_correction.elem_response_matrix(orbit, lattice, p_init, elem_types, remove_elem)
ocelot.cpbd.orbit_correction.measure_response_matrix(orbit, lattice)
ocelot.cpbd.orbit_correction.normal(loc=0.0, scale=1.0, size=None)

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2]_, is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]_.

Note

New code should use the normal method of a default_rng() instance instead; please see the random-quick-start.

locfloat or array_like of floats

Mean (“centre”) of the distribution.

scalefloat or array_like of floats

Standard deviation (spread or “width”) of the distribution. Must be non-negative.

sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

outndarray or scalar

Drawn samples from the parameterized normal distribution.

scipy.stats.normprobability density function, distribution or

cumulative density function, etc.

Generator.normal: which should be used for new code.

The probability density for the Gaussian distribution is

\[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },\]

where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance.

The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x - \sigma\) [2]_). This implies that normal is more likely to return samples lying close to the mean, rather than those far away.

1

Wikipedia, “Normal distribution”, https://en.wikipedia.org/wiki/Normal_distribution

2

P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.

Draw samples from the distribution:

>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

Verify the mean and the variance:

>>> abs(mu - np.mean(s))
0.0  # may vary
>>> abs(sigma - np.std(s, ddof=1))
0.1  # may vary

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
>>> plt.show()

Two-by-four array of samples from N(3, 6.25):

>>> np.random.normal(3, 2.5, size=(2, 4))
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],   # random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]])  # random
ocelot.cpbd.orbit_correction.quad_response_matrix(orbit, lattice)
ocelot.cpbd.orbit_correction.restore_corrector(corrector, lattice)

ocelot.cpbd.physics_proc module

class ocelot.cpbd.physics_proc.BeamAnalysis(filename)

Bases: ocelot.cpbd.physics_proc.PhysProc

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

finalize()

the method is called at the end of tracking

Returns

class ocelot.cpbd.physics_proc.BeamTransform(tws=None, x_opt=None, y_opt=None)

Bases: ocelot.cpbd.physics_proc.PhysProc

Beam matching

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

property twiss
class ocelot.cpbd.physics_proc.Chicane(r56, t566=0.0)

Bases: ocelot.cpbd.physics_proc.PhysProc

simple physics process to simulate longitudinal dynamics in chicane

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

class ocelot.cpbd.physics_proc.EmptyProc(step=1)

Bases: ocelot.cpbd.physics_proc.PhysProc

class ocelot.cpbd.physics_proc.LaserHeater(step=1)

Bases: ocelot.cpbd.physics_proc.LaserModulator

class ocelot.cpbd.physics_proc.LaserModulator(step=1)

Bases: ocelot.cpbd.physics_proc.PhysProc

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

lambda_ph(energy)

Wavelength of the laser pulse

Parameters

energy – in [GeV] - beam energy

Returns

wavelength in [m]

r56(energy)

Method calculate R56 of the undulator

Parameters

energy – in [GeV] - beam energy

Returns

R56 in [m]

class ocelot.cpbd.physics_proc.PhaseSpaceAperture(step=1)

Bases: ocelot.cpbd.physics_proc.PhysProc

Method to cut beam in longitudinal (by default), horizontal or/and vertical direction

Parameters
  • longitudinal – True, cutting in longitudinal direction

  • vertical – False, cutting in vertical direction

  • horizontal – False, cutting in horizontal direction

  • taumin – -5 longitudinal plane in [rms] from center of mass

  • taumax – 5 longitudinal plane in [rms] from center of mass

  • xmin – -5 horizontal plane in [rms] from center of mass

  • xmax – 5 horizontal plane in [rms] from center of mass

  • ymin – -5 vertical plane in [rms] from center of mass

  • ymax – 5 vertical plane in [rms] from center of mass

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

class ocelot.cpbd.physics_proc.PhysProc(step=1)

Bases: object

Parent class for all Physics processes

Method prepare(self, lat)
  • the method is called at the moment of Physics Process addition to Navigator class.

Method apply(self, p_array, dz)
  • the method is called on every step.

Attribute step
  • number of steps in [Navigator.unit_step] self.step*Navigator.unit_step = [m]

Attribute indx0
  • number of start element in lattice.sequence - assigned in navigator.add_physics_proc()

Attribute indx1
  • number of stop element in lattice.sequence - assigned in navigator.add_physics_proc()

Attribute s_start
  • position of start element in lattice - assigned in navigator.add_physics_proc()

Attribute s_stop
  • position of stop element in lattice.sequence - assigned in navigator.add_physics_proc()

Attribute z0
  • current position of navigator - assigned in track.track() before p.apply()

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

finalize(*args, **kwargs)

the method is called at the end of tracking

Returns

prepare(lat)

method is called at the moment of Physics Process addition to Navigator class.

Parameters

lat

Returns

class ocelot.cpbd.physics_proc.RectAperture(xmin=- inf, xmax=inf, ymin=- inf, ymax=inf, step=1)

Bases: ocelot.cpbd.physics_proc.PhysProc

Method to cut beam in horizontal or/and vertical direction

Parameters
  • xmin – -np.inf horizontal plane in [m]

  • xmax – np.inf horizontal plane in [m]

  • ymin – -np.inf vertical plane in [m]

  • ymax – np.inf vertical plane in [m]

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

class ocelot.cpbd.physics_proc.SaveBeam(filename)

Bases: ocelot.cpbd.physics_proc.PhysProc

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

class ocelot.cpbd.physics_proc.SmoothBeam

Bases: ocelot.cpbd.physics_proc.PhysProc

Physics Process for the beam smoothing. Can be applied when number of particles is not enough.

Attribute mslice

number of particles in the slice

# lat is the MagneticLattice navi = Navigator(lat)

smooth = SmoothBeam() smooth.mslice = 10000

navi.add_physics_process(smooth, start=elem, stop=elem) # elem is the lattice element where you want to apply smoothing

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

class ocelot.cpbd.physics_proc.SpontanRadEffects(K=0.0, lperiod=0.0, type='planar')

Bases: ocelot.cpbd.physics_proc.PhysProc

Effects of the spontaneous radiation: energy loss and quantum diffusion

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

energy_loss_und(energy, dz)
sigma_gamma_quant(energy, dz)

rate of energy diffusion

Parameters
  • energy – electron beam energy

  • Kx – undulator parameter

  • lperiod – undulator period

  • dz – length of the

Returns

sigma_gamma/gamma

ocelot.cpbd.r_matrix module

ocelot.cpbd.r_matrix.create_r_matrix(element)
ocelot.cpbd.r_matrix.rot_mtx(angle)
ocelot.cpbd.r_matrix.uni_matrix(z, k1, hx, sum_tilts=0.0, energy=0.0)

universal matrix. The function creates R-matrix from given parameters. r = element.l/element.angle +K - focusing lens, -K - defoc

Parameters
  • z – element length [m]

  • k1 – quadrupole strength [1/m**2]

  • hx – the curvature (1/r) of the element [1/m]

  • sum_tilts – rotation relative to longitudinal axis [rad]

  • energy – the beam energy [GeV]

Returns

R-matrix [6, 6]

ocelot.cpbd.response_matrix module

class ocelot.cpbd.response_matrix.LinacDisperseSimRM(lattice, hcors, vcors, bpms)

Bases: ocelot.cpbd.response_matrix.MeasureResponseMatrix

calculate(tw_init=None)

calculation of ideal dispersive response matrix

Parameters
  • lattice – class MagneticLattice

  • tw_init – if tw_init == None, function tries to find periodical solution

Returns

orbit.resp

class ocelot.cpbd.response_matrix.LinacDisperseTmatrixRM(lattice, hcors, vcors, bpms)

Bases: ocelot.cpbd.response_matrix.MeasureResponseMatrix

calculate(tw_init=None)

calculation of ideal response matrix

Parameters
  • lattice – class MagneticLattice

  • tw_init – if tw_init == None, function tries to find periodical solution

Returns

orbit.resp

class ocelot.cpbd.response_matrix.LinacOpticalRM(lattice, hcors, vcors, bpms)

Bases: ocelot.cpbd.response_matrix.MeasureResponseMatrix

calculate(tw_init=None)

calculation of ideal response matrix

Parameters
  • lattice – class MagneticLattice

  • tw_init – if tw_init == None, function tries to find periodical solution

Returns

orbit.resp

class ocelot.cpbd.response_matrix.LinacRmatrixRM(lattice, hcors, vcors, bpms)

Bases: ocelot.cpbd.response_matrix.MeasureResponseMatrix

calculate(tw_init=None)

calculation of ideal response matrix

Parameters
  • lattice – class MagneticLattice

  • tw_init – if tw_init == None, initial beam energy is ZERO

Returns

orbit.resp

class ocelot.cpbd.response_matrix.LinacSimRM(lattice, hcors, vcors, bpms)

Bases: ocelot.cpbd.response_matrix.MeasureResponseMatrix

calculate(tw_init=None)

calculation of ideal response matrix

Parameters
  • lattice – class MagneticLattice

  • tw_init – if tw_init == None, function tries to find periodical solution

Returns

orbit.resp

class ocelot.cpbd.response_matrix.MeasureResponseMatrix(lattice, hcors, vcors, bpms)

Bases: object

calculate()
optical_func_params(tw_init=None)

Optical function parameters for correctors and bpms. It is needed for calculation of ideal response matrix: defining beta functions on the azimuth of correctors and bpms: beta_x, beta_y; defining phase shift between origin of lattice and element: mu_x, mu_y; defining tunes of beta functions of whole lattice: nu_x, nu_y = mu(totalLen)/(2*pi)

Parameters

lattice – class MagneticLattice

Returns

read_virtual_dispersion(E0)
read_virtual_orbit(p_init=None, write2bpms=True)

searching closed orbit by function closed_orbit(lattice) and searching coordinates of beam at the bpm positions

Parameters

lattice – class MagneticLattice

Returns

orbit.bpms

class ocelot.cpbd.response_matrix.ResponseMatrix(method=None)

Bases: object

bpm2x_name(bpm_id)

Transform bpm id to a name how it use in a control system to get horizontal beam position :param bpm_id: :return: channel for X position

bpm2y_name(bpm_id)

Transform bpm id to a name how it use in a control system to get vertical beam position

Parameters

bpm_id

Returns

channel for Y position

calculate(tw_init=None)

rewrites cor_name, bpm_name and matrix

Parameters

method

Returns

clean_rm(coupling=True)
compare(rmatrix, absolut=0.001, relative=0.1)
data2df(matrix, bpm_names, cor_names)
df2data()
dump(filename)
extract(cor_list, bpm_list)
extract_df_slice(cor_list, bpm_list)
get_matrix()
inject(cor_list, bpm_list, inj_matrix)

Update some elements of the response matrix

Parameters
  • cor_list

  • bpm_list

  • inj_matrix

Returns

load(filename)
retrieve_from_scan(df_scan)
show(list_cor=None, list_bpm=None)
xy_names2bpm_id(xy_names)

transform BPM channels to bpm ids

Parameters

xy_names

Returns

class ocelot.cpbd.response_matrix.ResponseMatrixJSON(method=None)

Bases: object

calculate(tw_init=None)

rewrites cor_name, bpm_name and matrix

Parameters

method

Returns

compare(rmatrix, absolut=0.001, relative=0.1)
dump(filename)
extract(cor_list, bpm_list)
get_matrix()
inject(cor_list, bpm_list, inj_matrix)

Update some elements of the response matrix

Parameters
  • cor_list

  • bpm_list

  • inj_matrix

Returns

load(filename)
show(list_cor=None, list_bpm=None)
class ocelot.cpbd.response_matrix.RingRM(lattice, hcors, vcors, bpms)

Bases: ocelot.cpbd.response_matrix.MeasureResponseMatrix

calculate(tw_init=None)

calculation of ideal response matrix

Parameters
  • lattice – class MagneticLattice

  • tw_init – if tw_init == None, function tries to find periodical solution

Returns

orbit.resp

ocelot.cpbd.reswake module

writen by I. Zagorodnov, DESY and S.Tomin XFEL, 2015.

ocelot.cpbd.reswake.LossShape(bunch, wake)

loss, spread, peak dimensions:

wake - m , Volt/pC out - V/pC;

ocelot.cpbd.reswake.ResistiveZaZb(xb, bunch, a, conductivity, tau, Ind)
Parameters
  • xb

  • bunch

  • a – tube radius

  • conductivity

  • tau

  • Ind

Returns

ocelot.cpbd.reswake.imp_resistiveAC_SI(f, cond, a, tau, L)

resistive impedance of round pipe (in SI Units) dimensions: f - Hertz

cond - in 1/Second a - pipe radius in m tau - the relaxation time in s L-inductive for dielectric layer

ocelot.cpbd.reswake.impedance2wake(f, y)
Fourier transform with exp(-iwt)

f - Hz y - Om s - Meter w - V/C

ocelot.cpbd.reswake.pipe_wake(z, current, tube_radius, tube_len, conductivity, tau, roughness, d_oxid)
Parameters
  • z

  • current

  • tube_radius

  • tube_len

  • conductivity

  • tau

  • roughness

  • d_oxid

Returns

ocelot.cpbd.reswake.wake2impedance(s, w)
Fourier transform with exp(iwt)

s - Meter w - V/C f - Hz y - Om

ocelot.cpbd.reswake.xfel_pipe_wake(s, current)
Parameters
  • s – smaller number (usually negative) is the head

  • current

Returns

s, current, wake

ocelot.cpbd.sc module

@author: Igor Zagorodnov @ Martin Dohlus Created on 27.03.2015 Revision on 01.06.2017: coordinate transform to the velocity direction 2019: Added LSC: S. Tomin and I. Zagorodnov

class ocelot.cpbd.sc.LSC(step=1)

Bases: ocelot.cpbd.physics_proc.PhysProc

Longitudinal Space Charge smooth_param - 0.1 smoothing parameter, resolution = np.std(p_array.tau())*smooth_param

apply(p_array, dz)

wakes in V/pC

Parameters
  • p_array

  • dz

Returns

imp_lsc(gamma, sigma, w, dz)

gamma - energy sigma - transverse RMS size of the beam w - omega = 2*pi*f

imp_step_lsc(gamma, rb, w, dz)

longitudinal space-charge impedance in case of a stepped profile bunch

gamma - energy rb - transverse radius of the beam w - omega = 2*pi*f

impedance2wake(f, y)

Fourier transform with exp(-iwt) f - Hz y - Om s - Meter w - V/C

wake2impedance(s, w)

Fourier transform with exp(iwt) s - Meter w - V/C f - Hz y - Om

wake_lsc(s, bunch, gamma, sigma, dz)
class ocelot.cpbd.sc.SpaceCharge(step=1)

Bases: ocelot.cpbd.physics_proc.PhysProc

Space Charge physics process

Attributes:

self.step = 1 [in Navigator.unit_step] - step of the Space Charge kick applying self.nmesh_xyz = [63, 63, 63] - 3D mesh

Description:

The space charge forces are calculated by solving the Poisson equation in the bunch frame.

Then the Lorentz transformed electromagnetic field is applied as a kick in the laboratory frame. For the solution of the Poisson equation we use an integral representation of the electrostatic potential by convolution of the free-space Green’s function with the charge distribution. The convolution equation is solved with the help of the Fast Fourier Transform (FFT). The same algorithm for solution of the 3D Poisson equation is used, for example, in ASTRA

apply(p_array, zstep)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

el_field(X, Q, gamma, nxyz)
potential(q, steps)
prepare(lat)

method is called at the moment of Physics Process addition to Navigator class.

Parameters

lat

Returns

sym_kernel(ijk2, hxyz)
ocelot.cpbd.sc.smooth_z(Zin, mslice)

ocelot.cpbd.touschek module

ocelot.cpbd.touschek.B1()
ocelot.cpbd.touschek.B2()
ocelot.cpbd.touschek.F(tm, B1, B2)
ocelot.cpbd.touschek.t_touschek(tws, beam)

Touschek lifetime Piwinski DESY 98-179

ocelot.cpbd.track module

class ocelot.cpbd.track.Track_info(particle, x=0.0, y=0.0)

Bases: object

get_x()
get_xp()
get_y()
get_yp()
ocelot.cpbd.track.aperture_limit(lat, xlim=1, ylim=1)
ocelot.cpbd.track.arg_peaks(data, extrema_chk=1)

the function search peaks of spectrum and return positions of all peaks if extrema_chk == 1 uses numpy module if extrema_chk == 0 uses independent code (see below)

ocelot.cpbd.track.contour_da(track_list, nturns, lvl=0.9)

the function defines contour of DA. If particle “lived” > lvl*nturns then we set up nturns if particle “lived” < lvl*nturns then we set up 0

ocelot.cpbd.track.create_track_list(x_array, y_array, p_array, energy=0.0)

the function create list of Pxy

ocelot.cpbd.track.da_mpi(lat, nturns, x_array, y_array, errors=None, nsuperperiods=1)
ocelot.cpbd.track.ellipse_track_list(beam, n_t_sigma=3, num=1000, type='contour')
ocelot.cpbd.track.find_highest(sorted_posns, value, diap)

input: 1D array and value the function searches highest value in the array to the given value

ocelot.cpbd.track.find_nearest(positions, value)

input: 1D array and value the function searches nearest value in the array to the given value

ocelot.cpbd.track.fma(lat, nturns, x_array, y_array, nsuperperiods=1)
ocelot.cpbd.track.freq_analysis(track_list, lat, nturns, harm=True, diap=0.1, nearest=False, nsuperperiods=1)
ocelot.cpbd.track.harmonic_position(data1D, nu=None, diap=0.1, nearest=False)

function searches three highest harmonics and return: a. the highest if nu == None b. the nearest harmonics to the nu (if nu != None)

ocelot.cpbd.track.lattice_track(lat, p)
ocelot.cpbd.track.merge_drifts(lat)
ocelot.cpbd.track.nearest_particle(track_list, xi, yi)
ocelot.cpbd.track.normal(loc=0.0, scale=1.0, size=None)

Draw random samples from a normal (Gaussian) distribution.

The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2]_, is often called the bell curve because of its characteristic shape (see the example below).

The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]_.

Note

New code should use the normal method of a default_rng() instance instead; please see the random-quick-start.

locfloat or array_like of floats

Mean (“centre”) of the distribution.

scalefloat or array_like of floats

Standard deviation (spread or “width”) of the distribution. Must be non-negative.

sizeint or tuple of ints, optional

Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

outndarray or scalar

Drawn samples from the parameterized normal distribution.

scipy.stats.normprobability density function, distribution or

cumulative density function, etc.

Generator.normal: which should be used for new code.

The probability density for the Gaussian distribution is

\[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },\]

where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance.

The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x - \sigma\) [2]_). This implies that normal is more likely to return samples lying close to the mean, rather than those far away.

1

Wikipedia, “Normal distribution”, https://en.wikipedia.org/wiki/Normal_distribution

2

P. R. Peebles Jr., “Central Limit Theorem” in “Probability, Random Variables and Random Signal Principles”, 4th ed., 2001, pp. 51, 51, 125.

Draw samples from the distribution:

>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)

Verify the mean and the variance:

>>> abs(mu - np.mean(s))
0.0  # may vary
>>> abs(sigma - np.std(s, ddof=1))
0.1  # may vary

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
...          linewidth=2, color='r')
>>> plt.show()

Two-by-four array of samples from N(3, 6.25):

>>> np.random.normal(3, 2.5, size=(2, 4))
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],   # random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]])  # random
ocelot.cpbd.track.phase_space_transform(x, y, tws)

curved line of second order a11*x**2 + a22*y**2 + 2*a12*x*y + 2*a13*x + 2*a23*y + a33 = 0 gamma*x**2 + 2*alpha*x*x’ + beta*x’**2 = const

ocelot.cpbd.track.spectrum(data1D)

input: 1D sample data output: frequency and fourier transform

ocelot.cpbd.track.stable_particles(track_list, nturns)
ocelot.cpbd.track.track(lattice, p_array, navi, print_progress=True, calc_tws=True, bounds=None)

tracking through the lattice

Parameters
  • lattice – Magnetic Lattice

  • p_array – ParticleArray

  • navi – Navigator

  • print_progress – True, print tracking progress

  • calc_tws – True, during the tracking twiss parameters are calculated from the beam distribution

  • bounds – None, optional, [left_bound, right_bound] - bounds in units of std(p_array.tau())

Returns

twiss_list, ParticleArray. In case calc_tws=False, twiss_list is list of empty Twiss classes.

ocelot.cpbd.track.track_nturns(lat, nturns, track_list, nsuperperiods=1, save_track=True, print_progress=True)
ocelot.cpbd.track.track_nturns_mpi(mpi_comm, lat, nturns, track_list, errors=None, nsuperperiods=1, save_track=True)
ocelot.cpbd.track.tracking_step(lat, particle_list, dz, navi)

tracking for a fixed step dz :param lat: Magnetic Lattice :param particle_list: ParticleArray or Particle list :param dz: step in [m] :param navi: Navigator :return: None

ocelot.cpbd.track.update_effective_beta(beam, lat)

ocelot.cpbd.wake3D module

Created on 17.05.2016 @author: Igor Zagorodnov Added wake table WakeTableDechirperOffAxis on 11.2019 @authors: S. Tomin and I. Zagorodnov

ocelot.cpbd.wake3D.Der(x, y)
ocelot.cpbd.wake3D.Int1(x, y)
ocelot.cpbd.wake3D.Int1h(h, y)
class ocelot.cpbd.wake3D.Wake(step=1)

Bases: ocelot.cpbd.physics_proc.PhysProc

The wake field impact on the beam is included as series of kicks. In order to take into account the impact of the wake field on the beam the longitudinal wake function of point charge through the second order Taylor expansion is used. In general case it uses 13 one-dimensional functions to represent the longitudinal component of the wake function for arbitrary sets of the source and the wittness particles near to the reference axis.

w_sampling = 500 - defines the number of the equidistant sampling points for the one-dimensional

wake coefficients in the Taylor expansion of the 3D wake function.

filter_order = 20 - smoothing filter order wake_table = None - wake table [WakeTable()] factor = 1. - scaling coefficient TH - list from WakeTable, (T, H): T- table of wakes coefs, H - matrix of the coefs place in T

add_total_wake(X, Y, Z, q, TH, Ns, NF)
add_wake(I, T)

[x, W] = AddWake(I, T) :param I: wake table in V/C, W in V (R, L, Cinv, nm, W0, N0, W1, N1) :param T: wake table in V/C, W in V :return:

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

convolution(xu, u, xw, w)
get_long_wake(current_profile)

method to extract a longitudinal wake from the Table for specific current profile

Parameters

current_profile – 2D array with shape (n, 2) where first column is position and second is a beam current

Returns

wake

prepare(lat)

method is called at the moment of Physics Process addition to Navigator class.

Parameters

lat

Returns

wake_convolution(xb, bunch, xw, wake)
class ocelot.cpbd.wake3D.WakeKick(factor=1)

Bases: ocelot.cpbd.wake3D.Wake

apply(p_array, dz)

the method is called on every step.

Parameters
  • p_array

  • dz

Returns

class ocelot.cpbd.wake3D.WakeTable(wake_file=None)

Bases: object

WakeTable(wake_file) - load and prepare wake table wake_file - path to the wake table

load_table(wake_file)
process_wake_table(wake_table)
Parameters

wake_file – file name

Returns

(T, H): T- table of wakes coefs, H - matrix of the coefs place in T

read_file(wake_file)
class ocelot.cpbd.wake3D.WakeTableDechirperOffAxis(b=0.0005, a=0.01, width=0.02, t=0.00025, p=0.0005, length=1, sigma=3e-05, orient='horz')

Bases: ocelot.cpbd.wake3D.WakeTable

WakeTableDechirperOffAxis() - creates two wake tables for horizontal and vertical corrugated plates. Based on https://doi.org/10.1016/j.nima.2016.09.001 and SLAC-PUB-16881

Parameters
  • b – distance from the plate in [m]

  • a – half gap between plates in [m]

  • width – width of the corrugated structure in [m]

  • t – longitudinal gap in [m]

  • p – period of corrugation in [m]

  • length – length of the corrugated structure in [m]

  • sigma – characteristic (rms) longitudinal beam size in [m]

  • orient – “horz” or “vert” plate orientation

Returns

hor_wake_table, vert_wake_table

calculate_wake_tables(b, a, width, t, p, length, sigma)

Function creates two wake tables for horizontal and vertical corrugated plates

Parameters
  • b – distance from the plate in [m]

  • a – half gap between plates in [m]

  • width – width of the corrugated structure in [m]

  • t – longitudinal gap in [m]

  • p – period of corrugation in [m]

  • length – length of the corrugated structure in [m]

  • sigma – characteristic longitudinal beam size in [m]]

  • filename – save to files if filename is not None

Returns

hor_wake_table, vert_wake_table

ocelot.cpbd.wake3D.project_on_grid(Ro, I0, dI0, q_array)

Simple function to project particles charge on grid

Parameters
  • Ro – grid

  • I0 – grid index for each particle

  • dI0 – coefficient how particle close to Ro[i+1]. Example: particle i, dI0=0.7 -> Ro[i]———dI0[i]–Ro[i+1]

  • q_array – charge array in [C]

Returns

Ro

ocelot.cpbd.wake3D.project_on_grid_py(Ro, I0, dI0, q_array)

Simple function to project particles charge on grid

Parameters
  • Ro – grid

  • I0 – grid index for each particle

  • dI0 – coefficient how particle close to Ro[i+1]. Example: particle i, dI0=0.7 -> Ro[i]———dI0[i]–Ro[i+1]

  • q_array – charge array in [C]

Returns

Ro

ocelot.cpbd.wake3D.s2current(s_array, q_array, n_points, filter_order, mean_vel)

I = s2current(P0,q,Ns,NF) :param s_array: s-vector, coordinates in longitudinal direction :param q_array: charge-vector :param n_points: number of sampling points :param filter_order: filter order :param mean_vel: mean velocity :return:

ocelot.cpbd.wake3D.triang_filter(x, filter_order)

Module contents