Programming Homework 02

Submission Deadline: 20.05.2026 - 23:55
  • Your homework solution has to be handed in as a group solution via Moodle.
  • Your notebooks must run without errors in our environment on the RWTH-Cluster. See here for more information on how to get started.
Participant list

Please add your names and student ID (Matrikelnummer) here:

  1. Name, ID
  2. Name, ID
  3. Name, ID
  4. Name, ID

Learning goals

  • Hooke’s law and its weak formulation in 2D plane strain
  • FEM implementation of static linear elasticity in FenicsX
  • Validating an FE implementation against an analytical reference (Rod Elongation)
  • Connecting the full 2D elasticity solution to the dimensionally reduced Euler-Bernoulli beam theory (Cantilever Beam Bending)
  • Understand generalised eigenvalue problems for free vibration: natural frequencies and mode shapes

Make sure that you update the library folder in your CMM directory. Download link: library.tar.gz
Make sure that you update your dolfinx_latest.sif container image.

You can use the following command on the RWTH cluster/Linux:

    wget https://mbd.pages.rwth-aachen.de/courses/cmm/content/exercises/notebooks/homework02_new.out.ipynb
    rm -rf library
    wget https://mbd.pages.rwth-aachen.de/courses/cmm/content/exercises/notebooks/library.tar.gz
    tar -xvzf library.tar.gz
    rm library.tar.gz
    rm dolfinx_latest.sif
    apptainer pull oras://registry.git.rwth-aachen.de/mbd/courses/containers/dolfinx:latest

Acknowledgements

This notebook, in particular task 2 and task 3, are inspired by the work of

@software{bleyer2024comet,
  author       = {Bleyer, Jeremy},
  title        = {{Numerical tours of Computational Mechanics with 
                   FEniCSx}},
  month        = jan,
  year         = 2024,
  publisher    = {Zenodo},
  version      = {v0.1},
  doi          = {10.5281/zenodo.10470942},
  url          = {https://doi.org/10.5281/zenodo.10470942}
}

TODOs:

Linear Elasticity Problem Settting

Throughout this notebook we work in 2D plane strain on a rectangular domain \(\Omega = [0, L] \times [0, h]\). Plane strain corresponds to a material slab that is uniform and constrained in the third (out-of-plane) direction. The relevant constitutive law is Hooke’s law

\[ \sigma = \lambda\,\mathrm{tr}(D)\,\mathbf I_{2\times 2} + 2\mu D, \qquad D = \tfrac{1}{2}\bigl(\nabla \mathbf w + (\nabla \mathbf w)^T\bigr), \]

with the Lamé constants

\[ \lambda = \frac{E\,\nu}{(1+\nu)(1-2\nu)}, \qquad \mu = \frac{E}{2(1+\nu)}. \]

We use steel-like values throughout:

  • \(E = 210\) GPa, \(\nu = 0.3\)
  • \(\rho = 7850\ \mathrm{kg}/\mathrm{m}^3\)
  • \(\lambda \approx 121\) GPa, \(\mu \approx 80.8\) GPa

Three exercises follow. In P1 we validate the implementation by recovering \(E\) and \(\nu\) from a uniaxial test. In P2, we look at bending of a cantilever beam, and continue with a free-vibration eigenmode analysis of the same cantilever beam geometry in P3.

# Material parameters (steel)
E   = 210e9
nu  = 0.3
rho = 7850.0
lambda_ = (E*nu) / ((1 + nu)*(1 - 2*nu))
mu      = E / (2*(1 + nu))
print(f'E = {E:.3e} Pa,  nu = {nu},  rho = {rho} kg/m^3')
print(f'lambda = {lambda_:.3e} Pa,  mu = {mu:.3e} Pa')
E = 2.100e+11 Pa,  nu = 0.3,  rho = 7850.0 kg/m^3
lambda = 1.212e+11 Pa,  mu = 8.077e+10 Pa

Let’s go!

import os
from mpi4py import MPI
import numpy as np
from scipy.optimize import brentq

import dolfinx
import basix
import ufl
from dolfinx import fem, mesh
from dolfinx.fem import petsc
from petsc4py import PETSc

from slepc4py import SLEPc

import pyvista
from IPython.display import Image, display

import library.helpers
import library.plot
import library.tests

library.helpers.setup_notebook_paths()
output_dir = library.helpers.make_unique_dir('hw02')

if os.getenv('DEVCONTAINER'):
    pyvista.start_xvfb()

P1 — Rod Elongation

Before we trust any downstream FE result, we run a calibration test: apply a known uniaxial stress to a 2D slab and use the resulting strains to recover \(E\) and \(\nu\) from the numerical solution. If the implementation is correct, the recovered values must match the inputs.

Setup

Take a thin rectangle \([0,\ell]\times[0,s]\) with \(\ell = 0.10\ \mathrm m\) and \(s = 0.01\ \mathrm m\). Apply a tensile traction \(\mathbf t = (P/(s\cdot 1\ \mathrm m),\,0)\) to the right edge (the \(1\ \mathrm m\) accounts for the unit out-of-plane thickness in plane strain). Constrain the left edge in \(x\) (roller), and pin the bottom-left corner in \(y\) to remove the rigid-body translation.

For \(P = 10^7\) N (per unit out-of-plane metre) the imposed stress is \(\sigma_{xx} = P / (s \cdot 1\,\mathrm m) = 10^9\ \mathrm{Pa} = 1\) GPa, which gives a strain \(\sigma_{xx}/E \approx 4.76\cdot 10^{-3}\) — well within the linear regime, and large enough that a small visualisation scale already makes the deformation visible.

Strong problem

Let \(\Omega = [0,\ell]\times[0,s]\) with boundary partitioned into \(\Gamma_L\) (left, \(x=0\)), \(\Gamma_R\) (right, \(x=\ell\)), \(\Gamma_T\cup\Gamma_B\) (top/bottom, traction-free), and the corner point \(\mathbf x_c = (0,0)\). The strong problem is:

\[ \left\{\begin{aligned} -\nabla\cdot\sigma(\mathbf w) &= \mathbf 0 && \text{in } \Omega, \\ \sigma(\mathbf w)\,\mathbf n &= \mathbf t = (\sigma_{xx},0) && \text{on } \Gamma_R, \\ \sigma(\mathbf w)\,\mathbf n &= \mathbf 0 && \text{on } \Gamma_T \cup \Gamma_B, \\ w_x &= 0 && \text{on } \Gamma_L, \\ w_y(\mathbf x_c) &= 0, \end{aligned}\right. \]

with the constitutive law \(\sigma(\mathbf w) = \lambda\,\mathrm{tr}(D(\mathbf w))\,\mathbf I + 2\mu\,D(\mathbf w)\) and \(D(\mathbf w) = \tfrac{1}{2}(\nabla\mathbf w + \nabla\mathbf w^{\!T})\).

Weak problem

Define the (Ritz–Galerkin) trial-and-test space

\[ V = \bigl\{\,\mathbf w \in [H^1(\Omega)]^2 \;\big|\; w_x = 0 \text{ on } \Gamma_L,\ w_y(\mathbf x_c) = 0\,\bigr\}. \]

Multiplying the momentum balance by \(\mathbf v \in V\), integrating over \(\Omega\), applying the divergence theorem and inserting the Neumann data on \(\Gamma_R\) (with \(\Gamma_T\cup\Gamma_B\) traction-free) yields:

Find \(\mathbf w \in V\) such that \[ \int_\Omega \sigma(\mathbf w):\nabla\mathbf v \,dx \;=\; \int_{\Gamma_R} \mathbf t\cdot\mathbf v \,ds \] for all \(\mathbf v \in V\).

From the 3D rod analytic to a 2D plane-strain simulation

In §6.7.1 we derived the 3D rod result by imposing \(\sigma_{xx}\ne 0\) with all other stress components zero — in particular \(\sigma_{yy} = \sigma_{zz} = 0\) (the rod is laterally free). Hooke’s law inverted gives

\[ D_{11} = \frac{1}{E}\,\sigma_{xx}, \qquad D_{22} = D_{33} = -\frac{\nu}{E}\,\sigma_{xx}. \]

Our 2D simulation is not a 3D rod — it is a plane-strain slice. Plane strain is the limit of an infinitely-long out-of-plane geometry where every section deforms identically, so \(D_{33} = 0\) is enforced kinematically. With \(D_{33}=0\) the third row of Hooke’s law no longer says \(\sigma_{zz}=0\); instead it says

\[ \sigma_{zz} = \nu\,(\sigma_{xx}+\sigma_{yy}), \]

i.e. the rod is now squeezed by a non-zero \(\sigma_{zz}\) that the constraint generates. Substituting this back, the in-plane Hooke’s law (with the free-surface condition \(\sigma_{yy}=0\) from the unloaded top/bottom) becomes

\[ D_{11} = \frac{1-\nu^2}{E}\,\sigma_{xx}, \qquad D_{22} = -\frac{\nu(1+\nu)}{E}\,\sigma_{xx}. \]

So if we blindly apply the 3D rod formulas \(D_{11}=\sigma_{xx}/E_\text{meas}\) and \(D_{22}=-\nu_\text{meas}\sigma_{xx}/E_\text{meas}\) to the in-plane numbers, we do not recover \(E\) and \(\nu\) — we recover the apparent plane-strain constants

\[ E^* = \frac{E}{1-\nu^2}, \qquad \nu^* = \frac{\nu}{1-\nu}. \]

These two quantities are not new physics; they are exactly the bookkeeping needed to map the 3D rod relations onto a plane-strain measurement. (The same \(1/(1-\nu^2)\) factor reappears in the plate-bending stiffness \(K_b = E h^3/[12(1-\nu^2)]\) in §6.11, but via a different clamping: a Kirchhoff plate is in plane stress through the thickness, and the factor arises from the lateral kinematic constraint \(\varepsilon_{yy} = 0\) blocking anticlastic curvature. Same algebra, different transverse direction clamped.) In the limit \(\nu\to 0\) the constraint is inactive and \(E^*\to E\), \(\nu^*\to\nu\).

The conversion back is one-to-one:

\[ \nu = \frac{\nu^*}{1+\nu^*}, \qquad E = E^*(1-\nu^2). \]

Analysis Procedure

  1. Solve the static plane-strain problem.
  2. Read off \(D_{11}\) from the elongation \(\Delta\ell/\ell\) and \(D_{22}\) from the contraction \(\Delta s/s\).
  3. Compute \(E^*_\text{measured}\) and \(\nu^*_\text{measured}\).
  4. Convert back to physical \(E,\nu\) via \(\nu = \nu^*/(1+\nu^*)\) and \(E = E^*(1-\nu^2)\).
  5. Compare to the inputs.

1. Mesh and computational domain

# Domain and function spaces (2D plane strain)
def generate_domain(P0, P1, nx, ny):
    return mesh.create_rectangle(
        MPI.COMM_WORLD,
        [np.array(P0, dtype=np.float64), np.array(P1, dtype=np.float64)],
        [nx, ny],
        cell_type=mesh.CellType.quadrilateral,
    )
# P1 geometry: short slab
bb_rod = [[0.0, 0.0], [0.10, 0.01]]
domain_rod = generate_domain(bb_rod[0], bb_rod[1], nx=40, ny=4)
print('rod:', domain_rod.geometry.x.shape[0], 'nodes')
rod: 205 nodes

2. Setup our Continuous Galerkin (Finite) elements


def generate_functionspaces(domain):
    elem_CG2 = basix.ufl.element('CG', domain.topology.cell_name(), degree=2,
                                 shape=(domain.geometry.dim,))
    space_CG2 = fem.functionspace(domain, elem_CG2)

    elem_CG1 = basix.ufl.element('CG', domain.topology.cell_name(), degree=1,
                                 shape=(domain.geometry.dim,))
    space_CG1 = fem.functionspace(domain, elem_CG1)
    return space_CG2, space_CG1



space_CG2_rod, space_CG1_rod = generate_functionspaces(domain_rod)

3. The weak form in UFL: From Math to Code

Task 1

STUDENT TODO

Implement the weak form for static plane-strain elasticity in weak_form_uniaxial. Build the bilinear and linear forms using the small-strain tensor \(D(\mathbf{w}) = \tfrac{1}{2}(\nabla\mathbf{w} + \nabla\mathbf{w}^T)\), the Cauchy stress \(\sigma = \lambda\,\mathrm{tr}(D)\,\mathbf{I} + 2\mu D\), and the traction integral on the right edge \(\Gamma_R\).

def weak_form_uniaxial(V, domain, bb, P_per_metre=1e4):
    '''Static plane-strain weak form for a slab under uniaxial right-edge
    traction. Left edge is a vertical roller; bottom-left corner is pinned
    in y to remove rigid-body translation.'''
    u = ufl.TrialFunction(V)
    v = ufl.TestFunction(V)

    # Define ds on the different facets of the boundary (2D)
    # [ds(1)=left, ds(2)=right, ds(3)=bottom, ds(4)=top]
    facet_tags = library.helpers.generate_facets_tags(domain, bb[0], bb[1])
    ds = ufl.Measure('ds', domain=domain, subdomain_data=facet_tags)
    dx = ufl.dx

    ### TODO #############################################
    # Build the weak form for static plane-strain elasticity:
    #   - small-strain tensor D(w) = 0.5*(grad(w) + grad(w).T)
    #   - stress sigma = lambda_ * tr(D(u)) * I + 2*mu*D(u),  with I = ufl.Identity(2)
    #   - body force is zero in this section
    #   - traction t = (P_per_metre/length_y, 0) acts on the right edge ds(2)
    #     where length_y = bb[1][1] - bb[0][1]
    I = ufl.Identity(2)
    weak_form = 0
    ######################################################

    lhs = ufl.lhs(weak_form)
    rhs = ufl.rhs(weak_form)
    return lhs, rhs

4. Boundary Conditions

def boundary_conditions_rod(V, domain, bb):
    # Boundary conditions:
    # (a) left edge: u_x = 0 (vertical roller)
    def left_marker(x):
        return np.isclose(x[0], bb[0][0])
    V_x = V.sub(0)
    Vx_collapsed, _ = V_x.collapse()
    fixed_x = fem.Function(Vx_collapsed)
    facets_left = mesh.locate_entities_boundary(domain, domain.topology.dim - 1, left_marker)
    dofs_left_x = fem.locate_dofs_topological((V_x, Vx_collapsed),
                                                domain.topology.dim - 1, facets_left)
    bc_left = fem.dirichletbc(fixed_x, dofs_left_x, V_x)

    # (b) bottom-left corner: u_y = 0 (anchor)
    def corner_marker(x):
        return np.isclose(x[0], bb[0][0]) & np.isclose(x[1], bb[0][1])
    V_y = V.sub(1)
    Vy_collapsed, _ = V_y.collapse()
    fixed_y = fem.Function(Vy_collapsed)
    vertices = mesh.locate_entities_boundary(domain, 0, corner_marker)
    dofs_corner_y = fem.locate_dofs_topological((V_y, Vy_collapsed), 0, vertices)
    bc_corner = fem.dirichletbc(fixed_y, dofs_corner_y, V_y)

    return [bc_left, bc_corner]

5. Assemble and solve the linear system

# Solve and recover E, nu
P_per_metre = 1e7   # 10 MN per m of out-of-plane thickness  ->  sigma_xx = 1 GPa
lhs, rhs = weak_form_uniaxial(space_CG2_rod, domain_rod, bb_rod, P_per_metre=P_per_metre)

problem = fem.petsc.LinearProblem(
    lhs, rhs, bcs=boundary_conditions_rod(space_CG2_rod, domain_rod, bb_rod),
    petsc_options={'ksp_type': 'preonly', 'pc_type': 'lu'},
)
u_rod = problem.solve()

6. Visualisation

We exaggerate the displacement (factor \(50\)) and overlay the original (black) and deformed (red) wireframes.

# Project to CG1 to get nodal values
u_rod_cg1 = library.helpers.project(u_rod, space_CG1_rod)
library.plot.deformation_wireframe_2d(u_rod_cg1, 'rod (scale=10)', output_dir,
                                      'wireframe_rod', scale=10)
library.plot.display_image(image_path=os.path.join(output_dir, 'wireframe_rod.png'))
Image saved: hw02/wireframe_rod.png

7. Verification: Check values of \(E\), \(\nu\)


# Recover D_11 and D_22 from the deformation of the corner (\ell, 0) and (0, s)
length_x = bb_rod[1][0] - bb_rod[0][0]
length_y = bb_rod[1][1] - bb_rod[0][1]

coords = space_CG1_rod.tabulate_dof_coordinates()
ux = u_rod_cg1.x.array.reshape(-1, 2)[:, 0]
uy = u_rod_cg1.x.array.reshape(-1, 2)[:, 1]

# D_11: average elongation of the right edge
mask_right = np.isclose(coords[:, 0], length_x)
D11_meas = ux[mask_right].mean() / length_x

# D_22: average contraction of the top edge
mask_top = np.isclose(coords[:, 1], length_y)
D22_meas = uy[mask_top].mean() / length_y

print(f'D_11 measured = {D11_meas:.6e}')
print(f'D_22 measured = {D22_meas:.6e}')

# Apparent plane-strain constants
sigma_xx = P_per_metre / length_y
E_app = sigma_xx / D11_meas
nu_app = -D22_meas / D11_meas
print(f'\nApparent (plane-strain) constants:')
print(f'  E*  measured = {E_app/1e9:.4f} GPa   |   E* expected  = {E/(1-nu**2)/1e9:.4f} GPa')
print(f'  nu* measured = {nu_app:.4f}     |   nu* expected = {nu/(1-nu):.4f}')

# Convert to physical E, nu
nu_recovered = nu_app / (1.0 + nu_app)
E_recovered  = E_app * (1.0 - nu_recovered**2)
print(f'\nPhysical constants recovered from plane-strain measurement:')
print(f'  E  recovered = {E_recovered/1e9:.4f} GPa  |  E  input = {E/1e9:.4f} GPa')
print(f'  nu recovered = {nu_recovered:.6f}      |  nu input = {nu:.6f}')
D_11 measured = 4.333333e-03
D_22 measured = -1.857143e-03

Apparent (plane-strain) constants:
  E*  measured = 230.7692 GPa   |   E* expected  = 230.7692 GPa
  nu* measured = 0.4286     |   nu* expected = 0.4286

Physical constants recovered from plane-strain measurement:
  E  recovered = 210.0000 GPa  |  E  input = 210.0000 GPa
  nu recovered = 0.300000      |  nu input = 0.300000
Verification

The following cell verifies our implementation by checking that the recovered \(E\) and \(\nu\) match the input values to within numerical tolerance. If the weak formulation was correctly implemented, the test passes :)

library.tests.test_hw02_new_rod(E_recovered, nu_recovered, E, nu)
Passed test_hw02_new_rod?: True

P2 — Cantilever Beam Bending

We now solve the cantilever-bending problem in 2D plane strain. A rectangular slab of length \(L = 1\ \mathrm m\) and thickness \(h\) is clamped at \(x=0\) and loaded by a uniform downward traction \(\mathbf t_y\) on the right edge (\(x=L\)), with total line load \(F\) (force per unit out-of-plane metre).

Analytical reference: Euler-Bernoulli

§6.11 of the script reduces the 3D linear elasticity equations to the Euler-Bernoulli beam equation (EB) in the limit \(\eta = h/L \to 0\). For a cantilever clamped at \(x=0\), free at \(x=L\), with a tip point load \(F\), the closed-form deflection is

\[ w_\text{tip}^{EB} = \frac{F\,L^3}{3\, E^*\,I}, \qquad I = \frac{h^3}{12} \quad\text{(per unit out-of-plane metre)}. \]

Two important asymptotic facts:

  • The bending stiffness \(E^*\, I \propto h^3\) — a factor of two thicker beam is eight times stiffer (this is the central geometric scaling of plate/beam reduction).
  • For 2D plane strain the relevant modulus is the apparent \(E^* = E/(1-\nu^2)\), exactly the prefactor of \(K_b\) in §6.11.

We sweep \(h/L \in \{0.01, 0.05, 0.10, 0.20, 0.50\}\) and compare the FE tip deflection to the EB prediction. The agreement should be excellent at \(h/L = 0.01\) and progressively worse as \(h/L\) grows — that growing deviation is the price of the asymptotic reduction.

Strong problem

Let \(\Omega = [0,L]\times[0,h]\) with boundary partitioned into \(\Gamma_C\) (clamped, \(x=0\)), \(\Gamma_R\) (loaded right edge, \(x=L\)), and \(\Gamma_T \cup \Gamma_B\) (traction-free top/bottom). The strong problem is:

\[ \left\{\begin{aligned} -\nabla\cdot\sigma(\mathbf w) &= \mathbf 0 && \text{in } \Omega, \\ \mathbf w &= \mathbf 0 && \text{on } \Gamma_C, \\ \sigma(\mathbf w)\,\mathbf n &= \mathbf t = (0,-F/h) && \text{on } \Gamma_R, \\ \sigma(\mathbf w)\,\mathbf n &= \mathbf 0 && \text{on } \Gamma_T \cup \Gamma_B. \end{aligned}\right. \]

Weak problem

Define the (Ritz–Galerkin) trial-and-test space

\[ V = \bigl\{\,\mathbf w \in [H^1(\Omega)]^2 \;\big|\; \mathbf w = \mathbf 0 \text{ on } \Gamma_C\,\bigr\}. \]

Testing the momentum balance with \(\mathbf v\in V\) and using the Neumann data on \(\Gamma_R\):

Find \(\mathbf w \in V\) such that \[ \int_\Omega \sigma(\mathbf w):\nabla\mathbf v \,dx \;=\; \int_{\Gamma_R} \mathbf t\cdot\mathbf v \,ds \] for all \(\mathbf v \in V\).

3. The weak form and UFL: From Math to Code

Task 2

STUDENT TODO

Implement the weak form for the Cantilever Beam Bending problem in weak_form_cantilever. Build the bilinear and linear forms using the small-strain tensor \(D(\mathbf{w}) = \tfrac{1}{2}(\nabla\mathbf{w} + \nabla\mathbf{w}^T)\), the Cauchy stress \(\sigma = \lambda\,\mathrm{tr}(D)\,\mathbf{I} + 2\mu D\), and the uniform downward traction on the right edge \(\Gamma_R\).

def weak_form_cantilever(V, domain, bb, F_per_metre=10.0):
    '''Static plane-strain cantilever: clamped at x=0, uniform downward
    traction on the right edge equivalent to a tip line-load F (N/m).'''
    u = ufl.TrialFunction(V)
    v = ufl.TestFunction(V)

    facet_tags = library.helpers.generate_facets_tags(domain, bb[0], bb[1])
    ds = ufl.Measure('ds', domain=domain, subdomain_data=facet_tags)
    dx = ufl.dx

    ### TODO #############################################
    # Build the weak form for static plane-strain elasticity:
    #   - small-strain D(w), stress sigma (use ufl.Identity(2))
    #   - no body force
    #   - the right-edge traction is t = (0, -F_per_metre/h_y) so that the
    #     total downward line-load on the right edge equals F_per_metre N/m
    #   - the traction acts on ds(2) (the right edge marker)
    I = ufl.Identity(2)
    weak_form = 0
    ######################################################

    lhs = ufl.lhs(weak_form)
    rhs = ufl.rhs(weak_form)

    return lhs, rhs

4. Boundary Conditions

def boundary_conditions_cantilever(V, domain, bb):
    # Clamp left edge: u_x = u_y = 0
    def fixed_marker(x):
        return np.isclose(x[0], bb[0][0])
    fixed_function = fem.Function(V)
    facets_left = mesh.locate_entities_boundary(domain, domain.topology.dim - 1, fixed_marker)
    dofs_left = fem.locate_dofs_topological(V, domain.topology.dim - 1, facets_left)
    bc_clamped = fem.dirichletbc(fixed_function, dofs_left)

    return [bc_clamped]

1., 2. & 5. Sweep \(h/L\) and compare FE with EB

# Sweep h/L
L = 1.0
F = 10.0   # line load N/m
E_star = E / (1.0 - nu**2)

results = []
sol = {}
for h in [0.01, 0.05, 0.10, 0.20, 0.50]:
    bb = [[0.0, 0.0], [L, h]]
    nx = 100
    ny = max(4, int(round(h / L * nx)))
    domain_c = generate_domain(bb[0], bb[1], nx=nx, ny=ny)
    V_CG2, V_CG1 = generate_functionspaces(domain_c)

    lhs, rhs = weak_form_cantilever(V_CG2, domain_c, bb, F_per_metre=F)
    prob = fem.petsc.LinearProblem(lhs, rhs, bcs=boundary_conditions_cantilever(V_CG2, domain_c, bb),
        petsc_options={'ksp_type': 'preonly', 'pc_type': 'lu'})
    u_c = prob.solve()

    u_c_cg1 = library.helpers.project(u_c, V_CG1)
    coords = V_CG1.tabulate_dof_coordinates()
    uy = u_c_cg1.x.array.reshape(-1, 2)[:, 1]
    # Tip deflection = mean of uy on the right edge (mid-line could differ slightly)
    mask_right = np.isclose(coords[:, 0], L)
    w_tip_FE = -uy[mask_right].mean()

    I_section = h**3 / 12.0
    w_tip_EB  = F * L**3 / (3.0 * E_star * I_section)
    ratio = w_tip_FE / w_tip_EB

    results.append((h, w_tip_FE, w_tip_EB, ratio))
    print(f'h/L = {h:.2f}   w_FE = {w_tip_FE:.4e} m   w_EB = {w_tip_EB:.4e} m   FE/EB = {ratio:.4f}')

    if h == 0.10:        # keep this case for the visualisation below
        sol = dict(L=L, h=h, F=F, u=u_c_cg1, V=V_CG1, domain=domain_c, bb=bb)
h/L = 0.01   w_FE = 1.7321e-04 m   w_EB = 1.7333e-04 m   FE/EB = 0.9993
h/L = 0.05   w_FE = 1.3870e-06 m   w_EB = 1.3867e-06 m   FE/EB = 1.0003
h/L = 0.10   w_FE = 1.7421e-07 m   w_EB = 1.7333e-07 m   FE/EB = 1.0050
h/L = 0.20   w_FE = 2.2255e-08 m   w_EB = 2.1667e-08 m   FE/EB = 1.0272
h/L = 0.50   w_FE = 1.6573e-09 m   w_EB = 1.3867e-09 m   FE/EB = 1.1952

Looking at the results from the sweep, we can draw the following conclusions:

For thin beams (\(h/L \le 0.05\)) the FE solution agrees with Euler-Bernoulli to better than \(0.1\)%. As \(h/L\) grows the ratio rises above 1: the FE beam deflects more than EB predicts. Euler-Bernoulli assumes plane sections remain plane and normal to the deformed mid-surface, which neglects transverse shear; the full plane-strain FE retains it, adding a softening contribution that scales as \(\mathcal O((h/L)^2)\). At \(h/L = 0.20\) this is already a few-percent effect, and at \(h/L = 0.50\) the EB approximation has clearly stopped being asymptotically tight.

Verification

The following cell verifies our cantilever beam implementation by checking the tip-deflection ratios across all \(h/L\) values. If the weak formulation was correctly implemented, the test passes :)

library.tests.test_hw02_new_cantilever(results)
Passed test_hw02_new_cantilever?: True

6. Visualisation

# Visualise the h/L = 0.10 case, inline + XDMF
library.plot.deformation_wireframe_2d(
    sol['u'],
    f'cantilever h/L={sol["h"]/sol["L"]:.2f} (scale=2e5)',
    output_dir, 'wireframe_cantilever', scale=2e5)
library.plot.display_image(image_path=os.path.join(output_dir, 'wireframe_cantilever.png'))
Image saved: hw02/wireframe_cantilever.png

P3 — Eigenmodes of the Cantilever Beam

So far P2 was a static problem: the right-hand side was a prescribed traction, and we solved a single linear system. Now we ask a different question: with no external load, in what shapes and at what frequencies does the clamped-free beam naturally oscillate?

From dynamics to an eigenvalue problem

The dynamic momentum balance for a linear-elastic body (no body force) is

\[ \rho\,\ddot{\mathbf w}(\mathbf x, t) \;=\; \nabla\cdot\sigma\bigl(\mathbf w(\mathbf x, t)\bigr) \quad \text{in } \Omega. \]

We look for time-harmonic solutions of the form

\[ \mathbf w(\mathbf x, t) \;=\; \hat{\mathbf w}(\mathbf x)\,e^{i\omega t}, \]

i.e. spatial mode shapes that all oscillate at one common frequency \(\omega\). Substituting gives \(\ddot{\mathbf w} = -\omega^2\hat{\mathbf w}\,e^{i\omega t}\), the time factor cancels, and what remains is a spatial equation for the unknown pair \((\omega^2, \hat{\mathbf w})\):

\[ -\nabla\cdot\sigma(\hat{\mathbf w}) \;=\; \omega^2\,\rho\,\hat{\mathbf w}. \]

This is structurally the same as \(A\hat{\mathbf w} = \lambda\,\hat{\mathbf w}\) with \(\lambda = \omega^2\) — i.e. an eigenvalue problem: we are looking for the (infinitely many) scalar/function pairs that the operator \(-\rho^{-1}\nabla\cdot\sigma\) admits. The frequencies \(\omega_n\) at which non-trivial \(\hat{\mathbf w}_n\) exist are the natural frequencies, and the corresponding \(\hat{\mathbf w}_n\) are the mode shapes. Once we discretise with finite elements the operator becomes a matrix, and we get the generalised matrix eigenvalue problem \(K\hat{\mathbf w} = \omega^2 M\,\hat{\mathbf w}\) written out below.

Strong problem

Let \(\Omega = [0,L]\times[0,h]\) with \(\Gamma_C\) the clamped edge (\(x=0\)). The strong eigenvalue problem reads:

\[ \left\{\begin{aligned} -\nabla\cdot\sigma(\mathbf w) &= \omega^2\,\rho\,\mathbf w && \text{in } \Omega, \\ \mathbf w &= \mathbf 0 && \text{on } \Gamma_C, \\ \sigma(\mathbf w)\,\mathbf n &= \mathbf 0 && \text{on } \partial\Omega \setminus \Gamma_C. \end{aligned}\right. \]

We want all \((\omega^2,\mathbf w)\) pairs with \(\mathbf w \neq \mathbf 0\).

Weak problem

Define the (Ritz–Galerkin) trial-and-test space

\[ V = \bigl\{\,\mathbf w \in [H^1(\Omega)]^2 \;\big|\; \mathbf w = \mathbf 0 \text{ on } \Gamma_C\,\bigr\}. \]

Testing the strong form with \(\mathbf v\in V\) and integrating by parts (the boundary term vanishes because \(\sigma\mathbf n = \mathbf 0\) on the free part of \(\partial\Omega\) and \(\mathbf v = \mathbf 0\) on \(\Gamma_C\)):

Find \((\omega^2, \mathbf w) \in \mathbb R_{\ge 0} \times V\setminus\{\mathbf 0\}\) such that \[ \int_\Omega \sigma(\mathbf w):\nabla\mathbf v \,dx \;=\; \omega^2 \int_\Omega \rho\,\mathbf w\cdot\mathbf v \,dx \] for all \(\mathbf v \in V\).

After FE discretisation this becomes the generalised matrix eigenvalue problem \(K\,\hat{\mathbf w} = \omega^2\,M\,\hat{\mathbf w}\) with

\[ K_{ij} = \int_\Omega \sigma(\mathbf w_i):D(\mathbf w_j)\,dx, \qquad M_{ij} = \int_\Omega \rho\,\mathbf w_i\cdot\mathbf w_j\,dx, \]

which we solve with SLEPc (shift-invert around zero).

Bridging to the Euler-Bernoulli closed-form spectrum

In the lecture (§6.11) we stated the closed form of the EB eigenfrequencies but did not derive them. Here is the missing step. Recall the Euler-Bernoulli PDE (per unit out-of-plane metre, plane strain) for the mid-line deflection \(w(x,t)\):

\[ \rho A\,\ddot w(x,t) + E^* I\,w''''(x,t) \;=\; 0. \]

Make the same time-harmonic ansatz, \(w(x,t) = \hat w(x)\,e^{i\omega t}\):

\[ E^* I\,\hat w''''(x) \;=\; \omega^2\,\rho A\,\hat w(x) \quad\Longleftrightarrow\quad \hat w''''(x) \;=\; \beta^4\,\hat w(x), \qquad \beta^4 := \frac{\omega^2\,\rho A}{E^* I}. \]

This is a constant-coefficient ODE with characteristic roots \(\pm\beta, \pm i\beta\), so the general solution is

\[ \hat w(x) = c_1\cos(\beta x) + c_2\sin(\beta x) + c_3\cosh(\beta x) + c_4\sinh(\beta x). \]

The four constants are fixed by the four boundary conditions of a clamped-free beam:

\[ \underbrace{\hat w(0) = 0,\quad \hat w'(0) = 0}_{\text{clamp at }x=0}, \qquad \underbrace{\hat w''(L) = 0,\quad \hat w'''(L) = 0}_{\text{moment- and shear-free at }x=L}. \]

Imposing all four BCs gives a \(4\times 4\) homogeneous linear system \(A(\beta L)\,\mathbf c = \mathbf 0\) for the unknown coefficients \(\mathbf c=(c_1,\dots,c_4)\). A non-trivial mode shape exists iff \(\det A(\beta L) = 0\), which collapses to the transcendental characteristic equation

\[ \boxed{\;\cos(\beta L)\,\cosh(\beta L) + 1 \;=\; 0.\;} \]

This equation has a discrete sequence of positive roots \(\beta_1 L < \beta_2 L < \dots\). As \(n\) grows, \(1/\cosh(\beta L)\to 0\) rapidly, so the roots approach \((n-\tfrac12)\pi\) (the zeros of \(\cos\)). Each root then maps back to a frequency through the definition of \(\beta\):

\[ \omega_n \;=\; (\beta_n L)^2 \sqrt{\frac{E^*\,I}{\rho\,A\,L^4}}, \qquad f_n = \frac{\omega_n}{2\pi}, \]

with \(A = h\cdot 1\,\mathrm m\) and \(I = h^3/12\). We compute the \(\beta_n L\) roots numerically below using scipy.optimize.brentq rather than hard-coding them.

1. Mesh and computational domain

# Eigenmode geometry (thin beam where EB is most accurate)
L_eig = 1.0
h_eig = 0.01
bb_eig = [[0.0, 0.0], [L_eig, h_eig]]
domain_eig = generate_domain(bb_eig[0], bb_eig[1], nx=100, ny=4)

2. Setup our Continuous Galerkin (Finite) elements

V_CG2_eig, V_CG1_eig = generate_functionspaces(domain_eig)
print('eigenproblem dofs:', V_CG2_eig.dofmap.index_map.size_global * V_CG2_eig.dofmap.index_map_bs)
eigenproblem dofs: 3618

3. The weak form and UFL: From Math to Code

Task 3

STUDENT TODO

Implement the bilinear forms in weak_form_eigenproblem:

  • Stiffness a_form: \(\int_\Omega \sigma(\mathbf{u}) : \nabla\mathbf{v}\,dx\) with \(D(\mathbf{w}) = \tfrac{1}{2}(\nabla\mathbf{w} + \nabla\mathbf{w}^T)\) and \(\sigma = \lambda\,\mathrm{tr}(D)\,\mathbf{I} + 2\mu D\).
  • Mass m_form: \(\int_\Omega \rho\,\mathbf{u}\cdot\mathbf{v}\,dx\).
def weak_form_eigenproblem(V, domain, bb):

    u = ufl.TrialFunction(V)
    v = ufl.TestFunction(V)

    ### TODO #############################################
    # Build the bilinear forms:
    #   - small-strain D(w), stress sigma (use ufl.Identity(2))
    #   - stiffness:  a = inner(sigma(u), grad(v)) * dx
    #   - mass:       m = rho * inner(u, v) * dx
    a_form = 0
    m_form = 0
    ######################################################


    weakform_a = fem.form(a_form)
    weakform_m = fem.form(m_form)

    return weakform_a, weakform_m

4. Boundary Conditions

def boundary_conditions_eigenproblem(V, domain, bb):
    def fixed_marker(x): return np.isclose(x[0], bb[0][0])
    fixed_function = fem.Function(V)
    facets_left = mesh.locate_entities_boundary(domain, domain.topology.dim - 1, fixed_marker)
    dofs_left = fem.locate_dofs_topological(V, domain.topology.dim - 1, facets_left)
    bc_clamped = fem.dirichletbc(fixed_function, dofs_left)
    
    return [bc_clamped]

5. Assemble and Solve eigenvalue problem

We first assemble K, M, matrices for the free-vibration eigenproblem on the clamped-free beam. Dirichlet rows of M are scaled to a tiny diagonal so the spurious BC modes are pushed to very large eigenvalues.

weakform_a, weakform_m = weak_form_eigenproblem(V_CG2_eig, domain_eig, bb_eig)
bcs_eig = boundary_conditions_eigenproblem(V_CG2_eig, domain_eig, bb_eig)
K = fem.petsc.assemble_matrix(weakform_a, bcs=bcs_eig)
K.assemble()
M = fem.petsc.assemble_matrix(weakform_m, bcs=bcs_eig, diagonal=1e-12)
M.assemble()
Note

The following code is only for the interested reader. Feel free to skip it.

N_MODES = 10

eps = SLEPc.EPS().create(MPI.COMM_WORLD)
eps.setOperators(K, M)
eps.setProblemType(SLEPc.EPS.ProblemType.GHEP)
eps.setDimensions(nev=N_MODES + 4)
eps.setWhichEigenpairs(SLEPc.EPS.Which.TARGET_REAL)
eps.setTarget(0.0)
st = eps.getST()
st.setType(SLEPc.ST.Type.SINVERT)
st.setShift(0.0)
ksp = st.getKSP()
ksp.setType('preonly')
ksp.getPC().setType('lu')
eps.solve()

n_conv = eps.getConverged()
print(f'converged eigenpairs: {n_conv}')

eig_freq = []
eig_vec  = []
vr, vi = K.createVecs()
for i in range(n_conv):
    val = eps.getEigenpair(i, vr, vi).real
    if val < 1e-3:        # skip numerical zero / spurious BC modes
        continue
    omega = np.sqrt(val)
    eig_freq.append((val, omega, omega/(2*np.pi)))
    if len(eig_vec) < N_MODES:
        wf = fem.Function(V_CG2_eig)
        wf.x.array[:] = vr.array_r
        eig_vec.append(wf)
converged eigenpairs: 15

6. Visualization: Mode shapes

We project each eigenvector to CG1 and overlay the deformed wireframe on the original beam. Below we display the first \(N\) modes.

# Inline screenshots (each mode)
modes_cg1 = []
for k, wf in enumerate(eig_vec[:N_MODES]):
    wf_cg1 = library.helpers.project(wf, V_CG1_eig)
    amax = np.max(np.abs(wf_cg1.x.array))
    if amax > 0:
        wf_cg1.x.array[:] /= amax
    name = f'mode_{k+1}'
    library.plot.deformation_wireframe_2d(wf_cg1, f'mode {k+1}', output_dir, name, scale=0.05)
    display(library.plot.display_image(image_path=os.path.join(output_dir, f'{name}.png')))
    modes_cg1.append(wf_cg1)
Image saved: hw02/mode_1.png
Image saved: hw02/mode_2.png
Image saved: hw02/mode_3.png
Image saved: hw02/mode_4.png
Image saved: hw02/mode_5.png
Image saved: hw02/mode_6.png
Image saved: hw02/mode_7.png
Image saved: hw02/mode_8.png
Image saved: hw02/mode_9.png
Image saved: hw02/mode_10.png

7. Analysis: Comparison to Euler-Bernoulli frequencies

We solve \(\cos(\beta L)\cosh(\beta L) + 1 = 0\) by bracketing each root and applying Brent’s method. To avoid cosh overflowing for large arguments, we equivalently solve \(\cos(x) + \mathrm{sech}(x) = 0\) — same roots, but bounded.

Note

The following code is only for the interested reader. Feel free to skip it.

def char_eq(x):
    # cos(x) + 1/cosh(x) = 0  is equivalent to cos(x)*cosh(x) + 1 = 0
    return np.cos(x) + 1.0/np.cosh(x)

beta_L = []
for n in range(1, N_MODES + 1):
    # roots are near (n - 1/2)*pi for n>=2, and approx 1.875 for n=1
    centre = (n - 0.5)*np.pi if n >= 2 else 1.875
    a, b = centre - 0.6, centre + 0.6
    # Make sure we bracket a sign change; widen if needed
    while char_eq(a)*char_eq(b) > 0:
        a -= 0.1; b += 0.1
    beta_L.append(brentq(char_eq, a, b, xtol=1e-12))

print('beta_n * L (computed):')
for n, bL in enumerate(beta_L, start=1):
    print(f'  n={n:2d}   beta_n L = {bL:.10f}')

# Analytical Euler-Bernoulli frequencies
A = h_eig * 1.0          # per unit out-of-plane metre
I_sec = h_eig**3 / 12.0
omega_eb = lambda bL: bL**2 * np.sqrt(E_star * I_sec / (rho * A * L_eig**4))

f_FE_list = [freq for (_, _, freq) in eig_freq[:N_MODES]]
f_EB_list = [omega_eb(bL)/(2*np.pi) for bL in beta_L]

print(f'\n{"mode":>4} {"f_FE [Hz]":>14} {"f_EB [Hz]":>14} {"FE/EB":>10}')
for n in range(N_MODES):
    print(f'{n+1:>4} {f_FE_list[n]:>14.4f} {f_EB_list[n]:>14.4f} {f_FE_list[n]/f_EB_list[n]:>10.4f}')
beta_n * L (computed):
  n= 1   beta_n L = 1.8751040687
  n= 2   beta_n L = 4.6940911330
  n= 3   beta_n L = 7.8547574382
  n= 4   beta_n L = 10.9955407349
  n= 5   beta_n L = 14.1371683910
  n= 6   beta_n L = 17.2787595321
  n= 7   beta_n L = 20.4203522510
  n= 8   beta_n L = 23.5619449018
  n= 9   beta_n L = 26.7035375555
  n=10   beta_n L = 29.8451302091

mode      f_FE [Hz]      f_EB [Hz]      FE/EB
   1         8.7624         8.7586     1.0004
   2        54.8862        54.8892     0.9999
   3       153.5620       153.6913     0.9992
   4       300.5754       301.1735     0.9980
   5       496.1367       497.8614     0.9965
   6       739.7975       743.7188     0.9947
   7      1031.0574      1038.7477     0.9926
   8      1355.9408      1382.9482     0.9805
   9      1369.3274      1776.3201     0.7709
  10      1753.9379      2218.8635     0.7905
Verification

The following cell verifies our implementation: the lowest FE eigenfrequencies must match the Euler-Bernoulli closed-form values to within \(\sim 1\)%.

# Test: the lowest 3 FE bending modes must match the EB closed form
library.tests.test_hw02_new_eigenmodes(f_FE_list, f_EB_list, n_compare=3)

# Predicted frequency of the first longitudinal (axial) mode of a fixed-free bar:
# f_long_1 = c_L / (4 L)  with c_L = sqrt(E*/rho).
c_long = np.sqrt(E_star/rho)
f_long_1 = c_long / (4*L_eig)
print(f'\nFirst longitudinal (axial) mode prediction: f = c_L/(4L) = {f_long_1:.2f} Hz '
      f'(c_L = {c_long:.1f} m/s)')
Passed test_hw02_new_eigenmodes?: True

First longitudinal (axial) mode prediction: f = c_L/(4L) = 1355.48 Hz (c_L = 5421.9 m/s)

The first three FE frequencies should agree with Euler-Bernoulli to better than \(\sim 1\)%. Higher modes deviate more — the Euler-Bernoulli ansatz \(w(x,y,z,t) \approx -y\,\partial_x w(x,t)\) fails when the wavelength becomes comparable to the thickness.

Why does one of the FE modes not “wave”

Looking at the visualisations below, mode 8 does not look like a sine wave — the beam appears to keep its straight shape and only stretch/contract along its length. That is not a numerical artefact and the coefficient is not zero. It is a longitudinal (axial) mode: a pure compression-extension wave along \(x\) that keeps cross-sections planar and parallel to themselves. The 2D slab obviously supports such modes — they are perfectly physical.

What is going on is that we wrote down the Euler-Bernoulli bending equation \(\rho A\,\ddot w + E^*I\,w'''' = 0\) and that equation only describes the transverse deflection \(w(x,t)\). Axial extension/compression in linear elasticity is governed by a separate 1D rod equation \(\rho A\,\ddot u - E^*A\,u'' = 0\), decoupled from the bending equation. The FE eigensolver, on the other hand, sees the full plane-strain operator and returns the union of all elastic modes — bending and axial. The table only compares against the bending spectrum, so axial modes that show up between the bending ones simply don’t have an entry to compare to.

For a clamped-free bar the rod equation gives the longitudinal eigenfrequencies

\[ f_n^{long} = (2n-1)\,\frac{c_L}{4L}, \qquad c_L = \sqrt{E^*/\rho}, \]

i.e. the standing-wave frequencies of a quarter-wavelength resonator. The lowest one comes out around \(f_1^{long} \approx c_L/(4L) \approx 1355\) Hz for our steel beam, which slots into the FE spectrum between the seventh and eighth bending modes — and that is precisely what we see at mode 8 in the table. The FE/EB ratio for that row is therefore meaningless: the row is comparing an axial FE mode to the eighth bending frequency of EB, which describes a different physical phenomenon.

This also explains why the EB-bending comparison stays good for modes 1–7 here but breaks down at the row where an axial mode squeezes into the sequence.

Prepare for your presentation

During the presentation, be prepared to answer the following questions/tasks. We will ask 1-2 questions per person.

  1. What was this exercise about?
  2. What does the consistency check in P1 tell us that simply staring at the deformed shape does not? Why is recovering \(E\) and \(\nu\) a stronger test than visual inspection?
  3. Why does the rod test in 2D plane strain give an apparent \(E^* = E/(1-\nu^2)\) rather than \(E\)? What constraint causes this?
  4. The cantilever tip deflection scales as \(L^3\) and the bending stiffness as \(h^3\). Where does each cubic power come from?
  5. Why does the FE/EB ratio in P2 deviate from \(1\) at \(h/L = 0.10\)? In which direction (FE softer or stiffer than EB), and why?
  6. What sets the frequency ratio \(\omega_2/\omega_1\) for the clamped-free beam? Is it material-dependent or purely geometric?