### Quick start: plot cortical, subcortical, tracts, connectome, vertexwise, and voxelwise Source: https://teanijarv.github.io/yabplot Quick start example showing the core yabplot API: checking version, listing resources, getting atlas regions, and plotting cortical, subcortical, tract, connectome, vertexwise, and voxelwise data. It uses the 'aparc', 'aseg', 'xtract_medium', and 'schaefer400' atlases, and demonstrates volume projection with yab.project_vol2surf and thresholding. ```python import yabplot as yab import numpy as np # check that you have the latest version print(yab.__version__) # see available atlases and brain meshes print(yab.get_available_resources()) # see the region names for a specific atlas print(yab.get_atlas_regions(atlas='aseg', category='subcortical')) # plotting cortical surface regions atlas = 'aparc' dmap1 = {'L_lateraloccipital': 0.265, 'L_postcentral': 0.086} ax = yab.plot_cortical(data=dmap1, atlas=atlas, vminmax=[0.0, 0.3], cmap='viridis', bmesh='midthickness', views=['left_lateral', 'left_medial']) # plotting subcortical regions atlas = 'aseg' regs = yab.get_atlas_regions(atlas=atlas, category='subcortical') data = np.arange(1, len(regs)+1) ax = yab.plot_subcortical(data=data, atlas=atlas, vminmax=[2, 14], views=['left_lateral', 'superior', 'right_lateral'], bmesh_alpha=0.1, cmap='plasma') # plotting white matter tracts atlas = 'xtract_medium' regs = yab.get_atlas_regions(atlas=atlas, category='tracts') data = {reg: np.sin(i) for i, reg in enumerate(regs)} ax = yab.plot_tracts(data=data, atlas=atlas, style='matte', cmap='coolwarm', views=['left_lateral', 'anterior', 'superior'], bmesh='pial') # plotting connectome data = np.random.rand(400, 400) ax = yab.plot_connectome(matrix=data, atlas='schaefer400', edge_cmap='dense', node_cmap='binary', edge_threshold='95%', views=['left_lateral', 'superior', 'posterior'] ) # volume projection to cortical surface and vertexwise plotting threshold = 4 b_lh_path, b_rh_path = yab.data.get_surface_paths('midthickness', 'bmesh') lh_data, rh_data = yab.project_vol2surf('path/to/yourdata.nii.gz', bmesh='midthickness') lh_data = np.where(lh_data > threshold, lh_data, np.nan) rh_data = np.where(rh_data > threshold, rh_data, np.nan) lh_mesh, rh_mesh = yab.load_vertexwise_mesh(b_lh_path, b_rh_path, lh_data, rh_data) ax = yab.plot_vertexwise(lh_mesh, rh_mesh, cmap='viridis', vminmax=[-10, 10], views=['left_lateral', 'left_medial']) # plotting volume voxel-wise threshold = '99.5%' nii_path = 'path/to/yourdata.nii.gz' ax = yab.plot_voxelwise(nii_path, threshold='99%', cmap='Reds', views=['left_lateral', 'superior', 'anterior']) ``` -------------------------------- ### Install yabplot with uv Source: https://teanijarv.github.io/yabplot Install or update yabplot using the uv package manager. The first command adds the package, the second syncs and upgrades it. ```bash uv add yabplot # to install uv sync --upgrade-package yabplot # to update ``` -------------------------------- ### Import yabplot, matplotlib, and numpy Source: https://teanijarv.github.io/yabplot/tutorials/plot_styling Imports yabplot, matplotlib.pyplot, and numpy for the tutorial examples. ```python import yabplot as yab import matplotlib.pyplot as plt import numpy as np ``` -------------------------------- ### Project volume to surface and plot vertex-wise Source: https://teanijarv.github.io/yabplot/tutorials/plotting_vertexwise Fetches an example NIfTI volume from NeuroVault, loads standard midthickness brain meshes, projects the volume to surface vertex arrays, creates vertex-wise meshes, and plots with different colormaps and thresholding. ```python # fetch an example 3D volume data from neurovault nv_url = "http://neurovault.org/media/images/4874/MNI152_EB_01.nii.gz" nii_path = pooch.retrieve(url=nv_url, known_hash=None, path=pooch.os_cache("yabplot"), fname="sample_task_map.nii.gz") # load the standard brain mesh paths b_lh_path, b_rh_path = yab.data.get_surface_paths('midthickness', 'bmesh') # project 3d volume to 1d surface arrays lh_data, rh_data = yab.project_vol2surf(nii_path, bmesh='midthickness') # make vertex-wise brain meshes with the injected data lh_mesh, rh_mesh = yab.load_vertexwise_mesh(b_lh_path, b_rh_path, lh_data, rh_data) # plot ax = yab.plot_vertexwise(lh_mesh, rh_mesh, cmap='coolwarm') # plotting parameters are largely the same as in plot_cortical ax = yab.plot_vertexwise(lh_mesh, rh_mesh, cmap='Reds', vminmax=[0, 10]) # thresholding data before plotting lh_data = np.where(lh_data > 4, lh_data, np.nan) rh_data = np.where(rh_data > 4, rh_data, np.nan) lh_mesh, rh_mesh = yab.load_vertexwise_mesh(b_lh_path, b_rh_path, lh_data, rh_data) ax = yab.plot_vertexwise(lh_mesh, rh_mesh, cmap='inferno', vminmax=[0, 9]) ``` -------------------------------- ### Import libraries for voxel-wise plotting Source: https://teanijarv.github.io/yabplot/tutorials/plotting_voxelwise Imports the required libraries for the tutorial: pooch for downloading the example data, yabplot for plotting, and numpy for array operations. ```python import pooch import yabplot as yab import numpy as np ``` -------------------------------- ### Install yabplot with pip Source: https://teanijarv.github.io/yabplot Install or update yabplot using pip. The first command installs the package, the second upgrades it. ```bash pip install yabplot # to install pip install yabplot --upgrade # to update ``` -------------------------------- ### Basic voxel-wise plot with default threshold Source: https://teanijarv.github.io/yabplot/tutorials/plotting_voxelwise Downloads an example 3D PET volume using pooch and creates a basic voxel-wise plot with the default threshold (top 5% of voxels) and the 'Reds' colormap. ```python # fetch an example 3D PET volume (D2 receptor density) # [1] Hansen et al., Nat Neurosci (2022) nii_url = "https://github.com/netneurolab/hansen_receptors/raw/main/data/PET_nifti_images/D2_flb457_hc55_sandiego.nii.gz" nii_path = pooch.retrieve(url=nii_url, known_hash=None, path=pooch.os_cache("yabplot"), fname="sandiego2015_pet.nii.gz") # standard visualization using the 'Reds' colormap ax = yab.plot_voxelwise(nii_path, cmap='Reds') ``` -------------------------------- ### Whole-atlas tractometry with project_vol2tract_atlas and plot_tracts Source: https://teanijarv.github.io/yabplot/tutorials/plotting_tractometry Downloads an example FA volume from NeuroVault, samples it across all tracts in the 'xtract_medium' atlas with project_vol2tract_atlas, then plots the resulting tractometry with plot_tracts using three views, the pial brain mesh, and the 'berlin' colormap. ```python # fetch an example 3D fractional anisotropy (FA) volume from neurovault fa_url = "https://neurovault.org/media/images/264/JHU-ICBM-FA-2mm.nii.gz" fa_path = pooch.retrieve(url=fa_url, known_hash=None, path=pooch.os_cache("yabplot"), fname="sample_fa_map.nii.gz") # sample the volume across all tracts in the atlas # this returns a dictionary mapping tract names to their 1D scalar arrays. tract_data = yab.project_vol2tract_atlas(nii_path=fa_path, atlas='xtract_medium') # plot the tractometry ax = yab.plot_tracts( atlas='xtract_medium', data=tract_data, views=['anterior', 'superior', 'left_lateral'], bmesh='pial', cmap='berlin' ) ``` -------------------------------- ### Import required modules for yabplot Source: https://teanijarv.github.io/yabplot/tutorials/custom_background_mesh Imports the required modules for the tutorial: os, pooch, and yabplot. This is the initial setup for using yabplot's custom background mesh functionality. ```python import os import pooch import yabplot as yab ``` -------------------------------- ### YABPlot plotting workflow: data prep, plotter setup, and rendering Source: https://teanijarv.github.io/yabplot/reference/plotting This snippet shows the main plotting routine for YABPlot. It prepares color and data mappings, sets up the plotter with view configurations, iterates over views to add context and region meshes, and finalizes the plot with optional colorbars. It handles both data-driven and atlas-color modes, and supports different display types. ```python # prepare colors and map data if data is not None: 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)} c_vlim = [0, 1] # setup plotter 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) scalar_bar_mapper = None # pre-calculate side tokens for all meshes to avoid regex in loops side_info = {n: _get_side_tokens(n) for n in meshes.keys()} # plotting loop for i, (view_name, cfg) in enumerate(sel_views.items()): plotter.subplot(i // ncols, i % ncols) # add context (uses style kwargs for consistent lighting) add_context_to_view(plotter, ctx_meshes, cfg['side'], bmesh_alpha, bmesh_color, **shading_params) # add regions for name, mesh in meshes.items(): # side filtering using pre-calculated tokens is_left, is_right = side_info[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 # determine properties for this mesh 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: color = d_atlas_colors[name] props.update({'color': color, 'opacity': 1.0}) actor = plotter.add_mesh(mesh, **props) if data is not None and scalar_bar_mapper is None and 'scalars' in props: scalar_bar_mapper = actor.mapper set_camera(plotter, cfg, zoom=zoom) plotter.hide_axes() # colorbar cbar_info = [] if needs_bottom and scalar_bar_mapper: if display_type != 'matplotlib': add_colorbars(plotter, [scalar_bar_mapper], [''], nrows, figsize) else: cbar_info.append({'cmap': cmap, 'vminmax': c_vlim}) return finalize_plot(plotter, export_path, display_type, ax=ax, cbar_info=cbar_info, cbar_kwargs=cbar_kwargs) ``` -------------------------------- ### Import YabPlot and dependencies Source: https://teanijarv.github.io/yabplot/tutorials/custom_background_mesh Imports os, pooch, and yabplot as yab, required to set up the environment for building custom background meshes from nifti images. ```python # Define imports import os import pooch import yabplot as yab ``` -------------------------------- ### Plot subcortical atlas with sculpted and flat styles Source: https://teanijarv.github.io/yabplot/tutorials/getting_started Two examples of plotting the 'aseg' atlas with different styles: 'sculpted' and 'flat'. Views are set to left_lateral, superior, and anterior. ```python ax = yab.plot_subcortical( atlas='aseg', views=['left_lateral', 'superior', 'anterior'], style='sculpted', ) ``` ```python ax = yab.plot_subcortical( atlas='aseg', views=['left_lateral', 'superior', 'anterior'], style='flat', ) ``` -------------------------------- ### load_gii2pv: Load GIfTI and convert to PyVista with smoothing Source: https://teanijarv.github.io/yabplot/reference/utils Loads a GIfTI file, converts it to a PyVista PolyData mesh, and optionally applies Laplacian smoothing. Requires numpy (np) and pyvista (pv). The smoothing parameters control iterations and relaxation factor; higher relaxation factors can shrink the mesh significantly, and mesh.smooth_taubin() is suggested as an alternative if shrinkage is a concern. ```python def load_gii2pv(gii_path, smooth_i=0, smooth_f=0.1): """ Load GIfTI and convert to PyVista format with optional smoothing. Parameters ---------- smooth_i : int Number of smoothing iterations (e.g. 15). smooth_f : float Relaxation factor (0.0 to 1.0, e.g. 0.6). """ verts, faces = load_gii(gii_path) # create pyvista mesh faces_pv = np.hstack([np.full((faces.shape[0], 1), 3), faces]).flatten().astype(int) mesh = pv.PolyData(verts, faces_pv) # apply smoothing if smooth_i > 0: # use Laplacian smoothing (standard vtkSmoothPolyDataFilter) # note: higher relaxation factors can shrink the mesh significantly # if shrinkage is an issue, could consider mesh.smooth_taubin() instead mesh = mesh.smooth(n_iter=smooth_i, relaxation_factor=smooth_f) return mesh ``` -------------------------------- ### Create background mesh with yab.load_nii_as_mesh Source: https://teanijarv.github.io/yabplot/tutorials/custom_background_mesh Creates a background mesh from a NIfTI image using yab.load_nii_as_mesh. Parameters: smooth_i (smoothing iterations), smooth_f (vertex change aggressiveness), threshold (voxel selection after blur), blur_sigma (Gaussian blur in voxel units). Brain-extracted images work best. ```python bg_mesh = yab.load_nii_as_mesh( nii_path=aal_nii, smooth_i=20, smooth_f=0.1, threshold=0.5, blur_sigma=1.5 ) ``` -------------------------------- ### Fetch atlas tracts and sample FA volume Source: https://teanijarv.github.io/yabplot/tutorials/custom_background_mesh Fetches an example FA volume from NeuroVault and samples it across all tracts in the atlas, returning a dictionary mapping tract names to 1D scalar arrays. This is the first step for building a custom background mesh for white matter tract visualization. ```python # fetch an example 3D fractional anisotropy (FA) volume from neurovault fa_url = "https://neurovault.org/media/images/264/JHU-ICBM-FA-2mm.nii.gz" fa_path = pooch.retrieve(url=fa_url, known_hash=None, path=pooch.os_cache("yabplot"), fname="sample_fa_map.nii.gz") # sample the volume across all tracts in the atlas # this returns a dictionary mapping tract names to their 1D scalar arrays. tract_data = yab.project_vol2tract_atlas(nii_path=fa_path, atlas="xtract_medium") ``` -------------------------------- ### get_atlas_regions: Get ordered region names for an atlas Source: https://teanijarv.github.io/yabplot/reference/data Returns the list of region names for a given atlas in the specific order used for mapping data arrays. Handles cortical, subcortical, and tracts categories, with optional custom atlas path. Returns an empty list on errors and raises ValueError for invalid categories. ```python def get_atlas_regions(atlas, category, custom_atlas_path=None): """ Returns the list of region names for a given atlas in the specific order used for mapping data arrays. Parameters ---------- atlas : str Name of the atlas (e.g., 'aparc', 'aseg'). category : str 'cortical', 'subcortical', or 'tracts'. custom_atlas_path : str, optional Path to custom atlas directory. Returns ------- list List of strings containing region names. - If input data is a LIST, it must match this order. - If input data is a DICT, keys must match these names. """ # resolve the directory path try: atlas_dir = _resolve_resource_path(atlas, category, custom_path=custom_atlas_path) except Exception as e: print(f"Error resolving atlas: {e}") return [] # --- case 1: cortical --- if category == 'cortical': check_name = None if custom_atlas_path else atlas try: _, lut_path = _find_cortical_files(atlas_dir, strict_name=check_name) # use parse_lut to get the IDs and the full names list ids, _, names_list, _ = parse_lut(lut_path) # return only the names corresponding to the explicit IDs in the file. return [names_list[i] for i in ids] except Exception as e: print(f"Error parsing cortical atlas: {e}") return [] # --- case 2: subcortical --- elif category == 'subcortical': try: file_map = _find_subcortical_files(atlas_dir) return _get_ordered_names(atlas_dir, file_map) except Exception as e: print(f"Error listing subcortical regions: {e}") return [] # --- case 3: tracts --- elif category == 'tracts': try: file_map = _find_tract_files(atlas_dir) return _get_ordered_names(atlas_dir, file_map) except Exception as e: print(f"Error listing tracts: {e}") return [] else: raise ValueError("Category must be 'cortical', 'subcortical', or 'tracts'") ``` -------------------------------- ### Fetch FA volume, project to atlas, and plot tractometry Source: https://teanijarv.github.io/yabplot/tutorials/plotting_tractometry Downloads a sample FA volume from NeuroVault using pooch, projects it across all tracts in the 'xtract_medium' atlas, and plots the tractometry with multiple views and a custom colormap. ```python # fetch an example 3D fractional anisotropy (FA) volume from neurovault fa_url = "https://neurovault.org/media/images/264/JHU-ICBM-FA-2mm.nii.gz" fa_path = pooch.retrieve(url=fa_url, known_hash=None, path=pooch.os_cache("yabplot"), fname="sample_fa_map.nii.gz") # sample the volume across all tracts in the atlas # this returns a dictionary mapping tract names to their 1D scalar arrays. tract_data = yab.project_vol2tract_atlas(nii_path=fa_path, atlas='xtract_medium') # plot the tractometry ax = yab.plot_tracts( atlas='xtract_medium', data=tract_data, views=['anterior', 'superior', 'left_lateral'], bmesh='pial', cmap='berlin' ) ``` -------------------------------- ### Parse atlas metadata into dictionary Source: https://teanijarv.github.io/yabplot/tutorials/custom_subcortical_atlas Parses the AAL text file into a dictionary mapping integer IDs to region names, replacing spaces with underscores and slashes with hyphens. The loop skips lines that do not start with an integer ID and prints the total count and the resulting dictionary. The output shows 170 regions parsed successfully. ```python atlas_labels = {} with open(aal_txt, 'r') as f_in: for line in f_in: parts = line.strip().split() if len(parts) >= 2: try: rid = int(parts[0]) name = parts[1].replace(' ', '_').replace('/', '-') atlas_labels[rid] = name except ValueError: continue print(f"successfully parsed {len(atlas_labels)} total regions from text file.") print(atlas_labels) ``` ```text successfully parsed 170 total regions from text file. {1: 'Precentral_L', 2: 'Precentral_R', 3: 'Frontal_Sup_2_L', 4: 'Frontal_Sup_2_R', 5: 'Frontal_Mid_2_L', 6: 'Frontal_Mid_2_R', 7: 'Frontal_Inf_Oper_L', 8: 'Frontal_Inf_Oper_R', 9: 'Frontal_Inf_Tri_L', 10: 'Frontal_Inf_Tri_R', 11: 'Frontal_Inf_Orb_2_L', 12: 'Frontal_Inf_Orb_2_R', 13: 'Rolandic_Oper_L', 14: 'Rolandic_Oper_R', 15: 'Supp_Motor_Area_L', 16: 'Supp_Motor_Area_R', 17: 'Olfactory_L', 18: 'Olfactory_R', 19: 'Frontal_Sup_Medial_L', 20: 'Frontal_Sup_Medial_R', 21: 'Frontal_Med_Orb_L', 22: 'Frontal_Med_Orb_R', 23: 'Rectus_L', 24: 'Rectus_R', 25: 'OFCmed_L', 26: 'OFCmed_R', 27: 'OFCant_L', 28: 'OFCant_R', 29: 'OFCpost_L', 30: 'OFCpost_R', 31: 'OFClat_L', 32: 'OFClat_R', 33: 'Insula_L', 34: 'Insula_R', 35: 'Cingulate_Ant_L', 36: 'Cingulate_Ant_R', 37: 'Cingulate_Mid_L', 38: 'Cingulate_Mid_R', 39: 'Cingulate_Post_L', 40: 'Cingulate_Post_R', 41: 'Hippocampus_L', 42: 'Hippocampus_R', 43: 'ParaHippocampal_L', 44: 'ParaHippocampal_R', 45: 'Amygdala_L', 46: 'Amygdala_R', 47: 'Calcarine_L', 48: 'Calcarine_R', 49: 'Cuneus_L', 50: 'Cuneus_R', 51: 'Lingual_L', 52: 'Lingual_R', 53: 'Occipital_Sup_L', 54: 'Occipital_Sup_R', 55: 'Occipital_Mid_L', 56: 'Occipital_Mid_R', 57: 'Occipital_Inf_L', 58: 'Occipital_Inf_R', 59: 'Fusiform_L', 60: 'Fusiform_R', 61: 'Postcentral_L', 62: 'Postcentral_R', 63: 'Parietal_Sup_L', 64: 'Parietal_Sup_R', 65: 'Parietal_Inf_L', 66: 'Parietal_Inf_R', 67: 'SupraMarginal_L', 68: 'SupraMarginal_R', 69: 'Angular_L', 70: 'Angular_R', 71: 'Precuneus_L', 72: 'Precuneus_R', 73: 'Paracentral_Lobule_L', 74: 'Paracentral_Lobule_R', 75: 'Caudate_L', 76: 'Caudate_R', 77: 'Putamen_L', 78: 'Putamen_R', 79: 'Pallidum_L', 80: 'Pallidum_R', 81: 'Thalamus_L', 82: 'Thalamus_R', 83: 'Heschl_L', 84: 'Heschl_R', 85: 'Temporal_Sup_L', 86: 'Temporal_Sup_R', 87: 'Temporal_Pole_Sup_L', 88: 'Temporal_Pole_Sup_R', 89: 'Temporal_Mid_L', 90: 'Temporal_Mid_R', 91: 'Temporal_Pole_Mid_L', 92: 'Temporal_Pole_Mid_R', 93: 'Temporal_Inf_L', 94: 'Temporal_Inf_R', 95: 'Cerebellum_Crus1_L', 96: 'Cerebellum_Crus1_R', 97: 'Cerebellum_Crus2_L', 98: 'Cerebellum_Crus2_R', 99: 'Cerebellum_3_L', 100: 'Cerebellum_3_R', 101: 'Cerebellum_4_5_L', 102: 'Cerebellum_4_5_R', 103: 'Cerebellum_6_L', 104: 'Cerebellum_6_R', 105: 'Cerebellum_7b_L', 106: 'Cerebellum_7b_R', 107: 'Cerebellum_8_L', 108: 'Cerebellum_8_R', 109: 'Cerebellum_9_L', 110: 'Cerebellum_9_R', 111: 'Cerebellum_10_L', 112: 'Cerebellum_10_R', 113: 'Vermis_1_2', 114: 'Vermis_3', 115: 'Vermis_4_5', 116: 'Vermis_6', 117: 'Vermis_7', 118: 'Vermis_8', 119: 'Vermis_9', 120: 'Vermis_10', 121: 'Thal_AV_L', 122: 'Thal_AV_R', 123: 'Thal_LP_L', 124: 'Thal_LP_R', 125: 'Thal_VA_L', 126: 'Thal_VA_R', 127: 'Thal_VL_L', 128: 'Thal_VL_R', 129: 'Thal_VPL_L', 130: 'Thal_VPL_R', 131: 'Thal_IL_L', 132: 'Thal_IL_R', 133: 'Thal_Re_L', 134: 'Thal_Re_R', 135: 'Thal_MDm_L', 136: 'Thal_MDm_R', 137: 'Thal_MDl_L', 138: 'Thal_MDl_R', 139: 'Thal_LGN_L', 140: 'Thal_LGN_R', 141: 'Thal_MGN_L', 142: 'Thal_MGN_R', 143: 'Thal_PuI_L', 144: 'Thal_PuI_R', 145: 'Thal_PuM_L', 146: 'Thal_PuM_R', 147: 'Thal_PuA_L', 148: 'Thal_PuA_R', 149: 'Thal_PuL_L', 150: 'Thal_PuL_R', 151: 'ACC_sub_L', 152: 'ACC_sub_R', 153: 'ACC_pre_L', 154: 'ACC_pre_R', 155: 'ACC_sup_L', 156: 'ACC_sup_R', 157: 'N_Acc_L', 158: 'N_Acc_R', 159: 'VTA_L', 160: 'VTA_R', 161: 'SN_pc_L', 162: 'SN_pc_R', 163: 'SN_pr_L', 164: 'SN_pr_R', 165: 'Red_N_L', 166: 'Red_N_R', 167: 'LC_L', 168: 'LC_R', 169: 'Raphe_D', 170: 'Raphe_M'} ``` -------------------------------- ### Load connectivity data and create DataFrame Source: https://teanijarv.github.io/yabplot/tutorials/plotting_connectome Loads a connectivity matrix CSV and a labels CSV, then constructs a pandas DataFrame with row and column labels. The data is read with header=None for the matrix and the labels are taken from the column names of the labels file. ```python import pandas as pd import yabplot as yab import matplotlib.pyplot as plt data = pd.read_csv('/Users/to8050an/Developer/yabplot_miscfiles/test_data/hcp_connectivity/funcMatrix_ctx_schaefer_400.csv', header=None).to_numpy() labels = list(pd.read_csv('/Users/to8050an/Developer/yabplot_miscfiles/test_data/hcp_connectivity/funcLabels_ctx_schaefer_400.csv').columns) df = pd.DataFrame(data, index=labels, columns=labels) df ``` -------------------------------- ### Generate QC report with qc_custom_subcortical_atlas Source: https://teanijarv.github.io/yabplot/tutorials/custom_subcortical_atlas Generates a quality control report for custom subcortical atlases. The function scans .vtk files, calculates physical properties (vertex count, face count, volume in mm³), saves a .txt summary, and saves a picture of each structure. The example is commented out; uncomment and set the atlas directories to run. ```python from yabplot.atlas_builder import qc_custom_subcortical_atlas # print("\ngenerating qc report for the no-cerebellum atlas...") # qc_custom_subcortical_atlas(atlas_dir=dir_no_cerebellum) # print("generating qc report for the full subcortical atlas...") # qc_custom_subcortical_atlas(atlas_dir=dir_full_subcortical) ``` -------------------------------- ### yabplot.utils.load_gii2pv(gii_path, smooth_i=0, smooth_f=0.1) Source: https://teanijarv.github.io/yabplot/reference/utils Loads a GIfTI file and converts it to a PyVista mesh, with optional Laplacian smoothing. ```APIDOC ## `yabplot.utils.load_gii2pv(gii_path, smooth_i=0, smooth_f=0.1)` ### Description Load GIfTI and convert to PyVista format with optional smoothing. ### Method Function call ### Endpoint `yabplot.utils.load_gii2pv(gii_path, smooth_i=0, smooth_f=0.1)` ### Parameters #### Path Parameters - **gii_path** (string) - Required - Path to the GIfTI file. #### Query Parameters - **smooth_i** (int) - Optional - Number of smoothing iterations (e.g. 15). Default: 0. - **smooth_f** (float) - Optional - Relaxation factor (0.0 to 1.0, e.g. 0.6). Default: 0.1. ### Request Example ```python mesh = yabplot.utils.load_gii2pv('path/to/file.gii', smooth_i=15, smooth_f=0.6) ``` ### Response #### Success Response - **mesh** (PyVista PolyData) - The loaded and optionally smoothed mesh. #### Response Example ```python mesh ``` ``` -------------------------------- ### Configure file paths and output directory for custom cortical atlas Source: https://teanijarv.github.io/yabplot/tutorials/custom_cortical_atlas Sets up file paths for the source AAL3 atlas (NIfTI and text files) and creates the output directory for the custom Workbench atlas. Requires the AAL3v2_for_SPM12.tar.gz download from the provided URL. ```python import os import numpy as np import yabplot as yab # define where your source NIfTI and text files are located # you can download the same atlas for this tutorial in here: # https://www.gin.cnrs.fr/wp-content/uploads/AAL3v2_for_SPM12.tar.gz aal_txt = '/Users/to8050an/Developer/yabplot_miscfiles/AAL3/AAL3v1_1mm.nii.txt' aal_nii = '/Users/to8050an/Developer/yabplot_miscfiles/AAL3/AAL3v1_1mm.nii.gz' # define where the new atlas will be saved workdir_wb = 'dev/my_custom_atlases/cortical/AAL3v1' wb_label_list = os.path.join(workdir_wb, 'wb_labels.txt') os.makedirs(workdir_wb, exist_ok=True) ``` -------------------------------- ### Build cortical atlas with yab.build_cortical_atlas Source: https://teanijarv.github.io/yabplot/tutorials/custom_cortical_atlas Runs the atlas builder with the specified NIfTI file, label list, output directory, and exclusion list. The output shows the pipeline steps and warns that two regions were lost during smoothing/masking, resulting in 86 saved regions. ```python print("building cortical atlas...") yab.build_cortical_atlas( nii_path=aal_nii, wb_txt_path=wb_label_list, out_dir=os.path.join(workdir_wb, "atlas"), exclude_list=exclude_keywords ) ``` ```text building cortical atlas... fetching standard surfaces... running volume-to-surface projection... found 88 initial cortical regions. mapping and cleaning... building surface adjacency and filling holes... smoothing boundaries... [WARNING] Cingulate_Ant_L (id 35) lost during smoothing/masking. dropping from lut. [WARNING] Cingulate_Ant_R (id 36) lost during smoothing/masking. dropping from lut. final polished atlas saved to: dev/my_custom_atlases/cortical/AAL3v1/atlas saved 86 regions (2 empty regions dropped). ``` -------------------------------- ### Build subcortical atlas with yab.build_subcortical_atlas Source: https://teanijarv.github.io/yabplot/tutorials/custom_background_mesh Configures file paths, parses the AAL3 text file into a dictionary, defines subcortical keywords, builds a subcortical atlas with yab.build_subcortical_atlas, and verifies the number of regions. Requires the AAL3v1_1mm.nii.txt and .nii.gz files; the output is stored in ./subcortical/AAL3v1. ```python # define where your source NIfTI and text files are located # you can download the same atlas for this tutorial in here: # https://www.gin.cnrs.fr/wp-content/uploads/AAL3v2_for_SPM12.tar.gz aal_txt = "/Users/anthonygagnon/Downloads/AAL3/AAL3v1_1mm.nii.txt" aal_nii = "/Users/anthonygagnon/Downloads/AAL3/AAL3v1_1mm.nii.gz" # Define output folder for reconstructed meshes. dir_full_subcortical = "./subcortical/AAL3v1" # This section parses the AAL3 text file into a standard python dictionary mapping integers IDs to region names. atlas_labels = {} with open(aal_txt, 'r') as f_in: for line in f_in: parts = line.strip().split() if len(parts) >= 2: try: rid = int(parts[0]) name = parts[1].replace(' ', '_').replace('/', '-') atlas_labels[rid] = name except ValueError: continue print(f"successfully parsed {len(atlas_labels)} total regions from text file.") print(atlas_labels) # Filtering the atlas labels to extract subcortical regions and cerebellar regions. # define all subcortical keywords present in the mixed AAL3 atlas subcortical_keywords = [ 'Hippocampus', 'Amygdala', 'Caudate', 'Putamen', 'Pallidum', 'Thalamus', 'Thal', 'Cerebellum', 'Vermis', 'N_Acc', 'VTA', 'SN', 'Red_N', 'LC', 'Raphe' ] print("--- building atlas 1: full subcortical (using include_list) ---") yab.build_subcortical_atlas( nii_path=aal_nii, labels_dict=atlas_labels, out_dir=dir_full_subcortical, include_list=subcortical_keywords, smooth_i=20, smooth_f=0.7 ) # check the amount of regions regions_full = yab.get_atlas_regions(atlas=None, category='subcortical', custom_atlas_path=dir_full_subcortical) print(f"full atlas: found {len(regions_full)} meshes.") ```