#!/usr/bin/env python3 """When during an episode does the representation know which cable it is? Splits each episode by elapsed time and asks, separately per window, how well a probe recovers cable identity from the encoder features. The question this answers: during the first seconds the gripper is still reaching and has not touched the cable, so anything decodable there is visual. If accuracy is already high while reaching, touch is not what carries the distinction. Held-out episodes throughout; probes are fit per window on training episodes. """ import argparse import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler DIA = {"cable 1.70 sq": 1.7, "blue cable": 2.6, "cable 3.30 sq": 4.5} NAME = {1.7: "1.7 mm", 2.6: "2.6 mm", 4.5: "4.5 mm"} COLOR = {1.7: "#C05621", 2.6: "#2B6CB0", 4.5: "#2F855A"} def probe(X, y, tr, te): if tr.sum() < 30 or te.sum() < 15 or len(set(y[tr])) < 2: return np.nan c = make_pipeline(StandardScaler(), LogisticRegression(max_iter=3000)) c.fit(X[tr], y[tr]) return c.score(X[te], y[te]) def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", default="outputs/pca/cache_cable_phase.npz") ap.add_argument("--reach-sec", type=float, default=5.0, help="frames before this are treated as the reaching phase") ap.add_argument("--out", default="outputs/pca/cable_phase_analysis.png") args = ap.parse_args() d = np.load(args.cache, allow_pickle=True) X, y, ep, tsec, tpos = d["feats"], d["y"], d["eps"], d["tsec"], d["tpos"] rng = np.random.default_rng(0) tr_ep = np.zeros(len(y), bool) for t in np.unique(y): e = np.unique(ep[y == t]) tr_ep |= np.isin(ep, rng.choice(e, size=int(len(e) * 0.7), replace=False)) te_ep = ~tr_ep plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 11}) fig, axes = plt.subplots(1, 3, figsize=(17, 5.2)) # --- 1) accuracy vs elapsed time, in sliding windows edges = np.arange(0, 31, 2.5) mids, accs, ns = [], [], [] for a, b in zip(edges[:-1], edges[1:]): w = (tsec >= a) & (tsec < b) accs.append(probe(X, y, tr_ep & w, te_ep & w)) mids.append((a + b) / 2); ns.append((te_ep & w).sum()) axes[0].plot(mids, accs, "o-", color="#2B6CB0", lw=2, ms=6) axes[0].axhline(1 / 3, color="#888", ls="--", lw=1) axes[0].axvspan(0, args.reach_sec, color="#C05621", alpha=0.10) axes[0].annotate("reaching\n(no contact)", (args.reach_sec / 2, 0.36), ha="center", fontsize=9.5, color="#C05621") axes[0].set_xlabel("time since episode start [s]") axes[0].set_ylabel("held-out accuracy") axes[0].set_ylim(0.2, 1.02) axes[0].set_title("Cable identity over the episode", fontsize=12) # --- 2) reaching vs sorting, probe trained and tested within each phase reach = tsec < args.reach_sec sort = ~reach bars, labels = [], [] for name, w in (("reaching\n(<%.0fs)" % args.reach_sec, reach), ("sorting\n(>=%.0fs)" % args.reach_sec, sort)): bars.append(probe(X, y, tr_ep & w, te_ep & w)); labels.append(name) # cross-phase: train while reaching, test while sorting and vice versa bars.append(probe(X, y, tr_ep & reach, te_ep & sort)); labels.append("train reach\ntest sort") bars.append(probe(X, y, tr_ep & sort, te_ep & reach)); labels.append("train sort\ntest reach") axes[1].bar(labels, bars, color=["#C05621", "#2F855A", "#888", "#888"]) axes[1].axhline(1 / 3, color="#888", ls="--", lw=1) for i, v in enumerate(bars): axes[1].annotate(f"{v:.1%}", (i, v), ha="center", va="bottom", fontsize=10) axes[1].set_ylim(0, 1.08); axes[1].set_ylabel("held-out accuracy") axes[1].set_title("Reaching vs sorting", fontsize=12) # --- 3) PCA coloured by phase, to see what actually dominates the variance Xc = X - X.mean(0) p = PCA(n_components=4).fit(Xc) Z = p.transform(Xc) sc = axes[2].scatter(Z[te_ep, 0], Z[te_ep, 1], c=tsec[te_ep], s=12, alpha=0.7, cmap="viridis", edgecolors="none") plt.colorbar(sc, ax=axes[2], label="time since start [s]") axes[2].set_xlabel(f"PC1 ({p.explained_variance_ratio_[0]:.1%})") axes[2].set_ylabel(f"PC2 ({p.explained_variance_ratio_[1]:.1%})") axes[2].set_title("PC1/PC2 coloured by phase,\nnot by cable", fontsize=12) for ax in axes: ax.spines[["top", "right"]].set_visible(False) fig.tight_layout(); fig.savefig(args.out, dpi=150, bbox_inches="tight") print(f"wrote {args.out}\n") print(" accuracy by time window (held-out episodes):") for m, a, n in zip(mids, accs, ns): print(f" {m:5.1f}s {a:6.1%} (n={n})") print() for l, v in zip(labels, bars): print(f" {l.replace(chr(10), ' '):24s} {v:6.1%}") if __name__ == "__main__": main()