diff --git a/tests/test_plotting.py b/tests/test_plotting.py index b4d7966..9e58009 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -4,6 +4,7 @@ import matplotlib.pyplot as plt import yabplot as yab import pyvista as pv +from yabplot.plotting import get_base_name # tell PyVista to run in "off-screen" mode so it doesn't try to open a real window pv.OFF_SCREEN = True @@ -91,3 +92,166 @@ def test_export_path(tmp_path): yab.plot_cortical(atlas='aparc', display_type='matplotlib', export_path=str(out_file)) assert out_file.exists() assert out_file.stat().st_size > 0 + + +# --- get_base_name unit tests --- + +@pytest.mark.parametrize("name,expected", [ + # suffix patterns + ("putamen_l", "putamen"), + ("putamen_L", "putamen"), + ("Putamen_r", "Putamen"), + ("hippocampus-lh", "hippocampus"), + ("hippocampus-rh", "hippocampus"), + # prefix patterns + ("l-thalamus", "thalamus"), + ("r-thalamus", "thalamus"), + ("L_Thalamus", "Thalamus"), + ("R_Thalamus", "Thalamus"), + # word prefix patterns + ("left_caudate", "caudate"), + ("right_caudate", "caudate"), + ("left-amygdala", "amygdala"), + ("right-amygdala", "amygdala"), + # no hemisphere tag — returned as-is + ("brainstem", "brainstem"), + ("cerebellum", "cerebellum"), +]) +def test_get_base_name(name, expected): + assert get_base_name(name) == expected + + +# --- shared_hemisphere_colors behavioral tests --- + +def _count_unique_region_colors(shared_hemisphere_colors): + """Helper: run plot_subcortical and return the count of unique region colors.""" + from unittest.mock import patch + + captured = {} + original_add_mesh = pv.Plotter.add_mesh + + def recording_add_mesh(self, mesh, **kwargs): + color = kwargs.get('color') + if color is not None: + captured[id(mesh)] = color + return original_add_mesh(self, mesh, **kwargs) + + with patch.object(pv.Plotter, 'add_mesh', recording_add_mesh): + yab.plot_subcortical( + atlas='aseg', display_type='matplotlib', shared_hemisphere_colors=shared_hemisphere_colors + ) + + return len(set( + c if not isinstance(c, list) else tuple(c) + for c in captured.values() + )) + + +def test_subcortical_shared_hemisphere_colors_false_more_unique_than_true(): + """shared_hemisphere_colors=False (default) yields more unique colors than True.""" + unique_false = _count_unique_region_colors(shared_hemisphere_colors=False) + unique_true = _count_unique_region_colors(shared_hemisphere_colors=True) + assert unique_false > unique_true + + +def test_subcortical_shared_hemisphere_colors_smoke(): + """Smoke test: shared_hemisphere_colors=True renders without error.""" + yab.plot_subcortical(atlas='aseg', display_type='matplotlib', shared_hemisphere_colors=True) + + +def test_subcortical_atlas_color_seed_smoke(): + """Smoke test: a non-default atlas_color_seed renders without error.""" + yab.plot_subcortical(atlas='aseg', display_type='matplotlib', atlas_color_seed=7) + + +def _capture_region_colors(atlas_color_seed, cmap): + """Helper: return the per-region colors add_mesh receives, in call order.""" + from unittest.mock import patch + + captured = [] + original_add_mesh = pv.Plotter.add_mesh + + def recording_add_mesh(self, mesh, **kwargs): + color = kwargs.get('color') + if color is not None: + captured.append(tuple(color) if not isinstance(color, str) else color) + return original_add_mesh(self, mesh, **kwargs) + + with patch.object(pv.Plotter, 'add_mesh', recording_add_mesh): + yab.plot_subcortical(atlas='aseg', display_type='matplotlib', + cmap=cmap, atlas_color_seed=atlas_color_seed) + return captured + + +def test_atlas_color_seed_changes_colormap_arrangement(): + """With a colormap, different seeds produce different region color arrangements.""" + a = _capture_region_colors(42, 'viridis') + b = _capture_region_colors(7, 'viridis') + assert a and b, "no region colors were captured" + assert a != b, "different atlas_color_seed values should reshuffle colormap colors" + + +def test_subcortical_plot_regions_separately(tmp_path): + """plot_regions_separately=True writes one PNG per region+view combination.""" + yab.plot_subcortical( + atlas='aseg', + display_type='matplotlib', + plot_regions_separately=True, + export_path=str(tmp_path), + ) + png_files = list(tmp_path.glob("*.png")) + assert len(png_files) > 0, "No PNG files were written" + for f in png_files: + assert f.stat().st_size > 0, f"{f.name} is empty" + + +def test_subcortical_cmap_object_atlas_mode(): + """A Colormap object (not just a str) must work in atlas mode (data=None). + + The docstring advertises cmap as 'str or matplotlib.colors.Colormap'; passing + an object previously left color_map undefined and raised NameError. + """ + yab.plot_subcortical(atlas='aseg', display_type='matplotlib', cmap=plt.get_cmap('viridis')) + + +def test_plot_regions_separately_midline_no_collision(tmp_path): + """Midline regions must not overwrite their own left/right views. + + view_face strips 'left_'/'right_', so for a midline region (rendered in every + view) left_lateral and right_lateral would collapse to the same filename. The + fix keeps the full view name for regions without a hemisphere tag. + """ + atlas_dir = tmp_path / "atlas" + atlas_dir.mkdir() + # one midline region (no L/R token) and one lateralized region + pv.Sphere(center=(0, 0, 0)).save(str(atlas_dir / "brainstem.vtk")) + pv.Sphere(center=(-20, 0, 0)).save(str(atlas_dir / "Left-Putamen.vtk")) + + out = tmp_path / "out" + yab.plot_subcortical( + custom_atlas_path=str(atlas_dir), + display_type='matplotlib', + plot_regions_separately=True, + export_path=str(out), + views=['left_lateral', 'right_lateral'], + ) + + midline_files = sorted(f.name for f in out.glob("brainstem_*.png")) + # rendered in both lateral views -> must be two distinct files, not one overwritten + assert len(midline_files) == 2, f"midline region collided: {midline_files}" + + +def test_plot_regions_separately_displays_without_export(tmp_path, monkeypatch): + """Without export_path, per-region mode displays and returns axes, writing no files.""" + import matplotlib.axes + monkeypatch.chdir(tmp_path) + + result = yab.plot_subcortical( + atlas='aseg', display_type='matplotlib', + plot_regions_separately=True, views=['superior'], + ) + + assert isinstance(result, list) and len(result) > 0 + assert all(isinstance(a, matplotlib.axes.Axes) for a in result) + assert list(tmp_path.glob("*.png")) == [], "no files should be written without export_path" + plt.close('all') diff --git a/yabplot/plotting.py b/yabplot/plotting.py index bce7093..c08f133 100644 --- a/yabplot/plotting.py +++ b/yabplot/plotting.py @@ -1,6 +1,7 @@ import os import gc import re +import random import warnings import numpy as np import pandas as pd @@ -8,6 +9,7 @@ import pyvista as pv import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, to_rgba +from matplotlib.pyplot import get_cmap from scipy.ndimage import gaussian_filter from .data import ( @@ -120,6 +122,20 @@ def _render_cortical_views(lh_v, lh_f, lh_vals, rh_v, rh_f, rh_vals, is_cat, return finalize_plot(plotter, export_path, display_type, ax=ax, cbar_info=cbar_info, cbar_kwargs=cbar_kwargs) +def get_base_name(name): + """Strip one hemisphere suffix or prefix to get the base region name.""" + n = name.lower() + for suffix in ['_l', '_r', '-lh', '-rh']: + if n.endswith(suffix): + return name[:len(name)-len(suffix)] + for prefix in ['l-', 'r-', 'l_', 'r_']: + if n.startswith(prefix): + return name[len(prefix):] + for word in ['left_', 'right_', 'left-', 'right-']: + if n.startswith(word): + return name[len(word):] + return name + ### PLOT FOR ATLAS-BASED CORTICAL DATA ### @@ -317,10 +333,12 @@ def plot_vertexwise(lh, rh, scalars='Data', ax=None, cbar_kwargs=None, views=Non ### PLOT FOR ATLAS-BASED SUBCORTICAL DATA ### def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None, - figsize=None, cmap='coolwarm', vminmax=[None, None], nan_color='#cccccc', + figsize=None, cmap=None, vminmax=[None, None], nan_color='#cccccc', nan_alpha=1.0, style='default', bmesh='midthickness', bmesh_alpha=0.15, bmesh_color='lightgray', zoom=1.2, display_type='matplotlib', - export_path=None, custom_atlas_proc=dict(smooth_i=15, smooth_f=0.6)): + export_path=None, custom_atlas_proc=dict(smooth_i=15, smooth_f=0.6), + atlas_color_seed=42, plot_regions_separately=False, + shared_hemisphere_colors=False): """ Visualize data on the subcortical structures using a specified atlas. @@ -347,7 +365,10 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba figsize : tuple (width, height), optional Window size in inches. If None, automatically calculated based on the number of views and layout. cmap : str or matplotlib.colors.Colormap, optional - Colormap for continuous data. Ignored if `data` is None. Default is 'coolwarm'. + Colormap for continuous data. Defaults to 'coolwarm' when `data` is given. + If `data` is None (atlas mode), `cmap` is unused by default and regions get + randomly-seeded distinct colors; pass a colormap (name or object) to instead + sample region colors from that colormap's gradient. vminmax : list [min, max], optional Manual lower and upper bounds for the colormap. If [None, None], bounds are inferred from the data range. @@ -374,10 +395,39 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba 'object': returns the raw pyvista plotter object. export_path : str, optional If provided, saves the final figure to this path (e.g., 'figure.png'). + With `plot_regions_separately`, it is instead the directory that the + per-region PNGs are saved to. custom_atlas_proc : dict, optional Parameters for processing custom GIfTI files. Keys: 'smooth_i' (iterations) and 'smooth_f' (relaxation factor). Default is {'smooth_i': 15, 'smooth_f': 0.6}. + atlas_color_seed : int, optional + Seed controlling the categorical color arrangement in atlas (no-data) mode. + With the default palette it seeds the distinct-color generator; with a + colormap it seeds a shuffle so gradient-adjacent regions get contrasting + colors. Change it to get a different, reproducible arrangement. Ignored when + `data` is given. Default is 42. + plot_regions_separately : bool, optional + If True, renders each region + view combination on its own instead of a single + combined figure. If ``export_path`` is set, it is always treated as a directory + (created if missing): one transparent-background PNG per region + view is saved + there (named ``{region}_{view_face}.png``, useful for SVG tracing pipelines) + and None is returned. ``view_face`` is the view name without ``left_``/``right_``; + midline regions keep the full view name. Otherwise one matplotlib figure per + region + view is opened and the axes are returned as a list. + All renders share the same camera framing, so regions keep their relative + position and size, and the same size: `figsize` if given, else 3.5 x 3 inches. + `ax`, `layout`, `display_type` and `cbar_kwargs` are not used in this mode and + no colorbar is drawn. Default is False. + shared_hemisphere_colors : bool, optional + If True, bilateral region pairs (e.g. ``putamen_l`` / ``putamen_r``) are drawn + in the same color, so each structure reads as one color across both hemispheres. + Pairs are matched by name after removing one hemisphere tag (case-insensitive): + a ``_l``/``_r`` or ``-lh``/``-rh`` suffix, or a ``l-``/``r-``, ``l_``/``r_``, + ``left_``/``right_`` or ``left-``/``right-`` prefix. Regions named in any other + way keep their own color. + Only applies in atlas (no-data) mode; ignored when `data` is given. If False + (default), every region is assigned its own independent color. Returns ------- @@ -387,6 +437,8 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba - 'interactive': returns a trame browser viewer. - 'pyvista': returns a static jupyter widget. - 'object': returns the raw pyvista plotter. + with `plot_regions_separately`, returns None if `export_path` is set, + otherwise a list of matplotlib axes (one per region + view). """ # defaults @@ -414,27 +466,124 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba # prepare colors and map data if data is not None: + cmap = cmap if cmap is not None else 'coolwarm' d_data = prep_data(data, rmesh_names, atlas, 'subcortical') valid_vals = [v for v in d_data.values() if pd.notna(v)] vmin = vminmax[0] if vminmax[0] is not None else (min(valid_vals) if valid_vals else 0) vmax = vminmax[1] if vminmax[1] is not None else (max(valid_vals) if valid_vals else 1) c_vlim = [vmin, vmax] else: - colors = generate_distinct_colors(len(rmesh_names), seed=42) - d_atlas_colors = {name: color for name, color in zip(rmesh_names, colors)} + # determine the key for each region: base name (hemisphere-shared) or the raw name + color_keys = ( + list(dict.fromkeys(get_base_name(n) for n in rmesh_names)) + if shared_hemisphere_colors + else list(dict.fromkeys(rmesh_names)) + ) + + # generate one color per unique key + if cmap is None: + key_colors = generate_distinct_colors(len(color_keys), seed=atlas_color_seed) + else: + # get_cmap accepts either a colormap name (str) or a Colormap object + cmap_obj = get_cmap(cmap) + key_colors = [tuple(c[:3]) for c in cmap_obj(np.linspace(0, 1, len(color_keys)))] + random.Random(atlas_color_seed).shuffle(key_colors) + color_map = dict(zip(color_keys, key_colors)) + + lookup = get_base_name if shared_hemisphere_colors else (lambda n: n) + d_atlas_colors = {name: color_map[lookup(name)] for name in rmesh_names} c_vlim = [0, 1] - # setup plotter + # setup views and shading (shared by both code paths) sel_views = get_view_configs(views) - ax, display_type, figsize = prepare_plotter(ax, display_type, sel_views, layout, figsize) - - needs_bottom = (data is not None) - plotter, ncols, nrows = setup_plotter(sel_views, layout, figsize, display_type, - needs_bottom_row=needs_bottom) - # get shading parameters from style shading_params = get_shading_preset(style) + + if plot_regions_separately: + # per-region output; export_path is always a directory here + do_export = export_path is not None + if do_export: + out_dir = export_path + os.makedirs(out_dir, exist_ok=True) + + # every render has the same size. 'object' makes prepare_plotter only convert + # figsize to pixels, so no figure is created for the unused combined layout + _, _, region_size = prepare_plotter(None, 'object', sel_views, layout, figsize) + region_window_size = list(region_size) if region_size is not None else [700, 600] + region_axes = [] + + for view_name, cfg in sel_views.items(): + print(f"Rendering view: {view_name}...") + + for target_name in list(meshes.keys()): + is_left, is_right = _get_side_tokens(target_name) + if cfg['side'] == 'L' and is_right and not is_left: + continue + if cfg['side'] == 'R' and is_left and not is_right: + continue + + if is_left != is_right: + view_face = view_name.replace('left_', '').replace('right_', '') + else: + view_face = view_name + + indiv_plotter = pv.Plotter(off_screen=True, window_size=region_window_size) + indiv_plotter.set_background('white') + add_context_to_view(indiv_plotter, ctx_meshes, cfg['side'], bmesh_alpha, + bmesh_color, **shading_params) + + region_actors = {} + for name, mesh in meshes.items(): + n_is_left, n_is_right = _get_side_tokens(name) + if cfg['side'] == 'L' and n_is_right and not n_is_left: + continue + if cfg['side'] == 'R' and n_is_left and not n_is_right: + continue + + props = shading_params.copy() + if data is not None: + val = d_data.get(name, np.nan) if pd.notna(d_data.get(name)) else np.nan + has_val = not np.isnan(val) + mesh['Data'] = np.full(mesh.n_points, val) + props.update({ + 'scalars': 'Data', 'cmap': cmap, 'clim': c_vlim, + 'nan_color': nan_color, 'opacity': 1.0 if has_val else nan_alpha, + 'show_scalar_bar': False, + }) + else: + props.update({'color': d_atlas_colors[name], 'opacity': 1.0}) + + region_actors[name] = indiv_plotter.add_mesh(mesh, **props) + + # frame the camera on all regions before hiding the non-targets, so each + # region keeps its true position and size (hidden actors are not framed) + set_camera(indiv_plotter, cfg, zoom=zoom) + for name, actor in region_actors.items(): + actor.SetVisibility(name == target_name) + indiv_plotter.hide_axes() + + if do_export: + out_file = os.path.join(out_dir, f'{target_name}_{view_face}.png') + indiv_plotter.screenshot(out_file, transparent_background=True) + indiv_plotter.close() + print(f" Saved → {out_file}") + else: + img = indiv_plotter.screenshot(transparent_background=True, return_img=True) + indiv_plotter.close() + _, region_ax = plt.subplots() + region_ax.imshow(img) + region_ax.set_title(f'{target_name} ({view_name})', fontsize=8) + region_ax.axis('off') + region_axes.append(region_ax) + + return None if do_export else region_axes + + # setup plotter (combined / normal path) + ax, display_type, figsize = prepare_plotter(ax, display_type, sel_views, layout, figsize) + needs_bottom = (data is not None) + plotter, ncols, nrows = setup_plotter(sel_views, layout, figsize, display_type, + needs_bottom_row=needs_bottom) scalar_bar_mapper = None # pre-calculate side tokens for all meshes to avoid regex in loops