"""
Global DIC: shear bands in a sandstone
======================================

Two photographs of a sandstone, taken before and after loading in the true
triaxial cell of Laboratoire 3SR during Cyrille Couture's PhD thesis
[https://theses.fr/2020GRALI058], look identical to the eye. Here we measure
the displacement field between them with **global DIC**, and the deviatoric
strain derived from it reveals the shear bands forming in the sample.

Global DIC looks for the displacements of the nodes of a finite-element mesh
covering the whole image, rather than correlating independent patches.
With a fine mesh the problem becomes ill-posed and noisy, so we add a
**mechanical regularisation** (`Mendoza et al., 2019
<https://doi.org/10.1016/j.cma.2019.06.005>`_), which filters out displacement
fields that are not mechanically admissible below a length :math:`\\xi`.
The last part of this example shows the effect of :math:`\\xi`.

This is the example shown on the front page of the
`spam website <https://www.spam-project.dev>`_.
"""

######################
# Import modules
######################

import numpy
import matplotlib.pyplot as plt
import matplotlib.tri

import spam.datasets
import spam.DIC

# sphinx_gallery_thumbnail_number = 4

###############################################################################
# Load the images
# ---------------
# The two images (1248 x 1248 pixels) ship with spam. Global DIC works on
# floating point images.

im1 = spam.datasets.loadSandstone1().astype("<f4")
im2 = spam.datasets.loadSandstone2().astype("<f4")

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
for ax, im, title in zip(axes, [im1, im2], ["Before loading", "After loading"]):
    ax.imshow(im, cmap="Greys_r")
    ax.set_title(title)
    ax.set_axis_off()
plt.tight_layout()
plt.show()

###############################################################################
# Build the mesh
# --------------
# ``spam.DIC.mesh2D`` builds a triangular mesh (with gmsh) of a rectangle,
# here 1200 x 1200 pixels starting 24 pixels from the edge of the image, with
# elements about ``MESH_SIZE_PX`` pixels in size.
#
# Points are given in (row, column) order, like the image indices.

MESH_SIZE_PX = 20
points, connectivity = spam.DIC.mesh2D((1200, 1200), MESH_SIZE_PX, (24, 24))
print(f"{len(points)} nodes, {len(connectivity)} triangles")

# matplotlib works in (x, y) = (column, row)
triangulation = matplotlib.tri.Triangulation(points[:, 1], points[:, 0], connectivity)

fig, ax = plt.subplots(figsize=(6, 6))
ax.imshow(im1, cmap="Greys_r")
ax.triplot(triangulation, color="tab:cyan", linewidth=0.5)
ax.set_xlim(400, 700)
ax.set_ylim(700, 400)
ax.set_title(f"Zoom on the mesh ({MESH_SIZE_PX} px elements)")
ax.set_axis_off()
plt.show()

###############################################################################
# Run global DIC with mechanical regularisation
# ---------------------------------------------
# The main options of ``spam.DIC.globalDIC``:
#
# - ``bulkRegularisation=True`` turns the mechanical regularisation on;
# - ``xi_m`` is the regularisation length in pixels. Displacement fluctuations
#   shorter than this are filtered out. A good starting point is a few times
#   the element size (the default, if ``xi_m`` is not given, is twice the
#   mesh size); here we use 60 px, three elements;
# - ``maxIter`` and ``convCrit`` control the iterations: the correlation
#   stops when the RMS displacement increment of an iteration,
#   ``||dx|| / sqrt(n_dof)``, drops below ``convCrit`` pixels, or after
#   ``maxIter`` iterations;
# - ``poisson`` (default 0.25) is also a regularisation parameter: values
#   towards 0.5 smooth volume changes more strongly than shear (see
#   ``buildRegularisationMatrix`` in ``spam/DIC/globalDIC.py``).
#
# The result is one displacement vector (row, column) per node.

XI = 60
displacements = spam.DIC.globalDIC(
    im1,
    im2,
    points,
    connectivity,
    maxIter=25,
    convCrit=1e-07,
    bulkRegularisation=True,
    xi_m=XI,
)

###############################################################################
# Displacements
# -------------
# The magnitude of the displacement shows blocks of rock moving almost
# rigidly, with sharp transitions between them.

fig, ax = plt.subplots(figsize=(7, 6))
ax.imshow(im1, cmap="Greys_r")
m = ax.tripcolor(
    triangulation,
    numpy.linalg.norm(displacements, axis=1),
    shading="gouraud",
    cmap="viridis",
    alpha=0.8,
)
fig.colorbar(m, label="Displacement magnitude (px)")
ax.set_title(f"Displacements, $\\xi$ = {XI} px")
ax.set_axis_off()
plt.show()

###############################################################################
# Deviatoric strain
# -----------------
# ``spam.DIC.computeConstantStrainTriangles`` derives a constant strain
# tensor in each triangle from the nodal displacements, and returns its
# volumetric and deviatoric parts. The deviatoric strain shows where the
# deformation localises: the shear bands between the blocks.

strain, volumetric, deviatoric = spam.DIC.computeConstantStrainTriangles(
    points.astype("<f4"),
    connectivity,
    displacements.astype("<f4"),
)

vmax = numpy.percentile(deviatoric, 99.5)  # colour scale used for all strain maps below

fig, ax = plt.subplots(figsize=(7, 6))
ax.imshow(im1, cmap="Greys_r")
m = ax.tripcolor(triangulation, facecolors=deviatoric, cmap="inferno", vmin=0, vmax=vmax, alpha=0.85)
fig.colorbar(m, label="Deviatoric strain")
ax.set_title(f"Deviatoric strain, $\\xi$ = {XI} px")
ax.set_axis_off()
plt.show()

###############################################################################
# Effect of the regularisation length
# -----------------------------------
# We now run the same correlation without regularisation and with three
# values of :math:`\xi`, and plot the results with the same colour scales.
#
# - Without regularisation, the displacements look almost right, but they are
#   noisy at the scale of the elements: differentiated into strain, this noise
#   swamps the shear bands.
# - :math:`\xi` = 30 px brings the bands out, still on a noisy background;
#   60 px gives clean bands.
# - Too much regularisation (120 px) blurs the bands, and the thinner ones
#   disappear: :math:`\xi` should stay smaller than the features to measure.

settings = {"No regularisation": None, "$\\xi$ = 30 px": 30, "$\\xi$ = 60 px": 60, "$\\xi$ = 120 px": 120}
dmin, dmax = numpy.percentile(numpy.linalg.norm(displacements, axis=1), [0.5, 99.5])

fig, axes = plt.subplots(2, 4, figsize=(16, 8.5))
for column, (title, xi) in enumerate(settings.items()):
    u = spam.DIC.globalDIC(
        im1,
        im2,
        points,
        connectivity,
        maxIter=25,
        convCrit=1e-07,
        bulkRegularisation=xi is not None,
        xi_m=xi,
    )
    _, _, dev = spam.DIC.computeConstantStrainTriangles(points.astype("<f4"), connectivity, u.astype("<f4"))

    top, bottom = axes[0, column], axes[1, column]
    top.tripcolor(triangulation, numpy.linalg.norm(u, axis=1), shading="gouraud", cmap="viridis", vmin=dmin, vmax=dmax)
    bottom.tripcolor(triangulation, facecolors=dev, cmap="inferno", vmin=0, vmax=vmax)
    top.set_title(title)
    for ax in (top, bottom):
        ax.set_aspect("equal")
        ax.invert_yaxis()
        ax.set_axis_off()

axes[0, 0].text(-0.05, 0.5, "Displacement", transform=axes[0, 0].transAxes, rotation=90, va="center", ha="right", fontsize=12)
axes[1, 0].text(-0.05, 0.5, "Deviatoric strain", transform=axes[1, 0].transAxes, rotation=90, va="center", ha="right", fontsize=12)
plt.tight_layout()
plt.show()
