"""Mask R-CNN arithmetic: bilinear RoI sampling and matched-class mask BCE.
Pinned paper: arXiv:1703.06870v3. Standard library; no trained COCO detector.
Feature-grid integer centers; continuous unaligned coordinates, no -0.5 shift,
no legacy +1 width; clamp samples at boundary. Run with optional --json.
"""
import argparse
import json
import math


# region: bilinear
def bilinear(values, height, width, x, y):
    """Interpolate four grid centers with an explicit clamped boundary policy."""
    if height <= 0 or width <= 0 or len(values) != height*width:
        raise ValueError("Invalid feature map")
    if not all(math.isfinite(v) for v in [x, y, *values]):
        raise ValueError("Values and coordinates must be finite")
    x, y = max(0, min(width-1, x)), max(0, min(height-1, y))
    x0, y0 = math.floor(x), math.floor(y)
    x1, y1 = min(x0+1, width-1), min(y0+1, height-1)
    dx, dy = x-x0, y-y0
    return ((1-dy)*((1-dx)*values[y0*width+x0]+dx*values[y0*width+x1])
            + dy*((1-dx)*values[y1*width+x0]+dx*values[y1*width+x1]))
# endregion: bilinear


# region: roi
def roi_align(values, height, width, box, out_height=2, out_width=2, samples=2):
    """Four regular sample locations per bin, then average their values."""
    if len(box) != 4 or not all(math.isfinite(v) for v in box):
        raise ValueError("Invalid box")
    x1, y1, x2, y2 = box
    if x2 <= x1 or y2 <= y1 or min(out_height, out_width, samples) <= 0:
        raise ValueError("Box and output sizes must be positive")
    output = []
    for row in range(out_height):
        for col in range(out_width):
            points = []
            for sy in range(samples):
                for sx in range(samples):
                    x = x1+(col+(sx+0.5)/samples)*(x2-x1)/out_width
                    y = y1+(row+(sy+0.5)/samples)*(y2-y1)/out_height
                    points.append(bilinear(values, height, width, x, y))
            output.append(sum(points)/len(points))
    return output
# endregion: roi


# region: mask
def mask_loss(logits_by_class, target, class_index):
    """Mean independent sigmoid BCE on the ground-truth class channel only."""
    if not 0 <= class_index < len(logits_by_class) or not target:
        raise ValueError("Invalid matched class or empty target")
    if any(t not in (0, 1) for t in target):
        raise ValueError("Masks must be binary")
    if any(len(row) != len(target) for row in logits_by_class):
        raise ValueError("Mask shape mismatch")
    logits = logits_by_class[class_index]
    if not all(math.isfinite(z) for row in logits_by_class for z in row):
        raise ValueError("Logits must be finite")
    return sum(max(z, 0)-z*t+math.log1p(math.exp(-abs(z)))
               for z, t in zip(logits, target))/len(target)
# endregion: mask


def self_check():
    affine = [2*x+3*y+1 for y in range(4) for x in range(5)]
    for x, y in ((0, 0), (4, 3), (1.25, 2.5), (2, 1)):
        assert abs(bilinear(affine, 4, 5, x, y)-(2*x+3*y+1)) < 1e-12
    assert bilinear(affine, 4, 5, -1, 20) == affine[15]
    out = roi_align(affine, 4, 5, [0.2, 0.3, 3.8, 2.7])
    assert len(out) == 4 and all(math.isfinite(v) for v in out)
    assert mask_loss([[0, 0], [1, 2]], [1, 0], 0) == math.log(2)
    assert mask_loss([[0, 0], [-99, 99]], [1, 0], 0) == math.log(2)
    assert mask_loss([[1000, -1000]], [1, 0], 0) == 0


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()
    self_check()
    values = [x*x+y*y for y in range(5) for x in range(5)]
    report = {"kind": "analytical illustration", "roi": roi_align(values, 5, 5, [0.3, 0.6, 3.5, 3.8]),
              "mask_loss": mask_loss([[0, 1, -1, 2], [3, 3, 3, 3]], [0, 1, 0, 1], 0)}
    print(json.dumps(report, indent=2) if args.json else "Mask R-CNN self-check passed: interpolation, continuous bins and matched-class BCE.")


if __name__ == "__main__":
    main()
