{
 "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 intensity factor of a single-edge crack\n",
    "\n",
    "Whether an existing crack grows is decided in linear elastic fracture mechanics by the\n",
    "**stress intensity factor** $K_I$: near the tip the stresses grow like $K_I/\\sqrt{2\\pi r}$, and\n",
    "the crack becomes unstable when $K_I$ reaches the fracture toughness $K_{Ic}$ of the material.\n",
    "$K_I$ depends on the load, the crack length and the shape of the part, so it has to be computed.\n",
    "\n",
    "The most robust way is the **J-integral** of Rice, the energy released per unit crack\n",
    "advance. As a domain integral over a ring around the tip it reads\n",
    "\n",
    "$$J=\\int_A\\Big(\\sigma_{ij}\\,\\frac{\\partial u_i}{\\partial x_1}-W\\,\\delta_{1j}\\Big)\\frac{\\partial q}{\\partial x_j}\\,\\mathrm dA ,\n",
    "  \\qquad K_I=\\sqrt{E\\,J}\\quad\\text{(plane stress)},$$\n",
    "\n",
    "with the strain energy density $W$ and a weight $q$ that is 1 inside the ring and 0 outside.\n",
    "$J$ is the same for every ring; checking that is part of the result.\n",
    "\n",
    "**Setup.** A steel plate ($E=200$ GPa, $\\nu=0.3$), width $W=100$ mm, height 400 mm, 10 mm\n",
    "thick, with an edge crack of length $a$ at half height, $a/W=0.2$, 0.3, 0.4 and 0.5, in plane\n",
    "stress. The plates come from the CAD files `edge_crack_stress_intensity_<a/W in %>.step`,\n",
    "written by `edge_crack_stress_intensity_geometry.py` with the CAD objects of OneSimulation; the\n",
    "crack is a sharp wedge 0.2 mm wide at its mouth.\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `y_min` (bottom) | held, $u_x=u_y=0$ |\n",
    "| `y_max` (top) | tension $\\sigma=100$ MPa |\n",
    "| `x_min`, `x_max`, `crack.side` | traction free |\n",
    "\n",
    "**Reference.** H. Tada, P.C. Paris and G.R. Irwin, *The Stress Analysis of Cracks Handbook*,\n",
    "3rd ed., ASME Press 2000: $K_I=\\sigma\\sqrt{\\pi a}\\,F(a/W)$ with\n",
    "$F=1.12-0.231\\,\\alpha+10.55\\,\\alpha^2-21.72\\,\\alpha^3+30.39\\,\\alpha^4$, $\\alpha=a/W$, accurate to\n",
    "0.5 % for $\\alpha\\le0.6$. Near the tip the crack opens like Irwin's profile\n",
    "$\\delta(r)=(8K_I/E)\\sqrt{r/2\\pi}$."
   ]
  },
  {
   "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, small_strain_j_integral\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 each plate, `section` its cross-section at half thickness with the names of the\n",
    "cut faces on its sides. The triangles are 0.5 mm at the crack tip and grow to 10 mm away from\n",
    "it; for the mesh study the plate with $a/W=0.3$ is also meshed with 2 mm and 1 mm at the tip."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ratios = (0.2, 0.3, 0.4, 0.5)\n",
    "plates = {\n",
    "    ratio: load(f\"edge_crack_stress_intensity_{round(100 * ratio)}.step\")\n",
    "    for ratio in ratios\n",
    "}\n",
    "width, height, thickness = plates[0.3].size\n",
    "sections = {\n",
    "    ratio: plate.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "    for ratio, plate in plates.items()\n",
    "}\n",
    "tips = {ratio: np.array([ratio * width, height / 2]) for ratio in ratios}\n",
    "graded = lambda tip, size: TriangularMesher(\n",
    "    target_size=0.01,\n",
    "    size_field=lambda p: np.minimum(\n",
    "        size + 0.3 * np.hypot(p[:, 0] - tip[0], p[:, 1] - tip[1]), 0.01\n",
    "    ),\n",
    ")\n",
    "meshes = {\n",
    "    ratio: graded(tips[ratio], 0.0005).generate(section)\n",
    "    for ratio, section in sections.items()\n",
    "}\n",
    "tip_sizes = [0.002, 0.001, 0.0005]\n",
    "study_meshes = [\n",
    "    graded(tips[0.3], size).generate(sections[0.3]) for size in tip_sizes[:2]\n",
    "] + [meshes[0.3]]\n",
    "\n",
    "faces = sections[0.3].boundaries\n",
    "fig = plots.figure(1, 2, size=(12, 7))\n",
    "plots.geometry(\n",
    "    plates[0.3],\n",
    "    selection={\n",
    "        \"held\": plates[0.3].boundaries.y_min,\n",
    "        \"pulled\": plates[0.3].boundaries.y_max,\n",
    "        \"crack\": plates[0.3].boundaries[\"crack.side\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-60),\n",
    "    title=\"Plate with a/W = 0.3\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0.3],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"a/W = 0.3: {meshes[0.3].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 virtual crack advance $q$ is a smooth step from 1\n",
    "inside the radius $r_1$ to 0 outside $r_2$; `small_strain_j_integral` takes its gradient and\n",
    "returns $J$ per unit thickness. Three rings: 2-6 mm, 4-10 mm and 6-15 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stress, youngs_modulus = 100e6, 200e9\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=0.3,\n",
    "    kinematics=\"plane_stress\",\n",
    "    thickness=thickness,\n",
    ")\n",
    "solve = lambda mesh, faces: steel.solve(\n",
    "    mesh=mesh,\n",
    "    times=(0.0,),\n",
    "    order=2,\n",
    "    displacements=((faces.y_min, \"x\", 0.0), (faces.y_min, \"y\", 0.0)),\n",
    "    tractions=((faces.y_max, (0.0, stress)),),\n",
    ")\n",
    "results = {\n",
    "    ratio: solve(meshes[ratio], section.boundaries)\n",
    "    for ratio, section in sections.items()\n",
    "}\n",
    "study = [solve(mesh, faces) for mesh in study_meshes]\n",
    "advance = lambda tip, inner, outer: lambda p: np.einsum(\n",
    "    \"i,q,qj->qij\",\n",
    "    (1.0, 0.0),\n",
    "    -6\n",
    "    * (s := np.clip((np.hypot(*(p - tip).T) - inner) / (outer - inner), 0, 1))\n",
    "    * (1 - s)\n",
    "    / ((outer - inner) * np.hypot(*(p - tip).T)),\n",
    "    p - tip,\n",
    ")\n",
    "rings = [(0.002, 0.006), (0.004, 0.010), (0.006, 0.015)]\n",
    "intensity = {\n",
    "    ratio: [\n",
    "        np.sqrt(\n",
    "            youngs_modulus\n",
    "            * small_strain_j_integral(result, advance(tips[ratio], *ring))\n",
    "        )\n",
    "        for ring in rings\n",
    "    ]\n",
    "    for ratio, result in results.items()\n",
    "}\n",
    "study_intensity = [\n",
    "    [\n",
    "        np.sqrt(\n",
    "            youngs_modulus * small_strain_j_integral(result, advance(tips[0.3], *ring))\n",
    "        )\n",
    "        for ring in rings\n",
    "    ]\n",
    "    for result in study\n",
    "]\n",
    "tada = (\n",
    "    lambda a: stress\n",
    "    * np.sqrt(np.pi * a * width)\n",
    "    * (1.12 - 0.231 * a + 10.55 * a**2 - 21.72 * a**3 + 30.39 * a**4)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "$K_I$ on the three rings for every crack length against the handbook, and the mesh study for\n",
    "$a/W=0.3$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{'a/W':>5s} {'triangles':>10s} {'K_I, ring 1':>12s} {'ring 2':>9s} {'ring 3':>9s} {'Tada':>9s} {'deviation':>10s}  [MPa m^0.5]\"\n",
    ")\n",
    "for ratio in ratios:\n",
    "    values = intensity[ratio]\n",
    "    print(\n",
    "        f\"{ratio:5.1f} {meshes[ratio].cell_count:10d} {values[0] / 1e6:12.3f} {values[1] / 1e6:9.3f} {values[2] / 1e6:9.3f}\"\n",
    "        f\" {tada(ratio) / 1e6:9.3f} {100 * (np.mean(values) / tada(ratio) - 1):+9.2f} %\"\n",
    "    )\n",
    "print(\n",
    "    \"mesh study, a/W = 0.3: size at the tip [mm], mean K_I [MPa m^0.5], deviation from Tada\"\n",
    ")\n",
    "for size, values in zip(tip_sizes, study_intensity):\n",
    "    print(\n",
    "        f\"  {1e3 * size:4.1f} mm   {np.mean(values) / 1e6:8.3f}   {100 * (np.mean(values) / tada(0.3) - 1):+6.2f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"change between the two finest meshes: {100 * convergence([np.mean(v) for v in study_intensity], tip_sizes).change:.2f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The vertical displacement around the crack of $a/W=0.3$, the normalised stress intensity\n",
    "$F=K_I/\\sigma\\sqrt{\\pi a}$ against the handbook curve, the mesh study on the three rings, and the\n",
    "crack opening behind the tip against Irwin's profile."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, tip = results[0.3], tips[0.3]\n",
    "nodes = len(meshes[0.3].coordinates)\n",
    "behind = np.linspace(2e-4, 0.25 * tip[0], 60)\n",
    "opening = (\n",
    "    result.evaluate_displacement(\n",
    "        np.column_stack((tip[0] - behind, np.full_like(behind, tip[1] + 6e-4)))\n",
    "    )[:, 1]\n",
    "    - result.evaluate_displacement(\n",
    "        np.column_stack((tip[0] - behind, np.full_like(behind, tip[1] - 6e-4)))\n",
    "    )[:, 1]\n",
    ")\n",
    "alpha = np.linspace(0.15, 0.55, 81)\n",
    "fig = plots.figure(2, 2, size=(14, 11))\n",
    "plots.heatmap(\n",
    "    1e3 * result.coordinates[:nodes, 0],\n",
    "    1e3 * result.coordinates[:nodes, 1],\n",
    "    1e6 * result.displacement[0, :nodes, 1],\n",
    "    triangles=np.asarray(meshes[0.3].cells),\n",
    "    limits=(60, 240),\n",
    "    contours=12,\n",
    "    label=\"u_y [µm]\",\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    xlimits=(0, 60),\n",
    "    ylimits=(180, 220),\n",
    "    title=\"Vertical displacement, a/W = 0.3\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"ring {k + 1}\": (\n",
    "            np.array(ratios),\n",
    "            [\n",
    "                intensity[ratio][k] / (stress * np.sqrt(np.pi * ratio * width))\n",
    "                for ratio in ratios\n",
    "            ],\n",
    "        )\n",
    "        for k in range(3)\n",
    "    },\n",
    "    reference={\n",
    "        \"Tada, Paris and Irwin\": (\n",
    "            alpha,\n",
    "            tada(alpha) / (stress * np.sqrt(np.pi * alpha * width)),\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"a / W\",\n",
    "    ylabel=\"F = K_I / (σ √(πa))\",\n",
    "    title=\"Geometry factor of the edge crack\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"ring {k + 1}\": (\n",
    "            1e3 * np.array(tip_sizes),\n",
    "            [values[k] / 1e6 for values in study_intensity],\n",
    "        )\n",
    "        for k in range(3)\n",
    "    },\n",
    "    hlines={\"Tada, Paris and Irwin\": tada(0.3) / 1e6},\n",
    "    ylimits=(0.99 * tada(0.3) / 1e6, 1.005 * tada(0.3) / 1e6),\n",
    "    xlabel=\"element size at the tip [mm]\",\n",
    "    ylabel=\"K_I [MPa m^0.5]\",\n",
    "    title=\"Mesh study, a/W = 0.3\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"simulation\": (1e3 * behind, 1e6 * opening)},\n",
    "    reference={\n",
    "        \"Irwin's profile with the handbook K_I\": (\n",
    "            1e3 * behind,\n",
    "            1e6 * 8 * tada(0.3) / youngs_modulus * np.sqrt(behind / (2 * np.pi)),\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"distance behind the tip r [mm]\",\n",
    "    ylabel=\"crack opening δ [µm]\",\n",
    "    title=\"Crack opening near the tip, a/W = 0.3\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the crack length or the plate height in `edge_crack_stress_intensity_geometry.py` and\n",
    "write the STEP files again; at small heights the bending constraint of the held end lowers\n",
    "$K_I$. Compare with the fracture toughness of a steel (about 50 MPa m$^{0.5}$) to find the\n",
    "critical stress for each crack length."
   ]
  }
 ]
}
