visualizationtools module
Visualization tools for neuroimaging data using PyVista. Provides classes and functions for plotting brain surfaces, tractograms, and point clouds with customizable views and color mappings.
Classes: - BrainPlotter: A class for visualizing brain surfaces with various view configurations, colormaps, and optional colorbars.
Functions: - (Additional functions can be added here as needed)
- class clabtoolkit.visualizationtools.BrainPlotter(config_file=None)[source]
Bases:
objectA comprehensive brain surface visualization tool using PyVista.
This class provides flexible brain plotting capabilities with multiple view configurations, customizable colormaps, and optional colorbar support for neuroimaging data visualization.
Examples
>>> plotter = BrainPlotter("brain_plot_configs.json") >>> plotter.plot_hemispheres(surf_lh, surf_rh, map_name="thickness", ... views="8_views", colorbar=True) >>> >>> # Dynamic view selection >>> plotter.plot_hemispheres(surf_lh, surf_rh, views=["lateral", "medial", "dorsal"])
- __init__(config_file=None)[source]
Initialize the BrainPlotter with configuration file.
- Parameters:
config_file (str, optional) – Path to JSON file containing figure and view configurations. If None, uses default “viz_views.json” from config directory.
- Raises:
FileNotFoundError – If the configuration file doesn’t exist.
json.JSONDecodeError – If the configuration file contains invalid JSON.
KeyError – If required keys ‘figure_conf’ or ‘views_conf’ are missing.
Examples
>>> plotter = BrainPlotter() # Use default config >>> >>> plotter = BrainPlotter("custom_views.json") # Use custom config
- plot(objs2plot, hemi_id='lh', views='dorsal', views_orientation='horizontal', notebook=False, map_names=['default'], v_limits=(None, None), v_range=(None, None), range_color=(128, 128, 128, 255), use_opacity=True, colormaps='BrBG', save_path=None, non_blocking=True, colorbar=True, colorbar_style='individual', colorbar_titles=None, colorbar_position='right', config_file=None)[source]
Plot brain surfaces with optional threading and screenshot support.
- Parameters:
objs2plot (Union[cltsurf.Surface, clttract.Tractogram, cltpts.PointCloud, List]) – Object(s) to plot. Can be a single object or a list of objects.
hemi_id (List[str], default ["lh"]) – Hemisphere identifiers.
views (Union[str, List[str]], default "dorsal") – View angles for the surfaces.
views_orientation (str, default "horizontal") – Orientation of the views layout.
notebook (bool, default False) – Whether running in Jupyter notebook environment.
map_names (Union[str, List[str]], default ["default"]) – Names of the surface maps to plot.
v_limits (Optional[Union[Tuple[float, float], List[Tuple[float, float]]]], default (None, None)) – Value limits for colormapping.
v_range (Optional[Union[Tuple[float, float], List[Tuple[float, float]]]], default (None, None)) – Value range for colormap application. Values outside this range will be displayed in range_color.
range_color (Tuple, default (128, 128, 128, 255)) – RGBA color to use for values outside the specified v_range.
colormaps (Union[str, List[str]], default "BrBG") – Colormaps to use for each map.
use_opacity (bool, default True) – Whether to use opacity in the surface rendering. This is important when saving to HTML format to ensure proper visualization. If False, surfaces will be fully opaque.
save_path (Optional[str], default None) – File path for saving the figure. If None, plot is displayed.
non_blocking (bool, default False) – If True, display the plot in a separate thread, allowing the terminal or notebook to remain interactive. Only applies when save_path is None.
colorbar (bool, default True) – Whether to show colorbars.
colorbar_style (str, default "individual") – Style of colormap application.
colorbar_titles (Union[str, List[str]], optional) – Titles for the colorbars.
colorbar_position (str, default "right") – Position of the colorbars.
- plot_hemispheres(obj_rh, obj_lh, map_name='default', views='dorsal', vmin=None, vmax=None, range_min=None, range_max=None, range_color=(128, 128, 128, 255), use_opacity=True, colormap='viridis', colorbar=True, colorbar_title=None, colorbar_position='right', notebook=False, non_blocking=False, save_path=None, config_file=None)[source]
Plot brain hemispheres with multiple views.
- Parameters:
obj_rh (Union[cltsurf.Surface, clttract.Tractogram, cltpts.PointCloud]) – Right hemisphere object to plot. Can be a Surface, Tractogram, or PointCloud.
obj_lh (Union[cltsurf.Surface, clttract.Tractogram, cltpts.PointCloud]) – Left hemisphere object to plot. Can be a Surface, Tractogram, or PointCloud.
map_name (str "default") – Name of the data maps to visualize. Must be present in all the objects.
views (str or list of str, default "dorsal") – Views to display. Options include ‘dorsal’, ‘ventral’, ‘lateral’, ‘medial’, ‘anterior’, ‘posterior’. Can be a single view or a list of views. It can also include different multiple views specified as layouts: >>> plotter = BrainPlotter(“configs.json”) >>> layouts = plotter.list_available_layouts()
vmin (float, optional) – Minimum value for colormap scaling. If None, uses the minimum value from the data.
vmax (float, optional) – Maximum value for colormap scaling. If None, uses the maximum value from the data.
range_min (float, optional) – Minimum value for the value range. Values below this will be colored with range_color.
range_max (float, optional) – Maximum value for the value range. Values above this will be colored with range_color.
range_color (Tuple, default (128, 128, 128, 255)) – RGBA color to use for values outside the specified v_range.
colormap (str or list of str, default "BrBG") – Colormap to use for visualization.
colorbar (bool, default True) – Whether to display colorbars for the maps.
colorbar_title (str, optional) – Title for the colorbar. If None, map name are used.
colorbar_position (str, default "right") – Position of the colorbars. Options are ‘right’ or ‘bottom’.
notebook (bool, default False) – Whether to render the plot in a Jupyter notebook environment. If True, uses notebook-compatible rendering.
non_blocking (bool, default False) – If True, displays the plot in a non-blocking manner using threading. Only applicable when notebook is False and save_path is None.
save_path (str, optional) – File path to save the rendered figure. If provided, the figure is saved to this path instead of being displayed.
config_file (Union[str, Path, Dict], optional) – Path to a custom configuration file (JSON) or a dictionary containing configuration settings. If provided, this configuration will override the default settings for plotting.
- Returns:
The function does not return any value. It either displays the plot or saves it to a file, depending on the parameters provided.
- Return type:
None
- plot_scene(scene_objects, scene_config=None, views='dorsal', notebook=False, colorbar=True, colorbar_position='right', use_opacity=True, non_blocking=False, save_path=None, config_file=None)[source]
- list_available_view_names()[source]
List available view names for dynamic view selection.
- Returns:
Available view names that can be used in views parameter: [‘Lateral’, ‘Medial’, ‘Dorsal’, ‘Ventral’, ‘Rostral’, ‘Caudal’].
- Return type:
List[str]
Examples
>>> plotter = BrainPlotter() >>> view_names = plotter.list_available_view_names() >>> print(f"Available views: {view_names}")
- list_available_layouts()[source]
Display available visualization layouts and their configurations.
- Returns:
Dictionary containing detailed layout information for each configuration. Keys are configuration names, values contain shape, window_size, num_views, and views information.
- Return type:
Examples
>>> plotter = BrainPlotter("configs.json") >>> layouts = plotter.list_available_layouts() >>> print(f"Available layouts: {list(layouts.keys())}") >>> >>> # Access specific layout info >>> layout_info = layouts['8_views'] >>> print(f"Shape: {layout_info['shape']}") >>> print(f"Views: {layout_info['num_views']}")
- get_layout_details(views)[source]
Get detailed information about a specific layout configuration.
- Parameters:
views (str) – Name of the configuration to examine.
- Returns:
Detailed configuration information if found, None if configuration doesn’t exist. Contains shape, window_size, and views information.
- Return type:
Dict[str, Any] or None
Examples
>>> plotter = BrainPlotter("configs.json") >>> details = plotter.get_layout_details("8_views") >>> if details: ... print(f"Grid shape: {details['shape']}") ... print(f"Views: {len(details['views'])}") >>> >>> # Handle non-existent configuration >>> details = plotter.get_layout_details("invalid_config")
- get_figure_config()[source]
Get the current figure configuration settings.
- Returns:
Dictionary containing all figure styling settings including background color, font settings, mesh properties, and colorbar options.
- Return type:
Dict[str, Any]
Examples
>>> plotter = BrainPlotter("configs.json") >>> fig_config = plotter.get_figure_config() >>> print(f"Background color: {fig_config['background_color']}") >>> print(f"Title font: {fig_config['title_font_type']}")
- list_available_themes()[source]
Display all available themes with descriptions and previews.
Examples
>>> plotter = BrainPlotter("configs.json") >>> plotter.list_available_themes()
- update_figure_config(auto_save=False, **kwargs)[source]
Update figure configuration parameters with validation and automatic saving.
This method allows you to easily customize the visual appearance of your brain plots by updating styling parameters like colors, fonts, and mesh properties.
- Parameters:
auto_save (bool, default True) – Whether to automatically save changes to the JSON configuration file.
**kwargs (dict) –
Figure configuration parameters to update. Valid parameters include:
Background & Colors: - background_color : str (e.g., “black”, “white”, “#1e1e1e”) - title_font_color : str (e.g., “white”, “black”, “#ffffff”) - colorbar_font_color : str (e.g., “white”, “black”, “#ffffff”)
Title Settings: - title_font_type : str (e.g., “arial”, “times”, “courier”) - title_font_size : int (6-30, default: 10) - title_shadow : bool (True/False)
Colorbar Settings: - colorbar_font_type : str (e.g., “arial”, “times”, “courier”) - colorbar_font_size : int (6-20, default: 10) - colorbar_title_font_size : int (8-25, default: 15) - colorbar_outline : bool (True/False) - colorbar_n_labels : int (3-15, default: 11)
Mesh Properties: - mesh_ambient : float (0.0-1.0, default: 0.2) - mesh_diffuse : float (0.0-1.0, default: 0.5) - mesh_specular : float (0.0-1.0, default: 0.5) - mesh_specular_power : int (1-100, default: 50) - mesh_smooth_shading : bool (True/False)
- Raises:
ValueError – If invalid parameter names or values are provided.
TypeError – If parameter values are of incorrect type.
Examples
>>> plotter = BrainPlotter("configs.json") >>> >>> # Change background to white with black text >>> plotter.update_figure_config( ... background_color="white", ... title_font_color="black", ... colorbar_font_color="black" ... ) >>> >>> # Increase font sizes >>> plotter.update_figure_config( ... title_font_size=14, ... colorbar_font_size=12, ... colorbar_title_font_size=18 ... ) >>> >>> # Adjust mesh lighting for better visibility >>> plotter.update_figure_config( ... mesh_ambient=0.3, ... mesh_diffuse=0.7, ... mesh_specular=0.2 ... )
- apply_theme(theme_name, auto_save=False)[source]
Apply predefined visual themes to quickly customize plot appearance.
- Parameters:
theme_name (str) – Name of the theme to apply. Available themes: - “dark” : Dark background with white text - “light” : Light background with dark text - “high_contrast” : Maximum contrast for presentations - “minimal” : Clean, minimal styling - “publication” : Optimized for academic publications - “colorful” : Vibrant colors for engaging visuals
auto_save (bool, default True) – Whether to automatically save theme to configuration file.
- Raises:
ValueError – If theme_name is not recognized.
Examples
>>> plotter = BrainPlotter("configs.json") >>> >>> # Apply light theme for presentations >>> plotter.apply_theme("light") >>> >>> # Use high contrast for better visibility >>> plotter.apply_theme("high_contrast") >>> >>> # Publication-ready styling >>> plotter.apply_theme("publication")
- list_figure_config_options()[source]
Display all available figure configuration parameters with descriptions.
Shows parameter names, types, valid ranges, and examples to help users understand what can be customized.
Examples
>>> plotter = BrainPlotter("configs.json") >>> plotter.list_figure_config_options()
- reset_figure_config(auto_save=True)[source]
Reset figure configuration to default values.
- Parameters:
auto_save (bool, default True) – Whether to automatically save reset configuration to file.
Examples
>>> plotter = BrainPlotter("configs.json") >>> plotter.reset_figure_config() # Reset to defaults
- save_config()[source]
Save current configuration (both figure_conf and views_conf) to JSON file.
- Raises:
IOError – If unable to write to configuration file.
Examples
>>> plotter = BrainPlotter("configs.json") >>> plotter.update_figure_config(background_color="white", auto_save=False) >>> plotter.save_config() # Manually save changes
The visualizationtools module provides publication-quality brain surface visualization with flexible layout configurations and advanced rendering capabilities.
Key Features
Multi-view brain surface visualization
JSON-based view configuration system
Publication-ready figure generation
Flexible colormap and annotation support
PyVista-powered 3D rendering
Customizable layouts and camera positions
Main Classes
BrainPlotter
Advanced brain surface visualization with multi-view layouts.
Key Methods:
- plot_surface(): Render single surface with scalar overlays
- plot_multi_view(): Create multi-view layouts
- configure_views(): Set up custom view configurations
- save_figure(): Export high-resolution figures
- add_colorbar(): Add publication-quality colorbars
Common Usage Examples
Basic surface visualization:
from clabtoolkit.visualizationtools import BrainPlotter
# Initialize plotter with default configuration
plotter = BrainPlotter()
# Plot surface with scalar overlay
plotter.plot_surface(
surface_file="lh.pial",
scalar_file="lh.thickness.mgh",
colormap="viridis",
background_color="white"
)
Multi-view layouts:
# Create custom view configuration
view_config = {
"views": [
{"name": "lateral", "position": [1, 0, 0]},
{"name": "medial", "position": [-1, 0, 0]},
{"name": "dorsal", "position": [0, 0, 1]}
],
"layout": {"rows": 1, "cols": 3}
}
# Plot with multiple views
plotter = BrainPlotter(config=view_config)
plotter.plot_multi_view(
surface_files=["lh.pial", "rh.pial"],
scalar_files=["lh.thickness.mgh", "rh.thickness.mgh"]
)
Publication-ready figures:
# Generate high-quality publication figure
plotter.plot_surface(
surface_file="lh.inflated",
scalar_file="lh.curvature.mgh",
save_figure="/path/to/publication_figure.png",
dpi=300,
figure_size=(12, 8),
show_colorbar=True,
colorbar_title="Curvature (mm⁻¹)"
)