# SPDX-License-Identifier: CECILL-2.1
# Figures of docs/examples/grayscale.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 scikit-image and SciPy):
#     python docs/examples/scripts/grayscale.py
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import grayscale
from scipy import ndimage as ndi
from skimage import measure as skmeasure
from skimage import morphology

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

# --8<-- [start:image]
# Nine dark cells separated by bright walls, with noise.
rng = np.random.default_rng(3)
r, c = np.mgrid[:96, :128]
centres = rng.uniform([8, 8], [88, 120], size=(9, 2))
distance = np.min([np.hypot(r - y, c - x) for y, x in centres], axis=0)
noisy = np.clip(40 + 8 * distance + rng.normal(0, 12, distance.shape), 0, 255)
image = ndi.uniform_filter(noisy.astype(np.uint8), 3)


def count_minima(a):
    """Number of regional minima, 4-connected (the connectivity of the minima)."""
    return int(skmeasure.label(morphology.local_minima(a, connectivity=1), connectivity=1).max())


print("image:", image.shape, image.dtype, "minima:", count_minima(image))
# --8<-- [end:image]

# --8<-- [start:kernel]
kernel = grayscale.homotopic_kernel(image, 4)
print("homotopic_kernel: minima:", count_minima(kernel),
      " kernel <= image:", bool((kernel <= image).all()))
# --8<-- [end:kernel]

# --8<-- [start:lambda]
filtered = {}
for lam in (0, 5, 10, 20):
    filtered[lam] = grayscale.lambda_kernel(image, 4, lam)
    print(f"lambda_kernel, lambda_={lam:2d}: minima: {count_minima(filtered[lam])}")
print("lambda_=0 equals homotopic_kernel:", bool((filtered[0] == kernel).all()))
for lam in (5, 20):
    labels = skmeasure.label(morphology.local_minima(filtered[lam], connectivity=1),
                             connectivity=1)
    cells = {int(labels[int(round(y)), int(round(x))]) for y, x in centres}
    print(f"lambda_={lam}: the 9 cell centres lie in {len(cells)} different minima")
# --8<-- [end:lambda]

fig, axes = plt.subplots(1, 4, figsize=(9.2, 2.3), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
panels = ((f"image ({count_minima(image)} minima)", image),
          (f"homotopic_kernel ({count_minima(kernel)})", kernel),
          (f"lambda_kernel, 5 ({count_minima(filtered[5])})", filtered[5]),
          (f"lambda_kernel, 20 ({count_minima(filtered[20])})", filtered[20]))
for ax, (title, view) in zip(axes, panels):
    ax.imshow(view, cmap="gray", vmin=0, vmax=255, interpolation="nearest")
    ax.set_title(title, fontsize=9, color=TEXT)
    ax.set_xticks([])
    ax.set_yticks([])
fig.tight_layout()
fig.savefig(FIGURES / "grayscale.png", dpi=100)
plt.close(fig)
