Optimizers
HyperShape.Optimizers — Module
HyperShape.OptimizersOptimisers for problems with a box-bounded design vector z and constraints lo ≤ g(z) ≤ hi, linear or not (for example the volume of a projected density). OC and SiMPL treat one inequality themselves (see handles); the others go to the augmented Lagrangian (AugmentedLagrangian).
The module is independent of finite elements: an optimiser sees vectors, bounds and an oracle (see AbstractOracle). A new optimiser is a subtype of Optimizer that implements the four functions of the contract:
state = init(opt, z, oracle) # memory and history
info = step!(opt, state, z, oracle, ctx) # overwrites z with the next design, returns a StepInfo
reset!(opt, state) # forget the history (continuation jump, remeshing)
shrink!(opt, state, factor) # roll back the last step and reduce the next oneAn optimiser that treats constraints itself also declares which ones, with handles and max_native (by default none: every constraint then goes to the augmented Lagrangian, AugmentedLagrangian), and may implement objective_changed! (default reset!).
HyperShape.Optimizers.AbstractOracle — Type
AbstractOracleWhat an optimiser may ask about the problem. Methods to implement for a subtype O:
objective(o::O, z): value of the objective atz(forward problem only). ReturnNaNorInfif the value cannot be computed (for example, the forward problem did not converge); the optimisers treat it as a failed trial.gradient!(dF, o::O, z): writes the derivative∂F/∂z(a dual vector, no metric applied) intodF. The optimisers only call it for thezof their last call toobjectiveon this oracle, so an implementation can reuse the forward state of that call and only pay for the adjoint.bounds(o::O):(lb, ub), the bounds ofz(scalars or vectors of the length ofz), withlb < ub.- The constraints
loᵢ ≤ gᵢ(z) ≤ hiᵢ,i = 1, …, num_constraints(o)(default none):num_constraints(o::O)andconstraint_info(o::O, i)(aConstraintInfo);- linear ones:
linear_constraint(o::O, i)returns(a, V)withgᵢ(z) = aᵀz − V; the optimisers then useaandVexactly, andconstraintandconstraint_gradient!have defaults built from them; - the others:
linear_constraint(o, i)returnsnothingand the oracle implementsconstraint(o::O, i, z)(the scaled value;NaNorInfif it cannot be computed) andconstraint_gradient!(dG, o::O, i, z)(∂gᵢ/∂zat thezof the last call toconstraint(o, i, ·)).
constraints!(g, o, z)(all at once, at a trial design) andweighted_gradient!(the derivative ofw₀ f + Σ wᵢ gᵢ) have defaults built from those.
Methods with a default (Euclidean metric); they are not exported, extend them as Optimizers.inner:
inner(o::O, x, y): inner product of two primal vectors; defaultdot(x, y).riesz!(g, o::O, dF): primal representativeg = M⁻¹ dFof a dual vector; defaultcopyto!(g, dF).
Optimisers only use these functions, broadcasting and global reductions (dot, maximum) on the vectors. If the bounds, the constraints or the objective change (continuation), call reset! on the optimiser.
HyperShape.Optimizers.AugmentedLagrangian — Type
AugmentedLagrangian(update = Bertsekas(); native = :auto, constraint_tol = 1e-4)How a method (DensityMethod, ReactionDiffusion) treats the constraints its step does not treat itself (see handles): they enter the objective of the step through the rule update (Bertsekas), with multipliers updated after every accepted iteration.
native = :auto: in the order of the problem, the first constraints the optimiser handles (up tomax_native) stay with it, the rest go to the augmented Lagrangian (ReactionDiffusion: the constraint built withVolume; none withvolume = nothing); or a tuple of names,(:volume,), or()(all to the augmented Lagrangian; OC needs one constraint of its own). It is the one place where the constraints of the step are named.constraint_tol: the run converges only when every constraint of the augmented Lagrangian is met to it (scaled value).
A run resumed from a Checkpoint continues the multipliers and penalties saved there (the μ0 given now is not applied to them).
Used by default when the problem has constraints the optimiser does not handle; the banner says so.
HyperShape.Optimizers.AugmentedLagrangianOracle — Type
AugmentedLagrangianOracle(inner, al::AugmentedLagrangian, native, z)Oracle of the augmented problem: the objective is f + Σ term(gᵢ) over the absorbed constraints (all but the indices native of inner), whose gradient is one weighted_gradient! of inner; the native constraints are passed through, renumbered 1, …, length(native); z gives the vector type. Like any oracle, gradient! is only valid at the z of the last objective (it throws otherwise). The multipliers λ and penalties μ are vectors over all the constraints of inner (NaN in the native ones). end_iteration! updates them at an accepted design.
HyperShape.Optimizers.Bertsekas — Type
Bertsekas(; μ0 = 1.0, growth = 1.0, progress = 0.25, window = 50, μmax = 100.0)Classical multiplier update (Bertsekas; Rockafellar's form for inequalities and intervals). With y = g + λ/μ and Π the projection onto the bounds [lo, hi] of the constraint:
term = μ/2 (y − Π(y))² − λ²/(2μ), weight = μ (y − Π(y)), λ ← weightthat is λ ← max(0, λ + μ g) for g ≤ 0 and λ ← λ + μ g for an equality (λ > 0 when the upper bound is active, λ < 0 when the lower one is). The penalty μ starts at μ0. With growth > 1 it is multiplied by growth (up to μmax) every window iterations in which the violation is above the tolerance of the augmented Lagrangian and did not fall below progress times the one of the last check (window iterations before; the first check compares with the first iteration); progress = Inf grows it at every check while the constraint is violated. growth = 1 (default) keeps it fixed (then progress and window have no effect: giving them is an error; μmax is not used and any μ0 is accepted), which is what first-order optimisers such as SiMPL need: a large penalty makes the subproblem ill-conditioned. The scaled functionals are of order one, so μ0 = 1 is the neutral value. Bertsekas(μ0 = 0.2, growth = 1.025, window = 1, progress = Inf, μmax = 2.0) is the rule of Kim et al. (2020).
HyperShape.Optimizers.ConstraintInfo — Type
ConstraintInfo(lo, hi; linear = false, design_only = false, field = false)What an optimiser knows about one constraint lo ≤ g(z) ≤ hi (values already scaled): lo = -Inf for g ≤ hi (the usual g ≤ 0), lo = hi for an equality, both finite for an interval. linear: g is affine in z (the oracle then gives (a, V), linear_constraint); design_only: evaluating it solves no state; field: a constraint per point (reserved; always false).
HyperShape.Optimizers.FunctionOracle — Type
FunctionOracle(f, df!; lb = 0.0, ub = 1.0, constraint = nothing, constraints = nothing, metric = nothing)Oracle built from plain functions, for analytical tests and small problems.
f(z): objective value.df!(dF, z): writes∂F/∂zintodF.constraint = (a, V)with a vectora: linear constraintaᵀz ≤ V.constraint = (g, dg!)with functions: nonlinear constraintg(z) ≤ 0,dg!(dG, z)writes∂g/∂z.constraints = ((g₁, dg₁!, lo₁, hi₁), …): several constraintsloᵢ ≤ gᵢ(z) ≤ hiᵢ(taken as nonlinear), instead ofconstraint.metric = m: diagonal metric,inner(x, y) = Σ mᵢ xᵢ yᵢandriesz!(g, dF) = dF ./ m(cell volumes for P0 designs, lumped mass for P1 designs).nothingis the Euclidean metric.
evaluations(o) returns (value, derivative), the number of calls of each kind.
HyperShape.Optimizers.MultiplierUpdate — Type
MultiplierUpdateSupertype of the rules of an augmented Lagrangian (Bertsekas). A rule implements (all public in HyperShape.Optimizers, not exported):
term(u, g, λ, μ, c::ConstraintInfo): what the constraint adds to the objective;weight(u, g, λ, μ, c):∂term/∂g;initial_penalty(u): the penaltyμof every absorbed constraint at the start;update!(u, al::AugmentedLagrangianOracle): newal.λ[i]andal.μ[i]fori in al.absorbedfrom the valuesal.g[i]at the accepted design (al.infos[i]their bounds,al.updatesthe number of updates including this one, counted byend_iteration!,al.vreffree for the rule); returns whether anything changed.
HyperShape.Optimizers.OC — Type
OC(; move = 0.2, damping = 0.5, bisection_tol = 1e-3, max_bisections = 200, constraint_tol = 1e-4,
max_corrections = 8, adapt = (0.7, 1.2), move_min = 1e-3)Optimality criteria update of Andreassen et al. (top88, 2011) for one constraint g(z) ≤ 0:
zᵢ ← clamp(zᵢ Bᵢ^damping, max(lbᵢ, zᵢ - m), min(ubᵢ, zᵢ + m)), Bᵢ = max(0, -∂F/∂zᵢ) / (λ aᵢ),with m = move * (ub - lb) and λ > 0 found by bisection on aᵀz = V, starting from [0, 1e9].
- Linear constraint
aᵀz ≤ V: the bisection stops when(λ₂ - λ₁)/(λ₁ + λ₂) ≤ bisection_toland, as in top88, keeps the design of the last midpoint, so the constraint holds up to the bisection tolerance. Withadapt = nothingthe step is the one of top88. Requiresa > 0. - Nonlinear constraint (for example the volume of a projected density):
a = ∂g/∂zat the current design (floored at1e-12 maximum(a), since a filter can leave tiny or negative entries where a projection saturates; an entry with a zero derivative moves up to the move limit in the direction of descent) and the linearised constraintaᵀz ≤ aᵀzₖ - g(zₖ) - s. The shiftsis then corrected (chord, then bounded secant steps, at mostmax_corrections) until|g(z_new)| ≤ constraint_tol, evaluating the truegonce per correction;sis kept for the next step (reset!clears it). The bisection is solved tomin(bisection_tol, 1e-7)so that the corrections see a smooth function. If the move limit does not allow meeting the constraint, the step is still taken.
Move limits. With adapt = (dec, inc) (default) each entry has its own move limit mᵢ: multiplied by dec when its last step changed sign with respect to the one before, by inc when it kept it, and kept in [move_min, move] (as the move limits of MMA, Svanberg 1987). It damps the oscillation of OC at the interface when a tanh projection is sharp (a step of move is wider than the projection band, about 1/β). reset! (a continuation jump) restores every mᵢ to move; shrink! scales them all, and the retry after a rejected step does not update them. adapt = nothing gives the scalar move limit of top88 (then move_min has no effect: giving it is an error). move can follow a continuation, Continuation(β = proj => […], move = oc => […]) (see set_move!); with adapt it is the ceiling of the limits. The step of the StepInfo is the mean of the limits over all entries (those at a bound included).
The objective is evaluated once per step and the new design is not evaluated (f_new = NaN, kkt = NaN). If the move limit does not allow meeting the constraint (infeasible start), the step is still taken and violation > 0 in the StepInfo.
It also reports the stationarity measure of the design before the step (stationarity!, with the metric of the oracle, which the step does not use).
Domain. The update is multiplicative: it needs lb ≥ 0 (an error at init otherwise; shift the design to [0, 1] or use SiMPL) and it drops the positive part of the derivative (Bᵢ = 0 there). For an objective whose derivative changes sign (a mechanism, an augmented Lagrangian) the fixed point of OC need not be a stationary point: the first step measures the share of the derivative it drops (its positive part over the entries above the lower bound) and solve! reports it when it exceeds 5 % (use SiMPL then).
HyperShape.Optimizers.SiMPL — Type
SiMPL(; linesearch = :armijo, c1 = 1e-4, max_backtracks = 30, max_growth = 10.0, root_tol = 1e-12,
max_root_iterations = 100, constraint_tol = 1e-6, max_corrections = 8)Sigmoidal mirror descent with a projected latent variable (Keith, Kim, Lazarov and Surowiec, arXiv:2409.19341; Kim, Lazarov, Surowiec and Keith, arXiv:2411.19421).
The design is written as z = lb + (ub - lb) σ(ψ) with the sigmoid σ(x) = 1/(1 + e⁻ˣ), so every iterate satisfies the bounds strictly. One step, with g = M⁻¹ ∂F/∂z (see riesz!):
ψ ← ψ - α (g + μ M⁻¹a),where μ ≥ 0 is zero if the constraint aᵀz ≤ V is inactive and otherwise solves aᵀz(ψ) = V (Newton iteration kept inside a bracket).
Step size: α₀ = 1/maximum(abs, g) after init/reset!; afterwards √(α_GBB α_prev) with the generalised Barzilai–Borwein step α_GBB = (ψₖ - ψₖ₋₁, zₖ - zₖ₋₁)_M / |(gₖ - gₖ₋₁, zₖ - zₖ₋₁)_M|, capped at max_growth * α_prev (each rejected trial costs a forward solve). The step is halved until
linesearch = :armijo:F(z_new) ≤ F(z) + c1 ∂F/∂z ⋅ (z_new - z), orlinesearch = :bregman:F(z_new) ≤ F(z) + ∂F/∂z ⋅ (z_new - z) + D(z_new, z)/α, withDthe Bregman divergence of the (scaled) Fermi–Dirac entropy in the metricM.
A trial with a non-finite objective counts as failed. If no step is accepted after max_backtracks halvings, z is left unchanged and accepted = false. The tests allow a decrease lost in rounding (10 eps |F|), so a converged design keeps returning accepted steps with a negligible change instead of a failed line search.
Cost per step: one call to gradient! and one call to objective per trial (the value at the accepted trial is reused as the value of the next step). After init, reset! or a change of z by the caller, one more objective.
Optimality measure (kkt in StepInfo): (1, η)_M with λ = (ψ_trial - ψ)/α at the first trial of the step and η = max(-(z - lb) λ, (ub - z) λ) (eq. 23a of arXiv:2411.19421).
Requires a ≥ 0 (not all zero) in the linear constraint.
Nonlinear constraint g(z) ≤ 0 (for example the volume of a projected density; an extension of the method, which the references only state for a linear volume): at each step a = ∂g/∂z at the current design (floored at 1e-12 maximum(a)) and the linearised constraint aᵀz ≤ aᵀzₖ - g(zₖ) - s takes the place of aᵀz ≤ V. For each trial, the shift s is corrected (chord, then bounded secant steps, at most max_corrections, one evaluation of the true g each) until -constraint_tol ≤ g(z_trial) ≤ 0, aiming at -constraint_tol/2, so every accepted iterate is feasible; s is kept between steps (reset! clears it) and divided by 4 each time the line search halves the step (the linearisation error falls with the square of the step). A tolerance much larger than 1e-6 can stall the line search, because the slack of the constraint then moves the objective more than the expected decrease. At an infeasible design (g > constraint_tol: a start or a continuation jump) the step restores feasibility: the first trial with a finite objective is accepted, without the Armijo test.
It also reports the stationarity measure of the design before the step (stationarity!), the criterion of the paper.
HyperShape.Optimizers.StepInfo — Type
StepInfo{K}What step! reports about one design step, for an optimiser that handles K constraints.
accepted:falseif no acceptable step was found;zis then left unchanged.f: objective at the design before the step.f_new: objective at the new design, if the optimiser evaluated it (NaNotherwise).kkt: optimality measure at the design before the step, if the optimiser computes one (NaNotherwise).change:maximum(abs, z_new - z_old).step: step size (SiMPL) or move limit (OC) used; with adaptive move limits, their mean over all entries.evaluations: number of calls toobjectivein the step (forward solves).stationarity: stationarity measure at the design before the step,S = ‖z − P(z − g)‖_M(seestationarity!);NaNif the optimiser does not compute it.violations: for each constraint, its violation at the returned design (seeConstraintInfo;max(0, g(z))forg ≤ 0).violationis the largest.multipliers: for each constraint, its multiplier (linearised at the current design if it is nonlinear) used in the step: in OC theλof the last bisection (never0), in SiMPL the shiftμof the volume projection (0if the constraint is inactive);NaNwhen the step fails.
OC and SiMPL report StepInfo{1} (with violation 0 and multiplier NaN when the problem has no constraint), built with StepInfo(accepted, f, f_new, kkt, change, step, violation, evaluations, multiplier, stationarity).
HyperShape.Optimizers.bounds — Function
bounds(oracle) -> (lb, ub)Bounds of the design vector. See AbstractOracle.
HyperShape.Optimizers.computes_kkt — Method
computes_kkt(optimizer) -> BoolWhether the optimiser reports an optimality measure (kkt in StepInfo); StopCriteria(kkt_tol) needs one.
HyperShape.Optimizers.constraint — Method
constraint(oracle, i, z) -> Float64Value of the constraint i at z. Default, for a linear constraint: aᵀz − V. See AbstractOracle.
HyperShape.Optimizers.constraint_gradient! — Method
constraint_gradient!(dG, oracle, i, z) -> dGWrites ∂gᵢ/∂z into dG, for the z of the last call to constraint(oracle, i, ·). Default, for a linear constraint: a. See AbstractOracle.
HyperShape.Optimizers.constraint_info — Function
constraint_info(oracle, i) -> ConstraintInfoDescription of the constraint i. See AbstractOracle.
HyperShape.Optimizers.constraint_tol — Method
constraint_tol(opt::Optimizer) -> Float64Tolerance to which the optimiser meets a nonlinear constraint; the loop only declares convergence when the constraint holds to it. Default Inf (no requirement); OC and SiMPL return their constraint_tol.
HyperShape.Optimizers.constraints! — Method
constraints!(g, oracle, z) -> gValues of all the constraints at z (forward solves only, no derivatives): what a method that checks a trial design needs (GCMMA). Default: constraint(oracle, i, z) for each i.
HyperShape.Optimizers.end_iteration! — Method
end_iteration!(oracle, z) -> BoolCalled by the optimisation loop after every accepted iteration, at the accepted design z. An oracle whose objective depends on the iteration (the augmented Lagrangian: its multipliers) updates itself and returns true when its objective changed; the loop then calls objective_changed! on the optimiser. Default: nothing, false.
HyperShape.Optimizers.gradient! — Function
gradient!(dF, oracle, z)Writes ∂F/∂z into dF, for the z of the last call to objective. See AbstractOracle.
HyperShape.Optimizers.handles — Method
handles(opt::Optimizer, c::ConstraintInfo) -> BoolWhether the optimiser treats the constraint c itself (natively), as OC and SiMPL do with one inequality g ≤ 0 that costs no forward solve (design only). The constraints it does not handle go to the augmented Lagrangian. Default false. solve! asks it before scaling the constraints: only the kind of each bound (0, finite or ±Inf), linear, design_only and field are meaningful then.
HyperShape.Optimizers.init — Function
init(opt::Optimizer, z, oracle) -> stateCreates the memory of the optimiser for the starting design z.
HyperShape.Optimizers.inner — Method
inner(oracle, x, y)Inner product of two primal vectors in the metric of the design. Default: dot(x, y). Not exported (Gridap exports another inner): use Optimizers.inner.
HyperShape.Optimizers.linear_constraint — Method
linear_constraint(oracle, i) -> (a, V) or nothingThe constraint i as aᵀz − V when it is linear. Default nothing. See AbstractOracle.
HyperShape.Optimizers.max_native — Method
max_native(opt::Optimizer) -> IntHow many constraints the optimiser can treat natively (see handles). Default 0.
HyperShape.Optimizers.memory — Method
memory(opt::Optimizer, state, z) -> NamedTuple or nothingMemory of the optimiser after an accepted step to z, saved in a checkpoint (and carried across a rebuild of the problem) so that a resumed run continues as the uninterrupted one: a named tuple whose entries are real numbers or vectors with one entry per entry of z (fields of the design space, which a change of mesh can transfer). The vectors may be those of state: the loop copies them (as Vector{Float64}) and checks their length; numbers come back as Float64, and the order of the entries is kept. Default nothing: not saved, the resumed run starts from init.
HyperShape.Optimizers.multipliers — Method
multipliers(al::AugmentedLagrangianOracle), penalties(al)Multipliers λ and penalties μ, one per constraint of the inner oracle (NaN in the native ones).
HyperShape.Optimizers.num_constraints — Method
num_constraints(oracle) -> IntNumber of constraints. Default 0. See AbstractOracle.
HyperShape.Optimizers.objective — Function
objective(oracle, z)Value of the objective at z. See AbstractOracle.
HyperShape.Optimizers.objective_changed! — Method
objective_changed!(opt::Optimizer, state) -> stateTells the optimiser that its objective changed between two iterations (the multipliers of an augmented Lagrangian) while the design and the bounds did not. Default: reset!. SiMPL forgets its value and gradient but keeps its step size (Barzilai–Borwein), without which an augmented Lagrangian updated every iteration converges much more slowly; OC keeps nothing between steps.
HyperShape.Optimizers.requires_native — Method
requires_native(opt::Optimizer) -> BoolWhether the optimiser needs one constraint of its own to work (OC: its bisection is on the multiplier of that constraint). Default false.
HyperShape.Optimizers.reset! — Function
reset!(opt::Optimizer, state)Forgets the history of the optimiser (step-size memory, previous iterates), for example after a continuation jump or a remeshing. The next step behaves like the first one.
HyperShape.Optimizers.restore_memory! — Method
restore_memory!(opt::Optimizer, state, z, mem::NamedTuple) -> stateRestores into state, just created by init(opt, z, oracle), the memory mem returned by memory.
HyperShape.Optimizers.riesz! — Method
riesz!(g, oracle, dF)Writes into g the primal representative M⁻¹ dF of the dual vector dF. Default: copyto!(g, dF).
HyperShape.Optimizers.set_move! — Method
set_move!(opt::OC, move) -> optChanges the move limit of opt (the ceiling of the adaptive limits; with adapt it must be at least move_min). Used by a Continuation of move; the optimisation loop calls reset! after it, which restores the adaptive limits to the new value. Without reset! the limits are capped at the new value from the next step.
HyperShape.Optimizers.shrink! — Function
shrink!(opt::Optimizer, state, factor)Called by the loop after it rejected the last step and restored z to its value before that step. Rolls back the memory of the optimiser to the start of that step and multiplies the size of the next step (or the move limit) by factor (0 < factor < 1). Consecutive calls accumulate; the reduction is dropped once a step stands (the next step! is called without a shrink! in between) or after reset!.
HyperShape.Optimizers.stationarity! — Method
stationarity!(w, oracle, z, g, ga, a, V) -> SStationarity measure of the paper of SiMPL (Kim, Lazarov, Surowiec, Keith, 2024): S = ‖z − P(z − g)‖_M, with g = M⁻¹ ∂F/∂z (see riesz!), M the metric of the oracle and P the projection, in that metric, onto the bounds and the constraint aᵀz ≤ V (a = nothing: bounds only; a nonlinear constraint is linearised at z). For a diagonal metric P(y) = clamp(y − c M⁻¹a, lb, ub) with the smallest c ≥ 0 that meets the constraint, found by bisection; ga = M⁻¹a (pass riesz!(ga, oracle, a), not a). w is a work vector. It is absolute: it depends on the scale of the objective and on the metric (with the Euclidean metric it depends on the mesh). Returns NaN when no point within the bounds meets the constraint (V below the minimum of aᵀz over the bounds) or when V is not finite. Only broadcasting and reductions: no allocations.
HyperShape.Optimizers.step! — Function
step!(opt::Optimizer, state, z, oracle, ctx) -> StepInfoOverwrites z with the next design. ctx is the read-only context of the optimisation loop (it may be nothing).
HyperShape.Optimizers.violation — Method
violation(c::ConstraintInfo, g) -> Float64How far g is from [lo, hi] (0 inside).
HyperShape.Optimizers.violation — Method
violation(info::StepInfo) -> Float64Largest violation of the constraints at the returned design (0 without constraints).
HyperShape.Optimizers.weighted_gradient! — Method
weighted_gradient!(dL, oracle, w0, w, z) -> dLDerivative of w0 ⋅ f + Σᵢ wᵢ gᵢ at the z of the last calls to objective and constraint. Default: the separate derivatives, added (an implementation can do it in one reverse sweep). Zero weights cost nothing.