Matching and Optimization

Matching means varying parameters of a lattice (the “knobs”) until quantities such as the tunes, the beta functions at some point, chromaticities, etc have the values you want. In SciBmad all you need to do is write down the quantities and their goals, say what knobs should be varied to achieve that goal, and call optimize!.

Most optimizers need the derivatives of the quantities with respect to the knobs. In non-differentiable codes, these are computed with finite differences, which are approximate and need one more calculation per knob. Because SciBmad is fully differentiable, the default solver of optimize! gets the exact derivatives with respect to all knobs from a single calculation. For quantities without derivatives, such as the dynamic aperture, optimize! has the solver CMAES (see Dynamic Aperture Optimization).

A First Match

Let’s make the phase advance of a FODO cell \(90^\circ\) in both planes by varying its two quadrupoles.

using SciBmad

@elements begin
  qf = Quadrupole(Kn1=0.36, L=0.5)
  sf = Sextupole(Kn2=1.2, L=0.2)
  d = Drift(L=0.2)
  b = SBend(L=6.5, angle=pi/132)
  qd = Quadrupole(Kn1=-0.36, L=0.5)
  sd = Sextupole(Kn2=-1.2, L=0.2)
end

fodo = Beamline([qf, sf, d, b, d, qd, sd, d, 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       d      Drift        0.2     0.7                  0.8999999999999999
  4       b      SBend        6.5     0.8999999999999999   7.4
  5       d      Drift        0.2     7.4                  7.6000000000000005
  6       qd     Quadrupole   0.5     7.6000000000000005   8.100000000000001
  7       sd     Sextupole    0.2     8.100000000000001    8.3
  8       d      Drift        0.2     8.3                  8.5
  9       b      SBend        6.5     8.5                  15.0
  10      d      Drift        0.2     15.0                 15.2

First we need a way to refer to what twiss computes for fodo: lazy_twiss gives exactly that. It is a lazily-evaluated twiss call that can be read in the same way that twiss can, however nothing is actually computed until it is requested. Furthermore, it will automatically infer the at, cols, base_cols, as_taylor_series and GTPSA_descriptor keyword arguments to twiss based on what you request. Other than those inputs, lazy_twiss accepts all the same arguments as twiss.

tw = lazy_twiss(fodo)
TwissExpr of a Beamline with 10 elements

The tunes of the cell are then tw.q1 and tw.q2. A target is written with ==, and a knob with @knob:

res = optimize!(vary    = [@knob(qf.Kn1), @knob(qd.Kn1)],
                targets = [tw.q1 == 0.25, tw.q2 == 0.25])
Converged (all targets met) with Gauss-Newton: 5 iterations, 6 evaluations (1 with derivatives), 2.19 s
 Target  value         goal     met
 q1      0.2500000029  == 0.25  yes
 q2      0.2500000029  == 0.25  yes
 Knob    before  after          lower  upper
 qf.Kn1  0.36    0.3804445818   -Inf   Inf
 qd.Kn1  -0.36   -0.3805887111  -Inf   Inf

The quadrupole strengths have been changed, and twiss confirms the tunes:

twiss(fodo, at=[])
Twiss:
summ:
 q1     = 0.2500000029386404
 q2     = 0.2500000029327805
 etac   = 0.0010780794056116315
 alphac = 0.0010780802115373334

df:
0×26 DataFrame
 Row │ index  name  kind  s    beta1  phi1  dx   x    beta2  phi2  dy   y    slip  alpha1  alpha2  ⋯
     │                    [m]  [m]    [2π]  [m]  [m]  [m]    [2π]  [m]  [m]  [m]   [1]     [1]     ⋯
─────┴──────────────────────────────────────────────────────────────────────────────────────────────
                                                                                  11 columns omitted

undo!(res) would set the knobs back to where they were, and optimize!(res) continues a match that stopped early, with the same solver and maxiter.

Now let’s make the chromaticities \(+1\) in both planes with the sextupoles. The chromaticities are tw.dq1 and tw.dq2. They are only defined without synchrotron motion, so for a beamline with RF cavities use lazy_twiss(ring; rf_on=false).

res = optimize!(vary    = [@knob(sf.Kn2), @knob(sd.Kn2)],
                targets = [tw.dq1 == 1, tw.dq2 == 1])
Converged (all targets met) with Gauss-Newton: 1 iterations, 2 evaluations (1 with derivatives), 0.0144 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     8.676933672   -Inf   Inf
 sd.Kn2  -1.2    -17.22903302  -Inf   Inf

Quantities and Locations

Every summary value and every numeric column of twiss is available from a lazy twiss, written in the same way as for the result of twiss: tw.q1, tw.dq1, tw.q1[J1=1], tw.beta1[qd], tw.beta1[qd, :exit], tw.beta1[[b], :], tw.beta1["q*"], tw.dbeta1[qd], tw.h3000[1], and so on. Unlike for twiss, you do not choose truncation orders or rows: lazy_twiss knows what you need based on what you ask for.

You can form arbitrary expressions with the Twiss output to serve as targets/minimization goals using ordinary arithmetic and functions. For example, the square of the beta function at qd minus five times the average of the alpha function through the bends:

e = tw.beta1[qd]^2 - 5*mean(tw.alpha1[[b], :])
beta1[qd#6]^2 - (5 * (sum(alpha1[b#4], alpha1[d#5], alpha1[b#9], alpha1[d#10]) / 4))

The h terms are complex numbers. value gives them as such, but a target or a quantity to minimize needs their real and imag parts separately.

value computes an expression. Only the rows and columns of twiss that it needs are computed:

value(e)
21.37293446156831

A location with several places gives a vector, and arithmetic and comparisons apply to each of its entries. sum, mean, maximum, and minimum reduce it to one expression:

value(tw.beta1["q*"]) # beta1 at qf and at qd
2-element Vector{Float64}:
 25.130558884932828
  4.608524749455157
value(maximum(tw.beta1[:]))
25.130558884932892

A phase advance between two points is simply a difference:

value(tw.phi1[qd] - tw.phi1[qf]) # in units of 2π
0.11776925312699645

Anything else can be included with lazy: lazy(f) is the result of the function f(), computed from the lattice itself when it is needed. For example, the field gradient of qf in this beamline:

value(lazy(() -> fodo[1].Bn1))
-22.842477483551402

Values and Derivatives

SciBmad.value_and_jacobian gives the values of expressions and their exact derivatives with respect to knobs, for your own purposes. It is not exported, because DifferentiationInterface exports a function of the same name:

v, J = SciBmad.value_and_jacobian([tw.beta1[qd], tw.q1], [@knob(qf.Kn1), @knob(qd.Kn1)])
J # [dbeta1/dqf dbeta1/dqd; dq1/dqf dq1/dqd]
2×2 Matrix{Float64}:
 -29.2363   -0.573746
   1.01593   0.180136

deriv(expr, knob) is the derivative of an expression with respect to a knob as a new expression, as for the orbit response matrix in Orbit Correction. Such derivatives can be used like any other expression, also in targets. For more, see Parametric Normal Form.

More on Optimization

The next pages of this section cover:

optimize! — Function.

optimize!(; vary, targets=[], minimize=[], solver=GN(), maxiter=50, verbose=false,
          callback=nothing, state=nothing)
optimize!(prob::OptimizeProblem; solver=GN(), maxiter=50, verbose=false, callback=nothing,
          state=nothing)
optimize!(res::OptimizeResult; solver=res.solver, maxiter=res.maxiter, verbose=false,
          callback=nothing)

Varies the Knobs vary (also obj => :property pairs) until the Targets targets are met and the objectives minimize are as small as possible, and leaves the lattice there. Targets and objectives are written with expressions (LatticeExpr) of the quantities of a lazy_twiss:

tw = lazy_twiss(cell)
optimize!(vary=[@knob(qf.Kn1), @knob(qd.Kn1)], targets=[tw.q1 == 0.25, tw.q2 == 0.25])

The solvers GN (Gauss-Newton, the default) and LM (Levenberg-Marquardt) solve least-squares problems: targets, and at most one objective that is a sum of squares, minimize=sum(abs2, exprs) or abs2(expr), either times a positive number c. The sum of the squared distances from the targets (each times its weight) and of c times the squared expressions is made as small as possible, so targets and expressions are balanced against each other when they cannot all vanish. Larger target weights hold the targets more tightly.

optimize!(vary=[@knob(qf.Kn1), @knob(qd.Kn1)],
          minimize=sum(abs2, [tw.beta1[1] - 8, tw.beta2[1] - 12]))

The derivatives are exact (see SciBmad.value_and_jacobian). Each step is a Gauss-Newton step from the singular value decomposition of the Jacobian: the smallest change of the knobs that meets the targets to first order. Steps that do not reduce the residuals, or where the lattice has no solution (e.g. it is unstable), are rejected and shorter or damped ones taken, so there may be fewer, as many, or more targets than knobs. The Jacobian costs more than the values alone (for many knobs, many times more), so it is kept for the next steps as long as each step reduces the residuals about as much as it predicts. Where a step does clearly worse, the Jacobian is computed anew. Only a newly computed Jacobian, not a kept one, can end the optimization with “no further improvement possible” (see final_jacobian of GN). Knobs stay within their bounds and step limits, and <= and >= targets only count while they are violated. Like every such method it finds a nearby solution: targets of very different size (a tune and a beta function) should get weights that make their residuals comparable. To use another optimizer, see SciBmad.OptimizeProblem.

The solver CMAES (an evolution strategy) needs no derivatives and takes any targets and objectives: targets are constraints, and several objectives are minimized together (see there).

Keyword arguments

  • solver: GN() (default), LM() or CMAES(), with their settings

  • maxiter: Maximum number of iterations (generations of CMAES), default is 50

  • verbose: If true, prints the progress of the solver at each iteration. Default is false

  • callback: With CMAES, called as callback(res) with the result so far after each generation (e.g. to save res.state). Default is nothing

  • state: With CMAES, the state of an earlier result to continue from, e.g. saved to a file and loaded in another session: the optimization continues exactly as optimize!(res) would, for the same knobs, targets, objectives and solver (built again). Default is nothing

Returns an OptimizeResult. optimize!(res) continues from the current lattice, with the solver and maxiter of the optimization that returned res unless given; with CMAES it continues from the state of the solver in res.

OptimizeResult — Type.

OptimizeResult

The result of optimize!: converged (all targets met; with GN or LM, an objective and no targets: a minimum was found), status, iterations, the number of evaluations of the targets and objectives and how many of them with the Jacobian (jacobians), the time taken (elapsed, in seconds), the knob values before and after (x0, x), the values of the target expressions and then of the objectives, the sum of squared residuals after each iteration (history), the problem, the solver and maxiter. undo!(res) sets the knobs back to x0; optimize!(res) continues with the same solver and maxiter, unless others are given.

With CMAES the iterations are generations, evaluations counts the candidates, and history holds the best value so far after each generation (see CMAES). archive holds every evaluated candidate (empty for the other solvers): archive.x[c, :] the knob values, archive.f[c, :] the values of the objectives, archive.g[c, :] the target values as g of value``(prob, x) (met where <= 0), archive.t[c, :] the values of the target expressions, archive.run[c], archive.generation[c] and the fidelity level archive.level[c]. runs has the statistics of each run of CMAES, and state its state, from which optimize!(res) continues.

lazy_twiss — Function.

lazy_twiss(bl::Beamline; kwargs...)

The quantities of twiss(bl; kwargs...) as expressions (SciBmad.LatticeExpr), computed only when they are needed (by value, SciBmad.value_and_jacobian or optimize!), and then only at the locations used. Returns a SciBmad.TwissExpr. kwargs are those of twiss (rf_on, a_initial, spin, delta0, …) except at, cols, base_cols, as_taylor_series and GTPSA_descriptor, which are set from the expressions. The truncation orders are chosen from the quantities used; order can be given to use a higher one.

a_initial may be the a of another lazy twiss, e.g. lazy_twiss(line; a_initial=tw.a[end]), to continue the lattice functions of another beamline. initial may be a Context, whose variables can then be knobs, e.g. to match the Twiss parameters at the start of a line: ini = Context(beta1=10.0, beta2=10.0), lazy_twiss(line; initial=ini), @knob(ini.beta1).

Quantities

  • Summary values: tw.q1, tw.q2, tw.q3, tw.etac, tw.alphac, tw.qspin, tw.damp1, … A derivative of an amplitude-dependent value is selected as for the result of twiss, e.g. tw.q1[delta=2] (∂²q1/∂δ²) or tw.q1[J1=1]; tw.dq1 and tw.dq2 are short for the chromaticities tw.q1[delta=1] and tw.q2[delta=1], tw.dq1_n for tw.q1[delta=n].

  • Columns: tw.<column>[location] for every scalar column of twiss, including chromatic derivatives (tw.dbeta1, tw.dx_2) and tw.h<ijkl>.

Locations

The same as for the columns of the result of twiss (see TwissColumn):

  • tw.beta1[ele], tw.beta1[7]: the beginning of the element (placed once, else an error), or of the element with that beamline index. tw.beta1[[ele]]: every placement (a vector).

  • tw.beta1[ele, :exit]: the end of the element.

  • tw.beta1[ele, :]: every integration step of the element, both ends included (a vector; tw.beta1[[ele], :] of every placement). tw.beta1[ele, k]: after k integration steps.

  • tw.beta1[end], tw.beta1[begin]: the end and the beginning of the beamline (or of the part given with start and stop, which vectors are restricted to). end is a beamline index: tw.beta1[end-1] is the beginning of the last element.

  • tw.beta1["q*"], tw.beta1[r"..."]: elements by name, as for findelements (a vector).

  • tw.beta1[(s1, s2)], tw.beta1[:]: every integration step in an s-range, or of the whole beamline (a vector).

Vectors are elementwise: tw.beta1["q*"]^2, tw.beta1["q*"] <= 30 (one target per element), with sum, mean, maximum, minimum and norm.

value — Function.

value(expr)
value(exprs::AbstractArray)

The current value of the expression (LatticeExpr) expr, or of each expression of an array (complex for an h term). Each lazy_twiss used is computed with one twiss call, only at the locations and with the columns the expressions use.

value(prob::OptimizeProblem, x) -> (f, g)

At the knob values x, the values f of the objectives of prob, and for each target g = its weight times (its distance from its goal minus its tol): the target is met where g <= 0. Where the lattice has no solution (e.g. it is unstable), f and g are Inf. The knobs are left at x.

value(prob::OptimizeProblem, X::AbstractMatrix; fidelity=nothing) -> (F, G)

value(prob, x) for each row x = X[c, :] (a candidate): F[c, :] and G[c, :]. Sources that can compute all candidates at once do so (e.g. a lazy dynamic aperture whose knobs are all variables of its ring’s context, with batch_dynamic_aperture); the others are computed once per candidate. A candidate whose values cannot be computed has Inf in its rows. Afterwards the knobs have their values from before the call.

fidelity (a NamedTuple) replaces keyword arguments of the sources that take them, for this call, e.g. fidelity=(n_turns=100,) computes a lazy_dynamic_aperture with 100 turns. It is an error if no source takes one of them, and for those that change the shape of a dynamic aperture (deltas, n_theta, theta_lims).

SciBmad.value_and_jacobian — Function.

SciBmad.value_and_jacobian(exprs, knobs) -> (values, jacobian)
SciBmad.value_and_jacobian(exprs, knobs, x) -> (values, jacobian)

Not exported, because DifferentiationInterface exports a function of the same name: call it as SciBmad.value_and_jacobian.

The current values of the expressions (LatticeExprs) exprs and their exact derivatives in the knobs (Knobs, or obj => :property pairs): jacobian[i, j] is the derivative of exprs[i] (in the order of vec(exprs)) in knobs[j]. For a single expression, the value and its gradient are returned. With x, the knobs are first set to the values x (and stay there).

The derivatives are computed by automatic differentiation: the knobs are made parameters of the truncated power series (GTPSA) of one twiss call per lazy_twiss, with the truncation orders the expressions need, and the knobs are set back to their values afterwards.