{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Static stress analysis of a bracket\n",
    "\n",
    "A bracket made of 5 mm steel sheet hangs from a ceiling. Its two vertical **arms** are joined at\n",
    "the back by a horizontal web; two **mounting tabs** bent outwards from the top of the arms carry\n",
    "two bolt holes each. At the front end each arm has a downward **lug** with a pin hole. A pin\n",
    "through both lugs carries a load of 2 kN straight down.\n",
    "\n",
    "The part comes from the CAD file `bracket_static_stress.step`. It holds one half of the bracket\n",
    "(symmetric about $y=0$) with three named face groups: `bolts`, `pin` and `symmetry`. The script\n",
    "`bracket_static_stress_geometry.py` builds the part with the CAD objects of OneSimulation and\n",
    "writes the file.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| bolt holes | fixed |\n",
    "| pin hole | bearing pressure $p_{max}\\cos\\varphi$ on the lower half, resultant 1 kN per lug |\n",
    "| symmetry plane $y=0$ | $u_y=0$ |\n",
    "| all other faces | free |\n",
    "\n",
    "**Reference.** In the arm, beam theory gives the bending stress $M(z-H/2)/I$ with\n",
    "$M=(F/2)(x_{pin}-x)$. At the pin hole, Peterson's chart for a pin-loaded lug gives the stress\n",
    "concentration factor $K_t=2.85$ on the net-section stress."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher\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",
    "    FixedDisplacementComponents,\n",
    "    LinearElasticity,\n",
    "    Traction,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.results.derived import CylindricalFrame, frame_field\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the solid with its faces; the named groups of the file are available as\n",
    "`bracket.boundaries`. The mesh consists of quadratic tetrahedra that follow the round holes,\n",
    "4 mm in the sheet and 1.5 mm at the pin hole."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bracket = load(\"bracket_static_stress.step\")\n",
    "faces = bracket.boundaries\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.004,\n",
    "    geometry_order=2,\n",
    "    refinements=(LocalRefinement(region=faces.pin, target_size=0.0015),),\n",
    ").generate(bracket)\n",
    "\n",
    "view = plots.Camera(elevation=26, azimuth=-128)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    bracket,\n",
    "    selection={\"bolts\": faces.bolts, \"pin\": faces.pin, \"symmetry\": faces.symmetry},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half bracket with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The pin presses on the lower half of the hole with the pressure $p_{max}\\cos\\varphi$,\n",
    "$p_{max}=F/(\\pi r t)$, which adds up to half the load per lug."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "load_per_bracket, sheet, height, pin, radius = (\n",
    "    2000.0,\n",
    "    0.005,\n",
    "    0.040,\n",
    "    (0.115, 0.0225, -0.015),\n",
    "    0.006,\n",
    ")\n",
    "steel = IsotropicSolid(\n",
    "    density=7850.0,\n",
    "    specific_heat_capacity=470.0,\n",
    "    thermal_conductivity=50.0,\n",
    "    youngs_modulus=200e9,\n",
    "    poisson_ratio=0.30,\n",
    "    thermal_expansion_coefficient=1.2e-5,\n",
    ")\n",
    "\n",
    "\n",
    "def bearing(x, y, z):\n",
    "    \"\"\"Traction of the pin on the hole surface.\"\"\"\n",
    "    nx, nz = (pin[0] - np.asarray(x)) / radius, (pin[2] - np.asarray(z)) / radius\n",
    "    pressure = load_per_bracket / (np.pi * radius * sheet) * np.maximum(nz, 0.0)\n",
    "    return np.stack((-pressure * nx, np.zeros_like(nx), -pressure * nz), axis=-1)\n",
    "\n",
    "\n",
    "model = LinearElasticity(domain=bracket.volume, material=steel)\n",
    "problem = Problem(\n",
    "    name=\"Bracket\",\n",
    "    geometry=bracket,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacement(boundary=faces.bolts, physics=model, value=(0.0, 0.0, 0.0)),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.symmetry, physics=model, components=(\"y\",)\n",
    "        ),\n",
    "        Traction(boundary=faces.pin, physics=model, value=bearing),\n",
    "        TractionFree(\n",
    "            boundary=faces.all - faces.bolts - faces.symmetry - faces.pin, physics=model\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "displacement, stress, mises = (\n",
    "    result.field(f) for f in (model.displacement, model.stress, model.von_mises_stress)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The bending stress across the arm at $x=70$ mm at mid-thickness of the sheet, and the hoop stress\n",
    "on the wall of the pin hole. `frame_field` expresses the stress tensor in cylindrical components\n",
    "about the pin axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(1e-6, height - 1e-6, 21)\n",
    "bending = stress.evaluate(\n",
    "    np.column_stack((np.full_like(z, 0.070), np.full_like(z, pin[1]), z))\n",
    ")[:, 0]\n",
    "beam = (\n",
    "    load_per_bracket\n",
    "    / 2\n",
    "    * (pin[0] - 0.070)\n",
    "    * (z - height / 2)\n",
    "    / (sheet * height**3 / 12)\n",
    ")\n",
    "wall = frame_field(stress, CylindricalFrame(axis=(0, 1, 0), origin=pin)).sample(\n",
    "    along=faces.pin, subdivisions=3\n",
    ")\n",
    "hoop = wall.component(\"tt\")\n",
    "angle = np.degrees(\n",
    "    np.arctan2(wall.positions[:, 2] - pin[2], wall.positions[:, 0] - pin[0])\n",
    ")\n",
    "net_stress = load_per_bracket / 2 / ((0.030 - 2 * radius) * sheet)\n",
    "\n",
    "print(\n",
    "    f\"pin deflection: {1e3 * displacement.evaluate([[pin[0], pin[1], pin[2] - radius]])[0, 2]:.4f} mm\"\n",
    ")\n",
    "print(\n",
    "    f\"outer-fibre bending stress in the arm: simulation {np.polyfit(z - height / 2, bending, 1)[0] * height / 2 / 1e6:.2f} MPa, \"\n",
    "    f\"beam theory {beam[-1] / 1e6:.2f} MPa\"\n",
    ")\n",
    "print(\n",
    "    f\"stress concentration at the pin hole: simulation {hoop.max() / net_stress:.2f}, Peterson's chart 2.85\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The von Mises stress on the deformed bracket (displacement magnified 40 times), in the mid-plane\n",
    "of the lug, the bending stress across the arm and the hoop stress around the pin hole."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "megapascal = lambda s, position: s / 1e6\n",
    "fig = plots.figure(2, 2, size=(15, 11))\n",
    "plots.surface(\n",
    "    mises,\n",
    "    component=megapascal,\n",
    "    deformation=displacement,\n",
    "    deformation_scale=40.0,\n",
    "    limits=(0, 60),\n",
    "    symmetry={\"planes\": [((0, 1, 0), (0, 0, 0))]},\n",
    "    camera=view,\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Deformed bracket\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    mises,\n",
    "    plane=Plane(origin=(0, pin[1], 0), normal=(0, 1, 0)),\n",
    "    component=megapascal,\n",
    "    limits=(0, 32),\n",
    "    subdivisions=3,\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Lug with the pin hole\",\n",
    "    xlimits=(0.095, 0.135),\n",
    "    ylimits=(-0.05, 0.005),\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (bending / 1e6, 1e3 * z)},\n",
    "    reference={\"beam theory\": (beam / 1e6, 1e3 * z)},\n",
    "    xlabel=\"bending stress [MPa]\",\n",
    "    ylabel=\"z [mm]\",\n",
    "    title=\"Arm section at x = 70 mm\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (angle, hoop / 1e6)},\n",
    "    hlines={\"Peterson's chart\": 2.85 * net_stress / 1e6},\n",
    "    ylimits=(-10, 36),\n",
    "    xlabel=\"angle around the pin hole [°]\",\n",
    "    ylabel=\"hoop stress [MPa]\",\n",
    "    title=\"Hoop stress around the pin hole\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the sheet thickness or the lug in `bracket_static_stress_geometry.py`, write the STEP file\n",
    "again and rerun: the face names stay, so nothing else changes. Or replace the file by your own\n",
    "part and name its faces with `part.grouped(...)`."
   ]
  }
 ]
}
