{
 "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": [
    "# Mixed-mode stress intensity of an angled crack\n",
    "\n",
    "A crack that is not perpendicular to the load is opened and sheared at the same time. Near its\n",
    "tip the stresses are the sum of the two singular fields of Williams, weighted by the stress\n",
    "intensity factors $K_I$ (opening) and $K_{II}$ (in-plane sliding); both decide whether and in\n",
    "which direction the crack grows.\n",
    "\n",
    "The **interaction integral** separates them. It superposes the computed field with an\n",
    "auxiliary Williams field of a single mode and evaluates the J-integral of the sum as a domain\n",
    "integral over a ring around the tip; the cross term is proportional to the stress intensity\n",
    "factor of that mode:\n",
    "\n",
    "$$I^{(m)}=\\int_A\\Big(\\sigma_{ij}\\frac{\\partial u^{(m)}_i}{\\partial x_1}+\\sigma^{(m)}_{ij}\\frac{\\partial u_i}{\\partial x_1}\n",
    "  -\\sigma_{kl}\\varepsilon^{(m)}_{kl}\\,\\delta_{1j}\\Big)\\frac{\\partial q}{\\partial x_j}\\,\\mathrm dA,\\qquad\n",
    "  K_m=\\tfrac12E'\\,I^{(m)},$$\n",
    "\n",
    "with $x_1$ along the crack, the virtual advance $q$ and $E'=E/(1-\\nu^2)$ in plane strain.\n",
    "\n",
    "**Setup.** A steel plate ($E=200$ GPa, $\\nu=0.3$) 200 mm × 200 mm with a central crack of length\n",
    "$2a=20$ mm at the angle $\\beta=0°$, 30°, 45° and 60° to the plate edges, pulled by\n",
    "$\\sigma=100$ MPa; plane strain. The plates come from the CAD files\n",
    "`angled_crack_mixed_mode_<β>.step`, written by `angled_crack_mixed_mode_geometry.py` with the CAD\n",
    "objects of OneSimulation; the crack is a slender cut with sharp tips.\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `y_min` | roller, $u_y=0$ |\n",
    "| `x_min` | roller, $u_x=0$ (the plate contracts freely) |\n",
    "| `y_max` | tension $\\sigma$ |\n",
    "| `x_max`, `crack.side` | traction free |\n",
    "\n",
    "**Reference.** For a crack in a large plate, Y. Murakami (ed.), *Stress Intensity Factors\n",
    "Handbook*, Pergamon 1987, Case 1.1 (after Erdogan and Sih):\n",
    "$K_I=\\sigma\\sqrt{\\pi a}\\cos^2\\beta$, $K_{II}=\\sigma\\sqrt{\\pi a}\\sin\\beta\\cos\\beta$. With\n",
    "$a$ one tenth of the half width, the finite plate raises both by about 0.6 %."
   ]
  },
  {
   "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 (\n",
    "    SmallStrainSolid,\n",
    "    crack_tip_advance,\n",
    "    small_strain_interaction_integrals,\n",
    "    williams_auxiliary_fields,\n",
    ")\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 with the names of the cut faces. The\n",
    "triangles are 0.25 mm at both crack tips and grow to 15 mm away from them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "angles = (0, 30, 45, 60)\n",
    "plates = {beta: load(f\"angled_crack_mixed_mode_{beta}.step\") for beta in angles}\n",
    "side, _, thickness = plates[0].size\n",
    "sections = {\n",
    "    beta: plate.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "    for beta, plate in plates.items()\n",
    "}\n",
    "half_length = 0.010\n",
    "direction = {\n",
    "    beta: np.array([np.cos(np.radians(beta)), np.sin(np.radians(beta))])\n",
    "    for beta in angles\n",
    "}\n",
    "tips = {beta: side / 2 + half_length * direction[beta] for beta in angles}\n",
    "meshes = {\n",
    "    beta: TriangularMesher(\n",
    "        target_size=0.015,\n",
    "        size_field=lambda p, beta=beta: np.minimum(\n",
    "            0.00025\n",
    "            + 0.25\n",
    "            * np.minimum(\n",
    "                np.hypot(*(p[:, :2] - tips[beta]).T),\n",
    "                np.hypot(*(p[:, :2] - (side - tips[beta])).T),\n",
    "            ),\n",
    "            0.015,\n",
    "        ),\n",
    "    ).generate(section)\n",
    "    for beta, section in sections.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6.5))\n",
    "plots.geometry(\n",
    "    plates[30],\n",
    "    selection={\n",
    "        \"rollers\": plates[30].boundaries.y_min | plates[30].boundaries.x_min,\n",
    "        \"pulled\": plates[30].boundaries.y_max,\n",
    "        \"crack\": plates[30].boundaries[\"crack.side\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=-60),\n",
    "    title=\"Plate with the crack at 30°\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[30],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"β = 30°: {meshes[30].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Plane strain with quadratic triangles. For each angle the Williams fields are set up in the\n",
    "frame of the right-hand tip, and the interaction integral is evaluated on two rings,\n",
    "1.5-4 mm and 2.5-6 mm around it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stress, youngs_modulus, poisson = 100e6, 200e9, 0.3\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson,\n",
    "    kinematics=\"plane_strain\",\n",
    "    thickness=thickness,\n",
    ")\n",
    "results = {\n",
    "    beta: steel.solve(\n",
    "        mesh=meshes[beta],\n",
    "        times=(0.0,),\n",
    "        order=2,\n",
    "        tractions=((section.boundaries.y_max, (0.0, stress)),),\n",
    "        displacements=(\n",
    "            (section.boundaries.y_min, \"y\", 0.0),\n",
    "            (section.boundaries.x_min, \"x\", 0.0),\n",
    "        ),\n",
    "    )\n",
    "    for beta, section in sections.items()\n",
    "}\n",
    "rings = ((0.0015, 0.004), (0.0025, 0.006))\n",
    "intensity = {}\n",
    "for beta, result in results.items():\n",
    "    fields = williams_auxiliary_fields(\n",
    "        tips[beta], np.radians(beta), youngs_modulus, poisson, \"plane_strain\"\n",
    "    )\n",
    "    intensity[beta] = [\n",
    "        0.5\n",
    "        * fields.effective_modulus\n",
    "        * small_strain_interaction_integrals(\n",
    "            result, crack_tip_advance(tips[beta], direction[beta], *ring), fields\n",
    "        )\n",
    "        for ring in rings\n",
    "    ]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "$K_I$ and $K_{II}$ on both rings for every angle against the handbook values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "scale = stress * np.sqrt(np.pi * half_length)\n",
    "murakami = lambda beta: scale * np.array(\n",
    "    [np.cos(np.radians(beta)) ** 2, np.sin(np.radians(beta)) * np.cos(np.radians(beta))]\n",
    ")\n",
    "print(\n",
    "    f\"{'β':>4s} {'triangles':>9s} {'K_I ring 1':>11s} {'ring 2':>8s} {'handbook':>9s} {'dev.':>7s}   {'K_II ring 1':>11s} {'ring 2':>8s} {'handbook':>9s} {'dev.':>7s}  [MPa m^0.5]\"\n",
    ")\n",
    "for beta in angles:\n",
    "    ring1, ring2 = (np.asarray(values) / 1e6 for values in intensity[beta])\n",
    "    exact = murakami(beta) / 1e6\n",
    "    deviation = [\n",
    "        (\n",
    "            f\"{100 * ((ring1[k] + ring2[k]) / 2 / exact[k] - 1):+6.2f}%\"\n",
    "            if exact[k]\n",
    "            else f\"{'—':>7s}\"\n",
    "        )\n",
    "        for k in range(2)\n",
    "    ]\n",
    "    print(\n",
    "        f\"{beta:3d}° {meshes[beta].cell_count:9d} {ring1[0]:11.3f} {ring2[0]:8.3f} {exact[0]:9.3f} {deviation[0]}\"\n",
    "        f\"   {ring1[1]:11.3f} {ring2[1]:8.3f} {exact[1]:9.3f} {deviation[1]}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The vertical displacement around the crack at 45°, and both stress intensity factors over the\n",
    "crack angle with the handbook curves."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, nodes = results[45], len(meshes[45].coordinates)\n",
    "beta_line = np.linspace(0, 90, 181)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\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[45].cells),\n",
    "    limits=(25, 60),\n",
    "    contours=12,\n",
    "    label=\"u_y [µm]\",\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    xlimits=(80, 120),\n",
    "    ylimits=(80, 120),\n",
    "    title=\"Vertical displacement around the crack at 45°\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"K_{mode}, ring {k + 1}\": (\n",
    "            np.array(angles),\n",
    "            [intensity[beta][k][m] / scale for beta in angles],\n",
    "        )\n",
    "        for m, mode in enumerate((\"I\", \"II\"))\n",
    "        for k in range(2)\n",
    "    },\n",
    "    reference={\n",
    "        \"K_I, handbook\": (beta_line, np.cos(np.radians(beta_line)) ** 2),\n",
    "        \"K_II, handbook\": (\n",
    "            beta_line,\n",
    "            np.sin(np.radians(beta_line)) * np.cos(np.radians(beta_line)),\n",
    "        ),\n",
    "    },\n",
    "    xlabel=\"crack angle β [°]\",\n",
    "    ylabel=\"K / (σ √(πa))\",\n",
    "    title=\"Stress intensity factors over the crack angle\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "The two factors give the direction of crack growth, for example by the maximum tangential\n",
    "stress criterion (`maximum_tangential_stress_angle`). Lengthen the crack in\n",
    "`angled_crack_mixed_mode_geometry.py` to see the finite width raise both factors."
   ]
  }
 ]
}
