"""Original U-Net geometry and boundary weighting, not a trained segmentation model.
Source: Ronneberger, Fischer, Brox, arXiv:1505.04597v1 (2015).
Standard library only. Run python examples/unet.py [--json].
"""
import argparse
import json
import math


# region: geometry
def geometry(size=572):
    """Track valid 3x3 pairs, exact 2x2 pooling and 2x2 up-convolutions."""
    if not isinstance(size, int) or isinstance(size, bool) or size < 188:
        raise ValueError("Input must be an integer at least 188")
    original, skips = size, []
    for level in range(4):
        size -= 4
        if size % 2:
            raise ValueError("Pooling must divide exactly at all four levels")
        skips.append({"size": size, "channels": 64 * 2**level})
        size //= 2
    size -= 4
    bottleneck, decoder = size, []
    for skip in reversed(skips):
        up = 2 * size
        crop = (skip["size"] - up) // 2
        size = up - 4
        decoder.append({"up": up, "crop": crop, "size": size,
                        "channels": skip["channels"],
                        "concatenated_channels": 2 * skip["channels"]})
    return {"input": original, "encoder": skips, "bottleneck": bottleneck,
            "decoder": decoder, "output": size, "halo": (original-size)//2}
# endregion: geometry


# region: crop
def center_crop(values, height, width, target_height, target_width):
    """Crop a scalar channel; repeat independently for every skip channel."""
    dims = (height, width, target_height, target_width)
    if any(not isinstance(v, int) or isinstance(v, bool) or v <= 0 for v in dims):
        raise ValueError("Dimensions must be positive integers")
    if len(values) != height*width or target_height > height or target_width > width:
        raise ValueError("Invalid crop shape")
    top, left = (height-target_height)//2, (width-target_width)//2
    return [values[(top+y)*width+left+x]
            for y in range(target_height) for x in range(target_width)]
# endregion: crop


# region: boundary
def boundary_weight(d1, d2, wc=1.0, w0=10.0, sigma=5.0):
    """Original boundary term plus a supplied class-frequency weight."""
    if not all(math.isfinite(v) for v in (d1, d2, wc, w0, sigma)):
        raise ValueError("Values must be finite")
    if min(d1, d2, wc, w0) < 0 or sigma <= 0:
        raise ValueError("Require nonnegative distances/weights and positive sigma")
    return wc + w0 * math.exp(-(d1+d2)**2/(2*sigma**2))
# endregion: boundary


def self_check():
    g = geometry()
    assert [s["size"] for s in g["encoder"]] == [568, 280, 136, 64]
    assert g["bottleneck"] == 28 and g["output"] == 388
    assert [s["crop"] for s in g["decoder"]] == [4, 16, 40, 88]
    assert geometry(588)["output"] == 404
    assert center_crop(list(range(35)), 5, 7, 3, 3) == [9, 10, 11, 16, 17, 18, 23, 24, 25]
    assert boundary_weight(0, 0) == 11
    assert boundary_weight(2, 3) == boundary_weight(3, 2)
    assert boundary_weight(2, 3) > boundary_weight(5, 6)
    try:
        geometry(573)
    except ValueError:
        pass
    else:
        raise AssertionError("Incompatible pooling geometry accepted")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()
    self_check()
    report = {"kind": "analytical illustration", "geometry": geometry(),
              "gap_weights": [boundary_weight(d, d) for d in (0, 1, 2, 5, 10)]}
    print(json.dumps(report, indent=2) if args.json else "U-Net self-check passed: 572 → 388; halo 92; concat skips; boundary weights checked.")


if __name__ == "__main__":
    main()
