"""2장 · 박스와 IoU: 박스 표현 바꾸기, IoU, GIoU, L1 거리와 박스 회귀 손실.

무엇을 하나
  1. 박스의 두 표현 (cx, cy, w, h) ↔ (x0, y0, x1, y1) 을 서로 바꾸고, 도형 세상의 정답 박스를 96 픽셀 좌표로 되돌려 본다.
  2. IoU 와 GIoU 를 구현하고, 본문에서 손으로 계산한 값(A = (1, 1, 5, 4), B = (3, 2, 7, 6))과 비교한다.
  3. "IoU 0.5 는 얼마나 겹친 것인가" 를 숫자로 본다 (가로로 밀기, 대각선으로 밀기, 크기만 다르게 하기, 작은 박스의 불리함).
  4. 모든 쌍(N × M) 계산의 브로드캐스팅을 모양으로 따라가고, 짝끼리 버전과 비교한다.
  5. 직접 구현이 맞는지 확인한다 (무작위 박스 1000쌍의 성질 검사, 픽셀을 하나하나 세는 방법과의 대조).
  6. L1 · 1 − IoU · 1 − GIoU 의 값과 기울기를 autograd 로 확인한다 (겹치지 않으면 IoU 손실의 기울기는 0).
  7. 예측 박스를 정답에서 밀어 가며 세 값의 곡선과 손실 표면을 그리고,
     경사 하강법으로 박스 하나를 정답에 맞춰 본다 (네 가지 손실의 궤적과 수렴 곡선).
  8. 도형 세상 그림 위에 정답 박스와 흐트러뜨린 박스, 그 IoU · GIoU 를 그린다.

실행
  python ch02_boxes.py            # 본문 결과. CPU 로 8 – 15초 (GPU 는 쓰지 않는다)
  python ch02_boxes.py --quick    # 점 · 스텝 수를 줄인 빠른 확인. 약 3초
그림은 --fig-dir (기본 figures/) 에 ch02-*.png 로 저장된다.

3장부터의 실습 파일이 이 파일의 박스 함수들
(box_cxcywh_to_xyxy, box_xyxy_to_cxcywh, box_area, box_iou, generalized_box_iou,
 paired_box_iou, paired_generalized_box_iou)을 그대로 가져다 쓴다.
"""

from __future__ import annotations

import argparse
import os
import time

import torch


# --8<-- [start:convert]
def box_cxcywh_to_xyxy(boxes: torch.Tensor) -> torch.Tensor:
    """(cx, cy, w, h) → (x0, y0, x1, y1). 마지막 차원이 4 이면 앞의 모양은 무엇이든 된다.

    중심에서 너비 · 높이의 절반만큼 왼쪽 · 위로 가면 (x0, y0), 오른쪽 · 아래로 가면 (x1, y1) 이다.
    """
    cx, cy, w, h = boxes.unbind(-1)  # 마지막 차원을 풀어 네 텐서로. 각각의 모양은 (...,)
    return torch.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], dim=-1)  # 다시 (..., 4)


def box_xyxy_to_cxcywh(boxes: torch.Tensor) -> torch.Tensor:
    """(x0, y0, x1, y1) → (cx, cy, w, h). 중심은 두 모서리의 평균, 너비 · 높이는 두 모서리의 차."""
    x0, y0, x1, y1 = boxes.unbind(-1)
    return torch.stack([(x0 + x1) / 2, (y0 + y1) / 2, x1 - x0, y1 - y0], dim=-1)


def box_area(boxes: torch.Tensor) -> torch.Tensor:
    """(x0, y0, x1, y1) 박스의 넓이 = 가로 × 세로. 모양 (..., 4) → (...,)."""
    return (boxes[..., 2] - boxes[..., 0]) * (boxes[..., 3] - boxes[..., 1])
# --8<-- [end:convert]


# --8<-- [start:iou]
def box_iou(boxes1: torch.Tensor, boxes2: torch.Tensor):
    """모든 쌍의 IoU. boxes1: (N, 4), boxes2: (M, 4), 둘 다 (x0, y0, x1, y1).

    돌려주는 값: iou (N, M), union (N, M). [i, j] 가 boxes1[i] 와 boxes2[j] 의 값이다.
    """
    area1 = box_area(boxes1)  # (N,)
    area2 = box_area(boxes2)  # (M,)
    # 교집합 사각형: 왼쪽 위는 두 박스의 왼쪽 위 가운데 큰 값, 오른쪽 아래는 작은 값
    # boxes1[:, None, :2] 는 (N, 1, 2), boxes2[None, :, :2] 는 (1, M, 2) → 브로드캐스팅으로 (N, M, 2)
    left_top = torch.max(boxes1[:, None, :2], boxes2[None, :, :2])  # (N, M, 2)
    right_bottom = torch.min(boxes1[:, None, 2:], boxes2[None, :, 2:])  # (N, M, 2)
    wh = (right_bottom - left_top).clamp(min=0)  # 겹치지 않으면 음수 → 0 으로 자른다
    inter = wh[..., 0] * wh[..., 1]  # (N, M)
    union = area1[:, None] + area2[None, :] - inter  # (N, 1) + (1, M) − (N, M) → (N, M)
    return inter / union, union
# --8<-- [end:iou]


# --8<-- [start:giou]
def generalized_box_iou(boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor:
    """모든 쌍의 GIoU (N, M). GIoU = IoU − (C 의 넓이 − 합집합) / C 의 넓이. C 는 두 박스를 모두 덮는 가장 작은 박스."""
    iou, union = box_iou(boxes1, boxes2)
    # 둘러싸는 박스 C: 왼쪽 위는 작은 값, 오른쪽 아래는 큰 값 (교집합과 max · min 이 정확히 반대)
    left_top = torch.min(boxes1[:, None, :2], boxes2[None, :, :2])
    right_bottom = torch.max(boxes1[:, None, 2:], boxes2[None, :, 2:])
    wh = (right_bottom - left_top).clamp(min=0)
    enclosing = wh[..., 0] * wh[..., 1]
    return iou - (enclosing - union) / enclosing
# --8<-- [end:giou]


# --8<-- [start:paired]
def paired_box_iou(boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor:
    """짝지어진 박스끼리의 IoU. boxes1, boxes2: (K, 4) (x0, y0, x1, y1) → (K,). k 번째끼리만 계산한다."""
    left_top = torch.max(boxes1[:, :2], boxes2[:, :2])  # (K, 2): 새 축을 끼우지 않으니 같은 줄끼리만 만난다
    right_bottom = torch.min(boxes1[:, 2:], boxes2[:, 2:])
    wh = (right_bottom - left_top).clamp(min=0)
    inter = wh[:, 0] * wh[:, 1]
    union = box_area(boxes1) + box_area(boxes2) - inter
    return inter / union


def paired_generalized_box_iou(boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor:
    """짝지어진 박스끼리의 GIoU (K,). 손실을 계산할 때는 매칭된 쌍만 필요하므로 이 함수를 쓴다."""
    left_top = torch.max(boxes1[:, :2], boxes2[:, :2])
    right_bottom = torch.min(boxes1[:, 2:], boxes2[:, 2:])
    wh = (right_bottom - left_top).clamp(min=0)
    inter = wh[:, 0] * wh[:, 1]
    union = box_area(boxes1) + box_area(boxes2) - inter
    iou = inter / union
    outer_left_top = torch.min(boxes1[:, :2], boxes2[:, :2])
    outer_right_bottom = torch.max(boxes1[:, 2:], boxes2[:, 2:])
    outer_wh = (outer_right_bottom - outer_left_top).clamp(min=0)
    enclosing = outer_wh[:, 0] * outer_wh[:, 1]
    return iou - (enclosing - union) / enclosing
# --8<-- [end:paired]


# --8<-- [start:losses]
def box_l1(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    """L1 거리. pred, target: (K, 4) (cx, cy, w, h) → (K,). 네 숫자의 차의 절댓값을 더한다."""
    return (pred - target).abs().sum(dim=-1)


def iou_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    """IoU 손실 1 − IoU. pred, target: (K, 4) (cx, cy, w, h) → (K,)."""
    return 1 - paired_box_iou(box_cxcywh_to_xyxy(pred), box_cxcywh_to_xyxy(target))


def giou_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    """GIoU 손실 1 − GIoU. 값의 범위는 0 (완전히 일치) – 2 (한없이 멀리)."""
    return 1 - paired_generalized_box_iou(box_cxcywh_to_xyxy(pred), box_cxcywh_to_xyxy(target))


def detr_box_loss(pred: torch.Tensor, target: torch.Tensor, l1_coef: float = 5.0, giou_coef: float = 2.0):
    """DETR 계열의 박스 손실 = 5 · L1 + 2 · (1 − GIoU). 계수 5 와 2 는 DETR · LW-DETR · RF-DETR 이 모두 쓰는 값."""
    return l1_coef * box_l1(pred, target) + giou_coef * giou_loss(pred, target)


LOSSES = {  # 이름 → 손실 함수. 실험 · 그림에서 이 순서로 쓴다
    "1 - IoU": iou_loss,
    "1 - GIoU": giou_loss,
    "L1": box_l1,
    "5 L1 + 2 (1 - GIoU)": detr_box_loss,
}
# --8<-- [end:losses]


def fmt(values, digits: int = 4) -> str:
    """숫자 목록을 보기 좋게."""
    return "[" + ", ".join(f"{round(float(v), digits) + 0.0:.{digits}f}" for v in values) + "]"  # + 0.0 은 -0.0 을 0.0 으로


# --8<-- [start:pixels]
def pixel_example(size: int = 96) -> None:
    """도형 세상의 정답 박스(정규화 cx, cy, w, h)를 픽셀 좌표로 되돌리고, 실제로 칠해진 픽셀과 견준다."""
    from rf_shapes import CLASS_NAMES_KO, ShapesDataset, shape_mask

    dataset = ShapesDataset(8, size=size, seed=0)
    objects = dataset.scenes[0]  # 첫 그림의 객체 목록
    print(f"[1] 도형 세상 첫 그림({size}×{size})의 정답 박스를 픽셀로 되돌리기")
    for obj in objects:
        box = torch.tensor(obj["box"])  # 정규화 (cx, cy, w, h)
        xyxy = box_cxcywh_to_xyxy(box)  # 정규화 (x0, y0, x1, y1)
        pixels = xyxy * size  # 픽셀 좌표: 가로 · 세로 모두 size 를 곱한다
        # 실제로 칠해진 픽셀: 픽셀 (행 i, 열 j) 의 중심 ((j + 0.5)/size, (i + 0.5)/size) 이 도형 안이면 True
        mask = shape_mask(obj["cls"], obj["box"], size)
        rows = mask.any(axis=1).nonzero()[0]
        cols = mask.any(axis=0).nonzero()[0]
        # 열 j 의 픽셀은 가로로 [j, j + 1] 을 차지하므로, 칠해진 픽셀을 꼭 맞게 싸는 박스는 [첫 열, 마지막 열 + 1]
        tight = torch.tensor([cols[0], rows[0], cols[-1] + 1, rows[-1] + 1], dtype=torch.float32)
        iou = paired_box_iou(pixels[None], tight[None]).item()
        print(f"  {CLASS_NAMES_KO[obj['cls']]:<4} 정규화 (cx, cy, w, h) = {fmt(box)}")
        print(f"       정규화 (x0, y0, x1, y1) = {fmt(xyxy)}")
        print(f"       픽셀   (x0, y0, x1, y1) = {fmt(pixels, 2)}")
        print(f"       칠해진 픽셀을 싸는 박스 = {fmt(tight, 0)}   두 박스의 IoU = {iou:.4f}")
    # 해상도를 바꿔도 정규화 좌표는 그대로이고 픽셀 좌표만 달라진다
    box = torch.tensor(objects[0]["box"])
    for other in (64, 96, 128):
        print(f"  해상도 {other:>3}: 첫 객체의 픽셀 박스 = {fmt(box_cxcywh_to_xyxy(box) * other, 2)}")
# --8<-- [end:pixels]


# --8<-- [start:hand]
def hand_example() -> None:
    """본문에서 손으로 계산하는 예: A = (1, 1, 5, 4), B = (3, 2, 7, 6)."""
    a = torch.tensor([[1.0, 1.0, 5.0, 4.0]])  # (1, 4)
    b = torch.tensor([[3.0, 2.0, 7.0, 6.0]])
    iou, union = box_iou(a, b)  # 둘 다 (1, 1)
    giou = generalized_box_iou(a, b)
    print("[2] 손계산 예  A = (1, 1, 5, 4), B = (3, 2, 7, 6)")
    print(f"  A 의 (cx, cy, w, h) = {fmt(box_xyxy_to_cxcywh(a)[0], 1)},  B 의 (cx, cy, w, h) = {fmt(box_xyxy_to_cxcywh(b)[0], 1)}")
    print(f"  되돌리기: {fmt(box_cxcywh_to_xyxy(box_xyxy_to_cxcywh(a))[0], 1)}")
    print(f"  넓이 A = {box_area(a).item():.0f}, 넓이 B = {box_area(b).item():.0f}")
    print(f"  교집합 = {(iou * union).item():.0f}, 합집합 = {union.item():.0f}")
    print(f"  IoU  = {iou.item():.4f}")
    print(f"  GIoU = {giou.item():.4f}")
    print(f"  L1 (cx, cy, w, h 로) = {box_l1(box_xyxy_to_cxcywh(a), box_xyxy_to_cxcywh(b)).item():.1f}")
    # 크기 불변: 두 박스를 같은 비율로 키우거나, 가로 · 세로를 서로 다른 비율로 늘려도 IoU · GIoU 는 그대로
    scale = torch.tensor([96.0, 64.0, 96.0, 64.0])  # x 에는 96, y 에는 64 를 곱한다
    print(f"  모두 10배:          IoU = {box_iou(a * 10, b * 10)[0].item():.4f}, GIoU = {generalized_box_iou(a * 10, b * 10).item():.4f}"
          f", L1 = {box_l1(box_xyxy_to_cxcywh(a * 10), box_xyxy_to_cxcywh(b * 10)).item():.1f}")
    print(f"  가로 96배 세로 64배: IoU = {box_iou(a * scale, b * scale)[0].item():.4f}, GIoU = {generalized_box_iou(a * scale, b * scale).item():.4f}")
# --8<-- [end:hand]


# --8<-- [start:shift]
def shifted_pair(width: float, height: float, dx: float, dy: float = 0.0, scale: float = 1.0):
    """정답 박스 (0, 0, width, height) 와, 그것을 (dx, dy) 만큼 밀고 가운데를 기준으로 scale 배 한 예측 박스. 모양 (1, 4) 둘."""
    target = torch.tensor([[0.0, 0.0, width, height]])
    center = torch.tensor([width / 2 + dx, height / 2 + dy, width * scale, height * scale])
    return box_cxcywh_to_xyxy(center)[None], target


def how_much_overlap() -> None:
    """IoU 0.5 · 0.75 는 얼마나 어긋난 것인가, 그리고 작은 박스는 왜 불리한가."""
    print("[3] 같은 크기(가로 w)의 박스를 가로로 d 만큼 밀기: IoU = (w − d) / (w + d)")
    width = 1.0
    for name, d in [("w/7", 1 / 7), ("w/3", 1 / 3), ("w/2", 1 / 2), ("w", 1.0)]:
        pred, target = shifted_pair(width, 0.6, d)
        iou = paired_box_iou(pred, target).item()
        print(f"  d = {name:<4} → IoU = {iou:.4f}   (공식 {(width - d) / (width + d):.4f})")
    print("  정사각형(한 변 w)을 가로 · 세로 둘 다 d 만큼 밀기")
    for d in (0.0742, 0.1835, 1 / 3):
        pred, target = shifted_pair(1.0, 1.0, d, d)
        print(f"  d = {d:.4f} w → IoU = {paired_box_iou(pred, target).item():.4f}")
    print("  가운데는 같고 크기만 s 배")
    for s in (0.866, 0.7071, 0.5, 1.4142, 2.0):
        pred, target = shifted_pair(1.0, 1.0, 0.0, 0.0, scale=s)
        print(f"  s = {s:<6} → IoU = {paired_box_iou(pred, target).item():.4f}")
    print("  같은 2 픽셀 오차, 다른 크기의 정사각형 (가로로만 / 가로 · 세로 둘 다)")
    for side in (80, 40, 20, 10, 5):
        pred_x, target = shifted_pair(side, side, 2.0)
        pred_xy, _ = shifted_pair(side, side, 2.0, 2.0)
        print(f"  한 변 {side:>2} 픽셀: IoU = {paired_box_iou(pred_x, target).item():.4f} / {paired_box_iou(pred_xy, target).item():.4f}")
# --8<-- [end:shift]


# --8<-- [start:broadcast]
def broadcast_example() -> None:
    """모든 쌍 계산의 모양을 한 단계씩 찍어 본다. 예측 3개 × 정답 2개."""
    preds = torch.tensor([[1.0, 1.0, 5.0, 4.0], [3.0, 2.0, 7.0, 6.0], [8.0, 8.0, 9.0, 9.0]])  # (N = 3, 4)
    targets = torch.tensor([[3.0, 2.0, 7.0, 6.0], [0.0, 0.0, 4.0, 4.0]])  # (M = 2, 4)
    a = preds[:, None, :2]  # (3, 1, 2): 예측마다의 왼쪽 위 (x0, y0). 가운데에 길이 1 인 축을 끼웠다
    b = targets[None, :, :2]  # (1, 2, 2): 정답마다의 왼쪽 위. 맨 앞에 길이 1 인 축을 끼웠다
    left_top = torch.max(a, b)  # 길이 1 인 축이 상대의 길이만큼 늘어난다 → (3, 2, 2)
    print("[4] 모든 쌍 계산의 모양")
    print(f"  preds {tuple(preds.shape)}, targets {tuple(targets.shape)}")
    print(f"  preds[:, None, :2] {tuple(a.shape)}  vs  targets[None, :, :2] {tuple(b.shape)}  →  max {tuple(left_top.shape)}")
    iou, _ = box_iou(preds, targets)
    giou = generalized_box_iou(preds, targets)
    print(f"  IoU  (3, 2) =\n{iou}")
    print(f"  GIoU (3, 2) =\n{giou}")
    # 짝끼리: 예측 k 와 정답 k 만. 여기서는 앞의 두 예측을 두 정답과 짝지었다
    print(f"  짝끼리 IoU (2,) = {paired_box_iou(preds[:2], targets)}  (= 위 행렬의 [0, 0], [1, 1])")
# --8<-- [end:broadcast]


# --8<-- [start:check]
def random_boxes(n: int, generator: torch.Generator) -> torch.Tensor:
    """0 – 1 안에 들어가는 무작위 박스 n 개. (n, 4) (x0, y0, x1, y1)."""
    wh = torch.rand(n, 2, generator=generator) * 0.5 + 0.02  # 너비 · 높이 0.02 – 0.52
    center = wh / 2 + torch.rand(n, 2, generator=generator) * (1 - wh)  # 박스가 그림 밖으로 나가지 않게
    return box_cxcywh_to_xyxy(torch.cat([center, wh], dim=-1))


def check_properties(n: int, generator: torch.Generator) -> None:
    """무작위 박스 n 쌍으로 IoU · GIoU 의 성질을 확인한다. 본문에서 유도한 성질이 숫자로도 맞는지 본다."""
    a, b = random_boxes(n, generator), random_boxes(n, generator)
    a, b = a.double(), b.double()  # 부동소수점 오차를 줄이려고 배정밀도로
    iou = paired_box_iou(a, b)
    giou = paired_generalized_box_iou(a, b)
    all_iou, _ = box_iou(a, b)  # (n, n)
    all_giou = generalized_box_iou(a, b)
    print(f"[5] 무작위 박스 {n}쌍으로 성질 확인")
    print(f"  겹치는 쌍 {int((iou > 0).sum())}개, 겹치지 않는 쌍 {int((iou == 0).sum())}개")
    print(f"  IoU 범위  [{iou.min().item():.4f}, {iou.max().item():.4f}]  → 0 이상 1 이하: {bool((iou >= 0).all() and (iou <= 1).all())}")
    print(f"  GIoU 범위 [{giou.min().item():.4f}, {giou.max().item():.4f}]  → −1 초과 1 이하: {bool((giou > -1).all() and (giou <= 1).all())}")
    print(f"  GIoU ≤ IoU: {bool((giou <= iou + 1e-12).all())}   (IoU − GIoU 의 최솟값 {(iou - giou).min().item():.2e})")
    print(f"  대칭 IoU(A, B) = IoU(B, A): 최대 차 {(iou - paired_box_iou(b, a)).abs().max().item():.1e}"
          f",  GIoU 최대 차 {(giou - paired_generalized_box_iou(b, a)).abs().max().item():.1e}")
    print(f"  자기 자신과는 1: IoU {paired_box_iou(a, a).min().item():.4f}, GIoU {paired_generalized_box_iou(a, a).min().item():.4f}")
    print(f"  짝끼리 = 모든 쌍 행렬의 대각선: 최대 차 IoU {(all_iou.diagonal() - iou).abs().max().item():.1e}"
          f", GIoU {(all_giou.diagonal() - giou).abs().max().item():.1e}")
    scale = torch.tensor([640.0, 480.0, 640.0, 480.0], dtype=torch.float64)  # 가로 640, 세로 480 픽셀로
    print(f"  크기 불변 (가로 640배, 세로 480배): 최대 차 IoU {(paired_box_iou(a * scale, b * scale) - iou).abs().max().item():.1e}"
          f", GIoU {(paired_generalized_box_iou(a * scale, b * scale) - giou).abs().max().item():.1e}")
    back = box_cxcywh_to_xyxy(box_xyxy_to_cxcywh(a))
    print(f"  표현을 바꿨다 되돌리기: 최대 차 {(back - a).abs().max().item():.1e}")


def check_pixel_counting(n: int, generator: torch.Generator, grid: int = 32) -> None:
    """공식을 쓰지 않는 다른 방법과 대조: 정수 좌표 박스를 grid × grid 모눈에 칠하고 칸을 하나하나 센다."""
    low = torch.randint(0, grid - 1, (2, n, 2), generator=generator)  # 왼쪽 위 (x0, y0)
    size = torch.randint(1, grid // 2, (2, n, 2), generator=generator)  # 너비 · 높이 (1 이상)
    boxes = torch.cat([low, (low + size).clamp(max=grid)], dim=-1).float()  # (2, n, 4)
    a, b = boxes[0], boxes[1]
    cells = torch.arange(grid).float() + 0.5  # 칸의 중심 좌표 0.5, 1.5, …

    def paint(box):  # (n, 4) → (n, grid, grid) bool. 칸의 중심이 박스 안이면 True
        inside_x = (cells[None, :] > box[:, 0:1]) & (cells[None, :] < box[:, 2:3])  # (n, grid)
        inside_y = (cells[None, :] > box[:, 1:2]) & (cells[None, :] < box[:, 3:4])
        return inside_y[:, :, None] & inside_x[:, None, :]

    mask_a, mask_b = paint(a), paint(b)
    inter = (mask_a & mask_b).sum(dim=(1, 2)).float()  # 둘 다 칠한 칸 수
    union = (mask_a | mask_b).sum(dim=(1, 2)).float()  # 하나라도 칠한 칸 수
    # 둘러싸는 박스 C: 칠해진 칸이 있는 열 · 행의 범위
    either = mask_a | mask_b
    cols, rows = either.any(dim=1), either.any(dim=2)  # (n, grid)
    # (두 박스 사이에 틈이 있으면 칠해진 열 · 행의 개수가 아니라 처음과 끝 사이의 범위를 써야 한다)
    first_col, last_col = cols.float().argmax(dim=1), grid - 1 - cols.flip(1).float().argmax(dim=1)
    first_row, last_row = rows.float().argmax(dim=1), grid - 1 - rows.flip(1).float().argmax(dim=1)
    enclosing = ((last_col - first_col + 1) * (last_row - first_row + 1)).float()
    count_iou = inter / union
    count_giou = count_iou - (enclosing - union) / enclosing
    print(f"[5] 칸 세기와 대조 ({grid}×{grid} 모눈, 정수 좌표 박스 {n}쌍)")
    print(f"  IoU 최대 차 {(count_iou - paired_box_iou(a, b)).abs().max().item():.1e}"
          f",  GIoU 최대 차 {(count_giou - paired_generalized_box_iou(a, b)).abs().max().item():.1e}")
# --8<-- [end:check]


# --8<-- [start:grad]
def box_gradient(loss_fn, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    """손실을 예측 박스 (cx, cy, w, h) 로 미분한 기울기 (4,). autograd 가 계산한다."""
    pred = pred.clone().requires_grad_(True)  # 이 텐서로 미분하겠다고 표시
    loss_fn(pred[None], target[None]).sum().backward()  # 손실 → 역전파
    return pred.grad


def gradient_example() -> None:
    """본문의 손계산과 맞춰 보는 기울기. 정답 T = (3, 0, 5, 2), 예측은 같은 크기(2 × 2)로 왼쪽에 있다."""
    target = box_xyxy_to_cxcywh(torch.tensor([3.0, 0.0, 5.0, 2.0]))  # (cx, cy, w, h) = (4, 1, 2, 2)
    print("[6] autograd 로 본 기울기: 정답 (x0, y0, x1, y1) = (3, 0, 5, 2), 예측은 너비 · 높이 2")
    print("    손실을 예측의 (cx, cy, w, h) 로 미분한 값")
    for name, x0 in [("겹치지 않음 (예측 x0 = 0, d = 3)", 0.0), ("겹침       (예측 x0 = 2, d = 1)", 2.0)]:
        pred = box_xyxy_to_cxcywh(torch.tensor([x0, 0.0, x0 + 2.0, 2.0]))
        print(f"  {name}")
        for loss_name, loss_fn in LOSSES.items():
            value = loss_fn(pred[None], target[None]).item()
            grad = box_gradient(loss_fn, pred, target)
            print(f"    {loss_name:<20} 값 = {value:8.4f}   기울기 = {fmt(grad)}")
# --8<-- [end:grad]


# --8<-- [start:slide]
def slide_curves(points: int):
    """예측 박스(정답과 같은 크기)를 정답에서 가로로 d 만큼 밀어 가며 L1 · IoU · GIoU 와 손실의 기울기를 잰다.

    돌려주는 값: d (points,), 값 사전, 기울기 사전(손실을 cx 로 미분한 값의 절댓값).
    """
    width, height = 0.2, 0.2
    target = torch.tensor([0.3, 0.5, width, height])  # 정규화 (cx, cy, w, h)
    shifts = torch.linspace(0.0, 3 * width, points)  # d = 0 … 3w
    pred = target.repeat(points, 1)  # (points, 4)
    pred[:, 0] += shifts  # 중심만 오른쪽으로
    pred.requires_grad_(True)
    targets = target.repeat(points, 1)
    values, grads = {}, {}
    for name, loss_fn in list(LOSSES.items())[:3]:
        loss = loss_fn(pred, targets)  # (points,)
        (grad,) = torch.autograd.grad(loss.sum(), pred)  # (points, 4): 점마다 따로 미분된다
        values[name] = loss.detach()
        grads[name] = grad[:, 0].abs()  # cx 방향 성분의 크기
    print("[7] 가로로 밀기 (w = 0.2): 값과 |d손실/dcx|")
    print("    d/w    L1     IoU     GIoU   | 기울기 1−IoU  1−GIoU    L1   | 공식 2w/(w+d)²")
    for ratio in (0.0, 0.1, 0.25, 0.5, 0.9, 1.1, 1.5, 2.0, 3.0):
        k = int(torch.argmin((shifts / width - ratio).abs()))
        d = shifts[k].item()
        print(f"    {d / width:4.2f}  {values['L1'][k].item():.4f}  {1 - values['1 - IoU'][k].item():7.4f} {1 - values['1 - GIoU'][k].item():7.4f}"
              f"  |   {grads['1 - IoU'][k].item():7.4f}  {grads['1 - GIoU'][k].item():7.4f}  {grads['L1'][k].item():.4f} |   {2 * width / (width + d) ** 2:7.4f}")
    return shifts, values, grads
# --8<-- [end:slide]


# --8<-- [start:descent]
def descend(loss_fn, start: torch.Tensor, target: torch.Tensor, lr: float, steps: int, decay: bool = False):
    """경사 하강법으로 박스 하나를 정답에 맞춘다. start, target: (4,) 정규화 (cx, cy, w, h).

    매 스텝: 손실 → 기울기 → 박스 ← 박스 − lr · 기울기. 신경망은 없고, 박스의 숫자 네 개가 곧 매개변수다.
    decay=True 이면 학습률을 처음 값에서 0 까지 스텝에 따라 곧게 줄인다.
    돌려주는 값: 궤적 (steps + 1, 4), 스텝마다의 IoU (steps + 1,).
    """
    box = start.clone().requires_grad_(True)
    path, ious = [box.detach().clone()], []
    for k in range(steps):
        step_lr = lr * (1 - k / steps) if decay else lr
        loss = loss_fn(box[None], target[None]).sum()
        (grad,) = torch.autograd.grad(loss, box)
        with torch.no_grad():
            ious.append(1 - iou_loss(box[None], target[None]).item())
            box -= step_lr * grad  # 경사 하강법 한 스텝
            box[2:].clamp_(min=1e-3)  # 너비 · 높이가 0 이하로 내려가지 않게 (박스로서 뜻이 없어진다)
        path.append(box.detach().clone())
    ious.append(1 - iou_loss(box.detach()[None], target[None]).item())
    return torch.stack(path), torch.tensor(ious)


def descent_experiment(steps: int, lr: float):
    """멀리 떨어진 시작점에서 네 가지 손실로 각각 경사 하강법을 돌린다."""
    start = torch.tensor([0.20, 0.24, 0.16, 0.20])  # 왼쪽 위의 작은 박스
    target = torch.tensor([0.68, 0.64, 0.30, 0.24])  # 오른쪽 아래의 정답. 둘은 겹치지 않는다
    start_iou = 1 - iou_loss(start[None], target[None]).item()
    start_giou = 1 - giou_loss(start[None], target[None]).item()
    print(f"[8] 경사 하강법으로 박스 맞추기 (학습률 {lr}, {steps} 스텝)")
    print(f"  시작 {fmt(start, 2)} → 정답 {fmt(target, 2)},  시작 IoU = {start_iou:.4f}, GIoU = {start_giou:.4f}")
    results = {}
    for name, loss_fn in LOSSES.items():
        path, ious = descend(loss_fn, start, target, lr, steps)
        results[name] = (path, ious)
        reached = [next((k for k, v in enumerate(ious.tolist()) if v >= level), None) for level in (1e-9, 0.5, 0.9)]
        tail = ious[-max(steps // 10, 1):]  # 마지막 10% 구간
        print(f"  {name:<20} 마지막 박스 {fmt(path[-1], 3)}  마지막 IoU = {ious[-1].item():.4f}"
              f"  (마지막 10% 구간 최소 {tail.min().item():.4f} – 최대 {tail.max().item():.4f})")
        print(f"  {'':<20} 겹치기 시작한 스텝: {reached[0]},  IoU 0.5 에 처음 닿은 스텝: {reached[1]},  0.9: {reached[2]}"
              f"\n  {'':<20} 가는 길의 가장 큰 넓이 = {(path[:, 2] * path[:, 3]).max().item():.4f} (정답 {target[2].item() * target[3].item():.4f})")
    print(f"  학습률을 {lr} 에서 0 까지 곧게 줄이며 같은 {steps} 스텝")
    decayed = {}
    for name, loss_fn in LOSSES.items():
        path, ious = descend(loss_fn, start, target, lr, steps, decay=True)
        decayed[name] = (path, ious)
        print(f"  {name:<20} 마지막 박스 {fmt(path[-1], 3)}  마지막 IoU = {ious[-1].item():.4f}")
    return start, target, results, decayed
# --8<-- [end:descent]


# --8<-- [start:shapes]
def jitter_example(seed: int):
    """도형 세상 그림의 정답 박스를 여러 세기로 흐트러뜨리고 IoU · GIoU 를 잰다.

    같은 방향의 흐트러짐(표준 정규 난수 한 벌)에 세기 σ 만 곱해, 같은 픽셀 오차가 큰 박스와 작은 박스에 주는 영향을 본다.
    """
    from rf_shapes import CLASS_NAMES_KO, ShapesDataset

    dataset = ShapesDataset(16, size=96, seed=0)
    index = next(i for i, t in enumerate(dataset.targets) if len(t["labels"]) == 4)  # 객체가 4개인 첫 그림
    image, target = dataset[index]
    boxes = target["boxes"]  # (4, 4) 정규화 (cx, cy, w, h)
    generator = torch.Generator().manual_seed(seed)
    direction = torch.randn(boxes.shape, generator=generator)  # 흐트러뜨릴 방향 (4, 4)
    levels = (0.01, 0.03, 0.06, 0.10)
    print(f"[9] 도형 세상 그림 {index}번의 정답 박스를 흐트러뜨리기 (σ 는 그림 한 변에 대한 비율, 96 픽셀이면 σ × 96 픽셀)")
    print("  객체      너비 × 높이(픽셀)  " + "  ".join(f"σ={s:.2f} IoU / GIoU " for s in levels))
    rows = []
    for sigma in levels:
        noisy = boxes + sigma * direction
        noisy[:, 2:].clamp_(min=0.02)
        iou = paired_box_iou(box_cxcywh_to_xyxy(noisy), box_cxcywh_to_xyxy(boxes))
        giou = paired_generalized_box_iou(box_cxcywh_to_xyxy(noisy), box_cxcywh_to_xyxy(boxes))
        rows.append((sigma, noisy, iou, giou))
    for k in range(len(boxes)):
        cells = "  ".join(f"     {iou[k].item():.3f} / {giou[k].item():6.3f}" for _, _, iou, giou in rows)
        print(f"  {CLASS_NAMES_KO[int(target['labels'][k])]:<5}    {boxes[k, 2].item() * 96:5.1f} × {boxes[k, 3].item() * 96:5.1f}    {cells}")
    return image, target, rows
# --8<-- [end:shapes]


# ---------------------------------------------------------------------------
# 그림 (그림 안 글자는 영어)
# ---------------------------------------------------------------------------
BLUE, ORANGE, GREEN, RED, PURPLE, GRAY = "#0072B2", "#E69F00", "#009E73", "#D55E00", "#CC79A7", "#555555"
LOSS_STYLE = {
    "1 - IoU": (ORANGE, "--"),
    "1 - GIoU": (BLUE, "-"),
    "L1": (GREEN, ":"),
    "5 L1 + 2 (1 - GIoU)": (RED, "-."),
}


def draw_rect(ax, xyxy, color, linestyle="-", fill=False, alpha=0.25, linewidth=2.0, label=None):
    import matplotlib.patches as patches

    x0, y0, x1, y1 = [float(v) for v in xyxy]
    ax.add_patch(patches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=fill, facecolor=color, alpha=alpha if fill else 1.0,
                                   edgecolor=color, linewidth=linewidth, linestyle=linestyle, label=label))
    if fill:  # 채운 사각형은 테두리가 흐려지므로 한 번 더 그린다
        ax.add_patch(patches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, edgecolor=color, linewidth=linewidth,
                                       linestyle=linestyle))


def figure_levels(plt, fig_dir: str) -> None:
    """그림: 여러 IoU 값이 실제로 얼마나 겹친 것인지."""
    cases = []
    for iou in (0.9, 0.75, 0.5, 0.25):  # 가로로 밀기: d = w (1 − IoU) / (1 + IoU)
        d = (1 - iou) / (1 + iou)
        cases.append((f"shift x by {d:.3f} w", shifted_pair(1.0, 1.0, d)))
    cases.append(("shift x and y by 0.184 w", shifted_pair(1.0, 1.0, 0.1835, 0.1835)))
    cases.append(("same center, 0.707x size", shifted_pair(1.0, 1.0, 0.0, 0.0, scale=0.7071)))
    cases.append(("same center, 1.414x size", shifted_pair(1.0, 1.0, 0.0, 0.0, scale=1.4142)))
    cases.append(("no overlap (gap 0.3 w)", shifted_pair(1.0, 1.0, 1.3)))
    fig, axes = plt.subplots(2, 4, figsize=(11, 5.6))
    for ax, (title, (pred, target)) in zip(axes.flat, cases):
        iou = paired_box_iou(pred, target).item()
        giou = paired_generalized_box_iou(pred, target).item()
        draw_rect(ax, target[0], GREEN, fill=True, label="ground truth")
        draw_rect(ax, pred[0], RED, linestyle="--", fill=True, alpha=0.18, label="prediction")
        ax.set_xlim(-0.45, 2.45)
        ax.set_ylim(1.75, -0.75)  # y 축은 아래로 증가 (그림 좌표계)
        ax.set_aspect("equal")
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_title(f"{title}\nIoU = {iou:.2f}, GIoU = {giou:.2f}", fontsize=10)
    axes[0, 0].legend(loc="lower right", fontsize=8)
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch02-iou-levels.png"), dpi=120)
    plt.close(fig)


def figure_slide(plt, fig_dir: str, shifts, values, grads) -> None:
    """그림: 가로로 밀 때의 L1 · IoU · GIoU 값(왼쪽)과 손실의 기울기 크기(오른쪽)."""
    ratio = (shifts / 0.2).numpy()
    fig, axes = plt.subplots(1, 2, figsize=(11, 4.0))
    ax = axes[0]
    ax.plot(ratio, (1 - values["1 - IoU"]).numpy(), color=ORANGE, ls="--", lw=2.2, label="IoU")
    ax.plot(ratio, (1 - values["1 - GIoU"]).numpy(), color=BLUE, ls="-", lw=2.2, label="GIoU")
    ax.plot(ratio, values["L1"].numpy(), color=GREEN, ls=":", lw=2.4, label="L1 distance (= d)")
    ax.axvline(1.0, color=GRAY, lw=1, ls="-.")
    ax.text(1.04, 0.62, "boxes stop\noverlapping\n(d = w)", fontsize=9, color=GRAY)
    ax.axhline(0.0, color=GRAY, lw=0.6)
    ax.set_xlabel("shift d / box width w")
    ax.set_ylabel("value")
    ax.set_title("Values while sliding the prediction sideways")
    ax.legend(loc="lower left", fontsize=9)
    ax = axes[1]
    for name in ("1 - IoU", "1 - GIoU", "L1"):
        color, ls = LOSS_STYLE[name]
        ax.plot(ratio[1:], grads[name].numpy()[1:], color=color, ls=ls, lw=2.2, label=f"loss = {name}")
    ax.axvline(1.0, color=GRAY, lw=1, ls="-.")
    ax.set_xlabel("shift d / box width w")
    ax.set_ylabel("|d loss / d cx|")
    ax.set_title("Gradient size with respect to the box center")
    ax.legend(loc="upper right", fontsize=9)
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch02-slide.png"), dpi=120)
    plt.close(fig)


def figure_surface(plt, fig_dir: str, grid: int) -> None:
    """그림: 예측 박스의 중심 (cx, cy) 를 그림 전체에서 움직일 때의 손실 표면 (크기는 정답과 같게 고정)."""
    target = torch.tensor([0.60, 0.55, 0.30, 0.24])
    centers = (torch.arange(grid).float() + 0.5) / grid  # 픽셀 중심 규약과 같은 격자
    cy, cx = torch.meshgrid(centers, centers, indexing="ij")  # (grid, grid)
    pred = torch.stack([cx, cy, torch.full_like(cx, target[2].item()), torch.full_like(cx, target[3].item())], dim=-1)
    pred = pred.reshape(-1, 4)  # (grid², 4)
    targets = target.repeat(len(pred), 1)
    fig, axes = plt.subplots(1, 3, figsize=(12.5, 4.2))
    for ax, name in zip(axes, ("1 - IoU", "1 - GIoU", "L1")):
        surface = LOSSES[name](pred, targets).reshape(grid, grid).numpy()
        im = ax.imshow(surface, extent=(0, 1, 1, 0), cmap="viridis", interpolation="nearest")
        ax.contour(centers.numpy(), centers.numpy(), surface, levels=8, colors="white", linewidths=0.6, alpha=0.7)
        draw_rect(ax, box_cxcywh_to_xyxy(target), "white", linestyle="--", linewidth=1.5)
        ax.plot([target[0].item()], [target[1].item()], marker="+", color="white", ms=10, mew=2)
        ax.set_xlabel("predicted cx")
        ax.set_ylabel("predicted cy")
        ax.set_title(f"loss = {name}")
        fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch02-surface.png"), dpi=120)
    plt.close(fig)


def figure_descent(plt, fig_dir: str, start, target, results, decayed) -> None:
    """그림: 박스 중심의 궤적, 1 − GIoU 로 갈 때의 박스 모습, IoU 수렴 곡선(학습률 고정 / 줄이기)."""
    fig, axes = plt.subplots(2, 2, figsize=(11, 9.6))
    ax = axes[0, 0]
    draw_rect(ax, box_cxcywh_to_xyxy(target), "black", fill=True, alpha=0.10, label="ground truth")
    draw_rect(ax, box_cxcywh_to_xyxy(start), GRAY, linestyle=":", label="start")
    for name, (path, _) in results.items():
        color, ls = LOSS_STYLE[name]
        ax.plot(path[:, 0].numpy(), path[:, 1].numpy(), color=color, ls=ls, lw=2.0, label=name)
        ax.plot([path[-1, 0].item()], [path[-1, 1].item()], marker="o", color=color, ms=6)
    ax.set_xlim(0, 1)
    ax.set_ylim(1, 0)
    ax.set_aspect("equal")
    ax.set_xlabel("x (normalized)")
    ax.set_ylabel("y (normalized, downward)")
    ax.set_title("(a) Path of the box center, constant learning rate")
    ax.legend(loc="lower left", fontsize=8)

    ax = axes[0, 1]  # GIoU 손실만으로 갈 때 박스가 어떻게 변하는지
    path, _ = results["1 - GIoU"]
    draw_rect(ax, box_cxcywh_to_xyxy(target), "black", fill=True, alpha=0.10, label="ground truth")
    steps = len(path) - 1
    picks = [0, steps // 40, steps // 20, steps * 3 // 40, steps // 10]  # 본 실행에서는 0, 50, 100, 150, 200 스텝
    for n, k in enumerate(picks):
        draw_rect(ax, box_cxcywh_to_xyxy(path[k]), BLUE, linewidth=1.0 + 0.4 * n)
        x0, y0 = box_cxcywh_to_xyxy(path[k])[:2].tolist()
        ax.text(x0 + 0.008, y0 + 0.04, f"{k}", fontsize=9, color=BLUE)
    draw_rect(ax, box_cxcywh_to_xyxy(path[-1]), BLUE, linestyle="--", linewidth=2.0)
    x1, y1 = box_cxcywh_to_xyxy(path[-1])[2:].tolist()
    ax.text(x1 - 0.008, y1 + 0.045, f"{steps}", fontsize=9, color=BLUE, ha="right")
    ax.set_xlim(0, 1)
    ax.set_ylim(1, 0)
    ax.set_aspect("equal")
    ax.set_xlabel("x (normalized)")
    ax.set_ylabel("y (normalized, downward)")
    ax.set_title("(b) Boxes on the 1 - GIoU path (numbers = step)")

    for ax, runs, title in ((axes[1, 0], results, "(c) IoU, constant learning rate"),
                            (axes[1, 1], decayed, "(d) IoU, learning rate decayed linearly to 0")):
        for name, (_, ious) in runs.items():
            color, ls = LOSS_STYLE[name]
            ax.plot(range(len(ious)), ious.numpy(), color=color, ls=ls, lw=1.4, label=name)
        ax.set_xscale("symlog", linthresh=10)
        ax.set_xlabel("gradient descent step (log scale after 10)")
        ax.set_ylabel("IoU with the ground truth")
        ax.set_ylim(-0.03, 1.03)
        ax.set_title(title)
        ax.legend(loc="center left", fontsize=8)
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch02-descent.png"), dpi=120)
    plt.close(fig)


def figure_shapes(plt, fig_dir: str, image, target, rows) -> None:
    """그림: 도형 세상 그림 위의 정답 박스(초록 실선)와 흐트러뜨린 박스(주황 점선), 객체마다 IoU / GIoU."""
    from rf_shapes import draw_boxes

    fig, axes = plt.subplots(1, 4, figsize=(14, 4.1), layout="constrained")
    for ax, (sigma, noisy, iou, giou) in zip(axes, rows):
        draw_boxes(ax, image, target["boxes"], color="#39ff14", linewidth=1.6)
        draw_boxes(ax, image, noisy, color="#ffb000", linestyle="--", linewidth=1.6)
        for k, (cx, cy, w, h) in enumerate(target["boxes"].tolist()):
            ax.text(cx * 96 - 0.5, cy * 96 - 0.5, f"{iou[k].item():.2f}\n{giou[k].item():.2f}", color="white", fontsize=8,
                    fontweight="bold", ha="center", va="center",
                    bbox=dict(facecolor="black", alpha=0.55, edgecolor="none", pad=1.5))
        ax.set_title(f"noise {sigma:.2f} (about {sigma * 96:.0f} px)\nIoU (top) / GIoU (bottom)", fontsize=10)
    fig.savefig(os.path.join(fig_dir, "ch02-shapes-iou.png"), dpi=120)
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description="2장: 박스와 IoU")
    parser.add_argument("--quick", action="store_true", help="점 · 스텝 수를 줄여 오류만 빠르게 확인")
    parser.add_argument("--fig-dir", default="figures")
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()

    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    started = time.time()
    torch.manual_seed(args.seed)
    torch.set_printoptions(precision=4, sci_mode=False)
    generator = torch.Generator().manual_seed(args.seed)
    os.makedirs(args.fig_dir, exist_ok=True)
    pairs = 100 if args.quick else 1000
    points = 61 if args.quick else 601
    steps = 200 if args.quick else 2000
    grid = 48 if args.quick else 96

    pixel_example()
    hand_example()
    how_much_overlap()
    broadcast_example()
    check_properties(pairs, generator)
    check_pixel_counting(pairs, generator)
    gradient_example()
    shifts, values, grads = slide_curves(points)
    start, target, results, decayed = descent_experiment(steps, lr=0.002)
    image, shape_target, rows = jitter_example(args.seed)

    figure_levels(plt, args.fig_dir)
    figure_slide(plt, args.fig_dir, shifts, values, grads)
    figure_surface(plt, args.fig_dir, grid)
    figure_descent(plt, args.fig_dir, start, target, results, decayed)
    figure_shapes(plt, args.fig_dir, image, shape_target, rows)
    print(f"그림 5장을 {args.fig_dir}/ch02-*.png 로 저장. 걸린 시간 {time.time() - started:.1f}초")


if __name__ == "__main__":
    main()
