{
 "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 damage of a bar in uniaxial tension\n",
    "\n",
    "Phase-field models describe a crack by a damage field $d\\in[0,1]$ smeared over a width set by\n",
    "the regularisation length $\\ell$. The AT2 model of Bourdin, Francfort and Marigo minimises\n",
    "\n",
    "$$\\Pi(\\mathbf u,d)=\\int_\\Omega\\Big[(1-d)^2\\psi(\\boldsymbol\\varepsilon)+\\frac{G_c}{2\\ell}\\big(d^2+\\ell^2|\\nabla d|^2\\big)\\Big]\\,\\mathrm dV-W_\\mathrm{ext}\n",
    "  \\quad\\text{with}\\quad \\dot d\\ge0 .$$\n",
    "\n",
    "**The homogeneous solution.** As long as the bar stays uniform, the damage and the stress at\n",
    "the strain $\\varepsilon$ are\n",
    "\n",
    "$$d=\\frac{E\\varepsilon^2}{G_c/\\ell+E\\varepsilon^2},\\qquad \\sigma=(1-d)^2E\\varepsilon ,$$\n",
    "\n",
    "with the peak $\\sigma_c=\\frac{9}{16}\\sqrt{EG_c/3\\ell}$ at $\\varepsilon_c=\\sqrt{G_c/3E\\ell}$\n",
    "(K. Pham, J.-J. Marigo, C. Maurini, J. Mech. Phys. Solids 59, 2011, 1163-1190). Unlike a real\n",
    "brittle material, AT2 has no elastic range: damage grows from the first load step.\n",
    "\n",
    "**Localisation.** Past the peak the uniform state becomes unstable; at a small imperfection the\n",
    "damage concentrates into a crack across the bar. When the bar is broken ($\\sigma=0$) the damage\n",
    "away from the crack stays frozen at the value $d_h$ it had reached, and the crack profile along\n",
    "the bar is the solution of the obstacle problem $d\\ge d_h$:\n",
    "$d=d_h\\cosh\\big((x^*-|x-x_0|)/\\ell\\big)$ for $|x-x_0|<x^*$, $\\cosh(x^*/\\ell)=1/d_h$. Its energy\n",
    "plus the frozen uniform damage gives the dissipated energy, with $A$ the cross-section,\n",
    "\n",
    "$$D=G_cA\\Big[\\sqrt{1-d_h^2}-d_h^2\\,\\mathrm{arcosh}(1/d_h)+\\frac{L\\,d_h^2}{2\\ell}\\Big] .$$\n",
    "\n",
    "**Setup.** A concrete bar 100 mm long and 2 mm high, $E=30$ GPa, $\\nu=0.2$, $G_c=100$ N/m,\n",
    "$\\ell=2.5$ mm, in plane stress. The upper half comes from the CAD file\n",
    "`brittle_bar_phase_field.step`, written by `brittle_bar_phase_field_geometry.py` with the CAD\n",
    "objects of OneSimulation (1 mm thick). The damage at the centre starts at 0.1 (a Gaussian of\n",
    "width $\\ell$) as the imperfection.\n",
    "\n",
    "| side | displacement | damage |\n",
    "|---|---|---|\n",
    "| `x_min` (held end) | $u_x=0$ | zero flux |\n",
    "| `x_max` (pulled end) | $u_x=\\bar u(t)$, increasing | zero flux |\n",
    "| `y_min` (symmetry plane) | $u_y=0$ | zero flux |\n",
    "| `y_max` | traction free | zero flux |"
   ]
  },
  {
   "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 half bar, `section` its plane at half thickness with the names of the cut\n",
    "faces on its sides. Three uniform triangle meshes with the element size $\\ell/2$, $\\ell/4$ and\n",
    "$\\ell/8$; a uniform mesh leaves the place of the crack to the imperfection."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bar = load(\"brittle_bar_phase_field.step\")\n",
    "length, half_height, thickness = bar.size\n",
    "plane = bar.section((0, 0, 1), origin=(0, 0, thickness / 2))\n",
    "faces = plane.boundaries\n",
    "ell = 2.5e-3\n",
    "fractions = [2, 4, 8]\n",
    "meshes = {n: TriangularMesher(target_size=ell / n).generate(plane) for n in fractions}\n",
    "\n",
    "fig = plots.figure(2, 1, size=(15, 2.8))\n",
    "plots.geometry(\n",
    "    plane,\n",
    "    selection={\n",
    "        \"held end\": faces.x_min,\n",
    "        \"pulled end\": faces.x_max,\n",
    "        \"symmetry plane\": faces.y_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Upper half of the bar (section of the CAD part)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[8],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Finest mesh: {meshes[8].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The pulled end moves in 65 steps to twice the peak strain, finely after the peak. In each step\n",
    "the solver alternates between equilibrium and damage until the damage changes by less than\n",
    "$10^{-6}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, toughness, area = 30e9, 100.0, half_height * thickness\n",
    "peak_strain = np.sqrt(toughness / (3 * youngs_modulus * ell))\n",
    "peak_stress = 9 / 16 * np.sqrt(youngs_modulus * toughness / (3 * ell))\n",
    "strain = np.r_[np.linspace(0, 0.9, 10), np.linspace(0.92, 2.0, 55)] * peak_strain\n",
    "model = 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",
    ")\n",
    "results = {\n",
    "    n: model.solve(\n",
    "        mesh=mesh,\n",
    "        times=strain * length,\n",
    "        tolerance=1e-6,\n",
    "        max_iterations=5000,\n",
    "        displacements=(\n",
    "            (faces.x_min, \"x\", 0.0),\n",
    "            (faces.x_max, \"x\", lambda t: t),\n",
    "            (faces.y_min, \"y\", 0.0),\n",
    "        ),\n",
    "        initial_damage=lambda x, y: 0.1 * np.exp(-(((x - length / 2) / ell) ** 2)),\n",
    "    )\n",
    "    for n, mesh in meshes.items()\n",
    "}\n",
    "stress = {\n",
    "    n: result.reactions[:, np.isclose(result.coordinates[:, 0], length), 0].sum(axis=1)\n",
    "    / area\n",
    "    for n, result in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The peak stress and the homogeneous branch up to localisation, and for each mesh the frozen\n",
    "damage $d_h$, the dissipated energy against the analytical localised solution and the largest\n",
    "deviation of the damage along the symmetry plane from the obstacle profile."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "homogeneous = (\n",
    "    lambda e: youngs_modulus * e**2 / (toughness / ell + youngs_modulus * e**2)\n",
    ")\n",
    "fine = results[8]\n",
    "uniform = np.ptp(fine.damage, axis=1) < 0.01\n",
    "print(\n",
    "    f\"peak stress: simulation {stress[8].max() / 1e6:.4f} MPa at ε = {strain[stress[8].argmax()] / peak_strain:.3f} ε_c, \"\n",
    "    f\"homogeneous AT2 solution {peak_stress / 1e6:.4f} MPa at ε = ε_c, deviation {100 * (stress[8].max() / peak_stress - 1):+.3f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"homogeneous branch up to ε = {strain[uniform].max() / peak_strain:.2f} ε_c: largest stress deviation \"\n",
    "    f\"{np.abs(stress[8][uniform] - (1 - homogeneous(strain[uniform])) ** 2 * youngs_modulus * strain[uniform]).max() / peak_stress:.1e} σ_c\"\n",
    ")\n",
    "print(\n",
    "    f\"{'mesh':>6s} {'triangles':>9s} {'d_h':>7s} {'dissipated / G_c A':>19s} {'1D obstacle solution':>21s} {'deviation':>10s} {'profile deviation':>18s}\"\n",
    ")\n",
    "profiles, deviations = {}, []\n",
    "for n, result in results.items():\n",
    "    x, y = result.coordinates.T\n",
    "    frozen = result.damage[-1, np.argmin(x)]\n",
    "    reach = ell * np.arccosh(1 / frozen)\n",
    "    profiles[n] = np.where(\n",
    "        np.abs(x - length / 2) < reach,\n",
    "        frozen * np.cosh((reach - np.abs(x - length / 2)) / ell),\n",
    "        frozen,\n",
    "    )\n",
    "    exact = (\n",
    "        np.sqrt(1 - frozen**2)\n",
    "        - frozen**2 * np.arccosh(1 / frozen)\n",
    "        + length * frozen**2 / (2 * ell)\n",
    "    )\n",
    "    deviations.append(result.fracture_energy[-1] / (toughness * area) / exact - 1)\n",
    "    print(\n",
    "        f\"{'l/' + str(n):>6s} {meshes[n].cell_count:9d} {frozen:7.4f} {result.fracture_energy[-1] / (toughness * area):19.4f} {exact:21.4f}\"\n",
    "        f\" {100 * deviations[-1]:+9.2f} % {np.abs(result.damage[-1] - profiles[n])[np.isclose(y, 0.0)].max():18.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The damage in the bar at the end, the damage along the symmetry plane at four strains, the\n",
    "stress-strain curves of the three meshes with the homogeneous solution, and the final crack\n",
    "against the obstacle profile."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = fine.coordinates.T\n",
    "axis = np.isclose(y, 0.0)\n",
    "order = np.argsort(x[axis])\n",
    "shown = {\n",
    "    f\"ε = {strain[k] / peak_strain:.2f} ε_c\": k\n",
    "    for k in (9, 20, int(np.flatnonzero(uniform).max()) + 2, len(strain) - 1)\n",
    "}\n",
    "line = np.linspace(0, 2.0, 400) * peak_strain\n",
    "fig = plots.figure(layout=[[\"field\", \"field\"], [\"profiles\", \"curve\"]], size=(15, 9))\n",
    "plots.heatmap(\n",
    "    1e3 * x,\n",
    "    1e3 * y,\n",
    "    fine.damage[-1],\n",
    "    triangles=np.asarray(meshes[8].cells),\n",
    "    limits=(0, 1),\n",
    "    label=\"damage d\",\n",
    "    aspect=4.0,\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    xlimits=(40, 60),\n",
    "    title=\"Damage in the broken bar, centre part (height drawn 4 times enlarged)\",\n",
    "    ax=fig[\"field\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        label: (1e3 * x[axis][order], fine.damage[k, axis][order])\n",
    "        for label, k in shown.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"obstacle profile at the end\": (1e3 * x[axis][order], profiles[8][axis][order])\n",
    "    },\n",
    "    ylimits=(0, 1.05),\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"damage d on the symmetry plane\",\n",
    "    title=\"Damage along the bar, h = l/8\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"profiles\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"h = l/{n}\": (strain / peak_strain, values / 1e6)\n",
    "        for n, values in stress.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"homogeneous AT2 solution\": (\n",
    "            line / peak_strain,\n",
    "            (1 - homogeneous(line)) ** 2 * youngs_modulus * line / 1e6,\n",
    "        )\n",
    "    },\n",
    "    hlines={\"σ_c\": peak_stress / 1e6},\n",
    "    xlabel=\"strain ε / ε_c\",\n",
    "    ylabel=\"stress σ [MPa]\",\n",
    "    title=\"Stress-strain curve\",\n",
    "    legend=\"lower center\",\n",
    "    ax=fig[\"curve\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the imperfection to make the bar break earlier, with less frozen damage; shorten the bar\n",
    "to a few $\\ell$ and the uniform state stays stable past the peak. Compare a smaller $\\ell$: the\n",
    "peak stress grows like $1/\\sqrt\\ell$, which is why $\\ell$ is often chosen from the tensile\n",
    "strength of the material."
   ]
  }
 ]
}
