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

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import evaluation, topology
from scipy import ndimage as ndi
from skimage.draw import line

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

# --8<-- [start:reference]
# A vessel tree: segments drawn one pixel wide, then thickened to 5 pixels.
segments = [((5, 60), (40, 60)), ((40, 60), (75, 25)), ((40, 60), (75, 95)),
            ((60, 40), (60, 10)), ((58, 77), (30, 110)), ((75, 25), (90, 30)),
            ((75, 95), (92, 100))]
centre = np.zeros((96, 120), bool)
for (r0, c0), (r1, c1) in segments:
    centre[line(r0, c0, r1, c1)] = True
reference = ndi.binary_dilation(centre, np.ones((5, 5), bool))
print("reference:", topology.topology(reference, 8))
# --8<-- [end:reference]

# --8<-- [start:predictions]
cut = reference.copy()
cut[20:24, :] = False                      # the trunk is cut

merged = reference.copy()
merged[68:71, 32:89] = True                # a bridge between two branches

shifted = np.roll(reference, 2, axis=1)    # the whole tree moved by 2 pixels


def dice(a, b):
    return 2 * (a & b).sum() / (a.sum() + b.sum())


for name, prediction in (("cut", cut), ("merged", merged), ("shifted", shifted)):
    errors = evaluation.topology_errors(prediction, reference, 8)
    score = evaluation.cl_dice(prediction, reference, 8)
    print(f"{name:8s} Dice {dice(prediction, reference):.3f}  clDice {score:.3f}  {errors}")
# --8<-- [end:predictions]

fig, axes = plt.subplots(1, 4, figsize=(9.2, 2.6), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
panels = (("reference", reference), ("cut", cut), ("merged", merged), ("shifted", shifted))
for ax, (title, mask) in zip(axes, panels):
    rgb = np.ones(mask.shape + (3,))
    rgb[mask & reference] = (0.85, 0.85, 0.85)
    rgb[mask & ~reference] = (0.145, 0.490, 0.878)    # added pixels, blue
    rgb[~mask & reference] = (0.957, 0.447, 0.188)    # missing pixels, orange
    ax.imshow(rgb, interpolation="nearest")
    if title == "reference":
        ax.set_title(title, fontsize=9, color=TEXT)
    else:
        e = evaluation.topology_errors(mask, reference, 8)
        ax.set_title(f"{title}: objects {e.objects:+d}, holes {e.holes:+d}\n"
                     f"Dice {dice(mask, reference):.2f}, "
                     f"clDice {evaluation.cl_dice(mask, reference, 8):.2f}",
                     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 ((0.145, 0.490, 0.878),
                                                          (0.957, 0.447, 0.188))]
fig.legend(handles, ["added pixels", "missing pixels"], loc="lower right", ncol=2, fontsize=8,
           frameon=False)
fig.tight_layout(rect=(0, 0.07, 1, 1))
fig.savefig(FIGURES / "evaluation.png", dpi=100)
plt.close(fig)
