# SPDX-License-Identifier: CECILL-2.1
# Figures of docs/examples/watershed.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/watershed.py
from pathlib import Path

import matplotlib

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

FIGURES = Path(__file__).resolve().parents[2] / "figures"
TEXT = "#222222"
BLUE = (0.145, 0.490, 0.878)     # #257de0
ORANGE = (0.957, 0.447, 0.188)   # #f47230

# --8<-- [start:image]
# A smooth random relief, rescaled to 0..255.
rng = np.random.default_rng(0)
smooth = ndi.gaussian_filter(rng.standard_normal((96, 128)), 6)
image = np.round(255 * (smooth - smooth.min()) / np.ptp(smooth)).astype(np.uint8)
# --8<-- [end:image]

# --8<-- [start:topological]
lowered = watershed.topological_watershed(image, 4)
minima = morphology.local_minima(image, connectivity=1)          # 4-connected minima
minima_after = morphology.local_minima(lowered, connectivity=1)
print("lowered <= image everywhere:", bool((lowered <= image).all()))
print("regional minima before:", skmeasure.label(minima, connectivity=1).max(),
      "after:", skmeasure.label(minima_after, connectivity=1).max())
print("points outside the minima after:", int((~minima_after).sum()), "of", image.size)
# --8<-- [end:topological]

# --8<-- [start:lines]
# Markers: the regional minima of the image (any binary mask can be used).
lines = watershed.watershed_lines(image, minima, 4)
labels = skmeasure.label(minima, connectivity=1)
basins = segmentation.watershed(image, labels, connectivity=1, watershed_line=True)
lines_skimage = basins == 0

near = ndi.binary_dilation(lines_skimage, np.ones((3, 3), bool))
print("line pixels, digitopo:", int(lines.sum()), " scikit-image:", int(lines_skimage.sum()))
print("common:", int((lines & lines_skimage).sum()),
      " digitopo within 1 pixel of scikit-image:", int((lines & near).sum()))
print("basins (4-connected), digitopo:", skmeasure.label(~lines, connectivity=1).max(),
      " scikit-image:", skmeasure.label(~lines_skimage, connectivity=1).max())
# --8<-- [end:lines]

grey = np.repeat((image / 255.0)[..., None], 3, axis=2)
compare = np.ones(image.shape + (3,))
compare[lines] = BLUE
compare[lines_skimage] = ORANGE
compare[lines & lines_skimage] = (0.13, 0.13, 0.13)
on_image = grey.copy()
on_image[lines] = BLUE

fig, axes = plt.subplots(1, 4, figsize=(9.2, 2.7), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
panels = (("image", grey), ("topological_watershed", lowered),
          ("watershed_lines (blue)", on_image), ("lines compared", compare))
for ax, (title, view) in zip(axes, panels):
    if view.ndim == 2:
        ax.imshow(view, cmap="gray", vmin=0, vmax=255, interpolation="nearest")
    else:
        ax.imshow(view, interpolation="nearest")
    ax.set_title(title, fontsize=9, color=TEXT)
    ax.set_xticks([])
    ax.set_yticks([])
    for spine in ax.spines.values():
        spine.set_color("#dddddd")
handles = [plt.Rectangle((0, 0), 1, 1, color=c) for c in (BLUE, ORANGE, (0.13, 0.13, 0.13))]
fig.legend(handles, ["digitopo only", "scikit-image only", "both"], loc="lower right",
           ncol=3, fontsize=8, frameon=False)
fig.tight_layout(rect=(0, 0.08, 1, 1))
fig.savefig(FIGURES / "watershed.png", dpi=100)
plt.close(fig)
