File size: 13,399 Bytes
45e45cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#!/usr/bin/env python3
"""
Render summary figures + stats from episode_results/ (no GPU needed).

Reads:  <results-root>/episode_results/<chunk>_<episode>/<mode>.json
Writes: <results-root>/summary/
          fig1_absolute_scores.png   4 checkpoints x episodes x 5 modes
          fig2_metrics.png           Anchor Range / Anchor Std / Reference Error
          fig3_by_length.png         range vs video length
          summary.md                 mean / median / p90, %>threshold
          top10/rankNN_<episode>.png full 5-curve overlays, worst episodes

The 5 modes are the 3 GRM BEFORE-anchoring modes (incremental / forward /
backward) plus 2 sampling-density variants (interval_half / interval_double).
Because the density variants sample a different number of frames, checkpoints
are aligned by physical AFTER-frame index: the incremental (baseline) sequence
defines the 4 target frames (1/4, 2/4, 3/4, end); every mode contributes the
score of its AFTER frame closest to each target.

Metric (same as Robometer):
  Anchor Range   = max - min of the 5 mode scores at the same physical frame
  Anchor Std     = std of the 5 mode scores
  Reference Error= mode score - incremental score (signed)
  threshold      = 20 pts

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 = ["incremental", "forward", "backward", "interval_half", "interval_double"]
BASELINE = "incremental"
MODE_COLORS = {
    "incremental": "tab:blue", "forward": "tab:orange", "backward": "tab:green",
    "interval_half": "tab:red", "interval_double": "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 = {}
    ep_root = results_root / "episode_results"
    if not ep_root.exists():
        return data
    for ep_dir in sorted(ep_root.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 target_frames(baseline_after: list[int]) -> list[int]:
    """4 physical AFTER-frame indices at 1/4, 2/4, 3/4, end of the baseline seq."""
    L = len(baseline_after)
    ps = [int(round((L - 1) * k / 4)) for k in (1, 2, 3, 4)]
    return [baseline_after[p] for p in ps]


def score_at(payload: dict, target_af: int) -> float:
    """Score of the AFTER frame closest to target_af (physical alignment)."""
    afs = payload["after_frames"]
    j = min(range(len(afs)), key=lambda i: abs(afs[i] - target_af))
    return payload["scores_100"][j]


def video_length_s(payload: dict) -> float:
    return payload["total_raw_frames"] / max(payload.get("native_fps", 0.0), 1e-6)


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)
    rng_, std_ = {}, {}
    ref_err = defaultdict(list)          # mode -> [score - incremental score]
    fb_diff = []                         # forward - backward per (ep, frac)
    for ep in eps:
        base_after = data[ep][BASELINE]["after_frames"]
        tgts = target_frames(base_after)
        for frac, taf in zip(FRACS, tgts):
            for m in MODES:
                score[(ep, frac)][m] = score_at(data[ep][m], taf)
            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 == BASELINE:
                    continue
                ref_err[m].append(score[(ep, frac)][m] - score[(ep, frac)][BASELINE])
            fb_diff.append(score[(ep, frac)]["forward"] - score[(ep, frac)]["backward"])

    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)

    non_base = [m for m in MODES if m != BASELINE]

    # ── 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("score (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 Anchor Range, desc)")
    fig.suptitle("Summary of absolute progress scores - 5 anchoring modes per episode\n"
                 "(gray bar = min-max spread at the same physical 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("Anchor Range (pts)")
    ax.set_title("(A) Anchor 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("Anchor Range (pts)")
    ax.set_ylabel("count (episode x checkpoint)")
    ax.set_title(f"(B) Anchor 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("Anchor Std (pts)")
    ax.set_ylabel("count (episode x checkpoint)")
    ax.set_title("(C) Anchor Std distribution")
    ax.grid(alpha=0.2)

    ax = axes[1][1]
    ax.boxplot([ref_err[m] for m in non_base],
               labels=[m.replace("_", "\n") for m in non_base], showmeans=True)
    ax.axhline(0, color="black", lw=1)
    ax.set_ylabel("score - incremental score (pts)")
    ax.set_title("(D) Reference Error vs incremental (signed)")
    ax.grid(alpha=0.2)

    fig.suptitle("Prefix-robustness metrics (Robo-Dopamine, dense curves)", 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([video_length_s(data[e][BASELINE]) 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={int(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 Anchor Range over 4 checkpoints (pts)")
    ax.set_title("Anchor 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]][BASELINE]["camera"]
    lines = ["# Robo-Dopamine prefix-robustness - full batch summary (dense curves)", ""]
    lines += [f"Episodes: **{len(eps)}**  |  camera: {cam}  |  "
              f"modes: {', '.join(MODES)}  |  threshold: {THRESHOLD:.0f} pts", ""]
    lines += ["Score axis = the GRM pipeline `progress` field (0-100), i.e. the "
              "per-mode task-completion estimate. The 3 anchor modes share "
              f"frame_interval={data[eps[0]]['incremental']['frame_interval']}; "
              "interval_half / interval_double halve / double it and are aligned "
              "to each checkpoint by the closest physical AFTER frame.", ""]
    lines += ["## Anchor Range (max - min of 5 mode scores, same 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 += ["## Anchor Std", "", f"All cells: {stats(list(std_.values()))}", ""]
    lines += ["## Reference Error vs incremental (signed, pts)", "",
              "| mode | mean | median | std |", "|---|---|---|---|"]
    for m in non_base:
        a = np.array(ref_err[m])
        lines.append(f"| {m} | {a.mean():+.2f} | {np.median(a):+.2f} | {a.std():.2f} |")
    lines.append("")
    fb = np.array(fb_diff)
    lines += ["## Anchor bias: forward vs backward (systematic)", "",
              f"forward - backward (same frame): mean **{fb.mean():+.2f}** | "
              f"median {np.median(fb):+.2f} | std {fb.std():.2f} pts", "",
              "A large non-zero mean is direct evidence the model's completion "
              "estimate depends on whether it is anchored to the start or the goal.", ""]

    # ── top10: full-curve 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 Anchor Range)", "",
              "| rank | episode | max range | mean range | figure |",
              "|---|---|---|---|---|"]
    for rank, e in enumerate(worst, 1):
        base_after = data[e][BASELINE]["after_frames"]
        tgts = target_frames(base_after)
        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=(13, 6))
        for m in MODES:
            pay = data[e][m]
            xs = np.array(pay["after_frames"], dtype=float)
            ax.plot(xs, pay["scores_100"], color=MODE_COLORS[m], lw=1.5,
                    marker=".", ms=3, label=m)
        for frac, taf in zip(FRACS, tgts):
            ax.axvline(taf, color="0.6", ls=":", lw=1)
            ax.text(taf, 97, frac, ha="center", fontsize=8, color="0.4")
        ax.set_xlabel("physical AFTER-frame index (original video frames)")
        ax.set_ylabel("progress score (0-100)")
        ax.set_ylim(0, 100)
        ax.grid(alpha=0.2)
        ax.legend(fontsize=9)
        task = data[e][BASELINE]["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()