Examples and tutorials » Shape optimization examples » Shape optimization of a cantilever

Compute and inspect a boundary-variation compliance descent.

A cantilever carries a prescribed load while part of its boundary is clamped. The design task is to redistribute its material boundary so that elastic compliance and material area have a smaller weighted sum. This tutorial follows the state solve, regularized descent and mesh update in SimpleCantilever2D.

Objective and design boundary

The elastic body occupies a planar domain $\Omega$ . Its boundary has a clamped part $\Gamma_D$ , a loaded part $\Gamma_N$ and an optimizable traction-free part $\Gamma_0$ . The support and loaded boundary are held fixed during the design update. The objective is

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

A fixed positive weight $\ell=5$ penalizes material area. The program performs 50 boundary-displacement updates with remeshing. The measured history describes those iterations; an optimality or volume-constraint stopping criterion would require additional controls.

Compliance measures the work done by the applied load. Testing the elastic state equation with its displacement gives $C(\Omega)=\int_{\Gamma_N}f\cdot u\,ds$ ; the stored elastic strain energy is $C/2$ . A smaller compliance means a stiffer response for this fixed load. The area term assigns a cost to retaining material, so both contributions must be inspected when interpreting a decrease in $J$ .

State and design fields

QuantityC++ storageRole
$u$ u.getSolution()Elastic displacement under the current load
$\theta$ g.getSolution(), also referenced by dJRegularized direction for changing the design geometry
$\Omega$ OmegaCurrent mesh on which both fields are constructed

The elastic displacement describes the loaded body's response. The design direction changes the domain on which the next elastic state is solved.

Input and parameters

Modules

The program uses local vector-valued P1 spaces, elasticity assembly, sparse direct solves, MMG remeshing and XDMF output.

Physical and numerical data

ParameterValueRole
$\lambda$ 0.5769First Lamé coefficient
$\mu$ 0.3846Shear modulus
$\ell$ 5Area penalty
$h_{\max}$ 0.1MMG upper size setting
$h_{\min}$ 0.01MMG lower size setting and displacement scale
$\alpha$ 0.4Gradient regularization coefficient

Supply the mesh

Hydrate the repository's Git LFS resources, build SimpleCantilever2D, and pass SimpleCantilever2D.mfem.mesh as the executable's input argument. Run from a scratch directory so the exported fields and meshes are kept separate from the sources. The mesh carries boundary labels one, two and three for the free, clamped and loaded boundary parts respectively.

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

git lfs pull --include="resources/examples/ShapeOptimization/SimpleCantilever2D.mfem.mesh"
cmake --build build --target SimpleCantilever2D
mkdir -p results/simple-cantilever
cd results/simple-cantilever
../../build/examples/ShapeOptimization/SimpleCantilever2D \
  ../../resources/examples/ShapeOptimization/SimpleCantilever2D.mfem.mesh

Check the input's boundary attributes when substituting another mesh:

Facet attributeBoundaryData
1 $\Gamma_0$ Traction-free design boundary
2 $\Gamma_D$ Zero elastic displacement and zero design motion
3 $\Gamma_N$ Downward unit traction and zero design motion

One iteration

Solve the elastic state

The displacement satisfies the small-strain elasticity weak form with zero displacement on the clamp and a downward unit traction on the loaded boundary. The program checks sparse factorization and solution status.

With $\varepsilon(u)=\tfrac12(\nabla u+\nabla u^T)$ and $\sigma(u)=2\mu\varepsilon(u)+\lambda\operatorname{tr}\varepsilon(u)I$ , the weak problem is

\[ \int_\Omega\sigma(u):\varepsilon(v)\,dx =\int_{\Gamma_N}f\cdot v\,ds, \qquad f=(0,-1), \]

for test fields vanishing on $\Gamma_D$ . The absence of a traction term on $\Gamma_0$ imposes its natural zero-traction condition.

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

Compute a regularized descent

Let $n$ be the outward material normal and $W=\sigma(u):\varepsilon(u)$ . For smooth free-boundary variations with fixed support and load boundary, the continuous shape derivative is

\[ J'(\Omega)[\xi]=\int_{\Gamma_0}(\ell-W)\,\xi\cdot n\,ds. \]

Compliance is self-adjoint, so the elastic state also supplies the adjoint information needed for this derivative. The program therefore uses the state strain in the boundary density without a separate adjoint solve. Its negative provides a scalar boundary load $W-\ell$ . Regions with large $W$ relative to $\ell$ favor an outward design motion; the area penalty favors material removal. The regularization solve couples these boundary tendencies into a smooth vector field throughout the body.

\[ \alpha\int_\Omega\nabla\theta:\nabla w\,dx +\int_\Omega\theta\cdot w\,dx =\int_{\Gamma_0}(W-\ell)\,n\cdot w\,ds. \]

Both $\theta$ and $w$ vanish on the clamped and loaded parts. The boundary derivative is assembled by BoundaryIntegral, and g is the trial function for $\theta$ .

    // Hilbert extension-regularization procedure
    TrialFunction g(vh);
    TestFunction  w(vh);

    auto e = 0.5 * (Jacobian(u.getSolution()) + Jacobian(u.getSolution()).T());
    auto Ae = 2.0 * mu * e + lambda * Trace(e) * IdentityMatrix(d);

    Problem hilbert(g, w);
    hilbert = Integral(alpha * Jacobian(g), Jacobian(w))
            + Integral(g, w)
            - BoundaryIntegral(Dot(Ae, e) - ell, Dot(BoundaryNormal(Omega), w)).over(Gamma0)
            + DirichletBC(g, VectorFunction{0, 0}).on({GammaD, GammaN});
    Solver::SparseLU gradientSolver(hilbert);
    gradientSolver.solve();
    if (!gradientSolver.success())
      return EXIT_FAILURE;

The gradient term in this program has coefficient $\alpha$ ; the corresponding smoothing length is $\sqrt{\alpha}$ . This convention is explicit in the assembled expression.

For the continuous derivative and an exact regularization solve, testing with $w=\theta$ yields

\[ J'(\Omega)[\theta]= -\alpha\|\nabla\theta\|_{L^2(\Omega)}^2 -\|\theta\|_{L^2(\Omega)}^2\leq0. \]

This is a first-order descent relation at the current domain. The finite element boundary evaluation, finite motion and subsequent remeshing enter the actual recorded objective history.

Normalize the displacement

The field is scaled so its sampled maximum norm gives a displacement scale $h_{\min}$ . Non-finite norms fail the run; a zero norm ends the updates.

With $m$ the sampled maximum of $|\theta|$ , the displacement applied to the mesh is $\delta x=(h_{\min}/m)\theta$ . This makes the movement scale explicit even when the derivative magnitude changes during optimization. The positive scaling retains the direction of the regularized field. The chosen $h_{\min}$ controls both the movement scale and MMG's lower size setting in this example.

Move and remesh

    // Make the displacement
    GridFunction norm(sh);
    norm = Frobenius(dJ);
    const Real maximum = norm.max();
    if (!std::isfinite(maximum))
      return EXIT_FAILURE;
    if (maximum == 0)
      break;
    g.getSolution() *= hmin / maximum;
    Omega.displace(g.getSolution());

    // Refine the mesh using MMG
    MMG::Optimizer().setHMax(hmax).setHMin(hmin).optimize(Omega);

The fixed step is a demonstration policy. Inspect the recorded objective history when changing meshes, loads or material parameters; an objective- controlled line search can be introduced for a specified optimization policy. New spaces and problems are constructed on each remeshed domain.

Omega.displace() first moves the current mesh. MMG then changes the mesh as needed to meet its size and quality controls. The following iteration rebuilds the finite element spaces and recomputes the elastic state on that domain. The recorded sequence consists of a state solve, a descent solve, objective/output, displacement and remeshing.

Image
First computed elastic state. The mesh gives the design geometry; color shows the elastic displacement magnitude.
Image
Computed descent at the first state. Color shows its magnitude divided by the sampled maximum; equal-length arrows show direction.
Image
First design displacement, before MMG. The navy outline marks the previous boundary; the displayed mesh uses the actual movement scale 0.01.
Image
Mesh after MMG, as used by the second elastic state. Remeshing can change vertices and connectivity.

Inspect the computed run

Image
Elastic state on the initial material mesh.
Image
Elastic state on the last recorded material mesh, using the same color scale.
Image
Objective values recorded before each boundary update.

The checked 50-state run reduced the objective from approximately 3.56181 to 2.28789. Every recorded increment decreased the objective in this run. Both the elastic state and regularization solve succeeded at every state.

The mesh coordinates in the comparison depict the evolving design domain; color encodes the elastic displacement magnitude. Inspect the load path between the loaded boundary and the clamp together with the compliance and area columns. A reduced weighted objective can combine increased compliance with reduced material area, depending on their relative changes.

SimpleCantilever.csv records compliance, area and their weighted sum. SimpleCantilever.xdmf records the transient mesh, elastic displacement and unscaled regularized descent at the same iteration. Open the XDMF file in ParaView and select Apply to inspect that history.

| File | Interpretation | | :— | :— | | SimpleCantilever.csv | One row per solved state containing the iteration, compliance, area and $C+\ell|\Omega|$ | | SimpleCantilever.xdmf | Mesh, elastic displacement and unscaled descent for the same recorded states | | Omega0.mesh | Input geometry saved before the update loop | | Omega.mesh | Geometry after the most recent displacement and remeshing |

The full run records states 0 through 49, each before its geometry update. Omega.mesh after the loop contains the geometry following update 50. Its elastic response would require another state solve. The measured monotone history applies to the recorded run; an application can add objective-based step acceptance and a stopping test appropriate to its accuracy requirements.

The intermediate figures show the first update. They are rendered from the exported fields by visualize_stages.py with --mode simple. The pre-remeshing geometry applies the exported descent with the same positive normalization and movement scale as the C++ update.

Complete source

SimpleCantilever2D.cpp contains the input checks, solves, diagnostics and geometry updates.

Continue