Quickstart Guide

The following is an introduction to SciBmad in one copy-and-pastable block: build a FODO cell, compute its linear, nonlinear, chromatic and spin optics, adjust the sextupoles to set the chromaticities, and track particles with spin. The rest of this page walks through it step by step. To easily copy a block of code anywhere in the documentation, move your cursor to the top right of the code block and select to copy.

A Simple Copy-Paste Example

using SciBmad

# Define lattice elements using @elements
@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

# Construct a Beamline and define the reference species + momentum
fodo = Beamline([qf, sf, b, d, qd, sd, b, d],
        species_ref=Species("electron"), pc_ref=18e9)

# Change the quadrupole strengths
qf.Kn1 = 0.37
qd.Kn1 = -0.37

# Set number of integration steps in qd to 3
qd.n_steps = 3

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

# Find the drifts `d` in `fodo`
ds = fodo[[d]];

# Get the first element of `fodo`
first_ele = fodo[1];

# Gets all quadrupoles
quads = fodo[x -> x.kind == "Quadrupole"]; # Lambda function
quads = fodo["Quadrupole::*"];             # Classic Bmad syntax
quads = fodo[r"q.*"];                      # Regex match on name

# Compute the periodic optics
tw = twiss(fodo)

#= 
  Print the tunes, phase slip factor (etac), momentum compaction (alphac)
=#
@show tw.q1     # Horizontal-like tune
@show tw.q2     # Vertical-like tune
@show tw.etac   # Phase slip factor
@show tw.alphac # Momentum compaction

#=
  Print the horizontal-like beta function at various locations
  including inside elements
=#
@show tw.beta1[qd]        # Beginning of element qd
@show tw.beta1[qd, :exit] # End of qd
@show tw.beta1[qd, :]     # Every integration step inside qd
@show tw.beta1[qd, 2]     # 2nd integration step inside qd
@show tw.beta1[4, :]      # Every integration step of element 4
@show tw.beta1[(0, 1.23)] # Every integration step between s=0, s=1.23

#=
  Compute only specific quantities
  "beta1" = horizontal-like beta
  "phi2" = vertical-like phase advance,
  "dx" = horizontal dispersion
=#
tw = twiss(fodo, cols=["beta1", "phi2", "dx"])

#=
  Compute higher order chromatic quantities such as
  the chromaticity, Montague W functions ("w1", "w2"),
  and 2nd order dispersions ("dx_2", "dy_2") by setting
  the order of δ (chrom) equal to 2
=#
tw = twiss(fodo, cols=["w1", "w2", "dx_2", "dy_2"], chrom=2)
@show tw.q2
#= Prints:
  tw.q2 = AmplitudeDependentValue:
    0.05401330001000863 - 0.008253153240321323 δ
=#
# Get the y-chromaticity
chromy = tw.q2[delta=1]
chromy = tw.dq2 # or equivalently tw.dq2_1 

# Resonance driving terms h3000, h2100
tw = twiss(fodo, cols=["h3000", "h2100"])

#=
  Spin analysis (invariant spin field as Taylor series,
  amplitude-dependent spin tune).
=#
tw = twiss(fodo, cols=["nx", "ny", "nz"], spin=true,
      as_taylor_series=true, order=2)
@show tw.qspin
#= Prints:
  tw.qspin = AmplitudeDependentValue:
    -0.3094612779434053 - 0.3094612776559473 δ - 4.0543183384536337e-10 J₁ 
    + 28.127501690102246 J₂ - 2.950933476050364e-10 δ²
=#

#= 
  Adjust the sextupoles to make chromaticities to be +1 
  using SciBmad's autodiff + parametric normal form
=#
te = lazy_twiss(fodo)
sol = optimize!(vary = [@knob(sf.Kn2), @knob(sd.Kn2)],
                targets = [te.dq1 == 1, te.dq2 == 1])

#=
  Track a particle with [x, px, y, py, z, pz]
  = [1e-3 0. 0. 0. 0. 1e-3] for n_turns=10
=#
res = track(fodo, v0=[1e-3 0. 0. 0. 0. 1e-3], n_turns=10)

# Also do spin quaternion tracking:
res = track(fodo, v0=[1e-3 0. 0. 0. 0. 1e-3], n_turns=10, spin=true)
# Apply spin quaternion to horizontal initial spin direction (FAST):
s = track_spin(res.q, [1, 0, 0])

# Track a bunch, give matrix of size n_particles x 6:
n_particles = 10
res = track(fodo, v0=rand(n_particles, 6).*1e-5, n_turns=10, spin=true)

Step-By-Step Description

Constructing a Beamline

Let’s start by constructing a simple FODO cell Beamline: a focusing quadrupole (“F”), a gap (“O”), a defocusing quadrupole (“D”) and another gap, the basic repeating cell of many rings. Here the gaps hold a sextupole, a bending magnet and a drift.

To do this, we will define six LatElements, one for each kind of object in the cell. The lengths of each object are specified by L (in meters), and the quadrupole strengths can be set using the property Kn1, where n means the “normal” multipole (s would be “skew”) and 1 means 1st order multipole (quadrupole). The normal sextupole strength is thus Kn2. These strengths are normalized by the magnetic rigidity of the reference particle: Kn1 is in 1/m² and Kn2 in 1/m³. For the bend, the angle parameter sets both the curvature of the coordinate system and the corresponding magnetic field so that a “reference particle” will follow the coordinate system curvature exactly. The coordinate system curvature and normalized field strength can be set independently using g_ref and Kn0 respectively if desired.

using SciBmad

# Define lattice elements using @elements
@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

# Construct a Beamline and define the reference species + momentum
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

Wrapping the definitions in @elements sets the name of each element to the name of its variable (qf.name is "qf").

The Beamline is designed for a reference particle, here an electron with the momentum pc_ref = 18 GeV/c.

All element “kinds” (Sextupole, Quadrupole, etc.) are one single type LatElement under the hood. Therefore, there is nothing preventing you from writing e.g. Drift(L=1.2, Ks8=123). This structure provides maximal flexibility for defining and modifying elements (see Defining a LatElement for more). A default tracking method is chosen given an element kind, e.g. MatrixKick for a finite-length Quadrupole, which you can change at any time (see Tracking Methods).

LatElements in a beamline simply inherit all properties from the original element definition. For example, retuning the quadrupole strengths or number of integration steps

# Change the quadrupole strengths
qf.Kn1 = 0.37
qd.Kn1 = -0.37

# Set number of integration steps in qd to 3
qd.n_steps = 3
3

is reflected everywhere that element has been placed in a Beamline, without needing to rebuild fodo or search-and-replace through its element list (see Defining a Beamline for more).

The AtomicAndPhysicalConstants package is used for specifying particle species, and so any species defined by that package may be provided. Also, instead of specifying the reference momentum pc_ref (in eV/c), we alternatively could have specified the total reference energy E_ref (in eV), or the signed magnetic rigidity p_over_q_ref (in T·m).

We can find instances of elements in a Beamline, by searching in the following manners:

# 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 first element of `fodo`
first_ele = fodo[1];

# Gets all quadrupoles
quads = fodo[x -> x.kind == "Quadrupole"]; # Lambda function
quads = fodo["Quadrupole::*"];             # Classic Bmad syntax
quads = fodo[r"q.*"];                      # Regex match on name

To see all the ways you can search for elements, see Defining a Beamline.

Twiss

Once a Beamline is defined, we can compute its optics with twiss:

# Compute the periodic optics
tw = twiss(fodo)

# Compute the optics of fodo as an open line (not a ring), from given
# initial Twiss parameters at its beginning
two = twiss(fodo, initial=(beta1=13, alpha1=-1, beta2=10, alpha2=1))
Twiss:
summ:
 q1     = 0.06047065306852612
 q2     = 0.05659027623176736
 etac   = 0.000365705854970993
 alphac = 0.0003657066608966948

df:
11×26 DataFrame
 Row │ index  name  kind        s        beta1     phi1        dx         x             beta2      ⋯
     │                          [m]      [m]       [2π]        [m]        [m]           [m]        ⋯
─────┼──────────────────────────────────────────────────────────────────────────────────────────────
   1 │     1  qf    Quadrupole  0.0      13.0      0.0         0.0         0.0          10.0       ⋯
   2 │     2  sf    Sextupole   0.5      12.8109   0.00607321  0.0         0.0           9.94262
   3 │     3  b     SBend       0.7      12.2732   0.00861184  0.0         0.0          10.3025
   4 │     4  d     Drift       1.9       9.41752  0.0264118   0.0142793  -1.73472e-18  12.7618
   5 │     5  qd    Quadrupole  2.0       9.20826  0.0281209   0.0166591  -2.42861e-18  12.99      ⋯
   6 │     5  qd    Quadrupole  2.16667   8.96211  0.031046    0.0207178  -3.59957e-18  13.2426
   7 │     5  qd    Quadrupole  2.33333   8.90827  0.03402     0.0249897  -4.80755e-18  13.2286
   8 │     6  sd    Sextupole   2.5       9.04453  0.0369804   0.0295186  -6.06499e-18  12.9486
   9 │     7  b     SBend       2.7       9.33012  0.0404457   0.0351259  -7.6087e-18   12.4644    ⋯
  10 │     8  d     Drift       3.9      11.3138   0.0590753   0.0830359  -1.56125e-17   9.88481
  11 │    -1  END   ---         4.0      11.4999   0.0604707   0.0882169  -1.66533e-17   9.69507
                                                                                  17 columns omitted

By default this computes the closed orbit, tunes/phase advances and, in the Sagan-Rubin/Edwards-Teng coupling formalism, the beta functions, alpha functions, coupling matrix, phase advances/slip, and (crab) dispersions at all integration steps. The table itself is tw.df, a DataFrame. The numbers 1 and 2 in names such as beta1 and q1 refer to the two transverse normal modes, which are horizontal-like and vertical-like (x and y when there is no coupling).

The values for the whole ring, such as the tunes, are properties of tw:

@show tw.q1     # Horizontal-like tune
@show tw.q2     # Vertical-like tune
@show tw.etac   # Phase slip factor
@show tw.alphac; # Momentum compaction
tw.q1 = 0.05489859401259565
tw.q2 = 0.05401330001000864
tw.etac = 0.019165878242797245
tw.alphac = 0.019165879048722943

In Julia, the @ sign specifies a macro, which modifies the code it acts on. In this case, @show tw.q1 is syntactic sugar that replaces the line of code with println("tw.q1 = ", tw.q1).

The columns of the Twiss table contain the s-dependent values, and can be read at any location, for example the beginning/ends of elements, or every integration step over an s-range.

# Betas at various locations:
@show tw.beta1[qd]        # Beginning of element qd
@show tw.beta1[qd, :exit] # End of qd
@show tw.beta1[qd, :]     # Every integration step inside qd
@show tw.beta1[qd, 2]     # 2nd integration step inside qd
@show tw.beta1[4, :]      # Every integration step of element 4
@show tw.beta1[(0, 1.23)]; # Every integration step between s=0, s=1.23
tw.beta1[qd] = 10.129870326396501
tw.beta1[qd, :exit] = 10.129754513094344
tw.beta1[qd, :] = [10.129870326396501, 9.919066255779637, 9.91902817498379, 10.129754513094344]
tw.beta1[qd, 2] = 9.91902817498379
tw.beta1[4, :] = [10.322767541919562, 10.129870326396501]
tw.beta1[(0, 1.23)] = [13.410643494724914, 13.410480351675004, 12.925220128309162]

All of the ways to specify a location are described in Twiss.

If only a subset of quantities is needed, the cols keyword restricts the computation (and the columns returned) to exactly what you ask for, which can save computation time:

#=
  Compute only specific quantities of the periodic optics
  "beta1" = horizontal-like beta
  "phi2" = vertical-like phase advance,
  "dx" = horizontal dispersion
=#
tw = twiss(fodo, cols=["beta1", "phi2", "dx"])
Twiss:
summ:
 q1     = 0.05489859401259565
 q2     = 0.05401330001000864
 etac   = 0.019165878242797245
 alphac = 0.019165879048722943

df:
11×7 DataFrame
 Row │ index  name  kind        s        beta1     phi2        dx      
     │                          [m]      [m]       [2π]        [m]     
─────┼─────────────────────────────────────────────────────────────────
   1 │     1  qf    Quadrupole  0.0      13.4106   0.0         1.72652
   2 │     2  sf    Sextupole   0.5      13.4105   0.00785137  1.72681
   3 │     3  b     SBend       0.7      12.9252   0.0108852   1.69474
   4 │     4  d     Drift       1.9      10.3228   0.0268789   1.51609
   5 │     5  qd    Quadrupole  2.0      10.1299   0.0280573   1.50236
   6 │     5  qd    Quadrupole  2.16667   9.91907  0.0299805   1.48716
   7 │     5  qd    Quadrupole  2.33333   9.91903  0.0318842   1.48725
   8 │     6  sd    Sextupole   2.5      10.1298   0.0338073   1.50264
   9 │     7  b     SBend       2.7      10.5192   0.0361862   1.53034
  10 │     8  d     Drift       3.9      13.1662   0.0524821   1.71037
  11 │    -1  END   ---         4.0      13.4106   0.0540133   1.72652

To see all available columns that can be provided to cols, see the twiss docstring.

Nonlinear Twiss

Beyond the purely linear optics, twiss can also compute higher order quantities, simply by requesting the associated column and/or increasing the order of the underlying truncated power series map (a Taylor map, also called a DA map) used internally. All quantities are computed using SciBmad’s Lie series normal form analysis package NonlinearNormalForm.

twiss exposes two independent “orders” that can be set:

  • chrom, the order to which the energy deviation δ is truncated, for computing higher order chromatic quantities

  • order, the truncated order of all individual phase space variables, for computing amplitude-dependent tunes and resonance driving terms

The tunes and the beta and alpha functions are known to one order less in δ than the map, so for example, setting chrom=2 will compute the chromaticities (the tunes to first order in δ), and if requested in cols the Montague w1/w2 functions, second-order dispersions dx_2/dy_2, chromatic beta beat dbeta1/dbeta2 (equivalent to writing dbeta1_1/dbeta2_1), etc. In fact, we can request a chromatic derivative of any scalar-valued quantity, using the notation d<quantity>_<order>. By omitting the _<order>, order is assumed to be one. For example, dc11 is the first derivative w.r.t. δ of the coupling matrix component c11, and dc11_2 is the second derivative w.r.t. δ.

#=
  Compute higher order chromatic quantities such as
  the chromaticity, Montague W functions ("w1", "w2"),
  and 2nd order dispersions ("dx_2", "dy_2") by setting
  the order of δ (chrom) equal to 2
=#
tw = twiss(fodo, cols=["w1", "w2", "dx_2", "dy_2"], chrom=2)
Twiss:
summ:
 q1     = 0.05489859401259565 + 0.07905747898014202 δ
 q2     = 0.05401330001000864 - 0.00825315324032125 δ
 etac   = 0.019165878242797165 - 0.03645782324708619 δ
 alphac = 0.019165879048722932 - 0.036457825633970944 δ

df:
11×8 DataFrame
 Row │ index  name  kind        s        w1       w2       dx_2      dy_2 
     │                          [m]      [1]      [1]                     
─────┼────────────────────────────────────────────────────────────────────
   1 │     1  qf    Quadrupole  0.0      3.54327  2.2888   -5.06473   0.0
   2 │     2  sf    Sextupole   0.5      3.53053  2.32137  -4.89516   0.0
   3 │     3  b     SBend       0.7      3.3431   2.52065  -4.74081   0.0
   4 │     4  d     Drift       1.9      3.18849  2.61841  -4.27158   0.0
   5 │     5  qd    Quadrupole  2.0      3.17452  2.6279   -4.23376   0.0
   6 │     5  qd    Quadrupole  2.16667  3.16412  2.63122  -4.20777   0.0
   7 │     5  qd    Quadrupole  2.33333  3.17403  2.62045  -4.2557    0.0
   8 │     6  sd    Sextupole   2.5      3.19669  2.61269  -4.37802   0.0
   9 │     7  b     SBend       2.7      3.36402  2.375    -4.51511   0.0
  10 │     8  d     Drift       3.9      3.52807  2.29524  -5.01951   0.0
  11 │    -1  END   ---         4.0      3.54327  2.2888   -5.06473   0.0

When computed to a higher order, amplitude- and energy-dependent quantities, such as the tunes q1/q2, are returned not as plain numbers but as AmplitudeDependentValues - Taylor series in the actions J₁, J₂ (the amplitudes of the oscillations in the two transverse modes) and the energy deviation δ:

@show tw.q2
tw.q2 = AmplitudeDependentValue:
 0.05401330001000864 - 0.00825315324032125 δ
AmplitudeDependentValue:
 0.05401330001000864 - 0.00825315324032125 δ

Derivatives of an AmplitudeDependentValue can be extracted by indexing the quantity with the order of the derivative in each variable. For example, the linear chromaticity in y is \(\partial q_2/\partial\delta\):

# Get the y-chromaticity
chromy = tw.q2[delta=1]
-0.00825315324032125

For chromatic derivatives only, you can also use the shorthand d<quantity>_<order> notation:

chromy = tw.dq2 # or equivalently tw.dq2_1
-0.00825315324032125

Likewise, tw.q2[delta=2] (or tw.dq2_2) is \(\partial^2 q_2/\partial\delta^2\). The same mechanism extends naturally to purely amplitude-dependent tune shifts (once order is raised high enough to resolve them), using the J1 and J2 keyword arguments to extract tune derivatives w.r.t. the action variables.

We can also extract any so-called resonance driving term/detune coefficient - monomials of the nonlinear effective Hamiltonian in linear action-angle variables. And, if the beam is coasting (without synchrotron oscillations, e.g. without RF cavities), we can even take chromatic derivatives of these quantities as described before. These quantities are defined in Resonance driving terms and detuning.

# Resonance driving terms h3000, h2100
tw = twiss(fodo, cols=["h3000", "h2100"])
Twiss:
summ:
 q1     = 0.05489859401259562 + 0.079057478980142 δ
 q2     = 0.05401330001000863 - 0.008253153240321005 δ
 etac   = 0.019165878242797245 - 0.03645782324708643 δ
 alphac = 0.019165879048723012 - 0.03645782563397118 δ

df:
11×6 DataFrame
 Row │ index  name  kind        s        h3000                   h2100               
     │                          [m]                                                  
─────┼───────────────────────────────────────────────────────────────────────────────
   1 │     1  qf    Quadrupole  0.0        0.303294+0.205128im   0.664041+0.223308im
   2 │     2  sf    Sextupole   0.5        0.278905+0.237228im   0.655396+0.247536im
   3 │     3  b     SBend       0.7      -0.0492589-0.338686im    0.53745-0.428855im
   4 │     4  d     Drift       1.9       0.0595667-0.338563im    0.57978-0.372724im
   5 │     5  qd    Quadrupole  2.0       0.0694723-0.33667im    0.583397-0.367036im
   6 │     5  qd    Quadrupole  2.16667   0.0862015-0.332779im    0.58943-0.357268im
   7 │     5  qd    Quadrupole  2.33333    0.102889-0.328004im    0.59536-0.347297im
   8 │     6  sd    Sextupole   2.5        0.119144-0.322456im   0.601061-0.337333im
   9 │     7  b     SBend       2.7        0.355548+0.0946633im  0.685835+0.150991im
  10 │     8  d     Drift       3.9        0.307848+0.198229im   0.665703+0.218304im
  11 │    -1  END   ---         4.0        0.303294+0.205128im   0.664041+0.223308im

To compute these quantities, technically order=2 is required. However, twiss will automatically resolve the internal orders given the requested columns if not explicitly provided.

Spin Analysis

twiss can additionally analyze the spin dynamics by setting spin=true. This enables computation of the invariant spin field (as a Taylor series in the phase space coordinates if requested) and the amplitude-dependent spin tune:

#=
  Spin analysis (invariant spin field as Taylor series,
  amplitude-dependent spin tune).
=#
tw = twiss(fodo, cols=["nx", "ny", "nz"], spin=true,
      as_taylor_series=true, order=2)
n = [tw.nx[1], tw.ny[1], tw.nz[1]] # ISF at first element
3-element Vector{TPS64{GTPSA.Dynamic}}:
Descriptor(NV=6, MO=2)
INDEX  COEFFICIENT             ORDER   EXPONENTS
----------------------------------------------------
  1:   5.1250107573735025E-15    1     0 1  0 0  0 0
  1:   2.8726619691324133E+00    1     0 0  1 0  0 0
  1:   7.1359575554617916E-01    1     0 0  0 1  0 0
  1:   4.5945072601265647E-16    2     2 0  0 0  0 0
  1:  -6.0302080132287550E-15    2     1 1  0 0  0 0
  1:   3.2830643591428283E-14    2     0 2  0 0  0 0
  1:  -9.8609301475078297E+00    2     1 0  1 0  0 0
  1:   2.5979472292585228E+00    2     0 1  1 0  0 0
  1:  -2.6562252047002031E-15    2     0 0  2 0  0 0
  1:   4.6570660257458352E+00    2     1 0  0 1  0 0
  1:   5.5944457622852013E+01    2     0 1  0 1  0 0
  1:  -2.1118085537284523E-14    2     0 0  1 1  0 0
  1:   1.6585886635847223E-13    2     0 0  0 2  0 0
  1:   8.5340260066899683E-15    2     0 1  0 0  0 1
  1:  -1.6861654806572183E+01    2     0 0  1 0  0 1
  1:   1.6098131881371661E+01    2     0 0  0 1  0 1
----------------------------------------------------
  2:  -1.0000000000000000E+00    0     0 0  0 0  0 0
  2:  -4.3340880738064100E-16    1     0 0  1 0  0 0
  2:   4.0335793467732975E-16    1     0 0  0 1  0 0
  2:   4.4404318084393344E-16    2     2 0  0 0  0 0
  2:   1.9152285975148361E-15    2     1 1  0 0  0 0
       ... (Output truncated)

With as_taylor_series=true, the components of the ISF are returned as full Taylor series in the phase space variables \((x,p_x,y,p_y,z,\delta)\), rather than just returning \(\hat{n}_0\) (the invariant spin field on the closed orbit). The spin tune, accessible as tw.qspin, is likewise an AmplitudeDependentValue:

@show tw.qspin
tw.qspin = AmplitudeDependentValue:
 -0.30946127794340533 - 0.3094612776559479 δ - 4.0542440047447167e-10 J₁ + 28.127501690102278 J₂ - 2.9509497322187363e-10 δ²
AmplitudeDependentValue:
 -0.30946127794340533 - 0.3094612776559479 δ - 4.0542440047447167e-10 J₁ + 28.127501690102278 J₂ - 2.9509497322187363e-10 δ²

As with the orbital tunes, individual derivatives, such as the spin tune’s linear dependence on energy, or on its amplitude J₂, can be indexed.

Optimization using Autodiff

Let’s check the chromaticities of our FODO cell:

tw = twiss(fodo, chrom=2)
@show tw.dq1
@show tw.dq2
tw.dq1 = 0.07905747898014202
tw.dq2 = -0.00825315324032125
-0.00825315324032125

We want to adjust the sextupoles sf and sd so that these values are both +1. To do this, we first form a lazy twiss of our Beamline with lazy_twiss - this allows us to form mathematical expressions for any output of regular twiss, which we can then use in optimizations.

te = lazy_twiss(fodo)
TwissExpr of a Beamline with 8 elements

Because a lazy twiss allows expressions for any output from twiss, the cols keyword argument does not need to, and cannot, be provided.

We can now form the two target expressions using our lazy twiss, specifying that we want the chromaticities dq1 and dq2 to be +1 (with a lazy twiss, == does not compare two numbers: it makes a target).

[te.dq1 == 1, te.dq2 == 1]
2-element Vector{Target}:
 Target: q1[delta=1] == 1.0
 Target: q2[delta=1] == 1.0

Lastly, we need to specify our “knobs” - the things we want to change to achieve our targets. This is done using @knob with the normal sextupole strengths Kn2 of sf and sd:

[@knob(sf.Kn2), @knob(sd.Kn2)]
2-element Vector{Knob}:
 sf.Kn2
 sd.Kn2

Putting this all together into SciBmad’s optimize! function, we can now run the optimization:

te = lazy_twiss(fodo)
sol = optimize!(vary = [@knob(sf.Kn2), @knob(sd.Kn2)],
                targets = [te.dq1 == 1, te.dq2 == 1])
Converged (all targets met) with Gauss-Newton: 1 iterations, 2 evaluations (1 with derivatives), 1.18 s
 Target       value  goal    met
 q1[delta=1]  1.0    == 1.0  yes
 q2[delta=1]  1.0    == 1.0  yes
 Knob    before  after         lower  upper
 sf.Kn2  1.2     13.50047492   -Inf   Inf
 sd.Kn2  -1.2    -15.20232969  -Inf   Inf

We see that the match has been achieved, and can verify it with a regular twiss call:

twiss(fodo, chrom=2)
Twiss:
summ:
 q1     = 0.05489859401259572 + 0.9999999999999969 δ
 q2     = 0.054013300010008536 + 0.9999999999999996 δ
 etac   = 0.01916587824279715 - 0.674257178362959 δ
 alphac = 0.01916587904872292 - 0.6742571807498436 δ

df:
11×26 DataFrame
 Row │ index  name  kind        s        beta1     phi1        dx       x             beta2    phi ⋯
     │                          [m]      [m]       [2π]        [m]      [m]           [m]      [2π ⋯
─────┼──────────────────────────────────────────────────────────────────────────────────────────────
   1 │     1  qf    Quadrupole  0.0      13.4106   0.0         1.72652  -1.66533e-17  10.2966  0.0 ⋯
   2 │     2  sf    Sextupole   0.5      13.4105   0.00584419  1.72681  -2.10134e-17  10.2966  0.0
   3 │     3  b     SBend       0.7      12.9252   0.00826202  1.69474  -2.23928e-17  10.6921  0.0
   4 │     4  d     Drift       1.9      10.3228   0.0248246   1.51609  -3.1225e-17   13.3816  0.0
   5 │     5  qd    Quadrupole  2.0      10.1299   0.026381    1.50236  -3.22659e-17  13.6302  0.0 ⋯
   6 │     5  qd    Quadrupole  2.16667   9.91907  0.0290319   1.48716  -3.41695e-17  13.9105  0.0
   7 │     5  qd    Quadrupole  2.33333   9.91903  0.0317109   1.48725  -3.64246e-17  13.9105  0.0
   8 │     6  sd    Sextupole   2.5      10.1298   0.0343618   1.50264  -3.90545e-17  13.6302  0.0
   9 │     7  b     SBend       2.7      10.5192   0.0374456   1.53034  -4.24455e-17  13.1367  0.0 ⋯
  10 │     8  d     Drift       3.9      13.1662   0.0537008   1.71037  -6.41848e-17  10.4925  0.0
  11 │    -1  END   ---         4.0      13.4106   0.0548986   1.72652  -6.66134e-17  10.2966  0.0
                                                                                  17 columns omitted

Under the hood, optimize! uses SciBmad’s automatic differentiation and parametric normal form to achieve an exact, and fast, match.

lazy_twiss enables powerful accelerator lattice design and optimization workflows. Outputs of a lazy twiss (such as the optics functions) can be passed into other lazy twisses as initial conditions. For example, after matching arc FODO cells, one can pass the output values easily into another lazy twiss that is then used to match the arc FODO cells to a straight section. Derivatives of various quantities including w.r.t. knobs can also be matched through the same interface, for example as done in the Linear Optics from Closed Orbits (LOCO) algorithm. For all details, see the Matching and Optimization section of the documentation.

Track

To do particle tracking, a single function track is provided, which accepts initial phase space coordinates as an n_particle x 6 matrix (the coordinates are described on the Track page):

#=
  Track a particle with [x, px, y, py, z, pz]
  = [1e-3 0. 0. 0. 0. 1e-3] for n_turns=10
=#
res = track(fodo, v0=[1e-3 0. 0. 0. 0. 1e-3], n_turns=10)

# Also do spin quaternion tracking:
res = track(fodo, v0=[1e-3 0. 0. 0. 0. 1e-3], n_turns=10, spin=true)
# Apply spin quaternion to horizontal initial spin direction (FAST):
s = track_spin(res.q, [1, 0, 0])

# Track a bunch, give matrix of size n_particles x 6:
n_particles = 10
res = track(fodo, v0=rand(n_particles, 6).*1e-5, n_turns=10, spin=true)
TrackResult of 10 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.000409266 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:10, 1:1, 1:11]  [particle, location, saved turn]
 v[1:10, 1:6, 1:1, 1:11] [particle, coordinate, location, saved turn]
 q[1:10, 1:4, 1:1, 1:11] [particle, quaternion, location, saved turn]
bunch                    the Bunch at the end of tracking

The particles are saved at the end of the beamline after every turn by default (turn 0 holds the initial coordinates), and are read by turn and particle:

res.x[turn=10]               # x of all particles after turn 10
res.x[turn=:, particle=1]    # x of particle 1 at turns 0 to 10
11-element Vector{Float64}:
  6.756666283861964e-6
  2.2806729447708333e-5
  3.6663549413176945e-5
  4.669181402528549e-5
  5.170676760703166e-5
  5.11152533183765e-5
  4.498663059597292e-5
  3.4044748979594045e-5
  1.9581859964086647e-5
  3.304973136764266e-6
 -1.2866615058946475e-5

To save them at other places, give the elements (or positions inside elements) with at, and read them with the element first, as for the twiss results, e.g. res.x[qd, turn=10]. See the Track page for more details.

On the CPU, all tracking will automatically be parallelized using single instruction, multiple data (SIMD) if your hardware supports it. CPU multithreading can also be enabled by starting Julia with threads, and setting use_cpu_multithreading=true. For more details, see the CPU Parallelization section of the manual.

For GPU parallelized tracking, simply initialize your initial particle coordinates as a GPU array. For example:

using CUDA
n_particles = 100000 # 100,000 particles
v0 = CUDA.rand(Float64, n_particles, 6) .* 1e-5
res = track(fodo, v0=v0, n_turns=10, spin=true)

Apple Metal GPUs only support 32-bit floats, so on a Mac use Float32 coordinates; all of the tracking will then be done in 32-bit:

using Metal
v0 = MtlArray(rand(Float32, n_particles, 6) .* 1f-5)
res = track(fodo, v0=v0, n_turns=10, spin=true)

For more details, see the GPU Parallelization section of the manual.

Where to Go Next

This guide only scratched the surface. The rest of the documentation covers:

To get the most use out of SciBmad, we recommend going through the documentation sequentially, starting with the next page Defining a LatElement.