Targets, Knobs and Solvers¶
This page describes the parts of an optimization in detail: the targets, the quantities to minimize, the knobs, and the solvers. 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
Targets¶
Besides ==, a target can be an inequality:
tw.beta1[qd] <= 30
tw.beta1["q*"] <= 30 # at each of these elements
maximum(tw.beta1[:]) <= 100 # everywhere
An inequality only acts while it is violated. A target counts as met when it is within its
tolerance, which is 1e-8 unless you set it with Target. A weight makes a
target count more or less than the others while they cannot all be met:
Target(tw.q1, 0.25; tol=1e-6)
Target(tw.beta1[qd]; lower=5, upper=30, weight=0.1)
There may be fewer, as many, or more targets than knobs. With more knobs than needed, many solutions exist, and the default solver returns one near the starting point: each step is the smallest change of the knobs that meets the targets to first order. With more targets than can be met, it returns the closest it can get (in the least-squares sense) and reports the match as not converged.
Objectives¶
minimize is for quantities that should just be as small as possible. The solvers GN and LM
(see Solvers) make a sum of squares as small as possible, written
sum(abs2, exprs). For example,
we can minimize the driving terms of a ring with four sextupoles while also requiring that the
chromaticities are +1 (using reim, which returns a tuple of the real and imaginary parts, and
splatting those values with ... into the vector):
twc = lazy_twiss(ring; rf_on=false)
optimize!(vary = [@knob(s1.Kn2), @knob(s2.Kn2), @knob(s3.Kn2), @knob(s4.Kn2)],
targets = [Target(twc.dq1, 1; weight=100, tol=1e-4),
Target(twc.dq2, 1; weight=100, tol=1e-4)],
minimize = sum(abs2, [reim(twc.h3000[1])..., reim(twc.h2100[1])...,
reim(twc.h1020[1])...]))
The sum of the squares of the expressions in minimize and of the distances from the targets
(each times its weight) is made as small as possible. If they cannot all vanish, the result
balances them, so give targets that must hold a larger weight, as here. A positive factor, as in
10*sum(abs2, exprs), weighs all the expressions together.
minimize can also be a vector of expressions, each an objective of its
own, for solvers that take several: CMAES (see
Several Objectives) and other optimizers (see
Using Other Optimizers). GN and LM take only one sum of squares, and
give an error otherwise.
Knobs¶
A knob is any parameter that can be set with object.parameter = value:
@knob qf.Kn1 # an element parameter
@knob qf.Kn1 lower=0 upper=0.6 # with bounds
@knob d.L # also lengths
@knob ring.context.kqf # a variable used by deferred expressions
@knob ring.context.coilstrengths # a vector variable: one knob per entry
@knob ring.context.coilstrengths[2] # one entry of it
@knob qf.Kn1 is the same as Knob(qf, :Kn1). Setting a parameter of an element changes it
everywhere the element is placed (see Defining a Beamline), so @knob(qf.Kn1)
varies all qfs together.
To vary several different elements together, or to build any other knob, use a deferred expression and vary the variable it depends on:
qf.Kn1 = DefExpr(c -> c.kq)
qd.Kn1 = DefExpr(c -> -c.kq)
fodo.context.kq = 0.38
res = optimize!(vary = [@knob(fodo.context.kq)], targets = [tw.q1 == 0.25])
Converged (all targets met) with Gauss-Newton: 2 iterations, 3 evaluations (1 with derivatives), 1.44 s
Target value goal met
q1 0.2499999998 == 0.25 yes
Knob before after lower upper
kq 0.38 0.380413507 -Inf Inf
A variable can also be a vector, e.g. the strengths of many correctors, each set by a deferred
expression such as DefExpr(c -> c.coilstrengths[3]). @knob(ring.context.coilstrengths) then
varies every entry. The result lists them as coilstrengths[1], coilstrengths[2], and so on,
as many as fit in the terminal. print(res) shows all of them.
step limits how much a knob may change in one iteration of GN or LM
(@knob qf.Kn1 step=0.01). A knob is also an expression, so it can appear in targets:
@knob(qf.Kn1) + @knob(qd.Kn1) <= 0.05.
A knob whose effect repeats, such as the phase advance of a phase trombone in
units of 2π, is periodic. Its value is wrapped into [lower, upper), and the solvers move it
across a bound instead of stopping there:
@knob ring.context.dphi1 lower=-0.5 upper=0.5 periodic=true
Solvers¶
optimize! takes Gauss-Newton steps (solver = GN(),
the default), which find a nearby solution. With solver = LM() it uses the
Levenberg-Marquardt method of
BatchSolve instead. Like every such
method, it can stop at a point that small changes cannot improve, even though a solution exists
elsewhere. A better starting point, bounds on the knobs, or a search of the whole range of the knobs
with CMAES (below) then help.
Computing the Jacobian costs more than computing the values alone, for many knobs many times
more. Both methods therefore keep the Jacobian for the next steps as long as each step does about
as well as it predicts, and compute it anew where a step does clearly worse.
GN(reuse_jacobian = false) (or
LM(reuse_jacobian = false)) computes it after every step.
The settings of a solver are given with it, as here, and are listed below. The largest number of
iterations is a keyword argument of optimize!, maxiter (50 by default).
Optimizing the same problem again with optimize!(res), for an earlier
result res, starts
from the last Jacobian of the problem, as in the orbit correction with the
sextupoles turned on in steps.
solver = CMAES() is an evolution strategy. It needs no derivatives, and
searches the whole range between the bounds of the knobs, which every knob must have. It takes any
targets and objectives: targets are constraints, and several objectives are minimized together. It
computes many settings of the knobs at once and needs many more evaluations than GN, so it is
meant for quantities without derivatives, such as the dynamic aperture, and for problems with many
local minima. Its iterations are generations, each a set of settings of the knobs. Dynamic Aperture
Optimization shows it at work.
Target — Type.
Target(expr, value; tol=1e-8, weight=1, name)
Target(expr; lower=-Inf, upper=Inf, tol=1e-8, weight=1, name)
expr == value, expr <= value, expr >= value
A goal for optimize!: the expression (LatticeExpr) expr should equal value,
or lie between lower and upper. The target is met when it is within tol. weight multiplies
its residual, to make it count more or less than the other targets while they are not all met
(with CMAES, it is the scale of a violation).
Knob — Type.
Knob(obj, property; lower=-Inf, upper=Inf, step=Inf, periodic=false, name)
Knob(obj, property, index; lower=-Inf, upper=Inf, step=Inf, periodic=false, name)
Knob(get, set; lower=-Inf, upper=Inf, step=Inf, periodic=false, name="knob")
@knob obj.property lower=... upper=...
@knob obj.property[index] lower=... upper=...
Something that can be varied: the property of obj (a LatElement, a Context, a
Controller, or anything else with obj.property to get and set a number), or a pair of
functions get() and set(value). lower and upper are the bounds used by optimize!
(CMAES needs finite ones), and step the largest change per iteration of GN
and LM.
A periodic knob (e.g. a phase advance) has the same effect at x and at x + (upper - lower):
it is set to its value wrapped into [lower, upper), which must both be finite, and the solvers
move it across a bound instead of stopping there.
If the property is a vector of numbers (e.g. a variable of a Context holding the strengths of
several correctors), the knob stands for one knob per entry, named property[1],
property[2], …, with the same bounds: optimize!, value_and_jacobian and setknobs! vary
each entry. index (or @knob obj.property[index]) is one entry alone.
A Knob is also a LatticeExpr, so it can be used in expressions and targets.
Making a property a knob sets it, as obj.property = value does: if it was set to a deferred
expression, that dependence is replaced by the value.
Examples
k1 = Knob(qf, :Kn1; lower=0, upper=1)
k2 = @knob ring.context.kqd
k3 = @knob ring.context.coilstrengths # one knob per entry of the vector
k4 = @knob ring.context.coilstrengths[2]
GN — Type.
GN(; rcond=1e-10, reuse_jacobian=true, final_jacobian=true)
The Gauss-Newton solver of optimize!, for targets and at most one objective that is a
sum of squares (minimize=sum(abs2, exprs)). Each step is the Gauss-Newton step from the
singular value decomposition of the Jacobian of the residuals; where it does not reduce them, its
half, quarter and eighth are tried, then damped (Levenberg-Marquardt) steps.
rcond: singular values of the Jacobian belowrcondtimes the largest are ignored (knob combinations the targets do not respond to)reuse_jacobian: iftrue, the Jacobian (with its singular value decomposition) is kept for the next steps while they do about as well as it predicts. Iffalse, it is computed after every step. Every step counts as an iteration, so withtruean optimization may take more iterations, but fewer Jacobians.optimize!(prob)andoptimize!(res)also start from the last Jacobian of the same problem (e.g. when correcting the orbit after every step of a slow change of the lattice)final_jacobian: iftrue, only a newly computed Jacobian ends the optimization with “no further improvement possible”: the result is a minimum of the sum of squares. Iffalse, a kept Jacobian may end it too, which saves the last Jacobian; the result is then the minimum according to that Jacobian, off from the true one by about the change of the Jacobian since it was computed
LM — Type.
LM(; reuse_jacobian=true, final_jacobian=true)
The Levenberg-Marquardt solver of optimize! (BatchSolve.levenberg_marquardt!), for
targets and at most one objective that is a sum of squares (minimize=sum(abs2, exprs)).
reuse_jacobian and final_jacobian are as for GN (reuse_jac and final_jac of
BatchSolve.levenberg_marquardt!).
CMAES — Type.
CMAES(; lambda=nothing, sigma=0.3, repeats=1, weights=nothing, reference=nothing,
rng=Random.default_rng(), archive=:all, restarts=:ipop, repair=true, fidelity=[],
ftol=nothing)
The covariance matrix adaptation evolution strategy (CMA-ES, N. Hansen, “The CMA Evolution
Strategy: A Tutorial”, arXiv:1604.00772) as a solver of optimize!. It needs no
derivatives, so it works with any expression (e.g. of a lazy_dynamic_aperture), and
with many candidates at once: each generation, the candidates of all runs are computed with one
value(prob, X) (see SciBmad.OptimizeProblem), e.g. tracked as one bunch.
Every knob needs finite bounds: the search is in the knobs scaled to [0, 1] over their bounds. A candidate outside the bounds is computed at the closest point inside them (a periodic knob wrapped), and its value is increased by a penalty in the squared distance to that point, scaled so that a distance of one standard deviation of the candidates costs twice the interquartile range of the values of the run’s candidates in that generation (separately for the feasible ones and the others).
Targets are constraints: a candidate is feasible if it meets all of them. Feasible candidates
rank before the others, which rank by their mean violation (the mean of the positive g of
value(prob, x), so the weight of a target is the scale of its violation). Feasible candidates
rank by the largest weighted objective, max(w[i]*(f[i] - z[i])) (w the weights, z the
reference), whose minimum is a point of the Pareto front of the objectives where they are in
the proportions of 1/w relative to z. With one objective this is the objective itself.
A target that is a linear function of the knobs (an expression of knobs and lazy(f) alone, e.g.
the strength of a sextupole that follows several knobs, lazy(() -> sf.Kn2) <= 7) is met by
every candidate that is computed: like the bounds, a candidate is moved to the closest point
(in the knobs scaled to [0, 1]) where these targets and the bounds hold, with the same penalty.
This is checked with exact derivatives at three points. A target that depends on a periodic knob
stays an ordinary constraint.
lambda: candidates per run and generation. Default is4 + floor(3*log(n))fornknobssigma: initial step size, as a fraction of the bounds. Default is 0.3repeats: independent runs per weight vector, each from its own random mean. Runs that find the same best value with the same knobs are evidence that it is the best one can getweights: one weight per objective, or a vector of such vectors (or a matrix with one in each row) for runs aiming at several points of the Pareto front (each withrepeatsruns). Default is 1 for eachreference: the pointz. Default is 0 for each objectiverng: the random number generator (a copy of it is used, and kept in the result so thatoptimize!(res)continues exactly as an uninterrupted optimization)archive: which candidates the result keeps,:all,:feasibleor:nonerepair: iftrue(default), a candidate that does not meet a linear target (see above) is computed at the closest point that does, with the same penalty as for the boundsfidelity: cheaper settings of the sources to start with, e.g.[(n_turns=100,), (n_turns=300,)]: each level is the keyword arguments that replace those of every source that takes them (seevalue(prob, X; fidelity)). A run moves to the next level when the best value it found at its level has improved by less thanftolover the last10 + 30n/λgenerations and the median candidate of its generation meets all targets. Its candidates of that generation are then also computed at the new level: they start its best value there (values of different levels are not compared). So are up to 16 of its earlier candidates (the best of a generation, among those that meet all targets, spread over their range of values), and the rank correlation of their values at both levels is inres.state.switches(a warning if it is below 0.5: the cheaper level is then a poor guide;NaNif their values span less than 4ftol, too little to tell)ftol: withfidelity, the change of each objective that counts as an improvement. Default is the resolution of the quantity (for a quantity of alazy_dynamic_aperture, its negative, or a minimum or maximum of them: the step of its grid), otherwise it must be givenrestarts: what a run does when it has converged or stagnates (N. Hansen, “Benchmarking a BI-Population CMA-ES on the BBOB-2009 Function Testbed”, GECCO 2009: its step size has become negligible, its covariance matrix degenerate, or the median of its recent best and median values is not better than of earlier ones, over at least 120 + 30n/λ generations): start again from a new random mean with twice as many candidates (:ipop, the default), with as many (:same), or go on (:none). A run keeps its best candidate
The result res.x is the best candidate of the runs of the first weight vector (of those at the
highest fidelity level; the lattice is left there; res.converged if it meets all targets), and
pareto_front``(res) the candidates of the archive that no other feasible candidate beats
in every objective. res.history is the best value so far of those runs (the largest weighted
objective while feasible, else the mean violation) after each generation, and res.runs the
statistics of each run (best value, its knobs, step size, feasible candidates of the last
generation, candidates per generation, restarts, fidelity level, and the distance of its best knobs,
scaled to [0, 1], from those of the best run of its weight vector).
pareto_front — Function.
pareto_front(res::OptimizeResult)
The candidates of the archive of res (see CMAES) at its highest fidelity level that
meet all targets and that no other such candidate beats in every objective (is at least as good
in all of them and better in one), sorted by the first objective. Returns (x, f, index): x[i]
the knob values (for setknobs!(res.problem, x[i])), f[i, :] the objective values, index[i]
the row of the archive.