Design
Phase 0 (linear density methods) is implemented; the sections marked planned describe later phases. Names may still change until the package is registered.
OptVariables z ─► DesignFields x ─► PhysicalFields θ ─► weak forms ─► StateOperator (u, p)
▲ │
└──────── method (step) ◄── dJ/dz ◄── dJ/dθ ◄── Functional (J, DJ) ◄──┘Variables
Three linked levels, built in order; each one can only be created from the previous one.
| Level | Object | Meaning |
|---|---|---|
z | OptVariables | What the optimiser sees: one vector made of named blocks, with bounds |
x | DesignFields | Design fields on the design mesh: nodal (P1) or cell-wise (P0) |
θ | PhysicalFields | Physical fields read by the weak forms at the quadrature points |
Implemented (filter by PDE, tanh projection, P0 and P1 design fields):
F = HelmholtzFilter(dΩ; rmin = 0.05, ls = LUSolver()) # r = rmin/(2√3), P1, Neumann; ls goes to StaticLinearModel
z = OptVariables(ρ = FieldVariable(Vρ; bounds = (0.0, 1.0), init = 0.5))
x = DesignFields(z) # z → x: the identity (the only map for now)
θ = PhysicalFields(x; ρ = TanhProjection(β = 1.0, η = 0.5) ∘ F)
# the same in one line
z, x, θ = single_field_design(:ρ, Vρ; bounds = (0.0, 1.0), init = 0.5, map = TanhProjection(β = 1.0, η = 0.5) ∘ F)
# any other filter: a LinearOperator over a model written by the user (symmetric form)
af(ρ̃, v) = ∫(r^2 * ∇(ρ̃) ⋅ ∇(v) + ρ̃ * v)dΩ + ∫(r * ρ̃ * v)dΓ # Robin term on Γ
Sf = LinearOperator(StaticLinearModel(af, Uf, Vf, NothingBC(); ls = LUSolver()))
θ = PhysicalFields(x; ρ = HelmholtzFilter(Sf, dΩ))- Maps are composed with
∘in the mathematical order:proj ∘ Ffilters first and projects after. - The filter output lives in the trial space of the filter model (usually P1), also for a P0 design field. The projection is applied point by point at the quadrature points, so
θ.ρis a GridapCellField. θ.ρis a fixed object updated in place: weak forms capture it once (checked with the lazy and the compiled backends of HyperFEM).- Several physical fields can come from one design field (
E = :ρ => map); their sensitivities are added. - Sensitivities: for linear forms
δ -> ∫(… * δ)dΩwith respect to each physical field,design_gradient!returns the derivative with respect toz(derivative of the projection inside the integrals, then the transposed filter, which is the same solve because the filter form is symmetric). - The vectors HyperShape assembles (load vector of the filter, sensitivities) use
backend = :compiledby default (HyperFEMKernels: forms compiled once into threaded kernels) orbackend = :lazy(Gridap), chosen inHelmholtzFilter(Sf, dΩ; backend)andPhysicalFields(x; …, backend). Both give the same vectors up to rounding. On 65 000 cells the compiled backend computes a design gradient 1.5 times faster than the lazy one with one thread and 5 to 7 times faster with four (julia -t N); on meshes of about a thousand cells both take well under a millisecond. - Bounds and initial values are mandatory. Without a map a field is the identity:
DesignFields(z)(z → x),PhysicalFields(x; χ = :φ)(χ = :φ => Identity()) andPhysicalFields(x)(every design field under its own name); writingIdentity()is the same (decision of Jesús, 2026-11-28). - Only HyperShape writes
xandθ; the user reads them as Gridap fields. - The filtered density is a P1 field and
θis evaluated at the quadrature points, so the stiffness varies inside an element. Codes such as top88 use one value per element, the cell mean of the filtered field:CellMean(dΩ) ∘ Fgives that formulation (see the Validation page).
Frozen zones (solid or void the optimisation cannot change: the material under a load, at a support, a skin) are declared once, on the design space, as Dirichlet tags with their values:
add_tag_from_vertex_filter!(labels, "solid", model, x -> (x[1] <= 2 && x[2] >= ny - 2) || (x[1] >= nx - 2 && x[2] <= 2))
Vρ = TestFESpace(model, ReferenceFE(lagrangian, Float64, 0); conformity = :L2, dirichlet_tags = "solid")
z, x, θ = single_field_design(:ρ, Vρ; bounds = (0.0, 1.0), init = 0.5, frozen = 1.0, map = proj ∘ filter)- Their values are not variables:
zholds the free values only (the space with Dirichlet values is the affine mapx = P z + x₀), andxhas the frozen values in the zones. - The zone is real material in the physical field: at the end of every chain
x → θ, on the cells of the zones,θis the image of the frozen value by the pointwise maps (projection,PointwiseMap), whatever the filter (which would otherwise dilute it: with a filter aloneθwas 0.73–0.98 in small zones). The derivative vanishes there; the mask costs no solve and keeps a linear chain linear, soVolumeover filters stays a linear constraint. The filter still sees the zone as solid, so the free material next to it attaches smoothly. - A zone is made of whole cells (every Dirichlet value belongs to a cell whose values are all frozen); a line of nodes is an error. A vertex tag (
add_tag_from_vertex_filter!) serves P0 and P1 alike. To freeze the material under a load or at a support given as a boundary tag (a face, an edge, a vertex), in any mesh and in 3D,tag_adjacent_cells!(labels, "load_zone", model, "load"; layers = 1)tags the cells that contain it (and more layers around them); use"load_zone"indirichlet_tags. frozenis a number, one number per tag, or a function of the coordinates (constant on each frozen cell); inside the bounds. Several zones with different values (solid and void) are fine if they do not touch: the value of a zone is one number per cell. Periodic spaces work; spaces with other linear constraints (symmetries) are not supported yet.max_fractionofVolumeis a fraction of the whole domain, the zones included.frozen_indicator(x, :ρ)gives the zones as a P0 field (to write them);check_consistencychecks that θ equals the frozen value there; the banner shows the frozen cells of each block, and the checkpoint keeps their number. With a zone,θ.ρis an operation on fields: the fastFieldWriterwrites it through Gridap's slower path (a warning says so).
Interface maps turn a level-set-like field φ (φ ≥ 0 solid; the variable of reaction–diffusion) into the material, as one more map of the chain x → θ; the weak forms integrate the design region with the measure that HyperShape gives, so that a later treatment by cut cells changes the quadrature and not the forms:
z = OptVariables(φ = FieldVariable(Vφ; bounds = (-1.0, 1.0), init = x -> …)) # Vφ: P1; init may be a function of x
x = DesignFields(z)
θ = PhysicalFields(x; ρ = :φ => Ersatz() ∘ HelmholtzFilter(dΩ; rmin, ls = LUSolver())) # or ρ = :φ => Step()
dΩd = design_measures(θ; degree = 2) # dΩd.domain: a Measure; solid, void, interface reserved for cut cells
a(u, v) = ∫(… θ.ρ …)dΩd.domain
Vol = Volume(θ, dΩd; max_fraction = 0.4)Step(): χ = 1 where φ ≥ 0 at each quadrature point (the abrupt step of Li et al. 2023). A cut cell has the material of its quadrature points: a higherdegreesmooths the jumps of the objective but does not remove them (measured: with degree 2, 4 and 8 the objective did not change in 81, 52 and 10–30 of 120 small moves of an inclined interface). No derivative with respect to φ:DensityMethodrefuses it when the run starts,check_consistencyreports the derivative checks as not applicable (–); it is for methods that take the sensitivity with respect to the physical field (reaction–diffusion, next).Ersatz(): the classical ersatz material, the fraction of each cell where φ ≥ 0 (P0), with its exact derivative. Closed forms on triangles and tetrahedra (no cancellation, no allocations); quadrilaterals and hexahedra are split into 4 triangles and 24 tetrahedra around their centre (symmetric, about 6 times more accurate than splitting by a diagonal against the bilinear field). Exact volume with any quadrature for the subdivided interpolant; O(h²) for the geometry. Its input must be a nodal P1 scalar field (the design field or a filter output). The derivative lives on the cut cells only: a design without interface does not move and holes are not nucleated by it.- Frozen zones: the material of a zone is the step of its value (φ = 1 gives 1), with both maps.
- Cost of
Ersatz()(Mac M5 Max, one thread, measured by the design adviser and the reviewer): 65 536 quadrilaterals, 0.8 ms to update and 1.0 ms to pull back; 82 944 tetrahedra, 0.6 and 0.55 ms; a hexahedron cut by the interface about 350 ns (24 tetrahedra), one without interface a few ns. - Interface maps are for interface methods (reaction–diffusion, next):
DensityMethodrefusesStep()andErsatz()when the run starts (a density method interpolates the density itself, SIMP or RAMP). In interface methods the starting design need not meet the constraint: the evolution takes it there.
Starting designs with holes (hole_seed): the free values of a design field with a pattern of holes, given to FieldVariable as init:
φ0 = hole_seed(Vφ; radius = 0.05, spacing = 0.2, exclude = "clamp", connect = ("clamp", "load"))
z = OptVariables(φ = FieldVariable(Vφ; bounds = (-1.0, 1.0), init = φ0, frozen = 1.0))- Two uses: an optional perforated start for methods that nucleate holes (
ReactionDiffusion(…; sensitivity = :physical), as Yamada et al. 2010; studies of the dependence of the design on the start), and the mandatory start of methods that only move the boundary (the double-well reaction–diffusion,ReactionDiffusion(…; reaction = DoubleWell()), after Takezawa et al. 2010), whose holes are those of the seed (withbounds = (0.0, 1.0)). radius,spacing(default4radius),marginandwidthare lengths in the units of the mesh, so the start does not change when the mesh is refined. Patterns::hex(default; staggered rows in 2D, face-centred cubic in 3D, a hole at the centre of the box;jitter ∈ [0, 1)moves the centres at random without letting two holes touch),:lattice(square or cubic) and:cvt(a centroidal Voronoi tessellation of the region where holes may go, by Lloyd's relaxation: even spacing on any geometry and around the excluded zones; from the:hexcentres, or from random points at leastspacingapart withrng; therespacingis the mean distance from a centre to its nearest neighbour: the number of holes starts as that of:hexover the region and is corrected after measuring that distance, at most twice, so slender parts get fewer holes than their measure suggests;nholesfixes the number instead (rounded to whole orbits with a symmetry); so:cvtgives fewer holes than:hexwith the samespacing, 46 against 73 on a 2 × 1 plate; neighbours are at leastmin_distanceapart, by default2radius + (spacing − 2radius)/2: after each Lloyd step closer centres are pushed apart; the holes of:cvtare inside the region, those of:hexmay be cut by the boundary). The non-nucleating methods of the literature start from periodic staggered patterns (Takezawa et al. 2010); with the double-well prototype a staggered seed gave the bridge of Takezawa within 1–2 % of the published compliance and symmetric designs, and purely random seeds (Poisson disks) up to 20 % worse on the cantilever, which is why random points are only a start for:cvt.symmetry: reflections(point = p, normal = n)and rotations of ordern((point = p, order = n)in 2D,(point = p, axis = a, order = n)in 3D), alone or in a tuple: the seed is built in a fundamental region of the group and replicated, exactly symmetric; every replica keeps the distance between holes and the margins. The geometry and the zones must be symmetric too (a warning says when they are not). With:hexand:latticethe symmetry must also map the lattice onto itself (originmoves it): otherwise the replicas meet along seams with gaps, and a warning says so.- The holes keep away (
radius + margin) from the frozen zones of the space (read from it) and from the tags inexclude; the solid of the seed must join the tags ofconnect(defaultexclude) through faces, or a warning names the tag left out. Holes that no value of the field falls into (a mesh too coarse for the radius) give a warning; none at all, an error. - The value is a clipped distance (
lbat the centre withwidth = radius, the level(lb + ub)/2on the edge of the hole,ubbeyondradius + width), the minimum withbase; withbounds = (0.0, 1.0)it is a density with 0.5 on the edge. P0 and P1, any mesh in 2D and 3D; linear cost (a few microseconds per value;:cvttimes its at most 60 Lloyd steps per relaxation, up to three relaxations). Sequential. Not periodic across periodic sides. With a design space on part of the model, the cells outside it count as solid forconnect. An error when every value would be inside a hole, a warning above half (basedoes not count).
Planned: global parameters as blocks (applied voltage, fibre angle), scaling and symmetries in the map z → x, physical fields that depend on several design fields, material interpolation in the map x → θ.
Constitutive wrappers (planned, phase 1)
The design will enter the physics through constitutive models that wrap HyperFEM models by aggregation and return, besides the energy and its derivatives, the analytical derivatives with respect to the physical fields (energy interpolation, SIMP/RAMP per phase, interpolation of the solid contribution only in electro- and magneto-mechanics).
Operators
Two kinds of operator wrap a HyperFEM computational model built by the user.
StateOperator (forward, adjoint) | LinearOperator (filter, reaction–diffusion step, extension) | |
|---|---|---|
| Model | full weak forms | bilinear form only (the matrix) |
| Right-hand side | from the user's forms | vector assembled by HyperShape |
| Dependencies | invalidate the result (mandatory) | invalidate the matrix (default ()) |
solve function | (m, ctx) -> … | (m, b, ctx, stale) -> … |
Default solve (StaticLinearModel only) | solve!(m; Assembly = true) | solve!(m, b; Assembly = stale) |
- Dependencies are given positionally (
StateOperator(model, θ)) or withdepends =; an operator solves again only when one of them has changed. - HyperShape never chooses a solver: a default
solvecalls the solver of the user's model. Nonlinear, staggered and transient models need the user'ssolve(the load stepping and the restart are modelling decisions). ctxis a read-only context updated by HyperShape: design iteration, attempt, continuation values and phase.solve!passes it to every solve function of the user; outside the loop (checks, scripts)nothingis accepted.- The adjoint is declared in the state, with an
AdjointProblem: who solves the transposed system and the formspᵀ ∂R/∂θof the state. The functionals that read the state only give their partial derivatives.
Implemented:
model_u = StaticLinearModel(l, a, U, V, bc; ls = LUSolver()) # forms and solver of the user; they capture θ
# adjoint: the transposed tangent on the space with homogeneous Dirichlet values (U0, bc0), matrix only
model_p = StaticLinearModel((p, w) -> a(w, p), U0, V, bc0; ls = LUSolver())
S = StateOperator(model_u, θ; # default solve: solve!(m; Assembly = true)
adjoint = AdjointProblem(model_p; sensitivity = (u, p) -> (δ -> ∫((dk ∘ θ.ρ) * ∇(u) ⋅ ∇(p) * δ)dΩ)))For a linear and symmetric state, AdjointProblem(SymmetricState(); sensitivity) solves the adjoint with the matrix and the factorisation of the state itself (the forward model must be re-assembled by its solve, as the default one does); AdjointProblem(; sensitivity), without an operator, when only self-adjoint functionals read the state. The adjoint field is get_adjoint(S). A nonlinear forward state gives its own solve, and returns the convergence flag:
model_u = StaticNonlinearModel(res, jac, U, V, bc; nls)
uh = get_state(model_u) # captured by the transposed tangent
S = StateOperator(model_u, θ;
solve = (m, ctx) -> solve!(m; stepping = (nsteps = 10, maxbisec = 5), RestartState = false),
adjoint = AdjointProblem(StaticLinearModel((p, w) -> jac(1.0)(uh, w, p), U0, V, bc0; ls = LUSolver());
sensitivity = (u, p) -> (δ -> ∫(…)dΩ)))solvereturns the solution vector (taken as converged) or a tuple whose last element is the convergence flag, as(x, flagconv)from HyperFEM's nonlinear models. A failed solve does not throw:is_converged(S)isfalse, states that depend on it are not solved and the functionals returnNaN.- A state is solved again only when one of its dependencies changed; a failed solve is not repeated for the same design.
- The adjoint model is wrapped in a
LinearOperatorwith the dependencies ofS(extra ones withdepends): its matrix is assembled again only when the state changed, so one factorisation serves every gradient of a design. Its trial space must have homogeneous Dirichlet values (checked). - A state that depends on another state cannot be differentiated yet (the sensitivity through the upstream state would be missing): building a functional on it is an error.
Functionals
One Functional per objective or constraint:
J = Functional(Jform, S; dJdu, dJdθ = nothing, scale)
# Jform(u, θ) scalar value
# dJdu(u) ∂J/∂u, a linear form w -> ∫(…)dΩ in the test function of the adjoint; or SelfAdjoint()
# dJdθ(u, θ) ∂J/∂θ, a linear form δ -> ∫(…)dΩ (only if J reads θ directly)The value applies the forward operator S. The derivative is one reverse sweep: dJdu seeds the adjoint of S, the adjoint is solved once, and dJdθ − pᵀ ∂R/∂θ is pulled back through the maps down to z (the signs are put by HyperShape). θ is the physical fields S depends on (give fields = θ if it depends on none or on several). Implemented, with functional_value(J, ctx), functional_gradient!(gz, J, ctx) and functional_gradient!(gz, (J₁, …, Jₙ), w, ctx) (the derivative of Σ wᵢ Jᵢ in one sweep: one adjoint solve per state and one transposed solve per filter, whatever the number of functionals):
- The forms are
δ -> ∫(… * δ)dΩ, or a named tuple of such functions when θ has several fields. dJdu = SelfAdjoint()when∂J/∂uis the load of a linear and symmetric state (the compliance):p = u, no adjoint solve; valid only with homogeneous Dirichlet values in the state (checked).Jmay add a term of the design (with itsdJdθ); that∂J/∂uis the load is checked only bycheck_consistency.AdjointProblem(SymmetricState(); …): with the default solve of the state, the symmetry of the forward matrix is checked at the first adjoint solve of eachsolve!(two back substitutions; not with a solve function of the user).- Design-only functionals (volume):
Functional(Jform, θ; dJdθ, scale)withJform(θ)anddJdθ(θ). scaleis mandatory: a positive number,:initial(absolute value of the first evaluation) or1.0. A first value at the level of rounding (the functional is about zero at the start: moving z across its bounds would change the scaled value by more than 10⁸) is an error at the first derivative: give the scale.Volumeof a physical field that its design bounds and maps can make negative (a level set read withoutErsatz()orStep(), or through a projection) is an error; aPointwiseMapin the chain is not checked.
Consistency checks
check_consistency(J1, J2, …; ctx) (or a named tuple of functionals) checks, at the current design, what the user wrote and declared, and returns a report (r.passed, and one line per check, displayed as a table):
- the gradient of each functional, by a Taylor test (the error must fall with order 2 as the step is halved);
- the maps x → θ of each physical field alone, so that a failing gradient is located in the derivatives of the functional or of the state;
- the symmetry of each filter, with the user's solve;
- the declared dependencies: value and gradient at a new design, as usual and after forcing every reachable state and filter to assemble and solve again;
- optionally, the tangent of a state against its residual:
tangents = (S => (res, jac),).
z, the fields, the states and the scales of the functionals are restored on return. States shared by several functionals are solved once per design: each forward state at most steps + 4 times. A Taylor test where J does not change along the direction (a saturated projection) is reported as not tested. Objects that no declared dependency leads to cannot be checked. A physical field through Step() has no derivative: its gradient and chain checks are reported as not applicable (–, they do not count in passed) and the dependency check compares the values only. When every value of z is at a bound (the solid start of a level set) and no direction is given, the checks run at a probe design inside the bounds (lb + (ub − lb)(0.5 + 0.25 sin(1.7 i)), where a level set crosses zero) and the report says so in a note.
The derivatives are checked only when the user calls check_consistency (decision of Jesús, 2026-11-28): nothing in solve! runs it. The banner of solve! has a line derivatives: that says whether every functional of the problem had its gradient tested by check_consistency (of the problem or of the functionals) and passed; a functional through Step(), whose gradient cannot be tested, counts as not checked. The verdict goes with the Functional objects: a check on a coarse mesh with other objects does not count for the production run, whose line says "not checked".
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); only the step is specific.
| Method | Design field | Step |
|---|---|---|
DensityMethod(optimizer; metric) | density in [0, 1] | any Optimizer (OC, SiMPL) |
ReactionDiffusion(; τ) | level set in [−1, 1] through Ersatz() or Step(), or density in [0, 1] | one linear solve (factorised once), clipping, exact multiplier of the volume |
LevelSet (phase 2) | signed distance | velocity extension, advection, reinitialisation |
Implemented: Optimization, DensityMethod and ReactionDiffusion with the common loop.
Vol = Volume(θ, dΩ; max_fraction = 0.5) # physical (projected) density: nonlinear in z; Volume(x, dΩ; …) is linear
problem = Optimization(objective = J, constraints = (volume = Vol,)) # z is the one behind J
result = solve!(problem, DensityMethod(SiMPL()); # metric: LumpedMass() by default with SiMPL
maxiter = 300, stop = StopCriteria(stationarity_rtol = 1e-3),
continuation = Continuation(β = proj => [1, 2, 4, 8, 16, 32]; every = 40),
checkpoint = Checkpoint(filepath = "results/ckpt", every = 10),
monitors = (grey = Grey(θ, dΩ),),
post = OptPostProcessor((post, ctx) -> write_step(post, Ω, "rho" => θ.ρ); every = 10,
filepath = "results/opt"))
result.status, result.history.objective, result.history.constraints.volume, get_values(result.z)Volume(θ, dΩ; max_fraction) bounds the fraction of the domain filled by the physical density, the one the weak forms read; Volume(x, dΩ; max_fraction) that of the design density. The Helmholtz filter preserves the volume, the tanh projection does not: on a 150×50 half MBB beam with target 0.5, the design volume leaves the physical one at 0.64–0.68, the physical volume holds it at 0.5000.
- Constraints: any number, named, each a functional alone (
g ≤ 0, asVolume) or aConstraint(F; max, min, equal)in the units ofF(withscale = :boundthe scale is taken from the bounds). The banner shows the bounds in the units ofF; the history and the table, the scaled value(F − r)/s(rthe upper bound, or the lower one if there is none). Each optimiser declares which constraints it treats itself (handles,max_native): OC and SiMPL treat oneg ≤ 0that solves no state; the others go to the augmented Lagrangian (below). The oracle gives the optimiser, for each constrainti, its bounds and kind (constraint_info), its value and derivative, andweighted_gradient!, the derivative ofw₀ f + Σ wᵢ gᵢin one reverse sweep (one adjoint solve per state). For the constraint that OC or SiMPL treats, a linear one (Volumeover identity or filter maps, orlinear = true) is checked to be linear at the start and its vectorais computed once. A nonlinear one is linearised by the optimiser at every step and corrected with evaluations of the true constraint until it holds toconstraint_tol(OC1e-4, SiMPL1e-6; SiMPL keeps every iterate feasible; at an infeasible design, after a continuation jump, it first takes restoration steps that must reduce the violation, which can take several steps or end the stage as stalled). Cost per step: one transposed filter for its derivative and one filter per correction (about 1.5–3), no forward solve. - Augmented Lagrangian:
DensityMethod(SiMPL(); lagrangian = AugmentedLagrangian(Bertsekas(μ0 = 1.0))), the default whenever a constraint is not native (a lower bound, an equality, an interval, one that reads a state, or more than the optimiser takes). The optimiser seesf + Σ term(gᵢ)over those constraints (Bertsekas' rule:term = μ/2 (y − Π(y))² − λ²/(2μ)withy = g + λ/μandΠthe projection onto the bounds), whose gradient is one weighted reverse sweep; the multipliersλ ← μ (y − Π(y))are updated after every accepted iteration and the optimiser keeps its step size (objective_changed!: SiMPL keeps Barzilai–Borwein, which the bench needs). The penalty is fixed by default (growth = 1): a growing penalty makes the subproblem ill-conditioned for first-order optimisers (5 of 7 Hock–Schittkowski problems fail with SiMPL).native = (:volume,)or()chooses the split; OC needs one native constraint and is heuristic with an objective of mixed sign. The run converges only with every constraint met to its tolerance (constraint_tolof the optimiser for the native, of the augmented Lagrangian for the others). History:constraints,violations,multipliers(λfor the augmented Lagrangian) andpenalties; the checkpoint (format 2) keeps the split,λ,μand the counters, so a resumed run continues the same multipliers. - Metric:
LumpedMass(dΩ)(cell volumes for P0, lumped mass for P1) orEuclidean(); mandatory for SiMPL, OC uses it only for the stationarity measure (defaultEuclidean(); giveLumpedMass(dΩ)to compare it with SiMPL). - Rejection (
on_failure, defaultRejectStep(shrink = 0.5, max_attempts = 5)): if the forward problem does not converge at the new design, the loop restores the previous one, callsshrink!and tries again, at mostmax_attemptstimes; then it throwsOptimizationFailure(checkpoint written). SiMPL handles failures inside its line search; if it finds no step, the current continuation stage ends (in the last stage, or without continuation, the result is:stalled). - Continuation: explicit list of values per stage, a jump every
everyiterations (or when the optimiser finds no step); withclose_early = truealso when the stopping criteria are met. The optimiser forgets its memory at each jump; the optimisation only stops in the last stage. - Stopping:
maxiteris mandatory.stopdefaults toStopCriteria(objective_range = 1e-3)for OC and SiMPL (default_stop;ReactionDiffusion: material, objective and constraints, below): the range of the objective over the last 10 iterations of the last stage, relative to the largest|f|of that window, below 0.1 % (no reference to the first objective of the run, whose value may be far from the final one; an objective that tends to zero needsobjective_atol, an absolute tolerance on the range). With a tanh projectionchange_tolandkkt_tolare rarely reached; the objective settles (half MBB beam 150×50: OC with adaptive move limits stops at iteration 214, 0.4 % above its value at 500 iterations; SiMPL at 210, within 0.3 % of 350 iterations). Other criteria:kkt_tol,kkt_rtol(relative to the first iteration),stationarity_tol,stationarity_rtol(the measure‖z − P(z − g)‖_Mof the SiMPL paper, computed by OC and SiMPL at the design before each step and shown in the columnSof the table and the history),change_tol;stop = nothingrunsmaxiteriterations. A run that oscillates or whose physical volume keeps growing may still end atmaxiter. - Grey monitor:
solve!(…; monitors = (grey = Grey(θ, dΩ),))adds the measure of grey4/|Ω| ∫ρ(1 − ρ)to the history, the table and the closing line. It is fixed mostly by β, so it is a measure of quality, not a stopping criterion. - Context:
OptContext(iteration, attempt, trial, phase, continuation values, sensitivity mode) reaches every solve function of the user; phases:setup,:check,:optimizationand:linesearch;sensitivityis:physicalonly whileReactionDiffusioncomputes the sensitivity of its step with an interface map in the chain. - Checkpoint:
checkpoint.toml,z_<k>.binandhistory_<k>.csvin a folder; resume withsolve!(…; resume = "results/ckpt")(the folder; or the result ofload_checkpoint). OC (adaptive move limits, correction shift) and SiMPL (latent variable, Barzilai–Borwein memory, multiplier, shift) save their memory (memory/restore_memory!, a named tuple of numbers and design vectors), and the offsets of the linear constraints are kept (unless the user changed the bound or the scale), so a run resumed from an accepted iteration gives the designs of the uninterrupted one bit for bit (its first iteration repeats one forward solve). The state of a run is anOptState(problem.state[]aftersolve!;resume = problem.state[]continues without files); after an exception or an interruption the memory of the optimiser is not kept, and the resumed run restarts it. Checkpoints have format version 4 (version 3, without the columnstep_solvesof the history, is read with those rows at 0; a resumed run says so). AnOCcontinued bycontinuationgets itsmoveback at the end ofsolve!. - Factories and discretisation:
Optimization(model; design_setup, physics_setup)builds the problem from two functions of the user:design_setup(model) -> (; z, x)andphysics_setup(model, x) -> (; objective, constraints, monitors, output, …)(every name returned is kept inproblem.designandproblem.physics). What is continued or independent of the mesh (aTanhProjectionof aContinuation, aParameter, the optimiser) is created once, outside them; spaces, measures, fields, states, functionals, monitors and the output driver are created inside.solve!(…; discretization)says when the problem is built again:FixedMesh()(default) never;HyperShape.Methods.RebuildCheck(at | every; what = :design | :physics)on the same mesh, to check the factories (with linear states and direct solvers it is the run ofFixedMesh()bit for bit, the counts of solves aside; at each rebuild the screen says whether the objective at the rebuilt problem is identical to the one of the history). A rebuild goes through the capturedOptState, as a resume does; after itsolve!checks that the factories built new variables and functionals, kept the blocks, constraints (names, bounds, kind), monitors and output, and that a continuedTanhProjectionis in the new maps. With factories, monitors and the output come fromphysics_setup(OptPostProcessor(; every, filepath)without a driver); the post-processor closes its writers at each rebuild and keeps one collection.result.problemis the last problem. Adaptive meshes (phase 4) are discretisations with a change of mesh and a transfer of the state. Example:examples/mbb_factories.jl. - Start: a starting design that violates the constraint is scaled towards the lower bound (a linear constraint: on the entries it acts on, with equality; a nonlinear one: by regula falsi to
-1e-6 ≤ g ≤ 0); the factor is inresult.start_scaling. A resumed design is not touched, nor the design at a continuation jump. - Convergence with a nonlinear constraint: the stopping criteria count only when the constraint also holds to
constraint_tol. - Screen output:
verbose = 2(default) prints a banner (with the maps of the physical fields, the scales of the functionals and the parameters of the optimiser), a row per iteration (objective, its relative change, constraint, optimality measure, stationarity, change, step, multiplier, monitors, solves, time; only the columns that the method fills, no column for the continued parameters (their jumps are events), and only the counters of solves that can happen, explained by a legend, the last line of the banner), the events, a closing line with the objective also unscaled, the constraints at the last design in their units and the solves of the call;1omits the rows;0prints nothing. The output goes toio. For a method whose step solves linear systems of its own (ReactionDiffusion), the column of solves has the countersand the summary addsstep N: the hookHyperShape.step_solves(opt, state)(accumulated sinceinit,nothingby default), which the loop differences per iteration intohistory.step_solves(column 11 of the CSV), as it does with the forward, adjoint and filter solves. A density method has none: its table and summary do not change. - Failures:
OptimizationFailurecarries the message, the history up to the last accepted iteration and its number; the history also records the multiplier of the linear constraint. An objective that is not finite while its states converged is reported as such (a functional returned NaN or Inf), not as a forward failure. - Setup errors (checked again by every
solve!): a continuedParameterwhose values change and that no operator, map, functional, monitor, the method or a solve function of the user (by capturing it) declares; with aDensityMethod, an objective whose first derivative is identically zero (a load on a tag without faces;ReactionDiffusiontakes it as diffusion alone, and the closing line flags an objective exactly zero);OCwith a lower bound below zero (its update is multiplicative); and those of the functionals above. - Suspicious closings: the closing line is ⚠ instead of ✓, followed by the reasons, when the objective ended above its first value (from a feasible start; with a continuation, the first value of the last stage), is exactly zero or did not change over the last window while the design did, the whole design is at one bound, or
OCdropped more than 5 % of the derivative at its first step (the positive part of a derivative of mixed sign; also an event at the first iteration).statusandreasondo not change, and nothing is added to the result: withverbose = 0the reasons are not shown, so in a batch compareresult.objectivewithresult.history.objective[1]and look for a design at a bound.ReactionDiffusionwith an objective exactly zero is not flagged (a zero sensitivity is diffusion alone). A continuation thatmaxitercuts before its last stage is announced in the banner and at the end. - Repeated runs and resumes: a second
solve!on a problem (withoutresume) says what it inherits from the previous one (the design, scales fixed by:initial, continued values left at the last stage). A checkpoint keeps a fingerprint of the problem (the method with the parameters of its step and augmented Lagrangian, the metric, the bounds of the blocks, the bounds,Vmaxand scales of the functionals, the continuation, the projections;OptStateis unchanged, the fingerprint is kept beside it); a resume reports each difference, a changed offset of a linear constraint, and an objective at the restored design that differs from the last row of the history. - Solves per iteration: OC one filter, one forward, one adjoint (none if self-adjoint) and one transposed filter; SiMPL one filter and one forward per line-search trial (usually one), one adjoint and one transposed filter. After a rejected step the previous design is not solved again.
Reaction–diffusion
ReactionDiffusion(; τ, sensitivity) evolves one nodal P1 field φ by an implicit step of the reaction–diffusion equation ∂φ/∂t = −C g − λ + τ ℓ² Δφ (Yamada et al. 2010, Choi et al. 2011, Otomori et al. 2015, Kim et al. 2020):
z = OptVariables(φ = FieldVariable(Vφ; bounds = (-1.0, 1.0), init = 1.0, frozen = 1.0)) # level set, solid start
x = DesignFields(z)
θ = PhysicalFields(x; χ = :φ => Ersatz()) # material: the fraction of each cell where φ ≥ 0
dΩ = design_measures(θ; degree = 4)
# … the state with E(χ) = Emin + χ (1 − Emin), the compliance C and Vol = Volume(θ, dΩ; max_fraction = 0.5)
result = solve!(Optimization(z; objective = C, constraints = (volume = Vol,)),
ReactionDiffusion(; τ = 2e-4); maxiter = 400)The whole script is examples/cantilever_rd.jl. The same method evolves a density (bounds = (0.0, 1.0), χ = :φ (the identity) and SIMP in the weak forms).
Sensitivity (deduced from the design chain, decision of Jesús, 2026-11-28; the banner says which and why): with an interface map (
Step(),Ersatz()) read by the objective or by a constraint of the augmented Lagrangian, the derivative with respect to the material, the map taken as the identity weighted by the material,(w₀ + (1 − w₀) χ) ∂j/∂χ(w₀ = void_weight, default1e-3): it nucleates holes (the exact derivative through the map is not a method: it lives on the cut cells and would refill the void); with a density and with the double well, the exact derivative. The keywordsensitivityof earlier versions is deprecated (accepted with a warning; a value that contradicts the chain is an error), andvoid_weightgiven where it has no effect is an error.Step:
(mass/Δt + τ ℓ² K) δ = −τ ℓ² (K z + k_d) − C g,φ* = z + δ, thenz = clamp(φ* − λ φ̌, lb, ub).Kis the diffusion matrix (∇φ⋅∇v, or the bilinear formdiffusion = (φ, v) -> ∫(…)dΩof the user),k_dthe frozen values in the free rows,ℓ² = |D|^(2/d)(|D|the measure of the design domain, soτis dimensionless; in 3D this scaling is provisional),masslumped (default) or consistent. HyperShape assemblesm,K(andM) once on the design space with Gridap's assembler and factorises the operator once withls(Gridap'sLinearSolver,LUSolver()by default, shown in the banner);solve = (A, b, x, ctx, stale) -> xreplaces it (PETSc, an iterative solver). The operator is factorised again only whenΔtorτchange (aParameterof aContinuation, a rejected step). Frozen zones of the design space stay as they are (Neumann conditions for φ elsewhere).Volume (
ExactVolume(; max_step, tol, maxiter), the default): the constraint built withVolume, wherever it is in the problem (with none or several,solve!asks to name it withlagrangian = AugmentedLagrangian(native = (:name,))); the multiplierλis the root ofG(λ) = g(clamp(φ* − λ φ̌)) − g_kwithφ̌ = A⁻¹ m(Δteverywhere when no value is frozen): Newton on the clipped vector for a linear constraint (vectors only), Newton with the derivative of the constraint forErsatz(), regula falsi (Illinois) forStep(), always inside the bracket given by the bounds, from theλof the previous step. With an interface map the target goes downmax_step = 0.02of|D|per iteration from the start (a solid start is not made feasible), with equality; at the final target the constraint isg ≤ 0withλ ≥ 0. A density meets the target from the first iteration. The augmented Lagrangian of the method takes every other constraint. The tolerancetol = 1e-4is a fraction of|D|, likemax_step(converted with the scale of the constraint: the loop, the history and the table show the scaled value). WithStep()the volume is piecewise constant: the root evaluates it with the material meter of the step (the quadrature of theVolumefrom the nodal values: exact, no constraint evaluation, no allocation) until at most one quadrature point changes side inside the bracket, and ends on its feasible side: the best feasible volume at the resolution of the quadrature points (checked against a sweep of λ). On coarse meshes the jump of one point exceedstol. Measured on the 2 × 1 cantilever, 400 iterations (Mac of the lab, 4 threads, Julia 1.13.0, 2026-11-24):Ersatz()1.6 evaluations of the constraint per step at 120 × 60;Step()none through the constraint and 44, 31, 16, 4.2 and 3.8 evaluations of the meter at 20 × 10, 30 × 15, 40 × 20, 60 × 30 and 120 × 60; after the descent the volume ofStep()stays withintolat 60 × 30 and 120 × 60 (0.2 and 0.7 cells below at most) and goes down to 1.2–3.5 cells below on 30 × 15 and 20 × 10, where the quadrature points of a cell change together (before: up to 20 cells below, with 3.5–3.7 evaluations of the constraint per step).Sensitivity (mandatory):
:physicaldifferentiates with respect to the material, the interface map taken as the identity weighted by the material,(w₀ + (1 − w₀) χ) ∂j/∂χ(void_weight = w₀ = 1e-3): holes nucleate where the material is little used. The exact derivative through the map would refill the void (in the prototype the design oscillated, J = 16–70 against 2.4).:designis the exact derivative with respect to φ: for a density (without an interface map both are the same) and with the double well (below), where it is the default.:designwith an interface map is not a method andsolve!throws: the exact derivative lives on the cut cells and, with the exact multiplier of the volume, which shifts φ uniformly, the solid plateau sinks where the derivative vanishes (measured from hole seeds on the 120 × 60 cantilever: 7–25 % worse than:physical, specks). The variant that only moves the boundary, from a start with holes (hole_seed), is a density withreaction = DoubleWell(…).check_consistencyalways checks the exact derivative; withErsatz()give it steps below the default,check_consistency(…; h0 = 1e-3): larger steps cross the kinks of the cell fractions (a node changing sign) and the observed rates fall below 2 for a correct derivative.Normalisation (
normalize):L1Mean(c)(default,C = c |D| / Σ|gᵢ|, independent of the mesh),L2Norm()(Kim et al.),MaxAbs(), or a function(g, m, area) -> C.Stopping (
default_stop): the constraints met and the material changed in each of the last 5 iterations,M_k = ∫|χ_k − χ_{k−1}| / ∫χ_k < 2e-3(χthe field theVolumereads, cell by cell), and the relative range of the objective over the last 10 iterations below1e-3; the windows count only iterations with the constraints met, never the descent of the volume (StopCriteria(material_tol = 2e-3, objective_range = 1e-3, combine = :all)).M_kis computed by the step from the nodal values, without solves or allocations. Options:StopCriteria(rate_tol = 0.1)(‖Δφ‖∞/Δt),change_tol(‖Δφ‖∞) andphase_tolwithphase_window(the lumped mass of the nodes where φ changes sign over|D|, only with an interface map).Defaults of the evolution:
Δt = 0.2andmax_step = 0.02of|D|per iteration with an interface map,Δt = 0.4and the target from the first iteration for a density (the banner says which). On the 2 × 1 cantilever they reach a stable topology in a few tens of iterations (study of 24 runs on 120 × 60 and 240 × 120 meshes). The topology of reaction–diffusion depends on the path: with a smallerΔtthe design passes through metastable plateaus (9–16 holes, the objective and the material steady for 20 iterations or more) and the diffusion keeps merging holes long after the design looks converged; any reasonable criterion then stops on a plateau (a clean design, with an objective equal or better, but not the one of iteration 400). Neither the interface map (Step()orErsatz()) nor the stopping criterion is a recommendation yet: the choice will be validated with more cases.Diffusion and thickness:
√(τ |D|)(0.02 forτ = 2e-4on a 2 × 1 domain, 1.2 cells of a 120 × 60 mesh) is the length of a gradient (perimeter) energy, not a minimum thickness: bars of one or two cells are expensive but admissible, and they disappear only as the perimeter decreases, slowly. The 5th percentile of the thickness grows withτ, the minimum does not; a minimum size needs a filter or a constraint, which the method does not have.Condition of the design field on the boundary (
phi_bc)::neumann(default, the natural condition of the diffusion),:zero_boundary(φ = 0on every node of the boundary of the design domain, found from the topology of its cells; Otomori et al. 2015) or"tag" => valuepairs (φheld on the nodes of each tag, the nodes thatdirichlet_tagswould make Dirichlet; Yamada et al. 2010, Cui et al. 2023:phi_bc = ("load" => 1.0,)). The values are written into the design whensolve!starts, before the first evaluation and anyscale = :initial, and the step holds them in its operator: identity rows and columns, no increment andφ̌ = 0there, so the multiplier of the volume does not move them and the root of the volume leaves them out of its bracket (a value held at a bound would give 0/0). They stay values ofz: not a frozen zone (a zone is a set of cells of material), and where a tag touches the frozen values of a zone the zone wins. One more back-substitution per factorisation (φ̌); not with the double well. With:neumannnothing of this runs: the runs are those of before bit for bit.Rejection: when the forward problem does not converge at the new design,
RejectStephalvesΔt(the operator is factorised again, the gradient comes from the snapshot of the oracle) and the nominalΔtcomes back at the next step.Checkpoint: the multiplier is the memory of the step (
memory) and the windows of the stopping criteria are saved too: a resumed run is the uninterrupted one bit for bit and stops at the same iteration.Settings of papers: keywords like any other, not part of the API.
validation/common/presets.jlwrites those of Kim et al. (2020),KIM2020 = (Δ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))), used asReactionDiffusion(; τ, KIM2020...)(a keyword after them replaces theirs). Withvolume = nothingevery constraint goes to the augmented Lagrangian (nonativeto write); otherwise the step treats the constraint built withVolume, or the one named withlagrangian = AugmentedLagrangian(native = (:name,)), its only name (giving bothvolume = nothingand anative, or two different names, is an error). The positional presetsReactionDiffusion(:kim2020; …)and(:takezawa2010; …)of earlier versions are deprecated. Deprecated forms (these presets,sensitivity,ExactVolume(constraint),native = ()with the default volume) still run, with a warning that Julia shows only withjulia --depwarn=yes(off by default; on inPkg.test()).Per iteration: one forward solve, one adjoint (none with
SelfAdjoint()), one assembly of the sensitivity, one productK zand one substitution of the step, no factorisation; the volume costs a few evaluations (vectors for a density; the interface map and one integral for a level set). The solves of the step are inhistory.step_solves(one per step, one per implicit substep of the double well, none with the explicit scheme, plus the unit responseφ̌of the exact volume at each factorisation inside an iteration when values are held: after a rejected step and at the return to the nominal Δt), in the countersof the column of solves and in the summary (step N); the line below it adds the factorisations and the evaluations of the volume (through the constraint and by the material meter). Theφ̌thatinitsolves (at the start, at a resume and at each rebuild) is counted only in the summary, so with held values the summary has one more solve perinitthan the sum of the column. A resume or a rebuild right after a rejected step factorises at the nominal Δt in itsinit: theφ̌of the return to Δt goes there, and the next row has one solve less than in the uninterrupted run (the work is counted as done; designs and objectives are the same bits).Coarse meshes with
Step(): the default stop is not met on the 20 × 10, 30 × 15 and 40 × 20 cantilevers in 400 iterations (the material keeps changing by quadrature points,M_kof 1e-2 to 4e-2), whileErsatz()stops at 56, 124 and 99 and the density at 35, 51 and 32; at 60 × 30Step()stops at 123 and at 120 × 60 at 65. A run that reachesmaxiterwith the material still changing says so at the end. Without a meter (noVolumeover the design domain read throughIdentity(),Step()orErsatz()) the default stop uses the constraints and the objective range, and the banner says so.Allocations: the arithmetic of the step and a linear volume allocate nothing (one substitution of UMFPACK aside); each evaluation of a nonlinear volume reserves about 70 kB and each derivative of
Ersatz()about 130 kB (Gridap's integration), independent of the mesh.Not yet: the presets of Otomori, Yamada and Choi, the second loop of Kim et al. (2020) (explicit double well with a decreasing diffusion, a refinement stage), the double well with an interface map, 3D validation.
Double well
ReactionDiffusion(; τ, reaction = DoubleWell()) is the variant that only moves the boundary (Takezawa, Nishiwaki and Kitamura 2010; Kim et al. 2020, loop 2): a density φ ∈ [0, 1] read through Identity() (with an interpolation such as k(φ) = max(φ³, 1e-5) in the weak forms), started from a design with holes, evolves by
∂φ/∂t = τ ℓ² Δφ − W w′(φ) − 30 w(φ) (η C g/m + λ), w(φ) = φ² (1 − φ)²The well keeps the design near 0/1 with an interface of width ξ = √(τℓ²/2W); the sensitivity and the multiplier of the volume are both weighted by 30 w(φ), which vanishes at 0 and 1, so the reaction moves only the interface and no hole is nucleated (the start needs an interface: solve! throws otherwise and points to hole_seed(Vφ; bounds = (0.0, 1.0), …)).
φ0 = hole_seed(Vφ; bounds = (0.0, 1.0), radius = 0.1, spacing = 0.4, exclude = ("roller", "pin", "load"))
z = OptVariables(φ = FieldVariable(Vφ; bounds = (0.0, 1.0), init = φ0))
θ = PhysicalFields(DesignFields(z); χ = :φ) # a density read as it is (the identity)
# … the state with k(φ) = max(φ³, 1e-5), the compliance C and Vol = Volume(θ, dΩ; max_fraction = 0.3)
result = solve!(Optimization(z; objective = C, constraints = (volume = Vol,)),
ReactionDiffusion(; κ = 1e-5, reaction = DoubleWell()); maxiter = 300) # τ = κ/|D| = 5e-6, T = 25The whole script is examples/bridge_dw.jl; validation/bridge_takezawa.jl reproduces the published bridge.
- Scheme (decision of Jesús, 2026-11-25):
scheme = :implicit(default) splits each of thensubsteps of an iteration into an implicit diffusion with the operator of the step, factorised once,(m/Δt + τℓ²K) ψ = m φ/Δt − τℓ² k_d, and the semi-implicit pointwise reaction of Takezawa et al. (their Eqs. 44–45) applied toψ, withλinside the tilt term: the result stays in[0, 1]for anyΔt.scheme = :explicitis their scheme (ψ = φ − Δt τℓ² m⁻¹(K φ + k_d), no linear system). The sensitivity is computed once per iteration and frozen over the substeps. - Physical parameters (decision of Jesús, 2026-11-26):
κ = τ ℓ²and the time of the evolution per iterationT(DoubleWell(T = 25)) are physical, the same on every mesh.ReactionDiffusion(; κ = …)takesκdirectly (exactly one ofτandκ; the banner shows both):κis the coefficient ofKin the operator as given, andτenters asτ ℓ², soτ = κ/ℓ²with theℓ²of the method (a quadrature of|D|) gives the same run bit for bit (τ = κ/2on the domain 2 × 1 can differ in the last bits, and the double well amplifies them). With the wellκ(orτ) andΔtare numbers: aContinuationof them would leavenandΔtstale, andReactionDiffusionrefuses aParameterthere. An iteration isn = ⌈T/(cfl Δt_lim)⌉substeps ofΔt = T/n, withΔt_lim = 2/maxᵢ(τℓ² Σⱼ|Kᵢⱼ|/mᵢ)(Gershgorin, from the assembledKandmonce at the start:0.375 h²/(τℓ²)on squares, any mesh) andcfl = 4/3with:implicit,1/3with:explicit(h²/(8τℓ²), the step of Takezawa et al.). The pointwise reaction needs√(τℓ² Δt) ≲ 0.7 h(a limit like a CFL condition), so the number of substeps grows like(h₀/h)²: with κ = 1e-5 andT = 25on the domain 2 × 1, 2, 5, 20 and 80 substeps on 100 × 50, 200 × 100, 400 × 200 and 800 × 400. No new factorisation per iteration.DoubleWell(substeps = n)fixesninstead (withoutT: giving both is an error;Δt = :autoof the method is thencfl Δt_lim; the settings of Takezawa et al.,TAKEZAWA2010invalidation/common/presets.jl). The event after the setup givesT,n,Δt,Δt_limandξ = √(τℓ²/2W)in mean cell sizes(|D|/cells)^(1/d)(Kandmare assembled once, in the setup; the banner gives the formula; once persolve!, and again after a rebuild of the discretisation only if it changed). More than 10⁶ substeps per iteration are refused. With:explicitthe operator of the step is never factorised. - Mesh (study of 2026-11-25,
validation/mesh_double_well.jl): with κ = 1e-5 andT = 25the compliance of the cantilever 2 × 1 from:hexis the same within about 3 % on 100 × 50, 200 × 100 and 400 × 200 (2.558, 2.493, 2.426 with 2, 5 and 20 substeps: within ±2.7 % of the value on 200 × 100), but the topology depends on the seed and on the mesh (no holes are nucleated, and a coarse mesh resolves the seed and the thin bars differently). The bridge of Takezawa et al. has a point load: its compliance grows likelog(1/h), so its values on different meshes are not comparable (its validation is on 200 × 100, the mesh of the paper). - Volume: the same
ExactVolume; its multiplier acts inside the tilt (only on the interface, noφ̌and no extra solve):G(λ) = g(R(ψ; η C g/m + λ)) − g_jis non-increasing, its root is found at every substep on vectors (regula falsi, Illinois, from the previousλ), the target of the iteration is reached linearly over the substeps andmax_step = :autois0.01of|D|per iteration. A target out of reach in one substep (not enough interface) takes the end of the bracket; the next substeps catch up. - Defaults with the well: the exact sensitivity (
void_weightis refused),normalize = L2Norm()(withη = 10it isη = 20of Takezawa et al. on their domain of measure 2),W = 1/4. - Settling (decision of Jesús, 2026-11-25): with the sensitivity frozen over the substeps the interface overshoots and comes back, and 1–2 % of the material changes phase at every iteration.
settle = true(default) goes to one substep (of the sameΔt) per iteration when the constraints are met and the relative range of the objective over 10 iterations is below1e-3(settle = (window = 10, tol = 1e-3), both replaceable); an event says so. It depends only on the objective (no fraction ofmaxiter: a run resumed with a largermaxiteris the uninterrupted one), and a continuation jump starts the substeps and the window again.DoubleWell(settle = false)keeps the substeps. - Default stop with the well (decisions of Jesús, 2026-11-25/26): after settling the interface still keeps a cycle of a few per mille of the material per iteration, so the default stop takes
material_tol = 1e-2with the well (2e-3without it), the objective range1e-3over 10 iterations and the constraints unchanged. It is checked only from the iteration after the settling (or from the start with one substep, or withsettle = false).solve!(…; stop)replaces it and is not held. The early stops of the study (400 × 200 and 800 × 400 from the seed of Takezawa, iterations 49–53) were not an interface stuck with the windows met: on 400 × 200 (iteration 53) the relative range of the objective over the window was 3.5e-3, above1e-3, butobjective_rangethen measured it againstmax(max|f|, 1e-3 |f₁|), and the first objective of those runs is huge (holes of the seed over the supports:f₁ ≈ 3e5, a floor of 315 forJ ≈ 25). That floor, common to every method, has been removed: the range is relative to the window alone (objective_atolcovers objectives that tend to zero). It also caused the stops at 77 and 93 documented before (bridge 200 × 100 and the 400 × 200 case above with the hold, both from the seed of Takezawa). Measured (Validation page): the bridge 200 × 100 from:hexsettles at 74 and stops at 75 (J 23.90; from the seed of Takezawa 72 and 82, J 23.67), the cantilever 200 × 100 at 74 and 75 (J 2.493). - Grey:
StopCriteria(grey_tol)stops on the measure of greyΣᵢ mᵢ 4φ̂ᵢ(1 − φ̂ᵢ)/|D|(nodal, without allocations); with the well it stays at 1–3 % (the interface), so it is a criterion for a refinement stage, not for the evolution from the seed. - Settings of Takezawa et al. (
TAKEZAWA2010invalidation/common/presets.jl,ReactionDiffusion(; τ, TAKEZAWA2010...)):DoubleWell(W = 0.25, η = 20, scheme = :explicit, substeps = 20, settle = false), the normalisation1/‖g‖_L²(without|D|; a function(g, m, area) -> Cof the script),ExactVolume(max_step = 0.01); the script setsτ = κ/ℓ², the seed andmaxiter = 100, stop = nothing. Differences with the paper: an exact multiplier instead of their rule for ζ, P1 finite elements with lumped mass instead of finite differences. - Per iteration: one forward solve, one adjoint (none with
SelfAdjoint()),nsubstitutions (none with:explicit) andnroots on vectors, no factorisation; the step allocates nothing but the substitutions of UMFPACK (nothing at all with:explicit). - Checkpoint: the multiplier, the settling and the window of the objective that decides it are the memory of the step (the substeps follow from the settling and the setup): a resumed run is the uninterrupted one bit for bit, across the settling and with a larger
maxiter. - Not offered: the double well with an interface map (
Ersatz(),Step(): φ ∈ [−1, 1] read through the map gave hundreds of specks in the prototype), the sensitivity with respect to the material with the well, and the nucleation of holes.
Optimisers
HyperShape.Optimizers is independent of finite elements: an optimiser sees vectors, bounds and an oracle.
abstract type Optimizer end
init(opt, z, oracle) -> state # memory and history
step!(opt, state, z, oracle, ctx) -> StepInfo # overwrites z with the next design
reset!(opt, state) # forget the history
shrink!(opt, state, factor) # roll back the last step, reduce the step sizeThe oracle is the only thing an optimiser may ask: value and derivative of the objective, value at a trial point (forward problem only), bounds, the constraint (its vector when it is linear; its value and derivative when it is nonlinear, which needs no forward solve) and the inner product of the design metric. Implemented: OC (optimality criteria of top88, with adaptive move limits per entry by default) and SiMPL (mirror descent with a latent variable, Armijo or Bregman line search). FunctionOracle builds an oracle from plain functions:
using HyperShape.Optimizers
using HyperShape.Optimizers: init, step!
t = [0.9, 0.1, 0.7, 0.4]
oracle = FunctionOracle(z -> sum(abs2, z .- t) / 2, (dF, z) -> (dF .= z .- t);
lb = 0.0, ub = 1.0, constraint = (ones(4), 1.6)) # Σz ≤ 1.6
z = fill(0.4, 4)
opt = SiMPL()
state = init(opt, z, oracle)
for k in 1:50
info = step!(opt, state, z, oracle, nothing)
info.kkt < 1e-6 && break
endPost-processing
OptPostProcessor(driver; every, filepath) calls the user-written driver(post, ctx) at the starting design, every every accepted iterations, at the end and after a failure, following the pattern of HyperFEM's PostProcessor. It does not take the problem: solve! passes it (post.problem), so it can be built before or after it. The user decides which fields are written and on which triangulation; extend_field(f, Ω; outside) takes a field of the design zone to a larger domain with a fixed value outside.
post = OptPostProcessor(every = 10, filepath = "results/mbb") do post, ctx
write_step(post, Ω, "rho" => extend_field(θ.ρ, Ω; outside = 1.0), "u" => get_state(S))
endwrite_stepwrites with aHyperShape.FieldWriter(public, not exported, as it is meant to move to HyperFEM), one per name, built at the first call and closed whensolve!returns, fails or is interrupted. The mesh is built once and is continuous (one point per vertex of the grid, not one per cell and vertex ascreatevtk); the values come straight from the degrees of freedom: P0 as cell data, P1/Q1 as point data, pointwise operations on them and on constants (θ.ρ,E ∘ θ.ρ,1 - ρ) andextend_field. Other fields (gradients, discontinuous spaces) are evaluated by Gridap at the vertices, with a warning.format = :vtu(default, any ParaView, a.pvdcollection; each file carries the mesh) or:vtkhdf(one HDF5 file with every iteration and the mesh written once;using HDF5; ParaView ≥ 5.12; the same fields at every iteration).precision = Float32halves the values;async(default with more than one thread) writes in another task, so the loop only waits for a copy of the values.createvtkstays available:get_pvd(post)[ctx.iteration] = createvtk(Ω, file; cellfields = …).- The
.pvdcollection (iteration as time) is written again after every entry, so ParaView can open it during the run and it stays valid after an interruption; a resumed run keeps the entries up to its checkpoint (VTKHDF files drop the later steps). filepath/history.csvholds the history of the run, written again at every call.- No extra solves: the forward solve of the starting design is the one of the first iteration, done earlier.
Per step, three fields (P0, a projected P1 and a P1 vector), Apple M5 Max, Julia 1.13.0, 4 threads (minimum of 6 consecutive steps; VTU sizes include the mesh):
| 150×50 | 40³ | 64³ | |
|---|---|---|---|
createvtk | 4.5 ms, 2.0 MB | 44 ms, 34 MB | 196 ms, 139 MB |
| VTU | 0.28 ms, 0.76 MB | 1.3 ms, 8.6 MB | 5.5 ms, 35 MB |
| VTKHDF, Float32 | 0.57 ms, 0.22 MB | 0.97 ms, 2.2 MB | 2.4 ms, 8.7 MB |
loop blocked with async (VTKHDF, Float32) | 0.05 ms | 0.40 ms | 1.5 ms |
The first step builds the mesh and the maps (about 1 s at 64³). Planned: PVTU and VTKHDF with MPI, XDMF, GPU, quadratic cells, and moving the writers to HyperFEM (HyperFEM issue #257).
Defaults and how to replace them
A default never removes generality: everything it sets can be replaced from the user's script. The banner of solve! marks the defaults of the loop in use (stopping criteria, failure handling, metric).
| Default | Where | How to replace it |
|---|---|---|
solve!(m; Assembly = true) | StateOperator of a StaticLinearModel | solve = (m, ctx) -> … |
solve!(m, b; Assembly = stale) | LinearOperator of a StaticLinearModel | solve = (m, b, ctx, stale) -> … |
() (constant matrix) | dependencies of a LinearOperator | LinearOperator(model, deps) |
RejectStep(shrink = 0.5, max_attempts = 5) | solve!(…; on_failure) | on_failure = RejectStep(…) |
default_stop(optimizer) | solve!(…; stop) | stop = StopCriteria(…), stop = nothing or stop = (info, history, ctx) -> Bool |
Euclidean() (only for the stationarity measure) | DensityMethod(OC()) | metric = LumpedMass(dΩ), a vector of weights or an object with metric_weights(m, z) |
LumpedMass() (the lumped mass of the design space) | DensityMethod(SiMPL()) | the same |
Identity() | DesignFields(z), PhysicalFields(x; χ = :φ), PhysicalFields(x) | a map: PhysicalFields(x; χ = :φ => map) |
ls = LUSolver(), mass = :lumped, normalize = L1Mean(), volume = ExactVolume(), Δt = :auto (0.2 with an interface map, 0.4 without), void_weight = 1e-3, lagrangian = AugmentedLagrangian(), phi_bc = :neumann | ReactionDiffusion | the keyword of the same name; solve = (A, b, x, ctx, stale) -> x for any other solver; diffusion = (φ, v) -> ∫(…)dΩ |
max_step = :auto (0.02 of ` | D | with an interface map),tol = 1e-4(of |
maps Identity, HelmholtzFilter, TanhProjection, CellMean | PhysicalFields, single_field_design | PointwiseMap(f, df; parameters) |
continued objects TanhProjection (β), OC (move) | Continuation | any Parameter read by the user's forms or maps |
monitor Grey | solve!(…; monitors) | any object with monitor_value(m) |
initial = true, history = true, name = "optimization" | OptPostProcessor | the keyword of the same name |
format = :vtu, precision = Float64, compress = false, async = Threads.nthreads() > 1 | OptPostProcessor (writers of write_step) | the keyword of the same name; write_step(post, w::HyperShape.FieldWriter, …) with a writer of your own; or createvtk in the driver |
The solver is always the one of the user's model. For example, with PETSc (GridapPETSc) build the model with ls = PETScLinearSolver(); the default solve then calls it. Any other solve (a preconditioner rebuilt only every few iterations, a warm start, a matrix-free solver) goes in the user's own solve function.