From 61f4c625aea026deeeca67805f02beb4d8a3ebf1 Mon Sep 17 00:00:00 2001 From: anniegbryant Date: Fri, 22 May 2026 18:39:17 +1000 Subject: [PATCH 1/5] Add new subcortical feature params branch --- tests/test_plotting.py | 108 +++++++++++++++++++++++++++++++ yabplot/plotting.py | 140 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 239 insertions(+), 9 deletions(-) diff --git a/tests/test_plotting.py b/tests/test_plotting.py index b4d7966..c80d9f1 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,110 @@ 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"), + # 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 + + +# --- hemisphere_colors behavioral tests --- + +def _count_unique_region_colors(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', hemisphere_colors=hemisphere_colors + ) + + return len(set( + c if not isinstance(c, list) else tuple(c) + for c in captured.values() + )) + + +def test_subcortical_hemisphere_colors_false_more_unique_than_true(): + """hemisphere_colors=False (default) yields more unique colors than True.""" + unique_false = _count_unique_region_colors(hemisphere_colors=False) + unique_true = _count_unique_region_colors(hemisphere_colors=True) + assert unique_false > unique_true + + +def test_subcortical_hemisphere_colors_smoke(): + """Smoke test: hemisphere_colors=True renders without error.""" + yab.plot_subcortical(atlas='aseg', display_type='matplotlib', hemisphere_colors=True) + + +def test_subcortical_shuffle_colors_smoke(): + """Smoke test: shuffle_colors=True renders without error.""" + yab.plot_subcortical(atlas='aseg', display_type='matplotlib', shuffle_colors=True) + + +def test_shuffle_colors_reassigns_colors(): + """shuffle_colors logic reassigns colors to different regions (unit test).""" + from yabplot.utils import generate_distinct_colors + import random + + names = ['Left-Putamen', 'Right-Putamen', 'Left-Caudate', 'Right-Caudate', + 'Left-Thalamus', 'Right-Thalamus', 'Left-Hippocampus', 'Right-Hippocampus'] + n = len(names) + key_colors = generate_distinct_colors(n, seed=42) + + color_map_default = dict(zip(names, key_colors)) + + random.seed(42) + keys = list(color_map_default.keys()) + values = list(color_map_default.values()) + random.shuffle(values) + color_map_shuffled = dict(zip(keys, values)) + + any_changed = any( + tuple(color_map_default[name]) != tuple(color_map_shuffled[name]) + for name in names + ) + assert any_changed, "Shuffle produced no change in color assignments" + + +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" diff --git a/yabplot/plotting.py b/yabplot/plotting.py index bce7093..325e6bb 100644 --- a/yabplot/plotting.py +++ b/yabplot/plotting.py @@ -8,6 +8,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 +121,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 hemisphere suffix 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-']: + 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 ### @@ -320,7 +335,9 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba figsize=None, cmap='coolwarm', 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), + shuffle_colors=False, plot_regions_separately=False, + hemisphere_colors=False): """ Visualize data on the subcortical structures using a specified atlas. @@ -378,6 +395,18 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba Parameters for processing custom GIfTI files. Keys: 'smooth_i' (iterations) and 'smooth_f' (relaxation factor). Default is {'smooth_i': 15, 'smooth_f': 0.6}. + shuffle_colors : bool, optional + If True, shuffles the color assignments for categorical coloring to help + distinguish adjacent regions with similar colormap neighbors. Default is False. + plot_regions_separately : bool, optional + If True, saves a separate PNG file for each region + view combination instead + of a single combined figure. Each file is named ``{region}_{view_face}.png`` + and uses a transparent background (useful for SVG tracing pipelines). + ``export_path`` is treated as an output directory. Default is False. + hemisphere_colors : bool, optional + If True, bilateral region pairs (e.g. ``putamen_l`` / ``putamen_r``) share the + same color in atlas (no-data) mode. If False (default), every region is assigned + its own independent color. Returns ------- @@ -420,21 +449,114 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba 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 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=42) + color_map = {k: color for k, color in zip(color_keys, key_colors)} + elif isinstance(cmap, str): + cmap_obj = get_cmap(cmap) + color_map = { + k: tuple(c[:3]) + for k, c in zip(color_keys, cmap_obj(np.linspace(0, 1, len(color_keys)))) + } + + if shuffle_colors: + import random + random.seed(42) + keys = list(color_map.keys()) + values = list(color_map.values()) + random.shuffle(values) + color_map = dict(zip(keys, values)) + + lookup = get_base_name if 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: + # Determine output directory + if export_path is None: + out_dir = os.getcwd() + else: + _, _ext = os.path.splitext(export_path) + out_dir = os.path.dirname(export_path) if _ext else export_path + if not out_dir: + out_dir = os.getcwd() + os.makedirs(out_dir, exist_ok=True) + + for view_name, cfg in sel_views.items(): + view_face = view_name.replace('left_', '').replace('right_', '') + print(f"Rendering view: {view_name}...") + + for target_name in list(meshes.keys()): + tokens = set(re.split(r'[^a-z0-9]+', target_name.lower())) + is_left = any(x in tokens for x in ['left', 'l', 'lh']) + is_right = any(x in tokens for x in ['right', 'r', 'rh']) + if cfg['side'] == 'L' and is_right and not is_left: + continue + if cfg['side'] == 'R' and is_left and not is_right: + continue + + indiv_plotter = pv.Plotter(off_screen=True, window_size=list(figsize)) + indiv_plotter.set_background('white') + add_context_to_view(indiv_plotter, ctx_meshes, cfg['side'], bmesh_alpha, + bmesh_color, **shading_params) + + # Add all side-appropriate meshes; hide every one except the target. + # All meshes are added so the camera position stays consistent across + # exports, but only the target is visible. + for name, mesh in meshes.items(): + n_tokens = set(re.split(r'[^a-z0-9]+', name.lower())) + n_is_left = any(x in n_tokens for x in ['left', 'l', 'lh']) + n_is_right = any(x in n_tokens for x in ['right', 'r', 'rh']) + 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}) + + actor = indiv_plotter.add_mesh(mesh, **props) + actor.SetVisibility(name == target_name) + + set_camera(indiv_plotter, cfg, zoom=zoom) + indiv_plotter.hide_axes() + + 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}") + + return None + + # setup plotter (combined / normal path) + 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 From a714c110463e354c40fdf8ce5c870e52555c0a43 Mon Sep 17 00:00:00 2001 From: anniegbryant Date: Wed, 24 Jun 2026 10:28:19 -0400 Subject: [PATCH 2/5] Fix default argument behavior of cmap if data not provided --- yabplot/plotting.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/yabplot/plotting.py b/yabplot/plotting.py index 325e6bb..82ef328 100644 --- a/yabplot/plotting.py +++ b/yabplot/plotting.py @@ -332,7 +332,7 @@ 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), @@ -364,7 +364,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 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. @@ -443,6 +446,7 @@ 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) From caeed313ea50832208e9bb94898adace0155c228 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toomas=20Erik=20Anij=C3=A4rv?= Date: Fri, 24 Jul 2026 15:57:04 +0200 Subject: [PATCH 3/5] fix colormap-object crash and midline filename collision in plot_subcortical --- tests/test_plotting.py | 36 ++++++++++++++++++++++++++++++++++++ yabplot/plotting.py | 27 +++++++++++---------------- 2 files changed, 47 insertions(+), 16 deletions(-) diff --git a/tests/test_plotting.py b/tests/test_plotting.py index c80d9f1..45067a2 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -199,3 +199,39 @@ def test_subcortical_plot_regions_separately(tmp_path): 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}" diff --git a/yabplot/plotting.py b/yabplot/plotting.py index 82ef328..59a33f9 100644 --- a/yabplot/plotting.py +++ b/yabplot/plotting.py @@ -463,13 +463,11 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba # Generate one color per unique key if cmap is None: key_colors = generate_distinct_colors(len(color_keys), seed=42) - color_map = {k: color for k, color in zip(color_keys, key_colors)} - elif isinstance(cmap, str): + else: + # get_cmap accepts either a colormap name (str) or a Colormap object cmap_obj = get_cmap(cmap) - color_map = { - k: tuple(c[:3]) - for k, c in zip(color_keys, cmap_obj(np.linspace(0, 1, len(color_keys)))) - } + key_colors = [tuple(c[:3]) for c in cmap_obj(np.linspace(0, 1, len(color_keys)))] + color_map = dict(zip(color_keys, key_colors)) if shuffle_colors: import random @@ -502,30 +500,27 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba os.makedirs(out_dir, exist_ok=True) for view_name, cfg in sel_views.items(): - view_face = view_name.replace('left_', '').replace('right_', '') print(f"Rendering view: {view_name}...") for target_name in list(meshes.keys()): - tokens = set(re.split(r'[^a-z0-9]+', target_name.lower())) - is_left = any(x in tokens for x in ['left', 'l', 'lh']) - is_right = any(x in tokens for x in ['right', 'r', 'rh']) + 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=list(figsize)) indiv_plotter.set_background('white') add_context_to_view(indiv_plotter, ctx_meshes, cfg['side'], bmesh_alpha, bmesh_color, **shading_params) - # Add all side-appropriate meshes; hide every one except the target. - # All meshes are added so the camera position stays consistent across - # exports, but only the target is visible. for name, mesh in meshes.items(): - n_tokens = set(re.split(r'[^a-z0-9]+', name.lower())) - n_is_left = any(x in n_tokens for x in ['left', 'l', 'lh']) - n_is_right = any(x in n_tokens for x in ['right', 'r', 'rh']) + 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: From 09a960bf76bad040f30fbf896e193ff75a0013d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toomas=20Erik=20Anij=C3=A4rv?= Date: Fri, 24 Jul 2026 17:10:35 +0200 Subject: [PATCH 4/5] make per-region export optional and replace shuffle_colors with atlas_color_seed --- tests/test_plotting.py | 84 ++++++++++++++++++++++++--------------- yabplot/plotting.py | 89 ++++++++++++++++++++++++------------------ 2 files changed, 102 insertions(+), 71 deletions(-) diff --git a/tests/test_plotting.py b/tests/test_plotting.py index 45067a2..9e58009 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -106,6 +106,8 @@ def test_export_path(tmp_path): # prefix patterns ("l-thalamus", "thalamus"), ("r-thalamus", "thalamus"), + ("L_Thalamus", "Thalamus"), + ("R_Thalamus", "Thalamus"), # word prefix patterns ("left_caudate", "caudate"), ("right_caudate", "caudate"), @@ -119,9 +121,9 @@ def test_get_base_name(name, expected): assert get_base_name(name) == expected -# --- hemisphere_colors behavioral tests --- +# --- shared_hemisphere_colors behavioral tests --- -def _count_unique_region_colors(hemisphere_colors): +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 @@ -136,7 +138,7 @@ def recording_add_mesh(self, mesh, **kwargs): with patch.object(pv.Plotter, 'add_mesh', recording_add_mesh): yab.plot_subcortical( - atlas='aseg', display_type='matplotlib', hemisphere_colors=hemisphere_colors + atlas='aseg', display_type='matplotlib', shared_hemisphere_colors=shared_hemisphere_colors ) return len(set( @@ -145,46 +147,48 @@ def recording_add_mesh(self, mesh, **kwargs): )) -def test_subcortical_hemisphere_colors_false_more_unique_than_true(): - """hemisphere_colors=False (default) yields more unique colors than True.""" - unique_false = _count_unique_region_colors(hemisphere_colors=False) - unique_true = _count_unique_region_colors(hemisphere_colors=True) +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_hemisphere_colors_smoke(): - """Smoke test: hemisphere_colors=True renders without error.""" - yab.plot_subcortical(atlas='aseg', display_type='matplotlib', hemisphere_colors=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_shuffle_colors_smoke(): - """Smoke test: shuffle_colors=True renders without error.""" - yab.plot_subcortical(atlas='aseg', display_type='matplotlib', shuffle_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 test_shuffle_colors_reassigns_colors(): - """shuffle_colors logic reassigns colors to different regions (unit test).""" - from yabplot.utils import generate_distinct_colors - import random +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 - names = ['Left-Putamen', 'Right-Putamen', 'Left-Caudate', 'Right-Caudate', - 'Left-Thalamus', 'Right-Thalamus', 'Left-Hippocampus', 'Right-Hippocampus'] - n = len(names) - key_colors = generate_distinct_colors(n, seed=42) + 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) - color_map_default = dict(zip(names, key_colors)) + 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 - random.seed(42) - keys = list(color_map_default.keys()) - values = list(color_map_default.values()) - random.shuffle(values) - color_map_shuffled = dict(zip(keys, values)) - any_changed = any( - tuple(color_map_default[name]) != tuple(color_map_shuffled[name]) - for name in names - ) - assert any_changed, "Shuffle produced no change in color assignments" +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): @@ -235,3 +239,19 @@ def test_plot_regions_separately_midline_no_collision(tmp_path): 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 59a33f9..14f265b 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 @@ -127,7 +128,7 @@ def get_base_name(name): for suffix in ['_l', '_r', '-lh', '-rh']: if n.endswith(suffix): return name[:len(name)-len(suffix)] - for prefix in ['l-', 'r-']: + for prefix in ['l-', 'r-', 'l_', 'r_']: if n.startswith(prefix): return name[len(prefix):] for word in ['left_', 'right_', 'left-', 'right-']: @@ -336,8 +337,8 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba 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), - shuffle_colors=False, plot_regions_separately=False, - hemisphere_colors=False): + atlas_color_seed=42, plot_regions_separately=False, + shared_hemisphere_colors=False): """ Visualize data on the subcortical structures using a specified atlas. @@ -398,18 +399,23 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba Parameters for processing custom GIfTI files. Keys: 'smooth_i' (iterations) and 'smooth_f' (relaxation factor). Default is {'smooth_i': 15, 'smooth_f': 0.6}. - shuffle_colors : bool, optional - If True, shuffles the color assignments for categorical coloring to help - distinguish adjacent regions with similar colormap neighbors. Default is False. + 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, saves a separate PNG file for each region + view combination instead - of a single combined figure. Each file is named ``{region}_{view_face}.png`` - and uses a transparent background (useful for SVG tracing pipelines). - ``export_path`` is treated as an output directory. Default is False. - hemisphere_colors : bool, optional - If True, bilateral region pairs (e.g. ``putamen_l`` / ``putamen_r``) share the - same color in atlas (no-data) mode. If False (default), every region is assigned - its own independent color. + If True, renders each region + view combination on its own instead of a single + combined figure. If ``export_path`` is set, one transparent-background PNG per + region is saved there (named ``{region}_{view_face}.png``, useful for SVG + tracing pipelines) and None is returned; otherwise the per-region axes are + displayed and returned as a list. 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. + Only applies in atlas (no-data) mode; ignored when `data` is given. If False + (default), every region is assigned its own independent color. Returns ------- @@ -453,31 +459,24 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba vmax = vminmax[1] if vminmax[1] is not None else (max(valid_vals) if valid_vals else 1) c_vlim = [vmin, vmax] else: - # Determine the key for each region: base name (hemisphere-shared) or the raw name + # 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 hemisphere_colors + if shared_hemisphere_colors else list(dict.fromkeys(rmesh_names)) ) - # Generate one color per unique key + # generate one color per unique key if cmap is None: - key_colors = generate_distinct_colors(len(color_keys), seed=42) + 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)) - if shuffle_colors: - import random - random.seed(42) - keys = list(color_map.keys()) - values = list(color_map.values()) - random.shuffle(values) - color_map = dict(zip(keys, values)) - - lookup = get_base_name if hemisphere_colors else (lambda n: n) + 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] @@ -489,15 +488,18 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba shading_params = get_shading_preset(style) if plot_regions_separately: - # Determine output directory - if export_path is None: - out_dir = os.getcwd() - else: + # per-region output + do_export = export_path is not None + if do_export: _, _ext = os.path.splitext(export_path) out_dir = os.path.dirname(export_path) if _ext else export_path if not out_dir: out_dir = os.getcwd() - os.makedirs(out_dir, exist_ok=True) + os.makedirs(out_dir, exist_ok=True) + + # figsize can be None for non-matplotlib display types; fall back to default + region_window_size = list(figsize) if figsize is not None else [1000, 800] + region_axes = [] for view_name, cfg in sel_views.items(): print(f"Rendering view: {view_name}...") @@ -514,7 +516,7 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba else: view_face = view_name - indiv_plotter = pv.Plotter(off_screen=True, window_size=list(figsize)) + 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) @@ -545,12 +547,21 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba set_camera(indiv_plotter, cfg, zoom=zoom) indiv_plotter.hide_axes() - 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}") - - return None + 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) needs_bottom = (data is not None) From 27e811e2be1ea4e341fa13ee9701e1b2f4a2bd20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toomas=20Erik=20Anij=C3=A4rv?= Date: Tue, 13 Oct 2026 17:27:48 +0200 Subject: [PATCH 5/5] small edits --- yabplot/plotting.py | 51 ++++++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/yabplot/plotting.py b/yabplot/plotting.py index 14f265b..c08f133 100644 --- a/yabplot/plotting.py +++ b/yabplot/plotting.py @@ -123,7 +123,7 @@ def _render_cortical_views(lh_v, lh_f, lh_vals, rh_v, rh_f, rh_vals, is_cat, def get_base_name(name): - """Strip hemisphere suffix to get the base region 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): @@ -367,8 +367,8 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba cmap : str or matplotlib.colors.Colormap, optional 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 to instead sample - region colors from that colormap's gradient. + 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. @@ -395,6 +395,8 @@ 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). @@ -407,13 +409,23 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba `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, one transparent-background PNG per - region is saved there (named ``{region}_{view_face}.png``, useful for SVG - tracing pipelines) and None is returned; otherwise the per-region axes are - displayed and returned as a list. Default is False. + 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. @@ -425,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 @@ -482,23 +496,21 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba # 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) # get shading parameters from style shading_params = get_shading_preset(style) if plot_regions_separately: - # per-region output + # per-region output; export_path is always a directory here do_export = export_path is not None if do_export: - _, _ext = os.path.splitext(export_path) - out_dir = os.path.dirname(export_path) if _ext else export_path - if not out_dir: - out_dir = os.getcwd() + out_dir = export_path os.makedirs(out_dir, exist_ok=True) - # figsize can be None for non-matplotlib display types; fall back to default - region_window_size = list(figsize) if figsize is not None else [1000, 800] + # 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(): @@ -521,6 +533,7 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba 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: @@ -541,10 +554,13 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba else: props.update({'color': d_atlas_colors[name], 'opacity': 1.0}) - actor = indiv_plotter.add_mesh(mesh, **props) - actor.SetVisibility(name == target_name) + 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: @@ -564,6 +580,7 @@ def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cba 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)