Marlin Lee commited on
Commit
cc9ff34
·
1 Parent(s): 2f91961

Add pyvista renderer, precomputed phi map cache, and background-thread steering brain renders

Browse files
scripts/explorer/brain.py CHANGED
@@ -17,9 +17,10 @@ import numpy as np
17
 
18
  from .args import args
19
 
20
- # ---------- Nilearn surface rendering (TribeV2-style) ----------
21
 
22
  _NILEARN_AVAILABLE = False
 
23
  _fsavg5 = None # cached fsaverage5 surface data
24
  _fsavg5_tree = None # cached KDTree over pial-left coords
25
  _fsavg5_pials = None # cached (pial_left_xyz, pial_right_xyz)
@@ -27,12 +28,24 @@ _fsavg5_pials = None # cached (pial_left_xyz, pial_right_xyz)
27
  try:
28
  import nibabel as _nib
29
  from nilearn.datasets import fetch_surf_fsaverage as _fetch_surf_fsaverage
30
- from nilearn.plotting import plot_surf_stat_map as _plot_surf_stat_map
31
  from scipy.spatial import cKDTree as _cKDTree
32
  _NILEARN_AVAILABLE = True
33
  except ImportError:
34
  pass
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  def _get_fsavg5():
38
  global _fsavg5, _fsavg5_pials, _fsavg5_tree
@@ -41,7 +54,7 @@ def _get_fsavg5():
41
  pl = _nib.load(_fsavg5['pial_left']).darrays[0].data
42
  pr = _nib.load(_fsavg5['pial_right']).darrays[0].data
43
  _fsavg5_pials = (pl, pr)
44
- _fsavg5_tree = None # built on first render, needs voxel coords
45
  return _fsavg5
46
 
47
 
@@ -82,40 +95,171 @@ def _voxels_to_surface(values: np.ndarray, coords: np.ndarray,
82
  return textures[0], textures[1]
83
 
84
 
85
- def _render_brain_surface_b64(values: np.ndarray, title: str = '',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  compact: bool = False, cbar_label: str = '',
87
  figsize=(12, 3.5), dpi=80) -> str | None:
88
- """Render voxel values on fsaverage5 cortical surface (TribeV2-style).
89
-
90
- Uses KDTree IDW to project values onto pial vertices, then renders with
91
- nilearn's plot_surf_stat_map on the inflated fsaverage5 mesh.
92
- compact=True → single left-posterior view; False → 4-view (lat+med, both hemis).
93
- Returns base64 PNG or None if nilearn unavailable.
94
- """
95
  if not _NILEARN_AVAILABLE or _voxel_coords is None:
96
  return None
 
 
 
 
 
97
  fs = _get_fsavg5()
98
  tex_l, tex_r = _voxels_to_surface(values, _voxel_coords)
99
- # Percentile-based vmax stretches the colormap over actual signal range
100
  vmax = float(np.nanpercentile(np.abs(values), 98)) or 1e-6
101
- # bg_on_data=True keeps sulcal texture visible everywhere — looks like a brain
102
  kwargs = dict(cmap='RdBu_r', colorbar=False, vmin=-vmax, vmax=vmax,
103
  bg_on_data=True)
104
 
105
- # Views chosen to maximise visual cortex visibility (NSD = occipital / posterior)
106
- # (elev, azim) follow TribeV2 VIEW_DICT convention
107
  _VIEWS_FULL = [
108
- (tex_l, 'infl_left', 'sulc_left', 'left', (0, -135)), # L posterior-lateral
109
- (tex_l, 'infl_left', 'sulc_left', 'left', (0, 0)), # L medial
110
- (tex_r, 'infl_right', 'sulc_right', 'right', (0, 180)), # R medial
111
- (tex_r, 'infl_right', 'sulc_right', 'right', (0, -45)), # R posterior-lateral
112
  ]
113
 
114
  if compact:
115
  fig, ax = plt.subplots(1, 1, figsize=(3.5, 2.8),
116
  subplot_kw={'projection': '3d'},
117
  facecolor='#f8f8f8')
118
- # Posterior view of left hemisphere shows occipital cortex directly
119
  _plot_surf_stat_map(surf_mesh=fs['infl_left'], stat_map=tex_l,
120
  bg_map=fs['sulc_left'], hemi='left', view=(0, -135),
121
  axes=ax, figure=fig, **kwargs)
@@ -148,6 +292,25 @@ def _render_brain_surface_b64(values: np.ndarray, title: str = '',
148
  return base64.b64encode(buf.getvalue()).decode('utf-8')
149
 
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  # ---------- Phi (brain alignment) ----------
152
 
153
  _phi_cv = None # (C, V) concept-by-voxel matrix, memory-mapped
@@ -335,6 +498,10 @@ def dynadiff_request(sample_idx: int, steerings: list, seed: int) -> dict:
335
 
336
  def _render_phi_map_b64_compact(feat: int, figsize=(3.5, 2.8), dpi=70) -> str | None:
337
  """Single left-lateral surface view of phi, small enough for a steering card."""
 
 
 
 
338
  phi_vox = phi_voxel_row(feat)
339
  if phi_vox is None:
340
  return None
 
17
 
18
  from .args import args
19
 
20
+ # ---------- Surface rendering ----------
21
 
22
  _NILEARN_AVAILABLE = False
23
+ _PYVISTA_AVAILABLE = False
24
  _fsavg5 = None # cached fsaverage5 surface data
25
  _fsavg5_tree = None # cached KDTree over pial-left coords
26
  _fsavg5_pials = None # cached (pial_left_xyz, pial_right_xyz)
 
28
  try:
29
  import nibabel as _nib
30
  from nilearn.datasets import fetch_surf_fsaverage as _fetch_surf_fsaverage
 
31
  from scipy.spatial import cKDTree as _cKDTree
32
  _NILEARN_AVAILABLE = True
33
  except ImportError:
34
  pass
35
 
36
+ try:
37
+ import pyvista as _pv
38
+ _pv.OFF_SCREEN = True
39
+ _PYVISTA_AVAILABLE = True
40
+ except ImportError:
41
+ pass
42
+
43
+ if not _PYVISTA_AVAILABLE:
44
+ try:
45
+ from nilearn.plotting import plot_surf_stat_map as _plot_surf_stat_map
46
+ except ImportError:
47
+ pass
48
+
49
 
50
  def _get_fsavg5():
51
  global _fsavg5, _fsavg5_pials, _fsavg5_tree
 
54
  pl = _nib.load(_fsavg5['pial_left']).darrays[0].data
55
  pr = _nib.load(_fsavg5['pial_right']).darrays[0].data
56
  _fsavg5_pials = (pl, pr)
57
+ _fsavg5_tree = None
58
  return _fsavg5
59
 
60
 
 
95
  return textures[0], textures[1]
96
 
97
 
98
+ # ---------- PyVista surface renderer ----------
99
+
100
+ _pv_meshes = None # cached (mesh_left, mesh_right, sulc_left, sulc_right)
101
+
102
+
103
+ def _get_pv_meshes():
104
+ """Load fsaverage5 inflated meshes as pyvista PolyData (cached)."""
105
+ global _pv_meshes
106
+ if _pv_meshes is not None:
107
+ return _pv_meshes
108
+ fs = _get_fsavg5()
109
+ meshes = {}
110
+ for hemi in ('left', 'right'):
111
+ gii = _nib.load(fs[f'infl_{hemi}'])
112
+ coords = gii.darrays[0].data
113
+ faces_tri = gii.darrays[1].data.astype(np.int64)
114
+ n_faces = faces_tri.shape[0]
115
+ pv_faces = np.empty((n_faces, 4), dtype=np.int64)
116
+ pv_faces[:, 0] = 3
117
+ pv_faces[:, 1:] = faces_tri
118
+ mesh = _pv.PolyData(coords, pv_faces.ravel())
119
+ sulc = _nib.load(fs[f'sulc_{hemi}']).darrays[0].data
120
+ meshes[hemi] = (mesh, sulc)
121
+ _pv_meshes = meshes
122
+ return _pv_meshes
123
+
124
+
125
+ # Camera positions: (position, focal_point, viewup)
126
+ # Matched to the nilearn (elev, azim) views for visual cortex visibility
127
+ _PV_VIEWS = {
128
+ 'L_post_lat': {'position': (-100, -100, 30), 'focal_point': (0, 0, 0), 'viewup': (0, 0, 1)},
129
+ 'L_medial': {'position': (100, 0, 30), 'focal_point': (0, 0, 0), 'viewup': (0, 0, 1)},
130
+ 'R_medial': {'position': (-100, 0, 30), 'focal_point': (0, 0, 0), 'viewup': (0, 0, 1)},
131
+ 'R_post_lat': {'position': (100, -100, 30), 'focal_point': (0, 0, 0), 'viewup': (0, 0, 1)},
132
+ }
133
+
134
+
135
+ def _render_pv_single(mesh, sulc, tex, vmax, cam, size=(350, 280)):
136
+ """Render a single hemisphere view with pyvista, return RGBA numpy array."""
137
+ p = _pv.Plotter(off_screen=True, window_size=size)
138
+ p.set_background('#f8f8f8')
139
+
140
+ # Sulcal depth as grey background shading
141
+ sulc_norm = np.clip(sulc, -2, 2)
142
+ sulc_grey = 0.55 - 0.15 * (sulc_norm / 2.0)
143
+ sulc_rgb = np.column_stack([sulc_grey, sulc_grey, sulc_grey])
144
+ bg_mesh = mesh.copy()
145
+ bg_mesh.point_data['sulc_rgb'] = sulc_rgb
146
+ p.add_mesh(bg_mesh, scalars='sulc_rgb', rgb=True,
147
+ lighting=True, opacity=1.0)
148
+
149
+ # Stat map overlay — only show non-NaN vertices
150
+ valid = ~np.isnan(tex)
151
+ if valid.any():
152
+ overlay = mesh.copy()
153
+ overlay.point_data['stat'] = np.where(valid, tex, 0.0)
154
+ # Opacity proportional to absolute value
155
+ abs_tex = np.abs(np.where(valid, tex, 0.0))
156
+ alpha = np.where(valid, np.clip(abs_tex / vmax, 0.15, 1.0), 0.0)
157
+ overlay.point_data['alpha'] = alpha
158
+ p.add_mesh(overlay, scalars='stat', cmap='RdBu_r',
159
+ clim=[-vmax, vmax], opacity=alpha,
160
+ show_scalar_bar=False, lighting=True)
161
+
162
+ p.camera_position = [cam['position'], cam['focal_point'], cam['viewup']]
163
+ img = p.screenshot(return_img=True)
164
+ p.close()
165
+ return img
166
+
167
+
168
+ def _render_brain_pyvista_b64(values: np.ndarray, title: str = '',
169
+ compact: bool = False,
170
+ cbar_label: str = '') -> str | None:
171
+ """Render voxel values on fsaverage5 with pyvista (fast offscreen VTK)."""
172
+ if not _PYVISTA_AVAILABLE or not _NILEARN_AVAILABLE or _voxel_coords is None:
173
+ return None
174
+ try:
175
+ meshes = _get_pv_meshes()
176
+ except Exception:
177
+ return None
178
+
179
+ tex_l, tex_r = _voxels_to_surface(values, _voxel_coords)
180
+ vmax = float(np.nanpercentile(np.abs(values), 98)) or 1e-6
181
+
182
+ from PIL import Image as _PILImg
183
+
184
+ if compact:
185
+ mesh_l, sulc_l = meshes['left']
186
+ img = _render_pv_single(mesh_l, sulc_l, tex_l, vmax,
187
+ _PV_VIEWS['L_post_lat'], size=(350, 280))
188
+ pil = _PILImg.fromarray(img)
189
+ else:
190
+ views = [
191
+ ('left', tex_l, 'L_post_lat'),
192
+ ('left', tex_l, 'L_medial'),
193
+ ('right', tex_r, 'R_medial'),
194
+ ('right', tex_r, 'R_post_lat'),
195
+ ]
196
+ panels = []
197
+ for hemi, tex, view_key in views:
198
+ mesh, sulc = meshes[hemi]
199
+ panel = _render_pv_single(mesh, sulc, tex, vmax,
200
+ _PV_VIEWS[view_key], size=(300, 250))
201
+ panels.append(_PILImg.fromarray(panel))
202
+
203
+ # Composite 4 panels into one image
204
+ pw, ph = panels[0].size
205
+ canvas = _PILImg.new('RGB', (pw * 4, ph), color=(248, 248, 248))
206
+ for i, panel in enumerate(panels):
207
+ canvas.paste(panel, (i * pw, 0))
208
+ pil = canvas
209
+
210
+ if title:
211
+ # Draw title using matplotlib (lightweight, just text)
212
+ fig, ax = plt.subplots(figsize=(pil.width / 100, 0.3), facecolor='#f8f8f8')
213
+ ax.text(0.5, 0.5, title, ha='center', va='center', fontsize=10,
214
+ transform=ax.transAxes)
215
+ ax.set_axis_off()
216
+ title_buf = io.BytesIO()
217
+ fig.savefig(title_buf, format='png', dpi=100, bbox_inches='tight',
218
+ facecolor='#f8f8f8')
219
+ plt.close(fig)
220
+ title_buf.seek(0)
221
+ title_img = _PILImg.open(title_buf)
222
+ final = _PILImg.new('RGB', (pil.width, pil.height + title_img.height),
223
+ color=(248, 248, 248))
224
+ final.paste(title_img, ((pil.width - title_img.width) // 2, 0))
225
+ final.paste(pil, (0, title_img.height))
226
+ pil = final
227
+
228
+ buf = io.BytesIO()
229
+ pil.save(buf, format='PNG')
230
+ return base64.b64encode(buf.getvalue()).decode('utf-8')
231
+
232
+
233
+ # ---------- Nilearn fallback renderer ----------
234
+
235
+ def _render_brain_nilearn_b64(values: np.ndarray, title: str = '',
236
  compact: bool = False, cbar_label: str = '',
237
  figsize=(12, 3.5), dpi=80) -> str | None:
238
+ """Render with nilearn's plot_surf_stat_map (slower matplotlib 3D fallback)."""
 
 
 
 
 
 
239
  if not _NILEARN_AVAILABLE or _voxel_coords is None:
240
  return None
241
+ try:
242
+ _plot_surf_stat_map
243
+ except NameError:
244
+ return None
245
+
246
  fs = _get_fsavg5()
247
  tex_l, tex_r = _voxels_to_surface(values, _voxel_coords)
 
248
  vmax = float(np.nanpercentile(np.abs(values), 98)) or 1e-6
 
249
  kwargs = dict(cmap='RdBu_r', colorbar=False, vmin=-vmax, vmax=vmax,
250
  bg_on_data=True)
251
 
 
 
252
  _VIEWS_FULL = [
253
+ (tex_l, 'infl_left', 'sulc_left', 'left', (0, -135)),
254
+ (tex_l, 'infl_left', 'sulc_left', 'left', (0, 0)),
255
+ (tex_r, 'infl_right', 'sulc_right', 'right', (0, 180)),
256
+ (tex_r, 'infl_right', 'sulc_right', 'right', (0, -45)),
257
  ]
258
 
259
  if compact:
260
  fig, ax = plt.subplots(1, 1, figsize=(3.5, 2.8),
261
  subplot_kw={'projection': '3d'},
262
  facecolor='#f8f8f8')
 
263
  _plot_surf_stat_map(surf_mesh=fs['infl_left'], stat_map=tex_l,
264
  bg_map=fs['sulc_left'], hemi='left', view=(0, -135),
265
  axes=ax, figure=fig, **kwargs)
 
292
  return base64.b64encode(buf.getvalue()).decode('utf-8')
293
 
294
 
295
+ # ---------- Unified dispatch ----------
296
+
297
+ def _render_brain_surface_b64(values: np.ndarray, title: str = '',
298
+ compact: bool = False, cbar_label: str = '',
299
+ figsize=(12, 3.5), dpi=80) -> str | None:
300
+ """Render voxel values on fsaverage5 cortical surface.
301
+
302
+ Tries pyvista (fast VTK offscreen) first, falls back to nilearn (matplotlib 3D).
303
+ Returns base64 PNG or None.
304
+ """
305
+ b64 = _render_brain_pyvista_b64(values, title=title, compact=compact,
306
+ cbar_label=cbar_label)
307
+ if b64 is not None:
308
+ return b64
309
+ return _render_brain_nilearn_b64(values, title=title, compact=compact,
310
+ cbar_label=cbar_label, figsize=figsize,
311
+ dpi=dpi)
312
+
313
+
314
  # ---------- Phi (brain alignment) ----------
315
 
316
  _phi_cv = None # (C, V) concept-by-voxel matrix, memory-mapped
 
498
 
499
  def _render_phi_map_b64_compact(feat: int, figsize=(3.5, 2.8), dpi=70) -> str | None:
500
  """Single left-lateral surface view of phi, small enough for a steering card."""
501
+ from .state import active_ds
502
+ cached = active_ds().get('phi_map_cache', {}).get(feat)
503
+ if cached is not None:
504
+ return cached
505
  phi_vox = phi_voxel_row(feat)
506
  if phi_vox is None:
507
  return None
scripts/explorer/datasets.py CHANGED
@@ -180,6 +180,16 @@ def _load_dataset(path: str, label: str, *,
180
  entry['heatmap_patch_grid'] = d.get('patch_grid', 16)
181
  has_hm = 'no'
182
 
 
 
 
 
 
 
 
 
 
 
183
  has_clip = 'yes' if entry['clip_embeds'] is not None else 'no'
184
  print(f" d={d_model}, n={entry['n_images']}, backbone={entry['backbone']}, "
185
  f"clip={has_clip}, heatmaps={has_hm}")
 
180
  entry['heatmap_patch_grid'] = d.get('patch_grid', 16)
181
  has_hm = 'no'
182
 
183
+ # Brain render sidecar (precomputed compact phi map PNGs)
184
+ brain_render_sidecar = stem + '_brain_renders.pt'
185
+ if os.path.exists(brain_render_sidecar):
186
+ print(f" Loading brain render sidecar {os.path.basename(brain_render_sidecar)} ...")
187
+ br = torch.load(brain_render_sidecar, map_location='cpu', weights_only=False)
188
+ entry['phi_map_cache'] = {int(k): v for k, v in br.items()}
189
+ print(f" Cached {len(entry['phi_map_cache'])} phi map renders")
190
+ else:
191
+ entry['phi_map_cache'] = {}
192
+
193
  has_clip = 'yes' if entry['clip_embeds'] is not None else 'no'
194
  print(f" d={d_model}, n={entry['n_images']}, backbone={entry['backbone']}, "
195
  f"clip={has_clip}, heatmaps={has_hm}")
scripts/explorer/panels/steering.py CHANGED
@@ -307,18 +307,31 @@ if HAS_DYNADIFF:
307
  list(_dd_source.data['lam']),
308
  list(_dd_source.data['threshold']))
309
 
 
 
310
  def _update_steer_brain():
311
  feats, lams, thrs = _steerings_from_source()
312
  if not feats:
313
  steer_brain_div.text = ''
314
  return
315
- combined = compute_steering_direction(feats, lams, thrs)
316
- b64 = render_fmri_brain_compact_b64(
317
- combined, 'Steering Direction (φ sum)')
318
- steer_brain_div.text = (
319
- f'<img src="data:image/png;base64,{b64}" '
320
- f'style="max-width:100%"/>'
321
- if b64 else '')
 
 
 
 
 
 
 
 
 
 
 
322
 
323
  def _update_steered_brain():
324
  fmri = _Session.gt_fmri
@@ -329,13 +342,21 @@ if HAS_DYNADIFF:
329
  if not feats:
330
  steered_brain_div.text = ''
331
  return
332
- steered = compute_steered_fmri(fmri, feats, lams, thrs)
333
- b64 = render_fmri_brain_compact_b64(
334
- steered, 'Expected Steered Brain')
335
- steered_brain_div.text = (
336
- f'<img src="data:image/png;base64,{b64}" '
337
- f'style="max-width:100%"/>'
338
- if b64 else '')
 
 
 
 
 
 
 
 
339
 
340
  def _update_active_tiles():
341
  feats = list(_dd_source.data['feat'])
 
307
  list(_dd_source.data['lam']),
308
  list(_dd_source.data['threshold']))
309
 
310
+ _steer_render_token = [0] # mutable counter to discard stale renders
311
+
312
  def _update_steer_brain():
313
  feats, lams, thrs = _steerings_from_source()
314
  if not feats:
315
  steer_brain_div.text = ''
316
  return
317
+ _steer_render_token[0] += 1
318
+ my_token = _steer_render_token[0]
319
+ steer_brain_div.text = ''
320
+ doc = curdoc()
321
+
322
+ def _bg():
323
+ combined = compute_steering_direction(feats, lams, thrs)
324
+ b64 = render_fmri_brain_compact_b64(
325
+ combined, 'Steering Direction (φ sum)')
326
+ def _apply():
327
+ if _steer_render_token[0] == my_token:
328
+ steer_brain_div.text = (
329
+ f'<img src="data:image/png;base64,{b64}" '
330
+ f'style="max-width:100%"/>'
331
+ if b64 else '')
332
+ doc.add_next_tick_callback(_apply)
333
+
334
+ threading.Thread(target=_bg, daemon=True).start()
335
 
336
  def _update_steered_brain():
337
  fmri = _Session.gt_fmri
 
342
  if not feats:
343
  steered_brain_div.text = ''
344
  return
345
+ steered_brain_div.text = ''
346
+ doc = curdoc()
347
+
348
+ def _bg():
349
+ steered = compute_steered_fmri(fmri, feats, lams, thrs)
350
+ b64 = render_fmri_brain_compact_b64(
351
+ steered, 'Expected Steered Brain')
352
+ def _apply():
353
+ steered_brain_div.text = (
354
+ f'<img src="data:image/png;base64,{b64}" '
355
+ f'style="max-width:100%"/>'
356
+ if b64 else '')
357
+ doc.add_next_tick_callback(_apply)
358
+
359
+ threading.Thread(target=_bg, daemon=True).start()
360
 
361
  def _update_active_tiles():
362
  feats = list(_dd_source.data['feat'])