"""Reproduce the Berea shell counts from the public 200-by-200-by-200 segmentation.

Usage: python reproduce_edt.py berea_100_to_300.npz
The article used SciPy 1.18.1. The script reads the original NPZ locally.
"""
from __future__ import annotations

import argparse
import hashlib
import math
import struct
from fractions import Fraction
from pathlib import Path

import numpy as np
import scipy
from scipy import ndimage


SOURCE_SHA256 = "0c55fa043b95724000f2c56d9d947409932ba72230413ed5d738410c86838d66"
SPACING_METERS = 5.345e-6


def enumerate_squared(pores: np.ndarray, spacing: float) -> np.ndarray:
    """Minimize separately rounded squared costs by enumerating each successive axis."""
    costs = np.where(pores, np.inf, 0.0)
    for axis, length in enumerate(pores.shape):
        indices = np.arange(length)
        offsets = indices.astype(np.float64) * spacing
        squares = np.square(offsets)
        terms = squares[np.abs(indices[:, None] - indices[None, :])]
        lines = np.ascontiguousarray(np.moveaxis(costs, axis, -1))
        batches = lines.reshape(-1, length)
        for start in range(0, len(batches), 8):
            batch = batches[start : start + 8]
            candidates = batch[:, None, :] + terms[None, :, :]
            batch[:] = candidates.min(axis=-1)
        costs = np.moveaxis(lines, -1, axis)
    return costs


def rounded_radius(shell: int, spacing: float) -> float:
    """Round the positive radius once by testing both midpoints with exact rationals."""
    if shell == 0:
        return 0.0
    target_squared = Fraction(spacing) ** 2 * shell
    guess = spacing * math.sqrt(shell)
    while True:
        below = math.nextafter(guess, 0.0)
        above = math.nextafter(guess, math.inf)
        left = ((Fraction(below) + Fraction(guess)) / 2) ** 2
        right = ((Fraction(above) + Fraction(guess)) / 2) ** 2
        bits = struct.unpack(">Q", struct.pack(">d", guess))[0]
        odd = bool(bits & 1)
        if target_squared < left or (target_squared == left and odd):
            guess = below
        elif target_squared > right or (target_squared == right and odd):
            guess = above
        else:
            return guess


def attainable_shells(shape: tuple[int, ...], limit: int) -> list[int]:
    """List squared grid radii reachable by a displacement bounded by the volume."""
    shell_ids = {0}
    for length in shape:
        squares = [k * k for k in range(min(length, math.isqrt(limit) + 1))]
        shell_ids = {s + v for s in shell_ids for v in squares if s + v <= limit}
    return sorted(shell_ids)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("volume", type=Path, help="Original Berea NPZ from the article")
    args = parser.parse_args()
    if hashlib.sha256(args.volume.read_bytes()).hexdigest() != SOURCE_SHA256:
        raise ValueError("Unexpected input archive. Check the data link and the SHA-256.")
    with np.load(args.volume, allow_pickle=False) as archive:
        pores = archive["im"]
    if pores.shape != (200, 200, 200) or pores.dtype != np.bool_:
        raise ValueError("Expected a 200-by-200-by-200 Boolean pore mask.")

    h = SPACING_METERS
    distances = np.sqrt(enumerate_squared(pores, h))
    scipy_map = ndimage.distance_transform_edt(pores, sampling=h)
    flip = (slice(None, None, -1),) * pores.ndim
    reflected = ndimage.distance_transform_edt(pores[flip], sampling=h)[flip]
    unit_roots = ndimage.distance_transform_edt(pores)[pores]
    # At this volume size, squaring a rounded unit-grid root and taking the
    # nearest integer recovers the exact squared integer distance.
    unit_squared = np.rint(np.square(unit_roots)).astype(np.int32)
    shells = attainable_shells(pores.shape, int(unit_squared.max()))
    radii = [rounded_radius(j, h) for j in shells]
    by_enumeration = np.searchsorted(np.sort(distances[pores]), radii, side="right")
    by_scipy = np.searchsorted(np.sort(scipy_map[pores]), radii, side="right")

    print(f"SciPy {scipy.__version__}, {pores.sum()} pore voxels, {len(shells)} radii")
    print("SciPy distances changed by reflection:", np.count_nonzero(scipy_map != reflected))
    print("Returned roots differing from enumeration:", np.count_nonzero(scipy_map != distances))
    print("shell  radius_hex                 enumeration    SciPy  difference")
    for j, t, a, b in zip(shells, radii, by_enumeration, by_scipy):
        if a != b:
            print(f"{j:5d}  {t.hex():<25s} {a:11d} {b:8d} {a-b:11d}")
    radius = radii[shells.index(26)]
    on_shell = unit_squared == 26
    integer_limit = int((Fraction(radius) / Fraction(h)) ** 2)
    rows = (
        ("Integer grid", unit_squared <= 26),
        ("Geometry at stored radius", unit_squared <= integer_limit),
        ("Enumeration", distances[pores] <= radius),
        ("SciPy", scipy_map[pores] <= radius),
        ("Reflected SciPy", reflected[pores] <= radius),
    )
    print("rule, included on shell 26, cumulative pore count")
    for name, included in rows:
        print(name, np.count_nonzero(included & on_shell), np.count_nonzero(included), sep=", ")
    different = pores & ((distances <= radius) != (scipy_map <= radius))
    xor = distances[different].view(np.uint64) ^ scipy_map[different].view(np.uint64)
    print("Distinct bitwise XORs at differing shell-26 decisions:", np.unique(xor).tolist())
    for neighbor in (math.nextafter(radius, 0.0), math.nextafter(radius, math.inf)):
        print("Adjacent radius:", neighbor.hex(), np.count_nonzero(pores & (distances <= neighbor)),
              np.count_nonzero(pores & (scipy_map <= neighbor)))
    for name, values in (("Enumeration", distances), ("SciPy", scipy_map)):
        print(f"{name} root at (109, 116, 97):", float(values[109, 116, 97]).hex())


if __name__ == "__main__":
    main()
