Defining a Beamline

To construct a Beamline, provide an array of LatElements in the proper order, and optionally specify the reference species as species_ref and the reference energy as one of E_ref, pc_ref, or p_over_q_ref:

@elements begin
  qf = Quadrupole(Kn1=0.36, L=0.5)
  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)
  sd = Sextupole(Kn2=-1.2, L=0.2)
end

fodo = Beamline([qf, sf, b, d, qd, sd, b, d],
        species_ref=Species("electron"), pc_ref=18e9)
Beamline:
 species_ref = electron
 pc_ref = 1.8e10

  Index   Name   Kind         L [m]   s [m]                s_downstream [m]   
  1       qf     Quadrupole   0.5     0.0f0                0.5
  2       sf     Sextupole    0.2     0.5                  0.7
  3       b      SBend        1.2     0.7                  1.9
  4       d      Drift        0.1     1.9                  2.0
  5       qd     Quadrupole   0.5     2.0                  2.5
  6       sd     Sextupole    0.2     2.5                  2.7
  7       b      SBend        1.2     2.7                  3.9000000000000004
  8       d      Drift        0.1     3.9000000000000004   4.0

Alternatively, the reference species and energy may be provided in the first LatElement. So, we could have equivalently written this as:

@elements begin
  beg = Marker(species_ref=Species("electron"), pc_ref=18e9)
  qf = Quadrupole(Kn1=0.36, L=0.5)
  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)
  sd = Sextupole(Kn2=-1.2, L=0.2)
end

fodo = Beamline([beg, qf, sf, b, d, qd, sd, b, d])
Beamline:
 species_ref = electron
 pc_ref = 1.8e10

  Index   Name   Kind         L [m]   s [m]                s_downstream [m]   
  1       beg    Marker       0.0f0   0.0f0                0.0f0
  2       qf     Quadrupole   0.5     0.0f0                0.5
  3       sf     Sextupole    0.2     0.5                  0.7
  4       b      SBend        1.2     0.7                  1.9
  5       d      Drift        0.1     1.9                  2.0
  6       qd     Quadrupole   0.5     2.0                  2.5
  7       sd     Sextupole    0.2     2.5                  2.7
  8       b      SBend        1.2     2.7                  3.9000000000000004
  9       d      Drift        0.1     3.9000000000000004   4.0

The reference species and energy describe the particle the beamline is designed for, and normalized strengths such as Kn1 are relative to them. However, you can still track any other species through the beamline, for example muons through an electron ring. The behavior is equivalent to what happens in real life: nothing about the machine changes (the magnets have the same fields, and the RF cavities the same frequency and phase), and each particle responds to it according to its own charge, mass, and energy (see Track).

Beamline — Type.

Beamline(line; kwargs...)

Constructs a Beamline out of the LatElements in the vector line. The LatElements in the Beamline will be automatically constructed as children of those LatElements in line, inheriting all of their properties.

The reference energy of the beamline may be optionally specified using one of the keyword arguments: E_ref, pc_ref, p_over_q_ref, dE_ref, dpc_ref, or dp_over_q_ref. Whichever of these is specified will be the independent variable. The species of the beamline may be optionally specified using the species_ref keyword argument. Specifying either of these keyword arguments will permanently override both the reference species and energy defined in the first LatElement – see the warning below.

Examples

qf = Quadrupole(Kn1=0.36, L=0.5)
d = Drift(L=1)
qd = Quadrupole(Kn1=-0.36, L=0.5)

fodo = Beamline([qf, d, qd, d], species_ref=Species("electron"), E_ref=18e9)

Alternatively, one can specify the reference species/energy in the first element:

qf = Quadrupole(Kn1=0.36, L=0.5, species_ref=Species("electron"), E_ref=18e9)
d = Drift(L=1)
qd = Quadrupole(Kn1=-0.36, L=0.5)

fodo = Beamline([qf, d, qd, d])

Keyword arguments

  • context: A Context struct containing variables that can be stored in the beamline for convenience. If the Beamline is put in a Branch, this is merged into the Context shared by the whole Branch – see Branch.

  • species_ref: Reference species of the beamline.

  • E_ref: Total reference energy [eV]

  • pc_ref: Reference momentum [eV/c]

  • p_over_q_ref: A signed reference magnetic rigidity [T * m]

  • dE_ref: Change in total reference energy w.r.t. the directly-upstream beamline in units [eV]

  • dpc_ref: Change in reference momentum w.r.t. the directly-upstream beamline in units [eV/c]

  • dp_over_q_ref: Change in signed reference magnetic rigidty w.r.t. the directly upstream beamline [T * m]

Warning

Keyword arguments specified to the Beamline constructor will permanently override any corresponding properties specified in the first LatElement of the beamline. E.g.,

beg = Marker(species_ref=Species("electron"), E_ref=18e9)

a = Beamline([beg])
b = Beamline([beg], species_ref=Species("proton"), E_ref=1e9)

a.E_ref == beg.E_ref == 18e9 # true
b.E_ref == 1e9               # true
b.E_ref != beg.E_ref         # true

# If `beg` is reset:
beg.species_ref = Species("positron")

# `a` will still inherit it, but `b` will not:
a.species_ref == beg.species_ref   # true
b.species_ref == Species("proton") # true
b.species_ref != beg.species_ref   # true
Beamline

Structure containing a vector of LatElements in an ordered sequence, and optionally a Context struct containing conrol variables associated with the beamline for convenience. The reference species (specified as species_ref and reference energy (specified as one of E_ref, pc_ref, p_over_q_ref, dE_ref, dpc_ref, or dp_over_q_ref) is uniform over the entire beamline. The most-recently specified of these reference energy quantites will be stored as the independent variable, in the first LatElement of the Beamline.

Properties

  • line: A read-only array of LatElements in the beamline, in order

  • context: Context struct containing control variables associated with the beamline. If in a Branch, this is shared by the whole Branch (and Lattice, if any), and setting it sets it for all of them

  • branch: Branch that the beamline is placed in, if any

  • branch_index: Index of the beamline in the Branch, if in a Branch

Finding LatElements in a Beamline

Continuing with the above example, there are several ways to find LatElements in a Beamline, by indexing the beamline:

# Find the *single* instance of `qf` in fodo:
qf_in_fodo = fodo[qf];

# Find *all* the drifts `d` in `fodo` (note the extra [])
ds = fodo[[d]];

# Get the element at index 4
fodo[4];

# Provide an anonymous function to search for elements
quads = fodo[x -> x.kind == "Quadrupole"];
focusing_sextupoles = fodo[x -> x.Kn2 > 0];

fodo[d] would be an error, because d is placed twice: index with [[d]] for all of its placements, or with a beamline index for one of them. A vector can also mix elements and beamline indexes, e.g. fodo[[qf, 4]]. These are the same rules as for reading twiss and track results at elements.

The anonymous function is applied to all elements in the beamline, and if true is returned, then that element is included in the search output.

A Beamline can also be looped over like a vector of its elements, for example for ele in fodo ... end or foreach(x -> x.n_steps = 4, fodo).

Searching by Name

Elements can also be found by their names, using a string pattern with the same syntax as in Bmad. * matches any number of characters, and % or ? any single character. Putting an element kind and :: in front matches only elements of that kind, #N at the end picks the Nth match, and name1:name2 gives all elements from name1 through name2:

fodo["q*"];           # Names starting with "q": qf, qd
fodo["?d"];           # Two character names ending with "d": qd, sd
fodo["Sextupole::*"]; # All sextupoles: sf, sd
fodo["d#2"];          # The second d (element 9)
fodo["qf:qd"];        # Everything from qf through qd: qf, sf, b, d, qd
fodo["5:9"];          # Elements 5 through 9: d, qd, sd, b, d

Patterns can be combined with , (either one matches) and & (both match):

fodo["qf, qd"];               # qf or qd: qf, qd
fodo["Sextupole::* & qf:qd"]; # Sextupoles from qf through qd: sf

For anything more complicated, a Julia regular expression r"..." can be used instead. It must match the whole name, and the i flag makes it case insensitive:

fodo[r"(q|s)d"]; # qd or sd: qd, sd
fodo[r"Q.*"i];   # Names starting with "q" or "Q": qf, qd

The elements found are always in their order in the beamline, each at most once. If the end of a range comes before its start, as in fodo["sd:sf"], the range wraps around the end of the beamline, which is convenient for rings. Each end of a range must be exactly one element, so fodo["qf:b"] is an error because fodo has two bs.

findelements(fodo, "q*") is the same as fodo["q*"]. It can also search a whole Lattice with several branches, where branch>>name matches only in the branches named branch:

findelements — Function.

findelements(where::Union{Lattice,Branch,Beamline}, pattern::Union{AbstractString,Regex}) -> Vector{LatElement}

Returns all the LatElements in where that match pattern. where may be a Lattice, a Branch, or a Beamline. The returned elements are ordered by the order of the branches followed by their order in the branch, and each element appears at most once. No match is not an error, and an empty vector is returned.

Syntax

The syntax is based on Bmad’s. An “atom” is of the form

  {branch>>}{kind::}name{#N}

where {...} marks an optional part and

  • branch Match only elements in a Branch whose name matches.

  • kind Match only elements whose kind is kind, e.g. Quadrupole. This must be an exact match.

  • name Element name to match, or an integer element index where the first element of a Branch (or of the Beamline when where is a Beamline) has index 1. With an index and no branch, the element with that index in each branch searched is matched.

  • #N Match only the Nth element in each branch that matches the rest of the atom.

Atoms may be combined:

  atom1:atom2    # Range: All elements from atom1 through atom2 inclusive.
  set1, set2     # Union.
  set1 & set2    # Intersection.

& has the lowest precedence, so A, B & C is the intersection of A, B with C. A range is evaluated in each branch where both atom1 and atom2 match, and it is an error if either matches more than one element in that branch. If atom2 comes before atom1, the range wraps around the end of the branch.

Name matching

If pattern is a String, the branch and element names may use the Bmad wild card characters *, which matches any number of characters (including zero), and % or ?, either of which matches any single character. There are no other wildcard characters here.

If pattern is a Regex, e.g. r"q[0-9]+", the branch and element names are Julia regular expressions. Each must match the whole name, so r"Q" does not match an element named Q1. The flags of pattern (e.g. i for case insensitive) are applied to each. Operator characters in a regex group (...), character class [...], or quantifier {n,m}, or that are escaped with a backslash, are part of the regular expression.

Matching is case sensitive unless the i flag is used with a Regex.

Examples

findelements(lat, "q*")                     # Elements whose name begins with "q".
findelements(lat, r"q.*")                   # Same as above using a regex.
findelements(lat, r"q.*"i)                  # Same as above but case insensitive, so "Q1" also matches.
findelements(lat, "Quadrupole::q%")         # Quadrupoles with a two character name starting with "q".
findelements(lat, "Quadrupole::q?")         # Same as above. "?" and "%" are equivalent.
findelements(lat, "ring>>7")                # 7th element of the branch named "ring".
findelements(lat, "b*>>bpm#2")              # 2nd element named "bpm" in each branch with a name
                                            #   starting with "b".
findelements(lat, "m1:m2")                  # Elements from "m1" through "m2" in a line.
findelements(lat, "Marker::* & m1:m2")      # Markers from "m1" through "m2".
findelements(lat, "q1, q2")                 # Elements named "q1" or "q2".
findelements(lat, r"(q|s)[0-9]{1,2}")       # Regex with operator characters in a group and quantifier.

See also findbranches.

Multiple LatElements in (multiple) Beamlines

Again continuing with the FODO cell example above, note that fodo contains two instances of the element d and two instances of b. If the length of d is changed, then both instances of d will see this new, changed length:

drifts = fodo[[d]];
d.L = 2.0
println(drifts[1].L)
println(drifts[2].L)
2.0
2.0

However, both drifts in fodo are unique elements. We can check this using the === operator:

println(drifts[1] === drifts[2])
println(d === drifts[1])
println(d === drifts[2])
false
false
false

Under the hood, when an element is placed in a Beamline, a shallow copy of that element is created that points to the “parent” element, from which it inherits its parameters. So, in this above example when the “get” drifts[1].L is executed, the code goes to the parent element d and returns d.L. “Sets”, such as drifts[1].L = 10, will also pass through from the child to the parent:

drifts[1].L = 3.0
println(d.L)
println(drifts[2].L)
3.0
3.0

The only case where a child element can have parameters different from its parent is when a given parameter group is contained within the child. For example, drifts[1] and drifts[2] both have their own instance of BeamlineParams, from which we can extract things like beamline_index, s, and s_downstream. On the other hand, the parent element d does not have a BeamlineParams.

println("beamline_index:")
println(drifts[1].beamline_index)
println(drifts[2].beamline_index)

println("s_downstream:")
println(drifts[1].s_downstream)
println(drifts[2].s_downstream)

# This will error:
try
  d.beamline_index
catch err
  println(err)
end
beamline_index:
5
9
s_downstream:
4.9
9.8
ErrorException("Unable to get beamline_index: this LatElement is not in a Beamline. If you placed it in a Beamline `bl`, get it from its placement there: `bl[ele].beamline_index` (placed once), or `bl[[ele]]` for all of its placements")

The parent element can be retrieved using parent:

drifts[1].parent
LatElement:
  UniversalParams
   kind             = "Drift"
   name             = "d"
   L                = 3.0
   tracking_method  = DriftKick(
     order      = 4,
     opt_scheme = true,
   )
   n_steps          = 1
   n_slices         = 1
   fringe_at        = Fringe.BothEnds
   rad_damping      = false
   rad_fluctuations = false

Beamline-Dependent LatElement Parameters

Finally, elements in a beamline allow one to “get” parameters that may only be defined when said element is in a beamline. We showed the s and s_downstream, but another example would be the unnormalized magnetic field, if the normalized magnetic field is stored as an independent variable:

ele = Quadrupole(Kn1=2, L=2)
bl = Beamline([ele], p_over_q_ref=3)
println(bl[1].Bn1) # Returns Kn1 * p_over_q_ref = 2 * 3
6.0

The last parameter “set” will always define what the independent variable is. So if we then set the unnormalized quadrupole strength Bn1, that will be the independent variable:

ele.Bn1 = 10
println(bl[1].Kn1) # Returns Bn1 / p_over_q_ref = 10 / 3
3.3333333

Now, if we then change the reference energy of the beamline, Bn1 will remain constant but Kn1 will change:

bl.p_over_q_ref = 4
println(bl[1].Bn1) # == 10
println(bl[1].Kn1) # Now equals 10 / 4
10.0
2.5