Methods
HyperShape.Methods — Module
HyperShape.MethodsOptimisation problems and methods. A method is an operator z ↦ z⁺ over the functionals; all methods share one loop (evaluate, differentiate, step, accept or reject, continuation, stopping, checkpoint) and only the step is specific:
DensityMethod: density methods; the step is anyOptimizerofHyperShape.Optimizers(OC, SiMPL).ReactionDiffusion: reaction–diffusion of a level set (through an interface map) or of a density, with the volume met exactly at every step.
Level-set methods (phase 2) will plug into the same loop.
HyperShape.Methods.AbstractMethod — Type
AbstractMethodSupertype of the methods (DensityMethod, ReactionDiffusion; level set later). All methods share the loop of solve! (evaluation, acceptance, continuation, augmented Lagrangian, stopping, checkpoint, output); a method only gives its step and what the step sees of the problem, through four functions (public, not exported):
stepper(m): the step, anOptimizer(the supertypeHyperShape.Optimizer; its contractinit,step!,reset!,shrink!,memory,restore_memory!,objective_changed!is writtenHyperShape.Optimizers.init, …, public); the same object at every call (a continuation compares it);build_oracle(m, problem): the oracle the step sees (objective, gradient, constraints, bounds, metric); for now it must be aHyperShape.Methods.FunctionalOracle(internal: its interface may change), built for example withFunctionalOracle(problem, metric);augmented_lagrangian(m): theAugmentedLagrangianof the constraints the step does not treat;check_problem(m, problem): errors when the run starts (default: none).
method_label(m) (default: the name of the type) and metric_label(m) (default: none) go to the banner, with the lines of banner_lines(m, problem) (default: none; a vector of (text, colour)). feasible_start(m) (default true): whether a starting design that violates the native constraint is scaled to meet it before the first step (ReactionDiffusion: false, its step lowers the volume). A step with linear solves of its own reports them with HyperShape.step_solves(opt, state) (default nothing: none), which the loop records in history.step_solves. The internal hook HyperShape.Methods.reports_stationarity(opt) (default true) says whether the step reports the stationarity measure (the column S of the table).
HyperShape.Methods.Checkpoint — Type
Checkpoint(; filepath, every)Writes the state of the optimisation to the folder filepath every every accepted iterations, and also when the optimisation stops or fails: checkpoint.toml (format version 4, with the column step_solves in the history; load_checkpoint also reads version 3: iteration, continuation stage, scales of the functionals by name, who treats each constraint and the multipliers and penalties of the augmented Lagrangian by name, the offsets of the linear constraints, the method and the optimiser, sizes and the names of the other files; the discretisation and its number of rebuilds), z_<iteration>.bin (the design, raw Float64), history_<iteration>.csv and, for optimisers that save one, memory_<iteration>.bin (see memory: its numbers and then its vectors, raw Float64). These are the fields of an OptState. The data files are written first and checkpoint.toml last, under a temporary name and then renamed, so they always belong to the same iteration; older files are then deleted. Resume with solve!(…; resume = filepath) (or the result of load_checkpoint).
HyperShape.Methods.Continuation — Type
Continuation(; every, close_early = false, name = object => values, …)Continuation of parameters in stages: Continuation(β = proj => [1, 2, 4, 8, 16, 32]; every = 40) (with proj a TanhProjection) uses β = 1 in the first stage, 2 in the second, and so on. A stage ends after every iterations, or when the optimiser finds no acceptable step; with close_early = true, also when the StopCriteria are met (by default they only act in the last stage: early stages can look converged on a grey plateau before the topology forms). The optimisation can only stop in the last stage. At each jump the memory of the optimiser is forgotten (reset!), which costs one more forward solve. All value lists have the same length (the number of stages). Supported objects: Parameter (any number of the user: the penalty of the interpolation, a load factor), TanhProjection (β, through set_beta!) and OC (its move limit, through set_move!: Continuation(β = proj => [1, 2, 4, 8, 16], move = oc => [0.2, 0.2, 0.1, 0.05, 0.025]; every = 50), the same oc given to DensityMethod).
HyperShape.Methods.DensityMethod — Type
DensityMethod(optimizer; metric = default_metric(optimizer), lagrangian = AugmentedLagrangian())Density method (SIMP, RAMP or any interpolation written by the user in the weak forms): the step is optimizer (any Optimizer: OC(…), SiMPL(…)). metric: LumpedMass(dΩ), Euclidean(), a vector of positive weights (one per entry of z: inner(x, y) = Σ mᵢ xᵢ yᵢ), an object of the user with a method metric_weights(m, z) -> Vector (called once at the start of solve! and again after each rebuild of the problem), or a named tuple with one of them per block of z. SiMPL uses it in its step and its optimality measure; its default is LumpedMass() (independent of the mesh; the banner marks it as the default). OC uses it only for the stationarity measure (see StopCriteria); its default is Euclidean(), which makes that measure depend on the mesh. Another optimiser has no default unless it defines default_metric.
lagrangian: how the constraints the optimiser does not treat itself are handled, an AugmentedLagrangian (default AugmentedLagrangian(): Bertsekas with a fixed penalty μ = 1, multipliers updated after every accepted iteration, the first constraints the optimiser handles kept native). It is used only when there is such a constraint, or when its native names fewer than the optimiser would take.
HyperShape.Methods.Discretization — Type
DiscretizationSupertype of the discretisations given to solve!(…; discretization): they say whether the problem is built again during the run, when, and how. FixedMesh() (the default) never does; HyperShape.Methods.RebuildCheck does it on the same mesh; adaptive meshes come later. The contract (public, not exported):
needs_setup(d): whether the problem must have factories (Optimization(model; design_setup, physics_setup));due(d, k, info, history, ctx) -> Bool: after the accepted iterationk(not the last one, nor the iteration a run resumes from), whether to rebuild;historyis the liveOptHistory(its firsthistory.nentries are filled);rediscretize(d, problem, state::OptState, ctx) -> Optimization: the new problem (for exampleHyperShape.Methods.rebuild(problem), orrebuild(problem; what = :physics)to keep the design), called withctx.phase == :setup;solve!checks it (new variables, unless the design is kept, and new functionals; the same blocks and number of values of z, the same frozen cells, the same constraints with the same bounds and kind, the same monitors and output, a continuedTanhProjectionin the new maps) and continues fromstate. A change of mesh (another number of values) is not supported yet;discretization_label(d): the line of the banner.
A rebuild costs the calls of the factories, one forward solve and one filter (counted in the summary of the run, not in the rows of the history). An error at a rebuild, or before the first iteration after it, keeps the state of the rebuild (with the memory of the optimiser) in problem.state[] and in the checkpoint.
HyperShape.Methods.DoubleWell — Type
DoubleWell(; W = 0.25, η = 10.0, T = 25.0, cfl = :auto, scheme = :implicit, settle = true, substeps = nothing)The double-well reaction of ReactionDiffusion (Takezawa, Nishiwaki and Kitamura 2010; Kim et al. 2020, loop 2), given as ReactionDiffusion(; κ, reaction = DoubleWell()) (or τ = κ/ℓ²). The design is a density φ ∈ [lb, ub] (normally bounds = (0.0, 1.0), read through Identity() and an interpolation in the weak forms) that evolves by
∂φ̂/∂t = τ ℓ² Δφ̂ − W w′(φ̂) − 30 w(φ̂) (η C g/m + λ), w(φ̂) = φ̂² (1 − φ̂)², φ̂ = (φ − lb)/(ub − lb),with C the normalisation of the method (normalize, L2Norm() by default with the well), g/m the sensitivity density and λ the multiplier of the volume, found exactly at every substep (ExactVolume). Both the sensitivity and the multiplier are weighted by 30 w(φ̂), which vanishes at 0 and 1: the reaction only moves the interface and holes are not nucleated, so the start needs one (built with hole_seed(Vφ; bounds = (0.0, 1.0), …)). The well keeps the design close to 0/1 with an interface of width ξ = √(κ / 2W). κ = τ ℓ² is a physical parameter, the same on every mesh: on a coarse mesh the interface is thinner than a cell. With the well κ (or τ) is a number: the substeps are set from it once at the start, so a Continuation of τ (or of Δt) is refused.
W: height of the well (barrierW/16).η: gain of the sensitivity. Takezawa et al. useW = 1/4andη = 20withg/‖g‖_L²;η = 10withL2Norm()(|D| g/‖g‖_L²) is the same on their domain of measure 2.T: the time of the evolution per iteration (one forward solve, one sensitivity), split inton = ⌈T / (cfl Δt_lim)⌉substeps ofΔt = T/n, with the bound of GershgorinΔt_lim = 2 / maxᵢ(κ Σⱼ|Kᵢⱼ| / mᵢ)of the explicit diffusion, from the assembledKand lumped massmonce at the start (0.375 h²/κon a uniform mesh of squares; it holds on any mesh).Tis physical: the evolution per iteration does not depend on the mesh, and the number of substeps grows like(h₀/h)²(the pointwise reaction needs√(κ Δt) ≲ 0.7 h; more than 10⁶ substeps per iteration is refused). The method keepsΔt = :auto. An event after the setup givesT,n,Δt,Δt_limandξin mean cell sizesh̄ = (|D|/cells)^(1/d).cfl: the substep relative toΔt_lim;:autois4/3with:implicitand1/3with:explicit(h²/(8κ), the step of Takezawa et al.).scheme = :implicit(default): each substep diffuses implicitly,(m/Δt + κK) ψ = m φ/Δtwith the operator factorised once (the one of the step), and then applies the semi-implicit pointwise reaction of Takezawa et al. (their Eqs. 44–45) toψ, withλinside the tilt term, by a root on vectors.scheme = :explicit: the explicit substeps of Takezawa et al. (ψ = φ − Δt κ m⁻¹ K φ, no linear system and no factorisation), the scheme of the preset:takezawa2010.substeps = n(an integer):nsubsteps of theΔtof the method per iteration, instead ofT(giving both is an error:Twould have no effect);Δt = :autoof the method is thencfl Δt_limand a number replaces it (with:explicit,Δt ≤ Δt_limis checked). Withsubsteps = nothing(default) a numberΔtof the method is refused.settle: with the substeps frozen on one sensitivity the interface overshoots and comes back, and a few per cent of the material changes phase at every iteration.settle = true(that issettle = (window = 10, tol = 1e-3)) goes to one substep (of the sameΔt) per iteration once the constraints are met and the relative range of the objective over the lastwindowiterations is belowtol(an event says so); a continuation jump starts the substeps and the window again. The default stop is only checked from the iteration after the settling (or from the start whenn = 1).settle = (window = w, tol = t)changes the window and the tolerance (either can be left out).settle = falsekeeps the substeps and does not hold the default stop (givestopandmaxiteryourself).- The default stop with the well (
default_stop): the constraints met, the material changed less than1e-2in each of the last 5 iterations and the relative range of the objective over the last 10 below1e-3(StopCriteria(material_tol = 1e-2, objective_range = 1e-3, combine = :all);2e-3without the well: the interface of the well keeps a cycle of a few per mille of the material per iteration), after the settling.solve!(…; stop)replaces it (and is not held until the settling).
Mesh: with κ and T fixed, the compliance of the cantilever 2 × 1 (κ = 1e-5, T = 25, seed :hex) is the same within about 3 % on 100 × 50, 200 × 100 and 400 × 200 (with 2, 5 and 20 substeps), but the topology depends on the seed and on the mesh (the double well does not nucleate holes, and the seed is resolved differently on each mesh). The bridge of Takezawa et al. (a point load) is not comparable across meshes: its compliance grows like log(1/h).
With the well the sensitivity is the exact derivative (void_weight is refused), normalize defaults to L2Norm() and ExactVolume(max_step = :auto) lowers the target 1 % of |D| per iteration (spread over the substeps). Not with an interface map (Ersatz(), Step()). Per iteration: one forward solve, one adjoint, n back-substitutions (:implicit; none with :explicit) and n roots on vectors, no factorisation.
HyperShape.Methods.Euclidean — Type
Euclidean()Euclidean metric of the design vector: inner(x, y) = xᵀy. Mesh-dependent on non-uniform meshes.
HyperShape.Methods.ExactVolume — Type
ExactVolume(; max_step = :auto, tol = 1e-4, maxiter = 50)How ReactionDiffusion treats the volume (its default): natively, with a scalar multiplier λ found at every step so that the clipped design z = clamp(φ* − λ φ̌, lb, ub) meets the constraint (φ* the design after the reaction–diffusion step, φ̌ = A⁻¹ m the response of the step to a uniform unit source). It takes the constraint built with Volume (g ≤ 0), wherever it is in the problem; with none or with several, solve! throws: name the one to take in the augmented Lagrangian of the method, lagrangian = AugmentedLagrangian(native = (:name,)) (any inequality g ≤ 0 evaluated without a state, linear or not; the only place where the constraint of the step is named). The other constraints go to the augmented Lagrangian. ExactVolume(; constraint = :name) still names it, deprecated (a warning): use native.
max_step: how much the target may go down per iteration, as a fraction of the measure|D|of the design domain: the target of iterationkismax(V_obj, V_{k−1} − max_step |D|), met with equality while it goes down; atV_objthe constraint isg ≤ 0withλ ≥ 0.:auto(default):0.02when the constraint reads the material through an interface map (Step(),Ersatz()),nothingotherwise (a density: the target from the first iteration).nothing: the target from the first iteration. A number in(0, 1].tol: tolerance of the root as a fraction of|D|, likemax_step(1e-4: the volume within1e-4 |D|of its target), converted to the units of the scaled constraint with its scale; the loop converges only with the constraint met to it.maxiter: evaluations of the constraint per step at most.
The root of G(λ) = g(clamp(φ* − λ φ̌)) − g_k (non-increasing in λ) starts from the previous λ, inside the bracket given by the bounds (all values at the upper or at the lower bound): a linear constraint (a density) by Newton on the clipped vector (only vectors, no solve; the algorithm of Cui et al. 2023); a nonlinear one with a derivative (Ersatz()) by Newton with the derivative of the constraint, guarded by the bracket; Step() by regula falsi (Illinois) on the volume computed by the material meter of the step (the same quadrature as the Volume, from the nodal values: exact, cheap and without allocations), until at most one quadrature point changes side inside the bracket; it ends on its feasible side (the volume of Step() is piecewise constant, and on coarse meshes the jump of one point can be larger than tol). Without the meter (a Volume over part of the domain, another constraint) the evaluations of Step() go through the constraint, until the trials differ by less than 1e-9. If the evaluations run out before a feasible trial is seen, the step takes the bound of the bracket where every value is at its lower bound. Each evaluation of a nonlinear constraint updates the maps and integrates (no state is solved, but the integral reserves memory: about 70 kB per evaluation and 130 kB per derivative with Ersatz(), independent of the mesh); a linear one costs vector operations only, without allocations.
HyperShape.Methods.FixedMesh — Type
FixedMesh()The default discretisation of solve!: the mesh and the problem do not change during the run. Any problem (built from its functionals or with factories).
HyperShape.Methods.FunctionalOracle — Type
FunctionalOracleOracle (see HyperShape.Optimizers.AbstractOracle) of an Optimization: objective and gradient! call the objective functional at the requested design; each constraint i is gᵢ = (Fᵢ − rᵢ)/sᵢ with the bounds of its Constraint: a linear one gives (a, V) computed once at the start (linear_constraint), a nonlinear one is evaluated at the requested design (constraint, constraint_gradient!; a design-only one solves no state); weighted_gradient! differentiates w₀ f + Σ wᵢ gᵢ in one reverse sweep; inner/riesz! use the metric of the method.
- It is the only writer of the variables
z; a design equal to the current one is not set again, so the value cache of the functional avoids repeated forward solves. - It keeps a copy of the design, value and derivative of its last
gradient!: after a rejected step, the optimiser asks again at that design and gets them without solves. - A gradient that is not finite throws
OptimizationFailure.
HyperShape.Methods.Grey — Type
Grey(θ::PhysicalFields, dΩ; field = nothing)Monitor of the measure of grey of a physical density, M_nd = 4/|Ω| ∫ ρ (1 - ρ) dΩ (Sigmund 2007): 0 for a 0/1 design, 1 for a uniform 0.5. Pass it to solve!(…; monitors = (grey = Grey(θ, dΩ),)) to add it to the history, the table and the closing line; it is not a stopping criterion. field is mandatory when θ has several fields. Costs one integral per iteration (about 90 kB of memory, independent of the mesh).
HyperShape.Methods.L1Mean — Type
L1Mean(c = 1.0)Normalisation of the sensitivity of ReactionDiffusion (its default): C = c |D| / Σᵢ |gᵢ|, with gᵢ the derivative of the objective with respect to the nodal value i (a dual vector) and |D| the measure of the design domain. The normalised sensitivity density C gᵢ / mᵢ (mᵢ the lumped mass) then has mean absolute value c over the domain, whatever the mesh. c scales the reaction against the diffusion τ.
HyperShape.Methods.L2Norm — Type
L2Norm()Normalisation of the sensitivity of ReactionDiffusion: C = |D| / (Σᵢ gᵢ² / mᵢ)^½, the normalisation of Kim et al. (2020) with the measure |D| of the domain in place of |D|^½ (so that τ keeps the same meaning as with L1Mean).
HyperShape.Methods.LumpedMass — Type
LumpedMass(dΩ)Diagonal metric m = ∫ v dΩ assembled on each design space: the cell volumes for a P0 design, the lumped mass (row sums of the mass matrix) for a P1 design. inner(x, y) = Σ mᵢ xᵢ yᵢ, riesz!(g, dF) = dF ./ m.
LumpedMass()The same on the triangulation of each design space, with a quadrature of degree 2 (exact for designs of order up to 2): no measure to give, and it follows the design spaces if the mesh changes.
HyperShape.Methods.MaxAbs — Type
MaxAbs()Normalisation of the sensitivity of ReactionDiffusion: C = 1 / maxᵢ |gᵢ / mᵢ| (the largest normalised sensitivity density is one). It depends on the mesh: a singular sensitivity (at a point load) grows when the mesh is refined.
HyperShape.Methods.OptHistory — Type
OptHistoryHistory of an optimisation, one entry per accepted iteration (vectors): iteration, objective (scaled value at the accepted design), kkt (optimality measure, NaN if the optimiser does not compute it), stationarity (stationarity measure of the design before the step, see StopCriteria; NaN if the optimiser does not compute it), change (maximum(abs, Δz)), step (step size or move limit, the mean over the entries with adaptive limits), attempts, forward, adjoint, filter (solves in the iteration), step_solves (linear solves of the method's own step in the iteration, see step_solves: for ReactionDiffusion the solves with its diffusion operator, one per step or one per implicit substep of a DoubleWell; 0 for a method that has none, such as DensityMethod; like forward, it includes the rejected attempts of the iteration; the solves of init, at the start, a resume or a rebuild, are only in the summary of solve!); constraints, violations, multipliers and penalties (named tuples of vectors, one per constraint of the Optimization: scaled value and violation at the accepted design, multiplier, and penalty of the augmented Lagrangian; the multiplier of a constraint the optimiser treats is the one it reports and its penalty is NaN, the multiplier of one in the augmented Lagrangian is its λ before the update at the end of the iteration), monitors (named tuple of vectors, one per monitor of solve!) and continuation (named tuple of vectors, one per continued parameter: its value at each iteration).
HyperShape.Methods.OptResult — Type
OptResultResult of solve!: status (:converged, :maxiter or :stalled, the last when the optimiser found no acceptable step in the last continuation stage; in an earlier stage this ends the stage), reason (the criterion met: the name of its keyword in StopCriteria, :custom for a stop function, or nothing), iterations, objective (scaled, at the final design), z (the OptVariables of the problem, at the final design, with the fields and the forward state in sync with it: get_values(result.z)), history (OptHistory), time (seconds of the call), state (the state of the optimiser, for advanced use) and start_scaling (the factor t by which an infeasible starting design was scaled towards the lower bound, nothing if it was not) and multipliers (named tuple, one per constraint: the last multiplier reported by the optimiser for a native constraint, the final λ of the augmented Lagrangian, after its last update, for the others) and problem (the Optimization of the last stretch of the run: the problem given to solve!, or the last one built by a rebuild of the discretization). The full state of the run is in problem.state[] (OptState). show(result) gives the objective also unscaled (with the scale of the objective of problem).
HyperShape.Methods.OptState — Type
OptStateThe state of an optimisation by name, what a Checkpoint writes and resume reads (also kept in problem.state[] by solve!, so resume = problem.state[] continues without files): iteration, stage, stage_iterations, z (the last accepted design), blocks and frozen_cells (by block), continuation (names), scales (named tuple: objective and one per constraint), history (OptHistory), method and optimizer (names), memory (of the step, see memory; nothing after a failure or an exception: a run resumed from such a state starts the optimiser again from init and is not the uninterrupted one), handled (for each constraint, :native or :lagrangian), lagrangian (nothing, or the multipliers, penalties, penalty references and number of updates of the augmented Lagrangian, by name), linear_offsets (the offset V of each linear constraint, kept so that a resumed run uses the same bits), discretization (the name of the discretisation of the run) and events (its rebuilds so far). A rebuild of the problem during solve! goes through this state, as a resume does. A checkpoint also keeps a description of the problem (a fingerprint, see solve!), which a resume compares with the problem it is given. Nothing in it is tied to the mesh except the vectors of the design (z and those of memory).
HyperShape.Methods.Optimization — Type
Optimization(; objective, constraints = (;))
Optimization(z; objective, constraints = (;))
Optimization(model; design_setup, physics_setup)Optimisation problem: minimise the Functional objective over the variables z behind it (given or not; when given they are checked) subject to the bounds of z and the named constraints, for example constraints = (volume = Vol, tip = Constraint(Tip; max = 0.25)): a functional alone is F ≤ 0 (as Volume), a Constraint gives bounds max, min or equal in the units of the functional. The names go to the history (history.constraints.volume), the banner and the checkpoint. Constraints may read states.
The optimiser treats some constraints itself (OC and SiMPL: one inequality that solves no state, typically the volume; see handles); the others enter its objective through the augmented Lagrangian of the method (DensityMethod(…; lagrangian = AugmentedLagrangian(…)), used by default and shown in the banner).
A constraint built as linear (Volume over identity or filter maps, or a Functional(…; linear = true)) is checked to be linear when the optimisation starts, and costs nothing in the loop (its vector is computed once). A nonlinear one is linearised at every step by the optimiser, which then corrects it with evaluations of the true constraint (one filter solve each, no forward solve): see OC and SiMPL.
The third form builds the problem from two functions of the user (factories), so that solve! can build it again during the run (see discretization in solve!): design_setup(model) returns a named tuple with z (the OptVariables, on spaces of model) and x (the DesignFields built on z); physics_setup(model, x) returns a named tuple with objective and optionally constraints, monitors (as the keyword of solve!) and output (the driver of an OptPostProcessor built without one, (post, ctx) -> …). Both are called once here and again at each rebuild; every name they return is kept in problem.design and problem.physics (for example problem.physics.θ). What is continued or does not depend on the mesh (a TanhProjection of a Continuation, a Parameter, the optimiser) is created once, outside the factories, and used inside them; everything that depends on the mesh (spaces, measures, fields, states, functionals, monitors, output) is created inside. The factories may be called several times: they should have no other effects. A name close to one of the contract (monitor, constraint, outputs, post, driver, objectives, J) without the right one is an error. After a run with rebuilds the variable problem of the script is the first problem: the last one is result.problem (both share problem.state[]).
The problem owns the context ctx (OptContext) that reaches the solve functions of the user, and problem.state[], the last OptState captured by solve! (at the end of a run, after a failure or an interruption; a solve! that throws before its first iteration leaves the previous one): pass it as resume to continue without files.
HyperShape.Methods.OptimizationFailure — Type
OptimizationFailure(msg)Thrown by solve! when the optimisation cannot continue: the forward problem does not converge at the current design (first iteration or right after a continuation jump), every attempt of a step was rejected, or a gradient is not finite (failed adjoint). z, the fields and the states are left at the last accepted design, and the checkpoint (if any) is written first. history holds the OptHistory up to the last accepted iteration and iterations its number (nothing and 0 when thrown outside the loop).
HyperShape.Methods.ReactionDiffusion — Type
ReactionDiffusion(; τ, Δt = :auto, normalize = L1Mean(), volume = ExactVolume(), mass = :lumped,
void_weight = 1e-3, ls = LUSolver(), solve = nothing, diffusion = nothing, degree = 2,
lagrangian = AugmentedLagrangian(), reaction = nothing, phi_bc = :neumann)
ReactionDiffusion(; κ, reaction = DoubleWell(), kwargs...)Reaction–diffusion method (Yamada et al. 2010, Choi et al. 2011, Otomori et al. 2015, Kim et al. 2020): the design field φ (one nodal P1 field, φ ∈ [lb, ub]) evolves by an implicit step of
∂φ/∂t = −C g − λ + τ ℓ² Δφ,that is (mass/Δt + τ ℓ² K) δ = −τ ℓ² K z − C g (K the diffusion matrix, ℓ² = |D|^(2/d) with |D| the measure of the design domain, so τ is dimensionless), φ* = z + δ, and then z = clamp(φ* − λ φ̌, lb, ub) with the multiplier λ of the volume found exactly at every step (ExactVolume). g is the derivative of the objective (plus the terms of the augmented Lagrangian of the other constraints) and C its normalisation (normalize).
The material is read through the maps of the user: a level set (bounds = (-1.0, 1.0), solid start init = 1.0) through an interface map, χ = :φ => Ersatz() or Step(); or a density (bounds = (0.0, 1.0)) through Identity() and a SIMP interpolation in the weak forms. Frozen zones of the design space (FieldVariable(…; frozen)) are not variables: the step leaves them as they are.
Mandatory (modelling decisions):
τ: diffusion coefficient (dimensionless; a number or aParameter, which aContinuationcan change, not withDoubleWell); larger values give simpler designs with thicker members. Orκ = τ ℓ²instead (exactly one of the two): the same diffusion as a physical length squared,τ = κ/ℓ²withℓ² = |D|^(2/d)computed on the mesh (the banner shows both). The operator takesκas given; withτit takesτ ℓ², soτ = κ/ℓ²with thatℓ²gives the run ofκbit for bit, whileτ = κ/2on a domain of measure 2 can differ in the last bits (the measure is a sum of quadratures, not exactly 2).
The sensitivity of the step is deduced from the design chain when solve! starts (the banner says which and why):
- a functional that the step differentiates (the objective, the constraints of the augmented Lagrangian) reads a field through an interface map (
Step(),Ersatz()): the derivative with respect to the material, the interface map taken as the identity weighted by the material,(w₀ + (1 − w₀) χ) ∂j/∂χ(w₀ = void_weight): it nucleates holes, and the exact derivative through the map would refill the void (its value there is large: weak material, large strains); the exact derivative with an interface map is not a method (it lives on the cut cells and nothing holds the plateaus); - a density (no interface map; filters and projections allowed) and
reaction = DoubleWell(…): the exact derivative with respect to φ.
The variant that only moves the boundary, from a start with holes (hole_seed), is a density with reaction = DoubleWell(…). hole_seed also gives perforated starts with an interface map (studies of the dependence on the start). The keyword sensitivity = :physical | :design of earlier versions is still accepted with a deprecation warning (a value that contradicts the deduced one is an error). check_consistency always checks the exact derivative; with Ersatz() give it steps smaller than the default (h0 = 1e-3): larger ones cross the kinks of the cell fractions (a node changing sign) and the observed rates fall below 2 for a correct derivative.
Optional (each one replaceable, shown in the banner):
Δt: pseudo-time step (number orParameter);:auto(default) is0.2when the problem reads the design through an interface map and0.4otherwise (shown in the banner). With a smallerΔtthe topology depends on the path: the design passes through metastable plateaus and the diffusion keeps merging holes long after it looks converged; halved byRejectStepwhen the forward problem does not converge at the new design, back to its value at the next step.normalize:L1Mean(c)(defaultc = 1),L2Norm(),MaxAbs(), or a function(g, m, area) -> C(gthe derivative,mthe lumped mass,area=|D|), for example the normalisation of Takezawa et al. (2010) without|D|,(g, m, area) -> 1 / sqrt(sum(g .^ 2 ./ m))(a reduction over a lazy broadcast avoids the allocation:validation/common/presets.jl).volume:ExactVolume(; max_step, tol, maxiter), ornothing(every constraint to the augmented Lagrangian). The constraint the step treats is the one built withVolume, or the one named inlagrangian = AugmentedLagrangian(native = (:name,)); givingnativewithvolume = nothing, ornative = ()withvolume = ExactVolume(…)written, is an error;native = ()with the defaultvolumeis the same run asvolume = nothing(deprecated: writevolume = nothing).mass::lumped(default; the responseφ̌is positive andG(λ)monotone on non-obtuse meshes) or:consistent.void_weight:w₀of the sensitivity through an interface map, default1e-3; giving it when the sensitivity is the exact derivative (a density,DoubleWell) is an error (it would have no effect).ls: the linear solver of the step (a GridapLinearSolver), defaultLUSolver(): the operator is assembled once by HyperShape (Gridap's assembler, on the design space), factorised once and again only whenΔtorτchange.solve = (A, b, x, ctx, stale) -> xreplaces it (PETSc, an iterative solver of the user):Athe operator,bthe right-hand side,xthe output,stalewhetherAchanged since the last call. Give one of the two (withsolve,lsis not used: an error); neither withDoubleWell(scheme = :explicit), which solves no linear system (normass = :consistent: its substeps use the lumped mass).diffusion = (φ, v) -> ∫(…)dΩ: the bilinear form of the diffusion (default∫(∇(φ) ⋅ ∇(v))dΩwith a quadrature of degreedegree), for an anisotropic diffusion or a Robin term.degree(default 2): the degree of the quadrature of the design domain, for the default diffusion and also for the measure|D|, the lumped mass and the consistent mass (so it acts with adiffusionof the user too).lagrangian: theAugmentedLagrangianof the constraints the step does not treat (everything but the volume).reaction:nothing(default: the linear reaction−C g − λabove) orDoubleWell(…), the double-well reaction of Takezawa et al. (2010) for a density that only moves its interface, from a start with holes: then the sensitivity is the exact derivative,normalizedefaults toL2Norm(),Δt = :autoisT/nper substep (the timeTof the well per iteration innsubsteps) and the multiplier ofExactVolumeacts inside the tilt term of the well (itsmax_step = :autois0.01). See its docstring for the scheme, the substeps and the settling.phi_bc: the condition of the design field on the boundary.:neumann(default): none, the natural condition of the diffusion.:zero_boundary:φ = 0held on every node of the boundary of the design domain (from the topology of its cells, not from a tag; Otomori et al. 2015)."tag" => value, or a tuple of such pairs:φheld atvalueon the nodes of each tag of the model (the nodes thatdirichlet_tags = tagwould make Dirichlet in a P1 space; Yamada et al. 2010 and Cui et al. 2023 holdφ = 1where the load acts), for examplephi_bc = ("load" => 1.0,). The values must be inside the bounds. They are written into the design whensolve!starts (before the first evaluation) and the step keeps them: identity rows of its operator, no increment andφ̌ = 0there, so the multiplier of the volume does not move them. They are still values ofz(their derivative is computed, enters the normalisationCand is not used). Not a frozen zone: a frozen zone is a set of cells of material, not a line of nodes; where a tag touches the frozen values of a zone, the zone wins (the banner says how many); a tag with no node in the design domain, a tag given twice and two values on a node ofzshared by two tags are errors. With held valuesφ̌needs one more back-substitution per factorisation. Not withDoubleWell. A run resumed from a checkpoint starts from the design of the checkpoint (the held values are written into it again) and keeps itsscale = :initialvalues: those of the design it was started from, with or withoutphi_bc.
The settings of papers are keywords like any other: validation/common/presets.jl writes those of Kim et al. (2020, a density: Δt = 0.1, normalize = L2Norm(), mass = :consistent, volume = nothing, lagrangian = AugmentedLagrangian(Bertsekas(μ0 = 0.2, growth = 1.025, window = 1, progress = Inf, μmax = 2.0))) and of Takezawa, Nishiwaki and Kitamura (2010, the double well: reaction = DoubleWell(W = 0.25, η = 20, scheme = :explicit, substeps = 20, settle = false), the normalisation 1/‖g‖_L² without |D| and volume = ExactVolume(max_step = 0.01)) as named tuples, ReactionDiffusion(; τ, KIM2020...). The positional presets of earlier versions, ReactionDiffusion(:kim2020; τ) and (:takezawa2010; τ), still work with a deprecation warning. Julia shows deprecation warnings only with julia --depwarn=yes (off by default; on in Pkg.test()).
Per iteration: one forward solve, one adjoint (none with SelfAdjoint()), one assembly of the sensitivity, one product K z and one solve of the step (no factorisation); the volume costs a few evaluations of the constraint per step (vectors only for a density; the map and an integral each with an interface map, plus one derivative per Newton iteration with Ersatz(); the summary of solve! counts them). The solves of the step are in history.step_solves (with the unit response φ̌ of the exact volume, solved at each factorisation inside an iteration when values are held; the φ̌ of init, at the start, a resume or a rebuild, is only in the summary of solve!). The default stop (default_stop) needs the constraints met, the change of the material ∫|χ_k − χ_{k−1}| / ∫χ_k below 2e-3 (1e-2 with DoubleWell) in each of the last 5 iterations and the relative range of the objective below 1e-3 over the last 10, the windows counted with the constraints met; StopCriteria(rate_tol), change_tol and phase_tol are options. √(τ|D|) is the length of the diffusion (a perimeter energy), not a minimum thickness: bars of one or two cells can remain. Neither the interface map nor the stopping criterion is a recommendation: the choice will be validated with more cases. The starting design is not made feasible (the volume goes down from a solid start, max_step of |D| per iteration). Checkpoints save the multiplier and the windows of the stop (a resumed run is the uninterrupted one, also with a larger maxiter). gtol and the resolved Δt live in the method: one method object serves one solve! at a time (not concurrent runs).
HyperShape.Methods.RebuildCheck — Type
HyperShape.Methods.RebuildCheck(; at = nothing, every = nothing, what = :design)Builds the problem again on the same mesh, calling the factories of Optimization(model; design_setup, physics_setup) after the accepted iterations at (an integer or a collection) or every every iterations: both factories (what = :design) or only physics_setup, with the same design (what = :physics). The run continues from the state captured at that iteration (the path of resume), so with linear states solved by direct solvers it is the run of FixedMesh() bit for bit (the counts of solves aside: one forward solve and one filter more per rebuild, in the summary). A run resumed from a checkpoint written at an iteration of a rebuild does not rebuild there again. It checks that the factories capture nothing of the problem they replace, before paying for a change of mesh: at each rebuild the objective at the rebuilt problem is compared with the one of the history (identical, or its relative difference, on screen). A nonlinear state or an iterative solver starts from another initial guess after a rebuild, and agrees only to its tolerance.
HyperShape.Methods.RejectStep — Type
RejectStep(; shrink = 0.5, max_attempts = 5)What to do when the forward problem does not converge at the design proposed by the optimiser: go back to the previous design, call shrink! on the optimiser with shrink (0 < shrink < 1: OC multiplies its move limit) and try again, at most max_attempts attempts per iteration; then throw OptimizationFailure. RejectStep() is the default of solve! (with the defaults, the step can go down to 1/16 of the first one).
Optimisers that evaluate their trials (SiMPL) handle failures inside their line search, so for them this only applies if a step is accepted at a design that cannot be evaluated again.
HyperShape.Methods.StopCriteria — Type
StopCriteria(; objective_range = nothing, window = 10, kkt_tol = nothing, kkt_rtol = nothing,
stationarity_tol = nothing, stationarity_rtol = nothing, change_tol = nothing, rate_tol = nothing,
phase_tol = nothing, phase_window = 5, material_tol = nothing, material_window = 5, combine = :any,
grey_tol = nothing, objective_atol = nothing)Convergence criteria; each one is off unless given, and the first one met stops the optimisation (the reason in OptResult is the name of the keyword). With a Continuation they only act in the last stage, unless it was built with close_early = true (then a criterion met in an earlier stage ends that stage).
objective_range: range of the objective over the lastwindowiterations of the current stage,(max - min), relative to the largest|f|in the window, below this value:max - min <= objective_range * maximum(abs, window)(no division: a window of zeros meets it). A range, not the difference between the ends of the window, so an oscillation does not pass for convergence. The reference is the window alone, not the first objective of the run: a run whose first objective is much larger than the final one (a seed with holes over the supports) is not stopped early. An objective that tends to zero may never meet a relative range: giveobjective_atoltoo.objective_atol: only together withobjective_range: the criterion is also met when the range of the window is below this absolute value (units of the scaled objective; positive and finite), for objectives that tend to zero. Off by default. A run that ends atmaxiterwith the objective range not met says so.kkt_tol: optimality measure of the optimiser below this value (absolute: units of the scaled objective).kkt_rtol: the same, relative to the one of the first iteration of the run (off if that one is not a positive number). Only with optimisers that compute it (SiMPL; with OCsolve!throws before the first iteration).stationarity_tol: the stationarity measure of the paper of SiMPL,S = ‖z − P(z − g)‖_M(stationarity!, computed by OC and SiMPL at the design before the step, so the run stops one iteration after it is met), below this value (absolute: it depends onscaleand on the metric; withEuclidean()it depends on the mesh, useLumpedMass()).stationarity_rtol: relative to the first finite value of the run. With a nonlinear constraint the projection uses the constraint linearised atz. OC computes it with the metric ofDensityMethod(its step does not use it): giveLumpedMass()for a value independent of the mesh, comparable with SiMPL.change_tol:maximum(abs, Δz)of the step below this value. With a tanh projection it is rarely reached.rate_tol: the rate of change,maximum(abs, Δz)divided by thestepof the step (the pseudo-time stepΔtofReactionDiffusion, the one of the accepted step), below this value: a step shrunk after a rejection does not meet it by being short (measured: the iteration at which it stops still depends onΔt).phase_tol: the fraction of the design domain that changes phase in an iteration below this value in each of the lastphase_windowiterations (default 5) of the run: the lumped mass of the nodes where the level set changes sign, over|D|(phase_changeof the method). Only for a method whose design goes through an interface map (ReactionDiffusionwithStep()orErsatz());solve!throws otherwise. The windows ofphase_tolandmaterial_tolare saved in the checkpoint: a resumed run stops where the uninterrupted one does.material_tol: the material changed in an iteration,M_k = ∫|χ_k − χ_{k−1}| dΩ / ∫χ_k dΩ(material_changeof the method:χis the physical field read by theVolumeconstraint, cell by cell), below this value in each of the lastmaterial_windowiterations (default 5) with the constraints met (the window starts again whenever a constraint is violated: it does not count the descent of the volume). ForReactionDiffusion(the step computesM_kfrom the nodal values, without solves or allocations, when theVolumeintegrates over the design domain throughIdentity(),Step()orErsatz()); given without such a metersolve!throws, while the default stop ofReactionDiffusiondrops it (an event and a line of the banner say so). A run that ends atmaxiterwith the material still changing says so.grey_tol: the measure of grey of the design below this value,M_nd = Σᵢ mᵢ 4φ̂ᵢ(1 − φ̂ᵢ) / |D|(φ̂the design scaled to[0, 1]by its bounds,mᵢthe lumped mass of the free values; nodal, without allocations; Kim et al. 2020). ForReactionDiffusion(grey_measureof the method); with other methodssolve!throws before the first iteration (for a physical density use the monitorGrey).combine::any(default) stops when the first criterion given is met;:allwhen all of them are met in the same iteration, and then the window ofobjective_rangealso counts only iterations with the constraints met (the reason is:all). The default ofReactionDiffusionisStopCriteria(material_tol = 2e-3, objective_range = 1e-3, combine = :all).
The tolerances are not checked at the first iteration of a stage (after a continuation jump the first step restores feasibility and its measures say little); objective_range needs window iterations of the stage. A window given without its criterion (window without objective_range, phase_window without phase_tol, material_window without material_tol) is an error: it would have no effect.
Gridap.Algebra.solve! — Method
solve!(problem::Optimization, method::AbstractMethod; maxiter, on_failure = RejectStep(),
stop = default_stop(optimizer), continuation = nothing, checkpoint = nothing, post = nothing,
monitors = (;), resume = nothing, discretization = FixedMesh(), verbose = 2, io = stdout) -> OptResultRuns the optimisation from the current values of z. Mandatory: maxiter (total iterations, resumed ones included). Optional: on_failure (RejectStep, default RejectStep(shrink = 0.5, max_attempts = 5)), stop (StopCriteria; default default_stop: range of the objective below 0.1 % over 10 iterations of the last stage, or for ReactionDiffusion the material and the objective steady with the constraints met; stop = nothing runs maxiter iterations; or a function (or callable object) (info, history, ctx) -> Bool of the user, checked after every accepted iteration, with the StepInfo of the step (info.f is the objective before it), the OptHistory up to this iteration (a copy) and the context: true stops with reason :custom, under the same rules as StopCriteria (only in the last stage of a Continuation unless close_early; with a nonlinear constraint, only when it holds to the tolerance of the optimiser)), continuation (Continuation), checkpoint (Checkpoint), post (an OptPostProcessor: its driver is called at the starting design, at the accepted iterations that are multiples of every, at the end and after a failure, with the fields and the forward state at the accepted design) and monitors (a named tuple of monitors, such as (grey = Grey(θ, dΩ),): their values, see monitor_value, go to the history, the table and the closing line), resume (the folder of a Checkpoint, the result of load_checkpoint or problem.state[], an OptState), verbose and io. An OC whose move is continued by continuation gets its own move back when solve! returns or throws; the other continued parameters keep the values of the last stage.
discretization (FixedMesh() by default: the problem is not built again) says when the problem is built again during the run, which needs a problem built with Optimization(model; design_setup, physics_setup): HyperShape.Methods.RebuildCheck calls its factories again on the same mesh (a check of the factories before a change of mesh). The run continues from the state captured at the rebuild (as a resume), with the same history, checkpoint and post-processor; the result carries the last problem (result.problem). With factories, monitors and the driver of the post-processor come from physics_setup (monitors, output; the post-processor is then built without a driver, OptPostProcessor(; every, filepath)); with a discretisation that rebuilds, they cannot be given here, nor a metric fixed on the mesh (LumpedMass(dΩ); use LumpedMass()).
Screen output (verbose, default 2, printed to io): 0 nothing; 1 a banner (variables, constraints, metric, the maps of the physical fields with their parameters, the scale of each functional and where it comes from, the parameters of the optimiser, continuation, stopping criteria and failure handling, each marked when it is a default), the events (continuation jumps, rejected steps, stalls, a scaled start), a closing ✓/⚠/✗ line with the objective also in the units of the user (unscaled), a line with each constraint at the last design in its units (a Volume also as a fraction of its domain) and its scaled violation, and a summary of solves and time (the values in the units of the user are printed, not returned: result.objective and history are scaled); 2 also a row per iteration, with a legend as the last line of the banner: iteration, objective (scaled), its relative change, the constraint (scaled; max viol with several; its name cut to 12 characters; red beyond its tolerance), optimality measure kkt, stationarity measure S, change of z, step, multiplier, monitors, the solves of the iteration and time (the continued parameters have no column: each jump is an event, after which the header is printed again). Only the columns that the method fills are shown: no kkt when the optimiser does not compute it (OC, ReactionDiffusion), no S with ReactionDiffusion, no constraint and multiplier without constraints, and only the counters of solves that can happen (f forward, a adjoint, F filter, s the solves of the step for a method that counts them, see step_solves: ReactionDiffusion); history keeps every column. true is 2, false is 0. The summary counts every solve of the call (those of rejected or stalled trials, the setup and the final synchronisation included; step for a method that counts them).
With a checkpoint, an exception that is not an OptimizationFailure (an error in a solve, post or monitor function of the user, an interruption) writes a checkpoint at the last accepted design (history included) and is then rethrown; an OptimizationFailure writes its own.
If the starting design (not a resumed one) violates the constraint, it is scaled towards the lower bound, z = lb + t (z − lb) on the entries the constraint acts on (a linear constraint: so that it holds with equality; a nonlinear one: with t found by regula falsi so that -1e-6 ≤ g ≤ 0); t is returned in result.start_scaling and reported as an event when verbose ≥ 1. At a continuation jump the design is not touched: an optimiser that finds it infeasible restores feasibility in its next step.
Each iteration: the optimiser takes a step from the current design; the loop evaluates the new design (no solve when the optimiser already did, as SiMPL); if the forward problem does not converge there, the design is restored, the step shrunk and tried again. Solves per iteration: OC one filter, one forward, one adjoint (none for a self-adjoint functional) and one transposed filter; SiMPL one filter and one forward per trial of its line search (usually one), one adjoint and one transposed filter; one more forward after each continuation jump. A linear constraint costs nothing in the loop (its vector is computed once at the start); a nonlinear one costs, per step, one transposed filter for its derivative and one filter per correction (see OC and SiMPL), and no forward solve. With a nonlinear constraint the run only converges when the constraint also holds to the constraint_tol of the optimiser.
With several constraints, or one the optimiser does not treat itself, the method's augmented Lagrangian (DensityMethod(…; lagrangian)) takes the others: the banner says who treats each one, the table shows the largest violation and the largest |λ|, the multipliers are updated after every accepted iteration (no solve: the values at the accepted design are cached) and the run converges only when every constraint holds to its tolerance (a run that ends otherwise says which constraints do not). The scaled start acts on the native constraint only. A stop function receives the StepInfo of the optimiser, whose f is then the augmented objective; the history keeps the objective of the problem. Per iteration, the constraints of the augmented Lagrangian add no forward solve and, with their states, one adjoint solve per state in the same reverse sweep as the objective.
Checks. The derivatives written by the user are checked only by check_consistency, when the user calls it; the banner says whether every functional of the problem had its gradient checked and passed (derivatives:). Errors before the first step: a continued Parameter (with values that change) that nothing declares; at the first derivative of each run, an objective whose derivative is identically zero (a DensityMethod; ReactionDiffusion takes it as diffusion alone), a scale = :initial taken at a value at the level of rounding, a SymmetricState() whose matrix is not symmetric (see Volume and OC for theirs). They are checked again by every solve! (a resumed or repeated run too). The closing line is ⚠, not ✓, with the reasons, when the result is suspicious: the objective ended above its first value (from a feasible start; with a continuation, the first value of the last stage), it is exactly zero (not with ReactionDiffusion, where a zero sensitivity is diffusion alone) or did not change over the last window while the design did, every design variable is at one bound, or OC dropped more than 5 % of the derivative at its first step; status and reason are unchanged and nothing is added to the result, so with verbose = 0 these reasons are not shown: in a batch, compare result.objective with result.history.objective[1] and look for get_values(result.z) at a bound. A continuation that maxiter cuts before its last stage is announced in the banner and at the end. A second solve! on the same problem (without resume) says what it inherits from the previous run (the design, scales fixed by :initial, continued values left at the last stage). A checkpoint keeps a fingerprint of the problem (the method and the parameters of its step and of its augmented Lagrangian, the metric, the bounds of the blocks, the bounds, Vmax and scales of the functionals, the continuation, the projections): a resumed run reports each difference, a changed offset of a linear constraint, and an objective at the restored design that differs from the last row of its history.
HyperShape.Checks.check_consistency — Method
check_consistency(problem::Optimization; kwargs...)check_consistency of the objective and the constraints of problem, by name (objective and the names of the constraints).
HyperShape.Methods.augmented_lagrangian — Function
augmented_lagrangian(m::AbstractMethod) -> AugmentedLagrangianThe AugmentedLagrangian of m: which constraints the step treats itself (native) and how the others are handled. Part of the contract of a method (AbstractMethod); no default.
HyperShape.Methods.banner_lines — Method
banner_lines(m::AbstractMethod, problem) -> Vector{Tuple{String,Symbol}}Lines of the banner of solve! that are particular to m (its parameters and their defaults), as (text, colour) with the colour :normal, :yellow, … (default: none).
HyperShape.Methods.build_oracle — Function
build_oracle(m::AbstractMethod, problem) -> FunctionalOracleThe oracle the step of m sees for problem (objective, gradient, constraints, bounds, metric), built once per run, for example HyperShape.Methods.FunctionalOracle(problem, metric) (for now it must be a FunctionalOracle). Part of the contract of a method (AbstractMethod); no default.
HyperShape.Methods.check_problem — Method
check_problem(m::AbstractMethod, problem)Called by solve! before anything is evaluated: throws an ArgumentError when m cannot treat problem, and may set what the method deduces from it (ReactionDiffusion: its sensitivity). Default: nothing.
HyperShape.Methods.default_metric — Method
default_metric(optimizer)Metric of DensityMethod when none is given: Euclidean() for OC (which only uses it for the stationarity measure), LumpedMass() for SiMPL (decision of Jesús, 2026-11-28); an error for any other optimiser, which must be given one (or define a method of default_metric for its type).
HyperShape.Methods.default_stop — Method
default_stop(optimizer) -> Union{StopCriteria,Nothing}Stopping criteria of solve! when stop is not given: StopCriteria(objective_range = 1e-3) (range of the objective below 0.1 % over the last 10 iterations of the last stage), for OC and SiMPL. With a projection, kkt_tol and change_tol are rarely reached; the objective settles. ReactionDiffusion: StopCriteria(material_tol = 2e-3, objective_range = 1e-3, combine = :all), with material_tol = 1e-2 when the reaction is a DoubleWell.
HyperShape.Methods.discretization_label — Method
discretization_label(d::Discretization) -> StringThe line of the banner for d (default: the name of its type).
HyperShape.Methods.due — Function
due(d::Discretization, k, info, history, ctx) -> BoolAfter the accepted iteration k (not the last one, nor the one a run resumes from), whether d builds the problem again; info is the StepInfo of the step, history the live OptHistory. Part of the contract of a Discretization.
HyperShape.Methods.feasible_start — Method
feasible_start(m::AbstractMethod) -> BoolWhether solve! scales a starting design that violates the native constraint towards its lower bound before the first step (default true; ReactionDiffusion: false, its step lowers the volume).
HyperShape.Methods.load_checkpoint — Method
load_checkpoint(filepath) -> OptStateReads a checkpoint written by Checkpoint into an OptState; solve!(…; resume = filepath) calls it. OC (adaptive move limits, correction shift) and SiMPL (latent variable, Barzilai–Borwein memory, multiplier, correction shift) save their memory, so a resumed run continues as the uninterrupted one; a checkpoint written after a failure does not save the memory. Reads format versions 4 and 3; other versions are refused. A checkpoint of version 3 has no column step_solves in its history: its rows are read as 0 and the run resumed from it says so once; the zeros are not marked, so a later checkpoint or a second resume keeps them as 0 without a notice (the sum of the column then undercounts the solves of the step of those iterations).
HyperShape.Methods.material_change — Method
material_change(opt::Optimizer, state) -> Float64The material changed in the last accepted step, ∫|χ_k − χ_{k−1}| / ∫χ_k (see StopCriteria(material_tol)); NaN (the default) when the step does not compute it.
HyperShape.Methods.method_label — Method
method_label(m::AbstractMethod) -> StringThe name of m in the title of the banner and in the checkpoint (default: the name of its type).
HyperShape.Methods.metric_label — Method
metric_label(m::AbstractMethod) -> Union{Nothing,String}The metric of m as the banner writes it (nothing, the default: no line).
HyperShape.Methods.metric_weights — Function
metric_weights(m, z) -> AbstractVectorWeights of a diagonal metric of the user, one per entry of the variables z (or of the block, in a named tuple of metrics: then z is the space of that block). Called once at the start of solve! and again after each rebuild of the problem; they must be positive.
HyperShape.Methods.monitor_value — Method
monitor_value(m) -> RealValue of a monitor of solve! (monitors = (name = m, …)) at the accepted design, called once per accepted iteration after the forward solve (the closing line shows the last value recorded). It must return a real number; an exception ends the optimisation as an OptimizationFailure with the history and the checkpoint written. Defined for Grey.
HyperShape.Methods.needs_setup — Method
needs_setup(d::Discretization) -> BoolWhether the problem must have factories (Optimization(model; design_setup, physics_setup)) to run with d (default true; FixedMesh: false). Part of the contract of a Discretization.
HyperShape.Methods.phase_change — Method
phase_change(opt::Optimizer, state) -> Float64The fraction of the design domain whose phase changed in the last step (see StopCriteria(phase_tol)); NaN (the default) when the step has no phases (a density).
HyperShape.Methods.rebuild — Method
HyperShape.Methods.rebuild(problem; what = :design, model = problem.setup.model) -> OptimizationBuilds the problem again with its factories (a problem built with Optimization(model; design_setup, physics_setup)): both (what = :design) or only physics_setup, with the design of problem (what = :physics), on model (the same one by default; another model is for the discretisations that change the mesh, later). The new problem shares the context and state of problem; the values of z are not copied (solve! restores them from the state at a rebuild). Used by the discretisations of solve! (RebuildCheck).
HyperShape.Methods.rediscretize — Function
rediscretize(d::Discretization, problem, state::OptState, ctx) -> OptimizationThe problem built again by d (called with ctx.phase == :setup when due says so), for example HyperShape.Methods.rebuild(problem); solve! checks it and continues from state. Part of the contract of a Discretization.
HyperShape.Methods.reports_stationarity — Method
reports_stationarity(opt::Optimizer) -> BoolInternal hook of the screen output: whether the optimiser reports the stationarity measure in its StepInfo, so that the table of solve! has the column S (default true; false for the step of ReactionDiffusion).
HyperShape.Methods.step_solves — Method
step_solves(opt::Optimizer, state) -> Union{Nothing,Int}Linear solves done so far by the step itself, with its own operator (not those of the state, the adjoint or the filter), counted from init; nothing (the default) for a step that has none. The loop records the difference over each iteration in history.step_solves (rejected attempts and shrink! included) and, when it is not nothing, shows it in the table (the counter s of the column of solves) and in the summary (step). ReactionDiffusion: the solves with its diffusion operator (one per step, one per implicit substep of a DoubleWell, none with scheme = :explicit, and the unit response φ̌ of the exact volume when it is solved at a factorisation inside an iteration). What init solves (the φ̌ of the start, of a resume and of each rebuild) is in no row: only the summary counts it. A step of the user defines it on its own types: HyperShape.step_solves(::MyStep, s::MyState) = s.nsolves.
HyperShape.Methods.stepper — Function
stepper(m::AbstractMethod) -> OptimizerThe step of the method m, an Optimizer of HyperShape.Optimizers (DensityMethod: its optimiser; ReactionDiffusion: its implicit step). It must return the same object at every call (a continuation compares it). Part of the contract of a method (AbstractMethod); no default.