{
 "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": [
    "# Elliptic membrane under outward pressure (NAFEMS LE1)\n",
    "\n",
    "The membrane is a thin elliptic ring: the inner edge is the ellipse $(x/2)^2+(y/1)^2=1$, the\n",
    "outer edge the ellipse $(x/3.25)^2+(y/2.75)^2=1$ (metres), the thickness is 0.1 m. A uniform\n",
    "outward pressure of 10 MPa acts on the outer edge. Because of symmetry only the quarter\n",
    "$x\\ge0,\\ y\\ge0$ is modelled, in plane stress.\n",
    "\n",
    "The quarter comes from the CAD file `elliptic_membrane_le1.step`, which names its faces; the\n",
    "script `elliptic_membrane_le1_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| $x=0$ | $u_x=0$ |\n",
    "| $y=0$ | $u_y=0$ |\n",
    "| `outer` | normal traction $+10$ MPa (outward) |\n",
    "| `inner` | traction free |\n",
    "\n",
    "Steel with $E=210$ GPa and $\\nu=0.3$.\n",
    "\n",
    "**Reference.** NAFEMS, *The Standard NAFEMS Benchmarks*, rev. 3 (1990), test LE1: the hoop\n",
    "stress at point $D=(2,0)$, at the end of the long axis of the inner ellipse, is\n",
    "$\\sigma_{yy}=92.7$ MPa."
   ]
  },
  {
   "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.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 quarter with its named faces and `section` the mid-plane region, whose sides\n",
    "keep the names of the faces they were cut from. The mesher follows the two ellipses with short\n",
    "boundary segments; three meshes with interior cells of 0.2, 0.1 and 0.05 m grade away from them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "membrane = load(\"elliptic_membrane_le1.step\")\n",
    "faces = membrane.boundaries\n",
    "inner, outer, thickness = (2.0, 1.0), (3.25, 2.75), 0.1\n",
    "region = membrane.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "sides = region.boundaries\n",
    "sizes = [0.2, 0.1, 0.05]\n",
    "meshes = [\n",
    "    TriangularMesher(\n",
    "        target_size=size, grading=0.25, local_sizes={\"inner\": size / 3}\n",
    "    ).generate(region)\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    membrane,\n",
    "    selection={\n",
    "        \"outer (pressure)\": faces.outer,\n",
    "        \"inner\": faces.inner,\n",
    "        \"symmetry\": faces.symmetry_x | faces.symmetry_y,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=60, azimuth=-70),\n",
    "    title=\"Quarter membrane with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Middle 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",
    "The outward pressure is a traction along the normal of the outer ellipse, $p\\,\\mathbf n$ with\n",
    "$\\mathbf n\\propto(x/a^2,\\,y/b^2)$. The same model is solved with linear and with quadratic\n",
    "triangles on the three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pressure = 10e6\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=210e9,\n",
    "    poisson_ratio=0.3,\n",
    "    kinematics=\"plane_stress\",\n",
    "    thickness=thickness,\n",
    ")\n",
    "outward = (\n",
    "    lambda x, y: pressure\n",
    "    * np.stack((x / outer[0] ** 2, y / outer[1] ** 2), axis=-1)\n",
    "    / np.hypot(x / outer[0] ** 2, y / outer[1] ** 2)[..., None]\n",
    ")\n",
    "runs = {\n",
    "    (order, size): steel.solve(\n",
    "        mesh=mesh,\n",
    "        times=(0.0,),\n",
    "        order=order,\n",
    "        tractions=((sides.outer, outward),),\n",
    "        displacements=(\n",
    "            (sides[\"part.x_min\"], \"x\", 0.0),\n",
    "            (sides[\"part.y_min\"], \"y\", 0.0),\n",
    "        ),\n",
    "    )\n",
    "    for order in (1, 2)\n",
    "    for size, mesh in zip(sizes, meshes)\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The hoop stress follows from Hooke's law for plane stress with the gradient of the displacement\n",
    "field, evaluated exactly at point D."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hoop = (\n",
    "    lambda result, points: 210e9\n",
    "    / (1 - 0.3**2)\n",
    "    * (lambda g: g[:, 1, 1] + 0.3 * g[:, 0, 0])(\n",
    "        result.space.gradient(result.displacement[0], np.atleast_2d(points))\n",
    "    )\n",
    ")\n",
    "target = 92.7\n",
    "at_d = {key: hoop(result, (inner[0], 0.0))[0] / 1e6 for key, result in runs.items()}\n",
    "print(\n",
    "    \"elements             cell size [m]   triangles   σ_yy at D [MPa]   deviation from 92.7 MPa\"\n",
    ")\n",
    "for (order, size), value in at_d.items():\n",
    "    print(\n",
    "        f\"{['linear', 'quadratic'][order - 1]:20s} {size:13.3f} {meshes[sizes.index(size)].cell_count:11d} \"\n",
    "        f\"{value:17.2f} {100 * (value / target - 1):+14.2f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The hoop stress in the quarter on the finest quadratic mesh, the hoop stress along the symmetry\n",
    "line $y=0$ from D to the outer edge, and the mesh study at D for both element orders."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mesh, result = meshes[-1], runs[2, sizes[-1]]\n",
    "x = np.linspace(inner[0], outer[0], 120)\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.heatmap(\n",
    "    mesh.coordinates[:, 0],\n",
    "    mesh.coordinates[:, 1],\n",
    "    hoop(result, mesh.coordinates) / 1e6,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(-10, 95),\n",
    "    label=\"σ_yy [MPa]\",\n",
    "    title=\"Hoop stress σ_yy\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"linear triangles\": (\n",
    "            x[::4],\n",
    "            hoop(runs[1, sizes[-1]], np.column_stack((x, 0 * x)))[::4] / 1e6,\n",
    "        )\n",
    "    },\n",
    "    y={\"quadratic triangles\": (x, hoop(result, np.column_stack((x, 0 * x))) / 1e6)},\n",
    "    hlines={\"NAFEMS target at D\": target},\n",
    "    xlabel=\"x on the line y = 0 [m]\",\n",
    "    ylabel=\"σ_yy [MPa]\",\n",
    "    title=\"Hoop stress from D to the outer edge\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    [mesh.cell_count for mesh in meshes],\n",
    "    {\n",
    "        f\"{name} triangles\": [at_d[order, size] for size in sizes]\n",
    "        for order, name in ((1, \"linear\"), (2, \"quadratic\"))\n",
    "    },\n",
    "    hlines={\"NAFEMS target 92.7 MPa\": target},\n",
    "    markers=True,\n",
    "    xlabel=\"triangles\",\n",
    "    ylabel=\"σ_yy at D [MPa]\",\n",
    "    title=\"Mesh study at point D\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the half axes in `elliptic_membrane_le1_geometry.py` and write the STEP file again, or\n",
    "compare the plane-stress answer with the thick-plate variant of the benchmark (LE10), which\n",
    "has the same outline and bends under a pressure on its face."
   ]
  }
 ]
}
