OSCR

A single computational objective can produce specialization of streams in visual cortex.

Code ↔ Paper

16 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

11 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 16 matches · 1 of them tie a paragraph to a whole file without given lines: a weak match, whose lines are not tinted
  1. [1] § Results › Stream-hypothesized task models do not yield stream-specific spatial or functional correspondence ↔ notebooks/demo_plot_combined_source_data.ipynb, lines 333 to 399 · score 0.88 · MB v3 categorization, ConvNeXT, SlowFast, MB v2, MB v1, ResNet · Report a mismatch
  2. [2] § Results › Computational framework for stream-organization hypotheses ↔ notebooks/demo_plot_combined_source_data.ipynb, lines 333 to 399 · score 0.87 · DepthAnythingv2, ConvNeXT, DEKR Pose, MB v3, MB v2, MB v1 · Report a mismatch
  3. [3] § Methods › Representational overlap across MB v1 task models ↔ scripts/cka_mb18_overlap.py, lines 1 to 45 · score 0.87 · backbone.feature_provider.feature_provid, slow.layer4.1, linear CKA, overlap, detection, stimuli · block oscr:b:CEK6RTA5XWCZS-J · Report a mismatch
  4. [4] § Methods › Representational overlap across MB v1 task models ↔ scripts/fitting_one_to_one_unit2voxel.py, lines 30 to 112 · score 0.77 · backbone.feature_provider.feature_provid, slow.layer4.1, detection, v1, layers, models · block oscr:b:XK72NT8ZRBW96-9 · Report a mismatch
  5. [5] § Methods › Model unit selectivity and receptive field properties ↔ spacetorch/datasets/floc.py, lines 79 to 200 · score 0.69 · category selective, corridors, houses, instruments, limbs, adult · block oscr:b:G2MXPJC6ANCRZ-P · Report a mismatch
  6. [6] § Results › Stream-hypothesized task models do not yield stream-specific spatial or functional correspondence ↔ matlab/F04_A.m, lines 86 to 103 · score 0.67 · ConvNeXT, SlowFast, ResNet, CNN, SSD, Faster · block oscr:b:RF89V6745WRVK-9 · Report a mismatch
  7. [7] § Methods › Training: Neural network architectures and training tasks › Multiple behaviors models ↔ spacestream/utils/get_utils.py, lines 206 to 287 · score 0.66 · SlowFast model, detection model, Kinetics, vision, Faster, backbone · block oscr:b:VB50QMEK8A51Z-6 · Report a mismatch
  8. [8] § Methods › Testing: Evaluating theories › Linear regression ↔ spacestream/utils/mapping_utils.py, lines 17 to 84 · score 0.62 · linear regression, voxel responses, ridge, splits, mapping, layer · block oscr:b:9RXZEFKB9D5DR-X · Report a mismatch
  9. [9] § Results › Stream-hypothesized task models do not yield stream-specific spatial or functional correspondence ↔ notebooks/F04_A_processing.ipynb, lines 129 to 147 · score 0.59 · v3 depth, v3 pose, v3 categorization, MB, dorsal, lateral · Report a mismatch
  10. [10] § Methods › Training: Neural network architectures and training tasks › Spatial constraints models › Loss functions ↔ spacestream/models/slow_fast.py, lines 10 to 76 · score 0.59 · cross entropy loss, loss function, network, layer, model · block oscr:b:JAACS7ZA66KWJ-K · Report a mismatch
  11. [11] § Methods › Testing: Evaluating theories › Brain data › Category selectivity by stream in human cortex ↔ matlab/transform_selectivity_to_fsaverage.m, the whole file · a weak match · score 0.59 · fsaverage space, contrast maps, selectivity, bodies, fLoc, NSD · block oscr:b:PVZT8GSKN44CZ-I · Report a mismatch
  12. [12] § Results › Stream-hypothesized task models do not yield stream-specific spatial or functional correspondence ↔ notebooks/F03_B_processing.ipynb, lines 155 to 164 · score 0.55 · MB v2, MB v1, multiple behavior, collapsed, hypothesized, models · Report a mismatch
  13. [13] § Methods › Training: Neural network architectures and training tasks › Multiple behaviors models ↔ spacestream/utils/get_utils.py, lines 206 to 287 · score 0.55 · OpenAI, encoder, vision, Pretraining, ConvNeXT, DETR · block oscr:b:VB50QMEK8A51Z-6 · Report a mismatch
  14. [14] § Methods › Training: Neural network architectures and training tasks › Spatial constraints models › Loss functions ↔ spacetorch/losses/cross_entropy_spatial_correlation_loss.py, lines 11 to 58 · score 0.54 · cross entropy loss, batch, layer · block oscr:b:PHSXR1GRY51YB-K · Report a mismatch
  15. [15] § Methods › Training: Neural network architectures and training tasks › Spatial constraints models › Initialization of model unit position ↔ spacetorch/datasets/__init__.py, lines 1 to 35 · score 0.54 · retinal waves, sine grating · block oscr:b:B1ZMF48S1SSTX-9 · Report a mismatch
  16. [16] § Methods › Testing: Evaluating theories › Linear regression ↔ spacestream/analyses/base_fitter.py, lines 102 to 209 · score 0.52 · lower dimensional space, regression, splits, layer, train, stream · block oscr:b:VZH4GT9BX0YZ0-H · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 991 lines · 41 KB · Apache-2.0 · 2 matches

  1. # %% [markdown]
  2. # # Demo: Plot Combined Manuscript Source Data
  3. #
  4. # This notebook reads only `data/spacestream_manuscript_source_data.xlsx`. Each worksheet is one manuscript figure panel; panels with multiple source tables are parsed from stacked sections within that worksheet.
  5. # %%
  6. from pathlib import Path
  7. import os
  8. import zipfile
  9. import xml.etree.ElementTree as ET
  10. import matplotlib.pyplot as plt
  11. from matplotlib.lines import Line2D
  12. import numpy as np
  13. import pandas as pd
  14. import seaborn as sns
  15. ROOT = Path.cwd()
  16. if ROOT.name != "manuscript_figure_source_data":
  17. ROOT = Path("/oak/stanford/groups/kalanit/biac2/kgs/projects/Dawn/manuscript_figure_source_data")
  18. WORKBOOK = ROOT / "data" / "spacestream_manuscript_source_data.xlsx"
  19. OUT = ROOT / "outputs" / "combined_demo_plots"
  20. OUT.mkdir(parents=True, exist_ok=True)
  21. os.environ.setdefault("MPLCONFIGDIR", str(ROOT / ".matplotlib"))
  22. os.environ.setdefault("XDG_CACHE_HOME", str(ROOT / ".cache"))
  23. (ROOT / ".matplotlib").mkdir(exist_ok=True)
  24. (ROOT / ".cache").mkdir(exist_ok=True)
  25. plt.rcParams.update({
  26. "figure.dpi": 120,
  27. "savefig.dpi": 200,
  28. "axes.spines.top": False,
  29. "axes.spines.right": False,
  30. "font.size": 10,
  31. "font.family": "sans-serif",
  32. "font.sans-serif": ["Helvetica", "Arial", "DejaVu Sans"],
  33. "pdf.use14corefonts": True,
  34. "ps.useafm": True,
  35. "svg.fonttype": "none",
  36. "pdf.fonttype": 42,
  37. "ps.fonttype": 42,
  38. })
  39. sns.set_theme(style="ticks", rc={
  40. "font.family": "sans-serif",
  41. "font.sans-serif": ["Helvetica", "Arial", "DejaVu Sans"],
  42. })
  43. CORE_ROI_NAMES = ["Ventral", "Lateral", "Dorsal"]
  44. ROI_ORDER = ["Dorsal", "Lateral", "Ventral"]
  45. ROI_COLORS = ["#377E2C", "#1A1AAC", "#8C1A4C"]
  46. STREAM_PALETTE = {"Ventral": ROI_COLORS[2], "Lateral": ROI_COLORS[1], "Dorsal": ROI_COLORS[0]}
  47. STREAM_COLORS = {
  48. "Dorsal": "#006600",
  49. "Parietal": "#006600",
  50. "Lateral": "#4d7fff",
  51. "Ventral": "#990000",
  52. }
  53. STREAM_ORDER = ["Dorsal", "Lateral", "Ventral"]
  54. LEGACY_STREAM_ORDER = ["Parietal", "Lateral", "Ventral"]
  55. CONTRAST_ORDER = ["Places", "Bodies", "Faces"]
  56. TDANN_COLORS = {"simCLR": "#720298", "self_supervised": "#720298", "supervised": "#CB6D4A"}
  57. def savefig(fig, stem):
  58. png = OUT / f"{stem}.png"
  59. pdf = OUT / f"{stem}.pdf"
  60. fig.tight_layout()
  61. fig.savefig(png)
  62. fig.savefig(pdf)
  63. plt.close(fig)
  64. print(png.relative_to(ROOT))
  65. print(pdf.relative_to(ROOT))
  66. def despine(ax):
  67. ax.spines["top"].set_visible(False)
  68. ax.spines["right"].set_visible(False)
  69. def clean_legend_to_streams(ax, stream_order):
  70. handles, labels = ax.get_legend_handles_labels()
  71. stream_handles = {}
  72. for handle, label in zip(handles, labels):
  73. if label in stream_order and label not in stream_handles:
  74. stream_handles[label] = handle
  75. if stream_handles:
  76. ax.legend(stream_handles.values(), stream_handles.keys(), frameon=False, title="Stream")
  77. else:
  78. ax.legend([], [], frameon=False)
  79. # %% [markdown]
  80. # ## Load Combined Panel Workbook
  81. # %%
  82. NS_MAIN = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
  83. NS_REL = "{http://schemas.openxmlformats.org/package/2006/relationships}"
  84. NS_DOC_REL = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}"
  85. def _read_shared_strings(zf):
  86. if "xl/sharedStrings.xml" not in zf.namelist():
  87. return []
  88. root = ET.fromstring(zf.read("xl/sharedStrings.xml"))
  89. return ["".join(node.text or "" for node in item.findall(f".//{NS_MAIN}t")) for item in root.findall(f"{NS_MAIN}si")]
  90. def _read_sheet_rows(zf, sheet_path, shared_strings):
  91. root = ET.fromstring(zf.read(sheet_path))
  92. rows = []
  93. for row in root.findall(f".//{NS_MAIN}row"):
  94. values = []
  95. expected_col = 1
  96. for cell in row.findall(f"{NS_MAIN}c"):
  97. ref = cell.attrib.get("r", "A1")
  98. col_idx = 0
  99. for ch in "".join(ch for ch in ref if ch.isalpha()):
  100. col_idx = col_idx * 26 + (ord(ch.upper()) - 64)
  101. while expected_col < col_idx:
  102. values.append("")
  103. expected_col += 1
  104. cell_type = cell.attrib.get("t")
  105. if cell_type == "inlineStr":
  106. text_node = cell.find(f"{NS_MAIN}is/{NS_MAIN}t")
  107. values.append(text_node.text if text_node is not None and text_node.text is not None else "")
  108. elif cell_type == "s":
  109. value_node = cell.find(f"{NS_MAIN}v")
  110. idx = int(value_node.text) if value_node is not None and value_node.text is not None else -1
  111. values.append(shared_strings[idx] if 0 <= idx < len(shared_strings) else "")
  112. else:
  113. value_node = cell.find(f"{NS_MAIN}v")
  114. values.append(value_node.text if value_node is not None and value_node.text is not None else "")
  115. expected_col += 1
  116. while values and values[-1] == "":
  117. values.pop()
  118. rows.append(values)
  119. return rows
  120. def _numericize(df):
  121. out = df.copy()
  122. for col in out.columns:
  123. try:
  124. out[col] = pd.to_numeric(out[col])
  125. except (TypeError, ValueError):
  126. pass
  127. return out
  128. def load_source_workbook(path):
  129. with zipfile.ZipFile(path) as zf:
  130. shared_strings = _read_shared_strings(zf)
  131. workbook_xml = ET.fromstring(zf.read("xl/workbook.xml"))
  132. rels_xml = ET.fromstring(zf.read("xl/_rels/workbook.xml.rels"))
  133. rel_targets = {rel.attrib["Id"]: rel.attrib["Target"] for rel in rels_xml.findall(f"{NS_REL}Relationship")}
  134. panel_rows = {}
  135. for sheet in workbook_xml.findall(f".//{NS_MAIN}sheet"):
  136. name = sheet.attrib["name"]
  137. rid = sheet.attrib[f"{NS_DOC_REL}id"]
  138. sheet_path = "xl/" + rel_targets[rid].lstrip("/")
  139. panel_rows[name] = _read_sheet_rows(zf, sheet_path, shared_strings)
  140. return panel_rows
  141. def extract_panel_tables(panel_rows):
  142. panel_tables = {}
  143. tables = {}
  144. csvs = {}
  145. metadata_keys = {"figure_panel", "source_workbook", "source_table", "staging_csv", "rows"}
  146. for panel, rows in panel_rows.items():
  147. panel_tables[panel] = {}
  148. i = 0
  149. while i < len(rows):
  150. row = rows[i]
  151. if row and row[0] == "source_table":
  152. table_name = row[1]
  153. staging_csv = ""
  154. i += 1
  155. while i < len(rows):
  156. row = rows[i]
  157. if row and row[0] == "staging_csv":
  158. staging_csv = row[1] if len(row) > 1 else ""
  159. if row and row[0] not in metadata_keys:
  160. break
  161. i += 1
  162. if i >= len(rows):
  163. break
  164. header = rows[i]
  165. data_rows = []
  166. i += 1
  167. while i < len(rows):
  168. row = rows[i]
  169. if row and row[0] == "source_table":
  170. break
  171. if row:
  172. data_rows.append(row)
  173. i += 1
  174. width = len(header)
  175. padded = [r + [""] * max(width - len(r), 0) for r in data_rows]
  176. df = _numericize(pd.DataFrame([r[:width] for r in padded], columns=header))
  177. panel_tables[panel][table_name] = df
  178. tables[table_name] = df
  179. if staging_csv:
  180. csvs[Path(staging_csv).stem] = df
  181. continue
  182. i += 1
  183. return panel_tables, tables, csvs
  184. panel_rows = load_source_workbook(WORKBOOK)
  185. panel_tables, sheets, csvs = extract_panel_tables(panel_rows)
  186. print(f"Loaded {len(panel_tables)} panel sheets from {WORKBOOK}")
  187. print(f"Extracted {len(sheets)} source tables")
  188. for panel, table_map in panel_tables.items():
  189. print(panel, sorted(table_map))
  190. # %% [markdown]
  191. # ## Fig 1A: Mega Matrix And MDS
  192. # %%
  193. coords = csvs["fig1a_mds_coordinates_random_state0"].copy()
  194. mega_matrix = csvs["fig1a_mega_matrix"].to_numpy(dtype=float)
  195. roi_colors = {
  196. "Early": "#a6a6a6",
  197. "Midventral": "#f4bdd8",
  198. "Midlateral": "#ccdaff",
  199. "Midparietal": "#b3ffc6",
  200. "Ventral": "#DC267F",
  201. "Lateral": "#4d7fff",
  202. "Parietal": "#006600",
  203. }
  204. markers = {"lh": "v", "rh": "o"}
  205. fig, ax = plt.subplots(figsize=(10, 10))
  206. for (roi, hemi), group in coords.groupby(["roi_raw", "hemi"]):
  207. ax.scatter(
  208. group["mds_dim1"],
  209. group["mds_dim2"],
  210. s=35 + 20 * group["subject"].astype(int),
  211. c=roi_colors[roi],
  212. marker=markers[hemi],
  213. edgecolors="white",
  214. linewidths=0.5,
  215. alpha=0.9,
  216. label=f"{roi}, {hemi}",
  217. )
  218. ax.set_xlabel("MDS dimension 1")
  219. ax.set_ylabel("MDS dimension 2")
  220. ax.set_title("Fig 1A MDS from saved mega matrix")
  221. ax.spines[["top", "right"]].set_visible(False)
  222. savefig(fig, "fig1a_mds_source_style_demo")
  223. fig, ax = plt.subplots(figsize=(8, 8))
  224. im = ax.imshow(mega_matrix, cmap="magma", vmin=0, vmax=1)
  225. ax.set_title("Fig 1A source mega matrix")
  226. ax.set_xlabel("Matrix index")
  227. ax.set_ylabel("Matrix index")
  228. fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
  229. savefig(fig, "fig1a_mega_matrix_demo")
  230. # %% [markdown]
  231. # ## Fig 1B: Human fLoc Selectivity
  232. # %%
  233. def plot_floc_bar_strip(subject_df, hemi_df, stem, title, hue_order=None):
  234. sns.set_theme(style="ticks", context="talk")
  235. hue_order = hue_order or ["Dorsal", "Lateral", "Ventral"]
  236. fig, ax = plt.subplots(figsize=(6, 6), facecolor="white")
  237. ax.set_facecolor("white")
  238. sns.barplot(
  239. data=subject_df,
  240. x="contrast",
  241. y="frac_t_above",
  242. hue="stream",
  243. order=CONTRAST_ORDER,
  244. hue_order=hue_order,
  245. palette=STREAM_PALETTE,
  246. ci="sd",
  247. capsize=0.08,
  248. errwidth=1.5,
  249. edgecolor="white",
  250. linewidth=4,
  251. ax=ax,
  252. )
  253. markers = {"lh": "o", "rh": "^"}
  254. for hemi, marker in markers.items():
  255. sns.stripplot(
  256. data=hemi_df[hemi_df["hemi"] == hemi],
  257. x="contrast",
  258. y="frac_t_above",
  259. hue="stream",
  260. order=CONTRAST_ORDER,
  261. hue_order=hue_order,
  262. dodge=True,
  263. jitter=0.15,
  264. marker=marker,
  265. size=4.5,
  266. edgecolor="white",
  267. linewidth=0.5,
  268. palette=STREAM_PALETTE,
  269. ax=ax,
  270. )
  271. clean_legend_to_streams(ax, hue_order)
  272. ax.spines["right"].set_visible(False)
  273. ax.spines["top"].set_visible(False)
  274. ax.set_xlabel("Contrast")
  275. ax.set_ylabel("Fraction t > 3")
  276. ax.set_title(title)
  277. ax.grid(False)
  278. ax.tick_params(colors="black", labelcolor="black")
  279. ax.spines["left"].set_color("black")
  280. ax.spines["bottom"].set_color("black")
  281. savefig(fig, stem)
  282. plot_floc_bar_strip(
  283. csvs["fig1b_human_floc_selectivity_subject_bars"],
  284. csvs["fig1b_human_floc_selectivity_hemi_dots"],
  285. "fig1b_human_floc_selectivity_source_style_demo",
  286. "Fig 1B human fLoc selectivity",
  287. hue_order=["Dorsal", "Lateral", "Ventral"],
  288. )
  289. # %% [markdown]
  290. # ## Figs 3B/3C/4A/4B: Model Correspondence Panels
  291. # %%
  292. FIG3_MODEL_ORDER = [
  293. "MB_RN50", "MB_RN50_v2", "MB_RN50_v3", "MB_RN18",
  294. "TDANN_Supervised_0.0", "TDANN_SimCLR_0.0", "TDANN_Supervised", "TDANN_SimCLR",
  295. ]
  296. FIG3_MODEL_LABELS = ["MB v1", "MB v2", "MB v3", "MB v1", "Cat", "SimCLR", "TDANN Cat", "TDANN SimCLR"]
  297. FIG3_IN_BAR_LABELS = ["50", "50", "50", "18", "18", "18", "18", "18"]
  298. FIG3_XVALS = [1, 2, 3, 4.5, 5.5, 6.5, 8, 9]
  299. FIG4_MODEL_ORDER = [
  300. "MB_RN50_detection", "MB_RN50_action", "MB_RN50_categorization",
  301. "MB_RN50_v2_detection", "MB_RN50_v2_clip", "MB_RN50_v2_categorization",
  302. "MB_RN50_v3_depth", "MB_RN50_v3_pose", "MB_RN50_v3_categorization",
  303. "MB_RN18_detection", "MB_RN18_action", "MB_RN18_categorization",
  304. ]
  305. FIG4_MODEL_LABELS = ["SSD", "SlowFast", "ResNet", "DETR", "CLIP", "ConvNeXT-T", "DepthAnythingv2", "DEKR-Pose", "ResNet", "Faster R-CNN", "SlowFast", "ResNet"]
  306. FIG4_IN_BAR_LABELS = ["50", "50", "50", "50", "50", "50", "50", "50", "50", "18", "18", "18"]
  307. FIG4_XVALS = [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15]
  308. MATLAB_BAR_COLORS_FIG3 = ["#808080", "#808080", "#808080", "#808080", "#cc3300", "#660091", "#cc3300", "#660091"]
  309. MATLAB_BAR_ALPHAS_FIG3 = [0.35, 0.35, 0.35, 0.5, 0.5, 0.5, 0.75, 1.0]
  310. MATLAB_BAR_COLORS_FIG4 = ["#80b380", "#8080b3", "#cc8066", "#80b380", "#6666e6", "#cc8066", "#66cc66", "#4d4de6", "#cc8066", "#80b380", "#8080b3", "#cc8066"]
  311. def plot_matlab_like_three_roi(points, noise, model_order, model_labels, in_bar_labels, xvals, colors, alphas, stem, title, ylabel):
  312. noise_summary = noise.groupby("ROI")["result"].agg(["mean", "std"])
  313. ymax = float((noise_summary["mean"] + noise_summary["std"]).max() * 1.1)
  314. fig, axes = plt.subplots(1, 3, figsize=(16, 6), sharey=True)
  315. for ax, roi in zip(axes, ROI_ORDER):
  316. roi_points = points[points["ROIS"] == roi]
  317. band = noise_summary.loc[roi]
  318. ax.axhspan(band["mean"] - band["std"], band["mean"] + band["std"], color="0.9", alpha=1.0, zorder=0)
  319. means = roi_points.groupby("model_type")["result"].mean()
  320. for i, model in enumerate(model_order):
  321. mean = means.loc[model] if model in means.index else np.nan
  322. ax.bar(xvals[i], mean, width=0.95, color=colors[i], alpha=alphas[i], edgecolor="none", zorder=2)
  323. if np.isfinite(mean):
  324. ax.text(xvals[i], ymax * 0.04, in_bar_labels[i], rotation=90, color="0.82", fontsize=13, ha="center", va="bottom")
  325. model_rows = roi_points[roi_points["model_type"] == model]
  326. lh = model_rows[model_rows["hemi"] == "lh"]["result"]
  327. rh = model_rows[model_rows["hemi"] == "rh"]["result"]
  328. edge = {"Dorsal": "#003300", "Lateral": "#000033", "Ventral": "#330018"}[roi]
  329. ax.scatter(np.full(len(lh), xvals[i]), lh, marker="^", facecolors="none", edgecolors=edge, linewidths=1.4, zorder=3)
  330. ax.scatter(np.full(len(rh), xvals[i]), rh, marker="o", facecolors="none", edgecolors=edge, linewidths=1.4, zorder=3)
  331. ax.set_xticks(xvals)
  332. ax.set_xticklabels(model_labels, rotation=90, fontsize=10)
  333. ax.set_xlim(0, max(xvals) + 1.5)
  334. ax.set_ylim(0, ymax)
  335. ax.set_title(roi, fontsize=18)
  336. ax.spines["right"].set_visible(False)
  337. ax.spines["top"].set_visible(False)
  338. if ax is axes[0]:
  339. ax.set_ylabel(ylabel, fontsize=14)
  340. else:
  341. ax.tick_params(labelleft=False)
  342. ax.spines["left"].set_visible(False)
  343. fig.suptitle(title, fontsize=18)
  344. savefig(fig, stem)
  345. plot_matlab_like_three_roi(csvs["fig3b_spatial_correspondence_points"], csvs["fig3b_spatial_correspondence_noise_ceiling"], FIG3_MODEL_ORDER, FIG3_MODEL_LABELS, FIG3_IN_BAR_LABELS, FIG3_XVALS, MATLAB_BAR_COLORS_FIG3, MATLAB_BAR_ALPHAS_FIG3, "fig3b_spatial_correspondence_source_style_demo", "Fig 3B spatial correspondence", "Distance similarity [r]")
  346. plot_matlab_like_three_roi(csvs["fig3c_functional_correspondence_points"], csvs["fig3c_functional_correspondence_noise_ceiling"], FIG3_MODEL_ORDER, FIG3_MODEL_LABELS, FIG3_IN_BAR_LABELS, FIG3_XVALS, MATLAB_BAR_COLORS_FIG3, MATLAB_BAR_ALPHAS_FIG3, "fig3c_functional_correspondence_source_style_demo", "Fig 3C functional correspondence", "Functional similarity [r]")
  347. plot_matlab_like_three_roi(csvs["fig4a_mb_task_stream_assignment_points"], csvs["fig4a_mb_task_stream_assignment_noise_ceiling"], FIG4_MODEL_ORDER, FIG4_MODEL_LABELS, FIG4_IN_BAR_LABELS, FIG4_XVALS, MATLAB_BAR_COLORS_FIG4, [0.5] * 12, "fig4a_mb_task_stream_assignment_source_style_demo", "Fig 4A MB task-stream assignment", "Task-stream assignment [%]")
  348. plot_matlab_like_three_roi(csvs["fig4b_mb_task_functional_correspondence_points"], csvs["fig4b_mb_task_functional_correspondence_noise_ceiling"], FIG4_MODEL_ORDER, FIG4_MODEL_LABELS, FIG4_IN_BAR_LABELS, FIG4_XVALS, MATLAB_BAR_COLORS_FIG4, [0.5] * 12, "fig4b_mb_task_functional_correspondence_source_style_demo", "Fig 4B MB task functional correspondence", "Functional similarity [r]")
  349. # %% [markdown]
  350. # ## Fig 5B: Spatial Weight Curves
  351. # %%
  352. def plot_fig5b_source_style(points, bands, stem_prefix, title_prefix, ylim_top):
  353. sns.set_theme(style="ticks")
  354. line_kwargs = {"marker": ".", "markersize": 18, "lw": 1, "markeredgecolor": "w", "markeredgewidth": 1.5}
  355. version_order = [v for v in ["self_supervised", "supervised"] if v in set(points["version"])]
  356. label_map = {"self_supervised": "Self-supervised", "supervised": "Supervised"}
  357. for streamx, stream in enumerate(CORE_ROI_NAMES):
  358. fig, ax = plt.subplots(figsize=(3, 5))
  359. df_stream = points[points["stream"] == stream].rename(columns={"spatial_weight": "Spatial_Weight", "corr": "Corr", "version": "Version"})
  360. sns.lineplot(
  361. data=df_stream,
  362. x="Spatial_Weight",
  363. y="Corr",
  364. hue="Version",
  365. hue_order=version_order,
  366. palette=[TDANN_COLORS[v] for v in version_order],
  367. errorbar="se",
  368. ax=ax,
  369. **line_kwargs,
  370. )
  371. ax.set_xscale("symlog", linthresh=0.09)
  372. ax.set_xlim([-0.01, 50])
  373. ax.set_xticks([], minor=True)
  374. ax.set_xticks([0, 0.1, 0.25, 0.5, 1.25, 2.5, 25])
  375. ax.set_xticklabels([0, 0.1, "", "", 1.25, "", 25])
  376. band = bands[bands["stream"] == stream].iloc[0]
  377. ax.axhspan(band["mean"] - band["std"], band["mean"] + band["std"], xmin=0, xmax=1, color="lightgray", alpha=0.75)
  378. if streamx == 2:
  379. h, _ = ax.get_legend_handles_labels()
  380. ax.legend(h, [label_map[v] for v in version_order], frameon=False)
  381. else:
  382. ax.legend([], [], frameon=False)
  383. ax.set_xlabel("Spatial Weight", fontsize=14)
  384. ax.set_ylabel("Correlation", fontsize=14)
  385. ax.set_yticks([])
  386. ax.spines["left"].set_visible(False)
  387. ax.spines["right"].set_visible(False)
  388. ax.spines["top"].set_visible(False)
  389. ax.set_ylim(bottom=0.0, top=ylim_top)
  390. ax.set_title(f"{title_prefix}: {stream}")
  391. savefig(fig, f"{stem_prefix}_{stream.lower()}_source_style_demo")
  392. plot_fig5b_source_style(csvs["fig5b_sc_spatial_correspondence_by_weight_points"], csvs["fig5b_sc_spatial_correspondence_brain_band_mean_sd"], "fig5b_top_spatial_correspondence", "Fig 5B top", 0.3)
  393. plot_fig5b_source_style(csvs["fig5b_sc_functional_correspondence_by_weight_points"], csvs["fig5b_sc_functional_correspondence_brain_band_mean_sd"], "fig5b_bottom_functional_correspondence", "Fig 5B bottom", 0.5)
  394. # %% [markdown]
  395. # ## Fig 5C: Effective Dimensionality vs Functional Similarity
  396. # %%
  397. points = csvs["fig5c_effective_dimensionality_vs_functional_similarity_points"].copy()
  398. points = points.rename(columns={"spatial_weight": "Spatial Weight", "type": "Type", "combined": "Combined", "stream": "Stream", "ed": "ED", "corr": "Corr"})
  399. bands = csvs["fig5c_brain_reference_bands_mean_sd"]
  400. for ridx, roi in enumerate(CORE_ROI_NAMES):
  401. fig, ax = plt.subplots(figsize=(7, 9))
  402. sns.set_theme(style="ticks")
  403. df_roi = points[points["Stream"] == roi]
  404. band = bands[bands["stream"] == roi].iloc[0]
  405. ax.axhspan(band["mean_corr"] - band["std_corr"], band["mean_corr"] + band["std_corr"], xmin=0, xmax=1, color="lightgray", alpha=0.75)
  406. ax.axvspan(band["mean_ed"] - band["std_ed"], band["mean_ed"] + band["std_ed"], color="lightgray", alpha=0.75)
  407. sup_open = df_roi[(df_roi["Type"] == "supervised") & ~(df_roi["Spatial Weight"].astype(str).isin(["2.5"]))]
  408. sim_open = df_roi[(df_roi["Type"] == "simCLR") & ~(df_roi["Spatial Weight"].astype(str).isin(["0.25", "0.5"]))]
  409. sup_filled = df_roi[(df_roi["Type"] == "supervised") & (df_roi["Spatial Weight"].astype(str).isin(["2.5"]))]
  410. sim_filled = df_roi[(df_roi["Type"] == "simCLR") & (df_roi["Spatial Weight"].astype(str).isin(["0.25", "0.5"]))]
  411. ax.scatter(sup_open["ED"], sup_open["Corr"], s=70, facecolors="white", edgecolors="#CB6D4A", linewidths=2, alpha=0.3, zorder=10, label="supervised")
  412. ax.scatter(sim_open["ED"], sim_open["Corr"], s=70, facecolors="white", edgecolors="#720298", linewidths=2, alpha=0.3, zorder=10, label="simCLR")
  413. ax.scatter(sup_filled["ED"], sup_filled["Corr"], s=130, color="#CB6D4A", alpha=0.65, zorder=11)
  414. ax.scatter(sim_filled["ED"], sim_filled["Corr"], s=90, color="#720298", alpha=0.65, zorder=11)
  415. ax.set_xscale("log")
  416. ax.set_ylim(0, 0.43)
  417. ax.set_xlabel("Effective Dimensionality")
  418. ax.set_ylabel("Correlation")
  419. ax.set_title(f"Fig 5C {roi}")
  420. ax.legend(frameon=False)
  421. ax.spines["right"].set_visible(False)
  422. ax.spines["top"].set_visible(False)
  423. savefig(fig, f"fig5c_ed_vs_functional_similarity_{roi.lower()}_source_style_demo")
  424. # %% [markdown]
  425. # ## Figs 6A/6B: Transfer Panels
  426. # %%
  427. def plot_transfer_source_style(points, value_col, stem, title, ylim=None):
  428. sns.set_theme(style="ticks")
  429. fig, ax = plt.subplots(figsize=(3, 6))
  430. raw_streams = {"Ventral": "Ventral", "Dorsal": "Parietal"}
  431. wide = points.pivot_table(index="line_index", columns="stream_display", values=value_col, aggfunc="first")
  432. for _, row in wide.dropna(subset=["Dorsal", "Ventral"]).iterrows():
  433. ax.plot([0.025, 0.975], [row["Dorsal"], row["Ventral"]], c="k", alpha=0.15)
  434. for stream_display, xpos, color in [("Ventral", 1, "#8C1A4C"), ("Dorsal", 0, "#377E2C")]:
  435. for hemi, marker in [("lh", "^"), ("rh", "o")]:
  436. vals = points[(points["stream_display"] == stream_display) & (points["hemi"] == hemi)][value_col]
  437. ax.scatter(
  438. np.full(len(vals), xpos), vals, color=color, s=70, alpha=0.95,
  439. edgecolors="w", marker=marker, linewidths=0.5,
  440. )
  441. ax.set_xticks([0, 1])
  442. ax.set_xticklabels(["Dorsal", "Ventral"], fontsize=16)
  443. ax.set_xlim([-0.2, 1.2])
  444. if ylim:
  445. ax.set_ylim(ylim)
  446. ax.spines["right"].set_visible(False)
  447. ax.spines["top"].set_visible(False)
  448. ax.set_ylabel(value_col.replace("_", " "))
  449. ax.set_title(title)
  450. savefig(fig, stem)
  451. plot_transfer_source_style(csvs["fig6a_object_position_transfer_points"], "accuracy_proportion", "fig6a_object_position_transfer_source_style_demo", "Fig 6A object position", ylim=(0.425, 0.535))
  452. plot_transfer_source_style(csvs["fig6b_imagenet_category_transfer_points"], "max_accuracy_percent", "fig6b_imagenet_category_transfer_source_style_demo", "Fig 6B ImageNet category")
  453. # %% [markdown]
  454. # ## Fig 6C: Model fLoc Selectivity
  455. # %%
  456. plot_floc_bar_strip(
  457. csvs["fig6c_model_floc_selectivity_subject_bars"],
  458. csvs["fig6c_model_floc_selectivity_hemi_dots"],
  459. "fig6c_model_floc_selectivity_source_style_demo",
  460. "Fig 6C model fLoc selectivity",
  461. hue_order=["Dorsal", "Lateral", "Ventral"],
  462. )
  463. # %% [markdown]
  464. # ## Fig 6D: Face-Selective RF Eccentricity
  465. # %%
  466. df = csvs["fig6d_face_selective_rf_eccentricity_plot_points"].copy()
  467. sns.set_theme(style="ticks")
  468. fig, ax = plt.subplots(figsize=(4, 12))
  469. order = ["Lateral", "Ventral"]
  470. palette = [ROI_COLORS[1], ROI_COLORS[2]]
  471. sns.stripplot(
  472. x="stream", y="eccen", hue="stream", jitter=0.1, linewidth=0.75, edgecolor="w",
  473. palette=palette, data=df[(df["hemi"] == "rh") & (df["stream"].isin(order))],
  474. order=order, dodge=True, size=9, ax=ax,
  475. )
  476. sns.stripplot(
  477. x="stream", y="eccen", hue="stream", jitter=0.2, linewidth=1, edgecolor="w", marker="^",
  478. palette=palette, data=df[(df["hemi"] == "lh") & (df["stream"].isin(order))],
  479. order=order, dodge=True, size=9, ax=ax,
  480. )
  481. sns.violinplot(
  482. x="stream", y="eccen", hue="stream", fill=True, linewidth=3, inner="box",
  483. saturation=0.9, palette=palette, data=df[df["stream"].isin(order)], order=order,
  484. dodge=False, ax=ax,
  485. )
  486. for collection in ax.collections:
  487. collection.set_alpha(0.85)
  488. ax.spines["right"].set_visible(False)
  489. ax.spines["top"].set_visible(False)
  490. ax.legend([], [], frameon=False)
  491. ax.set_xlabel("")
  492. ax.set_ylabel("RF eccentricity")
  493. ax.set_title("Fig 6D face-selective RF eccentricity")
  494. savefig(fig, "fig6d_face_selective_rf_eccentricity_source_style_demo")
  495. # %% [markdown]
  496. # ## S2A/S2B: Stream Correlations And Cross-ROI Fits
  497. # %%
  498. def plot_s2a(points, summary):
  499. data = points.copy()
  500. summary = summary.copy()
  501. pair_order = ["Ventral/Lateral", "Ventral/Parietal", "Lateral/Parietal"]
  502. comparison_order = ["Within", "Between"]
  503. colors = {"Within": "#bdbdbd", "Between": "#525252"}
  504. x = np.arange(len(pair_order))
  505. width = 0.34
  506. offsets = {"Within": -width / 2, "Between": width / 2}
  507. fig, ax = plt.subplots(figsize=(4.6, 3.4), facecolor="white")
  508. for comparison in comparison_order:
  509. vals = []
  510. errs = []
  511. for pair in pair_order:
  512. row = summary[(summary["stream_pair"] == pair) & (summary["comparison"] == comparison)].iloc[0]
  513. vals.append(float(row["mean_fisher_z"]))
  514. errs.append(float(row["sem_fisher_z"]))
  515. xpos = x + offsets[comparison]
  516. ax.bar(xpos, vals, yerr=errs, width=width, color=colors[comparison], edgecolor="black", linewidth=0.8, capsize=2, label=comparison)
  517. for idx, pair in enumerate(pair_order):
  518. subj_vals = data[(data["stream_pair"] == pair) & (data["comparison"] == comparison)]["fisher_z"].to_numpy(float)
  519. jitter = np.linspace(-0.06, 0.06, len(subj_vals)) if len(subj_vals) else []
  520. ax.scatter(np.full(len(subj_vals), xpos[idx]) + jitter, subj_vals, s=18, color="lightgray", edgecolor="black", linewidth=0.35, zorder=3)
  521. ax.set_xticks(x)
  522. ax.set_xticklabels(pair_order, rotation=25, ha="right")
  523. ax.set_ylabel("RSM correlation (Fisher z)")
  524. ax.legend(frameon=False)
  525. despine(ax)
  526. fig.tight_layout()
  527. savefig(fig, "s2a_within_between_stream_correlations_demo")
  528. def plot_s2b(points, summary):
  529. data = points.copy()
  530. summary = summary.copy()
  531. roi_order = ["Ventral", "Lateral", "Parietal"]
  532. model_order = ["same_roi", "other_roi1", "other_roi2"]
  533. model_labels = {"same_roi": "Same ROI", "other_roi1": "Other ROI 1", "other_roi2": "Other ROI 2"}
  534. colors = {"same_roi": "#f0f0f0", "other_roi1": "#969696", "other_roi2": "#252525"}
  535. x = np.arange(len(roi_order))
  536. width = 0.22
  537. offsets = {"same_roi": -width, "other_roi1": 0, "other_roi2": width}
  538. fig, ax = plt.subplots(figsize=(4.5, 4.4), facecolor="white")
  539. for model in model_order:
  540. vals = []
  541. errs = []
  542. for roi in roi_order:
  543. row = summary[(summary["roi"] == roi) & (summary["Model"] == model)].iloc[0]
  544. vals.append(float(row["mean_corrected"]))
  545. errs.append(float(row["sem_corrected"]))
  546. xpos = x + offsets[model]
  547. ax.bar(xpos, vals, yerr=errs, width=width, color=colors[model], edgecolor="black", linewidth=0.8, capsize=2, label=model_labels[model])
  548. for idx, roi in enumerate(roi_order):
  549. subj_vals = data[(data["roi"] == roi) & (data["Model"] == model)]["corrected"].to_numpy(float)
  550. jitter = np.linspace(-0.035, 0.035, len(subj_vals)) if len(subj_vals) else []
  551. ax.scatter(np.full(len(subj_vals), xpos[idx]) + jitter, subj_vals, s=18, color="lightgray", edgecolor="blue", linewidth=0.35, zorder=3)
  552. ax.axhline(1, color="black", linestyle="--", linewidth=1.0)
  553. ax.set_ylim(0, 1.05)
  554. ax.set_xticks(x)
  555. ax.set_xticklabels(roi_order, rotation=25, ha="right")
  556. ax.set_ylabel("Corrected R-squared")
  557. ax.legend(frameon=False, loc="upper right")
  558. despine(ax)
  559. fig.tight_layout()
  560. savefig(fig, "s2b_cross_roi_subject_to_subject_demo")
  561. plot_s2a(sheets["s2a_points"], sheets["s2a_summary"])
  562. plot_s2b(sheets["s2b_points"], sheets["s2b_summary"])
  563. # %% [markdown]
  564. # ## S3C: Voxel-To-Voxel Accuracy, Checkpoint 0
  565. # %%
  566. df = sheets["s3c_points"].copy()
  567. df["display_roi"] = df["roi"].replace({"Parietal": "Dorsal"})
  568. order = ["Dorsal", "Lateral", "Ventral"]
  569. fig, ax = plt.subplots(figsize=(3.2, 4.2), facecolor="white")
  570. x = np.arange(len(order))
  571. for idx, roi in enumerate(order):
  572. vals = df.loc[df["display_roi"] == roi, "accuracy_percent"].to_numpy(float)
  573. ax.bar(idx, np.nanmean(vals), yerr=np.nanstd(vals, ddof=1), width=0.62,
  574. color=STREAM_COLORS[roi], alpha=0.75, edgecolor="white", linewidth=0.8)
  575. jitter = np.linspace(-0.12, 0.12, len(vals)) if len(vals) else []
  576. ax.scatter(np.full(len(vals), idx) + jitter, vals, s=26, color="lightgray", edgecolor="black", linewidth=0.4, zorder=3)
  577. ax.axhline(33.3, color="black", linestyle="--", linewidth=1.0)
  578. ax.set_xticks(x)
  579. ax.set_xticklabels(order, rotation=30, ha="right")
  580. ax.set_ylabel("Voxel assignment correspondence (%)")
  581. ax.set_ylim(0, 100)
  582. despine(ax)
  583. fig.tight_layout()
  584. savefig(fig, "s3c_voxel2voxel_accuracy_checkpoint0_demo")
  585. # %% [markdown]
  586. # ## S5A/S5B: TDANN sw0.25 vs V1-Control
  587. # %%
  588. def plot_s5_paired(points, stem, ylabel):
  589. data = points.copy()
  590. data["ROI"] = data["ROI"].replace({"Parietal": "Dorsal"})
  591. subj = data.groupby(["condition", "subject", "ROI"], as_index=False)["result"].mean()
  592. cond_order = ["TDANN_sw0.25", "TDANN_sw0.25_v1_control"]
  593. cond_labels = ["TDANN\nsw0.25", "V1-control\nsw0.25"]
  594. fig, axes = plt.subplots(1, 3, figsize=(7.2, 3.3), sharey=True, facecolor="white")
  595. for ax, roi in zip(axes, STREAM_ORDER):
  596. wide = subj[subj["ROI"] == roi].pivot(index="subject", columns="condition", values="result").dropna()
  597. vals = [wide[c].to_numpy(float) for c in cond_order]
  598. means = [np.nanmean(v) for v in vals]
  599. sems = [np.nanstd(v, ddof=1) / np.sqrt(np.sum(np.isfinite(v))) for v in vals]
  600. ax.bar([0, 1], means, yerr=sems, width=0.62, color=["#d7d7d7", "#9e9e9e"],
  601. edgecolor="#595959", linewidth=0.9, capsize=2, zorder=1)
  602. for _, row in wide.iterrows():
  603. ax.plot([0, 1], [row[cond_order[0]], row[cond_order[1]]], color="black", alpha=0.22, linewidth=0.7, zorder=2)
  604. ax.scatter([0, 1], [row[cond_order[0]], row[cond_order[1]]], color=STREAM_COLORS[roi],
  605. edgecolor="white", linewidth=0.4, s=24, zorder=3)
  606. ax.set_title(roi)
  607. ax.set_xticks([0, 1])
  608. ax.set_xticklabels(cond_labels, rotation=25, ha="right")
  609. despine(ax)
  610. axes[0].set_ylabel(ylabel)
  611. fig.tight_layout()
  612. savefig(fig, stem)
  613. plot_s5_paired(sheets["s5_spat_points"], "s5a_tdann_v1_control_spatial_demo", "Spatial similarity [r]")
  614. plot_s5_paired(sheets["s5_func_points"], "s5b_tdann_v1_control_functional_demo", "Noise-corrected correlation")
  615. # %% [markdown]
  616. # ## S6A/S6B: ViT-Control Correspondence Panels
  617. # %%
  618. S6A_ORDER = [
  619. "MB_RN50_v2_detection",
  620. "MB_RN50_v2_vit_control_detection",
  621. "MB_RN50_v2_clip",
  622. "MB_RN50_v2_vit_control_clip",
  623. "MB_RN50_v2_categorization",
  624. "MB_RN50_v2_vit_control_categorization",
  625. ]
  626. S6B_ORDER = [
  627. "MB_RN50_v2_detection",
  628. "MB_RN50_v2_detection_vit_control",
  629. "MB_RN50_v2_clip",
  630. "MB_RN50_v2_clip_vit_control",
  631. "MB_RN50_v2_categorization",
  632. "MB_RN50_v2_categorization_vit_control",
  633. ]
  634. MODEL_LABELS = {
  635. "MB_RN50_v2_detection": "Det.",
  636. "MB_RN50_v2_vit_control_detection": "Det.\nV1",
  637. "MB_RN50_v2_detection_vit_control": "Det.\nV1",
  638. "MB_RN50_v2_clip": "CLIP",
  639. "MB_RN50_v2_vit_control_clip": "CLIP\nV1",
  640. "MB_RN50_v2_clip_vit_control": "CLIP\nV1",
  641. "MB_RN50_v2_categorization": "Cat.",
  642. "MB_RN50_v2_vit_control_categorization": "Cat.\nV1",
  643. "MB_RN50_v2_categorization_vit_control": "Cat.\nV1",
  644. }
  645. MODEL_COLORS = ["#80b380", "#80b380", "#6666cc", "#6666cc", "#cc8066", "#cc8066"]
  646. MODEL_ALPHA = [1.0, 0.48, 1.0, 0.48, 1.0, 0.48]
  647. def plot_s6(points, noise, model_order, stem, ylabel, chance=None, ylim=None):
  648. data = points.copy()
  649. data["ROIS"] = data["ROIS"].replace({"Parietal": "Dorsal"})
  650. noise = noise.copy()
  651. noise["ROI"] = noise["ROI"].replace({"Parietal": "Dorsal"})
  652. fig, axes = plt.subplots(1, 3, figsize=(9.0, 3.2), sharey=True, facecolor="white")
  653. x = np.array([0, 1, 2.15, 3.15, 4.3, 5.3])
  654. for ax, roi in zip(axes, STREAM_ORDER):
  655. sub = data[data["ROIS"] == roi]
  656. for idx, model in enumerate(model_order):
  657. vals = sub.loc[sub["model_type"] == model, "result"].to_numpy(float)
  658. ax.bar(x[idx], np.nanmean(vals), yerr=np.nanstd(vals, ddof=1), width=0.82,
  659. color=MODEL_COLORS[idx], alpha=MODEL_ALPHA[idx], edgecolor="none", capsize=1.8, zorder=1)
  660. lh = sub[(sub["model_type"] == model) & (sub["hemi"] == "lh")]["result"].to_numpy(float)
  661. rh = sub[(sub["model_type"] == model) & (sub["hemi"] == "rh")]["result"].to_numpy(float)
  662. ax.scatter(np.full(len(lh), x[idx]) - 0.08, lh, marker="^", s=11, color="none", edgecolor="black", linewidth=0.35, zorder=3)
  663. ax.scatter(np.full(len(rh), x[idx]) + 0.08, rh, marker="o", s=11, color="none", edgecolor="black", linewidth=0.35, zorder=3)
  664. nvals = noise.loc[noise["ROI"] == roi, "result"].to_numpy(float)
  665. if len(nvals):
  666. ax.axhspan(np.nanmean(nvals) - np.nanstd(nvals, ddof=1), np.nanmean(nvals) + np.nanstd(nvals, ddof=1),
  667. color="lightgray", alpha=0.35, zorder=0)
  668. if chance is not None:
  669. ax.axhline(chance, color="black", linestyle=":", linewidth=1.0)
  670. ax.set_title(roi)
  671. ax.set_xticks(x)
  672. ax.set_xticklabels([MODEL_LABELS[m] for m in model_order], rotation=0)
  673. if ylim:
  674. ax.set_ylim(*ylim)
  675. despine(ax)
  676. axes[0].set_ylabel(ylabel)
  677. fig.tight_layout()
  678. savefig(fig, stem)
  679. plot_s6(sheets["s6a_points"], sheets["s6a_noise"], S6A_ORDER, "s6a_vit_control_stream_assignment_demo", "Stream assignment (%)", chance=33, ylim=(0, 100))
  680. plot_s6(sheets["s6b_points"], sheets["s6b_noise"], S6B_ORDER, "s6b_vit_control_functional_correspondence_demo", "Functional correspondence [r]", ylim=(0, 0.36))
  681. # %% [markdown]
  682. # ## S10: TDANN CKA Across Spatial Weights
  683. # %%
  684. summary = sheets["s10_summary"].copy()
  685. layer_order = [
  686. "base_model.maxpool", "base_model.layer1.0", "base_model.layer1.1",
  687. "base_model.layer2.0", "base_model.layer2.1", "base_model.layer3.0", "base_model.layer3.1",
  688. "base_model.layer4.0", "base_model.layer4.1",
  689. ]
  690. pretty = [l.replace("base_model.", "").replace("layer", "layer ") for l in layer_order]
  691. ceiling = summary[summary["comparison"] == "ceiling pooled (sw0.0 + sw0.25)"].set_index("layer").reindex(layer_order)
  692. cross = summary[summary["comparison"] == "cross-weight (sw0.0 vs sw0.25)"].set_index("layer").reindex(layer_order)
  693. x = np.arange(len(layer_order))
  694. fig, ax = plt.subplots(figsize=(5.7, 2.8), facecolor="white")
  695. c_mean = ceiling["mean_cka"].to_numpy(float)
  696. c_sem = ceiling["sem_cka"].to_numpy(float)
  697. x_mean = cross["mean_cka"].to_numpy(float)
  698. ax.plot(x, c_mean, color="#2F6DAE", lw=1.4, label="Noise ceiling")
  699. ax.fill_between(x, c_mean - c_sem, c_mean + c_sem, color="#2F6DAE", alpha=0.18, linewidth=0)
  700. ax.plot(x, x_mean, color="#C55A11", marker="o", ms=4, lw=2.0, label="Cross-weight")
  701. ax.set_xticks(x)
  702. ax.set_xticklabels(pretty, rotation=35, ha="right")
  703. ax.set_ylabel("Linear CKA")
  704. ax.set_xlabel("TDANN layer")
  705. ax.set_ylim(0, 1)
  706. ax.grid(axis="y", color="#d9d9d9", linewidth=0.7, alpha=0.7)
  707. ax.legend(frameon=False, loc="lower left")
  708. despine(ax)
  709. fig.tight_layout()
  710. savefig(fig, "s10_cka_tdann_spatial_weight_demo")
  711. # %% [markdown]
  712. # ## S12A: Functional Correspondence Across Spatial Weights
  713. # %%
  714. def plot_s12a(points, bands):
  715. data = points.copy()
  716. data["stream"] = data["stream"].replace({"Parietal": "Dorsal"})
  717. bands = bands.copy()
  718. bands["stream"] = bands["stream"].replace({"Parietal": "Dorsal"})
  719. data["spatial_weight"] = pd.to_numeric(data["spatial_weight"])
  720. versions = [v for v in ["self_supervised", "supervised"] if v in set(data["version"])]
  721. palette = {"self_supervised": "#720298", "supervised": "#B59410"}
  722. labels = {"self_supervised": "SimCLR", "supervised": "Supervised"}
  723. fig, axes = plt.subplots(1, 3, figsize=(8.4, 3.0), sharey=True, facecolor="white")
  724. for ax, stream in zip(axes, STREAM_ORDER):
  725. sub = data[data["stream"] == stream]
  726. for version in versions:
  727. vsub = sub[sub["version"] == version]
  728. grouped = vsub.groupby("spatial_weight")["corr"].agg(["mean", "std", "count"]).reset_index().sort_values("spatial_weight")
  729. grouped["sem"] = grouped["std"] / np.sqrt(grouped["count"])
  730. ax.plot(grouped["spatial_weight"], grouped["mean"], marker=".", markersize=9, lw=1.5,
  731. color=palette.get(version, "black"), label=labels.get(version, version))
  732. ax.fill_between(grouped["spatial_weight"].to_numpy(float),
  733. (grouped["mean"] - grouped["sem"]).to_numpy(float),
  734. (grouped["mean"] + grouped["sem"]).to_numpy(float),
  735. color=palette.get(version, "black"), alpha=0.12, linewidth=0)
  736. band = bands[bands["stream"] == stream]
  737. if len(band):
  738. mean = float(band["mean"].iloc[0])
  739. sd = float(band["std"].iloc[0])
  740. ax.axhspan(mean - sd, mean + sd, color="lightgray", alpha=0.45, zorder=0)
  741. ax.set_xscale("symlog", linthresh=0.09)
  742. ax.set_xlim(-0.01, 50)
  743. ax.set_xticks([0, 0.1, 0.25, 0.5, 1.25, 2.5, 25])
  744. ax.set_xticklabels(["0", "0.1", "", "", "1.25", "", "25"])
  745. ax.set_title(stream)
  746. ax.set_xlabel("Spatial weight")
  747. despine(ax)
  748. axes[0].set_ylabel("Functional correspondence [r]")
  749. axes[-1].legend(frameon=False, loc="upper right")
  750. fig.tight_layout()
  751. savefig(fig, "s12a_functional_correspondence_by_weight_demo")
  752. plot_s12a(sheets["s12a_points"], sheets["s12a_brain_band"])
  753. # %% [markdown]
  754. # ## S11: HVM Transfer, Selected Tasks
  755. # %%
  756. def plot_s11(seedavg):
  757. data = seedavg.copy()
  758. data["spatial_weight"] = pd.to_numeric(data["spatial_weight"])
  759. task_order = ["categorization", "combined_position", "rotation_xz", "size"]
  760. task_titles = {
  761. "categorization": "Categorization",
  762. "combined_position": "Position",
  763. "rotation_xz": "Rotation XZ",
  764. "size": "Size",
  765. }
  766. ylabels = {
  767. "categorization": "ImageNet accuracy (%)",
  768. "combined_position": "Position accuracy",
  769. "rotation_xz": "Rotation correlation [r]",
  770. "size": "Size correlation [r]",
  771. }
  772. fig, axes = plt.subplots(1, 4, figsize=(11.5, 3.0), facecolor="white")
  773. for ax, task in zip(axes, task_order):
  774. sub = data[data["task"] == task]
  775. for stream in STREAM_ORDER:
  776. grouped = (
  777. sub[sub["stream"] == stream]
  778. .groupby("spatial_weight")["result"]
  779. .agg(["mean", "std", "count"])
  780. .reset_index()
  781. .sort_values("spatial_weight")
  782. )
  783. grouped["sem"] = grouped["std"] / np.sqrt(grouped["count"])
  784. ax.plot(
  785. grouped["spatial_weight"],
  786. grouped["mean"],
  787. marker=".",
  788. markersize=9,
  789. lw=1.6,
  790. color=STREAM_COLORS[stream],
  791. label=stream,
  792. )
  793. ax.fill_between(
  794. grouped["spatial_weight"].to_numpy(float),
  795. (grouped["mean"] - grouped["sem"]).to_numpy(float),
  796. (grouped["mean"] + grouped["sem"]).to_numpy(float),
  797. color=STREAM_COLORS[stream],
  798. alpha=0.12,
  799. linewidth=0,
  800. )
  801. ax.set_xscale("symlog", linthresh=0.09)
  802. ax.set_xlim(-0.01, 50)
  803. ax.set_xticks([0, 0.1, 0.25, 0.5, 1.25, 2.5, 25])
  804. ax.set_xticklabels(["0", "0.1", "", "", "1.25", "", "25"])
  805. ax.set_title(task_titles[task])
  806. ax.set_xlabel("Spatial weight")
  807. ax.set_ylabel(ylabels[task])
  808. despine(ax)
  809. axes[-1].legend(frameon=False, loc="best")
  810. fig.tight_layout()
  811. savefig(fig, "s11_hvm_transfer_selected_tasks_demo")
  812. plot_s11(sheets["s11_seedavg"])
  813. # %% [markdown]
  814. # ## S12B: Supervised vs SimCLR Across Spatial Weights
  815. # %%
  816. def plot_s12b(points, bands):
  817. data = points.copy()
  818. data["spatial_weight"] = pd.to_numeric(data["spatial_weight"])
  819. bands = bands.copy()
  820. palette = {"simCLR": "#720298", "supervised": "#B59410"}
  821. labels = {"simCLR": "SimCLR", "supervised": "Supervised"}
  822. versions = [v for v in ["simCLR", "supervised"] if v in set(data["version"])]
  823. fig, axes = plt.subplots(1, 3, figsize=(8.4, 3.0), sharey=True, facecolor="white")
  824. for ax, stream in zip(axes, STREAM_ORDER):
  825. sub = data[data["stream"] == stream]
  826. for version in versions:
  827. grouped = (
  828. sub[sub["version"] == version]
  829. .groupby("spatial_weight")["means"]
  830. .agg(["mean", "std", "count"])
  831. .reset_index()
  832. .sort_values("spatial_weight")
  833. )
  834. grouped["sem"] = grouped["std"] / np.sqrt(grouped["count"])
  835. ax.plot(
  836. grouped["spatial_weight"],
  837. grouped["mean"],
  838. marker=".",
  839. markersize=9,
  840. lw=1.5,
  841. color=palette[version],
  842. label=labels[version],
  843. )
  844. ax.fill_between(
  845. grouped["spatial_weight"].to_numpy(float),
  846. (grouped["mean"] - grouped["sem"]).to_numpy(float),
  847. (grouped["mean"] + grouped["sem"]).to_numpy(float),
  848. color=palette[version],
  849. alpha=0.12,
  850. linewidth=0,
  851. )
  852. band = bands[bands["stream"] == stream]
  853. if len(band):
  854. mean = float(band["mean"].iloc[0])
  855. sd = float(band["std"].iloc[0])
  856. ax.axhspan(mean - sd, mean + sd, color="lightgray", alpha=0.45, zorder=0)
  857. ax.set_xscale("symlog", linthresh=0.09)
  858. ax.set_xlim(-0.01, 50)
  859. ax.set_xticks([0, 0.1, 0.25, 0.5, 1.25, 2.5, 25])
  860. ax.set_xticklabels(["0", "0.1", "", "", "1.25", "", "25"])
  861. ax.set_title(stream)
  862. ax.set_xlabel("Spatial weight")
  863. despine(ax)
  864. axes[0].set_ylabel("Noise-corrected correlation")
  865. axes[-1].legend(frameon=False, loc="upper right")
  866. fig.tight_layout()
  867. savefig(fig, "s12b_supervised_vs_simclr_by_weight_demo")
  868. plot_s12b(sheets["s12b_points"], sheets["s12b_brain_band"])
  869. # %%
  870. print(f"Wrote combined demo plots to {OUT}")
  871. print("PNG files:", len(list(OUT.glob("*.png"))))
  872. print("PDF files:", len(list(OUT.glob("*.pdf"))))

demo_plot_combined_source_data.ipynb at commit d85997e, under Apache-2.0 · at the source

Overview

Authors: Dawn Finzi1,2, Eshed Margalit3, Kendrick Kay4, Daniel L K Yamins1,2,5, Kalanit Grill-Spector1,5
  1. Department of Psychology, Stanford University, Stanford, CA USA
  2. Department of Computer Science, Stanford University, Stanford, CA USA
  3. Neurosciences Graduate Program, Stanford University, Stanford, CA USA
  4. Center for Magnetic Resonance Research, Department of Radiology, University of Minnesota, Minneapolis, MN USA
  5. Wu Tsai Neurosciences Institute, Stanford University, Stanford, CA USA
Institutions: Stanford University (United States); University of Minnesota (United States)
Journal: Nature communications, volume 17, issue 1, article 9762
Dates: received 19 April 2026; accepted 20 July 2026; published online 13 August 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41467-026-76098-y · PMID 42733086 · PMCID PMC13572372 · OpenAlex W7202347126
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: human (organism)
Methods: Connectivity, Statistics, Smoothing, state filtering, decompositions, Machine learning, Preprocessing, fMRI & imaging
Keywords: Computational neuroscience, Visual system, Computer science
MeSH: Neural Networks, Computer*, Visual Cortex*, Visual Pathways*, Brain Mapping, Computer Simulation, Humans, Magnetic Resonance Imaging, Models, Neurological, Visual Perception (* major topic)
Topic: Visual perception and processing mechanisms (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: NEI NIH HHS (R01 EY023915); National Science Foundation (NSF) (IIS-1822929); U.S. Department of Health & Human Services | National Institutes of Health (NIH) (R01EY023915)
Citations: not cited yet (Europe PMC); 119 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.

Repositories

Its files are read in the Code ↔ Paper reader above, with 16 matches between paragraphs and lines of code.

dawnfinzi/spacestream

License: Apache-2.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: d85997e327886f119441cc6a8355584373878d29, 26 September 2026
Languages: Python (49), Jupyter (12), MATLAB (9)
Size: 73 files, 70 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, environment (setup.py), 12 notebooks
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (49 files), PyTorch (23 files), h5py (21 files), SciPy (17 files), pandas (14 files), NiBabel (12 files), Matplotlib (11 files), scikit-learn (9 files), seaborn (7 files), Pillow (3 files), statsmodels (3 files), scikit-image (2 files), Hugging Face Transformers (2 files), xarray (2 files), FreeSurfer (1 file), Statistics and Machine Learning Toolbox (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
72 files

neuroailab/TDANN

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 80c585df69dcb831d1d6802e0776a8cf25d8cfef, 18 October 2024
Languages: Python (92), Jupyter (2)
Size: 479 files, 94 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, environment (requirements.txt, setup.cfg, setup.py), 2 notebooks
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (47 files), PyTorch (46 files), SciPy (15 files), Matplotlib (13 files), pandas (7 files), scikit-image (7 files), xarray (5 files), Pillow (4 files), scikit-learn (4 files), h5py (3 files)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
95 files

Zenodo 20753397

License: Apache-2.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: the references
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (49 files), PyTorch (23 files), h5py (21 files), SciPy (17 files), pandas (14 files), NiBabel (12 files), Matplotlib (11 files), scikit-learn (9 files), seaborn (7 files), Pillow (3 files), statsmodels (3 files), scikit-image (2 files), Hugging Face Transformers (2 files), xarray (2 files), FreeSurfer (1 file), Statistics and Machine Learning Toolbox (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)
72 files
At the source:

Code availability statement

The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41467-026-76098-y.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 3 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 234 scripts, each with its path and the digest of its content;
  • 16 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

Datasets cited

Data availability statement

The paper has a data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41467-026-76098-y.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 5 authors, 3 keywords, 9 MeSH terms, 3 funders, 88 references.

Cite

This paper

Finzi, D., Margalit, E., Kay, K., Yamins, D. L. K., & Grill-Spector, K. (2026). A single computational objective can produce specialization of streams in visual cortex. Nature communications, 17(1), 9762. https://doi.org/10.1038/s41467-026-76098-y

BibTeX

@article{finzi2026single,
author = {Finzi, Dawn and Margalit, Eshed and Kay, Kendrick and Yamins, Daniel L K and Grill-Spector, Kalanit},
title = {{A single computational objective can produce specialization of streams in visual cortex}},
journal = {Nature communications},
year = {2026},
month = aug,
volume = {17},
number = {1},
pages = {9762},
publisher = {Nature Portfolio},
issn = {2041-1723},
doi = {10.1038/s41467-026-76098-y},
url = {https://doi.org/10.1038/s41467-026-76098-y},
pmid = {42733086},
pmcid = {PMC13572372}
}

RIS

TY - JOUR
AU - Finzi, Dawn
AU - Margalit, Eshed
AU - Kay, Kendrick
AU - Yamins, Daniel L K
AU - Grill-Spector, Kalanit
TI - A single computational objective can produce specialization of streams in visual cortex
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/08/13
VL - 17
IS - 1
SP - 9762
SN - 2041-1723
PB - Nature Portfolio
DO - 10.1038/s41467-026-76098-y
UR - https://doi.org/10.1038/s41467-026-76098-y
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41467-026-76098-y",
"type": "article-journal",
"title": "A single computational objective can produce specialization of streams in visual cortex",
"container-title": "Nature communications",
"author": [
{
"family": "Finzi",
"given": "Dawn"
},
{
"family": "Margalit",
"given": "Eshed"
},
{
"family": "Kay",
"given": "Kendrick"
},
{
"family": "Yamins",
"given": "Daniel L K"
},
{
"family": "Grill-Spector",
"given": "Kalanit"
}
],
"container-title-short": "Nat Commun",
"volume": "17",
"issue": "1",
"page": "9762",
"DOI": "10.1038/s41467-026-76098-y",
"PMID": "42733086",
"PMCID": "PMC13572372",
"ISSN": "2041-1723",
"publisher": "Nature Portfolio",
"URL": "https://doi.org/10.1038/s41467-026-76098-y",
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
13
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41467-024-53147-y [code]
A large-scale examination of inductive biases shaping high-level visual representation in brains and machines.
Journal: Nature communications
In common: h5py, Pillow, NiBabel, 8 other tools, 14 references, author Kendrick Kay
[2] doi:10.1038/s42256-025-01072-0 [code]
High-level visual representations in the human brain are aligned with large language models.
Journal: Nature machine intelligence
In common: scikit-image, h5py, Pillow, 10 other tools, 12 references, author Kendrick Kay
[3] doi:10.1038/s42003-026-10169-0 [code]
Shared representations in brains and models reveal a two-route cortical organization during scene perception.
Journal: Communications biology
In common: Hugging Face Transformers, h5py, Pillow, 9 other tools, 14 references
[4] doi:10.1371/journal.pbio.3002366 [code]
Many but not all deep neural network audio models capture brain responses and exhibit correspondence between model stages and brain regions.
Journal: PLoS biology
In common: Hugging Face Transformers, xarray, FreeSurfer, 11 other tools, 10 references
[5] doi:10.1162/imag_a_00488 [code]
Individual variation in the functional lateralization of human ventral temporal cortex: Local competition and long-range coupling.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: FreeSurfer, statsmodels, NiBabel, 6 other tools, 16 references
[6] doi:10.1038/s42003-026-09685-w [code]
Achieving more human brain-like vision via human EEG representational alignment.
Journal: Communications biology
In common: Hugging Face Transformers, xarray, h5py, 9 other tools, 11 references
[7] doi:10.1038/s41467-026-69345-9 [code]
A 7T fMRI dataset of synthetic images for out-of-distribution modeling of vision.
Journal: Nature communications
In common: FreeSurfer, h5py, Pillow, 8 other tools, 11 references, author Kendrick Kay
[8] doi:10.1038/s41467-026-70065-3 [code]
Local lateral connectivity is sufficient for replicating cortex-like topographical organization in deep neural networks.
Journal: Nature communications
In common: xarray, scikit-image, h5py, 8 other tools, 12 references
[9] doi:10.1038/s41467-024-50310-3 [code]
Modeling short visual events through the BOLD moments video fMRI dataset and metadata.
Journal: Nature communications
In common: FreeSurfer, Pillow, statsmodels, 7 other tools, 11 references, author Kendrick Kay
[10] doi:10.1038/s41562-025-02220-7 [code]
End-to-end topographic networks as models of cortical map formation and human visual behaviour.
Journal: Nature human behaviour
In common: h5py, statsmodels, seaborn, 5 other tools, 15 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1038/s41467-026-76098-y.svg)](https://openscicode.org/badge/doi/10.1038/s41467-026-76098-y)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1038/s41467-026-76098-y.svg
   :target: https://openscicode.org/badge/doi/10.1038/s41467-026-76098-y
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1038/s41467-026-76098-y"><img src="https://openscicode.org/badge/doi/10.1038/s41467-026-76098-y.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.