#!/usr/bin/env python3 """ Render summary figures + stats from episode_results/ (no GPU needed). Reads: /episode_results/_/.json Writes: /summary/ fig1_absolute_scores.png 4 checkpoints x episodes x 5 modes fig2_metrics.png Prefix Range / Prefix Std / Reference Error fig3_by_length.png range vs video length summary.md mean / median / p90, %>threshold top10/rankNN_.png 5-mode checkpoint overlays, worst episodes Each mode json stores the accumulated VLAC value at 4 target frames reached by that mode's sampling path (dense_all is the baseline / reference). The metrics compare the 5 paths at the same physical target frame. Run with any python that has numpy + matplotlib: python render_figures.py [--results-root PATH] [--top-n 10] """ from __future__ import annotations import argparse import json from collections import defaultdict from pathlib import Path import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt MODES = ["dense_all", "stride2", "stride4", "front_dense", "back_dense"] REFERENCE_MODE = "dense_all" MODE_COLORS = { "dense_all": "tab:blue", "stride2": "tab:orange", "stride4": "tab:green", "front_dense": "tab:red", "back_dense": "tab:purple", } FRACS = ["1/4", "2/4", "3/4", "end"] THRESHOLD = 20.0 def parse_args(): p = argparse.ArgumentParser() base = Path(__file__).resolve().parent.parent p.add_argument("--results-root", default=str(base / "results_full")) p.add_argument("--top-n", type=int, default=10) return p.parse_args() def load_episodes(results_root: Path): """-> {ep_key: {mode: payload}} for episodes with all 5 modes present.""" data = {} for ep_dir in sorted((results_root / "episode_results").iterdir()): if not ep_dir.is_dir(): continue modes = {} for m in MODES: f = ep_dir / f"{m}.json" if f.exists(): modes[m] = json.loads(f.read_text()) if len(modes) == len(MODES): data[ep_dir.name] = modes return data def value_at(payload, frac): """Accumulated value for this mode at the given checkpoint fraction.""" return float(payload["checkpoints"][frac]["value"]) def main(): args = parse_args() root = Path(args.results_root) out = root / "summary" (out / "top10").mkdir(parents=True, exist_ok=True) data = load_episodes(root) eps = sorted(data) print(f"episodes with all {len(MODES)} modes: {len(eps)}") if not eps: return # ── extract checkpoint scores + metrics ─────────────────────────────── score = defaultdict(dict) # score[(ep, frac)][mode] rng_, std_ = {}, {} ref_err = defaultdict(list) # mode -> [score - dense_all score] for ep in eps: for frac in FRACS: for m in MODES: score[(ep, frac)][m] = value_at(data[ep][m], frac) arr = np.array([score[(ep, frac)][m] for m in MODES]) rng_[(ep, frac)] = float(arr.max() - arr.min()) std_[(ep, frac)] = float(arr.std(ddof=0)) for m in MODES: if m == REFERENCE_MODE: continue ref_err[m].append(score[(ep, frac)][m] - score[(ep, frac)][REFERENCE_MODE]) ep_mean_rng = {e: np.mean([rng_[(e, f)] for f in FRACS]) for e in eps} ep_max_rng = {e: max(rng_[(e, f)] for f in FRACS) for e in eps} order = sorted(eps, key=lambda e: -ep_mean_rng[e]) x = np.arange(len(order)) all_rng = list(rng_.values()) pct_all = 100.0 * np.mean(np.array(all_rng) > THRESHOLD) other_modes = [m for m in MODES if m != REFERENCE_MODE] # ── fig1: absolute scores ───────────────────────────────────────────── fig, axes = plt.subplots(4, 1, figsize=(16, 14), sharex=True) for ax, frac in zip(axes, FRACS): for i, e in enumerate(order): vals = [score[(e, frac)][m] for m in MODES] ax.plot([i, i], [min(vals), max(vals)], color="0.85", lw=1, zorder=1) for m in MODES: ax.scatter(x, [score[(e, frac)][m] for e in order], s=8, color=MODE_COLORS[m], label=m, zorder=2) ax.set_ylabel("value (0-100)") ax.set_title(f"checkpoint {frac}", loc="left", fontsize=11) ax.set_ylim(0, 100) ax.grid(alpha=0.2) axes[0].legend(ncol=5, fontsize=9, loc="upper right") axes[-1].set_xlabel("episode (sorted by mean Prefix Range, desc)") fig.suptitle("Summary of accumulated VLAC values — 5 sampling-path modes per episode\n" "(gray bar = min-max spread at the same physical target frame)", y=0.995) fig.tight_layout() fig.savefig(out / "fig1_absolute_scores.png", dpi=150) plt.close(fig) # ── fig2: metrics ───────────────────────────────────────────────────── fig, axes = plt.subplots(2, 2, figsize=(15, 11)) ax = axes[0][0] for frac in FRACS: vals = sorted((rng_[(e, frac)] for e in eps), reverse=True) pct = 100.0 * np.mean(np.array(vals) > THRESHOLD) ax.plot(vals, label=f"{frac} ({pct:.0f}% > {THRESHOLD:.0f} pts)") ax.axhline(THRESHOLD, color="red", ls="--", lw=1) ax.set_xlabel("episode rank (desc)") ax.set_ylabel("Prefix Range (pts)") ax.set_title("(A) Prefix Range per checkpoint, sorted") ax.legend(fontsize=9) ax.grid(alpha=0.2) ax = axes[0][1] ax.hist(all_rng, bins=30, color="tab:red", alpha=0.75) ax.axvline(THRESHOLD, color="black", ls="--", lw=1.5, label=f"{THRESHOLD:.0f}-pt threshold") ax.set_xlabel("Prefix Range (pts)") ax.set_ylabel("count (episode x checkpoint)") ax.set_title(f"(B) Prefix Range distribution — {pct_all:.0f}% above threshold") ax.legend(fontsize=9) ax.grid(alpha=0.2) ax = axes[1][0] ax.hist(list(std_.values()), bins=30, color="tab:blue", alpha=0.75) ax.set_xlabel("Prefix Std (pts)") ax.set_ylabel("count (episode x checkpoint)") ax.set_title("(C) Prefix Std distribution") ax.grid(alpha=0.2) ax = axes[1][1] ax.boxplot([ref_err[m] for m in other_modes], labels=[m.replace("_", "\n") for m in other_modes], showmeans=True) ax.axhline(0, color="black", lw=1) ax.set_ylabel("value - dense_all value (pts)") ax.set_title("(D) Reference Error vs dense_all (signed)") ax.grid(alpha=0.2) fig.suptitle("Prefix-robustness metrics (VLAC, accumulated critic values)", y=0.995) fig.tight_layout() fig.savefig(out / "fig2_metrics.png", dpi=150) plt.close(fig) # ── fig3: range vs video length ─────────────────────────────────────── fig, ax = plt.subplots(figsize=(10, 6)) dur = np.array([data[e][REFERENCE_MODE]["total_raw_frames"] / max(data[e][REFERENCE_MODE]["native_fps"], 1e-6) for e in eps]) mrng = np.array([ep_max_rng[e] for e in eps]) qs = np.quantile(dur, [0, 0.25, 0.5, 0.75, 1.0]) groups, labels = [], [] for lo, hi in zip(qs[:-1], qs[1:]): m = (dur >= lo) & (dur <= hi) groups.append(mrng[m]) labels.append(f"{lo:.0f}-{hi:.0f}s\n(n={m.sum()})") ax.boxplot(groups, labels=labels, showmeans=True) ax.axhline(THRESHOLD, color="red", ls="--", lw=1) ax.set_xlabel("video length (quartile bins)") ax.set_ylabel("max Prefix Range over 4 checkpoints (pts)") ax.set_title("Prefix Range vs video length") ax.grid(alpha=0.2) fig.tight_layout() fig.savefig(out / "fig3_by_length.png", dpi=150) plt.close(fig) # ── summary.md ──────────────────────────────────────────────────────── def stats(vals): a = np.array(vals) return (f"mean {a.mean():.2f} | median {np.median(a):.2f} | " f"p90 {np.quantile(a, 0.9):.2f} | max {a.max():.2f}") cam = data[eps[0]][REFERENCE_MODE]["camera"] lines = ["# VLAC prefix-robustness — full batch summary (accumulated critic values)", ""] lines += [f"Episodes: **{len(eps)}** | camera: {cam} | " f"modes: {', '.join(MODES)} | reference: {REFERENCE_MODE} | " f"threshold: {THRESHOLD:.0f} pts", ""] lines += ["## Prefix Range (max - min of 5 mode values, same target frame)", "", "| checkpoint | stats | % > threshold |", "|---|---|---|"] for frac in FRACS: vals = [rng_[(e, frac)] for e in eps] pct = 100.0 * np.mean(np.array(vals) > THRESHOLD) lines.append(f"| {frac} | {stats(vals)} | **{pct:.1f}%** |") lines.append(f"| all | {stats(all_rng)} | **{pct_all:.1f}%** |") ep_any = 100.0 * np.mean([ep_max_rng[e] > THRESHOLD for e in eps]) lines += ["", f"Episodes with >= 1 checkpoint above threshold: **{ep_any:.1f}%**", ""] lines += ["## Prefix Std", "", f"All cells: {stats(list(std_.values()))}", ""] lines += ["## Reference Error vs dense_all (signed, pts)", "", "| mode | mean | median | std |", "|---|---|---|---|"] for m in other_modes: a = np.array(ref_err[m]) lines.append(f"| {m} | {a.mean():+.2f} | {np.median(a):+.2f} | {a.std():.2f} |") lines.append("") # ── top10: 5-mode checkpoint overlays ───────────────────────────────── worst = sorted(eps, key=lambda e: -ep_max_rng[e])[:args.top_n] lines += [f"## Top {args.top_n} least-robust episodes (by max Prefix Range)", "", "| rank | episode | max range | mean range | figure |", "|---|---|---|---|---|"] xt = np.arange(len(FRACS)) for rank, e in enumerate(worst, 1): fname = f"rank{rank:02d}_{e}.png" lines.append(f"| {rank} | {e} | {ep_max_rng[e]:.1f} | " f"{ep_mean_rng[e]:.1f} | top10/{fname} |") fig, ax = plt.subplots(figsize=(11, 6)) for i, e2 in enumerate(FRACS): vals = [score[(e, e2)][m] for m in MODES] ax.plot([i, i], [min(vals), max(vals)], color="0.85", lw=2, zorder=1) for m in MODES: ys = [score[(e, frac)][m] for frac in FRACS] ax.plot(xt, ys, "-o", color=MODE_COLORS[m], lw=1.6, ms=6, label=m, zorder=2) ax.set_xticks(xt) ax.set_xticklabels(FRACS) ax.set_xlabel("target frame (checkpoint)") ax.set_ylabel("accumulated value (0-100)") ax.set_ylim(0, 100) ax.grid(alpha=0.2) ax.legend(fontsize=9) task = data[e][REFERENCE_MODE]["task"] ax.set_title(f"#{rank} {e} max range {ep_max_rng[e]:.1f}\n{task[:110]}", fontsize=10) fig.tight_layout() fig.savefig(out / "top10" / fname, dpi=140) plt.close(fig) (out / "summary.md").write_text("\n".join(lines)) print("written:", out) if __name__ == "__main__": main()