Track¶
Basics¶
The track function can be used for all particle tracking, including spin tracking with
radiation, intra-beam scattering, etc. At the highest level, all one needs to do is provide
the beamline to track through and a matrix of size n_particles x 6 of the initial particle
canonical phase space coordinates. Note that SciBmad uses the same six canonical coordinates
as in Bmad, in the order x, px, y, py, z, pz:
x,y: the horizontal and vertical positions relative to the reference trajectory [m]px,py: the horizontal and vertical momenta divided by the reference momentum \(P_0\)z\(= -\beta c (t - t_\mathrm{ref})\): the longitudinal position relative to the reference particle [m], positive when the particle is ahead of it (\(\beta c\) is the particle’s velocity, \(t\) its arrival time and \(t_\mathrm{ref}\) that of the reference particle)pz\(= (P - P_0)/P_0\): the relative momentum deviation, also called \(\delta\)
The parameters of the beamline, including deferred expressions, are evaluated
once when track is called, and kept for all turns of that call. Changes to them take effect
at the next call of track. To have parameters change during tracking (for example a ramp),
use time-dependent parameters.
@elements begin
qf = Quadrupole(Kn1=0.36, L=0.5)
bpm1 = BPM()
sf = Sextupole(Kn2=1.2, L=0.2)
d = Drift(L=0.1)
b = SBend(L=1.2, angle=pi/132)
qd = Quadrupole(Kn1=-0.36, L=0.5)
bpm2 = BPM()
sd = Sextupole(Kn2=-1.2, L=0.2)
end
fodo = Beamline([qf, bpm1, sf, b, d, qd, bpm2, sd, b, d],
species_ref=Species("electron"), pc_ref=18e9)
v0 = [1e-3 0 0 0 0 0;
1e-3 0 0 0 0 1e-3]
res = track(fodo, v0=v0, n_turns=10)
TrackResult of 2 particles:
config:
n_turns = 10
save_every_n_turns = 1
in_body_coordinates = false
save_reference = false
scalar_params = false
rf_on = true
ramp_particle_energy_without_rf = false
ramp_update_each_particle = false
batch_start = 1
verbose = false
groupsize = 0
use_cpu_multithreading = false
use_KA = false
use_explicit_SIMD = true
elapsed_time = 0.000153848 seconds
start = 1
turns = 0:1:10
s, index, name, kind the saved locations: the end of the beamline (s = 4.0)
state particle state codes, e.g. state[turn=n, particle=i]
x, px, y, py, z, pz the coordinates, e.g. x[turn=n, particle=i]
v all six coordinates, e.g. v[turn=n, particle=i]
data the internal, low-level data arrays:
state[1:2, 1:1, 1:11] [particle, location, saved turn]
v[1:2, 1:6, 1:1, 1:11] [particle, coordinate, location, saved turn]
bunch the Bunch at the end of tracking
The outputted structure is a TrackResult, which contains quite a lot of information
about the tracking. First, config is a TrackConfig structure that contains all the
configuration settings we may have provided to track, for example n_turns. For a
description of all settings, see the TrackConfig docstring.
The integer value start specifies the beamline index of the element where tracking was commenced (at the entrance end). This can be changed by specifying the start keyword argument to track. The turns that the particle coordinates were saved at are also included (res.turns), with 0 being the initial coordinates.
The four vectors s, index, name, and kind specify each of the locations in the beamline where phase space coordinates were saved (the s-positions, and the containing elements’ beamline indexes, names, and kinds). By default, the phase space coordinates are only saved at the end of the beamline, as in the above example. Further down on this page we discuss saving coordinates at different locations in the beamline.
Next, we have the TrackColumns: state, x, px, y, py, z, pz, and v. All TrackColumns store the particle data at every selected location and turn. If only one location is saved, then all TrackColumns can be indexed using the syntax x[turn=n, particle=i] where turn and particle can be integers, ranges/vectors of indexes, or colons : which specifies all. Both turn and particle default to a colon :.
res.x[turn=3] # x of all particles after turn 3
res.x[turn=3, particle=1] # x of particle 1
res.v[turn=3, particle=1] # all six coordinates x, px, y, py, z, pz
res.x[] # [particle, saved turn]
2×11 Matrix{Float64}:
0.001 0.000539823 1.92958e-5 -0.000503378 … -0.00143984 -0.0011422 -0.000717151
0.001 0.00062831 0.000389333 0.000309753 0.00199266 0.00247548 0.00288412
The saved turn k in res.x[] is the turn res.turns[k]: here the saved turns 1 to 11 are
the turns 0 to 10.
The values of state are 8-bit integers that correspond to the following constants defined in
BeamTracking:
const STATE_PREBORN = 0x0
const STATE_ALIVE = 0x1
const STATE_LOST = 0x2
const STATE_LOST_NEG_X = 0x3
const STATE_LOST_POS_X = 0x4
const STATE_LOST_NEG_Y = 0x5
const STATE_LOST_POS_Y = 0x6
const STATE_LOST_PZ = 0x7
const STATE_LOST_Z = 0x8
const STATE_IMPLICIT_NONCONVERGENCE = 0x9
Therefore, if a particle’s state is 0x1, that means it is alive and well! Once a
particle
is “lost” in tracking, its phase space coordinates are frozen at the point where it is lost.
STATE_PREBORN marks a location the particle has not reached yet (see
Starting at a Different Location).
track — Function.
track(bl::Beamline; kwargs...) -> TrackResult
All-encompassing function to track particles through the beamline bl using the configured
settings specified by the keyword arguments kwargs.
Keyword Arguments
v0: A matrix of size(n_particles, 6)storing the initial particle phase space coordinatesspin: Iftrue, spin tracking will be enabled with identity quaternions as initial quaternionsq0: A matrix of size(n_particles, 4)storing the initial particle spin quaternions if spin trackingweight: Optional vector of length(n_particles)specifying macroparticle weights per particle, default isnothingcorresponding to uniform weights for all particlesspecies: The species of the particles, default the reference species of the beamline (bl.species_ref)bunch: Instead of specifyingv0,spin,q0,weight, andspecies, an initialBunchmay be explicitly providedstart::Union{Integer,LatElement}: The element (or its beamline index) at whose beginning the tracking starts. Default is1at::Union{Nothing,Colon,AbstractVector}: Where the particles are saved, as intwiss: a vector of locations, each as one index of a column (seeTrackColumn): elements (at the beginning of each placement), beamline indexes, names (as forfindelements), and s-ranges (tuples: the integrator steps inside them, and the end of the beamline if they contain it).:is every integrator step and the end of the beamline. An entry that is not in the beamline is an error. Default isnothing, only the end of the beamline. The locations are ordered in s (from the beginning of the beamline). The locations beforestartare first reached in the second turn: before (turns 0 and 1) they areNaN(stateSTATE_PREBORN)n_turns::Int: Number of turns, each ending at the end of the beamline (the first turn begins atstart), defaults to1save_every_n_turns::Int: Multiple of turn number which specifies the turns tracking data is saved, defaults to1in_body_coordinates::Bool: Iftrue, particles saved inside misaligned elements are not transformed back to the reference curve coordinates. Default isfalsesave_reference::Bool: Iftrue, the reference time and energy at each location and saved turn are saved too (t_refandbeta_gamma_refof the result). This compiles the tracking separately and makes it slower (the reference time is computed at every integration step). Default isfalsescalar_params::Bool: Iftrue, only uses the primal values of anyLatElementproperties set asGTPSA.TPS,ForwardDiff.Dual, orReverseDiff.TrackedReal(ignores derivatives part, useful for closed orbit finding prior to parametric normal form). Default isfalserf_on::Bool: Iffalse, then anyRFParamsin anyLatElements are ignored for the entirety of the tracking. Default istrueramp_particle_energy_without_rf::Bool: Iftruewhen ramping (Beamline’s reference energy is aTimeFunction), then particle energies will be artificially ramped with the reference energy. Default isfalseramp_update_each_particle::Bool: Iftruewhen ramping, then each particle sees the reference energy at its own time (from its z-offset) at the element entrances, and the reference energy also changes through each element. Iffalse, all particles see the reference energy at the reference time at each element entrance. Usually only needed if ramping is fast compared to the time scale of bunch passage through elements. (Time-dependent element parameters are always evaluated at each particle’s own time.) Default isfalse.batch_start::Int: Specifies the starting index forBatchParams that particles in a bunch will see. E.g., ifbatch_start=3, then particle 1 sees index 3 in allBatchParams, particle 2 sees index 4, etc. Indexing ofBatchParams will loop around to the start if the particle index exceeds the length of theBatchParams. Default is1. WARNING: setting this argument will caused unaligned memory access on the GPU, which may reduce performance. In this case, considercircshift-ing allBatchParams instead.verbose::Bool: Iftrue, print the the status of tracking. Default isfalsegroupsize::Int: Designates a group of threads acting in parallel, preferably in lockstep. If tracking on a CUDA GPU, this is equal to the “block” size. On the CPU, would be a multiple of the vector register width. Default is0which letsKernelAbstractionsdecide.use_cpu_multithreading::Bool: Iftrue, then CPU multithreading will be used. Only beneficial for a large number of particles, as there is a cost to launching threads. Default isfalse.use_KA::Bool: Iftrue, usesKernelAbstractionsto launch tracking kernels. Default istrueifv0is a GPU array, elsefalse.use_explicit_SIMD::Bool: Iftrue, usesSciBmad’s explicit CPU SIMD tracking, which often guarantees vectorization of tracking on the CPU. Default is!use_KAconfig: Instead of specifyingn_turns,save_every_n_turns,in_body_coordinates,save_reference,scalar_params,ramp_particle_energy_without_rf,ramp_update_each_particle,verbose,groupsize,use_cpu_multithreading,use_KA, anduse_explicit_SIMD, a singleTrackConfigstruct can be provided instead. Setting any of these keyword arguments will override that inconfig.
TrackResult — Type.
struct TrackResult
Contains all information for a given particle tracking run. The particles are read at locations
of the beamline (given as for the columns of twiss; without a location, the only saved
location, by default the end of the beamline), for a saved turn and a particle:
res.x[turn=2] # x of all particles after turn 2 (at the only saved location)
res.x[turn=2, particle=1] # of particle 1
res.x[] # [particle, saved turn]
res.px[qd, turn=2] # at the beginning of the element qd (see `at` in `track`)
res.v[qd, :exit, particle=1] # all six coordinates at its end: [coordinate, saved turn]
Properties
x,px,y,py,z,pz: the coordinates,v: all six (the coordinate is the second index),q: the spin quaternions if spin was tracked,state: the state of the particles (STATE_ALIVE, …),t_ref,beta_gamma_ref: the reference time and energy (one value per location and turn) ifsave_reference=true. SeeTrackColumnfor how they are readturns: the saved turns (turn 0: the initial coordinates;NaNat the locations beforestart)start: the beamline index of the element where the tracking started (seestartintrack)s,index,name,kind: the s, the beamline index (-1for the end of the beamline), the name and the kind of the element of each saved locationdata: the saved arrays, indexed by location number (in the order ofs) and saved turn (1: the initial coordinates):state[particle, location, saved turn],v[particle, coordinate, location, saved turn],q[particle, quaternion, location, saved turn](ornothing),t_ref[location, saved turn]andbeta_gamma_ref[location, saved turn](ornothing; per particle withBatchParams: aBatchParamfor each location and turn)config: theTrackConfig,elapsed_time: the tracking time in seconds,bunch: theBunchat the end of tracking
TrackColumn — Type.
TrackColumn
A quantity of a TrackResult (e.g. res.x), read at locations of the beamline as
the columns of twiss (see TwissColumn), and for a saved turn and a particle given
with the keywords turn (the turn number, 0 for the initial coordinates) and particle,
written after the location (or alone):
res.x[]: without a location, at the only saved location (by default the end of the beamline; with several saved locations, one must be given),[particle, saved turn]res.x[turn=n]: all particles after turnn,res.x[turn=n, particle=i]: one number.turnandparticlecan also be:(all, as without them), a range or a vectorres.x[qd, turn=n],res.x[5, ...],res.x[qd, :exit, ...],res.x[end, ...]: at the beginning ofqd(placed once) or of the element with beamline index 5, at its end, at the end of the beamline (endis the beamline index of the end, one more than the number of elements)res.x[qd, :],res.x[[qd]],res.x["q*"],res.x[(2.0, 6.0)]: at several locations (every step ofqd, every placement ofqd, …; as fortwiss): their index comes after the particle ([particle, location, saved turn])
res.v, res.q and the spins from track_spin have the coordinate, quaternion or spin
component as the index after the particle, and t_ref and beta_gamma_ref no particle index
(unless they are per particle). The locations must have been saved (see at in track).
Saving Particle Data at Certain Locations¶
The particle data can also be saved at other locations given to track through the at keyword argument, which accepts a vector containing any combination of:
s-ranges as a tuple from start to stop, e.g.
(0., 1.23)saves the coordinates for all integration steps betweens=0ands=1.23Beamline element indexes as integers or index ranges (only at the beginning of the element). The end of the beamline is the index
length(fodo) + 1, one more than the number of elementsLatElements themselves (only at the beginning of each placement of the element)Element names, as in Searching by Name, e.g.
"bpm*"A colon
:for every integration step
For example, to save the phase space coordinates at the entrance of the BPMs in the above line, use:
res = track(fodo, v0=v0, n_turns=10, at=[bpm1, bpm2])
TrackResult of 2 particles:
config:
n_turns = 10
save_every_n_turns = 1
in_body_coordinates = false
save_reference = false
scalar_params = false
rf_on = true
ramp_particle_energy_without_rf = false
ramp_update_each_particle = false
batch_start = 1
verbose = false
groupsize = 0
use_cpu_multithreading = false
use_KA = false
use_explicit_SIMD = true
elapsed_time = 7.2786e-5 seconds
start = 1
turns = 0:1:10
s, index, name, kind the saved locations: bpm1 (s = 0.5), bpm2 (s = 2.5)
state particle state codes, e.g. state[location, turn=n, particle=i]
x, px, y, py, z, pz the coordinates, e.g. x[location, turn=n, particle=i]
v all six coordinates, e.g. v[location, turn=n, particle=i]
data the internal, low-level data arrays:
state[1:2, 1:2, 1:11] [particle, location, saved turn]
v[1:2, 1:6, 1:2, 1:11] [particle, coordinate, location, saved turn]
bunch the Bunch at the end of tracking
When there is more than one location saved, indexing for all TrackColumns requires specifying
which location(s) the data should be indexed at as the first indexing argument, using any of the
location indexing formats passable to at (element, element index, array of elements/indexes,
s-ranges, colon).
res.x[bpm2, turn=10] # x at bpm2 (the exit of qd) after turn 10
2-element Vector{Float64}:
-0.0007751064209200884
0.0023951314445364888
If the end of a beamline is saved, then end can be specified as the location for that
point. A location that is several places (e.g. [[d]] for every placement of element d,
[qd, :] for all integration steps through qd, an s-range) gives one value per
place, in the index after the particle. All of this is the exact same indexing scheme as for the
columns of twiss (see Twiss).
The s, and the beamline index, name and kind of the element of every saved location are in res.s, res.index, res.name and res.kind, so that for example the orbit through the beamline can be plotted:
res = track(fodo, v0=v0, n_turns=1, at=:) # : = Every integration step
using CairoMakie
lines(res.s, res.x[:, turn=1, particle=1]) # x vs. s for every integration step
Starting at a Different Location¶
The tracking can also start at the beginning of another element, given with start. The first
turn then goes from there to the end of the beamline (for example, n_turns=1 tracks through
the rest of a linac), and the locations before the start are first reached in the second turn,
so they are NaN until then, also in turn 0 (with state equal to
BeamTracking.STATE_PREBORN = 0x0):
res = track(fodo, v0=v0, n_turns=2, at=[qf, qd], start=qd)
res.x[qf, particle=1] # [NaN, NaN (not reached in turns 0 and 1), x in turn 2]
3-element Vector{Float64}:
NaN
NaN
0.0013192182126696233
Eventually when backwards tracking is supported by SciBmad, there will be an option to track backwards to the beginning of the beamline from any given start.
Saving the Reference Time/Energy¶
The reference time and energy at the chosen locations can be saved too, with
save_reference=true:
they are then res.t_ref (in seconds) and res.beta_gamma_ref (the reference energy as
\(\beta\gamma\)), one value per location and turn. This extra save makes the tracking slightly slower, so it is off by default:
res = track(fodo, v0=v0, n_turns=2, at=[qf, qd], save_reference=true)
res.t_ref[qd] # at the beginning of qd, for every saved turn
3-element Vector{Float64}:
0.0
6.671281906651319e-9
2.0013845719953957e-8
Spin Tracking¶
To do spin tracking, simply set spin=true. This will initialize all particles
with their
own spin quaternion, each of which will be
tracked along with the particle. A quaternion is essentially a rotation matrix - by tracking
quaternions instead of spin 3-vectors, we can track one particle once and then observe the
spin dynamics for any initial spin direction for that particle.
v0 = [1e-3 0 0 0 0 1e-3]
res = track(fodo, v0=v0, n_turns=10, spin=true)
TrackResult of 1 particle:
config:
n_turns = 10
save_every_n_turns = 1
in_body_coordinates = false
save_reference = false
scalar_params = false
rf_on = true
ramp_particle_energy_without_rf = false
ramp_update_each_particle = false
batch_start = 1
verbose = false
groupsize = 0
use_cpu_multithreading = false
use_KA = false
use_explicit_SIMD = true
elapsed_time = 0.000161452 seconds
start = 1
turns = 0:1:10
s, index, name, kind the saved locations: the end of the beamline (s = 4.0)
state particle state codes, e.g. state[turn=n, particle=i]
x, px, y, py, z, pz the coordinates, e.g. x[turn=n, particle=i]
v all six coordinates, e.g. v[turn=n, particle=i]
q spin quaternions (track_spin turns them into spin 3-vectors)
data the internal, low-level data arrays:
state[1:1, 1:1, 1:11] [particle, location, saved turn]
v[1:1, 1:6, 1:1, 1:11] [particle, coordinate, location, saved turn]
q[1:1, 1:4, 1:1, 1:11] [particle, quaternion, location, saved turn]
bunch the Bunch at the end of tracking
The spin quaternions are then res.q, for example
res.q[turn=5, particle=1] (its four
components): the rotation of the spin from the start of the tracking through turn 5.
To compute a particle’s spin 3-vector at each turn given some initial spin direction, we can
use the post-processing function track_spin:
s0 = [0, 1, 0] # initial vertical spin vector
s = track_spin(res.q, s0)
TrackColumn `spin` (read it with `spin[turn=n, particle=i]`)
s is read just like res.q, but with the three components of the spin vector:
s[turn=10, particle=1] # the spin of particle 1 after turn 10
3-element Vector{Float64}:
0.0
1.0
0.0
If you’d like to initialize different initial spin directions for each particle (perhaps
along the invariant spin field), give the initial spins as a matrix of size n_particles x 3.
Configuration Settings¶
While configuration settings can be set as keyword arguments at the level of track, a
TrackConfig structure may be provided instead, to the keyword argument config. All of
these settings are described below in the docstring for TrackConfig.
TrackConfig — Type.
struct TrackConfig
Defines configuration settings for a particles tracking run.
Properties
n_turns::Int: Number of turns, defaults to1save_every_n_turns::Int: Multiple of turn number which specifies the turns tracking data is saved, defaults to1in_body_coordinates::Bool: Iftrue, particles saved inside misaligned elements are not transformed back to the reference curve coordinates. Default isfalsesave_reference::Bool: Iftrue, the reference time and energy at each location and saved turn are saved too (t_refandbeta_gamma_refof the result). This compiles the tracking separately and makes it slower (the reference time is computed at every integration step). Default isfalsescalar_params::Bool: Iftrue, only uses the primal values of anyLatElementproperties set asGTPSA.TPS,ForwardDiff.Dual, orReverseDiff.TrackedReal(ignores derivatives part, useful for closed orbit finding prior to parametric normal form). Default isfalserf_on::Bool: Iffalse, then anyRFParamsin anyLatElements are ignored for the entirety of the tracking. Default istrueramp_particle_energy_without_rf::Bool: Iftruewhen ramping (Beamline’s reference energy is aTimeFunction), then particle energies will be artificially ramped with the reference energy. Default isfalseramp_update_each_particle::Bool: Iftruewhen ramping, then each particle sees the reference energy at its own time (from its z-offset) at the element entrances, and the reference energy also changes through each element. Iffalse, all particles see the reference energy at the reference time at each element entrance. Usually only needed if ramping is fast compared to the time scale of bunch passage through elements. (Time-dependent element parameters are always evaluated at each particle’s own time.) Default isfalse.batch_start::Int: Specifies the starting index forBatchParams that particles in a bunch will see. E.g., ifbatch_start=3, then particle 1 sees index 3 in allBatchParams, particle 2 sees index 4, etc. Indexing ofBatchParams will loop around to the start if the particle index exceeds the length of theBatchParams. Default is1. WARNING: setting this argument will caused unaligned memory access on the GPU, which may reduce performance. In this case, considercircshift-ing allBatchParams instead.verbose::Bool: Iftrue, print the the status of tracking. Default isfalsegroupsize::Int: Designates a group of threads acting in parallel, preferably in lockstep. If tracking on a CUDA GPU, this is equal to the “block” size. On the CPU, would be a multiple of the vector register width. Default is0which letsKernelAbstractionsdecide.use_cpu_multithreading::Bool: Iftrue, then CPU multithreading will be used. Only beneficial for a large number of particles, as there is a cost to launching threads. Default isfalse.use_KA::Bool: Iftrue, usesKernelAbstractionsto launch tracking kernels. Default istrue, and it must betruefor the GPU.use_explicit_SIMD::Bool: Iftrue, usesSciBmad’s explicit CPU SIMD tracking, which often guarantees vectorization of tracking on the CPU. Default is!use_KA
The Bunch Struct¶
While initial particle phase space coordinates, quaternions, macroparticle weights, and more
can be set at the level of track, these are ultimately used to construct a Bunch, which
may alternatively be provided to track with the keyword argument bunch. A Bunch
contains all information about a particle bunch, including its species, current reference
time t_ref (used to evaluate time-dependent parameters), and current
reference energy p_over_q_ref. All Bunch properties are described in the below
docstring.
If we’d like to continue tracking more turns with a bunch used in previous tracking, we can simply provide this bunch to track:
res = track(fodo, v0=v0, n_turns=5)
# track 5 more turns:
res2 = track(fodo, bunch=res.bunch, n_turns=5)
TrackResult of 1 particle:
config:
n_turns = 5
save_every_n_turns = 1
in_body_coordinates = false
save_reference = false
scalar_params = false
rf_on = true
ramp_particle_energy_without_rf = false
ramp_update_each_particle = false
batch_start = 1
verbose = false
groupsize = 0
use_cpu_multithreading = false
use_KA = false
use_explicit_SIMD = true
elapsed_time = 3.7951e-5 seconds
start = 1
turns = [0, 1, 2, 3, 4, 5]
s, index, name, kind the saved locations: the end of the beamline (s = 4.0)
state particle state codes, e.g. state[turn=n, particle=i]
x, px, y, py, z, pz the coordinates, e.g. x[turn=n, particle=i]
v all six coordinates, e.g. v[turn=n, particle=i]
data the internal, low-level data arrays:
state[1:1, 1:1, 1:6] [particle, location, saved turn]
v[1:1, 1:6, 1:1, 1:6] [particle, coordinate, location, saved turn]
bunch the Bunch at the end of tracking
The Bunch is tracked in place, so afterwards res.bunch and res2.bunch are the same
Bunch, after all 10 turns. The saved coordinates in res and res2 are not changed.
Bunch — Type.
Bunch(; v, state, spin, q, weight, callbacks, p_over_q_ref, t_ref, species)
Construct a Bunch of particles for tracking.
Required Keyword Arguments
v::AbstractMatrix: Matrix of particle phase space coordinates with shape(N, 6), whereNis the number of particles and the 6 columns are the canonical coordinates[x px y py z pz].
Optional Keyword Arguments
state: Array of particle states with lengthN. Each element is aUInt8flag indicating the particle status (e.g.0x1 == STATE_ALIVE). Defaults to all particles alive.spin::Bool=false: Iftrue, allocate identity quaternions for spin tracking.q: Matrix of spin quaternions with shape(N, 4), where each row is a unit quaternion[q0 q1 q2 q3]. Element type must match that ofv.weight: Array of particle weights with lengthN, ornothingif even weights for all particles. Defaults tonothing.callbacks: Tuple of functions to evaluate inside tracking kernels at each integration step (defaults to()), where each callback should be of the form
callback(i, coords, p::TrackPoint)
where i is the particle index, coords the Coords and p the point of the tracking (its s,
reference time, step, …; see TrackPoint).
p_over_q_ref: Reference momentum-over-charge defining the normalization of the phase space coordinates.t_ref=0.: Reference time.species=Species(): Particle species.
The Bunch also holds the position of its reference particle in the Beamline, s and step
(as the callbacks get them). Tracking a Beamline starts them at 0, tracking a single element
continues from them.
Example
N = 1000
v = zeros(N, 6)
bunch = Bunch(v=v, species=Species("electron"), p_over_q_ref=-60.0)
# With spin tracking:
bunch = Bunch(v=v, spin=true, species=Species("electron"), p_over_q_ref=-60.0)
Tracking a Different Species¶
By default, the particles tracked are of the reference species of the beamline. To track a
different species, give it to track with species (or give track a Bunch of that
species). Just like in a real accelerator,
the magnets keep the same fields, and each particle responds to them according to its own
charge, mass, and energy. For example, muons with the same momentum as the design electrons
follow the same orbit, but they are slower, so they fall behind (their z changes more):
res = track(fodo, v0=v0, species=Species("muon"), n_turns=10)
res.v[turn=10, particle=1]
Tracking Species("muon", -1.0, 1.056583755e8, 0.5, -2.00233184123, -2.80271738128469e-7, 0, AtomicAndPhysicalConstants.Kind.LEPTON) through a Beamline with reference species Species("electron", -1.0, 510998.95069, 0.5, -2.00231930436092, -5.795094307747843e-5, 0, AtomicAndPhysicalConstants.Kind.LEPTON): the fields of the Beamline are held fixed
6-element Vector{Float64}:
0.002884121602613005
0.00033836579267463473
0.0
0.0
-0.0011932726181455356
0.001
A particle with the opposite charge, such as a positron in an electron ring, is bent the other way by the dipoles and is quickly lost, just as it would be in the real ring.
Callbacks¶
The Bunch struct may also contain a tuple of functions callbacks. These functions are
executed every integration step, and allow users to inject their own code into the
tracking if desired. An element with n_slices slices of n_steps steps each (see
Integration Steps and Slices) executes them n_slices*n_steps times, and
elements without integration steps (patches, maps, and elements tracked with SaganCavity) once. For example, twiss uses callbacks to compute its results at every integration step, inside of elements.
Callbacks are required to have the function signature defined below
function mycallback(i, coords::BeamTracking.Coords, p::TrackPoint)
# Do stuff...
return
end
In the tracking, each callback is executed and provided the arguments shown above in the callback signature. These are:
i: Particle indexcoords: ABeamTracking.Coordsstruct, containing the fields:coords.state: particle state vector of lengthn_particlescoords.v: particle phase space matrix of sizen_particle x 6coords.q:nothingif no spin tracking, else, particle spin quaternion matrix of sizen_particle x 4coords.weight:nothingif uniform macroparticle weights, else weights vector of lengthn_particles
p: ATrackPoint, the point of the tracking, with the properties:p.s: Current s-position from the beginning of the beamlinep.t_ref: Current reference time of the bunch from the beginning of trackingp.step: Current integration step from the beginning of the beamline (the steps of the elements counted as above, the last one of an element at its exit). This is howtrackfinds the locations ofatp.beta_gamma_ref: Current reference Lorentz \(\beta\gamma\) of the bunchp.last_ds_step: Last integration step length before executing this callbackp.last_g: Last integration coordinate system curvature as a tuple(gx, gy)in lab coordinates before executing this callback
The functions transforms_out! and transforms_in! can be applied inside the callback to coords in order to transform the particle coordinates out of the element integration body frame and back into the laboratory frame. This can be useful if, for example, an element is misaligned, but you want to see the phase space coordinates in the laboratory frame. The transformations may be called by
simply executing transforms_out!(i, coords, p) or transforms_in!(i, coords, p)
Any of these quantities may be used in the callback. Also, as long as callbacks are written to be GPU compatible, they will work on the GPU. For example, this callback prints the \(x\) coordinate of each particle on the GPU in laboratory coordinates, each integration step:
using CUDA
function mycallback(i, coords, p)
transforms_out!(i, coords, p) # Transform out of body integration coordinates
CUDA.@cuprintln("Hi! I'm particle $i at $(p.t_ref) and my x-coordinate is $(coords.v[i,1])")
transforms_in!(i, coords, p) # Transform back into body integration coordinates
return
end
TrackPoint — Type.
TrackPoint
The point of the tracking at which the callbacks are executed, passed to each callback as
callback(i, coords, p::TrackPoint). Its properties are:
s: s from the beginning of theBeamline(when tracking a single element, continued from the position of theBunch: from the beginning of the element for a newBunch)t_ref: reference timestep: integration steps from the beginning of theBeamline(n_slices*n_stepsper element, the last one at the exit of the element; when tracking a single element, continued from the position of theBunchass)beta_gamma_ref: reference energy (beta*gamma)last_ds_step: length of the last integration steplast_g: curvature(gx, gy)of the last integration step
transforms_out!(i, coords, p) and transforms_in!(i, coords, p) transform particle i out of
and back into the element body frame (e.g. of a misaligned element).
The transforms are only computed when used.
Coordinates Number Type¶
By default, particle phase space (and quaternion) coordinates are 64-bit floats. However, there may be cases where the often-significant performance gains of using 32-bit floats outweigh the cost of lower precision. For example, almost every neural network implementation in major machine learning libraries defaults to 32-bit precision, because it is “good enough”. Furthermore, some GPUs (such as Apple Metal) only support 32-bit floats.
SciBmad tracking is also fully compatible with end-to-end 32-bit float tracking. To use this, simply initialize the particle phase space coordinates (and optionally spin quaternions) using 32-bit floats,
v0 = zeros(Float32, 1, 6) # 1 32-bit particle
res = track(fodo, v0=v0)
TrackResult of 1 particle:
config:
n_turns = 1
save_every_n_turns = 1
in_body_coordinates = false
save_reference = false
scalar_params = false
rf_on = true
ramp_particle_energy_without_rf = false
ramp_update_each_particle = false
batch_start = 1
verbose = false
groupsize = 0
use_cpu_multithreading = false
use_KA = false
use_explicit_SIMD = true
elapsed_time = 8.53e-5 seconds
start = 1
turns = [0, 1]
s, index, name, kind the saved locations: the end of the beamline (s = 4.0)
state particle state codes, e.g. state[turn=n, particle=i]
x, px, y, py, z, pz the coordinates, e.g. x[turn=n, particle=i]
v all six coordinates, e.g. v[turn=n, particle=i]
data the internal, low-level data arrays:
state[1:1, 1:1, 1:2] [particle, location, saved turn]
v[1:1, 1:6, 1:1, 1:2] [particle, coordinate, location, saved turn]
bunch the Bunch at the end of tracking
Note
When 32-bit floats are used for the particle coordinates, all numbers in the tracking (e.g. magnet strengths, lengths, and time-dependent parameters) are 32-bit floats too.
CPU Parallelization¶
On the CPU, all tracking will automatically be parallelized using explicitly-programmed
single instruction, multiple data (SIMD) instructions if your hardware supports it. To
disable explicit SIMD (and rely on potential compiler auto-vectorization), run track with
the keyword argument use_explicit_SIMD=false.
Multithreading¶
SciBmad tracking is also compatible with CPU multithreading. To do so, Julia must be started with threads. In a terminal:
$ julia --threads=auto
where auto will infer a number of threads to use based on your system, or alternatively an
integer number of threads may be specified. To check in a Julia session that multiple
threads are available, run the command
println(Threads.nthreads())
If this number is > 1, then you are ready to do multithreaded tracking. Simply set the
track configuration setting use_cpu_multithreading=true.
Note
There is a cost to launching threads on the CPU. Using multithreading with a small number of particles may actually slow down your tracking. We recommend checking with a small number of turns first to see if multithreading can improve your tracking performance, before doing a full long-term run.
Multiple Processes/Nodes¶
(Documentation in development, see Distributed and SlurmClusterManager in the meantime)
GPU Parallelization¶
All SciBmad tracking is fully GPU parallelized and branchless. To do particle tracking
on the GPU, either initialize a Bunch with the corresponding device GPUArray, or provide
the GPUArray to
track.
For example, to do GPU-parallelized spin tracking on a CUDA GPU,
using CUDA
n_particles = 100000
# Random initial phase space coordinates:
v0 = CUDA.rand(Float64, n_particles, 6) .* 1e-5
res = track(fodo, v0=v0, spin=true, n_turns=100)
Note
Julia is a just-in-time (JIT) compiled language, meaning that many functions (including the
tracking kernels in SciBmad) are only compiled once they are called with specific types
(e.g., a GPUArray). We try to precompile for as many cases as possible, but precompilation
for GPUArrays is not possible. As such, the first “turn” in tracking will have a latency
in order for the JIT compiler to compile SciBmad’s GPU tracking kernels.
Apple Metal GPUs only support 32-bit floats, so on a Mac use Float32 coordinates; all of
the tracking, including spin tracking, will then be done in 32-bit:
using Metal
v0 = MtlArray(rand(Float32, n_particles, 6) .* 1f-5)
res = track(fodo, v0=v0, spin=true, n_turns=100)
Multiple GPUs¶
(Documentation in development, see CUDA: Multiple GPUs in the meantime)