{
 "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": [
    "# Cracking of a notched beam in three-point bending\n",
    "\n",
    "The notched beam in three-point bending is the standard test for the fracture energy of\n",
    "concrete and rock. A sharp notch in the middle of the tension side concentrates the stress; at\n",
    "a critical load a crack starts at its tip and runs up towards the loading point.\n",
    "\n",
    "The crack is computed with a **phase-field model**: a damage field $d\\in[0,1]$, smeared over\n",
    "a width set by the length $\\ell$, minimises together with the displacement the energy\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 (the split of Amor,\n",
    "Marigo and Maurini, 2009), so the compressed zone under the load stays intact.\n",
    "\n",
    "**Setup.** A concrete beam 440 mm long, depth $W=100$ mm, thickness $B=50$ mm, span\n",
    "$S=400$ mm, with a sharp notch of depth $a_0=50$ mm; $E=30$ GPa, $\\nu=0.2$, $G_c=100$ N/m,\n",
    "plane stress. The beam rests on two bearing plates and is pushed down through a third plate at\n",
    "mid-span. It comes from the CAD file `notched_beam_phase_field.step`, written by\n",
    "`notched_beam_phase_field_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | displacement | damage |\n",
    "|---|---|---|\n",
    "| `left_plate.y_min` | $u_x=u_y=0$ | zero flux |\n",
    "| `right_plate.y_min` | $u_y=0$ | zero flux |\n",
    "| `load_plate.y_max` | $u_y=-\\delta(t)$ | zero flux |\n",
    "| all other faces, `notch.side` | traction free | zero flux |\n",
    "\n",
    "**Reference.** Linear elastic fracture mechanics with the geometry factor of ASTM E399 for\n",
    "$S/W=4$:\n",
    "\n",
    "$$K_I=\\frac{P\\,S}{B\\,W^{3/2}}\\,f(\\alpha),\\qquad\n",
    "  f(\\alpha)=\\frac{3\\sqrt\\alpha\\,\\big[1.99-\\alpha(1-\\alpha)(2.15-3.93\\alpha+2.7\\alpha^2)\\big]}{2(1+2\\alpha)(1-\\alpha)^{3/2}},\\qquad\\alpha=a/W .$$\n",
    "\n",
    "The crack grows while $K_I=\\sqrt{EG_c}$, which gives the force $P(a)$; the compliance grows by\n",
    "$\\mathrm dC/\\mathrm da=2S^2f^2/(BW^3E)$, which gives the deflection $\\delta=P\\,C(a)$. A\n",
    "phase-field crack approaches this curve as $\\ell$ becomes small against the ligament; on a mesh\n",
    "of size $h$ it dissipates $G_c(1+h/2\\ell)$ per unit area."
   ]
  },
  {
   "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 beam at half thickness; the cut faces keep their names. The triangles are\n",
    "1 mm in a band of $\\pm5\\ell$ above the notch and grow to 8 mm away from it, one mesh per\n",
    "regularisation length."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "beam = load(\"notched_beam_phase_field.step\")\n",
    "length, height, thickness = beam.size\n",
    "plane = beam.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "faces = plane.boundaries\n",
    "middle, depth, span, notch, h, mm = length / 2, 0.100, 0.400, 0.050, 0.001, 1e-3\n",
    "lengths = [4 * mm, 2 * mm]\n",
    "band = lambda ell: lambda p: np.minimum(\n",
    "    h\n",
    "    + 0.25\n",
    "    * np.hypot(\n",
    "        np.maximum(np.abs(p[:, 0] - middle) - 5 * ell, 0.0),\n",
    "        np.maximum(notch - 5 * mm - p[:, 1], 0.0),\n",
    "    ),\n",
    "    8 * mm,\n",
    ")\n",
    "meshes = {\n",
    "    ell: TriangularMesher(target_size=8 * mm, size_field=band(ell)).generate(plane)\n",
    "    for ell in lengths\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 4.5))\n",
    "plots.geometry(\n",
    "    beam,\n",
    "    selection={\n",
    "        \"supports\": beam.boundaries[\"left_plate.y_min\"]\n",
    "        | beam.boundaries[\"right_plate.y_min\"],\n",
    "        \"load\": beam.boundaries[\"load_plate.y_max\"],\n",
    "        \"notch\": beam.boundaries[\"notch.side\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=28, azimuth=-70),\n",
    "    title=\"Notched beam with its bearing plates\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[2 * mm],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"l = 2 mm: {meshes[2 * mm].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The loading plate moves down in 46 steps, 5 µm each around and after the peak. Each step\n",
    "alternates between equilibrium at fixed damage and damage at fixed displacement until the damage\n",
    "changes by less than $10^{-4}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, toughness = 30e9, 100.0\n",
    "deflection = np.r_[0.0, 0.02, 0.04, 0.06, np.arange(0.065, 0.2751, 0.005)] * mm\n",
    "results = {\n",
    "    ell: PhaseFieldFracture(\n",
    "        youngs_modulus=youngs_modulus,\n",
    "        poisson_ratio=0.2,\n",
    "        fracture_energy=toughness,\n",
    "        length_scale=ell,\n",
    "        thickness=thickness,\n",
    "        plane_stress=True,\n",
    "    ).solve(\n",
    "        mesh=meshes[ell],\n",
    "        times=deflection,\n",
    "        tolerance=1e-4,\n",
    "        max_iterations=3000,\n",
    "        displacements=(\n",
    "            (faces[\"left_plate.y_min\"], \"x\", 0.0),\n",
    "            (faces[\"left_plate.y_min\"], \"y\", 0.0),\n",
    "            (faces[\"right_plate.y_min\"], \"y\", 0.0),\n",
    "            (faces[\"load_plate.y_max\"], \"y\", lambda t: -t),\n",
    "        ),\n",
    "    )\n",
    "    for ell in lengths\n",
    "}\n",
    "force = {\n",
    "    ell: -result.reactions[\n",
    "        :, np.isclose(result.coordinates[:, 1], result.coordinates[:, 1].max()), 1\n",
    "    ].sum(axis=1)\n",
    "    for ell, result in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference: fracture mechanics\n",
    "\n",
    "$P(a)$ from $K_I=\\sqrt{EG_c(1+h/2\\ell)}$, and the deflection from the compliance of the notched\n",
    "beam: its elastic value at $a_0$ is read from the first load step, the growth is integrated\n",
    "from the geometry factor."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "factor = (\n",
    "    lambda a: 3\n",
    "    * np.sqrt(a)\n",
    "    * (1.99 - a * (1 - a) * (2.15 - 3.93 * a + 2.7 * a**2))\n",
    "    / (2 * (1 + 2 * a) * (1 - a) ** 1.5)\n",
    ")\n",
    "alpha = np.linspace(notch / depth, 0.85, 400)\n",
    "lefm = {}\n",
    "for ell in lengths:\n",
    "    critical = np.sqrt(youngs_modulus * toughness * (1 + h / (2 * ell)))\n",
    "    growth = np.r_[\n",
    "        0.0,\n",
    "        np.cumsum(\n",
    "            np.diff(alpha)\n",
    "            * depth\n",
    "            * 2\n",
    "            * span**2\n",
    "            * factor((alpha[1:] + alpha[:-1]) / 2) ** 2\n",
    "            / (thickness * depth**3 * youngs_modulus)\n",
    "        ),\n",
    "    ]\n",
    "    load_on_crack = critical * thickness * depth**1.5 / (span * factor(alpha))\n",
    "    lefm[ell] = (\n",
    "        load_on_crack * (deflection[1] / force[ell][1] + growth),\n",
    "        load_on_crack,\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The peak force against the fracture-mechanics value at the notch, and the energy dissipated by\n",
    "the end against $G_c$ times the crack area, measured from the notch to the highest point with\n",
    "$d>0.95$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{'l [mm]':>6s} {'triangles':>9s} {'peak force [kN]':>16s} {'LEFM, G_c':>10s} {'LEFM, G_c(1+h/2l)':>18s} {'deviation':>10s}\"\n",
    "    f\" {'crack tip y [mm]':>17s} {'dissipated / G_c(1+h/2l) A':>27s}\"\n",
    ")\n",
    "for ell, result in results.items():\n",
    "    tip = result.coordinates[result.damage[-1] > 0.95, 1].max()\n",
    "    area = (tip - notch) * thickness\n",
    "    print(\n",
    "        f\"{1e3 * ell:6.0f} {meshes[ell].cell_count:9d} {force[ell].max() / 1e3:16.3f} {lefm[ell][1][0] / np.sqrt(1 + h / (2 * ell)) / 1e3:10.3f}\"\n",
    "        f\" {lefm[ell][1][0] / 1e3:18.3f} {100 * (force[ell].max() / lefm[ell][1][0] - 1):+9.1f} % {1e3 * tip:17.1f}\"\n",
    "        f\" {result.fracture_energy[-1] / (toughness * (1 + h / (2 * ell)) * area):27.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The damage at the peak and at the end for $\\ell=2$ mm (zoomed on the ligament), and the\n",
    "force-deflection curves with the fracture-mechanics curves."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "main = results[2 * mm]\n",
    "x, y = main.coordinates.T\n",
    "shown = {\n",
    "    \"at the peak\": int(np.argmax(force[2 * mm])),\n",
    "    \"end of the test\": len(deflection) - 1,\n",
    "}\n",
    "fig = plots.figure(layout=[list(shown) + [\"force\"]], size=(17, 5.5))\n",
    "for panel, step in shown.items():\n",
    "    plots.heatmap(\n",
    "        x / mm,\n",
    "        y / mm,\n",
    "        main.damage[step],\n",
    "        triangles=np.asarray(meshes[2 * mm].cells),\n",
    "        limits=(0, 1),\n",
    "        label=\"damage d\",\n",
    "        xlabel=\"x [mm]\",\n",
    "        ylabel=\"y [mm]\",\n",
    "        xlimits=(170, 270),\n",
    "        ylimits=(-5, 105),\n",
    "        title=f\"{panel}: δ = {1e3 * deflection[step]:.3f} mm\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"phase field, l = {1e3 * ell:.0f} mm\": (deflection / mm, values / 1e3)\n",
    "        for ell, values in force.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"LEFM, l = {1e3 * ell:.0f} mm\": (curve[0] / mm, curve[1] / 1e3)\n",
    "        for ell, curve in lefm.items()\n",
    "    },\n",
    "    xlimits=(0, 0.28),\n",
    "    ylimits=(0, 1.15 * max(values.max() for values in force.values()) / 1e3),\n",
    "    xlabel=\"deflection δ [mm]\",\n",
    "    ylabel=\"force P [kN]\",\n",
    "    title=\"Force-deflection curve\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[\"force\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Halve $\\ell$ together with the mesh size in the band: the peak moves towards the\n",
    "fracture-mechanics value. Make the notch shallower in `notched_beam_phase_field_geometry.py` and\n",
    "write the STEP file again; with no notch at all the beam fails at the strength\n",
    "$\\sigma_c=\\frac{9}{16}\\sqrt{EG_c/3\\ell}$ of the AT2 model."
   ]
  }
 ]
}
