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 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Primitive classification probe visualization."""

from __future__ import annotations

import json
from pathlib import Path

import joblib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
from PIL import Image, ImageDraw, ImageFont
from scipy.ndimage import uniform_filter1d
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.metrics import confusion_matrix, f1_score
from sklearn.preprocessing import StandardScaler

from probe_common import (
    CLASS_NAMES,
    CLASS_TO_ID,
    ID_TO_CLASS,
    concept_timesteps_to_video_frames,
    demo_to_robot,
    ensure_dir,
    ffprobe_video,
    load_concept,
    natural_key,
    read_video_frame,
)

CLASS_COLORS = {
    "reach": "#2ca02c",
    "grasp": "#1f77b4",
    "transition": "#ff7f0e",
    "release": "#d62728",
    "retract": "#9467bd",
}
CLASS_SHORT = {"reach": "R", "grasp": "G", "transition": "T", "release": "L", "retract": "W"}
ROBOT_MARKERS = {"arx": "o", "franka": "+", "ur5": "^"}
VISUAL_SMOOTHING = 5


def align_proba_to_global_classes(model, proba: np.ndarray) -> np.ndarray:
    """Map predict_proba columns to fixed [reach, grasp, transition, release, retract] order."""
    n = proba.shape[0]
    out = np.zeros((n, len(CLASS_NAMES)), dtype=np.float32)
    classes = getattr(model, "classes_", None)
    if classes is None:
        clf = model.named_steps.get("clf") if hasattr(model, "named_steps") else model
        classes = getattr(clf, "classes_", np.arange(proba.shape[1]))
    for col_idx, cls_id in enumerate(classes):
        if int(cls_id) in CLASS_TO_ID.values():
            out[:, int(cls_id)] = proba[:, col_idx]
    return out


def select_representative_pair(
    cross_results: list[dict],
    demos: list[str],
    label_kind: str | None = None,
) -> tuple[str, str, int]:
    """Pick off-diagonal train/eval pair with aggregate macro_f1 closest to median."""
    if label_kind is not None:
        cross_results = [r for r in cross_results if r.get("label_kind") == label_kind]
    off_diag = [
        r
        for r in cross_results
        if r["train_demo"] != r["eval_demo"]
        and int(r.get("eval_validation_index", 0)) == 0
        and r.get("split") == "target"
    ]
    if not off_diag:
        return demos[0], demos[1], 0
    agg = {(r["train_demo"], r["eval_demo"]): r["macro_f1"] for r in off_diag}
    keys = sorted(agg.keys(), key=lambda k: (str(k[0]), str(k[1])))
    vals = [agg[k] for k in keys]
    median = float(np.median(vals))
    best_key = min(keys, key=lambda k: abs(agg[k] - median))
    return best_key[0], best_key[1], 0


def select_representative_episode(
    per_episode_rows: list[dict],
    train_demo: str,
    eval_demo: str,
    label_kind: str | None = None,
) -> int | None:
    """Pick episode with all classes whose macro_f1 is closest to pair median."""
    if label_kind is not None:
        per_episode_rows = [r for r in per_episode_rows if r.get("label_kind") == label_kind]
    rows = [
        r
        for r in per_episode_rows
        if r["train_demo"] == train_demo
        and r["eval_demo"] == eval_demo
        and r.get("has_all_classes")
    ]
    if not rows:
        rows = [
            r
            for r in per_episode_rows
            if r["train_demo"] == train_demo and r["eval_demo"] == eval_demo
        ]
    if not rows:
        return None
    f1s = [r["macro_f1"] for r in rows]
    median = float(np.median(f1s))
    best = min(rows, key=lambda r: abs(r["macro_f1"] - median))
    return int(best["episode_id"])


def draw_gt_strip(y: np.ndarray, width: int, height: int = 24) -> Image.Image:
    img = Image.new("RGB", (width, height), (240, 240, 240))
    draw = ImageDraw.Draw(img)
    T = len(y)
    if T == 0:
        return img
    for t in range(T):
        cls_id = int(y[t])
        if cls_id < 0:
            color = (200, 200, 200)
        else:
            color = CLASS_COLORS[CLASS_NAMES[cls_id]]
        x0 = int(t / T * width)
        x1 = int((t + 1) / T * width)
        draw.rectangle((x0, 0, max(x0 + 1, x1), height), fill=color)
    return img


def render_temporal_panel(
    gt: np.ndarray,
    proba: np.ndarray,
    title: str,
    width: int = 900,
    curve_height: int = 200,
    strip_height: int = 28,
) -> Image.Image:
    proba_smooth = uniform_filter1d(proba, size=VISUAL_SMOOTHING, axis=0, mode="nearest")
    total_h = strip_height + 20 + curve_height + 40
    img = Image.new("RGB", (width, total_h), "white")
    draw = ImageDraw.Draw(img)
    draw.text((8, 4), title, fill=(0, 0, 0))
    strip = draw_gt_strip(gt, width - 16, strip_height)
    img.paste(strip, (8, 22))

    pad_l, pad_t = 48, strip_height + 36
    plot_w = width - pad_l - 16
    plot_h = curve_height
    draw.rectangle((pad_l, pad_t, pad_l + plot_w, pad_t + plot_h), outline=(120, 120, 120))
    T = len(gt)
    for ci, name in enumerate(CLASS_NAMES):
        color = CLASS_COLORS[name]
        pts = []
        for t in range(T):
            x = pad_l + int(t / max(1, T - 1) * plot_w)
            val = float(proba_smooth[t, ci])
            y = pad_t + plot_h - int(val * plot_h)
            pts.append((x, y))
        if len(pts) >= 2:
            draw.line(pts, fill=color, width=2)
        draw.text((pad_l + 8 + ci * 100, pad_t - 14), name, fill=color)

    return img


def plot_temporal_source_target(
    source_gt: np.ndarray,
    source_proba: np.ndarray,
    target_gt: np.ndarray,
    target_proba: np.ndarray,
    source_title: str,
    target_title: str,
    output_path: Path,
) -> None:
    src = render_temporal_panel(source_gt, source_proba, source_title)
    tgt = render_temporal_panel(target_gt, target_proba, target_title)
    canvas = Image.new("RGB", (max(src.width, tgt.width), src.height + tgt.height + 8), "white")
    canvas.paste(src, (0, 0))
    canvas.paste(tgt, (0, src.height + 8))
    ensure_dir(output_path.parent)
    canvas.save(output_path.with_suffix(".png"))
    meta = {
        "visual_smoothing": VISUAL_SMOOTHING,
        "metrics_use_smoothed_prediction": False,
        "source_title": source_title,
        "target_title": target_title,
    }
    output_path.with_suffix(".json").write_text(json.dumps(meta, indent=2), encoding="utf-8")


def plot_confusion_matrix(
    y_true: np.ndarray,
    y_pred: np.ndarray,
    output_path: Path,
    title: str = "Confusion Matrix",
) -> None:
    labels = list(range(len(CLASS_NAMES)))
    cm = confusion_matrix(y_true, y_pred, labels=labels)
    fig, ax = plt.subplots(figsize=(6, 5))
    im = ax.imshow(cm, interpolation="nearest", cmap="Blues")
    ax.figure.colorbar(im, ax=ax)
    ax.set(
        xticks=np.arange(len(CLASS_NAMES)),
        yticks=np.arange(len(CLASS_NAMES)),
        xticklabels=CLASS_NAMES,
        yticklabels=CLASS_NAMES,
        title=title,
        ylabel="True",
        xlabel="Predicted",
    )
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
    thresh = cm.max() / 2.0 if cm.max() else 0
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], "d"), ha="center", va="center", color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    ensure_dir(output_path.parent)
    fig.savefig(output_path.with_suffix(".pdf"))
    fig.savefig(output_path.with_suffix(".png"))
    plt.close(fig)


def balanced_sample_indices(
    X: np.ndarray,
    y: np.ndarray,
    robots: np.ndarray,
    max_per_group: int = 400,
    seed: int = 42,
) -> np.ndarray:
    rng = np.random.default_rng(seed)
    selected = []
    for robot in sorted(set(robots), key=str):
        for cls_id in range(len(CLASS_NAMES)):
            mask = (robots == robot) & (y == cls_id)
            idxs = np.where(mask)[0]
            if len(idxs) == 0:
                continue
            if len(idxs) > max_per_group:
                idxs = rng.choice(idxs, size=max_per_group, replace=False)
            selected.extend(idxs.tolist())
    return np.array(sorted(set(selected)), dtype=np.int64)


def plot_tsne(
    episodes: list,
    label_kind: str,
    output_path: Path,
    max_per_group: int = 400,
    seed: int = 42,
) -> None:
    xs, ys, robots = [], [], []
    for ep in episodes:
        mask = ep.valid_mask
        if not np.any(mask):
            continue
        xs.append(ep.X[mask])
        ys.append(ep.y[mask])
        robots.append(np.full(int(mask.sum()), ep.robot))
    if not xs:
        print(f"skip tsne {label_kind}: no data")
        return
    X = np.concatenate(xs, axis=0)
    y = np.concatenate(ys, axis=0)
    robot_arr = np.concatenate(robots, axis=0)
    idx = balanced_sample_indices(X, y, robot_arr, max_per_group=max_per_group, seed=seed)
    Xs, ys, rs = X[idx], y[idx], robot_arr[idx]

    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(Xs)
    n_comp = min(50, X_scaled.shape[1], X_scaled.shape[0] - 1)
    if n_comp < 2:
        print(f"skip tsne {label_kind}: too few samples")
        return
    X_pca = PCA(n_components=n_comp, random_state=seed).fit_transform(X_scaled)
    perplexity = min(30, max(5, len(X_pca) // 4))
    tsne = TSNE(
        n_components=2,
        perplexity=perplexity,
        init="pca",
        learning_rate="auto",
        random_state=seed,
    )
    emb = tsne.fit_transform(X_pca)

    fig, ax = plt.subplots(figsize=(8, 7))
    for cls_id, name in enumerate(CLASS_NAMES):
        for robot, marker in ROBOT_MARKERS.items():
            m = (ys == cls_id) & (rs == robot)
            if not np.any(m):
                continue
            ax.scatter(
                emb[m, 0],
                emb[m, 1],
                c=CLASS_COLORS[name],
                marker=marker,
                s=18,
                alpha=0.55,
                edgecolors="none",
            )
    class_handles = [Patch(facecolor=CLASS_COLORS[n], label=n) for n in CLASS_NAMES]
    robot_handles = [
        Line2D([0], [0], marker=ROBOT_MARKERS[r], color="gray", linestyle="None", markersize=8, label=r)
        for r in ROBOT_MARKERS
    ]
    ax.legend(handles=class_handles + robot_handles, loc="best", fontsize=8)
    ax.set_title(f"Primitive Concept Space — {label_kind}")
    ax.set_xlabel("t-SNE 1")
    ax.set_ylabel("t-SNE 2")
    fig.tight_layout()
    ensure_dir(output_path.parent)
    fig.savefig(output_path.with_suffix(".pdf"))
    fig.savefig(output_path.with_suffix(".png"))
    plt.close(fig)


def episode_macro_f1(gt: np.ndarray, pred: np.ndarray, valid_mask: np.ndarray) -> float:
    labels = list(range(len(CLASS_NAMES)))
    y_true = gt[valid_mask]
    y_pred = pred[valid_mask]
    if len(y_true) == 0:
        return 0.0
    return float(f1_score(y_true, y_pred, average="macro", labels=labels, zero_division=0))


def episode_has_all_classes(gt: np.ndarray, valid_mask: np.ndarray) -> bool:
    present = set(int(v) for v in gt[valid_mask])
    return all(c in present for c in range(len(CLASS_NAMES)))


def collect_within_cv_episode_rows(folds: list[dict], pred_dir: Path) -> list[dict]:
    """Aggregate per-episode CV metrics from saved fold predictions."""
    rows: list[dict] = []
    for fold_info in folds:
        fold = int(fold_info["fold"])
        for eid in fold_info["test_episode_ids"]:
            npz_path = pred_dir / f"episode_{int(eid):05d}_fold{fold}.npz"
            if not npz_path.exists():
                continue
            data = np.load(npz_path)
            gt = data["gt"]
            pred = data["pred"]
            valid_mask = data["valid_mask"]
            rows.append(
                {
                    "episode_id": int(eid),
                    "fold": fold,
                    "macro_f1": episode_macro_f1(gt, pred, valid_mask),
                    "has_all_classes": episode_has_all_classes(gt, valid_mask),
                    "npz_path": str(npz_path),
                }
            )
    return rows


def select_representative_within_episode(episode_rows: list[dict]) -> dict | None:
    """Pick CV test episode with all classes and macro_f1 closest to median."""
    candidates = [r for r in episode_rows if r.get("has_all_classes")]
    if not candidates:
        candidates = list(episode_rows)
    if not candidates:
        return None
    f1s = [r["macro_f1"] for r in candidates]
    median = float(np.median(f1s))
    return min(candidates, key=lambda r: abs(r["macro_f1"] - median))


def load_within_episode_prediction(npz_path: Path) -> tuple[np.ndarray, np.ndarray]:
    data = np.load(npz_path)
    return data["gt"], data["proba"]


def plot_tsne_per_robot(
    episodes_by_robot: dict[str, list],
    label_kind: str,
    output_path: Path,
    max_per_group: int = 400,
    seed: int = 42,
) -> None:
    """Within-only t-SNE: one subplot per robot (no cross-robot mixing in each panel)."""
    robots = sorted(episodes_by_robot.keys(), key=str)
    if not robots:
        print(f"skip tsne within {label_kind}: no robots")
        return

    fig, axes = plt.subplots(1, len(robots), figsize=(5 * len(robots), 5), squeeze=False)
    for col, robot in enumerate(robots):
        ax = axes[0, col]
        episodes = episodes_by_robot[robot]
        xs, ys = [], []
        for ep in episodes:
            mask = ep.valid_mask
            if not np.any(mask):
                continue
            xs.append(ep.X[mask])
            ys.append(ep.y[mask])
        if not xs:
            ax.set_title(f"{robot} (no data)")
            continue

        X = np.concatenate(xs, axis=0)
        y = np.concatenate(ys, axis=0)
        robot_arr = np.full(len(y), robot)
        idx = balanced_sample_indices(X, y, robot_arr, max_per_group=max_per_group, seed=seed)
        Xs, ys = X[idx], y[idx]

        scaler = StandardScaler()
        X_scaled = scaler.fit_transform(Xs)
        n_comp = min(50, X_scaled.shape[1], X_scaled.shape[0] - 1)
        if n_comp < 2:
            ax.set_title(f"{robot} (too few samples)")
            continue
        X_pca = PCA(n_components=n_comp, random_state=seed).fit_transform(X_scaled)
        perplexity = min(30, max(5, len(X_pca) // 4))
        emb = TSNE(
            n_components=2,
            perplexity=perplexity,
            init="pca",
            learning_rate="auto",
            random_state=seed,
        ).fit_transform(X_pca)

        for cls_id, name in enumerate(CLASS_NAMES):
            m = ys == cls_id
            if not np.any(m):
                continue
            ax.scatter(
                emb[m, 0],
                emb[m, 1],
                c=CLASS_COLORS[name],
                s=18,
                alpha=0.6,
                edgecolors="none",
                label=name,
            )
        ax.set_title(robot)
        ax.set_xlabel("t-SNE 1")
        ax.set_ylabel("t-SNE 2")

    handles = [Patch(facecolor=CLASS_COLORS[n], label=n) for n in CLASS_NAMES]
    fig.legend(handles=handles, loc="upper center", ncol=len(CLASS_NAMES), fontsize=8, bbox_to_anchor=(0.5, 1.02))
    fig.suptitle(f"Within-robot Concept Space — {label_kind}", y=1.08)
    fig.tight_layout()
    ensure_dir(output_path.parent)
    fig.savefig(output_path.with_suffix(".pdf"), bbox_inches="tight")
    fig.savefig(output_path.with_suffix(".png"), bbox_inches="tight", dpi=150)
    plt.close(fig)


def plot_temporal_stack(
    panels: list[tuple[np.ndarray, np.ndarray, str]],
    output_path: Path,
) -> None:
    """Stack multiple temporal panels vertically."""
    if not panels:
        return
    rendered = [render_temporal_panel(gt, proba, title) for gt, proba, title in panels]
    width = max(img.width for img in rendered)
    height = sum(img.height for img in rendered) + 8 * (len(rendered) - 1)
    canvas = Image.new("RGB", (width, height), "white")
    y = 0
    for img in rendered:
        canvas.paste(img, (0, y))
        y += img.height + 8
    ensure_dir(output_path.parent)
    canvas.save(output_path.with_suffix(".png"))
    meta = {
        "visual_smoothing": VISUAL_SMOOTHING,
        "metrics_use_smoothed_prediction": False,
        "panels": [title for _, _, title in panels],
    }
    output_path.with_suffix(".json").write_text(json.dumps(meta, indent=2), encoding="utf-8")


def build_paper_figure(
    tsne_path: Path,
    temporal_path: Path,
    output_path: Path,
    label_kind: str,
    title: str | None = None,
) -> None:
    parts = []
    if tsne_path.with_suffix(".png").exists():
        parts.append(Image.open(tsne_path.with_suffix(".png")).convert("RGB"))
    if temporal_path.with_suffix(".png").exists():
        parts.append(Image.open(temporal_path.with_suffix(".png")).convert("RGB"))
    if not parts:
        return
    w = max(p.width for p in parts)
    h = sum(p.height for p in parts) + 16 * (len(parts) - 1)
    canvas = Image.new("RGB", (w, h), "white")
    y = 0
    for p in parts:
        canvas.paste(p, ((w - p.width) // 2, y))
        y += p.height + 16
    draw = ImageDraw.Draw(canvas)
    header = title or f"blocks_ranking_rgb / {label_kind}"
    draw.text((8, 8), header, fill=(0, 0, 0))
    ensure_dir(output_path.parent)
    canvas.save(output_path.with_suffix(".png"))
    canvas.save(output_path.with_suffix(".pdf"))


def model_from_checkpoint(path: Path):
    obj = joblib.load(path)
    if isinstance(obj, dict) and "model" in obj:
        return obj["model"], obj
    return obj, {"model_path": str(path)}


def predict_episode_proba(model, X: np.ndarray, valid_mask: np.ndarray) -> np.ndarray:
    proba = np.zeros((X.shape[0], len(CLASS_NAMES)), dtype=np.float32)
    if np.any(valid_mask):
        raw = model.predict_proba(X[valid_mask])
        aligned = align_proba_to_global_classes(model, raw)
        proba[valid_mask] = aligned
    return proba