{
 "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": [
    "# Brittle fracture of a holed plate\n",
    "\n",
    "In a plate with a notch and an off-centre hole the crack does not run straight: it starts at the\n",
    "notch tip, is attracted by the stress concentration of the hole, runs into it and finally breaks\n",
    "the remaining ligament on the other side. Such tests are used to check that a fracture model\n",
    "finds crack paths by itself (M. Ambati, T. Gerasimov, L. De Lorenzis, Comput. Mech. 55, 2015,\n",
    "383-405, after experiments on a plate of this type).\n",
    "\n",
    "The **phase-field model** smears the crack into a damage field $d\\in[0,1]$ of width $\\sim\\ell$; the\n",
    "displacement and the damage minimise\n",
    "\n",
    "$$\\Pi(\\mathbf u,d)=\\int_\\Omega\\Big[(1-d)^2\\,\\psi^+(\\boldsymbol\\varepsilon)+\\psi^-(\\boldsymbol\\varepsilon)\\Big]\\,\\mathrm dV\n",
    "  +\\frac{G_c}{2\\ell}\\int_\\Omega\\big(d^2+\\ell^2|\\nabla d|^2\\big)\\,\\mathrm dV-W_\\mathrm{ext}\n",
    "  \\quad\\text{with}\\quad\\dot d\\ge0 ,$$\n",
    "\n",
    "where only the tensile part $\\psi^+$ of the strain energy drives the crack.\n",
    "\n",
    "**Setup.** A plate 65 mm × 120 mm, 1 mm thick, with a hole of 20 mm diameter at (36.5, 51) mm\n",
    "and a sharp notch 10 mm long at a height of 65 mm; $E=5.98$ GPa, $\\nu=0.22$,\n",
    "$G_c=2.28$ N/mm (the material values of Ambati et al.), regularisation length $\\ell=2$ mm,\n",
    "plane stress. The plate comes from the CAD file `holed_plate_phase_field.step`, written by\n",
    "`holed_plate_phase_field_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| side | displacement | damage |\n",
    "|---|---|---|\n",
    "| `y_min` | $u_x=u_y=0$ | zero flux |\n",
    "| `y_max` | $u_x=0$, $u_y=\\delta(t)$ | zero flux |\n",
    "| `x_min`, `x_max`, `hole.outer_wall`, `notch.side` | traction free | zero flux |\n",
    "\n",
    "**Reference.** Griffith's energy balance: the energy dissipated in forming the crack equals $G_c$\n",
    "times the crack area, up to the overestimate $h/2\\ell$ of the regularised functional on a mesh\n",
    "of size $h$. The crack length is measured in the damage field: the area where $d>1/2$, divided by\n",
    "the width of this band on the straight last branch of the crack."
   ]
  },
  {
   "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 PhaseFieldFracture\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",
    "`section` cuts the plate at half thickness; the cut faces keep their names. The triangles are\n",
    "0.8 mm in the region between the notch, the hole and the right edge, where the crack is\n",
    "expected, and grow to 5 mm elsewhere."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate = load(\"holed_plate_phase_field.step\")\n",
    "width, height, thickness = plate.size\n",
    "plane = plate.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "faces = plane.boundaries\n",
    "mm, h, ell = 1e-3, 0.8e-3, 2e-3\n",
    "outside = lambda p, x0, x1, y0, y1: np.hypot(\n",
    "    np.maximum(np.maximum(x0 - p[:, 0], p[:, 0] - x1), 0),\n",
    "    np.maximum(np.maximum(y0 - p[:, 1], p[:, 1] - y1), 0),\n",
    ")\n",
    "mesh = TriangularMesher(\n",
    "    target_size=5 * mm,\n",
    "    size_field=lambda p: np.minimum(\n",
    "        h\n",
    "        + 0.25\n",
    "        * np.minimum(\n",
    "            outside(p, 8 * mm, 48 * mm, 50 * mm, 72 * mm),\n",
    "            outside(p, 44 * mm, 65 * mm, 35 * mm, 60 * mm),\n",
    "        ),\n",
    "        5 * mm,\n",
    "    ),\n",
    ").generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 9))\n",
    "plots.geometry(\n",
    "    plane,\n",
    "    selection={\n",
    "        \"held\": faces.y_min,\n",
    "        \"pulled\": faces.y_max,\n",
    "        \"hole\": faces[\"hole.outer_wall\"],\n",
    "        \"notch\": faces[\"notch.side\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Plate with a hole and a notch\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh, groups=(\"all\",), legend=False, title=f\"{mesh.cell_count} triangles\", ax=fig[1]\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The top edge moves up in 55 steps, finely after 0.3 mm. Each step alternates between equilibrium\n",
    "and damage until the damage changes by less than $10^{-3}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "toughness = 2280.0\n",
    "lift = np.r_[0.0, 0.1, 0.2, 0.3, np.arange(0.31, 0.8001, 0.01)] * mm\n",
    "result = PhaseFieldFracture(\n",
    "    youngs_modulus=5.98e9,\n",
    "    poisson_ratio=0.22,\n",
    "    fracture_energy=toughness,\n",
    "    length_scale=ell,\n",
    "    thickness=thickness,\n",
    "    plane_stress=True,\n",
    ").solve(\n",
    "    mesh=mesh,\n",
    "    times=lift,\n",
    "    tolerance=1e-3,\n",
    "    max_iterations=3000,\n",
    "    displacements=(\n",
    "        (faces.y_min, \"x\", 0.0),\n",
    "        (faces.y_min, \"y\", 0.0),\n",
    "        (faces.y_max, \"x\", 0.0),\n",
    "        (faces.y_max, \"y\", lambda t: t),\n",
    "    ),\n",
    ")\n",
    "x, y = result.coordinates.T\n",
    "force = result.reactions[:, np.isclose(y, height), 1].sum(axis=1)\n",
    "peak = int(np.argmax(force))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The crack length from the area with $d>1/2$ (integrated over the triangles) and the band width\n",
    "on the straight branch between x = 50 and 62 mm, the dissipated\n",
    "energy, and Griffith's $G_c$ times the crack area with and without the mesh overestimate. The AT2\n",
    "model also damages the material diffusely around the hole and the notch before the crack forms\n",
    "(it has no elastic range); that energy comes on top of the crack itself."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cells = np.asarray(mesh.cells)\n",
    "corners = np.asarray(mesh.coordinates)[cells][:, :, :2]\n",
    "edges = corners[:, 1:] - corners[:, :1]\n",
    "areas = 0.5 * np.abs(edges[:, 0, 0] * edges[:, 1, 1] - edges[:, 0, 1] * edges[:, 1, 0])\n",
    "broken = result.damage[-1][cells].mean(axis=1) > 0.5\n",
    "straight = (corners[:, :, 0].mean(axis=1) > 50 * mm) & (\n",
    "    corners[:, :, 0].mean(axis=1) < 62 * mm\n",
    ")\n",
    "band = areas @ (broken & straight) / (12 * mm)\n",
    "crack_length = areas @ broken / band\n",
    "griffith = toughness * crack_length * thickness\n",
    "print(\n",
    "    f\"peak force {force[peak]:.1f} N at δ = {lift[peak] / mm:.2f} mm; force at the end {force[-1]:.2f} N\"\n",
    ")\n",
    "print(\n",
    "    f\"width of the broken band (d > 1/2) on the straight branch: {band / mm:.2f} mm (AT2 profile on a fine mesh: 2 l ln 2 = {2 * ell * np.log(2) / mm:.2f} mm)\"\n",
    ")\n",
    "print(\n",
    "    f\"crack length = broken area / band width: {crack_length / mm:.1f} mm (straight-line distances: notch tip to hole \"\n",
    "    f\"{np.hypot(36.5 - 10, 65 - 51) - 10:.0f} mm, hole to right edge {65 - 46.5:.1f} mm)\"\n",
    ")\n",
    "print(\n",
    "    f\"dissipated energy {1e3 * result.fracture_energy[-1]:.2f} mJ, G_c a t = {1e3 * griffith:.2f} mJ, \"\n",
    "    f\"with h/2l: {1e3 * griffith * (1 + h / (2 * ell)):.2f} mJ; ratio {result.fracture_energy[-1] / (griffith * (1 + h / (2 * ell))):.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The damage before the peak, at the crack's arrival at the hole and at the end, and the\n",
    "force-displacement curve with the energies."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "arrival = int(\n",
    "    np.argmax(\n",
    "        result.damage[:, np.hypot(x - 36.5 * mm, y - 51 * mm) < 10.5 * mm].max(axis=1)\n",
    "        > 0.95\n",
    "    )\n",
    ")\n",
    "shown = {\n",
    "    \"before the peak\": max(peak - 3, 0),\n",
    "    \"crack at the hole\": arrival,\n",
    "    \"end of the test\": len(lift) - 1,\n",
    "}\n",
    "fig = plots.figure(layout=[list(shown), [\"force\", \"force\", \"energy\"]], size=(16, 13))\n",
    "for panel, step in shown.items():\n",
    "    plots.heatmap(\n",
    "        x / mm,\n",
    "        y / mm,\n",
    "        result.damage[step],\n",
    "        triangles=cells,\n",
    "        limits=(0, 1),\n",
    "        label=\"damage d\",\n",
    "        xlabel=\"x [mm]\",\n",
    "        ylabel=\"y [mm]\",\n",
    "        title=f\"{panel}: δ = {lift[step] / mm:.2f} mm\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    lift / mm,\n",
    "    force,\n",
    "    xlabel=\"top displacement δ [mm]\",\n",
    "    ylabel=\"force [N]\",\n",
    "    title=\"Force-displacement curve\",\n",
    "    legend=False,\n",
    "    ax=fig[\"force\"],\n",
    ")\n",
    "plots.line(\n",
    "    lift / mm,\n",
    "    {\n",
    "        \"external work\": 1e3 * result.external_work,\n",
    "        \"elastic energy\": 1e3 * result.elastic_energy,\n",
    "        \"crack energy\": 1e3 * result.fracture_energy,\n",
    "    },\n",
    "    hlines={\"G_c a t (1 + h/2l)\": 1e3 * griffith * (1 + h / (2 * ell))},\n",
    "    xlabel=\"top displacement δ [mm]\",\n",
    "    ylabel=\"energy [mJ]\",\n",
    "    title=\"Energies\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"energy\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the hole in `holed_plate_phase_field_geometry.py` and write the STEP file again: with the\n",
    "hole further to the right, the crack passes it. Halve $\\ell$ together with the mesh size in the\n",
    "refined region to sharpen the crack."
   ]
  }
 ]
}
