{
 "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": [
    "# Tapered cantilever with two load cases\n",
    "\n",
    "A cantilever of length $L=300$ mm is cut from a 5 mm steel plate. Its depth falls linearly from\n",
    "$h_0=60$ mm at the clamped root to $h_1=30$ mm at the free tip, both long edges inclined by the\n",
    "same angle, so the centre line stays straight. Two load cases are compared:\n",
    "\n",
    "| load case | load |\n",
    "|---|---|\n",
    "| A: tip load | shear force $F=1$ kN, spread evenly over the tip face |\n",
    "| B: edge load | distributed load $q=5$ N/mm downwards along the upper edge |\n",
    "\n",
    "In both cases the root is clamped and every other edge is traction free.\n",
    "\n",
    "The cantilever comes from the CAD file `tapered_cantilever_load_cases.step` with the faces\n",
    "`root`, `tip`, `top` and `bottom`; the script `tapered_cantilever_load_cases_geometry.py` builds\n",
    "it with the CAD objects of OneSimulation. The plate is thin and loaded in its plane, so the model\n",
    "is plane stress on the mid-plane.\n",
    "\n",
    "**Reference.** Beam theory for a member of variable depth $h(x)$, thickness $t$ and bending\n",
    "moment $M(x)$ (S. Timoshenko, *Strength of Materials*, Part I, 3rd ed., Van Nostrand (1955),\n",
    "Sec. 52): the bending stress $\\sigma_{xx}=M\\,y/I(x)$ with $I=t\\,h^3/12$, and the tip\n",
    "deflection from the unit-load method with bending and shear,\n",
    "\n",
    "$$\\delta=\\int_0^L\\Big(\\frac{M(x)\\,(L-x)}{E\\,I(x)}+\\frac{V(x)}{\\kappa\\,G\\,t\\,h(x)}\\Big)\\,dx,\n",
    "  \\qquad \\kappa=\\tfrac56 .$$\n",
    "\n",
    "For case A $M=F(L-x)$, $V=F$; for case B $M=q(L-x)^2/2$, $V=q(L-x)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.physics.solid_mechanics import SmallStrainSolid\n",
    "from onesim.results.comparisons import convergence\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 plate with its named faces and `section` the mid-plane region with the same\n",
    "side names. Three meshes of quadratic triangles with 6, 3 and 1.5 mm cells are used."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "beam = load(\"tapered_cantilever_load_cases.step\")\n",
    "faces = beam.boundaries\n",
    "length, _, thickness = beam.size\n",
    "region = beam.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "sides = region.boundaries\n",
    "sizes = [0.006, 0.003, 0.0015]\n",
    "meshes = [TriangularMesher(target_size=size).generate(region) for size in sizes]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 4.5))\n",
    "plots.geometry(\n",
    "    beam,\n",
    "    selection={\"root (clamped)\": faces.root, \"tip\": faces.tip, \"top\": faces.top},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=40, azimuth=-60),\n",
    "    title=\"Tapered cantilever with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane mesh: {meshes[1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Plane stress with quadratic triangles. The tip force becomes a uniform shear traction on the tip\n",
    "face, the edge load a vertical traction $q/t$ on the upper edge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, force, line_load, root, tip = (\n",
    "    210e9,\n",
    "    0.3,\n",
    "    1000.0,\n",
    "    5000.0,\n",
    "    0.060,\n",
    "    0.030,\n",
    ")\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson_ratio,\n",
    "    kinematics=\"plane_stress\",\n",
    "    thickness=thickness,\n",
    ")\n",
    "cases = {\n",
    "    \"A: tip load\": ((sides.tip, (0.0, -force / (tip * thickness))),),\n",
    "    \"B: edge load\": ((sides.top, (0.0, -line_load / thickness)),),\n",
    "}\n",
    "runs = {\n",
    "    case: [\n",
    "        steel.solve(\n",
    "            mesh=mesh,\n",
    "            times=(0.0,),\n",
    "            order=2,\n",
    "            displacements=((sides.root, \"x\", 0.0), (sides.root, \"y\", 0.0)),\n",
    "            tractions=tractions,\n",
    "        )\n",
    "        for mesh in meshes\n",
    "    ]\n",
    "    for case, tractions in cases.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The tip deflection on the three meshes against the unit-load method, and the bending stress,\n",
    "computed with Hooke's law from the gradient of the displacement, across the section at\n",
    "mid-length and along the lower edge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.0, length, 2001)\n",
    "depth = root + (tip - root) * x / length\n",
    "moments = {\n",
    "    \"A: tip load\": (force * (length - x), force + 0 * x),\n",
    "    \"B: edge load\": (line_load * (length - x) ** 2 / 2, line_load * (length - x)),\n",
    "}\n",
    "unit_load = lambda moment, shear: np.trapezoid(\n",
    "    moment * (length - x) / (youngs_modulus * thickness * depth**3 / 12)\n",
    "    + shear / (5 / 6 * youngs_modulus / (2 * (1 + poisson_ratio)) * thickness * depth),\n",
    "    x,\n",
    ")\n",
    "bending = (\n",
    "    lambda result, points: youngs_modulus\n",
    "    / (1 - poisson_ratio**2)\n",
    "    * (lambda g: g[:, 0, 0] + poisson_ratio * g[:, 1, 1])(\n",
    "        result.space.gradient(result.displacement[0], points)\n",
    "    )\n",
    ")\n",
    "height = np.linspace(-0.0225, 0.0225, 31)\n",
    "across = np.column_stack((np.full_like(height, length / 2), height))\n",
    "along = np.linspace(0.01, length - 0.01, 60)\n",
    "edge = np.column_stack((along, -(root + (tip - root) * along / length) / 2 + 1e-5))\n",
    "\n",
    "for case, results in runs.items():\n",
    "    deflections = [\n",
    "        -result.evaluate_displacement(np.array([[length, 0.0]]))[0, 1]\n",
    "        for result in results\n",
    "    ]\n",
    "    reference = unit_load(*moments[case])\n",
    "    study = convergence(deflections, sizes)\n",
    "    inertia = thickness * 0.045**3 / 12\n",
    "    print(\n",
    "        f\"{case}: tip deflection {1e3 * deflections[-1]:.4f} mm, unit-load method {1e3 * reference:.4f} mm, \"\n",
    "        f\"deviation {100 * (deflections[-1] / reference - 1):+.2f} % (mesh change {100 * study.change:.3f} %)\"\n",
    "    )\n",
    "    print(\n",
    "        f\"    outer-fibre stress at mid-length: simulation {bending(results[-1], across[-1:])[0] / 1e6:.2f} MPa, \"\n",
    "        f\"beam theory {np.interp(length / 2, x, moments[case][0]) * 0.0225 / inertia / 1e6:.2f} MPa\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The bending stress $\\sigma_{xx}$ for the tip load, the stress across the section at mid-length\n",
    "and along the lower edge for both load cases, each against beam theory."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mesh, result = meshes[-1], runs[\"A: tip load\"][-1]\n",
    "fig = plots.figure(\n",
    "    layout=[[\"map\", \"map\", \"map\"], [\"across\", \"edge\", \"tip\"]], size=(18, 10)\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * mesh.coordinates[:, 0],\n",
    "    1e3 * mesh.coordinates[:, 1],\n",
    "    bending(result, mesh.coordinates) / 1e6,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    colormap=\"diverging\",\n",
    "    centre=0.0,\n",
    "    limits=(-100, 100),\n",
    "    label=\"σ_xx [MPa]\",\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Load case A: bending stress\",\n",
    "    ax=fig[\"map\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        case: (bending(results[-1], across) / 1e6, 1e3 * height)\n",
    "        for case, results in runs.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"beam theory, {case[:1]}\": (\n",
    "            np.interp(length / 2, x, moments[case][0])\n",
    "            * height\n",
    "            / (thickness * 0.045**3 / 12)\n",
    "            / 1e6,\n",
    "            1e3 * height,\n",
    "        )\n",
    "        for case in runs\n",
    "    },\n",
    "    xlabel=\"σ_xx at x = 150 mm [MPa]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Bending stress across the mid-length section\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"across\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        case: (1e3 * along, bending(results[-1], edge) / 1e6)\n",
    "        for case, results in runs.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"beam theory, {case[:1]}\": (\n",
    "            1e3 * x,\n",
    "            -6 * moments[case][0] / (thickness * depth**2) / 1e6,\n",
    "        )\n",
    "        for case in runs\n",
    "    },\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"σ_xx at the lower edge [MPa]\",\n",
    "    title=\"Bending stress along the lower edge\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[\"edge\"],\n",
    ")\n",
    "plots.bars(\n",
    "    list(runs),\n",
    "    {\n",
    "        \"simulation\": [\n",
    "            -results[-1].evaluate_displacement(np.array([[length, 0.0]]))[0, 1] * 1e3\n",
    "            for results in runs.values()\n",
    "        ]\n",
    "    },\n",
    "    reference={\"unit-load method\": [1e3 * unit_load(*moments[case]) for case in runs]},\n",
    "    ylabel=\"tip deflection [mm]\",\n",
    "    title=\"Tip deflection\",\n",
    "    ax=fig[\"tip\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the depths in `tapered_cantilever_load_cases_geometry.py` and write the STEP file again:\n",
    "for a steeper taper the inclined edges carry part of the shear and beam theory starts to\n",
    "deviate. Combine both load cases by adding their tractions, or replace the clamp by a pin and a\n",
    "roller to compare support conditions."
   ]
  }
 ]
}
