Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 58 additions & 2 deletions docs/tutorials/plotting_vertexwise.ipynb

Large diffs are not rendered by default.

39 changes: 39 additions & 0 deletions tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,45 @@ def test_plot_vertexwise():
rh['Data'] = np.random.rand(rh.n_points)
yab.plot_vertexwise(lh, rh, display_type='matplotlib')

def _label_colors(plotter, labels):
"""Return the RGB color each label value is drawn with in the first view."""
actor = next(a for a in plotter.renderers[0].actors.values() if getattr(a, 'mapper', None) is not None)
table = actor.mapper.GetLookupTable()
colors = {}
for label in labels:
rgb = [0.0, 0.0, 0.0]
table.GetColor(float(label), rgb)
colors[label] = rgb
plotter.close()
return colors

@pytest.mark.parametrize("proc_vertices", ['sharp', None])
@pytest.mark.parametrize("dtype", [int, float])
def test_plot_vertexwise_lut(dtype, proc_vertices):
"""Verify that label i is colored with lut[i], also when the lut has unused entries."""
lut = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (0, 1, 1)]
lh = pv.Sphere()
rh = pv.Sphere()
# only labels 1-3 are present while the lut goes up to 5
lh['Data'] = np.resize([1, 2, 3], lh.n_points).astype(dtype)
rh['Data'] = np.resize([1, 2, 3], rh.n_points).astype(dtype)
plotter = yab.plot_vertexwise(lh, rh, lut=lut, proc_vertices=proc_vertices,
views=['left_lateral'], display_type='object')
colors = _label_colors(plotter, [1, 2, 3])
for label in [1, 2, 3]:
assert np.allclose(colors[label], lut[label])

def test_plot_vertexwise_integer_data_stays_continuous():
"""Verify that integer data without a lut is still drawn with the colormap."""
lh = pv.Sphere()
rh = pv.Sphere()
lh['Data'] = np.resize([0, 1], lh.n_points)
rh['Data'] = np.resize([0, 1], rh.n_points)
plotter = yab.plot_vertexwise(lh, rh, cmap='Reds', views=['left_lateral'], display_type='object')
colors = _label_colors(plotter, [0, 1])
assert np.allclose(colors[0], plt.get_cmap('Reds')(0.0)[:3], atol=0.01)
assert np.allclose(colors[1], plt.get_cmap('Reds')(1.0)[:3], atol=0.01)

def test_plot_voxelwise(synthetic_nifti):
"""Smoke test: verify that plot_voxelwise renders with synthetic volume."""
yab.plot_voxelwise(synthetic_nifti, threshold=5.0, blur_sigma=0, display_type='matplotlib')
Expand Down
43 changes: 40 additions & 3 deletions yabplot/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def plot_cortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_k

def plot_vertexwise(lh, rh, scalars='Data', ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None,
cmap='coolwarm', vminmax=[None, None], nan_color=(1.0, 1.0, 1.0), style='default', zoom=1.2,
display_type='matplotlib', export_path=None):
display_type='matplotlib', export_path=None, lut=None, proc_vertices='sharp'):
"""
Visualize arbitrary per-vertex scalar data on a user-supplied brain mesh.

Expand Down Expand Up @@ -269,6 +269,17 @@ def plot_vertexwise(lh, rh, scalars='Data', ax=None, cbar_kwargs=None, views=Non
'object': returns the raw pyvista plotter object.
export_path : str, optional
If provided, saves the figure to this path.
lut : list, numpy.ndarray or 'auto', optional
Lookup table for categorical data (e.g., labels or clusters), where ``lut[i]``
is the color of label ``i``. Label 0 is treated as background and drawn with
`nan_color`, so ``lut[0]`` is not used. If 'auto', a distinct color is generated
for each label. When provided, `cmap` and `vminmax` are ignored and no colorbar
is drawn. Default is None (data is treated as continuous).
proc_vertices : str or None, optional
Whether to process the vertices edges between labels. Only used when `lut` is
provided (continuous data is always plotted as is).
Set to None to not perform.
'sharp': Applies sharpening of the resolution of different color vertices (default).

Returns
-------
Expand Down Expand Up @@ -297,6 +308,9 @@ def plot_vertexwise(lh, rh, scalars='Data', ax=None, cbar_kwargs=None, views=Non
>>> lh['thickness'] = lh_thick_array
>>> rh['thickness'] = rh_thick_array
>>> plot_vertexwise(lh, rh, scalars='thickness', cmap='inferno')
>>>
>>> # If your data are labels (e.g., clusters 1 and 2), color label i with lut[i]
>>> plot_vertexwise(lh, rh, scalars='clusters', lut=['white', 'red', 'blue'])
"""

# extract v, f, raw from PyVista meshes
Expand All @@ -305,11 +319,34 @@ def plot_vertexwise(lh, rh, scalars='Data', ax=None, cbar_kwargs=None, views=Non
rh_v, rh_f = extract_polydata(rh)
rh_vals_raw = rh[scalars]

# categorical mode is opt-in: label i is colored with lut[i]
is_cat = lut is not None
max_id = None
if is_cat:
# labels must be whole numbers (NaN is allowed and treated as background)
labels = np.concatenate([lh_vals_raw, rh_vals_raw])
labels = labels[~np.isnan(labels)]
if not np.all(labels == np.round(labels)):
raise ValueError("lut requires whole-number labels (e.g., 0, 1, 2) but data contains other values.")
max_label = int(labels.max()) if labels.size else 0
if isinstance(lut, str) and lut == 'auto':
lut = generate_distinct_colors(max_label + 1, seed=42)
if max_label >= len(lut):
raise ValueError(f"lut has {len(lut)} colors but data contains label {max_label}.")
# color range must span the whole lut (not the data) to keep label i on lut[i]
max_id = len(lut) - 1
# 'blur' mixes neighbouring label ids, which would draw wrong labels on the edges
if proc_vertices not in ('sharp', None):
raise ValueError("proc_vertices must be 'sharp' or None.")
else:
# edge processing works per label, so continuous data is plotted as is
proc_vertices = None

# render
return _render_cortical_views(
lh_v, lh_f, lh_vals_raw, rh_v, rh_f, rh_vals_raw, False, ax, cbar_kwargs,
lh_v, lh_f, lh_vals_raw, rh_v, rh_f, rh_vals_raw, is_cat, ax, cbar_kwargs,
views, layout, figsize, cmap, vminmax, nan_color, style,
zoom, None, display_type, export_path
zoom, proc_vertices, display_type, export_path, lut_colors=lut, max_id=max_id
)


Expand Down
Loading