#!/usr/bin/env python3 """Cable clusters in the ACT encoder representation, ordered by cable diameter. Figure only -- titles and annotations are kept minimal so the plot can sit in a slide or paper with its own caption. Numbers needed for that caption (held-out R^2, per-class predicted diameter) are printed to stdout instead of drawn. left : unsupervised PCA of the 512-d encoder feature, on the two components that actually carry cable identity (PC1/PC2 are dominated by arm pose) right : ridge regression from the same features onto physical diameter, fitted on training episodes -- if thickness is encoded as a quantity, 2.6 mm lands between 1.7 and 4.5 without the ordering ever being supplied Episode-level split throughout: frames inside one episode are near-duplicates, so a frame-level split would leak the answer. """ 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 RidgeCV from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline 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 sep_ratio(Z, y, k): g = [Z[y == t, k] for t in sorted(set(y))] return np.var([x.mean() for x in g]) / (np.mean([x.var() for x in g]) + 1e-12) def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", default="outputs/pca/cache_cable_feats.npz") ap.add_argument("--out", default="outputs/pca/cable_diameter_clusters.png") args = ap.parse_args() d = np.load(args.cache, allow_pickle=True) X, y, ep = d["feats"], d["y"], d["eps"] dia = np.array([DIA[t] for t in y]) rng = np.random.default_rng(0) tr = np.zeros(len(y), bool) for t in np.unique(y): e = np.unique(ep[y == t]) tr |= np.isin(ep, rng.choice(e, size=int(len(e) * 0.7), replace=False)) te = ~tr plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 12}) fig, axes = plt.subplots(1, 2, figsize=(13, 5.6)) Xc = X - X.mean(0) p = PCA(n_components=30).fit(Xc) Z = p.transform(Xc) ratios = np.array([sep_ratio(Z, y, k) for k in range(30)]) i, j = np.argsort(ratios)[::-1][:2] for t in sorted(set(y), key=lambda s: DIA[s]): m = te & (y == t) axes[0].scatter(Z[m, i], Z[m, j], s=16, alpha=0.6, edgecolors="none", c=COLOR[DIA[t]], label=NAME[DIA[t]]) axes[0].set_xlabel(f"PC{i+1}") axes[0].set_ylabel(f"PC{j+1}") axes[0].legend(frameon=False) reg = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 4, 25))).fit(X[tr], dia[tr]) pred = reg.predict(X) for t in sorted(set(y), key=lambda s: DIA[s]): m = te & (y == t) axes[1].scatter(pred[m], Z[m, j], s=16, alpha=0.6, edgecolors="none", c=COLOR[DIA[t]], label=NAME[DIA[t]]) for v in (1.7, 2.6, 4.5): axes[1].axvline(v, color=COLOR[v], lw=1.1, ls="--", alpha=0.7) axes[1].set_xlabel("predicted cable diameter [mm]") axes[1].set_ylabel(f"PC{j+1}") axes[1].set_xticks([1.7, 2.6, 4.5]) axes[1].legend(frameon=False) for ax in axes: ax.spines[["top", "right"]].set_visible(False) fig.tight_layout() fig.savefig(args.out, dpi=160, bbox_inches="tight") # Caption material, printed rather than drawn. print(f"wrote {args.out}\n") print(f" left panel : PC{i+1} vs PC{j+1} " f"({p.explained_variance_ratio_[i]:.1%} and {p.explained_variance_ratio_[j]:.1%} of variance)") print(f" right panel : held-out R^2 = {reg.score(X[te], dia[te]):.2f}") for t in sorted(set(y), key=lambda s: DIA[s]): m = te & (y == t) print(f" true {DIA[t]:>4} mm -> predicted {pred[m].mean():.2f} +- {pred[m].std():.2f} mm (n={m.sum()})") print(f" frames: {te.sum()} held-out of {len(y)}; episode-level split") if __name__ == "__main__": main()