Download plot_figures.py from SSp1ash/LangDecoder: direct link, hf CLI and curl.
- Browser
- Download file 8.44 kB
-
https://huggingface.co/datasets/SSp1ash/LangDecoder/resolve/main/plot_figures.py
- Command line
-
hf download hf://datasets/SSp1ash/LangDecoder/plot_figures.py
-
curl -L -o plot_figures.py https://huggingface.co/datasets/SSp1ash/LangDecoder/resolve/main/plot_figures.py
8.44 kB
| import os, sys, json | |
| import numpy as np, pandas as pd, matplotlib | |
| matplotlib.use("Agg"); import matplotlib.pyplot as plt | |
| from scipy.stats import spearmanr | |
| from langdecoder.paths import OUT | |
| from langdecoder.surface import parcel_mean | |
| plt.rcParams.update({"font.family": "sans-serif", "font.sans-serif": ["Arial", "Liberation Sans", "DejaVu Sans"], "font.size": 8, "axes.spines.top": False, "axes.spines.right": False, "pdf.fonttype": 42}) | |
| F = OUT / "figures"; F.mkdir(exist_ok=True) | |
| C3 = ["#E64B35", "#4DBBD5", "#00A087"]; GREY = "#BDBDBD" | |
| def box(ax, cols, colors, labels): | |
| data = [np.asarray(c, float)[np.isfinite(c)] for c in cols] | |
| b = ax.boxplot(data, widths=0.55, showfliers=False, patch_artist=True, medianprops=dict(color="k")) | |
| for p, c in zip(b["boxes"], colors): p.set_facecolor(c); p.set_alpha(0.55) | |
| rng = np.random.default_rng(0) | |
| for i, (d, c) in enumerate(zip(data, colors)): ax.scatter(i + 1 + rng.uniform(-0.15, 0.15, len(d)), d, s=6, color=c, edgecolor="none", zorder=3) | |
| ax.set_xticks(range(1, len(cols) + 1)); ax.set_xticklabels(labels) | |
| S = OUT / "semantic_geometry" | |
| d = pd.read_csv(S / "semantic_attributes/ps_participants.csv"); A = ("concreteness", "socialness", "arousal") | |
| fig, ax = plt.subplots(figsize=(3.2, 2.4)); cols, colors, labs = [], [], [] | |
| for a, c in zip(A, C3): cols += [d[d.attribute == a].ps, d[d.attribute == a].random_control]; colors += [c, GREY]; labs += [a.capitalize(), "Random"] | |
| box(ax, cols, colors, labs); ax.set_ylabel("Cross-language parallelism"); plt.setp(ax.get_xticklabels(), rotation=45, ha="right") | |
| ax.set_title("Fig. 3d"); fig.tight_layout(); fig.savefig(F / "fig3d.pdf") | |
| d = pd.read_csv(S / "individual_correspondence/individual_correspondence.csv") | |
| for k, t, yl in (("h", "Fig. 3h", "Spatial ρ with other-language maps"), ("j", "Fig. 3j", "Spatial ρ with shared semantic geometry map")): | |
| fig, ax = plt.subplots(figsize=(2.0, 2.4)); box(ax, [d[d.language == L][f"{k}_rho"] for L in ("CN", "EN", "FR")], C3, ["CN", "EN", "FR"]) | |
| ax.axhline(0, color="k", lw=0.5, ls=":"); ax.set_ylabel(yl); ax.set_title(t); fig.tight_layout(); fig.savefig(F / f"fig3{k}.pdf") | |
| G = OUT / "generalization"; DATA = os.environ["LANGDECODER_DATA"] | |
| TIER3 = ["#4A90D9", "#E8413C", "#F5A623"] | |
| g1 = parcel_mean(np.load(DATA + "/atlas/margulies2016_g1_fslr32k.npy").astype(float)) | |
| sm = parcel_mean(np.mean([np.load(G / f"shared_map_train_{p}.npy").astype(float) for p in ("CN_EN", "CN_FR", "EN_FR")], 0)) | |
| ok = np.isfinite(g1) & np.isfinite(sm); r = (lambda v: (np.argsort(np.argsort(v)) + 0.5) / len(v)); x, y = r(sm[ok]), r(g1[ok]) | |
| t_sm, t_g1 = np.minimum((x * 3).astype(int), 2), np.minimum((y * 3).astype(int), 2); js = json.load(open(G / "gradient_correspondence.json")) | |
| fig, ax = plt.subplots(figsize=(2.4, 2.4)) | |
| for k, lab in enumerate(("Low", "Mid", "High")): ax.scatter(x[t_sm == k], y[t_sm == k], s=5, color=TIER3[k], edgecolor="none", label=lab) | |
| b = np.polyfit(x, y, 1); ax.plot([0, 1], np.polyval(b, [0, 1]), "k", lw=1); ax.legend(frameon=False, fontsize=6, ncol=3, loc="upper center", bbox_to_anchor=(0.5, 1.1), handletextpad=0.1) | |
| ax.text(0.02, 0.95, f"ρ = {js['rho']:.2f}\nspin P = {js['spin_p_one_sided']:.3f}", color="#E8413C", transform=ax.transAxes, va="top", fontsize=7) | |
| ax.set_xlabel("Shared semantic geometry gradient"); ax.set_ylabel("Principal functional gradient"); ax.set_title("Fig. 4h", pad=14) | |
| fig.tight_layout(); fig.savefig(F / "fig4h.pdf") | |
| M = np.array([[np.mean(t_sm[t_g1 == i] == j) for j in range(3)] for i in range(3)]) | |
| fig, ax = plt.subplots(figsize=(2.4, 2.2)); im = ax.imshow(M, cmap="Reds", vmin=0, vmax=1) | |
| for i in range(3): | |
| for j in range(3): ax.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center", color="w" if M[i, j] > 0.5 else "k", fontsize=7) | |
| ax.set_xticks(range(3)); ax.set_yticks(range(3)); ax.set_xticklabels(["Low", "Mid", "High"]); ax.set_yticklabels(["Low", "Mid", "High"]) | |
| ax.set_xlabel("Shared semantic geometry gradient"); ax.set_ylabel("Principal functional gradient"); ax.set_title("Fig. 4i") | |
| fig.colorbar(im, ax=ax, fraction=0.046); fig.tight_layout(); fig.savefig(F / "fig4i.pdf") | |
| import nibabel as nib, glob | |
| from nilearn import plotting | |
| ax_c = nib.load(sorted(glob.glob(DATA + "/LPPC-fMRI/sub-*/*.dtseries.nii"))[0]).header.get_axis(1) | |
| idx = [np.asarray(m.vertex, int) for _, _, m in list(ax_c.iter_structures())[:2]] | |
| surf = {h: DATA + f"/atlas/surfaces/tpl-fsLR_den-32k_hemi-{h}_inflated.surf.gii" for h in "LR"} | |
| tv = np.load(G / "gradient_tiers_vertex.npz"); maps = (("Principal functional gradient", tv["g1_percentile"]), ("Shared semantic geometry gradient", tv["shared_percentile"])) | |
| fig, axs = plt.subplots(2, 4, figsize=(7.2, 3.4), subplot_kw={"projection": "3d"}) | |
| for row, (name, v) in enumerate(maps): | |
| off = 0 | |
| for hi, (h, hemi) in enumerate((("L", "left"), ("R", "right"))): | |
| full = np.full(32492, np.nan); full[idx[hi]] = v[off:off + len(idx[hi])]; off += len(idx[hi]) | |
| for vi, view in enumerate(("lateral", "medial")): | |
| a = axs[row, hi * 2 + vi] | |
| plotting.plot_surf(surf[h], full, hemi=hemi, view=view, cmap="magma", vmin=0, vmax=1, axes=a, figure=fig, colorbar=False) | |
| a.set_title(f"{'Left' if h == 'L' else 'Right'} {view}" if row == 0 else "", fontsize=7) | |
| axs[row, 0].text2D(-0.15, 0.5, name.replace(" gradient", "\ngradient"), transform=axs[row, 0].transAxes, rotation=90, va="center", ha="center", fontsize=7) | |
| sm_ = plt.cm.ScalarMappable(cmap="magma", norm=plt.Normalize(0, 1)); cb = fig.colorbar(sm_, ax=axs, orientation="horizontal", fraction=0.04, pad=0.02, shrink=0.35) | |
| cb.set_label("Percentile within each map"); fig.suptitle("Fig. 4g, lateral and medial views", fontsize=8); fig.savefig(F / "fig4g_views.pdf", dpi=300); fig.savefig(F / "fig4g_views.png", dpi=300) | |
| import matplotlib.tri as mtri | |
| flat = {h: nib.load(DATA + f"/atlas/surfaces/S1200.{h}.flat.32k_fs_LR.surf.gii") for h in "LR"} | |
| full = {} | |
| for name, v in maps: | |
| off = 0 | |
| for hi, h in enumerate("LR"): | |
| f = np.full(32492, np.nan); f[idx[hi]] = v[off:off + len(idx[hi])]; off += len(idx[hi]); full[(name, h)] = f | |
| fig = plt.figure(figsize=(7.2, 3.6)); cols = [(h, name) for h in "LR" for name, _ in maps] | |
| short = {"Principal functional gradient": "Principal\nfunctional gradient", "Shared semantic geometry gradient": "Shared semantic\ngeometry gradient"} | |
| for c, (h, name) in enumerate(cols): | |
| a = fig.add_subplot(2, 4, c + 1, projection="3d") | |
| plotting.plot_surf(surf[h], full[(name, h)], hemi="left" if h == "L" else "right", view="lateral", cmap="magma", vmin=0, vmax=1, axes=a, figure=fig, colorbar=False) | |
| a.set_title(short[name], fontsize=7) | |
| xy = flat[h].darrays[0].data[:, :2]; tri = flat[h].darrays[1].data; val = full[(name, h)] | |
| a2 = fig.add_subplot(2, 4, c + 5); bad = ~np.isfinite(val) | |
| a2.triplot(mtri.Triangulation(xy[:, 0], xy[:, 1], tri[bad[tri].any(1)]), color="#BDBDBD", lw=0.2) | |
| t = mtri.Triangulation(xy[:, 0], xy[:, 1], tri[~bad[tri].any(1)]) | |
| a2.tripcolor(t, np.nan_to_num(val), cmap="magma", vmin=0, vmax=1, shading="gouraud", rasterized=True) | |
| a2.set_aspect("equal"); a2.axis("off") | |
| fig.text(0.29, 0.97, "Left hemisphere", ha="center", fontsize=8); fig.text(0.71, 0.97, "Right hemisphere", ha="center", fontsize=8) | |
| cb = fig.colorbar(plt.cm.ScalarMappable(cmap="magma", norm=plt.Normalize(0, 1)), ax=fig.axes, orientation="horizontal", fraction=0.035, pad=0.03, shrink=0.3) | |
| cb.set_label("Percentile within each map", fontsize=7); fig.savefig(F / "fig4g.pdf", dpi=300); fig.savefig(F / "fig4g.png", dpi=300) | |
| T = OUT / "transfer"; d = pd.read_csv(T / "prism_fig5e_contribution_by_group.csv"); js = json.load(open(T / "fig5e_spin_tests.json")) | |
| fig, ax = plt.subplots(figsize=(2.2, 2.4)); box(ax, [d[c] for c in ("Low", "Mid", "High")], C3[::-1], ["Low", "Mid", "High"]) | |
| ax.set_ylabel("Relative contribution (percentile)"); ax.set_title(f"Fig. 5e\nMid>Low {js['Mid-Low']['stars']}, High>Mid {js['High-Mid']['stars']}") | |
| fig.tight_layout(); fig.savefig(F / "fig5e.pdf") | |
| d = pd.read_csv(OUT / "nebula/fewshot_tier/prism_fig5f_langdecoder_ChinesePretrained_30pct.csv") | |
| fig, ax = plt.subplots(figsize=(2.2, 2.4)); box(ax, [d[c] for c in ("Low", "Mid", "High")], C3[::-1], ["Low", "Mid", "High"]) | |
| ax.axhline(0.5, color="k", lw=0.5, ls=":"); ax.set_ylabel("Passage identification (normalized rank)"); ax.set_title(f"Fig. 5f, n = {len(d)}") | |
| fig.tight_layout(); fig.savefig(F / "fig5f.pdf"); print("figures in", F) | |