{
 "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 around a small hole in a large plate (Kirsch)\n",
    "\n",
    "A thin plate with a circular hole of radius $a$ carries a uniform tension $\\sigma_0$ in the\n",
    "$x$ direction far from the hole. For an infinite plate Kirsch (1898) found the stress field in\n",
    "closed form. In polar coordinates about the hole centre, with the angle $\\theta$ measured from\n",
    "the load direction, the hoop stress is\n",
    "\n",
    "$$\\sigma_{\\theta\\theta}(r,\\theta)=\\frac{\\sigma_0}{2}\\Big(1+\\frac{a^2}{r^2}\\Big)\n",
    "  -\\frac{\\sigma_0}{2}\\Big(1+\\frac{3a^4}{r^4}\\Big)\\cos 2\\theta .$$\n",
    "\n",
    "At the edge of the hole it reaches $3\\sigma_0$ at $\\theta=90°$ (stress concentration factor\n",
    "$K_t=3$) and $-\\sigma_0$ at $\\theta=0$, and it decays to the remote value within a few hole\n",
    "radii.\n",
    "\n",
    "The plate is modelled as a quarter, a square of half-width $L=20a$, from the CAD file\n",
    "`kirsch_plate_hole_stress.step`; the script `kirsch_plate_hole_stress_geometry.py` builds it with\n",
    "the CAD objects of OneSimulation and also writes plates with $L=5a$, $10a$ and $40a$ for the\n",
    "plate-size study. The plate is thin and loaded in its plane, so the model is plane stress on its\n",
    "mid-plane.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| $x=0$ (`symmetry_x`) | $u_x=0$ |\n",
    "| $y=0$ (`symmetry_y`) | $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$, $a=10$ mm, $\\sigma_0=100$ MPa.\n",
    "\n",
    "**Reference.** G. Kirsch, *Die Theorie der Elastizität und die Bedürfnisse der\n",
    "Festigkeitslehre*, Zeitschrift des VDI 42 (1898); S. Timoshenko and J. N. Goodier, *Theory of\n",
    "Elasticity*, 3rd ed., McGraw-Hill (1970), Sec. 35. The hoop stress comes from\n",
    "`kirsch_hole_hoop_stress` of OneSimulation."
   ]
  },
  {
   "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, kirsch_hole_hoop_stress\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 quarter plate with its named faces; `section` cuts it at half thickness and\n",
    "returns the planar region, whose sides keep the names of the faces they were cut from. The\n",
    "triangles are graded from the hole, where three meshes use cells of $a/10$, $a/20$ and $a/40$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plates = {\n",
    "    size: load(f\"kirsch_plate_hole_stress{suffix}.step\")\n",
    "    for size, suffix in ((5, \"_5a\"), (10, \"_10a\"), (20, \"\"), (40, \"_40a\"))\n",
    "}\n",
    "plate = plates[20]\n",
    "faces = plate.boundaries\n",
    "radius, thickness = 0.010, plate.size[2]\n",
    "sections = {\n",
    "    size: part.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "    for size, part in plates.items()\n",
    "}\n",
    "mesher = lambda cell: TriangularMesher(\n",
    "    target_size=2 * radius, grading=0.15, local_sizes={\"hole.outer_wall\": cell}\n",
    ")\n",
    "cells = [radius / 10, radius / 20, radius / 40]\n",
    "meshes = [mesher(cell).generate(sections[20]) for cell in cells]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    plate,\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, L = 20a\",\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 same model is solved on the three meshes of the\n",
    "reference plate and, with the finest hole cells, on the four plate sizes."
   ]
  },
  {
   "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",
    "solve = lambda mesh, sides: steel.solve(\n",
    "    mesh=mesh,\n",
    "    times=(0.0,),\n",
    "    order=2,\n",
    "    displacements=((sides.x_min, \"x\", 0.0), (sides.y_min, \"y\", 0.0)),\n",
    "    tractions=((sides.x_max, (remote, 0.0)),),\n",
    ")\n",
    "results = [solve(mesh, sections[20].boundaries) for mesh in meshes]\n",
    "sized = {\n",
    "    size: solve(mesher(cells[-1]).generate(region), region.boundaries)\n",
    "    for size, region in sections.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The stress follows from the gradient of the quadratic displacement field, evaluated with\n",
    "Hooke's law for plane stress at any point of the plate: at the hole edge, along the two symmetry\n",
    "lines and on the mesh nodes for the map."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hooke = (\n",
    "    lambda result, points: youngs_modulus\n",
    "    / (1 - poisson_ratio**2)\n",
    "    * (\n",
    "        lambda g: np.stack(\n",
    "            (\n",
    "                g[:, 0, 0] + poisson_ratio * g[:, 1, 1],\n",
    "                g[:, 1, 1] + poisson_ratio * g[:, 0, 0],\n",
    "                (1 - poisson_ratio) / 2 * (g[:, 0, 1] + g[:, 1, 0]),\n",
    "            ),\n",
    "            axis=-1,\n",
    "        )\n",
    "    )(result.space.gradient(result.displacement[0], np.atleast_2d(points)))\n",
    ")\n",
    "peaks = [hooke(result, (0.0, radius))[0, 0] / remote for result in results]\n",
    "size_peaks = {\n",
    "    size: hooke(result, (0.0, radius))[0, 0] / remote for size, result in sized.items()\n",
    "}\n",
    "study = convergence(peaks, cells)\n",
    "distance = np.linspace(0.0, 4 * radius, 81)\n",
    "above = hooke(\n",
    "    results[-1], np.column_stack((np.zeros_like(distance), radius + distance))\n",
    ")[:, 0]\n",
    "beside = hooke(\n",
    "    results[-1], np.column_stack((radius + distance, np.zeros_like(distance)))\n",
    ")[:, 1]\n",
    "\n",
    "print(\n",
    "    f\"stress concentration at the hole edge, θ = 90°: simulation {peaks[-1]:.4f}, Kirsch 3.0000, deviation {100 * (peaks[-1] / 3 - 1):+.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"hoop stress at the hole edge, θ = 0: simulation {beside[0] / remote:.4f} σ0, Kirsch -1.0000 σ0\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation from Kirsch along the two symmetry lines up to 5a: \"\n",
    "    f\"{100 * max(np.abs(above - kirsch_hole_hoop_stress(distance, radius, remote, np.pi / 2)).max(), np.abs(beside - kirsch_hole_hoop_stress(distance, radius, remote, 0.0)).max()) / remote:.2f} % of σ0\"\n",
    ")\n",
    "print(\"hole cell size   triangles   K_t\")\n",
    "for cell, mesh, peak in zip(cells, meshes, peaks):\n",
    "    print(f\"a/{radius / cell:<14.0f} {mesh.cell_count:9d} {peak:9.4f}\")\n",
    "print(f\"observed order {study.order:.1f}, extrapolated K_t {study.extrapolated:.4f}\")\n",
    "print(\"plate half-width   K_t      deviation from 3\")\n",
    "for size, peak in size_peaks.items():\n",
    "    print(f\"{size:>14d}a {peak:8.4f} {100 * (peak / 3 - 1):+10.2f} %\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The stress $\\sigma_{xx}$ near the hole, the hoop stress along the two symmetry lines against\n",
    "Kirsch, and the stress concentration factor over the plate size: the finite plate approaches\n",
    "the infinite one as $a/L$ goes to zero."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mesh = meshes[-1]\n",
    "nodal = hooke(results[-1], mesh.coordinates)[:, 0] / 1e6\n",
    "fine = np.linspace(0.0, 4 * radius, 300)\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.heatmap(\n",
    "    1e3 * mesh.coordinates[:, 0],\n",
    "    1e3 * mesh.coordinates[:, 1],\n",
    "    nodal,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(-100, 300),\n",
    "    contours=0,\n",
    "    label=\"σ_xx [MPa]\",\n",
    "    xlimits=(0, 30),\n",
    "    ylimits=(0, 30),\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"σ_xx around the hole\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"θ = 90°, along x = 0\": (distance[::3] / radius, above[::3] / remote),\n",
    "        \"θ = 0, along y = 0\": (distance[::3] / radius, beside[::3] / remote),\n",
    "    },\n",
    "    reference={\n",
    "        \"Kirsch, θ = 90°\": (\n",
    "            fine / radius,\n",
    "            kirsch_hole_hoop_stress(fine, radius, remote, np.pi / 2) / remote,\n",
    "        ),\n",
    "        \"Kirsch, θ = 0\": (\n",
    "            fine / radius,\n",
    "            kirsch_hole_hoop_stress(fine, radius, remote, 0.0) / remote,\n",
    "        ),\n",
    "    },\n",
    "    hlines=0.0,\n",
    "    xlabel=\"distance from the hole edge (r - a)/a\",\n",
    "    ylabel=\"hoop stress / σ0\",\n",
    "    title=\"Hoop stress along the symmetry lines\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    [1 / size for size in size_peaks],\n",
    "    {\"simulation, L = 5a, 10a, 20a, 40a\": list(size_peaks.values())},\n",
    "    markers=True,\n",
    "    hlines={\"Kirsch, infinite plate\": 3.0},\n",
    "    xlimits=(0, 0.21),\n",
    "    ylimits=(2.9, 3.4),\n",
    "    xlabel=\"hole radius / plate half-width a/L\",\n",
    "    ylabel=\"stress concentration factor K_t\",\n",
    "    title=\"From the finite to the infinite plate\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the circle in `kirsch_plate_hole_stress_geometry.py` by an ellipse and compare with\n",
    "Inglis' formula $K_t=1+2b/c$, or load the plate in both directions: biaxial tension lowers\n",
    "the concentration to 2, pure shear raises it to 4."
   ]
  }
 ]
}
