# SPDX-License-Identifier: CECILL-2.1
# Figures of docs/examples/distance-maps.md. This script is the source of truth:
# the page includes parts of it with pymdownx.snippets. Run it from the
# repository root (it needs SciPy):
#     python docs/examples/scripts/distance_maps.py
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import distance
from scipy import ndimage as ndi

FIGURES = Path(__file__).resolve().parents[2] / "figures"
TEXT = "#222222"

# --8<-- [start:maps2d]
# A disk with a square notch, in a 2D image.
r, c = np.mgrid[:61, :61]
shape = (r - 30) ** 2 + (c - 30) ** 2 <= 26**2
shape[24:37, 40:] = False

maps2d = {kind: distance.distance_map(shape, kind)
          for kind in ("squared_euclidean", "chamfer", "d4", "d8")}
for kind, values in maps2d.items():
    print(f"2D {kind:17s} dtype {values.dtype}, maximum {values.max()}")
# --8<-- [end:maps2d]

# --8<-- [start:check]
# The outside of the array is background: pad before calling SciPy.
padded = np.pad(shape, 1)
inner = (slice(1, -1), slice(1, -1))
edt = ndi.distance_transform_edt(padded)[inner]
taxicab = ndi.distance_transform_cdt(padded, metric="taxicab")[inner]
chessboard = ndi.distance_transform_cdt(padded, metric="chessboard")[inner]
print("squared_euclidean == edt**2:", bool((maps2d["squared_euclidean"] == np.round(edt**2)).all()))
print("d4 == taxicab:", bool((maps2d["d4"] == taxicab).all()))
print("d8 == chessboard:", bool((maps2d["d8"] == chessboard).all()))
# --8<-- [end:check]

# --8<-- [start:maps3d]
# A ball with a cylindrical tunnel, in a 3D image (depth, rows, columns).
z, y, x = np.mgrid[:41, :41, :41]
ball = (z - 20) ** 2 + (y - 20) ** 2 + (x - 20) ** 2 <= 18**2
ball &= (y - 20) ** 2 + (x - 20) ** 2 > 5**2
maps3d = {kind: distance.distance_map(ball, kind)
          for kind in ("squared_euclidean", "d6", "d18", "d26")}
for kind, values in maps3d.items():
    print(f"3D {kind:17s} dtype {values.dtype}, maximum {values.max()}")
padded3d = np.pad(ball, 1)
inner3d = (slice(1, -1),) * 3
print("d6 == taxicab:", bool((maps3d["d6"] == ndi.distance_transform_cdt(
    padded3d, metric="taxicab")[inner3d]).all()))
print("d26 == chessboard:", bool((maps3d["d26"] == ndi.distance_transform_cdt(
    padded3d, metric="chessboard")[inner3d]).all()))
print("squared_euclidean == edt**2:", bool((maps3d["squared_euclidean"] == np.round(
    ndi.distance_transform_edt(padded3d)[inner3d] ** 2)).all()))
# --8<-- [end:maps3d]

fig, axes = plt.subplots(2, 4, figsize=(8.8, 4.8), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
rows = ((maps2d, "2D", lambda a: a), (maps3d, "3D, z=20", lambda a: a[20]))
for row, (maps, label, view) in zip(axes, rows):
    for ax, (kind, values) in zip(row, maps.items()):
        image = view(values).astype(float)
        image[view(values) == 0] = np.nan          # background shown in white
        ax.imshow(image, cmap="Blues", interpolation="nearest")
        ax.set_title(f"{label}: {kind}", fontsize=9, color=TEXT)
        ax.set_xticks([])
        ax.set_yticks([])
        for spine in ax.spines.values():
            spine.set_color("#dddddd")
fig.tight_layout()
fig.savefig(FIGURES / "distance-maps.png", dpi=100)
plt.close(fig)
