{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Global DIC: shear bands in a sandstone\n\nTwo photographs of a sandstone, taken before and after loading in the true\ntriaxial cell of Laboratoire 3SR during Cyrille Couture's PhD thesis\n[https://theses.fr/2020GRALI058], look identical to the eye. Here we measure\nthe displacement field between them with **global DIC**, and the deviatoric\nstrain derived from it reveals the shear bands forming in the sample.\n\nGlobal DIC looks for the displacements of the nodes of a finite-element mesh\ncovering the whole image, rather than correlating independent patches.\nWith a fine mesh the problem becomes ill-posed and noisy, so we add a\n**mechanical regularisation** ([Mendoza et al., 2019](https://doi.org/10.1016/j.cma.2019.06.005)), which filters out displacement\nfields that are not mechanically admissible below a length $\\xi$.\nThe last part of this example shows the effect of $\\xi$.\n\nThis is the example shown on the front page of the\n[spam website](https://www.spam-project.dev).\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Import modules\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy\nimport matplotlib.pyplot as plt\nimport matplotlib.tri\n\nimport spam.datasets\nimport spam.DIC"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Load the images\nThe two images (1248 x 1248 pixels) ship with spam. Global DIC works on\nfloating point images.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "im1 = spam.datasets.loadSandstone1().astype(\"<f4\")\nim2 = spam.datasets.loadSandstone2().astype(\"<f4\")\n\nfig, axes = plt.subplots(1, 2, figsize=(10, 5))\nfor ax, im, title in zip(axes, [im1, im2], [\"Before loading\", \"After loading\"]):\n    ax.imshow(im, cmap=\"Greys_r\")\n    ax.set_title(title)\n    ax.set_axis_off()\nplt.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Build the mesh\n``spam.DIC.mesh2D`` builds a triangular mesh (with gmsh) of a rectangle,\nhere 1200 x 1200 pixels starting 24 pixels from the edge of the image, with\nelements about ``MESH_SIZE_PX`` pixels in size.\n\nPoints are given in (row, column) order, like the image indices.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "MESH_SIZE_PX = 20\npoints, connectivity = spam.DIC.mesh2D((1200, 1200), MESH_SIZE_PX, (24, 24))\nprint(f\"{len(points)} nodes, {len(connectivity)} triangles\")\n\n# matplotlib works in (x, y) = (column, row)\ntriangulation = matplotlib.tri.Triangulation(points[:, 1], points[:, 0], connectivity)\n\nfig, ax = plt.subplots(figsize=(6, 6))\nax.imshow(im1, cmap=\"Greys_r\")\nax.triplot(triangulation, color=\"tab:cyan\", linewidth=0.5)\nax.set_xlim(400, 700)\nax.set_ylim(700, 400)\nax.set_title(f\"Zoom on the mesh ({MESH_SIZE_PX} px elements)\")\nax.set_axis_off()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Run global DIC with mechanical regularisation\nThe main options of ``spam.DIC.globalDIC``:\n\n- ``bulkRegularisation=True`` turns the mechanical regularisation on;\n- ``xi_m`` is the regularisation length in pixels. Displacement fluctuations\n  shorter than this are filtered out. A good starting point is a few times\n  the element size (the default, if ``xi_m`` is not given, is twice the\n  mesh size); here we use 60 px, three elements;\n- ``maxIter`` and ``convCrit`` control the iterations: the correlation\n  stops when the RMS displacement increment of an iteration,\n  ``||dx|| / sqrt(n_dof)``, drops below ``convCrit`` pixels, or after\n  ``maxIter`` iterations;\n- ``poisson`` (default 0.25) is also a regularisation parameter: values\n  towards 0.5 smooth volume changes more strongly than shear (see\n  ``buildRegularisationMatrix`` in ``spam/DIC/globalDIC.py``).\n\nThe result is one displacement vector (row, column) per node.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "XI = 60\ndisplacements = spam.DIC.globalDIC(\n    im1,\n    im2,\n    points,\n    connectivity,\n    maxIter=25,\n    convCrit=1e-07,\n    bulkRegularisation=True,\n    xi_m=XI,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Displacements\nThe magnitude of the displacement shows blocks of rock moving almost\nrigidly, with sharp transitions between them.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots(figsize=(7, 6))\nax.imshow(im1, cmap=\"Greys_r\")\nm = ax.tripcolor(\n    triangulation,\n    numpy.linalg.norm(displacements, axis=1),\n    shading=\"gouraud\",\n    cmap=\"viridis\",\n    alpha=0.8,\n)\nfig.colorbar(m, label=\"Displacement magnitude (px)\")\nax.set_title(f\"Displacements, $\\\\xi$ = {XI} px\")\nax.set_axis_off()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Deviatoric strain\n``spam.DIC.computeConstantStrainTriangles`` derives a constant strain\ntensor in each triangle from the nodal displacements, and returns its\nvolumetric and deviatoric parts. The deviatoric strain shows where the\ndeformation localises: the shear bands between the blocks.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "strain, volumetric, deviatoric = spam.DIC.computeConstantStrainTriangles(\n    points.astype(\"<f4\"),\n    connectivity,\n    displacements.astype(\"<f4\"),\n)\n\nvmax = numpy.percentile(deviatoric, 99.5)  # colour scale used for all strain maps below\n\nfig, ax = plt.subplots(figsize=(7, 6))\nax.imshow(im1, cmap=\"Greys_r\")\nm = ax.tripcolor(triangulation, facecolors=deviatoric, cmap=\"inferno\", vmin=0, vmax=vmax, alpha=0.85)\nfig.colorbar(m, label=\"Deviatoric strain\")\nax.set_title(f\"Deviatoric strain, $\\\\xi$ = {XI} px\")\nax.set_axis_off()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Effect of the regularisation length\nWe now run the same correlation without regularisation and with three\nvalues of $\\xi$, and plot the results with the same colour scales.\n\n- Without regularisation, the displacements look almost right, but they are\n  noisy at the scale of the elements: differentiated into strain, this noise\n  swamps the shear bands.\n- $\\xi$ = 30 px brings the bands out, still on a noisy background;\n  60 px gives clean bands.\n- Too much regularisation (120 px) blurs the bands, and the thinner ones\n  disappear: $\\xi$ should stay smaller than the features to measure.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "settings = {\"No regularisation\": None, \"$\\\\xi$ = 30 px\": 30, \"$\\\\xi$ = 60 px\": 60, \"$\\\\xi$ = 120 px\": 120}\ndmin, dmax = numpy.percentile(numpy.linalg.norm(displacements, axis=1), [0.5, 99.5])\n\nfig, axes = plt.subplots(2, 4, figsize=(16, 8.5))\nfor column, (title, xi) in enumerate(settings.items()):\n    u = spam.DIC.globalDIC(\n        im1,\n        im2,\n        points,\n        connectivity,\n        maxIter=25,\n        convCrit=1e-07,\n        bulkRegularisation=xi is not None,\n        xi_m=xi,\n    )\n    _, _, dev = spam.DIC.computeConstantStrainTriangles(points.astype(\"<f4\"), connectivity, u.astype(\"<f4\"))\n\n    top, bottom = axes[0, column], axes[1, column]\n    top.tripcolor(triangulation, numpy.linalg.norm(u, axis=1), shading=\"gouraud\", cmap=\"viridis\", vmin=dmin, vmax=dmax)\n    bottom.tripcolor(triangulation, facecolors=dev, cmap=\"inferno\", vmin=0, vmax=vmax)\n    top.set_title(title)\n    for ax in (top, bottom):\n        ax.set_aspect(\"equal\")\n        ax.invert_yaxis()\n        ax.set_axis_off()\n\naxes[0, 0].text(-0.05, 0.5, \"Displacement\", transform=axes[0, 0].transAxes, rotation=90, va=\"center\", ha=\"right\", fontsize=12)\naxes[1, 0].text(-0.05, 0.5, \"Deviatoric strain\", transform=axes[1, 0].transAxes, rotation=90, va=\"center\", ha=\"right\", fontsize=12)\nplt.tight_layout()\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.13.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}