{
 "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": [
    "# Phase-field fracture: single-edge-notched tension test\n",
    "\n",
    "A phase-field model replaces a sharp crack by a damage field $d(\\mathbf x)\\in[0,1]$\n",
    "($d=1$: broken) smeared over a width set by the regularisation length $\\ell$. The\n",
    "displacement $\\mathbf u$ and the damage minimise the total energy (AT2 model)\n",
    "\n",
    "$$\\Pi(\\mathbf u,d)=\\int_\\Omega\\Big[g(d)\\,\\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\n",
    "  -W_\\mathrm{ext},\\qquad g(d)=(1-d)^2(1-k)+k ,$$\n",
    "\n",
    "subject to irreversibility, $\\dot d\\ge0$. The second integral converges to the Griffith\n",
    "surface energy $G_c\\,A_\\mathrm{crack}$ as $\\ell\\to0$. The strain energy is split into a\n",
    "part $\\psi^+$ that drives the crack and a part $\\psi^-$ that does not (volumetric energy in\n",
    "compression), after Amor, Marigo and Maurini (J. Mech. Phys. Solids 57, 2009).\n",
    "\n",
    "**Setup** (C. Miehe, M. Hofacker, F. Welschinger, Comput. Methods Appl. Mech. Eng. 199,\n",
    "2010, 2765-2778): a 1 mm x 1 mm plate with a sharp notch from the left side to the centre;\n",
    "$E=210$ GPa, $\\nu=0.3$, $G_c=2.7$ N/mm, plane strain. The specimen comes from the CAD file\n",
    "`phase_field_fracture_sent.step`, written by `phase_field_fracture_sent_geometry.py` with the\n",
    "CAD objects of OneSimulation; the model lives on its cross-section.\n",
    "\n",
    "| side | displacement | damage |\n",
    "|---|---|---|\n",
    "| `y_min` (bottom) | $u_x=u_y=0$ | zero flux |\n",
    "| `y_max` (top) | $u_x=0$, $u_y=u$ | zero flux |\n",
    "| `x_min`, `x_max` | traction free | zero flux |\n",
    "| `notch.side` (both flanks) | traction free | zero flux |\n",
    "\n",
    "**Reference.** The published force-displacement curve: peak force about 0.70 kN per mm\n",
    "thickness at $u\\approx5.5$ µm (points digitised from the figure), with a straight crack across\n",
    "the ligament. And the Griffith balance: the energy dissipated in forming the crack equals $G_c$\n",
    "times the 0.5 mm ligament times the thickness, up to the overestimate $h/2\\ell$ of the\n",
    "regularised functional on a mesh of size $h$."
   ]
  },
  {
   "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",
    "`load` returns the solid, `section` its cross-section at half thickness with the names of the\n",
    "cut faces on its sides. Each case has its own triangle mesh: the size is $h$ in a band of\n",
    "$\\pm5\\ell$ around the crack plane, from $6\\ell$ in front of the notch tip to the right side, and\n",
    "grows to 50 µm away from it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "specimen = load(\"phase_field_fracture_sent.step\")\n",
    "side, _, thickness = specimen.size\n",
    "plate = specimen.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "faces = plate.boundaries\n",
    "tip, mm = side / 2, 1e-3\n",
    "cases = {\n",
    "    \"l = 0.0075 mm, h = l/2\": (0.0075 * mm, 0.00375 * mm),\n",
    "    \"l = 0.015 mm, h = l/2\": (0.015 * mm, 0.0075 * mm),\n",
    "    \"l = 0.015 mm, h = l/4\": (0.015 * mm, 0.00375 * mm),\n",
    "}\n",
    "main = \"l = 0.015 mm, h = l/4\"\n",
    "band = lambda ell, h: lambda p: np.minimum(\n",
    "    h\n",
    "    + 0.25\n",
    "    * np.hypot(\n",
    "        np.maximum(tip - 6 * ell - p[:, 0], 0.0),\n",
    "        np.maximum(np.abs(p[:, 1] - side / 2) - 5 * ell, 0.0),\n",
    "    ),\n",
    "    0.05 * mm,\n",
    ")\n",
    "meshes = {\n",
    "    label: TriangularMesher(target_size=0.05 * mm, size_field=band(ell, h)).generate(\n",
    "        plate\n",
    "    )\n",
    "    for label, (ell, h) in cases.items()\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6.5))\n",
    "plots.geometry(\n",
    "    plate, title=\"Cross-section of the specimen with its named sides\", ax=fig[0]\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[main],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{main}: {meshes[main].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The top side is moved up in 39 steps, fine around the expected peak; the load parameter of the\n",
    "solver is the displacement itself. Each step alternates between equilibrium at fixed damage and\n",
    "the damage at fixed displacement until the damage changes by less than $10^{-4}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, toughness = 210e9, 0.3, 2700.0\n",
    "lift = (\n",
    "    np.r_[\n",
    "        0.0,\n",
    "        np.arange(0.5e-3, 4.01e-3, 0.5e-3),\n",
    "        np.arange(4.25e-3, 5.0e-3, 0.25e-3),\n",
    "        np.arange(5.0e-3, 6.31e-3, 0.05e-3),\n",
    "    ]\n",
    "    * mm\n",
    ")\n",
    "results = {\n",
    "    label: PhaseFieldFracture(\n",
    "        youngs_modulus=youngs_modulus,\n",
    "        poisson_ratio=poisson_ratio,\n",
    "        fracture_energy=toughness,\n",
    "        length_scale=ell,\n",
    "        thickness=thickness,\n",
    "    ).solve(\n",
    "        mesh=meshes[label],\n",
    "        times=lift,\n",
    "        tolerance=1e-4,\n",
    "        max_iterations=5000,\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",
    "        tractions=(\n",
    "            (faces.x_min, (0.0, 0.0)),\n",
    "            (faces.x_max, (0.0, 0.0)),\n",
    "            (faces[\"notch.side\"], (0.0, 0.0)),\n",
    "        ),\n",
    "    )\n",
    "    for label, (ell, h) in cases.items()\n",
    "}\n",
    "force = {\n",
    "    label: result.reactions[:, np.isclose(result.coordinates[:, 1], side), 1].sum(\n",
    "        axis=1\n",
    "    )\n",
    "    for label, result in results.items()\n",
    "}\n",
    "peak = {label: int(np.argmax(values)) for label, values in force.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "Peak force and the displacement at the peak against the published values, and the energy\n",
    "dissipated after the peak against Griffith's $G_c$ times the ligament, without and with the\n",
    "mesh overestimate $h/2\\ell$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "published = np.array(\n",
    "    [\n",
    "        (0.0, 0.0),\n",
    "        (0.00055, 0.0768),\n",
    "        (0.00128, 0.1774),\n",
    "        (0.00197, 0.2716),\n",
    "        (0.00290, 0.3955),\n",
    "        (0.00369, 0.4961),\n",
    "        (0.00421, 0.5619),\n",
    "        (0.00471, 0.6200),\n",
    "        (0.00501, 0.6535),\n",
    "        (0.00524, 0.6780),\n",
    "        (0.00543, 0.6960),\n",
    "        (0.00555, 0.7012),\n",
    "        (0.00557, 0.6584),\n",
    "        (0.00562, 0.5613),\n",
    "        (0.00568, 0.4629),\n",
    "        (0.00575, 0.3192),\n",
    "        (0.00580, 0.1833),\n",
    "        (0.00583, 0.0214),\n",
    "        (0.00583, 0.0007),\n",
    "    ]\n",
    ")\n",
    "griffith = toughness * (side - tip) * thickness\n",
    "print(\n",
    "    f\"{'case':24s} {'triangles':>9s} {'peak force [kN]':>16s} {'u at peak [µm]':>15s} {'dissipated / G_c a t':>21s} {'with h/2l':>10s}\"\n",
    ")\n",
    "print(f\"{'Miehe et al. (2010)':24s} {'':9s} {0.70:16.3f} {5.5:15.2f}\")\n",
    "for label, (ell, h) in cases.items():\n",
    "    released = (\n",
    "        results[label].fracture_energy[-1] - results[label].fracture_energy[peak[label]]\n",
    "    )\n",
    "    print(\n",
    "        f\"{label:24s} {meshes[label].cell_count:9d} {force[label][peak[label]] / 1e3:16.3f} {1e6 * lift[peak[label]]:15.2f}\"\n",
    "        f\" {released / griffith:21.3f} {released / (griffith * (1 + h / (2 * ell))):10.3f}\"\n",
    "    )\n",
    "x, y = results[main].coordinates.T\n",
    "broken = (results[main].damage[-1] > 0.95) & (x > tip)\n",
    "print(\n",
    "    f\"crack path ({main}): mean height {y[broken].mean() / mm:.4f} mm, between {y[broken].min() / mm:.4f} and {y[broken].max() / mm:.4f} mm\"\n",
    ")\n",
    "print(\n",
    "    f\"smallest damage change between two steps: {np.diff(results[main].damage, axis=0).min():.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The damage before the peak, at the peak and after separation; the force-displacement curves\n",
    "with the published points; and the energies of the main case."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shown = {\n",
    "    \"before the peak\": int(np.argmin(np.abs(lift - 4e-6))),\n",
    "    \"at the peak\": peak[main],\n",
    "    \"separated\": len(lift) - 1,\n",
    "}\n",
    "energy = results[main]\n",
    "fig = plots.figure(layout=[list(shown), [\"force\", \"force\", \"energy\"]], size=(16, 10.5))\n",
    "for panel, step in shown.items():\n",
    "    plots.heatmap(\n",
    "        x / mm,\n",
    "        y / mm,\n",
    "        energy.damage[step],\n",
    "        triangles=np.asarray(meshes[main].cells),\n",
    "        limits=(0, 1),\n",
    "        label=\"damage d\",\n",
    "        xlabel=\"x [mm]\",\n",
    "        ylabel=\"y [mm]\",\n",
    "        title=f\"{panel}: u = {1e6 * lift[step]:.2f} µm\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.line(\n",
    "    1e6 * lift,\n",
    "    {label: values / 1e3 for label, values in force.items()},\n",
    "    points={\"Miehe et al. (2010), digitised\": (1e3 * published[:, 0], published[:, 1])},\n",
    "    xlabel=\"top displacement u [µm]\",\n",
    "    ylabel=\"force [kN per mm thickness]\",\n",
    "    title=\"Force-displacement curve\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"force\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e6 * lift,\n",
    "    {\n",
    "        \"external work\": 1e3 * energy.external_work,\n",
    "        \"elastic energy\": 1e3 * energy.elastic_energy,\n",
    "        \"crack energy\": 1e3 * energy.fracture_energy,\n",
    "    },\n",
    "    hlines={\n",
    "        \"crack energy at the peak + G_c a t\": 1e3\n",
    "        * (energy.fracture_energy[peak[main]] + griffith)\n",
    "    },\n",
    "    xlabel=\"top displacement u [µm]\",\n",
    "    ylabel=\"energy [mJ]\",\n",
    "    title=f\"Energies, {main}\",\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",
    "Change the notch in `phase_field_fracture_sent_geometry.py` and write the STEP file again, or\n",
    "move the top side sideways instead of up (the shear test of Miehe et al.): the crack then\n",
    "curves downwards. Try a smaller $\\ell$ together with a finer band."
   ]
  }
 ]
}
