#!/usr/bin/env python3 """t-SNE of four cable sizes, testing whether 3.00 sq lands between blue and 3.30. The claim under test is an ordering one, so it is checked numerically rather than by eye: a diameter/size axis is regressed on held-out episodes and the class means along it are compared. t-SNE distances are not metric, so the map alone cannot support a "lies between" statement -- the axis can. Confound worth stating: 3.00 sq comes from a different dataset than the other three. Anything session-specific (lighting, gel state, day) travels with that label. The ordering test is the guard: a session artefact has no reason to place 3.00 sq *between* two other sizes rather than off to one side. """ 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.manifold import TSNE from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler # Conductor cross-section [sq mm]; used only to order the classes. SQ = {"1.70 sq": 1.70, "blue (2.6 mm)": 2.30, "3.00 sq": 3.00, "3.30 sq": 3.30} COLOR = {"1.70 sq": "#C05621", "blue (2.6 mm)": "#2B6CB0", "3.00 sq": "#805AD5", "3.30 sq": "#2F855A"} def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", default="outputs/pca/cache/cache_4sizes.npz") ap.add_argument("--outdir", default="outputs/pca/4sizes") ap.add_argument("--perplexity", type=float, default=30.0) ap.add_argument("--blue-sq", type=float, default=2.30, help="cross-section assigned to the blue cable for the ordering test") args = ap.parse_args() SQ["blue (2.6 mm)"] = args.blue_sq import os os.makedirs(args.outdir, exist_ok=True) d = np.load(args.cache, allow_pickle=True) X, lab, ep = d["feats"], d["label"], d["eps"] order = sorted(set(lab), key=lambda s: SQ[s]) rng = np.random.default_rng(0) tr = np.zeros(len(lab), bool) for t in np.unique(lab): e = np.unique(ep[lab == t]) tr |= np.isin(ep, rng.choice(e, size=int(len(e) * 0.7), replace=False)) te = ~tr Xc = X - X.mean(0) Z = PCA(n_components=30).fit_transform(Xc) emb = TSNE(n_components=2, perplexity=args.perplexity, init="pca", random_state=0).fit_transform(Z) plt.rcParams.update({"font.family": ["DejaVu Sans"], "font.size": 12}) # --- t-SNE on its own fig, ax = plt.subplots(figsize=(7.6, 6.8)) for t in order: m = te & (lab == t) ax.scatter(emb[m, 0], emb[m, 1], s=16, alpha=0.65, edgecolors="none", c=COLOR[t], label=t) ax.set_xlabel("t-SNE 1"); ax.set_ylabel("t-SNE 2") ax.set_title(f"t-SNE of four cable sizes (perplexity {args.perplexity:g})", fontsize=13) ax.legend(frameon=False, title="cable") ax.spines[["top", "right"]].set_visible(False) fig.tight_layout(); fig.savefig(f"{args.outdir}/tsne_4sizes.png", dpi=160, bbox_inches="tight") # --- ordering test on a regressed size axis sq = np.array([SQ[t] for t in lab]) reg = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-2, 4, 25))).fit(X[tr], sq[tr]) pred = reg.predict(X) r2 = reg.score(X[te], sq[te]) fig, ax = plt.subplots(figsize=(8.4, 6.0)) for t in order: m = te & (lab == t) ax.scatter(pred[m], Z[m, 1], s=16, alpha=0.6, edgecolors="none", c=COLOR[t], label=t) ax.axvline(pred[m].mean(), color=COLOR[t], lw=1.3, ls="--", alpha=0.85) ax.set_xlabel("predicted conductor cross-section [sq mm]") ax.set_ylabel("PC2") ax.set_title(f"Size axis — held-out $R^2$ = {r2:.2f}", fontsize=13) ax.legend(frameon=False, title="cable") ax.spines[["top", "right"]].set_visible(False) fig.tight_layout(); fig.savefig(f"{args.outdir}/size_axis_4sizes.png", dpi=160, bbox_inches="tight") # --- centroid distances in the raw feature space: is 3.00 between blue and 3.30? cent = {t: X[te & (lab == t)].mean(0) for t in order} def dist(a, b): return float(np.linalg.norm(cent[a] - cent[b])) print(f"wrote {args.outdir}/tsne_4sizes.png") print(f"wrote {args.outdir}/size_axis_4sizes.png\n") print(f" size axis held-out R^2 = {r2:.2f}") print(" mean position on the size axis (held-out frames):") means = {} for t in order: m = te & (lab == t) means[t] = pred[m].mean() print(f" {t:14s} true {SQ[t]:.2f} -> {pred[m].mean():.2f} +- {pred[m].std():.2f}") b, t300, t330 = means["blue (2.6 mm)"], means["3.00 sq"], means["3.30 sq"] print(f"\n 3.00 sq between blue and 3.30 sq on this axis: " f"{'YES' if b < t300 < t330 or t330 < t300 < b else 'NO'}") print("\n centroid distances in the 512-d feature space:") print(f" blue <-> 3.00 {dist('blue (2.6 mm)', '3.00 sq'):.2f}") print(f" 3.00 <-> 3.30 {dist('3.00 sq', '3.30 sq'):.2f}") print(f" blue <-> 3.30 {dist('blue (2.6 mm)', '3.30 sq'):.2f} " f"(should be the largest if 3.00 sits between)") print(f" 1.70 <-> blue {dist('1.70 sq', 'blue (2.6 mm)'):.2f}") if __name__ == "__main__": main()