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

import matplotlib

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

FIGURES = Path(__file__).resolve().parents[2] / "figures"
TEXT = "#222222"
# Fixed order of categorical colours, one per branch kind.
KIND_COLOURS = {
    measure.BranchKind.TERMINAL: "#f47230",
    measure.BranchKind.INTERNAL: "#257de0",
    measure.BranchKind.ISOLATED: "#00b894",
    measure.BranchKind.CYCLE: "#ee7fac",
}

# --8<-- [start:shape]
# A thick "Y" with a ring, and six small bumps on its boundary.
r, c = np.mgrid[:80, :140]
shape = (np.abs(r - 55) <= 6) & (c >= 8) & (c <= 132)
shape |= (np.abs((r - 55) + (c - 75)) <= 6) & (r >= 8) & (r <= 55)
shape |= (r - 55) ** 2 + (c - 32) ** 2 <= 15**2
shape &= (r - 55) ** 2 + (c - 32) ** 2 > 5**2
for row, col in [(48, 60), (62, 95), (62, 115), (48, 110), (40, 30), (31, 96)]:
    shape[row - 1:row + 2, col - 1:col + 2] = True
print("shape:", topology.topology(shape, 8))

curve = skeleton.curvilinear_skeleton(shape, 8)
# --8<-- [end:shape]

# --8<-- [start:branches]
b = measure.branches(curve, 8)
print(len(b), "branches:", {k.name: b.count(k) for k in measure.BranchKind})
for k in range(len(b)):
    kind = measure.BranchKind(b.kind[k]).name
    print(f"  {k:2d} {kind:8s} length {b.length[k]:5.1f}  from {b.start[k]} to {b.end[k]}")
# --8<-- [end:branches]

# --8<-- [start:prune]
pruned = measure.prune(curve, 8, min_length=8)
again = measure.branches(pruned, 8)
print("after prune:", len(again), "branches:", {k.name: again.count(k) for k in measure.BranchKind})
print("topology before:", topology.topology(b.skeleton, 8))
print("topology after: ", topology.topology(pruned, 8))
# --8<-- [end:prune]


def kind_image(shape, branches):
    """0 background, 1 object, 2 + kind on each branch, 7 on the junctions."""
    out = shape.astype(np.uint8)
    for path, kind in zip(branches.paths, branches.kind):
        out[tuple(path.T)] = 2 + int(kind)
    out[branches.labels == -1] = 7
    return out


cmap = ListedColormap(["white", "#d9d9d9", "white"] + list(KIND_COLOURS.values()) + ["#222222"])
fig, axes = plt.subplots(1, 2, figsize=(8.4, 3.0), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
for ax, (title, result) in zip(axes, (("measure.branches(curve, 8)", b),
                                       ("after measure.prune(curve, 8, min_length=8)", again))):
    ax.imshow(kind_image(shape, result), cmap=cmap, vmin=0, vmax=7, 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")
present = [k for k in KIND_COLOURS if b.count(k)]  # the legend lists the kinds shown
handles = [plt.Rectangle((0, 0), 1, 1, color=KIND_COLOURS[k]) for k in present]
handles.append(plt.Rectangle((0, 0), 1, 1, color="#222222"))
fig.legend(handles, [k.name.lower() for k in present] + ["junction"], loc="lower center",
           ncol=len(handles), fontsize=8, frameon=False)
fig.tight_layout(rect=(0, 0.08, 1, 1))
fig.savefig(FIGURES / "branches-prune.png", dpi=100)
plt.close(fig)

# --8<-- [start:spacing]
# A ring of median radius 30 um, imaged twice: with square pixels of 1 um, and
# with pixels of 2 um (rows) x 1 um (columns).
def ring_image(step):
    rows, cols = np.mgrid[:int(100 / step[0]), :int(100 / step[1])]
    y = (rows - rows.shape[0] // 2) * step[0]
    x = (cols - cols.shape[1] // 2) * step[1]
    return (x**2 + y**2 <= 34**2) & (x**2 + y**2 >= 26**2)


expected = 2 * np.pi * 30
results = {}
for step in [(1.0, 1.0), (2.0, 1.0)]:
    image = ring_image(step)
    centre = skeleton.parallel_skeleton(image, 8, "curvilinear")
    ring = measure.branches(centre, 8, spacing=step)
    results[step] = (image, ring)
    kinds = [measure.BranchKind(k).name for k in ring.kind]
    error = 100 * (ring.length[0] - expected) / expected
    print(f"spacing {step}: {kinds}, length {ring.length[0]:.1f} um, "
          f"circle {expected:.1f} um, {error:+.1f} %")
# --8<-- [end:spacing]

fig, axes = plt.subplots(1, 2, figsize=(5.6, 2.9), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
for ax, (step, (image, ring)) in zip(axes, results.items()):
    view = image.astype(np.uint8) + ring.skeleton
    # aspect = row step / column step: the image is shown in micrometres.
    ax.imshow(view, cmap=ListedColormap(["white", "#d9d9d9", "#257de0"]), vmin=0, vmax=2,
              aspect=step[0] / step[1], interpolation="nearest")
    ax.set_title(f"spacing={step}: {image.shape[0]} x {image.shape[1]} pixels",
                 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 / "branches-spacing.png", dpi=100)
plt.close(fig)
