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

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import skeleton, topology

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


def overlay(obj, thin):
    """White background, object in light grey, thin result in blue."""
    rgb = np.ones(obj.shape + (3,))
    rgb[obj != 0] = (0.85, 0.85, 0.85)
    rgb[thin != 0] = BLUE
    return rgb


def show(panels, name, width=7.6, height=2.5, points=None):
    """One image per panel; points (rows, columns) are drawn as orange dots on the last one."""
    fig, axes = plt.subplots(1, len(panels), figsize=(width, height), facecolor="white",
                             edgecolor="#bbbbbb", linewidth=1)
    axes = np.atleast_1d(axes)
    for ax, (title, rgb) in zip(axes, panels):
        ax.imshow(rgb, 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")
    if points is not None:
        axes[-1].plot(points[1], points[0], "o", color=ORANGE, markersize=6,
                      markeredgecolor="white", markeredgewidth=0.8)
    fig.tight_layout()
    fig.savefig(FIGURES / name, dpi=100)
    plt.close(fig)


# --8<-- [start:shape]
# A disk with a hole, and two arms.
r, c = np.mgrid[:80, :120]
shape = ((r - 40) ** 2 + (c - 40) ** 2 <= 28**2) & ((r - 40) ** 2 + (c - 36) ** 2 > 9**2)
shape |= (np.abs(r - 40) <= 5) & (c >= 60) & (c <= 112)
shape |= (np.abs((r - 40) + (c - 70)) <= 6) & (c >= 60) & (c <= 95) & (r < 40)
print("shape:", int(shape.sum()), "pixels,", topology.topology(shape, 8))
# --8<-- [end:shape]

# 1. Sequential skeletons ------------------------------------------------------
# --8<-- [start:sequential]
ultimate = skeleton.ultimate_skeleton(shape, 8)
curvilinear = skeleton.curvilinear_skeleton(shape, 8)
for name, result in (("ultimate", ultimate), ("curvilinear", curvilinear)):
    print(f"{name:11s}", int(result.sum()), "pixels,", topology.topology(result, 8))
# --8<-- [end:sequential]

show([("shape", overlay(shape, np.zeros_like(shape))),
      ("ultimate_skeleton", overlay(shape, ultimate)),
      ("curvilinear_skeleton", overlay(shape, curvilinear))], "skeletons-sequential.png")

# 2. Parallel skeletons: symmetric or not -----------------------------------
# --8<-- [start:parallel]
square = np.zeros((14, 14), bool)
square[3:11, 3:11] = True                     # a square of even side
results = {
    "symmetric": skeleton.parallel_skeleton(square, 8),
    "asymmetric": skeleton.parallel_skeleton(square, 8, symmetric=False),
}
for name, result in results.items():
    print(f"square, {name:10s}", int(result.sum()), "pixels")

symmetric_curve = skeleton.parallel_skeleton(shape, 8, "curvilinear")
asymmetric = skeleton.parallel_skeleton(shape, 8, symmetric=False)
print("shape, symmetric curvilinear:", int(symmetric_curve.sum()), "pixels,",
      topology.topology(symmetric_curve, 8))
print("shape, asymmetric ultimate:  ", int(asymmetric.sum()), "pixels,",
      topology.topology(asymmetric, 8))
# --8<-- [end:parallel]

show([("square, symmetric", overlay(square, results["symmetric"])),
      ("square, asymmetric", overlay(square, results["asymmetric"])),
      ("curvilinear, symmetric", overlay(shape, symmetric_curve)),
      ("ultimate, asymmetric", overlay(shape, asymmetric))],
     "skeletons-parallel.png", width=8.4, height=2.4)

# 3. priority and inhibit -------------------------------------------------------
# --8<-- [start:priority]
# Default priority: squared Euclidean distance to the background.
default = skeleton.ultimate_skeleton(shape, 8)
# Another priority: the column index. The points on the left are removed first.
columns = np.broadcast_to(np.arange(shape.shape[1]), shape.shape)
by_column = skeleton.ultimate_skeleton(shape, 8, priority=columns)
for name, result in (("default", default), ("by column", by_column)):
    print(f"priority {name:9s}", int(result.sum()), "pixels,", topology.topology(result, 8))
# --8<-- [end:priority]

# --8<-- [start:inhibit]
# Points that must stay: the tips of the two arms and one point of the disk.
anchors = np.zeros_like(shape)
anchors[40, 111] = anchors[25, 85] = anchors[66, 40] = True
kept = skeleton.ultimate_skeleton(shape, 8, inhibit=anchors)
print("inhibit:", int(kept.sum()), "pixels,", topology.topology(kept, 8),
      "anchors kept:", bool(kept[anchors].all()))
# --8<-- [end:inhibit]

show([("priority: distance (default)", overlay(shape, default)),
      ("priority: column index", overlay(shape, by_column)),
      ("inhibit: 3 points (orange)", overlay(shape, kept))],
     "skeletons-priority-inhibit.png", points=np.nonzero(anchors))

# 4. A 3D skeleton -----------------------------------------------------------------
# --8<-- [start:volume]
z, y, x = np.mgrid[:40, :64, :72]
torus = (np.sqrt((x - 40) ** 2 + (y - 32) ** 2) - 16) ** 2 + (z - 20) ** 2 <= 6**2
tube = ((y - 32) ** 2 + (z - 20) ** 2 <= 4**2) & (x >= 52) & (x <= 69)
plate = (np.abs(z - 20) <= 3) & (np.abs(y - 32) <= 14) & (x >= 2) & (x <= 22)
volume = torus | tube | plate
print("volume:", volume.shape, int(volume.sum()), "voxels,", topology.topology(volume, 26))

curves = skeleton.curvilinear_skeleton(volume, 26)
surfaces = skeleton.parallel_skeleton(volume, 26, "surface")
for name, result in (("curvilinear", curves), ("surface", surfaces)):
    print(f"{name:11s}", int(result.sum()), "voxels,", topology.topology(result, 26))
# --8<-- [end:volume]

# --8<-- [start:projection]
def projection(obj, thin, axis):
    """Maximum projections along one axis: object in grey, skeleton in blue."""
    return overlay(obj.max(axis=axis), thin.max(axis=axis))


show([("volume, seen from above", projection(volume, np.zeros_like(volume), 0)),
      ("curvilinear_skeleton", projection(volume, curves, 0)),
      ("parallel_skeleton, surface", projection(volume, surfaces, 0)),
      ("surface, side view", projection(volume, surfaces, 1))],
     "skeletons-3d.png", width=8.4, height=2.3)
# --8<-- [end:projection]
