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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,4 @@ venv.bak/

# Visual Studio Code
.vscode/

143 changes: 125 additions & 18 deletions docs/tutorials/plot_styling.ipynb

Large diffs are not rendered by default.

14 changes: 13 additions & 1 deletion tests/test_mesh.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
import numpy as np
import pyvista as pv
from yabplot.mesh import load_nii_as_mesh, make_cortical_mesh
from yabplot.mesh import load_nii_as_mesh, make_cortical_mesh, get_region_boundaries

def test_load_nii_as_mesh(synthetic_nifti):
"""Verify that marching cubes mesh extraction works on a NIfTI volume."""
Expand All @@ -22,3 +22,15 @@ def test_make_cortical_mesh():
assert mesh.n_cells == 4
assert 'TestData' in mesh.point_data
assert np.all(mesh.point_data['TestData'] == scalars)

def test_get_region_boundaries():
"""Verify that a region border is traced between the two regions, not along mesh edges."""
plane = pv.Plane(i_size=10, j_size=10, i_resolution=10, j_resolution=10).triangulate()
verts, faces = plane.points, plane.faces.reshape(-1, 4)[:, 1:]
# region 1 ends at x=-1 and region 2 starts at x=0
labels = np.where(verts[:, 0] < -0.5, 1, 2)

lines = get_region_boundaries(verts, faces, labels)
assert lines.n_lines > 0
assert np.all((lines.points[:, 0] > -1) & (lines.points[:, 0] < 0))
assert get_region_boundaries(verts, faces, labels, region_ids=[3]) is None
13 changes: 13 additions & 0 deletions tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ def test_plot_cortical():
"""Smoke test: verify that plot_cortical renders with standard atlas."""
yab.plot_cortical(atlas='aparc', display_type='matplotlib')

def test_plot_cortical_contours():
"""Verify that contours are drawn for the selected regions and a wrong-sized mask is rejected."""
regions = yab.get_atlas_regions('aparc', 'cortical')
kwargs = dict(atlas='aparc', views=['left_lateral'], display_type='object')
without = yab.plot_cortical(**kwargs)
with_contours = yab.plot_cortical(contours=regions[:2], **kwargs)
assert len(with_contours.renderers[0].actors) == len(without.renderers[0].actors) + 1
without.close()
with_contours.close()

with pytest.raises(ValueError, match="mask length"):
yab.plot_cortical(contours=np.array([True, False]), **kwargs)

def test_plot_subcortical():
"""Smoke test: verify that plot_subcortical renders with standard atlas."""
yab.plot_subcortical(atlas='aseg', display_type='matplotlib')
Expand Down
100 changes: 100 additions & 0 deletions yabplot/mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,106 @@ def get_puzzle_pieces(v, f, raw_vals):
return base_p, pieces


def get_region_boundaries(vertices, faces, labels, values=None, include_nan=True,
region_ids=None):
"""Trace the borders between adjacent regions as a PyVista line mesh.

The borders are traced through the faces rather than along the mesh edges:
the labels are turned into smooth per-region fields (the same ones that
``proc_vertices='sharp'`` colors the surface with) and a border is placed
where the fields of two neighboring regions are equal. This gives smooth
lines that sit on the color borders of the rendered surface.

Parameters
----------
vertices : numpy.ndarray
(N, 3) float array of vertex coordinates.
faces : numpy.ndarray
(M, 3) int array of triangle face indices.
labels : numpy.ndarray
(N,) integer label array (one ID per vertex).
values : numpy.ndarray, optional
(N,) float array of mapped data values (may contain NaN). Only used
together with ``include_nan=False``.
include_nan : bool, optional
If False and ``values`` is provided, skip the borders between two
regions without data — i.e. draw outlines around regions that have
data (including their border with NaN regions) only. Default True.
region_ids : set or array-like of int, optional
If provided, only the borders of these label IDs are included. Draws
the full outline of each selected region (including its border with
unselected regions).

Returns
-------
pyvista.PolyData or None
Line mesh of the borders, or None if no borders exist.
"""
n_v = len(vertices)
u_labs, inv = np.unique(labels, return_inverse=True)
if len(u_labs) < 2:
return None

# smooth per-region fields, the same ones 'sharp' takes its colors from
masks = np.zeros((n_v, len(u_labs)))
masks[np.arange(n_v), inv] = 1.0
masks = get_smooth_masks_vectorized(faces, n_v, masks, iterations=4)
region = np.argmax(masks, axis=1)

# unique mesh edges and, for each face, the ids of its three edges
edges = np.sort(np.concatenate([faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]]), axis=1)
keys, face_edges = np.unique(edges[:, 0].astype(np.int64) * n_v + edges[:, 1], return_inverse=True)
face_edges = face_edges.reshape(3, -1).T
v0, v1 = keys // n_v, keys % n_v

# a border crosses every edge whose two ends lie in different regions,
# at the point where the fields of those two regions are equal
crossed = region[v0] != region[v1]
v0, v1 = v0[crossed], v1[crossed]
r0, r1 = region[v0], region[v1]
d0 = masks[v0, r0] - masks[v0, r1]
d1 = masks[v1, r1] - masks[v1, r0]
t = np.divide(d0, d0 + d1, out=np.full(len(d0), 0.5), where=(d0 + d1) > 0)
t = np.clip(t, 0.01, 0.99) # stay off the vertices so no segment collapses
points = vertices[v0] + t[:, None] * (vertices[v1] - vertices[v0])
pairs = np.column_stack([u_labs[r0], u_labs[r1]])

point_id = np.full(len(keys), -1)
point_id[crossed] = np.arange(len(points))
face_points = point_id[face_edges]
n_crossed = (face_points >= 0).sum(axis=1)

# two crossed edges: the border runs straight through the face
two = np.sort(face_points[n_crossed == 2], axis=1)[:, 1:]
# three crossed edges: three regions meet inside the face
three = face_points[n_crossed == 3]
center_id = len(points) + np.arange(len(three))
points = np.vstack([points, points[three].mean(axis=1)])
segments = np.vstack([two] + [np.column_stack([three[:, k], center_id]) for k in range(3)])
seg_pairs = np.vstack([pairs[two[:, 0]]] + [pairs[three[:, k]] for k in range(3)])

# optionally restrict to the borders of the requested region IDs
keep = np.ones(len(segments), dtype=bool)
if region_ids is not None:
keep &= np.isin(seg_pairs, list(region_ids)).any(axis=1)

# optionally skip the borders between two regions without data
if not include_nan and values is not None:
has_data = np.unique(labels[~np.isnan(values)])
keep &= np.isin(seg_pairs, has_data).any(axis=1)

segments = segments[keep]
if len(segments) == 0:
return None

# drop the points that are not used anymore
used, segments = np.unique(segments, return_inverse=True)
segments = segments.reshape(-1, 2)
lines = np.column_stack([np.full(len(segments), 2), segments]).ravel()

return pv.PolyData(points[used], lines=lines)


def lines_from_streamlines(streamlines):
if len(streamlines) == 0: return np.array([]), np.array([]), np.array([])

Expand Down
142 changes: 138 additions & 4 deletions yabplot/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from .mesh import (
map_values_to_surface, get_puzzle_pieces, apply_internal_blur,
apply_dilation, get_smooth_mask, lines_from_streamlines,
make_cortical_mesh, load_bmesh, extract_polydata
make_cortical_mesh, load_bmesh, extract_polydata, get_region_boundaries
)

from .scene import (
Expand All @@ -35,11 +35,111 @@
)


def _build_contour_layers(contours, lh_v, lh_f, rh_v, rh_f,
tar_labels, lh_vals_raw, rh_vals_raw,
lut_ids, lut_names, n_lh):
"""Build a list of (lh_mesh, rh_mesh, kwargs) contour render layers.

``contours`` accepts:
- ``True``: all regions, default style.
- style-dict (values are primitives): all regions, custom style.
- list / bool ndarray: those regions, default style.
- region-dict (all values are dicts): per-region style for listed regions only.

The lines are drawn as thin tubes (``line_width`` is their diameter in mm), so
they look the same in every display mode and figure size.
"""
_BASE = {'color': 'black', 'line_width': 1.0, 'opacity': 1.0, 'include_nan': True,
'lighting': False}

# a single region name
if isinstance(contours, str):
contours = [contours]

# name → label-ID lookup (lut_names is a dense list indexed by label ID)
name_to_id = {name: lid for lid, name in enumerate(lut_names)
if name and name != 'Unknown'}

def _pop_include_nan(d):
d = d.copy()
return d.pop('include_nan', _BASE['include_nan']), d

def _names_to_ids(names):
unknown = [str(n) for n in names if n not in name_to_id]
if unknown:
warnings.warn(f"contours: ignoring region names that are not in the atlas: {unknown}")
return {name_to_id[n] for n in names if n in name_to_id}

is_region_dict = (isinstance(contours, dict) and
bool(contours) and
all(isinstance(v, dict) for v in contours.values()))

if isinstance(contours, dict) and not is_region_dict and any(isinstance(v, dict) for v in contours.values()):
raise ValueError(
"contours dict must be either a style dict (e.g. {'color': 'white'}) or a dict "
"of region names mapped to style dicts, not a mix of both."
)

if contours is True:
inc_nan, pv_kw = _pop_include_nan(_BASE.copy())
groups = [(None, inc_nan, pv_kw)]

elif isinstance(contours, dict) and not is_region_dict:
inc_nan, pv_kw = _pop_include_nan({**_BASE, **contours})
groups = [(None, inc_nan, pv_kw)]

elif is_region_dict:
from collections import defaultdict
base_inc_nan, base_pv = _pop_include_nan(_BASE.copy())
kwargs_groups = defaultdict(list)
_names_to_ids(contours) # warns about names that are not in the atlas
for rname, rkwargs in contours.items():
inc_nan, pv_kw = _pop_include_nan({**base_pv, 'include_nan': base_inc_nan, **rkwargs})
key = (tuple(sorted(pv_kw.items())), inc_nan)
rid = name_to_id.get(rname)
if rid is not None:
kwargs_groups[key].append(rid)
groups = [(set(ids), inc_nan, dict(kw)) for (kw, inc_nan), ids in kwargs_groups.items()]

else:
# list of names or boolean mask
inc_nan, pv_kw = _pop_include_nan(_BASE.copy())
cr = np.asarray(contours)
if cr.dtype == bool:
if len(cr) != len(lut_ids):
raise ValueError(
f"Contours mask length mismatch! The atlas LUT defines {len(lut_ids)} regions, "
f"but the mask has {len(cr)}."
)
region_ids = {int(i) for i in lut_ids[cr]}
else:
region_ids = _names_to_ids(cr)
groups = [(region_ids, inc_nan, pv_kw)]

layers = []
for region_ids_set, inc_nan, pv_kw in groups:
pv_kw = pv_kw.copy()
radius = pv_kw.pop('line_width') / 2
lh_c = get_region_boundaries(lh_v, lh_f, tar_labels[:n_lh],
values=lh_vals_raw, include_nan=inc_nan,
region_ids=region_ids_set)
rh_c = get_region_boundaries(rh_v, rh_f, tar_labels[n_lh:],
values=rh_vals_raw, include_nan=inc_nan,
region_ids=region_ids_set)
# thin tubes instead of pixel-wide lines, so the width scales with the brain
lh_c, rh_c = [c if c is None else c.strip().tube(radius=radius, n_sides=8)
for c in (lh_c, rh_c)]
if lh_c is not None or rh_c is not None:
layers.append((lh_c, rh_c, pv_kw))
return layers


def _render_cortical_views(lh_v, lh_f, lh_vals, rh_v, rh_f, rh_vals, is_cat,
ax, cbar_kwargs,
views, layout, figsize, cmap, vminmax, nan_color,
style, zoom, proc_vertices, display_type, export_path,
lut_colors=None, max_id=None):
lut_colors=None, max_id=None,
contour_layers=None):
"""Internal helper to render cortical data."""

# setup colors and vminmax
Expand Down Expand Up @@ -109,6 +209,15 @@ def _render_cortical_views(lh_v, lh_f, lh_vals, rh_v, rh_f, rh_vals, is_cat,
)
if scalar_bar_mapper is None: scalar_bar_mapper = actor.mapper

# draw region boundary contours if requested
if contour_layers:
for lh_c, rh_c, ckw in contour_layers:
for c_mesh, side_key in [(lh_c, 'L'), (rh_c, 'R')]:
if c_mesh is None:
continue
if cfg['side'] in [side_key, 'both']:
plotter.add_mesh(c_mesh, **ckw)

set_camera(plotter, cfg, zoom=zoom)
plotter.hide_axes()

Expand Down Expand Up @@ -142,7 +251,7 @@ def get_base_name(name):
def plot_cortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None,
bmesh='midthickness', figsize=None, cmap='coolwarm', vminmax=[None, None],
nan_color=(1.0, 1.0, 1.0), style='default', zoom=1.2, proc_vertices='sharp',
display_type='matplotlib', export_path=None):
display_type='matplotlib', export_path=None, contours=False):
"""
Visualize data on the cortical surface using a specified atlas.

Expand Down Expand Up @@ -196,6 +305,20 @@ def plot_cortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_k
'object': returns the raw pyvista plotter object.
export_path : str, optional
If provided, saves the final figure to this path (e.g., 'figure.png').
contours : bool, dict, list, str, or numpy.ndarray, optional
Draw boundary lines between atlas regions. Default ``False``. Four forms:

- ``True``: all regions, default style (black, 1.5 mm wide, opaque).
- **style dict** (values are primitives): all regions, custom style.
Keys: ``color``, ``line_width`` (width in mm on the surface, default ``1.5``),
``opacity``, ``include_nan``.
``include_nan=False`` suppresses borders between two NaN regions while
keeping outlines around regions that have data. Default ``True``.
- **list** of region name strings (or a single name) or **bool ndarray**
(one value per region, in the same order as array ``data``):
those regions only, default style.
- **region dict** (values are dicts): only the listed regions, each
style dict merged with the global defaults. Same keys as style dict.

Returns
-------
Expand Down Expand Up @@ -231,11 +354,22 @@ def plot_cortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_k
lh_vals_raw = all_vals[:len(lh_v)]
rh_vals_raw = all_vals[len(lh_v):]

# compute region boundary contours
contour_layers = None
if contours is not False and contours is not None:
n_lh = len(lh_v)
contour_layers = _build_contour_layers(
contours, lh_v, lh_f, rh_v, rh_f,
tar_labels, lh_vals_raw, rh_vals_raw,
lut_ids, lut_names, n_lh
)

# render
return _render_cortical_views(
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, proc_vertices, display_type, export_path, lut_colors, max_id
zoom, proc_vertices, display_type, export_path, lut_colors, max_id,
contour_layers
)


Expand Down
Loading