Using Other Optimizers

For other methods than the solvers of optimize! (see Solvers), an optimization problem can be given to the optimization packages of Julia. The examples use the FODO cell of Matching and Optimization and its lazy twiss:

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)
tw = lazy_twiss(fodo)
TwissExpr of a Beamline with 10 elements

For other optimizers, SciBmad.OptimizeProblem provides what the optimization packages of Julia ask for. It and its functions are not exported: write them with SciBmad..

prob = SciBmad.OptimizeProblem(vary    = [@knob(qf.Kn1, lower=0.2, upper=0.6),
                                          @knob(qd.Kn1, lower=-0.6, upper=-0.2)],
                               targets = [tw.q1 == 0.25, tw.q2 == 0.25])
OptimizeProblem with 2 knobs, 2 targets
  • prob.x, prob.lower, prob.upper: the current values and the bounds of the knobs

  • SciBmad.residuals(prob, x): the vector of the distances from the targets (each times its weight), at the knob values x, followed by the expressions of the sum of squares to minimize, if any

  • SciBmad.residuals_and_jacobian(prob, x): these and their exact derivatives with respect to the knobs

  • SciBmad.penalty(prob, x): one number, the sum of their squares. It is Inf where the lattice has no solution, for example where it is unstable

  • value(prob, x): the values f of the quantities to minimize (one per entry of minimize), and for each target g, its weight times (its distance from its goal minus its tolerance). A target is met where g <= 0, the form that optimizers with constraints take. Where the lattice has no solution, f and g are Inf

  • value(prob, X): the same for many settings of the knobs at once, one per row of the matrix X: F[c, :] and G[c, :] for the row c (see below)

  • setknobs!(prob, x): sets the knobs

The residuals and the penalty need a problem that GN and LM can solve: targets, and at most one sum of squares to minimize. These functions set the knobs to x, so the lattice is left at the last x an optimizer tried. Finish with setknobs! at the solution, as below.

For example, with NewtonRaphson of NonlinearSolve:

using NonlinearSolve

f = NonlinearFunction((x, p) -> SciBmad.residuals(prob, x);
                      jac = (x, p) -> SciBmad.residuals_and_jacobian(prob, x)[2])
sol = solve(NonlinearProblem(f, prob.x), NewtonRaphson())
setknobs!(prob, sol.u)
twiss(fodo, at=[])
Twiss:
summ:
 q1     = 0.25000000000012507
 q2     = 0.2500000000001256
 etac   = 0.0010780794265294246
 alphac = 0.0010780802324551263

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

With the gradient-based LBFGS of Optim:

import Optim

function g!(G, x) # gradient of the penalty
  r, J = SciBmad.residuals_and_jacobian(prob, x)
  G .= 2 .* (J'*r)
end
res = Optim.optimize(x -> SciBmad.penalty(prob, x), g!, prob.x, Optim.LBFGS())
setknobs!(prob, Optim.minimizer(res))

And with a genetic algorithm that needs no derivatives, here differential evolution of Metaheuristics, within the bounds of the knobs:

import Metaheuristics

bounds = [prob.lower prob.upper]'
res = Metaheuristics.optimize(x -> SciBmad.penalty(prob, x), bounds, Metaheuristics.DE())
setknobs!(prob, Metaheuristics.minimizer(res))

Such a global search can be finished with optimize!(prob), which then starts from its result.

value(prob, X) computes the sources that can compute many settings of the knobs together only once, for example a lazy dynamic aperture whose knobs are all variables of the context of its beamline (see Dynamic Aperture Optimization).

Metaheuristics computes a population in this form with parallel_evaluation = true, here for its multi-objective NSGA-II, with the areas of a dynamic aperture at two δ as the objectives:

lda = lazy_dynamic_aperture(fodo; n_turns=100, emit_1=1e-9, emit_2=1e-10, n_r=11, n_theta=5,
                            max_sig_x=1000, max_sig_y=3000, deltas=[0.0, 0.01])
prob2 = SciBmad.OptimizeProblem(vary     = [@knob(sf.Kn2, lower=0, upper=40),
                                            @knob(sd.Kn2, lower=-40, upper=0)],
                                targets  = [tw.dq1 >= 0, tw.dq2 >= 0],
                                minimize = [-lda.area[1], -lda.area[end]])

f(X) = ((F, G) = value(prob2, X); (F, G, zeros(0, 0)))
options = Metaheuristics.Options(parallel_evaluation=true, iterations=15, f_calls_limit=Inf)
res = Metaheuristics.optimize(f, [prob2.lower'; prob2.upper'],
                              Metaheuristics.NSGA2(N=20, options=options))
Metaheuristics.pareto_front(res)

The third matrix that f returns holds equality constraints, which value does not give: a target written with == is in G, met within its tolerance. NSGA-II computes 2N new candidates per generation, and Metaheuristics stops when it has computed f_calls_limit candidates, before iterations unless that is Inf.

CMAES of optimize! takes the same problems. Some of what it does is its own: it moves candidates onto targets that are linear in the knobs, starts with cheaper settings of the sources (fidelity), and continues from an earlier result. For another optimizer, linear targets are ordinary constraints, and value(prob, X) computes the sources with their own settings (or with those given as its keyword argument fidelity). Periodic knobs are wrapped by value itself, so any value within their bounds is valid.

How It Works

The knobs are made parameters of the truncated power series that twiss computes with (see Parametric Normal Form), with the truncation orders that the quantities and their derivatives need. One twiss calculation per lazy twiss then gives the values and all derivatives, and the lattice is restored afterwards. While this runs, the lattice holds these parameters, so optimize!, value and value_and_jacobian, sb.value and sb.value_and_jacobian must not be used from several threads at once on the same lattice.

Making a parameter a knob sets it, as qf.Kn1 = 0.38 does. If the parameter was set to a deferred expression, that dependence is then broken, also by value and value_and_jacobian. To keep it, vary the variable the expression depends on. Deferred expressions and contexts that knobs act through must not be restricted to a number type such as DefExpr{Float64} or Context{Float64}.

SciBmad.OptimizeProblem — Type.

SciBmad.OptimizeProblem(; vary, targets=[], minimize=[])

An optimization problem: the Knobs vary (or obj => :property pairs), the Targets to meet, and the objectives minimize, expressions (LatticeExpr) whose values should be as small as possible: one expression, or a vector of them, each an objective of its own. optimize! solves it. To use any other optimizer (the type and these functions are not exported: write them with SciBmad.):

  • prob.x, prob.lower, prob.upper: the current values and the bounds of the knobs

  • value(prob, x) -> (f, g): at the knob values x, the values of the objectives f, and for each target g = its weight times (its distance from its goal minus its tol), so that the target is met where g <= 0. Where the lattice has no solution (e.g. it is unstable), all of them are Inf

  • SciBmad.residuals(prob, x): the residual vector of a least-squares problem (see below)

  • SciBmad.residuals_and_jacobian(prob, x): the residuals and their exact Jacobian in the knobs

  • SciBmad.penalty(prob, x): the sum of the squared residuals, Inf where the lattice has no solution (for optimizers that take a scalar and no derivatives)

  • setknobs!(prob, x): sets the knobs

These functions leave the knobs at x.

A least-squares problem has targets and at most one objective, which is a sum of squares c*sum(abs2, exprs) (or c*abs2(expr)) with a positive number c (or none). Its residuals are, for each target, its weight times its distance from its goal (zero where it is met), and then √c times each expression of exprs.

A SciBmad.OptimizeProblem keeps the last Jacobian that optimize! computed for it with GN or LM, so that the next optimize!(prob) (with their default reuse_jacobian=true) starts from it.

SciBmad.residuals — Function.

SciBmad.residuals(prob::OptimizeProblem, x)

The residual vector of the least-squares problem prob at the knob values x (see SciBmad.OptimizeProblem). The knobs are left at x.

SciBmad.residuals_and_jacobian — Function.

SciBmad.residuals_and_jacobian(prob::OptimizeProblem, x) -> (r, J)

The residual vector of the least-squares problem prob at the knob values x (see SciBmad.OptimizeProblem) and its exact Jacobian in the knobs. The knobs are left at x.

SciBmad.penalty — Function.

SciBmad.penalty(prob::OptimizeProblem, x)

The sum of the squared residuals of the least-squares problem prob at the knob values x, or Inf if the lattice has no solution there (e.g. it is unstable). The knobs are left at x.