parcellationtools module
- class clabtoolkit.parcellationtools.Parcellation(parc_file=None, color_table=None, affine=None, parc_id=None, space_id='unknown')[source]
Bases:
objectComprehensive class for working with brain parcellation data.
Provides tools for loading, manipulating, and analyzing brain parcellation files with associated lookup tables. Supports filtering, masking, grouping, volume calculations, and various export formats for neuroimaging workflows.
- __init__(parc_file=None, color_table=None, affine=None, parc_id=None, space_id='unknown')[source]
Initialize Parcellation object from file or array.
- Parameters:
parc_file (str, Path, or np.ndarray, optional) – Path to parcellation file (NIfTI format) or numpy array containing parcellation data. If string/Path, loads from file and attempts to find associated TSV/LUT files. Default is None.
color_table (str, Path, or dict, optional) – Color lookup table for parcellation regions. Can be: - Path to TSV/LUT file with columns: index, name, R, G, B, A (and optionally opacity) - Dictionary with required keys ‘index’, ‘name’, ‘color’ and optional keys ‘opacity’, ‘headerlines’ If None, color table is auto-generated or loaded from sidecar files. Default is None.
affine (np.ndarray, optional) – 4x4 affine transformation matrix. If None and parc_file is array, creates identity matrix centered on data. Default is None.
parc_id (str, optional) – Unique identifier for the parcellation. If None, generated from file name or set to ‘numpy_array’ for array input. Default is None.
space_id (str, optional) – Identifier for the space in which the parcellation is defined (e.g., ‘MNI152NLin6Asym’, ‘native’). Default is “unknown”.
- data
3D parcellation data array (integer labels).
- Type:
np.ndarray
- affine
4x4 affine transformation matrix.
- Type:
np.ndarray
- dtype
Data type of the parcellation.
- Type:
np.dtype
- Raises:
ValueError – If parcellation file does not exist or parc_file is None.
FileNotFoundError – If specified color_table file does not exist.
Examples
>>> # Load from file with automatic color table detection >>> parc = Parcellation('parcellation.nii.gz') >>> >>> # Load with explicit color table >>> parc = Parcellation('parcellation.nii.gz', color_table='colors.tsv') >>> >>> # Create from array with custom affine >>> parc = Parcellation(label_array, affine=img.affine, parc_id='custom') >>> >>> # Create from array with full color dictionary >>> color_dict = { ... 'index': [1, 2, 3], ... 'name': ['region1', 'region2', 'region3'], ... 'color': ['#FF0000', '#00FF00', '#0000FF'], ... 'opacity': [1.0, 0.8, 0.6], # optional ... 'headerlines': ['# My custom parcellation'] # optional ... } >>> parc = Parcellation(label_array, color_table=color_dict) >>> >>> # Create with minimal color dictionary (opacity defaults to 1.0) >>> color_dict = { ... 'index': [1, 2, 3], ... 'name': ['region1', 'region2', 'region3'], ... 'color': ['#FF0000', '#00FF00', '#0000FF'] ... } >>> parc = Parcellation(label_array, color_table=color_dict)
- get_space_id()[source]
Infer the space identifier from the parcellation filename if space is not yet set.
- Returns:
space_id – The space identifier extracted from the BIDS filename, or “unknown” if not found.
- Return type:
Notes
This method only attempts to extract the space entity from BIDS-compliant filenames. It does not modify the space attribute.
Examples
>>> # Extract from BIDS filename >>> parc = Parcellation('sub-01_space-t1_atlas-xxx.nii.gz') >>> space_id = parc.get_space_id() >>> print(space_id) 't1'
>>> # Non-BIDS filename >>> parc = Parcellation('custom_parcellation.nii.gz') >>> space_id = parc.get_space_id() >>> print(space_id) 'unknown'
>>> # No file set >>> parc = Parcellation() >>> space_id = parc.get_space_id() >>> print(space_id) 'unknown'
- set_space_id(space_id=None)[source]
Set the space identifier for the parcellation.
- Parameters:
space_id (str, optional) – Identifier for the space. If None, attempts to infer from filename using get_space_id().
- Returns:
space_id – The space identifier that was set.
- Return type:
Notes
Priority order for setting space: 1. Provided space_id parameter (if not None) 2. Inferred from filename via get_space_id() (returns “unknown” if not found)
This method sets the space attribute of the Parcellation object.
Examples
>>> # Explicitly set space >>> parc = Parcellation('sub-01_atlas-xxx.nii.gz') >>> parc.set_space_id('mni152') 'mni152'
>>> # Infer from filename >>> parc = Parcellation('sub-01_space-t1_atlas-xxx.nii.gz') >>> parc.set_space_id() 't1'
>>> # Fallback to unknown >>> parc = Parcellation('custom_parcellation.nii.gz') >>> parc.set_space_id() 'unknown'
- get_parcellation_id()[source]
Generate a unique identifier for the parcellation based on its filename. If the filename follows BIDS naming conventions, it extracts relevant entities to form the ID. If the filename does not follow BIDS conventions, it uses the filename without extension.
- Returns:
Unique identifier for the parcellation, formatted as ‘atlas-<atlas_name>_seg-<seg_name>_scale-<scale_value>_desc-<description>’. If no entities are found, it returns the filename without extension.
- Return type:
- Raises:
ValueError – If the parcellation file is not set.
Notes –
This method is useful for identifying and categorizing parcellation files based on their naming conventions. –
It can be used to easily retrieve or reference specific parcellations in analyses or reports. –
Examples
>>> parc = Parcellation('sub-01_ses-01_acq-mprage_space-t1_atlas-xxx_seg-yyy_scale-1_desc-test.nii.gz') >>> parc_id = parc.get_parcellation_id() >>> print(parc_id) 'atlas-xxx_seg-yyy_scale-1_desc-test' >>> parc = Parcellation('custom_parcellation.nii.gz') >>> parc_id = parc.get_parcellation_id() >>> print(parc_id) 'custom_parcellation'
- export_summary_to_hdf5(out_file, overwrite=False)[source]
Export parcellation summary to HDF5 file.
- Parameters:
out_file (str) – Path to output HDF5 file.
- Raises:
ValueError – If the parcellation data is not set.
Notes
This method saves the parcellation data, index, name, and color attributes to an HDF5 file. It is useful for archiving and sharing parcellation information in a structured format.
Examples
>>> parc.export_summary_to_hdf5('parcellation_summary.h5')
- prepare_for_tracking()[source]
Prepare parcellation for fiber tracking by merging cortical white matter labels to their corresponding cortical gray matter values.
Converts white matter labels (>=3000) to corresponding gray matter labels by subtracting 3000, and removes other structures labels (>=5000). This method is useful for tractography applications where the parcellation was generated using Chimera (https://github.com/connectomicslab/chimera). It can also be applied to other parcellations following the same labeling scheme. - Gray matter regions: 1-2999 - White matter regions: 3000-4999 (to be merged with gray matter)
3000 for white matter label
For FreeSurfer cortical white matter labels, the value is 3000 + corresponding gray matter label
Other structures: 5000-5008 (to be removed)
Corporus Callosum: 5009-5013 (to be merged with white matter)
Examples
>>> parc.prepare_for_tracking() >>> print(f"Max label after prep: {parc.data.max()}")
- keep_by_name(names2keep, rearrange=False)[source]
Filter parcellation to keep only regions with specified names.
- Parameters:
Examples
>>> # Keep only hippocampal regions >>> parc.keep_by_name('hippocampus') >>> >>> # Keep multiple regions and rearrange >>> parc.keep_by_name(['frontal', 'parietal'], rearrange=True)
- keep_by_code(codes2keep, rearrange=False)[source]
Filter parcellation to keep only specified region codes.
- Parameters:
- Raises:
ValueError – If codes2keep is empty or contains invalid codes.
Examples
>>> # Keep specific regions >>> parc.keep_by_code([1, 2, 5, 10]) >>> >>> # Keep and rearrange >>> parc.keep_by_code([100, 200, 300], rearrange=True)
- remove_by_code(codes2remove, rearrange=False)[source]
Remove regions with specified codes from parcellation.
- Parameters:
Examples
>>> # Remove specific regions >>> parc.remove_by_code([1, 5, 10]) >>> >>> # Remove and rearrange >>> parc.remove_by_code([100, 200], rearrange=True)
- remove_by_name(names2remove, rearrange=False)[source]
Remove regions with specified names from parcellation.
- Parameters:
Examples
>>> # Remove ventricles >>> parc.remove_by_name('ventricle') >>> >>> # Remove multiple structures >>> parc.remove_by_name(['csf', 'unknown'], rearrange=True)
- apply_mask(image_mask, mask_codes=None, invert=False, fill=False)[source]
Apply spatial mask to restrict parcellation to specific regions.
- Parameters:
image_mask (str, Path, np.ndarray, or Parcellation) – 3D mask array, parcellation object, or path to mask file. Can be binary mask (0/1) or labeled image with region codes.
mask_codes (list or np.ndarray, optional) – Specific codes in the mask image to use for masking. If None, uses all non-zero values in mask. Default is None.
invert (bool, optional) – If False, keep only voxels where mask has specified codes. If True, remove voxels where mask has specified codes. Default is False.
fill (bool, optional) – Whether to grow regions to fill mask using region growing. Default is False.
- Raises:
ValueError – If mask file doesn’t exist or shapes don’t match.
Examples
>>> # Apply binary cortical mask >>> parc.apply_mask(cortex_mask) >>> >>> # Mask using specific regions from another parcellation >>> parc.apply_mask(roi_parc, mask_codes=[1, 2, 3]) >>> >>> # Inverse masking with region growing >>> parc.apply_mask(exclusion_mask, invert=True, fill=True)
- mask_image(image_2mask, masked_image=None, roi_codes=None, roi_names=None, invert=False)[source]
Mask external images using parcellation as binary mask.
- Parameters:
image_2mask (str, Path, list, or np.ndarray) – Image(s) to mask using parcellation. Can be file path(s) or array.
masked_image (str, Path, list, optional) – Output path(s) for masked images. Required when image_2mask is path(s). Ignored when image_2mask is numpy array. Default is None.
roi_codes (str, list or np.ndarray, optional) – Region codes to use for masking. Default is None (all non-zero regions).
roi_names (str or list, optional) – Region names to use for masking. Default is None.
invert (bool, optional) – If False, keep only voxels within specified regions. If True, remove voxels within specified regions. Default is False.
- Returns:
If image_2mask is numpy array, returns masked array. If image_2mask is path(s), returns list of output paths.
- Return type:
np.ndarray or list
- Raises:
ValueError – If both roi_codes and roi_names are specified, if output paths don’t match input paths in length, or files don’t exist, or shapes don’t match.
Examples
>>> # Mask T1 image with all parcellation regions >>> parc.mask_image('T1w.nii.gz', 'T1w_masked.nii.gz') ['T1w_masked.nii.gz']
>>> # Mask with specific region codes >>> parc.mask_image('fmri.nii.gz', 'fmri_masked.nii.gz', roi_codes=[1, 2, 3]) ['fmri_masked.nii.gz']
>>> # Mask with specific region names >>> parc.mask_image('dwi.nii.gz', 'dwi_masked.nii.gz', roi_names=['cortex', 'hippocampus']) ['dwi_masked.nii.gz']
>>> # Inverted masking (remove specific regions) >>> parc.mask_image('dwi.nii.gz', 'dwi_masked.nii.gz', roi_codes=[5, 6], invert=True) ['dwi_masked.nii.gz']
>>> # Mask numpy array >>> masked_data = parc.mask_image(img_array, roi_codes=[10, 20])
- compute_region_adjacency(roi_codes=None, roi_names=None, rearrange=False)[source]
Computes the region adjacency (neighbor) matrix for the parcellation.
- Parameters:
roi_codes (list or np.ndarray, optional) – Specific region codes to include. Default is None (all regions).
roi_names (list or str, optional) – Specific region names to include. Default is None.
rearrange (bool, optional) – Whether to rearrange the parcellation labels before computing connectivity. Default is False.
- Returns:
neighb_matrix (np.ndarray) – Binary adjacency matrix (n_regions x n_regions) indicating neighboring regions.
source (dict) – Dictionary containing source region indices, codes, and names.
target (dict) – Dictionary containing target region indices, codes, and names.
- Raises:
ValueError – If both roi_codes and roi_names are specified.
- Return type:
- compute_centroids(roi_codes=None, roi_names=None, gaussian_smooth=True, sigma=1.0, closing_iterations=2, centroid_table=None)[source]
Compute region centroids, voxel counts, and volumes.
- Parameters:
roi_codes (list or np.ndarray, optional) – Specific region codes to include. Default is None (all regions).
roi_names (list or str, optional) – Specific region names to include. Default is None.
gaussian_smooth (bool, optional) – Whether to apply Gaussian smoothing before centroid calculation. Default is True.
sigma (float, optional) – Standard deviation for Gaussian smoothing. Default is 1.0.
closing_iterations (int, optional) – Number of morphological closing iterations. Default is 2.
centroid_table (str or Path, optional) – Path to save results as TSV file. Default is None.
- Returns:
DataFrame with columns: index, name, color, x_vox, y_vox, z_vox, x_mm, y_mm, z_mm, nvoxels, volume.
- Return type:
pd.DataFrame
- Raises:
ValueError – If both roi_codes and roi_names are specified.
Notes
This method sets the centroids attribute (Nx3 array in mm or voxel coordinates).
Examples
>>> # Compute all centroids >>> centroids_df = parc.compute_centroids() >>> >>> # Specific regions with file output >>> df = parc.compute_centroids( ... roi_codes=[1, 2, 3], ... centroid_table='centroids.tsv' ... ) >>> # Specific regions by name >>> df = parc.compute_centroids( ... roi_names=['hippocampus', 'amygdala'], ... centroid_table='centroids.tsv' ... )
- get_regionwise_timeseries(time_series_data, vols_to_delete=None, method='nilearn', metric='mean', roi_codes=None, roi_names=None)[source]
Compute region-wise time series.
- Parameters:
time_series_data (str or np.ndarray) – Path to time series file or numpy array with shape (dimx X dimy X dimZ x Timepoints).
roi_codes (list or np.ndarray, optional) – Specific region codes to include. Default is None (all regions).
roi_names (list or str, optional) – Specific region names to include. Default is None.
ouput_h5file (str, optional) – Path to save results as HDF5 file. Default is None.
- Returns:
DataFrame with columns: index, name, color, X, Y, Z (mm), nvoxels, volume.
- Return type:
pd.DataFrame
- Raises:
ValueError – If both roi_codes and roi_names are specified.
Examples
>>> # Compute region-wise time series from file >>> region_ts = parc.get_regionwise_timeseries('timeseries.nii.gz') >>> # Compute from numpy array >>> region_ts = parc.get_regionwise_timeseries(time_series_data=np.random.rand(64, 64, 64, 100)) >>> # Compute with specific regions using codes >>> region_ts = parc.get_regionwise_timeseries( ... time_series_data='timeseries.nii.gz', ... roi_codes=[1, 2, 3])
- surface_extraction(roi_codes=None, roi_names=None, gaussian_smooth=True, smooth_iterations=10, fill_holes=True, sigma=1.0, closing_iterations=1, out_filename=None, merge_surfaces=True, out_format='freesurfer', save_annotation=True, overwrite=False)[source]
Extract 3D surface meshes from parcellation regions.
Uses marching cubes algorithm with optional smoothing and hole filling to create high-quality surface meshes for visualization or analysis.
- Parameters:
roi_codes (list or np.ndarray, optional) – Region codes to extract surfaces for. Default is None (all regions).
roi_names (list or str, optional) – Region names to extract surfaces for. Default is None.
gaussian_smooth (bool, optional) – Whether to apply Gaussian smoothing to volume. Default is True.
smooth_iterations (int, optional) – Number of Taubin smoothing iterations. Default is 10.
fill_holes (bool, optional) – Whether to fill holes in extracted meshes. Default is True.
sigma (float, optional) – Standard deviation for Gaussian smoothing. Default is 1.0.
closing_iterations (int, optional) – Morphological closing iterations before extraction. Default is 1.
out_filename (str, optional) – Output file path for merged surface. Default is None.
merge_surfaces (bool, optional) – Whether to merge all region surfaces into one. Default is True.
out_format (str, optional) – Output format: ‘freesurfer’, ‘vtk’, ‘ply’, ‘stl’, ‘obj’. Default is ‘freesurfer’.
save_annotation (bool, optional) – Whether to save annotation file with surface. Default is True.
overwrite (bool, optional) – Whether to overwrite existing files. Default is False.
- Returns:
Merged surface object containing all extracted regions or list of surfaces.
- Return type:
- Raises:
ValueError – If both roi_codes and roi_names are specified.
FileNotFoundError – If output directory doesn’t exist.
FileExistsError – If output file exists and overwrite=False.
Examples
>>> # Extract all surfaces >>> surface = parc.surface_extraction() >>> >>> # Extract specific regions with high quality >>> surface = parc.surface_extraction( ... roi_codes=[1, 2, 3], ... smooth_iterations=20, ... out_filename='regions.surf' ... )
- adjust_values()[source]
Synchronize index, name, and color attributes with data contents.
Removes entries for codes not present in data and updates min/max label range.
Examples
>>> parc.adjust_values() >>> print(f"Regions in data: {len(parc.index)}")
- group_by_codes(group_dict, keep_ungrouped=False)[source]
Group array values and create color table for new groups.
Structures not included in any group will remain unchanged with their original properties in both the array and color table.
Parameters:
- group_dictdict
{new_id: {‘index’: [old_ids], ‘name’: str, ‘color’: str, ‘opacity’: float}} Index values can be integers, strings with ranges (“11:12”, “50-52”), or mixed. Name, color, and opacity are optional.
- keep_ungroupedbool, optional
Whether to keep structures not included in any group. Default is False.
Returns:
- tuple(modified_array, color_table)
- modified_arraynumpy.ndarray
Array with grouped values replaced by new IDs. Ungrouped structures remain unchanged.
- color_tabledict
Color table with ‘index’, ‘name’, ‘color’, ‘opacity’, ‘headerlines’ keys. Includes both grouped structures and ungrouped structures with original properties.
Examples:
>>> import numpy as np >>> array = np.random.randint(0, 60, (100, 100, 100)) >>> >>> # Define groups with mixed specifications >>> group_dict = { ... 3: {'index': ["11:12", "50-52", 13]}, # Auto-generated name and color ... 4: {'index': [10, 49], 'name': 'Thalamus', 'color': '#33FF57', 'opacity': 0.8}, ... 5: {'index': [17, 53, 18, 54], 'name': 'LimbicSystem', 'color': '#3357FF'}, ... 6: {'index': [8, 47], 'name': 'Cerebellum', 'color': '#F1C40F', 'opacity': 0.8} ... } >>> >>> grouped_array, color_table = parc.group_by_codes(group_dict) >>> print(color_table['index']) # [3, 4, 5, 6, ...ungrouped codes...] >>> print(color_table['name']) # ['group_1', 'Thalamus', 'LimbicSystem', 'Cerebellum', ...original names...]
- group_by_names(group_dict, keep_ungrouped=True)[source]
Group array values and create color table for new groups using name-based dictionary.
Structures not included in any group will remain unchanged with their original properties in both the array and color table.
Parameters:
- group_dictdict
{name: {‘codes’: [old_ids], ‘color’: (R,G,B)/hex or str, ‘opacity’: float, ‘index’: new_id}} Codes can be integers, strings with ranges (“11:12”, “50-52”), or mixed. Color can be RGB tuple (0-255) or hex string. Opacity is optional (default: 1.0).
- keep_ungroupedbool, optional
Whether to keep structures not included in any group. Default is True.
Returns:
- tuple(modified_array, color_table)
- modified_arraynumpy.ndarray
Array with grouped values replaced by new IDs. Ungrouped structures remain unchanged.
- color_tabledict
Color table with ‘index’, ‘name’, ‘color’, ‘opacity’, ‘headerlines’ keys. Includes both grouped structures and ungrouped structures with original properties.
Examples:
>>> group_dict = { ... 'BasalGanglia': {"codes": [11, 12, 50, 51, 13, 52], "color": (255, 0, 0), "opacity": 0.8, "index": 1}, ... 'Thalamus': {"codes": [10, 49], "color": (0, 255, 0), "opacity": 0.8, "index": 2}, ... 'Limbic': {"codes": [17, 53, 18, 54, 26, 58], "color": (0, 0, 255), "opacity": 0.8, "index": 3}, ... 'Cerebellum': {"codes": [7, 46], "color": (255, 255, 0), "opacity": 0.8, "index": 4} ... } >>> >>> grouped_array, color_table = parc.group_by_names(group_dict) >>> print(color_table['index']) # [1, 2, 3, 4, ...ungrouped codes...] >>> print(color_table['name']) # ['BasalGanglia', 'Thalamus', 'Limbic', 'Cerebellum', ...original names...]
- rearrange(offset=0)[source]
Rearrange parcellation labels to consecutive integers.
- Parameters:
offset (int, optional) – Starting value for rearranged labels. Default is 0 (starts from 1).
Examples
>>> # Rearrange to 1, 2, 3, ... >>> parc.rearrange() >>> >>> # Start from 100 >>> parc.rearrange(offset=99)
- harmonize()[source]
Harmonize parcellation attributes with data contents.
Ensures index, name, color and opacity attributes align in type and length with actual data values, removing unused entries and updating min/max label range.
Examples
>>> parc.harmonize() >>> print(f"Regions in data: {len(parc.index)}")
- add_parcellation(parc2add, append=False)[source]
Combine another parcellation into current object.
- Parameters:
parc2add (Parcellation or list) – Parcellation object(s) to add.
append (bool, optional) – If True, adds new labels by offsetting. If False, overlays directly. Default is False.
Examples
>>> # Overlay parcellations >>> parc1.add_parcellation(parc2, append=False) >>> >>> # Append with new labels >>> parc1.add_parcellation(parc2, append=True)
- save_parcellation(out_file, affine=None, headerlines=[], lut_file=None, lut_type='lut', force=True)[source]
Save parcellation to NIfTI file with optional lookup tables.
- Parameters:
out_file (str) – Output file path.
affine (np.ndarray, optional) – Affine transformation matrix. If None, uses object’s affine.
headerlines (list, str, or None, optional) – Header lines for LUT format. If None, uses object’s headerlines.
lut_file (str, Path, list of str/Path, or None, optional) – Path(s) for lookup table file(s). If None, paths are auto-generated from out_file using the appropriate extension for each lut_type. If a list, must match the length of lut_type.
lut_type (str or list of str, optional) – Lookup table format(s): ‘lut’, ‘tsv’, ‘fsl’, or ‘nilearn’. Can be a list to export multiple formats simultaneously, e.g. [‘lut’, ‘tsv’]. Default is ‘lut’.
force (bool, optional) – Whether to overwrite existing files. Default is True.
- Raises:
ValueError – If lut_file is a list whose length does not match lut_type, or if an unrecognised lut_type is given.
Examples
>>> # Save with a single LUT format >>> parc.save_parcellation('output.nii.gz', lut_type='tsv')
>>> # Save with multiple LUT formats (auto-generated paths) >>> parc.save_parcellation('output.nii.gz', lut_type=['lut', 'tsv'])
>>> # Save with multiple LUT formats and explicit paths >>> parc.save_parcellation( ... 'output.nii.gz', ... lut_type=['lut', 'tsv'], ... lut_file=['custom.lut', 'custom.tsv'] ... )
- load_colortable(lut_file=None)[source]
Load lookup table to associate codes with names and colors.
- Parameters:
lut_file (str or dict, optional) – Path to LUT file or dictionary with index/name/color keys. Default is None.
Examples
>>> # Load FreeSurfer LUT >>> parc.load_colortable('FreeSurferColorLUT.txt') >>> >>> # Load TSV table >>> parc.load_colortable('regions.tsv')
- sort_index()[source]
Sort index, name, and color attributes by index values.
Examples
>>> parc.sort_index() >>> print(f"First region: {parc.name[0]} (code: {parc.index[0]})")
- export_colortable(out_file, lut_type='lut', headerlines=[], force=True)[source]
Export lookup table to file.
- Parameters:
Examples
>>> # Export FreeSurfer LUT >>> parc.export_colortable('regions.lut', lut_type='lut') >>> >>> # Export TSV >>> parc.export_colortable('regions.tsv', lut_type='tsv')
- replace_values(codes2rep, new_codes=None)[source]
Replace region codes with new values, supporting group replacements.
- parc_range()[source]
Update minimum and maximum label values in parcellation.
Sets minlab and maxlab attributes based on non-zero values in data.
- Returns:
tuple –
- minlabint
Minimum label value (excluding zero).
- maxlabint
Maximum label value.
- Return type:
(minlab, maxlab)
Examples
>>> parc.parc_range() >>> print(f"Label range: {parc.minlab} - {parc.maxlab}")
- compute_morphometry_table(output_table=None, add_bids_entities=False, map_files=None, map_ids=None, units='unknown', exclude_by_code=None, exclude_by_name=None, include_by_code=None, include_by_name=None, include_global=True)[source]
Compute morphometry table for all regions in parcellation. Sets morphometry containing region volumes and statistics.
- Parameters:
output_table (str or Path, optional) – Path to save the output table. If None, does not save. Default is None.
add_bids_entities (bool, optional) – Whether to add BIDS entities to the output. Default is False.
map_files (str, Path, or list of str/Path, optional) – Paths to additional map files for morphometry. If None, only base morphometry is computed. Default is None. This method will compute morphometry for each map file provided.
map_ids (str or list, optional) – IDs for the additional maps. If None, uses filenames as IDs. Default is None.
units (str or list, optional) – Units for the additional maps. If None, uses “unknown”. Default is “unknown”.
include_by_code (list or np.ndarray, optional) – List of region codes to include. If None, includes all. Default is None.
include_by_name (list or str, optional) – List of region names to include. If None, includes all. Default is None.
exclude_by_code (list or np.ndarray, optional) – List of region codes to exclude. If None, excludes none. Default is None.
exclude_by_name (list or str, optional) – List of region names to exclude. If None, excludes none. Default is None.
include_global (bool, optional) – Whether to include global morphometry metrics. Default is True.
- Raises:
TypeError – If output_table is not a string or Path, or if map_files/map_ids/units have incorrect types.
FileNotFoundError – If the output directory does not exist.
ValueError – If lengths of map_files, map_ids, and units don’t match after normalization.
Examples
>>> from pathlib import Path >>> # Compute morphometry table and save to CSV >>> parc.compute_morphometry_table( ... output_table='morphometry.csv', ... add_bids_entities=True, ... map_files=['map1.nii.gz', 'map2.nii.gz'], ... map_ids=['map1', 'map2'], ... units=['mm^3', 'unknown'] ... ) >>> # Using Path objects >>> parc.compute_morphometry_table( ... output_table=Path('morphometry.csv'), ... add_bids_entities=True, ... map_files=[Path('map1.nii.gz'), Path('map2.nii.gz')], ... map_ids=['map1', 'map2'], ... units=['mm^3', 'unknown'] ... ) >>> # Compute morphometry without additional maps >>> parc.compute_morphometry_table( ... output_table='morphometry_base.csv', ... add_bids_entities=False ... ) >>> # Compute morphometry with a single map file as Path >>> parc.compute_morphometry_table( ... output_table=Path('morphometry_single.csv'), ... add_bids_entities=True, ... map_files=Path('single_map.nii.gz'), ... map_ids='single_map', ... units='mm^3' ... )
- compute_volume_table(exclude_by_code=None, exclude_by_name=None, include_by_code=None, include_by_name=None, include_global=True, output_table=None)[source]
Compute volume table for all regions in parcellation.
Sets volumetable attribute containing region volumes and statistics.
- exclude_by_codelist or np.ndarray, optional
Region codes to exclude from the analysis. If None, no regions are excluded by code. Useful for excluding regions like ventricles or non-brain tissue.
- exclude_by_namelist or str, optional
Region names to exclude from the analysis. If None, no regions are excluded by name. Example: [“Ventricles”, “White-Matter”] to focus only on gray matter regions.
- include_by_codelist or np.ndarray, optional
Region codes to include in the analysis. If None, all regions are included. Useful for focusing on specific regions of interest.
include_by_name : list or str, optional
Region names to include in the analysis. If None, all regions are included. Example: [“Cortex”, “Hippocampus”] to focus on specific structures.
- add_bids_entitiesbool, default=True
Whether to include BIDS entities as columns in the resulting DataFrame. This extracts subject, session, and other metadata from the filename.
- region_prefixstr, default=”supra-side”
Prefix to use for region names when they cannot be determined from the parcellation object. The prefix will be combined with the region index number.
- include_globalbool, default=True
Whether to include a the total volume in the output table. If True, adds a row for the total volume calculated from the parcellation.
Examples
>>> parc.compute_volume_table() >>> volume_df, _ = parc.volumetable >>> print(volume_df.head())
The parcellationtools module provides comprehensive brain parcellation handling, regional analysis, and atlas-based processing capabilities.
Key Features
Load parcellations with associated lookup tables
Regional filtering and grouping operations
Volume calculations and statistical analysis
Multi-format support (NIfTI, TSV, LUT)
Parcellation validation and correction
BIDS-compliant output generation
Main Classes
Parcellation
The core class for managing brain parcellations and their associated metadata.
Key Methods:
- load_from_file(): Load parcellation with lookup table
- filter_regions(): Filter parcellation by region criteria
- group_regions(): Group regions into larger anatomical units
- compute_regional_volumes(): Calculate volumes for each region
- save_to_file(): Export parcellation in various formats
- validate(): Check parcellation integrity
Common Usage Examples
Basic parcellation loading and analysis:
from clabtoolkit.parcellationtools import Parcellation
# Load parcellation with lookup table
parc = Parcellation()
parc.load_from_file(
"/path/to/parcellation.nii.gz",
"/path/to/lookup_table.lut"
)
# Get basic information
print(f"Number of regions: {len(parc.regions)}")
print(f"Volume dimensions: {parc.shape}")
Regional analysis:
# Filter specific anatomical regions
parc.filter_regions(['cortex', 'cerebellum'])
# Group regions by lobes
parc.group_regions(grouping_file="/path/to/lobe_mapping.json")
# Compute regional volumes
volumes = parc.compute_regional_volumes()
volumes_df = pd.DataFrame(volumes)
Export and conversion:
# Save filtered parcellation
parc.save_to_file("/path/to/output_parcellation.nii.gz")
# Export lookup table
parc.export_lut("/path/to/output_lut.txt")