Dynamic Aperture Optimization

The quantities of a dynamic aperture can be targets and objectives of an optimization. The examples use two cells of a small ring, as a periodic beamline. Each cell has a sextupole next to each quadrupole, and their strengths are variables of the beamline’s context:

using SciBmad

@elements begin
  qf = Quadrupole(Kn1=1.2, L=0.4)
  d = Drift(L=0.3)
  b = SBend(L=1.5, angle=pi/16)
  qd = Quadrupole(Kn1=-1.2, L=0.4)
  sf1 = Sextupole(Kn2=DefExpr(c -> c.ksf1), L=0.2)
  sd1 = Sextupole(Kn2=DefExpr(c -> c.ksd1), L=0.2)
  sf2 = Sextupole(Kn2=DefExpr(c -> c.ksf2), L=0.2)
  sd2 = Sextupole(Kn2=DefExpr(c -> c.ksd2), L=0.2)
end
cells = Beamline([qf, sf1, d, b, d, qd, sd1, d, b, d,
                  qf, sf2, d, b, d, qd, sd2, d, b, d];
                 species_ref=Species("electron"), pc_ref=3e9)
cells.context.ksf1 = 9.0
cells.context.ksd1 = -15.0
cells.context.ksf2 = 0.0
cells.context.ksd2 = 0.0;

Only the sextupoles of the first cell are on. They make the chromaticities positive:

tw0 = twiss(cells; chrom=2, at=[])
tw0.dq1, tw0.dq2
(0.7197556700084055, 0.7290064663716624)

lazy_dynamic_aperture gives the quantities of dynamic_aperture as expressions, as lazy_twiss does for twiss (see Matching and Optimization). They are read in the same way as the result of dynamic_aperture, and nothing is computed until a value is needed:

settings = (n_turns=50, emit_1=1e-6, emit_2=1e-7, n_r=11, n_theta=5, max_sig_x=80,
            max_sig_y=500, deltas=[0.0, 0.01, 0.02], min_area=0.1)
lda = lazy_dynamic_aperture(cells; settings...)
value(lda.area[:]) # the areas at δ = 0, 1% and 2%
3-element Vector{Float64}:
 0.118
 0.06999999999999999
 0.026000000000000002

These settings are coarse, so that the examples run in seconds: 50 turns, and a grid of 10 particles along each of 5 angles. The areas are fractions of the area of the grid, and change in steps: one radial step of the grid along one angle changes an area by about lda.resolution (0.02 here). A result found with such settings is checked with finer ones (see Repeats).

A First Optimization

The dynamic aperture has no derivatives, so it needs an optimizer that does not use them. The solver CMAES of optimize! is one. Here it makes both areas, at δ = 0 and at δ = 2%, as large as it can, while the chromaticities stay at least 0.5:

using Random

tw = lazy_twiss(cells)
knobs = [@knob(cells.context.ksf1, lower=-12, upper=12),
         @knob(cells.context.ksd1, lower=-18, upper=18),
         @knob(cells.context.ksf2, lower=-12, upper=12),
         @knob(cells.context.ksd2, lower=-18, upper=18)]
res = optimize!(vary = knobs,
                targets = [tw.dq1 >= 0.5, tw.dq2 >= 0.5],
                minimize = [-lda.area[1], -lda.area[end]],
                solver = CMAES(rng = Xoshiro(1)), maxiter = 60)
Converged (maximum number of iterations) with CMA-ES: 60 iterations, 480 evaluations (0 with derivatives), 12.0 s
 Target       value         goal    met
 q1[delta=1]  0.5650527722  >= 0.5  yes
 q2[delta=1]  0.6938113824  >= 0.5  yes
 Minimized   value
 -(area[1])  -0.284
 -(area[3])  -0.198
 Knob  before  after         lower  upper
 ksf1  9.0     2.703259027   -12.0  12.0
 ksd1  -15.0   -4.979512436  -18.0  18.0
 ksf2  0.0     5.280767106   -12.0  12.0
 ksd2  0.0     -9.188741111  -18.0  18.0
 Run  weights  best    feasible  σ              restarts  distance
 1    1        -0.198  7 of 8    0.04944800531  0         0.0

CMAES is the covariance matrix adaptation evolution strategy. In each iteration (a generation) it draws candidates for the knobs from a normal distribution, 8 here (the default for four knobs), and moves the mean and the shape of the distribution toward the best of them. It searches within the bounds of the knobs, which it needs, and starts from a random point within them, not from the current values. rng makes the run reproducible. All settings of CMAES are listed in Solvers.

The objectives are minimized, so the areas enter with a minus sign. With two objectives, CMAES makes the larger of them as small as possible: here, the smaller of the two areas as large as possible. The targets are constraints: a candidate that meets them ranks before every candidate that does not.

The dynamic apertures of all candidates of a generation are computed together. When every knob is a variable of the context, as here, this is one call of batch_dynamic_aperture (see Batched Dynamic Aperture Scans). The beam sizes that set the grid are those of the beamline as it was before the optimization, for all candidates. That is right for sextupoles, which do not change the linear optics, but not for knobs that do, such as quadrupoles.

The beamline is left at the best candidate, and dynamic_aperture confirms its areas:

da = dynamic_aperture(cells; settings..., verbose=false)
da.area
3-element Vector{Float64}:
 0.28400000000000003
 0.26999999999999996
 0.198

Targets

The area should also not fall below a minimum within the range of δ. lda.reach is the largest δ up to which the area stays at least min_area, 0.1 here (see Reading the Result). With the areas of the start, 0.118 at δ = 0 and 0.070 at δ = 1%, it was 0.004. Here it must be at least 2%:

res = optimize!(vary = knobs,
                targets = [tw.dq1 >= 0.5, tw.dq2 >= 0.5, Target(lda.reach; lower=0.02, weight=50)],
                minimize = [-lda.area[1], -lda.area[end]],
                solver = CMAES(rng = Xoshiro(1), repeats = 2), maxiter = 60)
Converged (maximum number of iterations) with CMA-ES: 60 iterations, 960 evaluations (0 with derivatives), 12.1 s
 Target       value         goal     met
 q1[delta=1]  0.5648379039  >= 0.5   yes
 q2[delta=1]  0.5346016111  >= 0.5   yes
 reach        0.02          >= 0.02  yes
 Minimized   value
 -(area[1])  -0.324
 -(area[3])  -0.248
 Knob  before        after         lower  upper
 ksf1  2.703259027   3.953565235   -12.0  12.0
 ksd1  -4.979512436  -5.611826142  -18.0  18.0
 ksf2  5.280767106   3.759923316   -12.0  12.0
 ksd2  -9.188741111  -7.000817866  -18.0  18.0
 Run  weights  best    feasible  σ               restarts  distance
 1    1        -0.248  6 of 8    0.03927225969   0         0.0
 2    1        -0.222  8 of 8    0.004798316767  0         0.08193462214

Candidates that do not meet the targets rank by their mean violation. The violation of a target is its distance from its goal times its weight, so the weight sets the scale of a violation: here a reach that is 0.01 short counts as much as a chromaticity that is 0.5 short.

A target can only guide the search where it changes with the knobs. If the area at δ = 0 is already below min_area, the reach is 0, however bad the candidate is. With bounds of ±20 and ±30 instead of ±12 and ±18, some runs ended in such a region without meeting the targets: choose bounds that exclude settings far from any useful one.

Repeats

repeats = 2 above made two independent runs, each from its own random starting point. The table at the end of the result shows the best value of each, and the distance of its best knobs from those of the best run (the root mean square of the differences, as fractions of the bounds). The same is in res.runs:

[(r.best, r.distance) for r in res.runs]
2-element Vector{Tuple{Float64, Float64}}:
 (-0.24799999999999994, 0.0)
 (-0.22199999999999998, 0.08193462214021291)

Runs that end at the same value with the same knobs are evidence that this is the best that can be found. Here the values agree to about one grid step, but the knobs do not: they differ most in ksd1 - ksd2, 10.4 in run 1 and 1.2 in run 2. The reason is the beamline: its two cells are identical, so the chromaticities depend only on ksf1 + ksf2 and ksd1 + ksd2. Along ksd1 - ksd2 the areas change slowly, and the coarse grid sees this as irregular jumps of a grid step, so it cannot tell such settings apart. A finer grid with more turns can:

for r in res.runs
  setknobs!(res.problem, r.x)
  dafine = dynamic_aperture(cells; settings..., n_r=41, n_theta=15, n_turns=200, verbose=false)
  println("run ", r.run, ": ", dafine.area)
end
setknobs!(res.problem, res.x);
run 1: [0.2752916666666667, 0.2442083333333334, 0.20558333333333334]
run 2: [0.203375, 0.1857916666666667, 0.16279166666666667]

On it, run 2 is clearly better: 0.21 against 0.15 at δ = 2%. Compare candidates only with the same settings (grid, number of turns, number type): the areas on the finer grid are smaller than on the coarse one for both runs.

Several Objectives

With several objectives CMAES minimizes the largest weighted one, max(w[i]*(f[i] - z[i])), with the weights w and the reference point z (0 by default). Its minimum is a point of the Pareto front, where no objective can be improved without making another worse, and where the objectives are in the proportions 1/w relative to z. Several weight vectors make runs for several points of the front:

res = optimize!(vary = knobs,
                targets = [tw.dq1 >= 0.5, tw.dq2 >= 0.5],
                minimize = [-lda.area[1], -lda.area[end]],
                solver = CMAES(rng = Xoshiro(1), weights = [[1, 1], [1, 0.5], [0.5, 1]]),
                maxiter = 60)
front = pareto_front(res)
front.f
1×2 Matrix{Float64}:
 -0.35  -0.248

pareto_front(res) takes the candidates of all runs that meet the targets and that no other candidate beats in both areas. front.x[i] are the knob values of the row i, which setknobs!(res.problem, front.x[i]) sets.

Fidelity Levels

A dynamic aperture with few turns is cheaper and usually larger than with many. fidelity starts with cheaper settings and moves to more expensive ones:

res = optimize!(vary = knobs,
                targets = [tw.dq1 >= 0.5, tw.dq2 >= 0.5, Target(lda.reach; lower=0.02, weight=50)],
                minimize = [-lda.area[1], -lda.area[end]],
                solver = CMAES(rng = Xoshiro(1),
                               fidelity = [(n_turns=50,), (n_turns=200, n_r=21)]),
                maxiter = 100)
res.state.switches
1-element Vector{Any}:
 (run = 1, generation = 64, level = 2, correlation = 0.9240164263936983)

Each level replaces these settings of the lazy dynamic aperture. A run usually goes through three stages: no candidate meets the targets; a few do, near the edge of what is allowed; many do, and the objectives improve. More turns make the dynamic aperture smaller, so moving up in the second stage would make the candidates miss the targets again, at a higher cost. A run therefore moves up only when two things hold. Its best value has improved by less than ftol (by default the grid step of the objectives) over the last 10 + 30n/λ generations, for n knobs and λ candidates. And the median candidate of its generation meets the targets: the median shows the state of the whole population, while the best value can come from one lucky candidate.

When a run moves up, some of its earlier candidates are computed at the new level as well. The rank correlation of their values at both levels is in res.state.switches (0.96 here), and CMAES warns if it is below 0.5: the cheaper level is then a poor guide. The result res is that of the highest level, here on the grid with 21 radial points, so its values cannot be compared with those of the other examples.

Linear Targets and Periodic Knobs

Knobs are often combinations of magnet strengths. Here the strengths of each family are a common part, which sets the chromaticities, and a difference between the cells, which does not:

sf1.Kn2 = DefExpr(c -> c.kf + c.hf)
sf2.Kn2 = DefExpr(c -> c.kf - c.hf)
sd1.Kn2 = DefExpr(c -> c.kd + c.hd)
sd2.Kn2 = DefExpr(c -> c.kd - c.hd)
cells.context.kf, cells.context.hf = 4.5, 4.5 # (the strengths of the start)
cells.context.kd, cells.context.hd = -7.5, -7.5

res = optimize!(vary = [@knob(cells.context.kf, lower=-12, upper=12),
                        @knob(cells.context.hf, lower=-12, upper=12),
                        @knob(cells.context.kd, lower=-18, upper=18),
                        @knob(cells.context.hd, lower=-18, upper=18)],
                targets = [tw.dq1 >= 0.5, tw.dq2 >= 0.5,
                           Target(lazy(() -> cells[sf1].Kn2); lower=-12, upper=12),
                           Target(lazy(() -> cells[sf2].Kn2); lower=-12, upper=12),
                           Target(lazy(() -> cells[sd1].Kn2); lower=-18, upper=18),
                           Target(lazy(() -> cells[sd2].Kn2); lower=-18, upper=18)],
                minimize = [-lda.area[1], -lda.area[end]],
                solver = CMAES(rng = Xoshiro(1)), maxiter = 60)
Converged (maximum number of iterations) with CMA-ES: 60 iterations, 480 evaluations (0 with derivatives), 6.56 s
 Target       value         goal              met
 q1[delta=1]  0.6029170078  >= 0.5            yes
 q2[delta=1]  0.6090852307  >= 0.5            yes
 lazy(...)    3.530932593   in [-12.0, 12.0]  yes
 lazy(...)    4.543927837   in [-12.0, 12.0]  yes
 … 2 more
 Minimized   value
 -(area[1])  -0.284
 -(area[3])  -0.248
 Knob  before  after         lower  upper
 kf    4.5     4.037430215   -12.0  12.0
 hf    4.5     -0.506497622  -12.0  12.0
 kd    -7.5    -6.730106786  -18.0  18.0
 hd    -7.5    0.2515646215  -18.0  18.0
 Run  weights  best    feasible  σ             restarts  distance
 1    1        -0.248  8 of 8    0.0131931937  0         0.0

The limits of the magnets are targets that are linear functions of the knobs. CMAES finds such targets itself, and moves every candidate to the closest point where they hold, as it does with the bounds, so that no candidate is lost to them. Only targets written with knobs, lazy functions and arithmetic are checked for this.

A knob whose effect repeats, such as the phase advance of a phase trombone, is made periodic (see Knobs): CMAES then wraps it into its bounds instead of stopping at them.

Restarts

A run that has converged, or whose best and median values have stopped improving over many generations (at least 120 + 30n/λ), starts again from a new random point with twice as many candidates (restarts = :ipop, the default). It keeps its best candidate. res.runs[i].restarts counts the restarts. There is no shorter limit: in the second stage above, a run can go a few dozen generations without a better candidate and still not be stuck.

Continuing and Saving

optimize!(res; maxiter = 20) continues an optimization exactly as if it had not stopped. To keep the progress of a long optimization in a file, save res.state after each generation with callback, for example with JLD2:

using JLD2

res = optimize!(vary = knobs,
                targets = [tw.dq1 >= 0.5, tw.dq2 >= 0.5, Target(lda.reach; lower=0.02, weight=50)],
                minimize = [-lda.area[1], -lda.area[end]],
                solver = CMAES(rng = Xoshiro(1)), maxiter = 1000,
                callback = r -> jldsave("da-opt.jld2"; state = r.state))

The state holds every candidate computed (res.archive) and everything needed to continue. res itself also holds the lattice, which cannot be stored in a file and loaded again (its deferred expressions are functions). In another session, build the beamline, the knobs, the targets, the objectives and the solver in the same way, and continue from the saved state:

res = optimize!(vary = knobs,
                targets = [tw.dq1 >= 0.5, tw.dq2 >= 0.5, Target(lda.reach; lower=0.02, weight=50)],
                minimize = [-lda.area[1], -lda.area[end]],
                solver = CMAES(rng = Xoshiro(1)), maxiter = 1000,
                state = load("da-opt.jld2", "state"))

maxiter counts the generations of this call.

lazy_dynamic_aperture — Function.

lazy_dynamic_aperture(ring::Beamline; kwargs...)

The quantities of dynamic_aperture(ring; kwargs...) (a DynamicAperture) as expressions, computed only when they are needed (by value or an optimization). kwargs are those of dynamic_aperture except output_file and verbose. The quantities are read as from the result of dynamic_aperture, by position:

  • da.x[j, i], da.y[j, i], da.r[j, i] (angle j, δ i), da.area[i], da.reach: expressions

  • da.resolution, da.deltas, da.thetas, da.min_area: plain numbers, from the keyword arguments

e.g. da.area[end], da.area[:], da.r[:, 1]. For many candidates of the knobs at once (a generation of CMAES, or value(prob, X)), it is computed with batch_dynamic_aperture when every knob is a variable of the context of ring, with what that function does (e.g. the beam sizes of the ring as it is, for all candidates), else with one dynamic_aperture per candidate. The dynamic aperture has no derivatives: SciBmad.value_and_jacobian, deriv and the solvers GN and LM cannot use these expressions.