# SPDX-License-Identifier: CECILL-2.1
# Figure of docs/examples/pgm-files.md. This script is the source of truth:
# the page includes parts of it with pymdownx.snippets. Run it from the
# repository root (the files are written to a temporary directory):
#     python docs/examples/scripts/pgm_files.py
import tempfile
from pathlib import Path

import matplotlib

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

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

# --8<-- [start:write]
r, c = np.mgrid[:48, :64]
shape = ((r - 24) ** 2 / 20**2 + (c - 32) ** 2 / 28**2 <= 1) & ((r - 24) ** 2 + (c - 32) ** 2 > 36)
images = {
    "shape.pgm": shape,                                         # bool: written as 0/255
    "skeleton.pgm": skeleton.ultimate_skeleton(shape, 8).astype(np.uint8),
    "distance.pgm": distance.distance_map(shape),               # int32
    "volume.pgm": np.random.default_rng(0).random((4, 5, 6)).astype(np.float32),
}

folder = Path(tempfile.mkdtemp())
for name, image in images.items():
    digitopo.io.write(folder / name, image)
    back = digitopo.io.read(folder / name)
    header = (folder / name).read_bytes()[:2].decode("ascii")
    print(f"{name:13s} {image.dtype!s:8s} -> {header} -> {back.dtype!s:8s} "
          f"shape {back.shape}, size {(folder / name).stat().st_size} bytes")
# --8<-- [end:write]

# --8<-- [start:check]
back = digitopo.io.read(folder / "shape.pgm")
print("bool values read back:", np.unique(back).tolist())
print("int32 identical:", bool((digitopo.io.read(folder / "distance.pgm") == images["distance.pgm"]).all()))
print("float32 identical:", bool((digitopo.io.read(folder / "volume.pgm") == images["volume.pgm"]).all()))
# --8<-- [end:check]

fig, axes = plt.subplots(1, 3, figsize=(7.6, 2.3), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
for ax, name in zip(axes, ("shape.pgm", "skeleton.pgm", "distance.pgm")):
    image = digitopo.io.read(folder / name)
    ax.imshow(image, cmap="gray", interpolation="nearest")
    ax.set_title(f"io.read('{name}'): {image.dtype}", fontsize=9, color=TEXT)
    ax.set_xticks([])
    ax.set_yticks([])
fig.tight_layout()
fig.savefig(FIGURES / "pgm-files.png", dpi=100)
plt.close(fig)
