{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a87813b4",
   "metadata": {},
   "source": [
    "# Bending of a clamped beam\n",
    "\n",
    "A beam (length $L$, width $b$, height $h$) fully clamped on the left carries a\n",
    "uniformly distributed transverse load with total force $F$ pointing down on the right.\n",
    "\n",
    "The beam comes from the CAD file `cantilever_beam_bending.step`; its faces are named `x_min`,\n",
    "`x_max`, `y_min`, `y_max`, `z_min` and `z_max`. The script `cantilever_beam_bending_geometry.py`\n",
    "builds it with the CAD objects of OneSimulation. OneSimulation solves the stationary 3D\n",
    "equilibrium $-\\nabla\\!\\cdot\\boldsymbol\\sigma=0$ with an isotropic Hooke law on quadratic\n",
    "hexahedra.\n",
    "\n",
    "**Reference.** Euler-Bernoulli beam theory gives the deflection line\n",
    "\n",
    "$$u_z(x)=-\\frac{F\\,(3Lx^2-x^3)}{6EI},\\qquad I=\\frac{b h^3}{12}.$$\n",
    "\n",
    "It neglects shear and 3D clamping effects and is therefore an approximate target value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d6ad20d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import CadHexahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacement,\n",
    "    LinearElasticity,\n",
    "    Traction,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b8f9b35",
   "metadata": {},
   "source": [
    "## Geometry and mesh"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecb42e8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "beam = load(\"cantilever_beam_bending.step\")\n",
    "faces = beam.boundaries\n",
    "length, width, height = beam.size\n",
    "mesh = CadHexahedralMesher(cells=(24, 4, 4)).generate(beam)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 4.5))\n",
    "plots.geometry(\n",
    "    beam,\n",
    "    selection={\"clamped\": faces.x_min, \"loaded\": faces.x_max},\n",
    "    labels=False,\n",
    "    title=\"Beam with its clamped and loaded face\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh, groups=(\"all\",), legend=False, title=f\"{mesh.cell_count} hexahedra\", ax=fig[1]\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21c8b5d4",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "210fd5f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "force, youngs_modulus = 30.0, 70e9\n",
    "aluminium = IsotropicSolid(\n",
    "    density=2700.0,\n",
    "    specific_heat_capacity=900.0,\n",
    "    thermal_conductivity=200.0,\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=0.30,\n",
    "    thermal_expansion_coefficient=23e-6,\n",
    ")\n",
    "model = LinearElasticity(domain=beam.volume, material=aluminium)\n",
    "problem = Problem(\n",
    "    name=\"Clamped beam under end-face load\",\n",
    "    geometry=beam,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacement(boundary=faces.x_min, physics=model, value=(0.0, 0.0, 0.0)),\n",
    "        Traction(\n",
    "            boundary=faces.x_max,\n",
    "            physics=model,\n",
    "            value=(0.0, 0.0, -force / (width * height)),\n",
    "        ),\n",
    "        TractionFree(boundary=faces.all - faces.x_min - faces.x_max, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "displacement = (\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.displacement)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d3d8d1b",
   "metadata": {},
   "source": [
    "## Comparison with beam theory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5482d990",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(0.0, length, 25)\n",
    "deflection = displacement.evaluate(\n",
    "    np.column_stack((x, np.full_like(x, width / 2), np.full_like(x, height / 2)))\n",
    ")[:, 2]\n",
    "beam_theory = (\n",
    "    -force * (3 * length * x**2 - x**3) / (6 * youngs_modulus * width * height**3 / 12)\n",
    ")\n",
    "\n",
    "print(\n",
    "    f\"tip deflection: simulation {1e3 * deflection[-1]:.4f} mm, Euler-Bernoulli {1e3 * beam_theory[-1]:.4f} mm, \"\n",
    "    f\"deviation {100 * (deflection[-1] / beam_theory[-1] - 1):+.2f} %\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb643707",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f03b0dba",
   "metadata": {},
   "outputs": [],
   "source": [
    "plots.line(\n",
    "    1e3 * x,\n",
    "    points={\"simulation\": 1e3 * deflection},\n",
    "    reference={\"Euler-Bernoulli\": 1e3 * beam_theory},\n",
    "    xlabel=\"position along the beam x [mm]\",\n",
    "    ylabel=\"deflection u_z [mm]\",\n",
    "    title=\"Clamped beam: deflection line\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15fb862e",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the cross-section in `cantilever_beam_bending_geometry.py` and write the STEP file again;\n",
    "for stubby beams the shear contribution grows and beam theory becomes less accurate. More cells\n",
    "through the height bring the 3D result closer to its own limit."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
