"""3장 · 탐지기 채점: 정밀도 · 재현율 · AP · mAP, 그리고 NMS.

무엇을 하나
  1. 예측 박스를 정답 박스에 짝지어 참 양성(TP) · 거짓 양성(FP) 을 가린다 (match_detections).
  2. 점수 순으로 정밀도 – 재현율 곡선을 그리고, COCO 방식(재현율 101점 보간)으로 AP 를 계산한다
     (precision_recall_curve, average_precision).
  3. IoU 문턱값 0.50, 0.55, …, 0.95 의 AP 를 평균해 COCO 의 대표 지표 AP(= AP@[.50:.95]) 를 얻는다 (evaluate_ap).
  4. 겹치는 예측을 지우는 NMS 를 구현한다 (nms, nms_per_class).
     DETR 계열은 쓰지 않지만, 왜 필요 없는지 알려면 알아야 한다.
  5. 본문의 손계산 예를 코드로 다시 계산하고, 직접 구현한 AP · NMS 를 다른 방법으로 짠 것과 대조한다.
  6. 도형 세상 검증 세트의 정답으로 "가짜 탐지기" 를 만들어 AP 가 무엇에 반응하는지 본다:
     박스 위치 잡음, 점수의 질, 중복 예측, 헛예측, 그리고 NMS.

실행
  python ch03_metrics.py            # 본문 결과 (학습 없음, CPU 로 약 1분)
  python ch03_metrics.py --quick    # 연기 시험 (그림 60장, 10 – 20초)
그림은 --fig-dir (기본 figures/) 에 ch03-*.png 로 저장된다.
7장부터의 실습 파일이 이 파일의 evaluate_ap 로 모델을 채점한다. nms 는 7장에서 다시 쓴다 (DETR 에 NMS 가 필요 없음을 확인).
"""

from __future__ import annotations

import argparse
import os
import time

import numpy as np
import torch

from ch02_boxes import box_cxcywh_to_xyxy, box_iou, paired_box_iou
from rf_shapes import CLASS_NAMES, NUM_CLASSES, ShapesDataset, draw_boxes

# COCO 의 IoU 문턱값 10개: 0.50, 0.55, …, 0.95
COCO_IOU_THRESHOLDS = tuple(round(0.5 + 0.05 * i, 2) for i in range(10))


# --8<-- [start:match]
def match_detections(pred_boxes: torch.Tensor, pred_scores: torch.Tensor, gt_boxes: torch.Tensor,
                     iou_threshold: float) -> torch.Tensor:
    """그림 한 장, 클래스 하나의 예측을 정답에 짝짓는다. 박스는 모두 (x0, y0, x1, y1).

    점수가 높은 예측부터 차례로, 아직 짝이 없는 정답 가운데 IoU 가 가장 큰 것을 고른다.
    그 IoU 가 문턱값 이상이면 참 양성(TP), 아니면 거짓 양성(FP) 이다. 정답 하나는 한 번만 쓰인다.

    돌려주는 값: 점수 내림차순으로 정렬한 예측마다의 TP 여부 (bool 텐서).
    """
    order = torch.argsort(pred_scores, descending=True, stable=True)
    is_tp = torch.zeros(len(order), dtype=torch.bool)
    if len(gt_boxes) == 0 or len(order) == 0:
        return is_tp
    iou, _ = box_iou(pred_boxes[order], gt_boxes)  # (예측 수, 정답 수)
    gt_used = torch.zeros(len(gt_boxes), dtype=torch.bool)
    for rank in range(len(order)):
        candidate = iou[rank].clone()
        candidate[gt_used] = -1.0  # 이미 짝이 있는 정답은 후보에서 뺀다
        best_iou, best_gt = candidate.max(dim=0)
        if best_iou >= iou_threshold:
            is_tp[rank] = True
            gt_used[best_gt] = True
    return is_tp
# --8<-- [end:match]


# --8<-- [start:ap]
def precision_recall_curve(is_tp: np.ndarray, num_gt: int):
    """점수 내림차순으로 늘어놓은 TP 여부에서 정밀도 · 재현율 곡선을 만든다.

    k 번째 값은 "점수가 높은 순으로 k 개까지만 예측으로 인정했을 때" 의 정밀도 · 재현율이다.
    """
    tp_cum = np.cumsum(is_tp)  # 위에서부터 k 개 가운데 TP 수
    fp_cum = np.cumsum(~is_tp)  # 위에서부터 k 개 가운데 FP 수
    recall = tp_cum / max(num_gt, 1)
    precision = tp_cum / np.maximum(tp_cum + fp_cum, 1)
    return precision, recall


def average_precision(precision: np.ndarray, recall: np.ndarray) -> float:
    """COCO 방식 AP: 재현율 0, 0.01, …, 1.00 의 101개 지점에서 보간한 정밀도의 평균.

    1) 정밀도를 오른쪽부터 누적 최댓값으로 바꿔 톱니를 없앤다 (재현율 r 이상에서 얻을 수 있는 최고 정밀도).
    2) 지점 r 마다, 재현율이 r 이상이 되는 첫 자리의 정밀도를 읽는다. 그런 자리가 없으면 0.
    """
    if len(precision) == 0:
        return 0.0
    envelope = np.maximum.accumulate(precision[::-1])[::-1]
    points = np.linspace(0.0, 1.0, 101)
    index = np.searchsorted(recall, points, side="left")
    sampled = np.where(index < len(envelope), envelope[np.minimum(index, len(envelope) - 1)], 0.0)
    return float(sampled.mean())
# --8<-- [end:ap]


# --8<-- [start:evaluate]
def evaluate_ap(predictions, targets, num_classes: int, iou_thresholds=COCO_IOU_THRESHOLDS, max_dets: int = 100):
    """데이터셋 전체를 채점한다.

    predictions[i]: {"boxes": (n, 4) 정규화 (cx, cy, w, h), "scores": (n,), "labels": (n,)} — i 번째 그림의 예측
    targets[i]:     {"boxes": (m, 4) 정규화 (cx, cy, w, h), "labels": (m,)}                — i 번째 그림의 정답

    돌려주는 값: {"AP": IoU 문턱값 전체 평균, "AP50": …, "AP75": …,
                 "per_class": 클래스별 AP (문턱값 평균), "table": (문턱값 수, 클래스 수) 배열}
    정답이 하나도 없는 클래스는 평균에서 뺀다 (COCO 와 같다).
    """
    table = np.full((len(iou_thresholds), num_classes), np.nan)
    for cls in range(num_classes):
        num_gt = sum(int((t["labels"] == cls).sum()) for t in targets)
        if num_gt == 0:
            continue
        for ti, threshold in enumerate(iou_thresholds):
            scores_all, tp_all = [], []
            for pred, target in zip(predictions, targets):
                scores = pred["scores"].detach().cpu()
                keep = torch.argsort(scores, descending=True, stable=True)[:max_dets]  # 그림마다 점수 상위 max_dets 개만
                labels = pred["labels"].detach().cpu()[keep]
                boxes = box_cxcywh_to_xyxy(pred["boxes"].detach().cpu()[keep])
                scores = scores[keep]
                chosen = labels == cls
                gt_boxes = box_cxcywh_to_xyxy(target["boxes"].cpu()[target["labels"].cpu() == cls])
                is_tp = match_detections(boxes[chosen], scores[chosen], gt_boxes, threshold)
                scores_all.append(torch.sort(scores[chosen], descending=True).values)
                tp_all.append(is_tp)
            scores_all = torch.cat(scores_all).numpy()
            tp_all = torch.cat(tp_all).numpy()
            order = np.argsort(-scores_all, kind="stable")  # 모든 그림의 예측을 점수 순으로 한 줄로
            precision, recall = precision_recall_curve(tp_all[order], num_gt)
            table[ti, cls] = average_precision(precision, recall)
    per_threshold = np.nanmean(table, axis=1)
    result = {
        "AP": float(np.nanmean(per_threshold)),
        "per_class": np.nanmean(table, axis=0),
        "table": table,
    }
    for name, value in (("AP50", 0.5), ("AP75", 0.75)):
        if value in iou_thresholds:
            result[name] = float(per_threshold[iou_thresholds.index(value)])
    return result
# --8<-- [end:evaluate]


# --8<-- [start:nms]
def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float = 0.5) -> torch.Tensor:
    """비최대 억제(NMS). boxes: (n, 4) (x0, y0, x1, y1). 남길 박스의 번호를 점수 내림차순으로 돌려준다.

    점수가 가장 높은 박스를 남기고, 그 박스와 IoU 가 문턱값을 넘는 나머지를 지운다. 남은 것으로 되풀이한다.
    """
    order = torch.argsort(scores, descending=True)
    keep = []
    while len(order) > 0:
        best = order[0]
        keep.append(int(best))
        if len(order) == 1:
            break
        iou, _ = box_iou(boxes[best][None], boxes[order[1:]])
        order = order[1:][iou[0] <= iou_threshold]
    return torch.tensor(keep, dtype=torch.long)
# --8<-- [end:nms]


# --8<-- [start:class_nms]
def nms_per_class(pred: dict, iou_threshold: float = 0.5) -> dict:
    """그림 한 장의 예측 {"boxes" (cx, cy, w, h), "scores", "labels"} 에 클래스별로 NMS 를 적용한다.

    클래스가 다른 박스끼리는 아무리 겹쳐도 서로 지우지 않는다 (원 위에 겹친 사각형은 다른 객체다).
    """
    boxes = box_cxcywh_to_xyxy(pred["boxes"])
    kept = []
    for cls in pred["labels"].unique():
        index = torch.nonzero(pred["labels"] == cls).flatten()  # 이 클래스 예측의 번호
        keep = nms(boxes[index], pred["scores"][index], iou_threshold)
        kept.append(index[keep])
    kept = torch.cat(kept) if kept else torch.zeros(0, dtype=torch.long)
    return {"boxes": pred["boxes"][kept], "scores": pred["scores"][kept], "labels": pred["labels"][kept]}
# --8<-- [end:class_nms]


def average_precision_11point(precision: np.ndarray, recall: np.ndarray) -> float:
    """참고: 재현율 0, 0.1, …, 1.0 의 11개 지점만 쓰는 옛 방식. 101점 방식과 지점 수만 다르다."""
    total = 0.0
    for r in np.linspace(0.0, 1.0, 11):
        reachable = precision[recall >= r - 1e-12]
        total += float(reachable.max()) if len(reachable) else 0.0
    return total / 11


# ─────────────────────────── 본문의 손계산 예를 코드로 확인 ───────────────────────────

# --8<-- [start:hand]
def hand_examples():
    """본문에서 손으로 계산한 숫자를 같은 함수들로 다시 계산한다. 박스는 (x0, y0, x1, y1), 단위는 모눈 한 칸."""
    print("[1] 손계산 예 확인")
    # (가) 예측 4개를 정답 2개에 짝짓기 — 그림 3-1
    gt = torch.tensor([[1.0, 1.0, 5.0, 5.0], [6.0, 5.0, 9.0, 9.0]])  # G1, G2
    pred = torch.tensor([[1.0, 1.0, 5.0, 6.0], [2.0, 1.0, 6.0, 5.0], [6.0, 6.0, 10.0, 9.0], [1.0, 7.0, 3.0, 9.0]])
    scores = torch.tensor([0.9, 0.8, 0.7, 0.6])  # P1 … P4
    iou, _ = box_iou(pred, gt)
    print("  IoU 표 (행 P1–P4, 열 G1 G2):", [[round(v, 3) for v in row] for row in iou.tolist()])
    for threshold in (0.5, 0.75):
        is_tp = match_detections(pred, scores, gt, threshold)
        print(f"  IoU 문턱값 {threshold:.2f}: TP 여부 {is_tp.tolist()}"
              f" → TP {int(is_tp.sum())}, FP {int((~is_tp).sum())}, FN {len(gt) - int(is_tp.sum())}")
    # 점수 문턱값을 바꿀 때의 정밀도 · 재현율 (IoU 문턱값 0.5)
    is_tp = match_detections(pred, scores, gt, 0.5).numpy()
    precision, recall = precision_recall_curve(is_tp, num_gt=len(gt))
    for k, score_threshold in enumerate((0.85, 0.75, 0.65, 0.55)):
        print(f"  점수 문턱값 {score_threshold:.2f} (위에서 {k + 1}개 인정): 정밀도 {precision[k]:.3f}, 재현율 {recall[k]:.3f}")

    # (나) 정답 3개, 예측 5개가 점수 순으로 TP · FP · TP · FP · TP
    is_tp = np.array([True, False, True, False, True])
    precision, recall = precision_recall_curve(is_tp, num_gt=3)
    envelope = np.maximum.accumulate(precision[::-1])[::-1]
    print("  정밀도  ", np.round(precision, 3).tolist())
    print("  재현율  ", np.round(recall, 3).tolist())
    print("  보간 정밀도", np.round(envelope, 3).tolist())
    ap = average_precision(precision, recall)
    print(f"  AP (101점) {ap:.4f} | 손계산 (34·1 + 33·(2/3) + 34·0.6)/101 = {(34 + 33 * 2 / 3 + 34 * 0.6) / 101:.4f}")
    print(f"  참고: 11점 방식 {average_precision_11point(precision, recall):.4f},"
          f" 보간 곡선 아래의 정확한 넓이 {(1 + 2 / 3 + 0.6) / 3:.4f}")

    # (다) 확인 문제: 정답 2개, 같은 예측 4개의 점수 순서만 다를 때
    for name, flags in (("FP · TP · TP · FP", [False, True, True, False]), ("TP · TP · FP · FP", [True, True, False, False]),
                        ("TP · FP · FP · TP", [True, False, False, True])):
        precision, recall = precision_recall_curve(np.array(flags), num_gt=2)
        print(f"  순서 {name}: AP {average_precision(precision, recall):.4f}")

    # (라) NMS 손계산: 박스 5개 A – E
    boxes = torch.tensor([[1.0, 1.0, 5.0, 5.0], [2.0, 1.0, 6.0, 5.0], [1.0, 2.0, 5.0, 6.0], [6.0, 6.0, 9.0, 9.0],
                          [6.0, 6.0, 9.0, 10.0]])
    box_scores = torch.tensor([0.9, 0.8, 0.7, 0.6, 0.5])
    iou, _ = box_iou(boxes, boxes)
    names = "ABCDE"
    print("  NMS 예의 IoU: " + ", ".join(f"{names[i]}{names[j]} {iou[i, j]:.3f}" for i in range(5) for j in range(i + 1, 5)
                                      if iou[i, j] > 0))
    for threshold in (0.3, 0.5, 0.7):
        keep = nms(boxes, box_scores, threshold)
        print(f"  NMS 문턱값 {threshold}: 남는 박스 {[names[i] for i in keep.tolist()]}")
# --8<-- [end:hand]


def run_checks(rng: np.random.Generator, trials: int):
    """직접 구현한 AP · NMS 를, 정의를 그대로 옮긴 느린 구현과 무작위 입력으로 대조한다."""
    print("[2] 구현 대조")
    worst = 0.0
    for _ in range(trials):
        n = int(rng.integers(1, 40))
        is_tp = rng.random(n) < rng.random()
        num_gt = int(is_tp.sum()) + int(rng.integers(0, 5))
        precision, recall = precision_recall_curve(is_tp, max(num_gt, 1))
        # 정의 그대로: 지점 r 마다 "재현율이 r 이상인 자리들의 정밀도 가운데 최댓값" 을 구해 평균
        total = 0.0
        for r in np.linspace(0.0, 1.0, 101):
            reachable = precision[recall >= r]
            total += float(reachable.max()) if len(reachable) else 0.0
        worst = max(worst, abs(total / 101 - average_precision(precision, recall)))
    print(f"  average_precision 과 정의 그대로의 계산: {trials}번 가운데 가장 큰 차이 {worst:.1e}")

    same = 0
    for _ in range(trials):
        n = int(rng.integers(1, 30))
        xy = torch.from_numpy(rng.uniform(0.0, 0.6, size=(n, 2)).astype(np.float32))
        wh = torch.from_numpy(rng.uniform(0.1, 0.4, size=(n, 2)).astype(np.float32))
        boxes = torch.cat([xy, xy + wh], dim=1)
        scores = torch.from_numpy(rng.random(n).astype(np.float32))
        threshold = float(rng.uniform(0.2, 0.8))
        # 느린 구현: 점수 순으로 보며, 이미 남긴 박스 가운데 하나라도 IoU 가 문턱값을 넘으면 버린다
        iou, _ = box_iou(boxes, boxes)
        reference = []
        for i in torch.argsort(scores, descending=True).tolist():
            if all(iou[i, j] <= threshold for j in reference):
                reference.append(i)
        same += int(reference == nms(boxes, scores, threshold).tolist())
    print(f"  nms 와 느린 구현: {trials}번 가운데 {same}번 일치")


# ─────────────────────────── 가짜 탐지기 ───────────────────────────

# --8<-- [start:fake]
def jitter_boxes(boxes: torch.Tensor, sigma: float, rng: np.random.Generator) -> torch.Tensor:
    """박스 (n, 4) (cx, cy, w, h) 에 위치 잡음을 넣는다.

    중심은 박스 크기의 sigma 배를 표준편차로 하는 가우시안만큼 옮기고 (큰 박스는 많이, 작은 박스는 조금),
    너비 · 높이에는 exp(sigma · 표준 정규) 를 곱한다 (sigma = 0.1 이면 대략 ±10% 늘거나 준다).
    """
    noise = torch.from_numpy(rng.normal(size=tuple(boxes.shape)).astype(np.float32))
    cx, cy, w, h = boxes.unbind(-1)
    return torch.stack([cx + sigma * w * noise[:, 0], cy + sigma * h * noise[:, 1],
                        w * torch.exp(sigma * noise[:, 2]), h * torch.exp(sigma * noise[:, 3])], dim=-1)


def make_scores(iou: torch.Tensor, mode: str, rng: np.random.Generator) -> torch.Tensor:
    """예측마다 점수를 붙인다. iou 는 그 예측과 (그것을 만든) 정답 박스의 IoU.

    "iou"       점수 = IoU. 박스가 정확할수록 점수가 높다 (이상적인 점수).
    "noisy_iou" 점수 = IoU + 표준편차 0.1 의 잡음. 대체로 맞지만 가끔 순서가 뒤집힌다.
    "random"    점수 = 0.5 – 1 의 균등 난수. 박스의 질과 아무 상관이 없다.
    "inverse"   점수 = 1 − IoU. 박스가 나쁠수록 점수가 높다 (최악의 점수).
    """
    n = len(iou)
    if mode == "iou":
        return iou.clone()
    if mode == "noisy_iou":
        # 위쪽은 자르지 않는다: 1 에서 자르면 점수가 같은 예측이 여럿 생겨 순서가 모호해진다.
        # 점수가 1 을 조금 넘어도 AP 는 점수의 크기가 아니라 순서만 본다.
        return (iou + 0.1 * torch.from_numpy(rng.normal(size=n).astype(np.float32))).clamp(min=0.01)
    if mode == "random":
        return torch.from_numpy(rng.uniform(0.5, 1.0, size=n).astype(np.float32))
    if mode == "inverse":
        return 1.0 - iou
    raise ValueError(mode)


def fake_detector(targets, seed: int, sigma: float = 0.0, score_mode: str = "random", duplicates: int = 0,
                  duplicate_score_scale: float = 1.0, junk: int = 0, junk_score=(0.01, 0.2)):
    """정답을 흔들어 만든 가짜 탐지 결과. evaluate_ap 가 받는 predictions 형식으로 돌려준다.

    - 정답 박스마다 예측 하나: 위치 잡음 sigma 를 넣고, 클래스는 정답 그대로, 점수는 score_mode 로.
    - duplicates: 정답마다 같은 방법으로 따로 흔든 박스를 그만큼 더 낸다 (같은 객체를 여러 번 예측).
      그 점수에는 duplicate_score_scale 을 곱한다 (1 이면 원래 예측과 비슷한 점수, 0.3 이면 낮은 점수).
    - junk: 그림마다 아무 데나 놓은 박스(헛예측)를 그만큼 더 낸다. 클래스는 무작위, 점수는 junk_score 구간의 균등 난수.

    난수를 셋으로 나눠 쓴다: 박스용 · 점수용 · 추가분(중복 · 헛예측)용. 그래서 sigma 와 score_mode 가 같으면
    duplicates · junk 를 바꿔도 "원래 예측" 은 박스도 점수도 똑같다. score_mode 만 바꾸면 박스는 똑같다.
    """
    box_rng = np.random.default_rng([seed, 0])
    score_rng = np.random.default_rng([seed, 1])
    extra_rng = np.random.default_rng([seed, 2])
    predictions = []
    for target in targets:
        gt_boxes, gt_labels = target["boxes"], target["labels"]
        gt_xyxy = box_cxcywh_to_xyxy(gt_boxes)
        boxes = jitter_boxes(gt_boxes, sigma, box_rng)
        iou = paired_box_iou(box_cxcywh_to_xyxy(boxes), gt_xyxy)  # 예측 k 와 정답 k 의 IoU, (객체 수,)
        all_boxes, all_scores, all_labels = [boxes], [make_scores(iou, score_mode, score_rng)], [gt_labels]
        for _ in range(duplicates):
            copy = jitter_boxes(gt_boxes, sigma, extra_rng)
            copy_iou = paired_box_iou(box_cxcywh_to_xyxy(copy), gt_xyxy)
            all_boxes.append(copy)
            all_scores.append(make_scores(copy_iou, score_mode, extra_rng) * duplicate_score_scale)
            all_labels.append(gt_labels)
        if junk > 0:
            wh = extra_rng.uniform(0.14, 0.42, size=(junk, 2))
            center = extra_rng.uniform(wh / 2, 1 - wh / 2)  # 그림 밖으로 나가지 않게
            all_boxes.append(torch.from_numpy(np.concatenate([center, wh], axis=1).astype(np.float32)))
            all_scores.append(torch.from_numpy(extra_rng.uniform(*junk_score, size=junk).astype(np.float32)))
            all_labels.append(torch.from_numpy(extra_rng.integers(0, NUM_CLASSES, size=junk)))
        predictions.append({"boxes": torch.cat(all_boxes), "scores": torch.cat(all_scores), "labels": torch.cat(all_labels)})
    return predictions
# --8<-- [end:fake]


def pr_curve_of_class(predictions, targets, cls: int, iou_threshold: float, max_dets: int = 100):
    """evaluate_ap 의 안쪽 계산을 클래스 하나 · IoU 문턱값 하나에 대해 하고, 곡선 (정밀도, 재현율) 을 돌려준다."""
    num_gt = sum(int((t["labels"] == cls).sum()) for t in targets)
    scores_all, tp_all = [], []
    for pred, target in zip(predictions, targets):
        keep = torch.argsort(pred["scores"], descending=True, stable=True)[:max_dets]
        chosen = pred["labels"][keep] == cls
        boxes = box_cxcywh_to_xyxy(pred["boxes"][keep])[chosen]
        scores = pred["scores"][keep][chosen]
        gt_boxes = box_cxcywh_to_xyxy(target["boxes"][target["labels"] == cls])
        tp_all.append(match_detections(boxes, scores, gt_boxes, iou_threshold))
        scores_all.append(torch.sort(scores, descending=True).values)
    scores_all = torch.cat(scores_all).numpy()
    order = np.argsort(-scores_all, kind="stable")
    return precision_recall_curve(torch.cat(tp_all).numpy()[order], num_gt)


def mean_own_iou(predictions, targets) -> float:
    """가짜 탐지기의 "원래 예측"(앞쪽 객체 수만큼) 과 정답의 평균 IoU."""
    values = []
    for pred, target in zip(predictions, targets):
        n = len(target["labels"])
        values.append(paired_box_iou(box_cxcywh_to_xyxy(pred["boxes"][:n]), box_cxcywh_to_xyxy(target["boxes"])))
    return float(torch.cat(values).mean())


def describe(result: dict) -> str:
    return f"AP50 {result['AP50']:.3f} | AP75 {result['AP75']:.3f} | AP {result['AP']:.3f}"


# ─────────────────────────── 실험 ───────────────────────────

BLUE, ORANGE, GREEN, PINK, GRAY = "#0072B2", "#D55E00", "#009E73", "#CC79A7", "#555555"


def experiment_noise(dataset, sigmas, seed: int, fig_dir: str):
    """실험 1: 박스 위치 잡음을 키울 때 AP50 · AP75 · AP 가 어떻게 무너지는가. 점수는 박스의 질과 무관한 난수."""
    import matplotlib.pyplot as plt

    targets = dataset.targets
    print("[3] 실험 1 · 박스 위치 잡음 (점수는 무작위)")
    print("  sigma | 평균 IoU | AP50  | AP75  | AP")
    rows = []
    for sigma in sigmas:
        predictions = fake_detector(targets, seed, sigma=sigma, score_mode="random")
        result = evaluate_ap(predictions, targets, NUM_CLASSES)
        rows.append((sigma, mean_own_iou(predictions, targets), result))
        print(f"  {sigma:5.2f} | {rows[-1][1]:8.3f} | {result['AP50']:.3f} | {result['AP75']:.3f} | {result['AP']:.3f}")
    # AP 한 숫자가 어떻게 만들어지는지: sigma 하나를 골라 문턱값별 · 클래스별 값을 그대로 보인다
    sigma, _, result = rows[min(len(rows) - 1, 5)]
    per_threshold = np.nanmean(result["table"], axis=1)  # (문턱값 10개,) — 클래스 평균
    print(f"  sigma {sigma:.2f} 의 IoU 문턱값별 AP(클래스 평균): " + " ".join(f"{v:.3f}" for v in per_threshold))
    print(f"    → 열 개의 평균 {per_threshold.mean():.3f}")
    print("    IoU 0.50 에서의 클래스별 AP: " + ", ".join(f"{name} {v:.3f}" for name, v in zip(CLASS_NAMES, result["table"][0]))
          + f" → 평균 {np.nanmean(result['table'][0]):.3f}")

    fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.9))
    xs = [row[0] for row in rows]
    for key, color, style, marker in (("AP50", BLUE, "-", "o"), ("AP75", ORANGE, "--", "s"), ("AP", GREEN, "-.", "^")):
        label = "AP (mean of 10 thresholds)" if key == "AP" else key
        axes[0].plot(xs, [row[2][key] for row in rows], color=color, linestyle=style, marker=marker, label=label)
    axes[0].plot(xs, [row[1] for row in rows], color=GRAY, linestyle=":", marker="x", label="mean IoU of the boxes")
    axes[0].set_xlabel("box noise sigma (fraction of box size)")
    axes[0].set_ylabel("value")
    axes[0].set_title("AP vs. box noise")
    axes[0].set_ylim(-0.02, 1.05)
    axes[0].grid(alpha=0.3)
    axes[0].legend(fontsize=8)
    # 오른쪽: IoU 문턱값마다의 AP (클래스 평균). 이 10개의 평균이 COCO 의 AP 다.
    styles = ["-", "--", "-.", ":"]
    picked = [row for row in rows if row[0] in (0.0, 0.04, 0.1, 0.2)] or rows[:4]
    for k, (sigma, _, result) in enumerate(picked):
        per_threshold = np.nanmean(result["table"], axis=1)
        axes[1].plot(COCO_IOU_THRESHOLDS, per_threshold, color=[BLUE, GREEN, ORANGE, PINK][k % 4], linestyle=styles[k % 4],
                     marker="o", markersize=4, label=f"sigma = {sigma:.2f} (AP {result['AP']:.3f})")
    axes[1].set_xlabel("IoU threshold")
    axes[1].set_ylabel("AP at that threshold")
    axes[1].set_title("AP at each of the 10 IoU thresholds")
    axes[1].set_xticks(COCO_IOU_THRESHOLDS)
    axes[1].tick_params(axis="x", labelsize=7)
    axes[1].set_ylim(-0.02, 1.05)
    axes[1].grid(alpha=0.3)
    axes[1].legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch03-noise-ap.png"), dpi=120)
    plt.close(fig)

    # 잡음의 크기를 눈으로: 같은 그림 두 장에 sigma 를 바꿔 가며
    shown = [0.0, 0.04, 0.1, 0.2]
    fig, axes = plt.subplots(2, len(shown), figsize=(2.6 * len(shown), 5.6))
    for col, sigma in enumerate(shown):
        predictions = fake_detector(targets, seed, sigma=sigma, score_mode="random")
        for row, index in enumerate((0, 3)):
            ax = axes[row, col]
            image, target = dataset[index]
            n = len(target["labels"])
            draw_boxes(ax, image, target["boxes"], color="#39ff14", linewidth=1.6)
            draw_boxes(ax, image, predictions[index]["boxes"][:n], color="#ff40ff", linestyle="--", linewidth=1.6)
            iou = paired_box_iou(box_cxcywh_to_xyxy(predictions[index]["boxes"][:n]), box_cxcywh_to_xyxy(target["boxes"]))
            ax.set_title(f"sigma = {sigma:.2f}\nIoU " + ", ".join(f"{v:.2f}" for v in iou.tolist()), fontsize=8)
    fig.suptitle("ground truth (solid green) and fake predictions (dashed magenta)", fontsize=10)
    fig.tight_layout(rect=(0, 0, 1, 0.97), h_pad=2.2)
    fig.savefig(os.path.join(fig_dir, "ch03-fake-detections.png"), dpi=120)
    plt.close(fig)


def experiment_scores(targets, sigma: float, seed: int, fig_dir: str):
    """실험 2: 박스는 똑같고 점수만 다를 때. 점수 순서가 AP 를 얼마나 좌우하는가."""
    import matplotlib.pyplot as plt

    print(f"[4] 실험 2 · 점수의 질 (박스는 모두 같다: sigma = {sigma})")
    modes = (("iou", "score = IoU (ideal)", BLUE, "-"), ("noisy_iou", "score = IoU + noise", GREEN, "--"),
             ("random", "score = random", ORANGE, "-."), ("inverse", "score = 1 - IoU (worst)", PINK, ":"))
    results = {}
    for mode, _, _, _ in modes:
        predictions = fake_detector(targets, seed, sigma=sigma, score_mode=mode)
        results[mode] = (predictions, evaluate_ap(predictions, targets, NUM_CLASSES))
    # 박스가 같으니 "IoU 가 문턱값 이상인 예측의 비율" 은 네 경우 모두 같다
    own = torch.cat([paired_box_iou(box_cxcywh_to_xyxy(p["boxes"]), box_cxcywh_to_xyxy(t["boxes"]))
                     for p, t in zip(results["iou"][0], targets)])
    q50, q75 = float((own >= 0.5).float().mean()), float((own >= 0.75).float().mean())
    print(f"  예측 {len(own)}개 가운데 정답과 IoU ≥ 0.50 인 비율 {q50:.3f}, IoU ≥ 0.75 인 비율 {q75:.3f}")
    for mode, _, _, _ in modes:
        print(f"  {mode:9s} | {describe(results[mode][1])}")
    print(f"  참고: 비율의 제곱 {q50 ** 2:.3f} (IoU 0.50), {q75 ** 2:.3f} (IoU 0.75)")

    fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.9))
    for mode, label, color, style in modes:
        precision, recall = pr_curve_of_class(results[mode][0], targets, cls=0, iou_threshold=0.75)
        axes[0].plot(recall, precision, color=color, linestyle=style, linewidth=1.8,
                     label=f"{label}: AP75 {average_precision(precision, recall):.3f}")
    axes[0].set_xlabel("recall")
    axes[0].set_ylabel("precision")
    axes[0].set_title(f"PR curves, class '{CLASS_NAMES[0]}', IoU threshold 0.75")
    axes[0].set_xlim(-0.02, 1.02)
    axes[0].set_ylim(-0.02, 1.05)
    axes[0].grid(alpha=0.3)
    axes[0].legend(fontsize=8, loc="upper right")
    width = 0.2
    for k, (mode, label, color, _) in enumerate(modes):
        values = [results[mode][1][key] for key in ("AP50", "AP75", "AP")]
        bars = axes[1].bar(np.arange(3) + (k - 1.5) * width, values, width, color=color, label=label,
                           hatch=["", "//", "..", "xx"][k], edgecolor="white")
        for bar, value in zip(bars, values):
            axes[1].text(bar.get_x() + bar.get_width() / 2, value + 0.01, f"{value:.2f}", ha="center", fontsize=7)
    axes[1].set_xticks(np.arange(3))
    axes[1].set_xticklabels(["AP50", "AP75", "AP"])
    axes[1].set_ylim(0, 1.1)
    axes[1].set_title("same boxes, different scores")
    axes[1].grid(axis="y", alpha=0.3)
    axes[1].legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch03-score-quality.png"), dpi=120)
    plt.close(fig)
    return results["noisy_iou"][0]


def figure_pr_curve(predictions, targets, fig_dir: str):
    """PR 곡선 그림: 왼쪽은 본문의 손계산 예, 오른쪽은 가짜 탐지기(실험 2 의 noisy_iou). 원래 곡선 · 보간 곡선 · 101점."""
    import matplotlib.pyplot as plt

    hand = precision_recall_curve(np.array([True, False, True, False, True]), 3)
    real = pr_curve_of_class(predictions, targets, cls=0, iou_threshold=0.75)
    points = np.linspace(0.0, 1.0, 101)
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.9))
    for ax, (precision, recall), title in ((axes[0], hand, "hand example: 3 objects, 5 predictions"),
                                           (axes[1], real, f"fake detector, class '{CLASS_NAMES[0]}', IoU threshold 0.75")):
        envelope = np.maximum.accumulate(precision[::-1])[::-1]
        index = np.searchsorted(recall, points, side="left")
        sampled = np.where(index < len(envelope), envelope[np.minimum(index, len(envelope) - 1)], 0.0)
        ax.plot(recall, precision, color=ORANGE, linestyle="--", linewidth=1.3, marker="o" if len(recall) < 20 else None,
                label="raw precision-recall curve")
        ax.step(points, sampled, where="post", color=BLUE, linewidth=1.8, label="interpolated (running max from the right)")
        ax.fill_between(points, sampled, step="post", color=BLUE, alpha=0.12)
        ax.plot(points, sampled, linestyle="none", marker=".", markersize=3, color="black", label="101 sampled points")
        ax.set_title(f"{title}\nAP = mean of the 101 points = {sampled.mean():.4f}", fontsize=9)
        ax.set_xlabel("recall")
        ax.set_ylabel("precision")
        ax.set_xlim(-0.02, 1.02)
        ax.set_ylim(-0.02, 1.08)
        ax.grid(alpha=0.3)
        ax.legend(fontsize=8, loc="lower left")
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch03-pr-curve.png"), dpi=120)
    plt.close(fig)
    print(f"  PR 곡선 그림: 손계산 예 AP {average_precision(*hand):.4f},"
          f" 가짜 탐지기 '{CLASS_NAMES[0]}' IoU 0.75 의 AP {average_precision(*real):.4f} (예측 {len(real[0])}개)")


def experiment_duplicates(targets, sigma: float, seed: int, fig_dir: str):
    """실험 3: 중복 예측 · 헛예측을 넣을 때, 그리고 NMS 를 적용할 때."""
    import matplotlib.pyplot as plt

    print(f"[5] 실험 3 · 중복 예측, 헛예측, NMS (sigma = {sigma}, 점수 = IoU + 잡음)")
    base = dict(sigma=sigma, score_mode="noisy_iou")
    variants = [
        ("base", "기본 (객체마다 예측 1개)", fake_detector(targets, seed, **base)),
        ("+1 duplicate, low score", "+ 중복 1개씩, 낮은 점수(×0.3)", fake_detector(targets, seed, duplicates=1, duplicate_score_scale=0.3, **base)),
        ("+1 duplicate, similar score", "+ 중복 1개씩, 비슷한 점수", fake_detector(targets, seed, duplicates=1, **base)),
        ("+3 duplicates, similar score", "+ 중복 3개씩, 비슷한 점수", fake_detector(targets, seed, duplicates=3, **base)),
        ("+20 junk boxes, low score", "+ 헛예측 20개씩, 낮은 점수", fake_detector(targets, seed, junk=20, **base)),
        ("+96 junk boxes, low score", "+ 헛예측 96개씩, 낮은 점수", fake_detector(targets, seed, junk=96, **base)),
        ("+20 junk boxes, high score", "+ 헛예측 20개씩, 높은 점수", fake_detector(targets, seed, junk=20, junk_score=(0.5, 1.0), **base)),
    ]
    results = []
    for label, label_ko, predictions in variants:
        count = sum(len(p["scores"]) for p in predictions) / len(predictions)
        result = evaluate_ap(predictions, targets, NUM_CLASSES)
        results.append((label, result))
        print(f"  {label_ko:28s} | 그림당 예측 {count:6.2f}개 | {describe(result)}")

    # 중복 박스가 원래 예측과 얼마나 겹치는가 (NMS 문턱값을 읽을 때 필요하다)
    overlap = []
    for pred, target in zip(variants[2][2], targets):
        n = len(target["labels"])  # 앞의 n 개가 원래 예측, 뒤의 n 개가 중복
        overlap.append(paired_box_iou(box_cxcywh_to_xyxy(pred["boxes"][:n]), box_cxcywh_to_xyxy(pred["boxes"][n:])))
    low, mid, high = np.quantile(torch.cat(overlap).numpy(), [0.05, 0.5, 0.95])
    print(f"  중복 박스와 원래 예측의 IoU: 5% 지점 {low:.2f}, 가운데값 {mid:.2f}, 95% 지점 {high:.2f}")
    print("  NMS 를 적용하면 (클래스별)")
    duplicated = variants[3][2]
    nms_rows = []
    for threshold in (0.3, 0.5, 0.7, 0.9):
        cleaned = [nms_per_class(p, threshold) for p in duplicated]
        count = sum(len(p["scores"]) for p in cleaned) / len(cleaned)
        result = evaluate_ap(cleaned, targets, NUM_CLASSES)
        nms_rows.append((threshold, result))
        print(f"  중복 3개씩 → NMS 문턱값 {threshold} | 그림당 예측 {count:6.2f}개 | {describe(result)}")
    results.insert(4, ("+3 duplicates, then NMS 0.5", nms_rows[1][1]))
    cleaned = [nms_per_class(p, 0.5) for p in variants[0][2]]
    count = sum(len(p["scores"]) for p in cleaned) / len(cleaned)
    print(f"  기본 → NMS 문턱값 0.5       | 그림당 예측 {count:6.2f}개 | {describe(evaluate_ap(cleaned, targets, NUM_CLASSES))}")

    fig, ax = plt.subplots(figsize=(9.5, 4.6))
    ys = np.arange(len(results))[::-1]
    height = 0.27
    for k, (key, color, hatch) in enumerate((("AP50", BLUE, ""), ("AP75", ORANGE, "//"), ("AP", GREEN, ".."))):
        values = [result[key] for _, result in results]
        bars = ax.barh(ys + (1 - k) * height, values, height, color=color, hatch=hatch, edgecolor="white", label=key)
        for bar, value in zip(bars, values):
            ax.text(value + 0.008, bar.get_y() + bar.get_height() / 2, f"{value:.3f}", va="center", fontsize=7)
    ax.set_yticks(ys)
    ax.set_yticklabels([label for label, _ in results], fontsize=8)
    ax.set_xlim(0, 1.12)
    ax.set_xlabel("AP")
    ax.set_title("what duplicates, junk boxes and NMS do to AP")
    ax.grid(axis="x", alpha=0.3)
    ax.legend(fontsize=8, loc="lower right")
    fig.tight_layout()
    fig.savefig(os.path.join(fig_dir, "ch03-duplicates.png"), dpi=120)
    plt.close(fig)


# --8<-- [start:crowded]
def crowded_targets(n: int, rng: np.random.Generator, pair_iou: float = 0.7):
    """진짜로 겹친 객체만 있는 정답을 만든다 (그림은 그리지 않는다. 채점에는 정답 박스만 있으면 된다).

    그림마다 같은 클래스 · 같은 크기의 객체 둘을 가로로 dx 만큼 어긋나게 놓는다.
    너비 w 인 두 박스를 dx 만큼 밀면 IoU = (w − dx) / (w + dx) 이므로, dx = w (1 − IoU) / (1 + IoU) 로 잡는다.
    """
    targets = []
    for _ in range(n):
        w, h = rng.uniform(0.2, 0.35, size=2)
        dx = w * (1 - pair_iou) / (1 + pair_iou)
        cx = rng.uniform(w / 2 + 0.02, 1 - w / 2 - dx - 0.02)
        cy = rng.uniform(h / 2 + 0.02, 1 - h / 2 - 0.02)
        cls = int(rng.integers(0, NUM_CLASSES))
        targets.append({"boxes": torch.tensor([[cx, cy, w, h], [cx + dx, cy, w, h]], dtype=torch.float32),
                        "labels": torch.tensor([cls, cls])})
    return targets
# --8<-- [end:crowded]


def experiment_crowded(n: int, sigma: float, seed: int):
    """실험 4: 객체끼리 진짜로 겹쳐 있으면 NMS 문턱값을 어떻게 잡아도 손해를 본다."""
    targets = crowded_targets(n, np.random.default_rng([seed, 3]))
    pair = torch.cat([box_iou(box_cxcywh_to_xyxy(t["boxes"][:1]), box_cxcywh_to_xyxy(t["boxes"][1:]))[0].flatten()
                      for t in targets])
    print(f"[6] 실험 4 · 진짜로 겹친 객체 (그림 {n}장, 그림마다 같은 클래스 객체 2개, 서로의 IoU {float(pair.mean()):.3f})")
    base = dict(sigma=sigma, score_mode="noisy_iou")
    single = fake_detector(targets, seed, **base)
    doubled = fake_detector(targets, seed, duplicates=1, **base)
    print(f"  객체마다 예측 1개              | 그림당 예측 {2.0:5.2f}개 | {describe(evaluate_ap(single, targets, NUM_CLASSES))}")
    for name, predictions in (("예측 1개", single), ("예측 2개(중복 1개)", doubled)):
        for threshold in (None, 0.3, 0.5, 0.7, 0.9):
            if threshold is None and predictions is single:
                continue
            cleaned = predictions if threshold is None else [nms_per_class(p, threshold) for p in predictions]
            count = sum(len(p["scores"]) for p in cleaned) / len(cleaned)
            how = "NMS 없음      " if threshold is None else f"NMS 문턱값 {threshold}"
            print(f"  {name} → {how} | 그림당 예측 {count:5.2f}개 | {describe(evaluate_ap(cleaned, targets, NUM_CLASSES))}")


def main():
    parser = argparse.ArgumentParser(description="3장: 탐지기 채점")
    parser.add_argument("--quick", action="store_true", help="그림 수를 줄여 빠르게 확인")
    parser.add_argument("--fig-dir", default="figures", help="그림을 저장할 폴더")
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()
    os.makedirs(args.fig_dir, exist_ok=True)

    import matplotlib

    matplotlib.use("Agg")
    started = time.time()
    rng = np.random.default_rng(args.seed)

    hand_examples()
    run_checks(rng, trials=50 if args.quick else 300)

    # 도형 세상 검증 세트(seed=1). 그림은 정답만 쓰므로 탐지기도 학습도 필요 없다.
    dataset = ShapesDataset(60 if args.quick else 500, seed=1)
    targets = dataset.targets
    counts = [int(sum((t["labels"] == c).sum() for t in targets)) for c in range(NUM_CLASSES)]
    print(f"검증 세트: 그림 {len(targets)}장, 객체 {sum(counts)}개 (" +
          ", ".join(f"{name} {n}" for name, n in zip(CLASS_NAMES, counts)) + ")")

    sigmas = (0.0, 0.1, 0.2) if args.quick else (0.0, 0.02, 0.04, 0.06, 0.08, 0.1, 0.15, 0.2, 0.3)
    experiment_noise(dataset, sigmas, args.seed, args.fig_dir)
    noisy = experiment_scores(targets, sigma=0.1, seed=args.seed, fig_dir=args.fig_dir)
    figure_pr_curve(noisy, targets, args.fig_dir)
    experiment_duplicates(targets, sigma=0.05, seed=args.seed, fig_dir=args.fig_dir)
    experiment_crowded(40 if args.quick else 300, sigma=0.05, seed=args.seed)
    print(f"끝 ({time.time() - started:.1f}초)")


if __name__ == "__main__":
    main()
