File size: 30,098 Bytes
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa90b0
 
 
 
 
 
 
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa90b0
 
 
 
 
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa90b0
 
 
 
 
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b504c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4fdc38
 
 
 
 
 
 
0b504c6
 
 
f4fdc38
 
0b504c6
 
f4fdc38
0b504c6
f4fdc38
0b504c6
f4fdc38
0b504c6
 
 
f4fdc38
0b504c6
 
 
 
 
 
 
f4fdc38
0b504c6
 
f4fdc38
 
 
0b504c6
 
 
 
 
 
 
 
 
 
 
 
f4fdc38
0b504c6
 
 
 
 
 
 
 
f4fdc38
0b504c6
f4fdc38
 
 
0b504c6
 
 
 
 
 
 
 
f4fdc38
0b504c6
 
 
 
 
 
 
 
 
 
 
 
f4fdc38
 
 
 
 
0b504c6
 
99e41a8
f4fdc38
99e41a8
 
 
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#!/usr/bin/env python3
"""README videos, 1280x720 @ 30 fps H.264 (+ GIF previews). All content comes from cached results.

  robot_rollouts      SO-101 arm (MuJoCo Menagerie) pick-and-place, 5 cameras, then the camera swarm's
                      verdict: clean, and with 3 of 5 cameras inverted (liar majority)
  swarm_rendezvous    12 robots, 4 colluding Byzantine robots: mean vs W-MSR vs RACE-C+W-MSR + live error plot
  planbench_modulo    a real cached LLM plan for a PlanBench instance: validator catches the failing step,
                      the repaired plan (LLM-Modulo) reaches the goal
"""
import json
import os
import subprocess
import sys
from pathlib import Path

os.environ.setdefault("MUJOCO_GL", "egl")
import matplotlib  # noqa: E402
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
from PIL import Image, ImageDraw, ImageFont  # noqa: E402

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from robotics.bench import trackA, trackB  # noqa: E402
from robotics.benchmarks import blocksworld as bw  # noqa: E402
from robotics.swarm import attacks, fusion  # noqa: E402

OUT = Path("media/videos")
OUT.mkdir(parents=True, exist_ok=True)
W, H, FPS = 1280, 720, 30
TEAL, RED, INK, GREY, AMBER, BG = (15, 118, 110), (220, 38, 38), (31, 41, 55), (156, 163, 175), (217, 119, 6), (250, 250, 249)
FONT_DIR = Path(matplotlib.get_data_path()) / "fonts/ttf"


def font(size, bold=False):
    return ImageFont.truetype(str(FONT_DIR / ("DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf")), size)


class Writer:
    def __init__(self, path):
        self.path = path
        self.p = subprocess.Popen(["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
                                   "-s", f"{W}x{H}", "-r", str(FPS), "-i", "-", "-c:v", "libx264", "-preset", "slow",
                                   "-crf", "20", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(path)],
                                  stdin=subprocess.PIPE)

    def add(self, img, n=1):
        b = np.asarray(img.convert("RGB").resize((W, H)) if img.size != (W, H) else img.convert("RGB")).tobytes()
        for _ in range(n):
            self.p.stdin.write(b)

    def close(self):
        self.p.stdin.close()
        self.p.wait()


def to_gif(mp4, width=640, fps=12):
    gif = mp4.with_suffix(".gif")
    pal = mp4.with_suffix(".pal.png")
    vf = f"fps={fps},scale={width}:-1:flags=lanczos"
    subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(mp4), "-vf", vf + ",palettegen=max_colors=128",
                    str(pal)], check=True)
    subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(mp4), "-i", str(pal), "-lavfi",
                    vf + "[x];[x][1:v]paletteuse=dither=sierra2_4a", str(gif)], check=True)
    pal.unlink()
    return gif


def card(title, lines, accent=TEAL):
    im = Image.new("RGB", (W, H), BG)
    d = ImageDraw.Draw(im)
    d.rectangle([0, 0, 14, H], fill=accent)
    d.text((80, 230), title, font=font(46, True), fill=INK)
    for k, ln in enumerate(lines):
        d.text((82, 320 + 44 * k), ln, font=font(26), fill=(75, 85, 99))
    return im


# ============================================================================ robot rollouts
def robot_rollouts(n_show=3, liars=(1, 2, 3), robot="so101"):
    if robot == "panda":
        from robotics.sim.panda_env import rollout
    else:
        from robotics.sim.so101_env import rollout
    eps = {e["seed"]: e for e in map(json.loads, open(f"data/{robot}/episodes.jsonl"))}
    (Ph, yh, _), (Pe, ye, kinds) = trackA.load_scores(f"results/{robot}/vlm_scores.jsonl")
    eval_seeds = sorted(s for s, e in eps.items() if e["split"] == "eval")
    Pa = attacks.apply(Pe, list(liars), "invert", "eval", np.random.default_rng(0))
    maj_c = fusion.majority(Pe, Pe)
    rs_c = fusion.race_s(Pe, Pe, 0)[:2]
    maj_a = fusion.majority(Pa, Pa)
    rs_a = fusion.race_s(Pa, Pa, 0)[:2]
    dec = lambda st: st[0] > st[1]  # noqa: E731
    mc, rc, ma, ra = dec(maj_c), dec(rs_c), dec(maj_a), dec(rs_a)
    want = ["success", "wrong_place", "wrong_object", "drop_transit", "miss_grasp"]
    picks = []
    for mode in want:
        for k, s in enumerate(eval_seeds):
            if eps[s]["mode"] == mode and rc[k] == ye[k] and ra[k] == ye[k] and ma[k] != ye[k] and k not in picks:
                picks.append(k)
                break
        if len(picks) == n_show:
            break
    out_path = OUT / ("panda_rollouts.mp4" if robot == "panda" else "robot_rollouts.mp4")
    arm = "Franka Panda" if robot == "panda" else "SO-101"
    wr = Writer(out_path)
    wr.add(card(f"RoboRACE · {arm} camera swarm", [
        f"A MuJoCo {arm} arm (Menagerie model) runs scripted pick-and-place with injected failures.",
        "Ground truth comes from the final physics state, never from the script.",
        "Five camera agents judge success with Cosmos-Reason2-2B on a CPU; then 3 of 5 cameras lie.",
        "Majority vote vs RACE-S (label-free, receiver-anchored) — real cached scores."]), FPS * 4)
    for n, k in enumerate(picks):
        seed = eval_seeds[k]
        e = eps[seed]
        ep = rollout(seed, want_success=(e["mode"] == "success"), record_video=True, render_size=320)
        assert ep.success == e["success"], "replay must reproduce the cached episode"
        frames = ep.frames + [ep.frames[-1]] * 1
        for f_i, fr in enumerate(frames):
            wr.add(_robot_frame(fr, e, n, len(picks), phase="rollout", progress=f_i / len(frames)))
        for phase, P, fused_maj, fused_rs in (("clean", Pe, mc, rc), ("attack", Pa, ma, ra)):
            for t in range(int(FPS * 3.2)):
                wr.add(_robot_frame(frames[-1], e, n, len(picks), phase=phase, scores=P[k], reveal=min(1, t / 25),
                                    maj=fused_maj[k], rs=fused_rs[k], gt=ye[k], liars=liars if phase == "attack" else ()))
    wr.add(card("Takeaway", ["With an honest swarm, every fusion rule agrees with the ground truth.",
                             "With a liar majority, majority vote flips; RACE-S learns negative weights for",
                             "the lying cameras without labels, inverts them, and stays correct."]), FPS * 4)
    wr.close()
    return out_path


def panda_rollouts():
    return robot_rollouts(robot="panda")


def _robot_frame(views, e, n, n_tot, phase, progress=0.0, scores=None, reveal=0.0, maj=None, rs=None, gt=None, liars=()):
    from robotics.sim.so101_env import CAMERAS
    im = Image.new("RGB", (W, H), BG)
    d = ImageDraw.Draw(im)
    d.rectangle([0, 0, W, 58], fill=(255, 255, 255))
    d.text((20, 12), f"Task: “{e['task']}”", font=font(24, True), fill=INK)
    d.text((W - 300, 18), f"episode {n + 1}/{n_tot} · seed {e['seed']}", font=font(17), fill=(107, 114, 128))
    pos = [(10, 68), (330, 68), (650, 68), (10, 396), (330, 396)]
    for j, c in enumerate(CAMERAS):
        x, y = pos[j]
        tile = Image.fromarray(views[c]).resize((310, 310))
        im.paste(tile, (x, y))
        liar = j in liars
        col = RED if liar else (TEAL if j == 0 else GREY)
        d.rectangle([x - 2, y - 2, x + 311, y + 311], outline=col, width=5 if (liar or j == 0) else 2)
        lab = f"{c}{' · receiver' if j == 0 else ''}{' · LIAR' if liar else ''}"
        d.rectangle([x, y, x + 8 + 10 * len(lab), y + 26], fill=col)
        d.text((x + 5, y + 3), lab, font=font(15, True), fill=(255, 255, 255))
        if scores is not None:
            p = float(scores[j])
            bw_ = int(296 * p * reveal)
            d.rectangle([x + 7, y + 284, x + 303, y + 302], fill=(243, 244, 246))
            d.rectangle([x + 7, y + 284, x + 7 + bw_, y + 302], fill=RED if liar else TEAL)
            d.text((x + 10, y + 262), f"P(success) = {p:.2f}", font=font(15, True), fill=(255, 255, 255),
                   stroke_width=2, stroke_fill=(0, 0, 0))
    # sixth cell: how to read the frame
    lx, ly = 650, 396
    d.rectangle([lx, ly, lx + 310, ly + 310], fill=(255, 255, 255), outline=(229, 231, 235), width=2)
    d.text((lx + 16, ly + 14), "How to read", font=font(18, True), fill=INK)
    legend = [(TEAL, "receiver (own camera)"), (RED, "lying camera"), (GREY, "honest camera")]
    for k, (col, txt) in enumerate(legend):
        y0 = ly + 52 + 34 * k
        d.rectangle([lx + 16, y0, lx + 34, y0 + 18], outline=col, width=4)
        d.text((lx + 44, y0), txt, font=font(14), fill=INK)
    d.text((lx + 16, ly + 162), "bar = the camera's reported\nP(success) from Cosmos-Reason2-2B\n(real cached scores, CPU)",
           font=font(14), fill=(75, 85, 99), spacing=4)
    d.text((lx + 16, ly + 238), "ground truth = final physics\nstate, never the script", font=font(14), fill=(75, 85, 99),
           spacing=4)
    # right panel
    px = 970
    d.rectangle([px, 68, W - 10, H - 10], fill=(255, 255, 255), outline=(229, 231, 235), width=2)
    if phase == "rollout":
        d.text((px + 18, 88), "Executing", font=font(22, True), fill=INK)
        d.text((px + 18, 122), "IK + position control,\nkinematic grasp,\nfree-body physics", font=font(16),
               fill=(75, 85, 99), spacing=6)
        d.rectangle([px + 18, 220, W - 30, 236], fill=(243, 244, 246))
        d.rectangle([px + 18, 220, px + 18 + int((W - 48 - px) * progress), 236], fill=TEAL)
        return im
    title = "Honest swarm" if phase == "clean" else "3 of 5 cameras lie"
    d.text((px + 18, 88), title, font=font(22, True), fill=TEAL if phase == "clean" else RED)
    d.text((px + 18, 122), "reports inverted: 1 − p" if phase == "attack" else "all cameras report truthfully",
           font=font(15), fill=(75, 85, 99))
    if reveal >= 1:
        rows = [("Majority vote", maj), ("RACE-S (ours)", rs)]
        for k, (nm, v) in enumerate(rows):
            ok = v == gt
            y0 = 180 + 92 * k
            d.text((px + 18, y0), nm, font=font(18, True), fill=INK)
            d.text((px + 18, y0 + 28), f"{'SUCCESS' if v else 'FAILURE'}  {'✓' if ok else '✗'}", font=font(24, True),
                   fill=TEAL if ok else RED)
        d.line([px + 18, 372, W - 30, 372], fill=(229, 231, 235), width=2)
        d.text((px + 18, 386), "Ground truth (physics)", font=font(16, True), fill=INK)
        d.text((px + 18, 412), f"{'SUCCESS' if gt else 'FAILURE'}", font=font(24, True), fill=INK)
        if e["mode"] != "success":
            d.text((px + 18, 446), "failure mode: " + e["mode"].replace("_", " "), font=font(16), fill=(107, 114, 128))
    return im


# ============================================================================ swarm rendezvous
def swarm_rendezvous(F=4, attack="collude", seed=11):
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    methods = [("mean", "DeGroot average", GREY), ("wmsr", "W-MSR (LeBlanc 2013)", (37, 99, 235)),
               ("race_c+wmsr", "RACE-C + W-MSR (ours)", TEAL)]
    base = trackB.World(F=F, attack=attack, seed=seed)
    target = np.array([6.5, 4.0])
    m = base.measure(target)
    traces = {}
    for meth, _, _ in methods:
        w = trackB.World(F=F, attack=attack, seed=seed)
        w.sigma, w.byz, w.A, w.pos = base.sigma, base.byz, base.A, base.pos
        chan = trackB.channel_estimates(w, trackB.history(w)) if meth.startswith("race_c") else None
        tr = []
        if meth.startswith("race_c"):
            trackB.mission(w, meth, chan, target=target, m=m.copy(), trace=tr)
        else:
            x = m.copy()
            honest = ~w.byz
            tr = [(x.copy(), np.zeros((w.n, w.n), bool))]
            for rnd in range(15):
                new = x.copy()
                for i in np.flatnonzero(honest):
                    nb = np.flatnonzero(w.A[i])
                    vals = np.array([w.lie(j, i, x[j], target, "eval", rnd) if w.byz[j] else x[j] for j in nb])
                    new[i] = np.vstack([x[i], vals]).mean(0) if meth == "mean" else trackB._wmsr(x[i], vals, w.F)
                x = new
                tr.append((x.copy(), np.zeros((w.n, w.n), bool)))
        traces[meth] = tr
    honest = ~base.byz
    n_rounds = max(len(t) for t in traces.values())
    per, hold = 9, 60
    pos = {k: base.pos.astype(float).copy() for k in traces}
    trail = {k: [base.pos.astype(float).copy()] for k in traces}
    err_hist = {k: [] for k in traces}
    allp = np.vstack([base.pos, target, target + base.bloc])
    lo, hi = allp.min(0) - 0.8, allp.max(0) + 0.8
    wr = Writer(OUT / "swarm_rendezvous.mp4")
    wr.add(card("RoboRACE · Byzantine rendezvous", [
        "12 robots measure a target with noisy sensors, agree on it by radio, and drive there.",
        f"{F} robots are Byzantine and collude: they all broadcast the same false target.",
        "Same robots, same lies, three consensus rules."], accent=(37, 99, 235)), FPS * 3)
    fig = plt.figure(figsize=(12.8, 7.2), dpi=100)
    canvas = FigureCanvasAgg(fig)
    for t in range(n_rounds * per + hold):
        r = min(t // per, n_rounds - 1)
        fig.clf()
        gs = fig.add_gridspec(2, 3, height_ratios=[3.2, 1], left=0.02, right=0.98, top=0.9, bottom=0.08, hspace=0.25,
                              wspace=0.05)
        for col, (meth, title, c) in enumerate(methods):
            ax = fig.add_subplot(gs[0, col])
            est, banned = traces[meth][min(r, len(traces[meth]) - 1)]
            pos[meth][honest] += 0.1 * (est[honest] - pos[meth][honest])
            trail[meth].append(pos[meth].copy())
            P = pos[meth]
            Tr = np.array(trail[meth])
            for i in range(base.n):
                for j in np.flatnonzero(base.A[i]):
                    if j > i:
                        iso = (banned[i, j] and honest[i]) or (banned[j, i] and honest[j])
                        ax.plot(*zip(P[i], P[j]), color="#dc2626" if iso else "#e5e7eb", lw=1.6 if iso else 0.6,
                                ls="--" if iso else "-", zorder=1)
            for i in np.flatnonzero(honest):
                ax.plot(Tr[:, i, 0], Tr[:, i, 1], color=np.array(c) / 255, alpha=0.35, lw=1, zorder=2)
            ax.add_patch(plt.Circle(target, 0.5, fill=False, ls=":", color="#b45309", lw=1.4, zorder=3))
            ax.scatter(*target, marker="*", s=260, color="#f59e0b", edgecolor="black", zorder=3)
            ax.scatter(*(target + base.bloc), marker="P", s=110, color="#fecaca", edgecolor="#dc2626", zorder=3)
            ax.scatter(P[honest, 0], P[honest, 1], s=42, color=np.array(c) / 255, edgecolor="white", zorder=5)
            ax.scatter(P[~honest, 0], P[~honest, 1], s=80, marker="X", color="#dc2626", zorder=5)
            err = np.linalg.norm(P[honest] - target, axis=1).max()
            if col == 0 or len(err_hist[meth]) < t + 1:
                err_hist[meth].append(err)
            ax.set_xlim(lo[0], hi[0])
            ax.set_ylim(lo[1], hi[1])
            ax.set_aspect("equal")
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_title(title, fontsize=13, fontweight="bold", color=np.array(c) / 255 if col else "#374151")
            ok = err < 0.5
            ax.text(0.02, 0.03, f"worst honest error {err:.2f} m" + ("  ✓" if ok else ""), transform=ax.transAxes,
                    fontsize=11, fontweight="bold", color="#0f766e" if ok else "#b91c1c")
        axe = fig.add_subplot(gs[1, :])
        for meth, title, c in methods:
            axe.plot(np.arange(len(err_hist[meth])) / FPS, err_hist[meth], color=np.array(c) / 255, lw=2, label=title)
        axe.axhline(0.5, color="#b45309", ls=":", lw=1.2)
        axe.text(0.01, 0.55, "mission tolerance 0.5 m", fontsize=9, color="#b45309", transform=axe.get_yaxis_transform())
        axe.set_xlim(0, (n_rounds * per + hold) / FPS)
        axe.set_ylim(0, max(8, max(max(v) for v in err_hist.values())))
        axe.set_ylabel("worst honest\nerror (m)", fontsize=9)
        axe.set_xlabel("time (s)", fontsize=9)
        axe.legend(fontsize=9, ncol=3, loc="upper right", frameon=False)
        axe.spines[["top", "right"]].set_visible(False)
        fig.suptitle("★ true target   ✚ liars' false target   ✖ Byzantine robot   red dashed = link isolated by RACE-C",
                     fontsize=11, x=0.02, ha="left", y=0.975, color="#374151")
        canvas.draw()
        wr.add(Image.frombuffer("RGBA", canvas.get_width_height(), canvas.buffer_rgba()).convert("RGB"))
    plt.close(fig)
    wr.close()
    return OUT / "swarm_rendezvous.mp4"


# ============================================================================ PlanBench LLM-Modulo
COLMAP = {"red": (220, 38, 38), "blue": (37, 99, 235), "orange": (249, 115, 22), "yellow": (234, 179, 8),
          "green": (22, 163, 74), "purple": (147, 51, 234), "white": (229, 231, 235), "black": (31, 41, 55)}


def _stacks(state):
    towers = []
    for b, under in state.on.items():
        if under == "table":
            tower = [b]
            while True:
                above = [x for x, u in state.on.items() if u == tower[-1]]
                if not above:
                    break
                tower.append(above[0])
            towers.append(tower)
    return sorted(towers)


def _bw_frame(state, title, sub, goal, status=None, status_col=INK, plan=None, cur=-1, failed=None):
    im = Image.new("RGB", (W, H), BG)
    d = ImageDraw.Draw(im)
    d.text((40, 24), title, font=font(26, True), fill=INK)
    d.text((40, 62), sub, font=font(17), fill=(75, 85, 99))
    d.rectangle([40, 600, 760, 610], fill=(120, 113, 108))
    bs = 74
    for k, tower in enumerate(_stacks(state)):
        x = 70 + k * 120
        for h, b in enumerate(tower):
            y = 600 - (h + 1) * bs
            d.rounded_rectangle([x, y, x + bs - 4, y + bs - 4], radius=8, fill=COLMAP.get(b, GREY), outline=INK, width=2)
            d.text((x + 8, y + 26), b, font=font(15, True), fill=(255, 255, 255), stroke_width=2, stroke_fill=(0, 0, 0))
    if state.holding:
        b = state.holding
        d.rounded_rectangle([380, 130, 380 + bs - 4, 130 + bs - 4], radius=8, fill=COLMAP.get(b, GREY), outline=INK, width=2)
        d.text((388, 156), b, font=font(15, True), fill=(255, 255, 255), stroke_width=2, stroke_fill=(0, 0, 0))
        d.line([418, 100, 418, 130], fill=INK, width=4)
        d.text((470, 150), "hand", font=font(15), fill=(107, 114, 128))
    d.rectangle([800, 110, W - 30, H - 30], fill=(255, 255, 255), outline=(229, 231, 235), width=2)
    d.text((820, 124), "goal: " + ", ".join(f"{a} on {b}" for a, b in goal), font=font(15, True), fill=INK)
    if plan:
        for i, stp in enumerate(plan[:14]):
            col = RED if failed == i else (TEAL if i < cur or (i == cur and failed is None) else (107, 114, 128))
            mark = "▶ " if i == cur else "   "
            d.text((820, 165 + 28 * i), f"{mark}{i + 1}. {stp}", font=font(16, i == cur), fill=col)
    if status:
        d.rectangle([40, 650, 760, 700], fill=(255, 255, 255), outline=status_col, width=3)
        d.text((56, 663), status, font=font(17, True), fill=status_col)
    return im


def planbench_modulo():
    ins = {i["instance_id"]: i for i in bw.load()}
    best = None
    for f in sorted(Path("results/planbench").glob("*.jsonl")):
        for r in map(json.loads, open(f)):
            if (not r["oneshot"]) and r["modulo"] and r["attempts"][0]["error"] and len(r["attempts"]) == 2:
                if best is None or len(r["attempts"][0]["plan"]) > len(best[1]["attempts"][0]["plan"]):
                    best = (f.stem, r)
    agent, r = best
    q = ins[r["instance_id"]]["query"]
    s0, goal = bw.parse_statement(q)
    wr = Writer(OUT / "planbench_modulo.mp4")
    wr.add(card("PlanBench Blocksworld · LLM-Modulo", [
        f"Instance {r['instance_id']} of the official PlanBench plan-generation task (Valmeekam et al.).",
        f"Agent: {agent}. Every frame below replays its real cached answers.",
        "An exact simulator checks each action; its error message is the repair feedback."], accent=AMBER), FPS * 3)
    for a_i, att in enumerate(r["attempts"]):
        s = s0.copy()
        steps = bw.parse_plan("\n".join(f"({x})" for x in att["plan"]))   # cached as "act a b" -> PDDL
        label = "one-shot plan (official prompt)" if a_i == 0 else "repaired plan after validator feedback"
        wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", f"{len(steps)} actions", goal, plan=att["plan"], cur=-1), FPS)
        failed = None
        for i, (act, args) in enumerate(steps):
            err = bw.step(s, act, args)
            if err:
                failed = i
                wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", f"executing step {i + 1}", goal,
                                 status=f"✗ validator: step {i + 1}: {err}"[:78], status_col=RED, plan=att["plan"],
                                 cur=i, failed=i), FPS * 4)
                break
            wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", f"executing step {i + 1}", goal, plan=att["plan"], cur=i),
                   int(FPS * 0.7))
        if failed is None:
            reached = all(s.on.get(a) == b for a, b in goal)
            wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", "done", goal,
                             status="✓ goal reached — plan valid" if reached else "✗ executable but goal not reached",
                             status_col=TEAL if reached else RED, plan=att["plan"], cur=len(steps)), FPS * 3)
    wr.close()
    return OUT / "planbench_modulo.mp4"


# ============================================================================ Track D maze swarm
def _maze_xml(G, goal, n, byz, cell=0.2):
    H, W = G.shape
    walls = "".join(f'<geom type="box" size="{cell / 2} {cell / 2} 0.07" pos="{c * cell:.2f} {-(r * cell):.2f} 0.07" material="wall"/>'
                    for r in range(H) for c in range(W) if G[r, c])
    bots = ""
    for i in range(n):
        col = "0.86 0.15 0.15 1" if byz[i] else "0.06 0.46 0.43 1"
        bots += (f'<body name="bot{i}" mocap="true" pos="0 0 0.05"><geom type="cylinder" size="0.065 0.035" rgba="{col}"/>'
                 f'<geom type="sphere" size="0.03" pos="0 0 0.05" rgba="0.95 0.95 0.95 1"/>'
                 f'<geom type="cylinder" size="0.03 0.012" pos="0 0.07 -0.01" euler="1.5708 0 0" rgba="0.1 0.1 0.1 1"/>'
                 f'<geom type="cylinder" size="0.03 0.012" pos="0 -0.07 -0.01" euler="1.5708 0 0" rgba="0.1 0.1 0.1 1"/></body>')
    cx, cy = (W - 1) * cell / 2, -(H - 1) * cell / 2
    return f"""<mujoco><visual><global offwidth="1280" offheight="960"/><quality shadowsize="4096"/>
  <headlight ambient="0.5 0.5 0.5" diffuse="0.4 0.4 0.4" specular="0 0 0"/></visual>
  <asset><material name="wall" rgba="0.35 0.38 0.45 1"/>
    <texture name="fl" type="2d" builtin="checker" rgb1="0.93 0.92 0.9" rgb2="0.88 0.87 0.85" width="128" height="128"/>
    <material name="floor" texture="fl" texrepeat="{W} {H}"/>
    <texture type="skybox" builtin="gradient" rgb1="0.96 0.96 0.97" rgb2="0.8 0.83 0.88" width="64" height="128"/></asset>
  <worldbody><light pos="{cx} {cy - 2} 6" dir="0 0.25 -1" diffuse="0.6 0.6 0.6" castshadow="true"/>
    <geom type="plane" size="{W * cell} {H * cell} 0.01" pos="{cx} {cy} 0" material="floor"/>
    <geom type="cylinder" size="{cell * 0.42} 0.004" pos="{goal[1] * cell:.2f} {-(goal[0] * cell):.2f} 0.004" rgba="0.96 0.62 0.04 1"/>
    <body name="look" pos="{cx} {cy + 0.25} 0"/>
    <camera name="iso" mode="targetbody" target="look" pos="{cx} {cy - 4.1} 5.2"/>
    {walls}{bots}</worldbody></mujoco>"""


def _belief_panel(G, B, pos, byz, goal, recv, title, stats, size=300):
    H, W = G.shape
    k = size // H
    im = Image.new("RGB", (400, H * k + 54), BG)
    d = ImageDraw.Draw(im)
    col = {"free": (243, 244, 246), "wall": (75, 85, 99), "unknown": (209, 213, 219), "false_wall": (220, 38, 38),
           "missed_wall": (251, 191, 36)}
    for r in range(H):
        for c in range(W):
            b, g = (B[r, c] if B is not None else -1), G[r, c]
            key = "unknown" if b < 0 else ("wall" if g else "false_wall") if b == 1 else ("missed_wall" if g else "free")
            d.rectangle([c * k, 54 + r * k, c * k + k - 1, 54 + r * k + k - 1], fill=col[key])
    d.ellipse([goal[1] * k - 2, 54 + goal[0] * k - 2, goal[1] * k + k + 1, 54 + goal[0] * k + k + 1], outline=(217, 119, 6), width=3)
    for i, (r, c) in enumerate(pos):
        fill = (220, 38, 38) if byz[i] else (15, 118, 110)
        d.ellipse([c * k + 1, 54 + r * k + 1, c * k + k - 2, 54 + r * k + k - 2], fill=fill,
                  outline=(0, 0, 0) if i == recv else None, width=2)
    d.text((2, 2), title, font=font(16, True), fill=INK)
    d.text((2, 26), stats, font=font(13), fill=(75, 85, 99))
    return im


MAZE_TEXT = {"invert": ("invert their reports", "they report every wall as free and every free cell as a wall."),
             "false_walls": ("invent walls", "they report free cells as walls 60% of the time (their wall reports are worthless, their 'free' reports are true).")}
MAZE_NAMES = {"majority": "Majority map fusion", "reputation": "Beta-reputation (discards liars)", "race_map": "RACE map (hand-written)",
              "race_net_m": "RACE-Net-M (ours, learned)", "race_net_m + reach-repair": "RACE-Net-M (ours, learned)"}


def maze_swarm(attack="invert", F=3, base="majority", ours=None, name="maze_swarm"):
    import mujoco
    from robotics.bench import trackD
    rows = json.loads(Path("results/trackD/rows.json").read_text())
    if ours is None:
        ours = "race_net_m + reach-repair" if any(r["method"] == "race_net_m + reach-repair" for r in rows) else "race_map"
    gap = {}
    for r in rows:
        if r["attack"] == attack and r["liars"] == F and r["method"] in (ours, base):
            gap.setdefault(r["subset"], {})[r["method"]] = r["acc"]
    seed = max(gap, key=lambda k: gap[k][ours] - gap[k][base])
    runs = {}
    for m in (base, ours):
        tr = []
        res = trackD.episode(seed, attack, F, m, trace=tr)
        runs[m] = (tr, res)
    G, goal, byz = runs[ours][1]["G"], runs[ours][1]["goal"], runs[ours][1]["byz"]
    n = len(byz)
    recv = int(np.flatnonzero(~byz)[0])
    model = mujoco.MjModel.from_xml_string(_maze_xml(G, goal, n, byz))
    data = mujoco.MjData(model)
    ren = mujoco.Renderer(model, 640, 760)
    mids = [model.body_mocapid[model.body(f"bot{i}").id] for i in range(n)]
    Tm = max(len(runs[m][0]) for m in runs)
    wr = Writer(OUT / f"{name}.mp4")
    wr.add(card("RoboRACE · Track D · maze swarm", [
        f"6 mobile robots explore an unknown maze and share what they sense. {F} of them lie:",
        MAZE_TEXT[attack][1],
        f"{MAZE_NAMES[base]} vs {MAZE_NAMES[ours]}: each robot checks its peers against the cells",
        "it sensed itself, then INVERTS consistent liars and ignores worthless reports."], accent=(124, 58, 237)), FPS * 4)
    last_B = {m: None for m in runs}
    sub = 5
    for t in range(Tm + 6):
        frames = {}
        for m, (tr, res) in runs.items():
            st = tr[min(t, len(tr) - 1)]
            prev = tr[min(max(t - 1, 0), len(tr) - 1)]
            if recv in st["beliefs"]:
                last_B[m] = st["beliefs"][recv]
            frames[m] = (st, prev)
        for k in range(sub):
            a = (k + 1) / sub
            st, prev = frames[ours]
            for i in range(n):
                r = prev["pos"][i][0] + (st["pos"][i][0] - prev["pos"][i][0]) * a
                c = prev["pos"][i][1] + (st["pos"][i][1] - prev["pos"][i][1]) * a
                data.mocap_pos[mids[i]] = [c * 0.2, -r * 0.2, 0.05]
            mujoco.mj_forward(model, data)
            ren.update_scene(data, camera="iso")
            im = Image.new("RGB", (W, H), BG)
            d = ImageDraw.Draw(im)
            d.text((16, 8), f"Track D · cooperative maze exploration · {F} of {n} robots {MAZE_TEXT[attack][0]}", font=font(19, True), fill=INK)
            im.paste(Image.fromarray(ren.render()).resize((606, 720 - 44 - 8)), (8, 44))
            d.text((20, 52), "RACE-Net-M run (3-D view): teal = honest, red = liar, gold = goal" if "net" in ours
                   else "RACE map run (3-D view): teal = honest, red = liar, gold = goal", font=font(13, True), fill=INK)
            for row, m in enumerate((base, ours)):
                tr, res = runs[m]
                st = frames[m][0]
                honest_done = int(st["done"][~byz].sum())
                B = last_B[m]
                wrong = int(((B == 1) & (G == 0)).sum()) if B is not None else 0
                finished = t >= len(tr) - 1
                stats = (f"step {min(t + 1, len(tr))} · at goal {honest_done}/{int((~byz).sum())} · false walls {wrong}"
                         + (f" · SPL {res['spl']:.2f}" if finished else ""))
                title = MAZE_NAMES[m]
                panel = _belief_panel(G, B, st["pos"], byz, goal, recv, title, stats, size=280)
                im.paste(panel, (628, 44 + row * 338))
            d.rectangle([1040, 60, 1270, 300], fill=(255, 255, 255), outline=(229, 231, 235), width=2)
            d.text((1052, 252), "maps = belief of the\nrobot circled in black", font=font(13), fill=(75, 85, 99), spacing=4)
            for j, (cc, lab) in enumerate((((75, 85, 99), "wall (correct)"), ((243, 244, 246), "free (correct)"), ((209, 213, 219), "unknown"),
                                           ((220, 38, 38), "FALSE wall (lie believed)"), ((251, 191, 36), "missed wall"))):
                d.rectangle([1052, 74 + 34 * j, 1070, 92 + 34 * j], fill=cc, outline=(156, 163, 175))
                d.text((1080, 74 + 34 * j), lab, font=font(13), fill=INK)
            wr.add(im)
    ren.close()
    wr.add(im, FPS * 3)
    wr.close()
    return OUT / f"{name}.mp4"


def maze_false_walls():
    return maze_swarm("false_walls", 3, base="reputation", name="maze_false_walls")


if __name__ == "__main__":
    which = sys.argv[1:] or ["swarm_rendezvous", "planbench_modulo", "robot_rollouts", "maze_swarm", "maze_false_walls", "panda_rollouts"]
    for name in which:
        p = globals()[name]()
        print(p, f"{p.stat().st_size / 1e6:.1f} MB  (README GIFs: python scripts/make_gifs.py)", flush=True)