Examples and tutorials » Shape optimization examples » Optimizing a level-set cantilever

Couple elasticity, descent regularization, transport and body-fitted remeshing.

The material boundary in this example is represented by the zero set of a scalar field. Each iteration solves the elastic body, extends a descent direction through its surrounding domain, transports the field and reconstructs a fitted mesh. This tutorial explains how those operations exchange geometry and fields in LevelSetCantilever2D.

Domain representation

A background domain $D$ contains material $\Omega$ and exterior cells. Cell labels one and two identify those regions, while facet label four identifies their interface. The signed-distance construction assigns negative values in the material.

\[ \Omega=\{x:\phi(x)<0\},\qquad\Gamma=\{x:\phi(x)=0\}. \]

At each iteration, the level set is transported and MMG reconstructs a body-fitted interface. Its connectivity and entity numbering can change.

The objective is compliance plus material-area penalty.

\[ J(\Omega)=\int_\Omega\sigma(u):\varepsilon(u)\,dx+\ell|\Omega|. \]

The elastic state has a fixed clamp and a downward traction on the loaded boundary. The optimizable material interface is traction-free.

Compliance measures load work, and the positive area penalty assigns a cost to retaining material. With the load fixed, the objective balances stiffness against material usage. The boundary-deformation tutorial develops the same objective and free-boundary derivative using an explicitly displaced material mesh. The examples use different initial domains, area weights and update scales; comparisons between their numerical histories require matching those choices.

Two meshes and their fields

ObjectC++ storagePurpose
Background $D_h$ thContains both material and exterior cells; carries descent and transport
Material $\Omega_h$ trimmedExtracted cell submesh on which elasticity is solved
Elastic displacement $u_h$ u.getSolution()Response of the current material body to its load
Design direction $\theta_h$ g.getSolution(), aliased by dJRegularized motion extended across the background
Signed distance and transported fielddist, advect.getSolution()Encode the current and proposed material interface

Cell and facet attributes belong to different entity dimensions. Cell label 2 marks exterior material, while facet label 2 marks the clamp. Their equal integer values do not identify the same geometric entities.

Input and controls

Modules

The program combines local elasticity, Distance::Eikonal, Advection::Lagrangian, MMG and XDMF output. These operations each act on the mesh and finite element spaces belonging to the current iteration.

Parameters

The Lamé coefficients are $\lambda=0.5769$ and $\mu=0.3846$ . The area penalty is $\ell=0.4$ , the regularization length is $\alpha=0.1$ , and the initial MMG size bounds are 0.005 and 0.05. A normalized descent field is transported with fixed step 0.0225. The default budget is 300 updates.

The executable takes the hydrated resource LevelSetCantilever2D.mfem.mesh as its first argument. A second positive integer optionally selects the iteration budget. Run in a scratch directory; the program creates out/ for its history files.

Build and run the example from a configured checkout with these commands.

git lfs pull --include="resources/examples/ShapeOptimization/LevelSetCantilever2D.mfem.mesh"
cmake --build build --target LevelSetCantilever2D
mkdir -p results/level-set-cantilever
cd results/level-set-cantilever
../../build/examples/ShapeOptimization/LevelSetCantilever2D \
  ../../resources/examples/ShapeOptimization/LevelSetCantilever2D.mfem.mesh 300

Replacing the final argument with a smaller positive integer selects a shorter execution check. The 300-state measurements below use the full budget. A replacement input mesh must carry the material labels above, facet label 4 on the design interface, label 2 on the clamp and label 3 on the loaded boundary.

One iteration

1. Prepare the current geometry

MMG quality optimization prepares the body-fitted mesh. Facet-to-cell incidence is then recomputed for boundary and interface operations. Remeshing failures reduce the requested sizes and retry, with a cap of eight consecutive failures.

2. Extract the elastic body

th.trim(exterior) constructs the material submesh. New spaces on that submesh describe the state, while full-background spaces describe the descent and transport fields.

This separation gives the state its physical material domain while retaining a field in the surrounding cells through which the interface can move. The state bilinear form is assembled only on the extracted material body.

3. Solve elasticity

The state displacement is zero on the clamp and is loaded by $f=(0,-1)$ . On the material domain, the weak equation is

\[ \int_{\Omega_h}\sigma(u_h):\varepsilon(v_h)\,dx =\int_{\Gamma_N}f\cdot v_h\,ds, \]

with $\varepsilon(u)=\operatorname{sym}\nabla u$ and $\sigma(u)=2\mu\varepsilon(u)+\lambda\operatorname{tr}\varepsilon(u)I$ . Test fields vanish on the clamp. The free interface has the natural zero-traction condition.

    // Elasticity equation
    Problem elasticity(u, v);
    elasticity = LinearElasticityIntegral(u, v)(lambda, mu)
               - BoundaryIntegral(f, v).over(GammaN)
               + DirichletBC(u, VectorFunction{0, 0}).on(GammaD);
    Solver::CG stateSolver(elasticity);
    stateSolver.solve();
    if (!stateSolver.success())
      return EXIT_FAILURE;

The conjugate-gradient result is checked before the displacement is used.

4. Extend a regularized descent

The displacement derivative and interface normal are evaluated from the material side. For fixed supports and load boundary, the negative shape derivative supplies the density $\sigma(u):\varepsilon(u)-\ell$ . The clamped and loaded boundary parts receive zero two-component velocity.

Write $W=\sigma(u_h):\varepsilon(u_h)$ and take $n$ outward from the material. The free-boundary derivative density is $\ell-W$ , so its negative is used on the right-hand side of

\[ \alpha^2\int_{D_h}\nabla\theta_h:\nabla w_h\,dx +\int_{D_h}\theta_h\cdot w_h\,dx =\int_{\Gamma_h}(W-\ell)n\cdot w_h\,ds. \]

The full-background solve spreads the interface load into neighboring cells and regularizes its variation. Its coefficient is $\alpha^2$ , giving the smoothing length $\alpha$ in this program. The vector $\theta_h$ then supplies the transport velocity.

jac.traceOf(interior) selects the material-side displacement derivative on an internal facet; n.traceOf(interior) selects the corresponding outward material normal. These choices orient material growth and removal consistently. FaceIntegral assembles the load on marked internal facets.

    auto jac = Jacobian(u.getSolution());
    jac.traceOf(interior);
    auto e = 0.5 * (jac + jac.T());
    auto Ae = 2.0 * mu * e + lambda * Trace(e) * IdentityMatrix(d);
    auto n = FaceNormal(th);
    n.traceOf(interior);

    // Hilbert extension-regularization procedure
    TrialFunction g(vh);
    TestFunction w(vh);
    Problem hilbert(g, w);
    hilbert = Integral(alpha * alpha * Jacobian(g), Jacobian(w)) + Integral(g, w) -
      FaceIntegral(Dot(Ae, e) - ell, Dot(n, w)).over(Gamma) +
      DirichletBC(g, VectorFunction{0, 0}).on(GammaD, GammaN);
    Solver::CG gradientSolver(hilbert);
    gradientSolver.solve();
    if (!gradientSolver.success())
      return EXIT_FAILURE;

5. Construct and transport the distance

The Eikonal step reconstructs distance from the tagged interface, then sign() makes the material side negative. The descent is normalized before transport. Non-finite norms fail the run; a zero norm ends the updates.

Distance is reconstructed from the current fitted interface at every iteration. Its sign identifies material and exterior, and its approximately unit gradient near the interface gives the scalar field a geometric scale. The normalized velocity is $V_h=\theta_h/\max|\theta_h|$ , using the program's nodal norm sampling. The transport problem is

\[ \partial_s\phi+V_h\cdot\nabla\phi=0, \qquad \phi(\cdot,0)=d_h, \]

where $d_h$ is the signed-distance approximation. The parameter $s$ advances the design; each elastic state is static. Advection::Lagrangian advances this field along characteristics.

The fixed increment $\Delta s=0.0225$ sets a nominal interface-motion scale after velocity normalization. It retains its initial value when a meshing retry reduces the requested mesh size. Step acceptance therefore needs to be assessed together with the current mesh and objective history.

    GridFunction dist(sh);
    Distance::Eikonal(dist).setInterior(interior)
                           .setInterface(Gamma)
                           .solve()
                           .sign();

    th.save("Distance.mesh", IO::FileFormat::MFEM);
    dist.save("Distance.gf", IO::FileFormat::MFEM);

    // Advect the level set function
    Alert::Info() << "   | Advecting the distance function." << Alert::Raise;
    GridFunction norm(sh);
    norm = Frobenius(dJ);
    const Real maximum = norm.max();
    if (!std::isfinite(maximum))
      return EXIT_FAILURE;
    if (maximum == 0)
      break;
    dJ /= maximum;

    TrialFunction advect(sh);
    TestFunction test(sh);

    Advection::Lagrangian(advect, test, dist, dJ).step(dt);

6. Recover the interface

The transported field supplies the zero level set for MMG reconstruction.

      th = MMG::LevelSetDiscretizer().split(interior, {interior, exterior})
                                     .split(exterior, {interior, exterior})
                                     .setRMC(1e-6)
                                     .setHMax(hmax)
                                     .setHMin(hmin)
                                     .setHausdorff(hausd)
                                     .setAngleDetection(false)
                                     .setBoundaryReference(Gamma)
                                     .setBaseReferences(GammaD)
                                     .discretize(advect.getSolution());

The next iteration constructs fresh spaces and problems on that new mesh. The MMG behavior guide describes preservation of required entities and material labels at level-set cuts.

Both existing cell references are configured to split into material label 1 and exterior label 2 according to the transported sign. The new interface receives facet label 4. MMG can insert, remove and renumber mesh entities while constructing this fitted interface. The following iteration extracts its material body and recomputes the state, descent and distance fields.

The output snapshot is written just before this reconstruction. It combines the current state with the proposed transported field, so the next frame shows the recovered geometry after its preparation step.

Image
Computed normalized descent on the first background mesh. Arrows show direction; the navy contour marks the current material interface.
Image
Current signed-distance approximation at the first state. The navy zero contour marks the material boundary; colors saturate outside the interval from -0.05 to 0.05.
Image
Transported field after the first design step. Navy marks the current zero contour and cyan the proposed zero contour; the same clipped color interval is used.
Image
Material mesh used by the second elastic state, after interface reconstruction and preparation. Edges show the fitted triangulation.

Inspect the numerical history

Image
Elastic state on the initial material mesh.
Image
Elastic state on the last recorded material mesh, using the same color scale.

The checked 300-state run reduced the objective from approximately 1.19842 to 0.942951. Its history contains 138 increasing steps, consistent with a fixed-step policy that accepts updates without an objective-decrease test. This run establishes successful execution of the specified update sequence. Assessing stationarity requires an additional stopping criterion.

An independent geometry check found positive signed Jacobians in all 600 exported domain/state grids. Its minimum triangle shape measure was approximately $8.83\times10^{-7}$ at iteration 26. A stage-by-stage probe traced this sliver to the preceding level-set reconstruction. The minimum was approximately $8.39\times10^{-7}$ after that cut and remained approximately $8.83\times10^{-7}$ after quality optimization. Monitor shape quality as well as Jacobian signs when using this workflow. Metric-driven cleanup or step rejection requires its own geometric acceptance policy and validation.

A positive Jacobian records orientation and nonzero cell area. The normalized triangle shape measure

\[ q_K=\frac{4\sqrt3\,|K|} {\sum_{e\subset\partial K}|e|^2} \]

equals one for an equilateral triangle and approaches zero for a sliver. The recorded small value identifies a cell that remains positive in area while having very poor shape. Such cells can affect conditioning and field gradients, so geometry checks should accompany an objective plot.

obj.txt records the objective at solved states. The transient XDMF file out/ShapeOptimization.xdmf contains a full-background domain grid with descent, distance and transported level set, and a material state grid with displacement. Open the file in ParaView, select Apply and choose the grid and field to inspect.

OutputInterpretation
obj.txtWeighted objective at each recorded solved state
domain blockBackground geometry with normalized descent dJ, current distance dist and transported field advect
state blockMaterial submesh with elastic displacement u
out/Omega.<i>.meshBackground mesh after the corresponding interface reconstruction

In ParaView, select Extract Block to compare domain and state. Inspect the zero contour of advect on a current frame, then compare it with the next frame's material boundary. On state, color by the magnitude of u and select Surface With Edges to inspect the load path and cell shapes. The displayed mesh represents the design geometry and the colors represent its elastic response.

The complete run records state indices 0 through 299. The final reconstruction is saved as out/Omega.300.mesh; its elastic state would require another iteration. The observed objective reduction, 138 increasing steps and local sliver formation describe separate properties of this run.

The intermediate-stage figures use recorded states 0 and 1 from the same history. visualize_stages.py --mode levelset renders the exported dist, dJ, advect and next material mesh.

Fixed-step transport and remeshing define this demonstration. Objective histories, interface geometry and solver status should be inspected when choosing a step or assessing stationarity.

Complete source

Build LevelSetCantilever2D. The source ShapeOptimization/LevelSetCantilever2D.cpp includes the command-line checks, bounded remeshing retries, solve checks and output handling.

Continue