Module and Function reference

Isolate module reference

Cerebellar Isolation using a Unet model @authors: Yao Li, Carlos Hernandez-Castillo, Joern Diedrichsen

isolation.isolate(t1_file: str | None = None, t2_file: str | None = None, brain_mask_file: str | None = None, label_file: str | None = None, result_folder: str | None = None, template: str = 'MNI152NLin6Asym', type_of_transform: str = 'Similarity', max_iterations: int = 5, params: str = 'pre_trained_numpy.pkl', save_cropped_files: bool = False, use_q_form: bool = False, verbose: bool = True) ANTsImage

main function for cerebellum isolation

Parameters:
  • t1_file – (string) filename and path to T1w image, optional

  • t2_file – (string) filename and path to T2w image, optional

  • brain_mask_file – (string) filename and path to brain mask, optional

  • label_file – (string) filename and path to label image, optional (reserved, currently has no effect)

  • result_folder – (string) path to output folder (optional, otherwise it is saved to input image folder)

  • template – (string) template to use (reserved)

  • type_of_transform – (string) reserved for future use (see ANTspy)

  • max_iterations – (int) maximum number of registration iterations (optional, default 5)

  • params – (string) path to params file (reserved)

  • save_cropped_files – (bool) set to True to save files cropped to window

  • use_q_form – (bool) set to True to use q-form

  • verbose – (bool) whether to print out status information during processing

isolation.registration(img: ANTsImage, brain_mask: ANTsImage | None = None, template_name: str = 'MNI152NLin6Asym', type_of_transform: str = 'Similarity', max_iterations: int = 5, mi_lower: float = 1.22, mi_upper: float = 1.23) Tuple[ANTsTransform, int]

register the image to this template. The function runs ants registration multiple time and find the best registration results evaluated using normalized mutual information.

Parameters:
  • img – (ANTsImage) image to be registered

  • brain_mask – (ANTsImage) brain mask of the image

  • template – (string) The name of template used. It uses MNI152NLin6Asym by default. (Note that the template must be stored in SUITPy/templates directory and come with brain mask)

  • type_of_transform – (string) transform type (Affine by default, check ANTsPY[https://antspy.readthedocs.io/en/latest/registration.html] for details)

  • max_iterations – (int) maximum number of iterations

  • mi_lower – (float) lower bound of normalized mutual information (range (1, 2)); setting this value too high would result in an error, while setting it too low might cause poor alignment.

  • mi_upper – (float) upper bound of normalized mutual information (range (1, 2)); setting this value too high would result in a warning, while setting it too low would prevent the function from searching for better results.

Returns:
  • trans – (ANTsTransform) the transformation from the subject space to the template space

  • status – (int) the status of the registration (0: for success mi>upper, 1: found one of mi>mi_lower, 2: failure)

Normalize module reference

Cerebellar normalization and isolation using ANTsPy @authors: Yaping Wang, Jorn Diedrichsen

normalization.bounding_box(img_file, mask_file)

Crops an image file (3-5d) to a bounding box defined a 3d mask. The first 3 dimensions of the image and mask must match.

Parameters:
  • img_file (str or Nifti1Image) – Path to deformation field NIfTI file (4D or 5D).

  • mask_file (str or Nifti1Image) – Path to 3D mask NIfTI file. Non-zero defines ROI.

Returns:

cropped_file (Nifti1Image) – The cropped image

normalization.deformation_from_displacement(template_file, displacement_file, deformation_file, whichtoinvert=None, verbose=False)

Convert an ANTs composite displacement field into a deformation field y(x) that maps voxel coordinates in the template space into world coordinates of moveable image. This deformation map can be used to convert points from template space into the moveable space or to resample the moveable image into the template space.

Parameters:
  • template_file (ANTs image) – the template image (defines grid, affine, spacing)

  • displacement_file (str) – Path to ANTs displacement field.

  • deformation_file (str) – Output filename for the resulting deformation field.

  • whichtoinvert (list of bool) – List indicating which transforms to invert

normalization.normalize(source_file, mask_file, space='SUIT', template_file=None, type_of_transform='antsRegistrationSyN[s]', write_normalized=True, write_ants_transform=False, write_deformation=True, write_inv_deformation=False, write_jacobian_determinant=False, write_log_jacobian_determinant=False, result_folder=None, use_q_form=False, verbose=1)

Normalizes a T1w image to the SUIT template using ANTsPy

Parameters:
  • source_file (str) – Path to the source T1w image

  • mask_file (str) – Path to the cerebellar mask image

  • space (str) – Cerebellar-only template (SUIT, MNI152NLin6AsymC / ‘MNI’, MNI152NLin2009cSymC / ‘MNISym’)

  • template_file (str) – Optional path to a custom template file

  • type_of_transform (str) – ANTs registration type (e.g., ‘antsRegistrationSyN[s]’)

  • write_normalized (bool) – Save normalized (template-space) T1 image

  • write_ants_transform (bool) – Save ANTs forward and inverse transforms

  • write_deformation (bool) – Save deformation field y(x) for reslicing other images

  • write_inv_deformation (bool) – Save inverse deformation field for reslicing atlas into individual space

  • write_jacobian_determinant (bool) – Computes & save geometric Jacobian determinant

  • write_log_jacobian_determinant (bool) – Computes & save logarithmic geometric Jacobian determinant

  • result_folder (str) – Output folder. If None, uses same folder as source file

  • use_q_form (bool) – set to True to use q-form

  • verbose (int) – 0: silent, 1:Progress log, 2:detailed log

Returns:

dict – A dictionary containing output images (if selected to be written) fwdtransforms (str): Path to forward transforms (if write_ant_transform) invtransforms (str): Path to inverse transforms (if write_ant_transform) fwd_deformation (str): Path to composite displacement field inv_deformation (str): Path to inverse deformation field normalized_image (str): Path to normalized image in template space jacobian_determinant (str): Path to Jacobian determinant map log_jacobian_determinant (str): Path to log-Jacobian determinant map

Reslice module reference

Module to resample image into atlas space @authors: Jorn Diedrichsen

reslice.reslice_image(source_image, deformation, mask=None, interp=1, voxelsize=None, imagedim=None, affine=None, replace_nan=True, mask_thr=1.0)

Reslices images into atlas space using a deformation map and mask

Parameters:
  • source_image – (Nifti1Image, str, or iterable of NIFTI) Images to reslice

  • deformation – (Nifti1Image, str): Nonlinear deformation file (y_xxx.nii)

  • mask (NIFTI, str) – Optional masking image (defaults to None)

  • interp (int) – 0: nearest neighbor, 1:trilinear

  • voxelsize (tuple) – Desired voxel size - defaults to deformation image

  • imagedim (tuple) – desired image dimensions: Defaults to deformation image

  • affine (ndaray) – affine transformation matrix of target image

  • replace_nan (bool) – if true, replaces Nan values with 0

  • mask_thr (float) – If given, binarizes the mask at this threshold Defaults to 1.0

Returns:

image (NIFTI image or list of NIFTI Images)

Flatmap module reference

Module for mapping and plotting data to the cerebellar flatmap. @authors Jorn Diedrichsen, Maedbh King, Elaine Liu, Da Zhi

flatmap.map_to_rgb(data, scale=None, threshold=[0, 0, 0])

Maps data to RGB

Parameters:
  • data (_type_) – List of vectors or 3xP ndarray. use [data,None,None] to skip color channels

  • scale (list) – maximum brightness

  • threshold (list) – Threshold [0,0,0].

Returns:

rgba (ndarray) – Nx4 array of RGBA values

flatmap.plot(data, surf=None, underlay='SUIT.shape.gii', undermap='Greys', underscale=[-0.5, 0.5], overlay_type='func', threshold=None, cmap=None, cscale=None, label_names=None, borders='borders.txt', bordercolor='k', bordersize=2, alpha=1.0, render='matplotlib', hover='auto', new_figure=True, colorbar=False, cbar_tick_format='%.2g', backgroundcolor='w', frame=[-110, 110, -110, 110])

Visualize cerebellar activity on a flatmap

Parameters:
  • data (np.array, giftiImage, or name of gifti file) – Data to be plotted, should be a 28935-long vector

  • surf (str or giftiImage) – surface file for flatmap (default: FLAT.surf.gii in SUIT pkg)

  • underlay (str, giftiImage, or np-array) – Full filepath of the file determining underlay coloring (default: SUIT.shape.gii in SUIT pkg)

  • undermap (str) – Matplotlib colormap used for underlay (default: gray)

  • underscale (array-like) – Colorscale [min, max] for the underlay (default: [-1, 0.5])

  • overlay_type (str) – ‘func’: functional activation (default) ‘label’: categories ‘rgb’: RGB(A) values (0-1) directly specified. Alpha is optional

  • threshold (scalar or 2-element array) – Threshold for functional overlay. If one value is given, only values above are shown If two values are given, values below lower threshold or above upper threshold are shown

  • cscale (ndarray or list) – Colorscale [min, max] for the overlay (default: [data.min, data.max])

  • cmap (str) – A Matplotlib colormap or an equivalent Nx3 or Nx4 floating point array (N rgb or rgba values). (defaults to ‘jet’ if none given)

  • label_names (list) – labelnames (default is None - extracts from .label.gii )

  • borders (str) – Full filepath of the borders txt file or workbench border file (default: borders.txt in SUIT pkg)

  • bordercolor (char or matplotlib.color) – Color of border - defaults to ‘k’

  • bordersize (int) – Size of the border points - defaults to 2

  • alpha (float) – Opacity of the overlay (default: 1)

  • render (str) – Renderer for graphic display ‘matplot’ / ‘plotly’. Dafault is matplotlib

  • hover (str) – When renderer is plotly, it determines what is displayed in the hover label: ‘auto’, ‘value’, or None

  • new_figure (bool) – If False, plot renders into matplotlib’s current axis. If True, it creates a new figure (default=True)

  • colorbar (bool) – By default, colorbar is not plotted into matplotlib’s current axis (or new figure if new_figure is set to True)

  • cbar_tick_format – str, optional Controls how to format the tick labels of the colorbar, and for the hover label. Ex: use “%i” to display as integers. Default=’%.2g’ for scientific notation.

  • backgroundcolor (str or matplotlib.color) – Axis background color (default: ‘w’)

  • frame (ndarray) – [L,R,T,B] of the area of flatmap that is rendered Defaults to entire flatmap

Returns:
  • ax (matplotlib.axis) – If render is matplotlib, the function returns the axis

  • fig (plotly.go.Figure) – If render is plotly, it returns Figure object

flatmap.plot_multi_flat(data, grid, cmap=None, dtype='label', cscale=None, titles=None, colorbar=False, space='SUIT', render='matplotlib', bordersize=2, labels=None, fig_size=(5, 5))

Maps and plots a grid of flatmaps with some data , requires data to be in volume space

Parameters:
  • data (array or list) – NxP array of data

  • grid (tuple) – (rows,cols) grid for subplot

  • cmap (colormap or list) – Color map or list of color maps. Defaults to None.

  • dtype (str, optional) – ‘label’ or ‘func’

  • cscale (_type_, optional) – Scale of data (None)

  • titles (_type_, optional) – _description_. Defaults to None.

  • colorbar (bool)

flatmap.save_colorbar(gifti, outpath)

plots colorbar for gifti object (*.label.gii) and saves it to outpath

Parameters:
  • gifti (gifti image) – Nibabel Gifti image

  • outpath (str) – outpath for colorbar image

flatmap.vol_to_surf(volumes, space='SUIT', ignore_zeros=False, depths=[0, 0.2, 0.4, 0.6, 0.8, 1.0], stats='nanmean', outer_surf_gifti=None, inner_surf_gifti=None)

Maps volume data onto a surface, defined by inner and outer surface. Function enables mapping of volume-based data onto the vertices of a surface. For each vertex, the function samples the volume along the line connecting the two surfaces. The points along the line are specified in the variable ‘depths’. default is to sample at 5 locations between white an gray matter surface. Set ‘depths’ to 0 to sample only along the white matter surface, and to 0.5 to sample along the mid-gray surface. The averaging across the sampled points for each vertex is dictated by the variable ‘stats’. For functional activation, use ‘mean’ or ‘nanmean’. For discrete label data, use ‘mode’.

Parameters:
  • volumes (list or nib obj) – List of filenames/nib objs, or nib obj to be mapped

  • space (string) – Normalization space: ‘SUIT’ (default), ‘FSL’, ‘SPM’, ‘MNISym’, ‘MNI’

  • ignore_zeros (bool) – Should zeros be ignored in mapping? default: False

  • depths (array-like) – Depths of points along line at which to map (0=white/gray, 1=pial). DEFAULT: [0.0,0.2,0.4,0.6,0.8,1.0]

  • stats (lambda function) – function that calculates the Statistics to be evaluated. ‘nanmean’: default and used for activation data ‘mode’: used when discrete labels are sampled. The most frequent label is assigned.

  • outer_surf_gifti (string or nibabel.GiftiImage) – optional pial surface, filename or loaded gifti object, overwrites space

  • inner_surf_gifti (string or nibabel.GiftiImage) – White surface, filename or loaded gifti object, overwrites space

Returns:

mapped_data (numpy.array) – A Data array for the mapped data

Atlas module reference

Module to importing cerebellar atlases and templates from the [cerebellar atlas repository](https://github.com/DiedrichsenLab/cerebellar_atlases) @authors: Jorn Diedrichsen, Vahid Ashkani

atlas.fetch_atlas(atlas, atlas_dir=None, maps='all', space='all', base_url=None, resume=True, verbose=1)

Download and install cerebellar atlas maps from github.com/DiedrichsenLab/cerebellar_atlases

Parameters:
  • atlas (str) – Name of the atlas (Diedrichsen_2009, King_2019, etc. )

  • atlas_dir (str) – Base directory of Cerebellar atlases, files will be in atlas_dir/atlas_name/..

  • maps (list or str) – Which maps to download within the altas (i.e. atl-Buckner7)

  • space (str) – Volumetric files should be in ‘SUIT’, ‘MNI’, or ‘MNISym’ space (default ‘all’)

  • base_url – string, optional base_url of files to download (None results in default base_url).

  • resume (bool) – REsume download after fail

  • verbose (int) – Default 1

Returns:

data (data dict) –

Dictionary, contains keys:
  • data_dir: Absolute path of downloaded folder

  • files: list of string. Absolute paths of downloaded files on disk.

  • description: A short description of data and some references.

Notes

For more details, see https://github.com/DiedrichsenLab/cerebellar_atlases

atlas.summarize_data(images, label_image=None, atlas=None, maps=None, space='SUIT', atlas_dir=None, stats=['nanmean'], region_names=None, outfilename=None, verbose=0, lut_file=None)

Summarize the data from the images by ROIs defined in a label image.

This works optimally with the files provided in the cerebellar atlas repository, but can also operate on completely custom label images.

Important

  • The atlas is not downloaded automatically. You must call fetch_atlas(…) yourself beforehand if you want to use the cerebellar-atlases repository.

  • If you provide label_image, the function will use that image directly and ignore the atlas / maps / space for determining ROIs.

  • The data images need to be in the same common atlas space (SUIT / MNI) as the label_image, but they do not be stored in the same voxel grid.

Parameters:
  • images (list or str or nib image) – One or multiple image(s) (3D or 4D NIfTI) to summarize.

  • label_image (str or nib image or None) – Custom label image independent of cerebellar atlases. If provided, this is used as the ROI definition.

  • atlas (str or None) – Name of the atlas (Diedrichsen_2009, King_2019, etc.). Ignored if label image is provided.

  • maps (str or None) – Name of the map within the atlas (atl-Buckner7, atl-Anatomical). Ignored if label image is provided.

  • space (str) – Space for the volumetric atlas file: ‘SUIT’, ‘MNI’, ‘MNISym’, etc. Ignored if label image is provided.

  • atlas_dir (str or None) – Base directory of cerebellar atlases. If None, the default atlas directory used by SUITPy is used.

  • stats (sequence of str) – Which statistics to compute inside each ROI. Supported keys: ‘mean’, ‘nanmean’, ‘std’, ‘nanstd’, ‘nansum’

  • region_names (sequence of str or None) – Optional list of region names. If provided and length >= number of non-zero labels, it overrides names from the LUT.

  • outfilename (str or None) – If not None, write the resulting table as a tab-delimited text file AND an .xlsx file with the same basename.

  • resume (bool) – Unused here, kept for API compatibility.

  • verbose (int) – Verbosity level.

  • lut_file (str or None) – Optional LUT file for mapping label indices to names. If None and using cerebellar atlases, it defaults to <maps>.lut in the atlas directory. For custom label images, if lut_file is None, generic names (‘region <id>’) are used.

Returns:

df (pandas.DataFrame) –

One row per image / frame / region with columns:
  • image: integer index of input image

  • image_name: basename or placeholder for the image

  • atlas: atlas name (or custom label name)

  • map: map name (if applicable)

  • space: space name (if applicable)

  • frame: frame index (0 for 3D images)

  • region: integer label value

  • regionname: region label name

  • volume: ROI volume in mm^3

  • plus one column per requested statistic.