{
 "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": [
    "# Thick elliptic plate under pressure (NAFEMS LE10)\n",
    "\n",
    "The plate is an elliptic ring: the hole is the ellipse $(x/2)^2+(y/1)^2=1$, the outer edge the\n",
    "ellipse $(x/3.25)^2+(y/2.75)^2=1$ (metres), and the plate is 0.6 m thick. A pressure of 1 MPa\n",
    "acts on the upper face. Because of symmetry only the quarter $x\\ge0,\\ y\\ge0$ is modelled.\n",
    "\n",
    "The quarter comes from the CAD file `thick_plate_pressure_le10.step`, which names its faces; the\n",
    "script `thick_plate_pressure_le10_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `symmetry_x` and `symmetry_y` | no displacement normal to the face |\n",
    "| `outer` | $u_x=u_y=0$ |\n",
    "| mid-height line of `outer` | $u_z=0$ |\n",
    "| `top` | pressure 1 MPa |\n",
    "| `bottom` and `hole` | free |\n",
    "\n",
    "Steel with $E=210$ GPa and $\\nu=0.3$.\n",
    "\n",
    "**Reference.** NAFEMS, *The Standard NAFEMS Benchmarks*, test LE10: the stress at point\n",
    "$D=(2,0,0.3)$, on the loaded face at the end of the hole's long axis, is\n",
    "$\\sigma_{yy}=-5.38$ MPa."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import Geometric, TwoSided, VolumeBlock, merge_volume_blocks\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",
    "    FixedDisplacementComponents,\n",
    "    LinearElasticity,\n",
    "    Pressure,\n",
    "    TractionFree,\n",
    ")\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 named faces. The benchmark is run on quadratic hexahedra: the\n",
    "quarter ring is one block whose map blends the two ellipses, graded towards the hole and towards\n",
    "point D, with a node layer at mid-height for the line support. `merge_volume_blocks` binds the\n",
    "block to the faces of the loaded part."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate = load(\"thick_plate_pressure_le10.step\")\n",
    "faces = plate.boundaries\n",
    "hole, outer_edge, thickness = (2.0, 1.0), (3.25, 2.75), 0.6\n",
    "\n",
    "\n",
    "def plate_mesh(n):\n",
    "    \"\"\"Hexahedral mesh with n cells across the ring and around it.\"\"\"\n",
    "    ring = lambda xi, eta, zeta: (\n",
    "        ((1 - xi) * hole[0] + xi * outer_edge[0]) * np.cos(np.pi / 2 * eta),\n",
    "        ((1 - xi) * hole[1] + xi * outer_edge[1]) * np.sin(np.pi / 2 * eta),\n",
    "        thickness * (zeta - 0.5),\n",
    "    )\n",
    "    through = np.r_[\n",
    "        0.5 * Geometric(n // 2, ratio=4.0, toward=\"end\").reference(),\n",
    "        0.5 + 0.5 * TwoSided(n // 2 + 1, 3.0).reference()[1:],\n",
    "    ]\n",
    "    return merge_volume_blocks(\n",
    "        [\n",
    "            VolumeBlock(\n",
    "                ring,\n",
    "                Geometric(n, ratio=4.0).reference(),\n",
    "                Geometric(n, ratio=3.0).reference(),\n",
    "                through,\n",
    "            )\n",
    "        ],\n",
    "        plate,\n",
    "        order=2,\n",
    "    )\n",
    "\n",
    "\n",
    "meshes = [plate_mesh(n) for n in (8, 12, 16)]\n",
    "view = plots.Camera(elevation=32, azimuth=-62)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(\n",
    "    plate,\n",
    "    selection={\n",
    "        \"top\": faces.top,\n",
    "        \"outer\": faces.outer,\n",
    "        \"hole\": faces.hole,\n",
    "        \"symmetry_y\": faces.symmetry_y,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter plate with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Coarsest mesh: {meshes[0].cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "steel = IsotropicSolid(\n",
    "    density=7850.0,\n",
    "    specific_heat_capacity=470.0,\n",
    "    thermal_conductivity=50.0,\n",
    "    youngs_modulus=210e9,\n",
    "    poisson_ratio=0.30,\n",
    "    thermal_expansion_coefficient=1.2e-5,\n",
    ")\n",
    "model = LinearElasticity(domain=plate.volume, material=steel)\n",
    "problem = Problem(\n",
    "    name=\"NAFEMS LE10\",\n",
    "    geometry=plate,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.outer,\n",
    "            physics=model,\n",
    "            components=(\"x\", \"y\", \"z\"),\n",
    "            where={\"z\": lambda x, y, z: abs(z) < 1e-9},\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.symmetry_x, physics=model, components=(\"x\",)\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.symmetry_y, physics=model, components=(\"y\",)\n",
    "        ),\n",
    "        Pressure(boundary=faces.top, physics=model, value=1.0e6),\n",
    "        TractionFree(boundary=faces.bottom | faces.hole, physics=model),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "stresses = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.stress)\n",
    "    for mesh in meshes\n",
    "]\n",
    "stress = stresses[-1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The stress $\\sigma_{yy}$ at point D on the three meshes against the NAFEMS target."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "target = -5.38\n",
    "at_d = [\n",
    "    field.evaluate([[hole[0], 0.0, thickness / 2]])[0, 1] / 1e6 for field in stresses\n",
    "]\n",
    "print(\"hexahedra   σ_yy at D [MPa]   deviation from the NAFEMS target -5.38 MPa\")\n",
    "for mesh, value in zip(meshes, at_d):\n",
    "    print(f\"{mesh.cell_count:9d} {value:17.4f} {100 * (value / target - 1):+12.2f} %\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The stress $\\sigma_{yy}$ on the loaded face and on the symmetry plane $y=0$, and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "megapascal = lambda s, position: s[:, 1] / 1e6\n",
    "fig = plots.figure(1, 3, size=(16, 5))\n",
    "plots.surface(\n",
    "    stress,\n",
    "    boundary=faces.top,\n",
    "    component=megapascal,\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-16, 16),\n",
    "    subdivisions=3,\n",
    "    label=\"σ_yy [MPa]\",\n",
    "    title=\"Loaded face\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.surface(\n",
    "    stress,\n",
    "    boundary=faces.symmetry_y,\n",
    "    component=megapascal,\n",
    "    colormap=\"diverging\",\n",
    "    limits=(-8, 8),\n",
    "    subdivisions=3,\n",
    "    label=\"σ_yy [MPa]\",\n",
    "    title=\"Symmetry plane y = 0\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    [mesh.cell_count for mesh in meshes],\n",
    "    {\"simulation\": at_d},\n",
    "    hlines={\"NAFEMS target\": target},\n",
    "    markers=True,\n",
    "    xlabel=\"hexahedra\",\n",
    "    ylabel=\"σ_yy at D [MPa]\",\n",
    "    title=\"Mesh study at point D\",\n",
    "    legend=\"center 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 `thick_plate_pressure_le10_geometry.py` and write the STEP file again, or\n",
    "replace the pressure by a line load on the hole edge. The thin-plate variant of the benchmark\n",
    "(LE1) has the same outline in plane stress."
   ]
  }
 ]
}
