{
 "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": [
    "# Singular stress at a re-entrant corner\n",
    "\n",
    "At a sharp inner corner the material surrounds the corner point over an angle of $270°$. The\n",
    "elastic field near such a corner was found by Williams (1952): the stresses vary like\n",
    "\n",
    "$$\\sigma_{ij}\\sim K\\,r^{\\lambda-1}f_{ij}(\\theta),$$\n",
    "\n",
    "where $r$ is the distance from the corner and $\\lambda$ the smallest root of the eigenvalue\n",
    "equation of the wedge. For the symmetric (opening) field of a wedge of opening $2\\alpha$ it is\n",
    "$\\lambda\\sin2\\alpha+\\sin(2\\alpha\\lambda)=0$; with $2\\alpha=3\\pi/2$ the root is\n",
    "$\\lambda=0.5445$, so the stress grows like $r^{-0.4555}$. The stress at the corner is infinite:\n",
    "a finer mesh always shows a higher peak, roughly by $2^{0.4555}=1.37$ for every halving of the\n",
    "cells next to the corner. A real part has a fillet, and with it the peak converges to a finite\n",
    "value.\n",
    "\n",
    "The plate, 100 mm x 100 mm with legs 50 mm wide and 5 mm thick, comes in two versions from\n",
    "`reentrant_corner_singular_stress.step` (sharp corner) and\n",
    "`reentrant_corner_singular_stress_fillet.step` (corner rounded to 2 mm); the script\n",
    "`reentrant_corner_singular_stress_geometry.py` builds both with the CAD objects of OneSimulation.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| end of the horizontal leg, $x=100$ mm (`fixed`) | $\\mathbf u=0$ |\n",
    "| end of the vertical leg, $y=100$ mm (`loaded`) | shear traction $(-10\\ \\mathrm{MPa},\\ 0)$, which opens the corner |\n",
    "| all other edges | traction free |\n",
    "\n",
    "Aluminium, $E=70$ GPa, $\\nu=0.33$, plane stress.\n",
    "\n",
    "**Reference.** M. L. Williams, *Stress singularities resulting from various boundary conditions\n",
    "in angular corners of plates in extension*, J. Appl. Mech. 19 (1952) 526; the exponent\n",
    "$\\lambda=0.5445$ for the $270°$ wedge is tabulated there."
   ]
  },
  {
   "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.derived import voigt, von_mises\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 plates with their named faces, `section` the mid-plane regions. The base mesh\n",
    "has 5 mm cells, 0.2 mm along the two edges that meet at the corner (and along the fillet); every\n",
    "refinement level splits each triangle into four."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plates = {\n",
    "    \"sharp corner\": load(\"reentrant_corner_singular_stress.step\"),\n",
    "    \"2 mm fillet\": load(\"reentrant_corner_singular_stress_fillet.step\"),\n",
    "}\n",
    "faces = plates[\"sharp corner\"].boundaries\n",
    "thickness = plates[\"sharp corner\"].size[2]\n",
    "regions = {\n",
    "    name: plate.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "    for name, plate in plates.items()\n",
    "}\n",
    "levels = (0, 1, 2, 3)\n",
    "meshes = {\n",
    "    name: [\n",
    "        TriangularMesher(\n",
    "            target_size=0.005,\n",
    "            grading=0.25,\n",
    "            refinements=level,\n",
    "            local_sizes={\n",
    "                side: 0.0002\n",
    "                for side in region.boundary_groups()\n",
    "                if side.startswith((\"cut\", \"fillet\"))\n",
    "            },\n",
    "        ).generate(region)\n",
    "        for level in levels\n",
    "    ]\n",
    "    for name, region in regions.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    plates[\"sharp corner\"],\n",
    "    selection={\"fixed\": faces.fixed, \"loaded\": faces.loaded, \"corner\": faces.corner},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=50, azimuth=-60),\n",
    "    title=\"L-shaped plate with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"sharp corner\"][1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane mesh after one refinement: {meshes['sharp corner'][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 on all eight meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate = SmallStrainSolid(\n",
    "    youngs_modulus=70e9,\n",
    "    poisson_ratio=0.33,\n",
    "    kinematics=\"plane_stress\",\n",
    "    thickness=thickness,\n",
    ")\n",
    "runs = {\n",
    "    name: [\n",
    "        plate.solve(\n",
    "            mesh=mesh,\n",
    "            times=(0.0,),\n",
    "            order=2,\n",
    "            tractions=((regions[name].boundaries.y_max, (-10e6, 0.0)),),\n",
    "            displacements=(\n",
    "                (regions[name].boundaries.x_max, \"x\", 0.0),\n",
    "                (regions[name].boundaries.x_max, \"y\", 0.0),\n",
    "            ),\n",
    "        )\n",
    "        for mesh in meshes[name]\n",
    "    ]\n",
    "    for name in regions\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The von Mises stress at the integration points. The peak is taken within 5 mm of the corner,\n",
    "away from the clamped end, which has a singularity of its own. Along the bisector of the corner,\n",
    "the line into the material at $45°$, the slope of the stress against the distance on a log-log\n",
    "scale is the exponent $\\lambda-1$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "corner = np.array([0.050, 0.050])\n",
    "mises = {\n",
    "    name: [von_mises(voigt(result.stress[0])) for result in results]\n",
    "    for name, results in runs.items()\n",
    "}\n",
    "near = {\n",
    "    name: [\n",
    "        np.linalg.norm(result.quadrature_coordinates - corner, axis=1) < 0.005\n",
    "        for result in results\n",
    "    ]\n",
    "    for name, results in runs.items()\n",
    "}\n",
    "peaks = {\n",
    "    name: [\n",
    "        stress[inside].max() / 1e6 for stress, inside in zip(mises[name], near[name])\n",
    "    ]\n",
    "    for name in runs\n",
    "}\n",
    "offset = runs[\"sharp corner\"][-1].quadrature_coordinates - corner\n",
    "distance = np.linalg.norm(offset, axis=1)\n",
    "bisector = (\n",
    "    np.abs(np.arctan2(-offset[:, 1], -offset[:, 0]) - np.pi / 4) < np.radians(4)\n",
    ") & (distance < 0.01)\n",
    "fitted = bisector & (distance > 5e-5) & (distance < 1e-3)\n",
    "slope = np.polyfit(\n",
    "    np.log(distance[fitted]), np.log(mises[\"sharp corner\"][-1][fitted]), 1\n",
    ")[0]\n",
    "\n",
    "print(\n",
    "    \"refinement   triangles   peak at the sharp corner [MPa]   peak at the 2 mm fillet [MPa]\"\n",
    ")\n",
    "for level in levels:\n",
    "    print(\n",
    "        f\"{level:10d} {meshes['sharp corner'][level].cell_count:11d} {peaks['sharp corner'][level]:32.1f} {peaks['2 mm fillet'][level]:31.1f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"growth of the sharp-corner peak per refinement: {', '.join(f'{b / a:.3f}' for a, b in zip(peaks['sharp corner'], peaks['sharp corner'][1:]))}\"\n",
    "    f\" (Williams: 2^0.4555 = {2**0.4555:.3f})\"\n",
    ")\n",
    "print(\n",
    "    f\"change of the fillet peak on the last refinement: {100 * (peaks['2 mm fillet'][-1] / peaks['2 mm fillet'][-2] - 1):+.2f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"exponent along the bisector between 0.05 and 1 mm: {slope:.4f}, Williams λ - 1 = -0.4555, deviation {100 * (slope / -0.4555 - 1):+.1f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The von Mises stress around the corner on the finest mesh of each plate, the stress along the\n",
    "bisector against the Williams power law, and the peak stress over the refinement: the sharp\n",
    "corner climbs without end, the fillet settles."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cells = {\n",
    "    name: mises[name][-1].reshape(meshes[name][-1].cell_count, -1).max(axis=1) / 1e6\n",
    "    for name in runs\n",
    "}\n",
    "fig = plots.figure(1, 3, size=(19, 5.5))\n",
    "plots.mesh(\n",
    "    meshes[\"sharp corner\"][-1],\n",
    "    cell_values=cells[\"sharp corner\"],\n",
    "    edges=False,\n",
    "    limits=(0, 300),\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Sharp corner, finest mesh\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"simulation, sharp corner\": (\n",
    "            1e3 * distance[bisector],\n",
    "            mises[\"sharp corner\"][-1][bisector] / 1e6,\n",
    "        )\n",
    "    },\n",
    "    reference={\n",
    "        \"Williams, r^-0.4555\": (\n",
    "            np.geomspace(0.01, 10, 50),\n",
    "            np.exp(\n",
    "                np.mean(\n",
    "                    np.log(mises[\"sharp corner\"][-1][fitted] / 1e6)\n",
    "                    + 0.4555 * np.log(1e3 * distance[fitted])\n",
    "                )\n",
    "            )\n",
    "            * np.geomspace(0.01, 10, 50) ** -0.4555,\n",
    "        )\n",
    "    },\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"distance from the corner along the bisector [mm]\",\n",
    "    ylabel=\"von Mises stress [MPa]\",\n",
    "    title=\"Power law along the bisector\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    [meshes[\"sharp corner\"][level].cell_count for level in levels],\n",
    "    peaks,\n",
    "    markers=True,\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"triangles\",\n",
    "    ylabel=\"peak von Mises stress near the corner [MPa]\",\n",
    "    title=\"Diverging and converging peaks\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the fillet radius in `reentrant_corner_singular_stress_geometry.py` and write the STEP\n",
    "files again: the converged peak follows the stress concentration charts for shoulder fillets.\n",
    "Evaluate the generalised stress intensity $K$ from the fitted line, or open the corner angle and\n",
    "watch the exponent go to zero at $180°$."
   ]
  }
 ]
}
