"""closed-loop 기준선 그림 (발표자료 'closed-loop 평가 지표 — HD-Score' 장). 시나리오 2개 × [위에서 본 주행 경로 | constant 정책이 부딪힌 순간의 정면 카메라 관측]. 입력은 nusim sim run 결과 outputs/closed_loop/<시나리오>/{replay_800,constant_800} (800×450, 2026-10-11) 그대로. 실행: source scripts/local_env.sh && python docs/presentation/figures/closed_loop/fig_hdscore.py [출력.png] """ import json import sys from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from matplotlib import font_manager from matplotlib.patches import Polygon from PIL import Image from nusim.sim.geometry import Drivable, ObstacleGrid ROOT = Path(__file__).resolve().parents[4] CL = ROOT / "outputs/closed_loop" OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[1] / "out/fig_hdscore.png" FONT = "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc" font_manager.fontManager.addfont(FONT) plt.rcParams["font.family"] = font_manager.FontProperties(fname=FONT).get_name() plt.rcParams["font.size"] = 15 SCEN = [("scene-0402_easy", "scene-0402 Easy — 235 m 직선"), ("scene-0006_easy", "scene-0006 Easy — 101 m, 90° 회전")] C_REPLAY, C_CONST, C_ROUTE = "#4472C4", "#ED7D31", "#9AA3B0" def steps(d): a = np.genfromtxt(d / "steps.csv", delimiter=",", names=True) return a fig, axes = plt.subplots(2, 2, figsize=(12, 8.2), gridspec_kw={"width_ratios": [1, 1.6]}) for row, (name, title) in enumerate(SCEN): rep, con = CL / name / "replay_800", CL / name / "constant_800" ep = json.loads((con / "episode.json").read_text()) sr, sc = json.loads((rep / "score.json").read_text()), json.loads((con / "score.json").read_text()) route = np.array(ep["route"]) a_r, a_c = steps(rep), steps(con) ax = axes[row, 0] pts = np.r_[route, np.c_[a_c["x"], a_c["y"]]] lo, hi = pts.min(0) - 12, pts.max(0) + 12 c, half = (lo + hi) / 2, (hi - lo).max() / 2 x0, x1, y0, y1 = c[0] - half, c[0] + half, c[1] - half, c[1] + half for rings in Drivable.load(Path(ep["paths"]["drivable"])).polys: ax.add_patch(Polygon(rings[0], closed=True, fc="#E6EAF0", ec="none", zorder=0)) for hole in rings[1:]: ax.add_patch(Polygon(hole, closed=True, fc="white", ec="none", zorder=0)) og = ObstacleGrid.load(Path(ep["paths"]["obstacles"])) occ = np.ma.masked_equal((og.g != 0).astype(float), 0) h, w = og.g.shape ax.imshow(occ, origin="lower", cmap="Greys", vmin=0, vmax=1.4, interpolation="nearest", extent=[og.x0, og.x0 + w * og.res, og.y0, og.y0 + h * og.res], zorder=1) ax.plot(route[:, 0], route[:, 1], "--", color=C_ROUTE, lw=1.4, zorder=2, label="경로 (기록)") ax.plot(a_r["x"], a_r["y"], color=C_REPLAY, lw=2.4, zorder=3, label=f"replay HD {sr['hd_score']:.3f}") ax.plot(a_c["x"], a_c["y"], color=C_CONST, lw=2.4, zorder=4, label=f"constant HD {sc['hd_score']:.3f}") ax.plot(a_c["x"][-1], a_c["y"][-1], "x", color="#C00000", ms=13, mew=3, zorder=5, label="충돌") ax.plot(route[0, 0], route[0, 1], "o", color="k", ms=6, zorder=5) ax.set_xlim(x0, x1); ax.set_ylim(y0, y1); ax.set_aspect("equal") ax.set_xticks([]); ax.set_yticks([]) ax.set_title(title, fontsize=19, fontweight="bold") ax.legend(loc="lower right" if row == 0 else "upper right", fontsize=14, framealpha=0.9) sb = 20.0 # 축척 막대 ax.plot([x0 + 4, x0 + 4 + sb], [y0 + 4, y0 + 4], color="k", lw=3) ax.text(x0 + 4 + sb / 2, y0 + 6, "20 m", ha="center", fontsize=14) cam = sorted((con / "front").glob("*.jpg"))[-1] ax = axes[row, 1] ax.imshow(Image.open(cam)) ax.set_xticks([]); ax.set_yticks([]) ax.set_title(f"constant — 충돌 순간 정면 관측 ({sc['progress_m']:.0f} m, {sc['duration_s']:.1f} s)", fontsize=18) fig.tight_layout(pad=0.6) OUT.parent.mkdir(parents=True, exist_ok=True) fig.savefig(OUT, dpi=150) print("saved", OUT)