{
 "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": [
    "# Stress concentration at a superelliptic hole\n",
    "\n",
    "A superellipse $|x/a|^n+|y/a|^n=1$ is a circle for $n=2$ and approaches a square with sharp\n",
    "corners as $n\\to\\infty$. Such holes appear as rounded window and hatch openings. A thin plate\n",
    "with a superelliptic hole carries a uniform tension $\\sigma_0$ in the $x$ direction far from the\n",
    "hole. At the traction-free edge of the hole the only stress left is the hoop stress, which is\n",
    "there equal to the first stress invariant,\n",
    "\n",
    "$$\\sigma_{tt}=\\sigma_{xx}+\\sigma_{yy}\\quad\\text{on the hole edge},$$\n",
    "\n",
    "and its largest value divided by $\\sigma_0$ is the stress concentration factor $K_t$. As $n$\n",
    "grows the edge facing the load becomes flat and the peak moves from the top of the hole towards\n",
    "the rounded corners. A slightly squarish hole spreads the stress and is gentler than the circle;\n",
    "with sharper corners the factor rises again above the circle's value.\n",
    "\n",
    "The plates are quarters of a square of half-width $L=20a$ with $a=10$ mm, from the CAD files\n",
    "`superellipse_hole_stress_concentration.step` ($n=4$) and `..._n2`, `_n3`, `_n6`, `_n10.step`; the\n",
    "script `superellipse_hole_stress_concentration_geometry.py` builds them with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| $x=0$ | $u_x=0$ |\n",
    "| $y=0$ | $u_y=0$ |\n",
    "| $x=L$ (`loaded`) | traction $(\\sigma_0,0)$ |\n",
    "| hole and $y=L$ | traction free |\n",
    "\n",
    "Steel, $E=200$ GPa, $\\nu=0.3$, $\\sigma_0=100$ MPa, plane stress.\n",
    "\n",
    "**Reference.** For the circle, Kirsch's solution: $\\sigma_{tt}=\\sigma_0(1-2\\cos2\\theta)$ on the\n",
    "edge, $K_t=3$ (S. Timoshenko and J. N. Goodier, *Theory of Elasticity*, 3rd ed., McGraw-Hill\n",
    "(1970), Sec. 35). For square holes with rounded corners, W. D. Pilkey and D. F. Pilkey,\n",
    "*Peterson's Stress Concentration Factors*, 3rd ed., Wiley (2008), Ch. 4, shows the rise of the\n",
    "factor as the corners sharpen."
   ]
  },
  {
   "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 each plate, `section` its mid-plane region; the hole edge keeps its name\n",
    "`cut.hole`. The triangles are 0.25 mm on the hole edge and grade to 20 mm far from it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exponents = (2, 3, 4, 6, 10)\n",
    "plates = {\n",
    "    n: load(f\"superellipse_hole_stress_concentration{'' if n == 4 else f'_n{n}'}.step\")\n",
    "    for n in exponents\n",
    "}\n",
    "faces = plates[4].boundaries\n",
    "radius, thickness = 0.010, plates[4].size[2]\n",
    "regions = {\n",
    "    n: plate.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "    for n, plate in plates.items()\n",
    "}\n",
    "meshes = {\n",
    "    n: TriangularMesher(\n",
    "        target_size=0.02, grading=0.15, local_sizes={\"cut.hole\": 0.00025}\n",
    "    ).generate(region)\n",
    "    for n, region in regions.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    plates[4],\n",
    "    selection={\n",
    "        \"loaded\": faces.loaded,\n",
    "        \"hole\": faces.hole,\n",
    "        \"symmetry\": faces.symmetry_x | faces.symmetry_y,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=-70),\n",
    "    title=\"Quarter plate with the hole n = 4\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[4],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane mesh: {meshes[4].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, remote = 200e9, 0.3, 100e6\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson_ratio,\n",
    "    kinematics=\"plane_stress\",\n",
    "    thickness=thickness,\n",
    ")\n",
    "runs = {\n",
    "    n: steel.solve(\n",
    "        mesh=mesh,\n",
    "        times=(0.0,),\n",
    "        order=2,\n",
    "        tractions=((regions[n].boundaries.x_max, (remote, 0.0)),),\n",
    "        displacements=(\n",
    "            (regions[n].boundaries.x_min, \"x\", 0.0),\n",
    "            (regions[n].boundaries.y_min, \"y\", 0.0),\n",
    "        ),\n",
    "    )\n",
    "    for n, mesh in meshes.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "In plane stress Hooke's law gives the first invariant directly from the strain,\n",
    "$\\sigma_{xx}+\\sigma_{yy}=E(\\varepsilon_{xx}+\\varepsilon_{yy})/(1-\\nu)$; it is evaluated with the\n",
    "gradient of the displacement at 400 points along each hole edge, parametrised by the polar\n",
    "angle $\\theta$ from the load direction."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "invariant = (\n",
    "    lambda result, points: youngs_modulus\n",
    "    / (1 - poisson_ratio)\n",
    "    * np.trace(result.space.gradient(result.displacement[0], points), axis1=1, axis2=2)\n",
    ")\n",
    "theta = np.linspace(0.0, np.pi / 2, 400)\n",
    "edges = {\n",
    "    n: radius\n",
    "    * np.column_stack((np.cos(theta) ** (2 / n), np.sin(theta) ** (2 / n)))\n",
    "    * (1 + 1e-6)\n",
    "    for n in exponents\n",
    "}\n",
    "hoop = {n: invariant(runs[n], edges[n]) / remote for n in exponents}\n",
    "polar = {n: np.degrees(np.arctan2(edges[n][:, 1], edges[n][:, 0])) for n in exponents}\n",
    "\n",
    "print(\"exponent n   K_t      polar angle of the peak\")\n",
    "for n in exponents:\n",
    "    print(f\"{n:10d} {hoop[n].max():7.3f} {polar[n][np.argmax(hoop[n])]:12.1f}°\")\n",
    "print(\n",
    "    f\"circle: K_t {hoop[2].max():.4f} against Kirsch 3.0000 ({100 * (hoop[2].max() / 3 - 1):+.2f} %), largest deviation of the hoop \"\n",
    "    f\"stress along the edge from σ0(1 - 2cos2θ): {np.abs(hoop[2] - (1 - 2 * np.cos(2 * np.radians(polar[2])))).max():.3f} σ0\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The first stress invariant near the hole with $n=4$, the hoop stress along the five hole\n",
    "edges, and the stress concentration factor over the exponent."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mesh = meshes[4]\n",
    "fig = plots.figure(1, 3, size=(19, 5.5))\n",
    "plots.heatmap(\n",
    "    1e3 * mesh.coordinates[:, 0],\n",
    "    1e3 * mesh.coordinates[:, 1],\n",
    "    invariant(runs[4], mesh.coordinates) / 1e6,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(-100, 350),\n",
    "    label=\"σ_xx + σ_yy [MPa]\",\n",
    "    xlimits=(0, 30),\n",
    "    ylimits=(0, 30),\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"First stress invariant, n = 4\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={f\"n = {n}\": (polar[n], hoop[n]) for n in exponents},\n",
    "    reference={\"Kirsch, circle\": (np.degrees(theta), 1 - 2 * np.cos(2 * theta))},\n",
    "    hlines=0.0,\n",
    "    xlabel=\"polar angle θ from the load direction [°]\",\n",
    "    ylabel=\"hoop stress / σ0\",\n",
    "    title=\"Hoop stress along the hole edge\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    list(exponents),\n",
    "    {\"simulation\": [hoop[n].max() for n in exponents]},\n",
    "    markers=True,\n",
    "    hlines={\"Kirsch, circle\": 3.0},\n",
    "    xlabel=\"exponent n of the superellipse\",\n",
    "    ylabel=\"stress concentration factor K_t\",\n",
    "    title=\"From circle to square\",\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",
    "Stretch the hole to $|x/a|^n+|y/b|^n=1$ with $b\\neq a$ in\n",
    "`superellipse_hole_stress_concentration_geometry.py`, rotate it against the load, or load the\n",
    "plate in shear: the corners of a square hole are worst at $45°$ to the load."
   ]
  }
 ]
}
