tracttools module

class clabtoolkit.tracttools.Tractogram(tractogram_input=None, tracts=None, affine=None, header=None, color='#BFBDBD', alpha=1.0, name='default')[source]

Bases: object

A class to represent and manipulate tractograms.

name

Identifier for this tractogram instance.

Type:

str

tract_file

Path to the source file, or a sentinel (‘from_object’, ‘from_components’) indicating how the tractogram was constructed.

Type:

str or None

tracts

The streamlines themselves.

Type:

ArraySequence or list of np.ndarray

affine

Affine transformation matrix (voxel-to-RASmm or similar, per nibabel convention).

Type:

np.ndarray

header

Header information from the source tractogram file (format-specific).

Type:

dict

data_per_point

Scalar/vector maps defined per streamline point. Each value is an ArraySequence-like structure with one entry per streamline point.

Type:

dict

data_per_streamline

Scalar/vector maps defined per streamline (one value per streamline). Always includes a ‘length’ entry (streamline length in mm).

Type:

dict

colortables

Named color tables (e.g. for categorical overlays like ‘cluster_id’), each an entry with ‘names’, ‘color_table’, and ‘lookup_table’ keys.

Type:

dict

centroids

Cluster centroids computed by compute_centroids(). Only present after that method has been called.

Type:

ArraySequence, optional

centroids_indexes

For each centroid, the indices of the original streamlines belonging to that cluster. Only present after compute_centroids() has been called.

Type:

list of list of int, optional

__init__(tractogram_input=None, tracts=None, affine=None, header=None, color='#BFBDBD', alpha=1.0, name='default')[source]

Initializes the Tractogram class by loading a tractogram file.

Parameters:

tractogram_input (str or nb.streamlines.Tractogram):

Path to the tractogram file or nibabel Tractogram object.

Raises:

FileNotFoundError: If the specified tractogram file does not exist.

load_tractogram_from_file(tractogram_input)[source]

Loads a tractogram file and extracts streamlines, affine transformation, and header information.

Parameters:

tractogram_input (str):

Path to the tractogram file.

Returns:

Tuple[List[np.ndarray], np.ndarray, Dict]:

A tuple containing the list of streamlines, affine transformation matrix, and header information.

load_tractogram_from_object(tractogram)[source]

Loads a tractogram from a nibabel Tractogram object.

Parameters:

tractogram (nb.streamlines.Tractogram):

A nibabel Tractogram object containing streamlines and metadata.

Returns:

None

load_colortable(lut_file, map_name='default', opacity=1.0)[source]

Loads a colortable from a file and associates it with a specified map name.

Parameters:

lut_filestr or dict, optional

Path to LUT file or dictionary with index/name/color keys.

map_name (str):

Name of the map to associate with the loaded colortable.

opacity (float or np.ndarray):

Opacity value(s) for the colortable. Can be a single float or an array of floats.

Returns:

None

smooth_streamlines(iterations=1, sigma=1.0)[source]

Smooth streamlines using a Gaussian filter.

Parameters:
  • iterations (int, optional) – Number of smoothing iterations to perform. Default is 1.

  • sigma (float, optional) – Standard deviation for Gaussian kernel. Default is 1.0.

Returns:

The method modifies the streamlines in place.

Return type:

None

resample_streamlines(nb_points=51, interp_method='linear')[source]

Resample streamlines to a specified number of points.

Parameters:

nb_points (int, optional) – Number of points to resample each streamline to. Default is 51.

Returns:

resampled_streamlines – Resampled streamlines in the same format as the input streamlines. Each streamline is a numpy array with shape (nb_points, 3).

Return type:

List[np.ndarray] or nb.streamlines.array_sequence.ArraySequence

Raises:
  • ValueError – If nb_points is not a positive integer.

  • ValueError – If the tractogram has no streamlines loaded.

  • ValueError – If streamlines are empty.

  • ValueError – If individual streamlines are not valid numpy arrays.

Examples

>>> tractogram = Tractogram('input.trk')
>>> resampled_streamlines = tractogram.resample_streamlines(nb_points=100)
>>> print(f"Resampled {len(resampled_streamlines)} streamlines to 100 points each")
explore_tractogram()[source]

Display comprehensive information about the tractogram.

Provides a formatted overview of the tractogram including streamline count, spatial transformations, header metadata, scalar data properties, and available colortables. Useful for quick inspection and validation of tractogram data.

The method displays:
  • Basic tractogram identification and streamline count

  • Affine transformation matrix for spatial mapping

  • Header information (dimensions, voxel sizes, origin)

  • Scalar data per point (with min/max statistics)

  • Scalar data per streamline (with min/max statistics)

  • Available colortables for visualization

Returns:

Prints formatted information to stdout.

Return type:

None

Notes

This method performs no modifications to the tractogram data. It only displays information for inspection purposes.

Examples

>>> tractogram = Tractogram('input.trk')
>>> tractogram.explore_tractogram()
╔════════════════════════════════════════════════════════════════╗
║                    TRACTOGRAM EXPLORATION                      ║
╠════════════════════════════════════════════════════════════════╣
║ Name: default                                                  ║
║ Streamlines: 15,000                                            ║
╠════════════════════════════════════════════════════════════════╣
║ AFFINE TRANSFORMATION MATRIX                                   ║
║   [[ 1.00   0.00   0.00  -90.00]                               ║
║    [ 0.00   1.00   0.00 -126.00]                               ║
║    [ 0.00   0.00   1.00  -72.00]                               ║
║    [ 0.00   0.00   0.00    1.00]]                              ║
╠════════════════════════════════════════════════════════════════╣
║ HEADER INFORMATION                                             ║
║   Dimensions:    181 × 217 × 181                               ║
║   Voxel Size:    1.00 × 1.00 × 1.00 mm                         ║
╠════════════════════════════════════════════════════════════════╣
║ SCALAR DATA PER POINT (2 maps)                                 ║
║   fa          Min: 0.0000    Max: 0.9200                       ║
║   md          Min: 0.0005    Max: 0.0020                       ║
╠════════════════════════════════════════════════════════════════╣
║ SCALAR DATA PER STREAMLINE (1 map)                             ║
║   length      Min: 20.50     Max: 150.30                       ║
╠════════════════════════════════════════════════════════════════╣
║ COLORTABLES (2 available)                                      ║
║   • default                                                    ║
║   • cluster_id                                                 ║
╚════════════════════════════════════════════════════════════════╝
streamline_to_points(map_name, point_map_name=None)[source]

Converts maps_per_streamline to maps_per_point by assigning the streamline value to all its points. This method creates a new set of data_per_point where each point in a streamline inherits the value of its corresponding streamline from data_per_streamline.

Parameters:
  • map_name (str, optional) – The name of the map in data_per_streamline to convert.

  • point_map_name (str, optional) – The name of the new map to create in data_per_point. If None, uses map_name.

Returns:

An ArraySequence containing all points from all streamlines.

Return type:

ArraySequence

Raises:
  • ValueError – If the specified map_name does not exist in data_per_streamline.:

  • ValueError – If the streamline value for the specified map is not a single value per streamline.:

Examples

>>> tractogram = Tractogram('input.trk')
>>> point_data = tractogram.streamline_to_points(map_name='cluster_id')
>>> print(f"Converted streamline map 'cluster_id' to point data with {len(point_data)} points")
points_to_streamline(map_name, streamline_map_name=None, metric='mean')[source]

Converts maps_per_point to maps_per_streamline by averaging point values for each streamline. This method creates a new set of data_per_streamline where each streamline’s value is the average of its corresponding points from data_per_point.

Parameters:
  • map_name (str) – The name of the map in data_per_point to convert.

  • streamline_map_name (str, optional) – The name of the new map to create in data_per_streamline. If None, uses map_name.

  • metric (str, optional) – The aggregation metric to use: “mean”, “median”, “max”, or “min”. Default is “mean”.

Returns:

A 2D array of shape (n_streamlines, n_features) containing aggregated values.

Return type:

np.ndarray

add_tractogram(tract2add)[source]

This method merges the current Tractogram with one or more other Tractogram objects. The resulting Tractogram contains all streamlines and associated metadata from the input Tractogram objects.

Parameters:

tractograms (Tractogram, List[Tractogram], str, Path, or List[Union[str, Path, Tractogram]]) – The Tractogram(s) to merge with the current Tractogram. This can be a single Tractogram object, a list of Tractogram objects, a file path (str or Path) to a tractogram file, or a list containing any combination of these types.

Returns:

A new Tractogram object containing the merged streamlines and metadata.

Return type:

Tractogram

Raises:

TypeError – If any item in the input list is not a Tractogram object.:

Examples

>>> tract1 = Tractogram('tract1.trk')
>>> tract2 = Tractogram('tract2.trk')
>>> merged_tract = tract1.add_tractogram(tract2)
>>> print(f"Merged tractogram has {len(merged_tract.tracts)} streamlines")
>>> merged_tract = tract1.add_tractogram('tract3.trk')
>>> print(f"Merged tractogram has {len(merged_tract.tracts)} streamlines")
compute_centroids(method='qb', thresholds=[10])[source]

Extract bundle centroids from tractogram and save them as .trk files.

Parameters:
  • method (str, optional) – Clustering method to use. Can be ‘qbx’ or ‘qb’. Default is ‘qb’.

  • nb_points (int, optional) – Number of points to resample the streamlines to. Default is 51.

  • method – Clustering method to use. Can be ‘qbx’ or ‘qb’. Default is ‘qb’.

  • thresholds (list of int, optional) – List of thresholds to use for clustering (only for qbx). Default is [10]. If using ‘qb’, only the first threshold will be used.

Returns:

  • centroids (ArraySequence) – ArraySequence of centroids for each cluster.

  • centroids_indexes (list of list of int) – List of lists containing the indices of streamlines in each cluster.

Raises:
  • ValueError – If the specified clustering method is not recognized.:

  • ValueError – If thresholds are not provided as a non-empty list for QuickBundlesX.:

Notes

The centroids and their corresponding streamline indices are stored as attributes of the Tractogram object for later use.

Examples

>>> tractogram = Tractogram('input.trk')
>>> centroids, indices = tractogram.compute_centroids(method='qb', thresholds=[10])
>>> print(f"Computed {len(centroids)} centroids using QuickBundles with threshold 10")
>>> ""
>>> centroids_qbx, indices_qbx = tractogram.compute_centroids(method='qbx', thresholds=[20, 15, 10])
>>> print(f"Computed {len(centroids_qbx)} centroids using QuickBundlesX with thresholds [20,
15, 10]")
label_streamlines_by_clusters()[source]

Label each streamline in the tractogram with its corresponding cluster ID.

This method assigns a cluster ID to each streamline based on the clustering results obtained from the compute_centroids method. The cluster IDs are stored in the data_per_streamline attribute of the Tractogram object under the key ‘cluster_id’.

Returns:

np.ndarray:

Array of cluster IDs for each streamline in the tractogram.

Raises:

ValueError: If centroids or centroid indexes are not computed.

Examples:

>>> tractogram = Tractogram('input.trk')
>>> tractogram.compute_centroids(method='qb', thresholds=[10])
>>> cluster_ids = tractogram.label_streamlines_by_clusters()
>>> print(f"Assigned cluster IDs to {len(cluster_ids)} streamlines")
get_cluster_streamlines(cluster_id)[source]

Retrieve the streamlines belonging to a specific cluster.

Parameters:

cluster_id (int):

Index of the cluster to retrieve streamlines from.

Returns:

List[np.ndarray]:

List of streamlines belonging to the specified cluster.

Raises:

ValueError: If centroids or centroid indexes are not computed. IndexError: If the specified cluster_id is out of range.

Examples:

>>> tractogram = Tractogram('input.trk')
>>> tractogram.compute_centroids(method='qb', thresholds=[10])
>>> cluster_streamlines = tractogram.get_cluster_streamlines(cluster_id=0)
>>> print(f"Cluster 0 has {len(cluster_streamlines)} streamlines")
compute_streamline_lengths()[source]

Compute the lengths of all streamlines in the tractogram.

This method both returns the lengths and stores them in data_per_streamline[“length”].

interpolate_on_tractogram(scal_map, interp_method='linear', storage_mode='data_per_point', map_name='fa', reduction='mean')[source]

Interpolate scalar values (e.g., FA) from a NIfTI image onto this tractogram.

Loads a scalar map and interpolates its values at each streamline point (or aggregates them per streamline), storing the result on this Tractogram instance under map_name.

Parameters:
  • scal_map (str or Path) – Path to the scalar image (e.g., FA map in NIfTI format). Must exist and be readable.

  • interp_method ({'linear', 'nearest'}, default='linear') – Interpolation method used for RegularGridInterpolator. - ‘linear’: Trilinear interpolation - ‘nearest’: Nearest neighbor interpolation

  • storage_mode ({'data_per_point', 'data_per_streamline'}, default='data_per_point') – Where to store the interpolated values: - ‘data_per_point’: one value per streamline point, stored in self.data_per_point[map_name] - ‘data_per_streamline’: one aggregated value per streamline, stored in self.data_per_streamline[f”{map_name}_{reduction}”]

  • map_name (str, default='fa') – Key under which to store the scalar map.

  • reduction ({'mean', 'median', 'min', 'max'}, default='mean') – Aggregation method used when storage_mode=’data_per_streamline’. Applied to all scalar values along each streamline to produce a single value.

Returns:

This method mutates the Tractogram in place: it populates either self.data_per_point[map_name] or self.data_per_streamline[f”{map_name}_{reduction}”], depending on storage_mode.

Return type:

None

Raises:
  • FileNotFoundError – If the scalar map file does not exist.

  • ValueError – If interp_method is not ‘linear’ or ‘nearest’, if storage_mode is not ‘data_per_point’ or ‘data_per_streamline’, or if reduction is not one of ‘mean’, ‘median’, ‘min’, ‘max’.

  • IOError – If there are issues loading the scalar map.

Notes

  • Points outside the scalar map boundaries are assigned NaN.

  • Empty streamlines are handled gracefully with empty arrays.

  • When using ‘data_per_streamline’ mode, the stored key is suffixed with

the reduction method (e.g., ‘fa_mean’). - This method only populates the requested storage_mode and does not touch the other one; if you need the same scalar in both storage modes, call this method twice with different storage_mode values (e.g. once with ‘data_per_point’ and once with ‘data_per_streamline’).

Examples

>>> tractogram = Tractogram('input.trk')
>>> tractogram.interpolate_on_tractogram('fa_map.nii.gz', map_name='fractional_anisotropy')
>>> print(tractogram.data_per_point['fractional_anisotropy'])
>>> tractogram.interpolate_on_tractogram(
...     'md_map.nii.gz', storage_mode='data_per_streamline',
...     reduction='median', map_name='mean_diffusivity'
... )
>>> print(tractogram.data_per_streamline['mean_diffusivity_median'])
get_pointwise_colors(overlay_name='default', colormap='viridis', vmin=None, vmax=None, range_min=None, range_max=None, range_color=(128, 128, 128, 255))[source]

Compute streamlines colors for visualization based on the specified overlay.

This method processes the overlay data and creates appropriate point colors for visualization, handling both scalar data (with colormaps) and categorical data (with discrete color tables).

Parameters:
  • overlay_name (str, optional) – Name of the overlay to visualize. If None, the first available overlay is used.

  • colormap (str, optional) – Colormap to use for scalar overlays. If None, uses parcellation color table for categorical data or ‘viridis’ for scalar data.

  • vmin (np.float64, optional) – Minimum value for scaling the colormap. If None, uses the minimum value of the overlay.

  • vmax (np.float64, optional) – Maximum value for scaling the colormap. If None, uses the maximum value of the overlay. If both vmin and vmax are None, the colormap will be applied to the full range of the overlay values. If both are provided, they will be used to scale the colormap.

  • range_min (np.float64, optional) – Minimum threshold for the overlay values. Values below this will be colored with range_color. If None, no minimum threshold is applied.

  • range_max (np.float64, optional) – Maximum threshold for the overlay values. Values above this will be colored with range_color. If None, no maximum threshold is applied.

  • range_color (Tuple[int, int, int, int], optional) – RGBA color to use for values outside the specified range (range_min, range_max). Default is gray (128, 128, 128, 255).

Returns:

point_colors – RGBA colors for each point in each streamline, in the same nested structure as the tractogram’s streamlines (one array per streamline).

Return type:

ArraySequence

Raises:

ValueError – If the specified overlay is not found among available point/streamline maps.

Notes

Categorical overlays (those with an entry in self.colortables) are colored using the associated discrete color table. Scalar overlays are colored using colormap scaled by vmin/vmax.

Examples

>>> tractogram = Tractogram('input.trk')
>>> # Colors for a categorical overlay (uses discrete colortable)
>>> point_colors = tractogram.get_pointwise_colors(overlay_name="cluster_id")
>>>
>>> # Colors for scalar data with a custom colormap
>>> point_colors = tractogram.get_pointwise_colors(overlay_name="fa", colormap="hot")
reduce_streamlines(percentage=50)[source]

Reduces the number of streamline by a specified factor.

Parameters:

percentage (np.float):

Percentage of streamlines to keep (between 0 and 100).

Returns:

None

Raises:

ValueError: If percentage is not between 0 and 100.

Notes:

This method modifies the tractogram in place, reducing the number of streamlines by keeping every N-th streamline, where N is determined by the specified percentage.

Examples:

>>> tractogram = Tractogram('input.trk')
>>> tractogram.reduce_streamlines(percentage=25)
>>> print(f"Reduced tractogram now has {len(tractogram.tracts)} streamlines")
filter(condition, **kwargs)[source]

Filters streamlines based on their lengths.

Parameters:

condition (str):

Condition string to filter streamlines. Supported formats: - ‘length > X’: Keep streamlines longer than X mm. - ‘length < X’: Keep streamlines shorter than X mm. - ‘length >= X’: Keep streamlines longer than or equal to X mm. - ‘length <= X’: Keep streamlines shorter than or equal to X mm. - ‘length == X’: Keep streamlines exactly X mm long. - ‘length != X’: Exclude streamlines exactly X mm long. - ‘Xmin <= length <= Ymax’: Keep streamlines between X and Y mm.

Returns:

filtered_streamlines (List[np.ndarray] or None):

List of streamlines that match the condition. Returns None if no streamlines match.

Raises:

ValueError: If the condition format is invalid or if the specified map is not found.

Notes:

This method modifies the tractogram in place, updating the streamlines and associated data based on the filtering condition.

list_maps()[source]

Lists all available scalar maps in the tractogram.

Returns:

Dictionary with two keys:

  • ’maps_per_point’list of str

    Names of scalar maps stored per point. Empty list if none available.

  • ’maps_per_streamline’list of str

    Names of scalar maps stored per streamline. Empty list if none available.

Return type:

dict

Examples

>>> tractogram = Tractogram('input.trk')
>>> maps = tractogram.list_maps()
>>> print("Point maps:", maps['maps_per_point'])
>>> print("Streamline maps:", maps['maps_per_streamline'])
get_maps_info()[source]

Retrieves information about scalar maps stored in the tractogram.

Returns:

pd.DataFrame:

DataFrame containing map names, storage modes, and value statistics.

Examples:

>>> tractogram = Tractogram('input.trk')
>>> maps_info = tractogram.get_maps_info()
>>> print(maps_info)
get_tractogram_info()[source]

Retrieves basic information about the tractogram object.

Returns:

Dict:

Dictionary containing number of streamlines, affine matrix, and header info.

centroids_to_tractogram()[source]

Converts the computed centroids into a new tractogram object.

Returns:

nb.streamlines.Tractogram:

A new tractogram object containing the centroids as streamlines.

Raises:

ValueError: If centroids have not been computed yet.

Examples:

>>> tractogram = Tractogram('input.trk')
>>> tractogram.compute_centroids(method='qb', thresholds=[10])
>>> centroids_tractogram = tractogram.centroids_to_tractogram()
>>> print(f"Centroids tractogram has {len(centroids_tractogram.tractogram.streamlines)} streamlines")
save_tractogram(out_file, tracts=None, affine=None, header=None, file_type='trk', overwrite=False)[source]

Saves the tractogram to a specified file.

Parameters:

out_file (str):

Path to the output tractogram file.

tracts (Optional[List[np.ndarray]]):

List of streamlines to save. If None, uses the current tracts.

affine (Optional[np.ndarray]):

Affine transformation matrix. If None, uses the current affine.

header (Optional[Dict]):

Header information. If None, uses the current header.

file_type (str):

Type of the output file (‘tck’ or ‘trk’). Default is ‘trk’.

overwrite (bool):

Whether to overwrite the existing file. Default is False.

Returns:

None

Raises:

ValueError: If the specified file type is not supported.

FileExistsError: If the output file already exists and overwrite is False.

Examples:

>>> tractogram = Tractogram('input.trk')
>>> tractogram.save_tractogram('output.trk', file_type='trk', overwrite=True)
>>> print("Tractogram saved to output.trk")
plot(overlay_name='default', cmap='viridis', vmin=None, vmax=None, range_min=None, range_max=None, range_color=(128, 128, 128, 255), views=['lateral'], hemi='lh', use_opacity=False, plot_style='tube', vis_percentage=100, force_reduction=True, notebook=False, show_colorbar=False, colorbar_title=None, colorbar_position='bottom', save_path=None)[source]

Plot the tractrogram with specified overlay and visualization parameters.

Renders the tractogram with optional overlays using PyVista, supporting multiple camera views, custom colormaps, and interactive or static output. Handles both categorical parcellation data and continuous scalar overlays.

Parameters:
  • overlay_name (str, default "default") – Name of the overlay to visualize from the tractogram’s point data.

  • cmap (str, optional) – Colormap for scalar data. If None, uses parcellation colors for categorical data or ‘viridis’ for scalar data.

  • vmin (float, optional) – Minimum value for colormap scaling. If None, uses data minimum.

  • vmax (float, optional) – Maximum value for colormap scaling. If None, uses data maximum.

  • views (str or List[str], default ["lateral"]) – Camera view(s): ‘lateral’, ‘medial’, ‘dorsal’, ‘ventral’, ‘anterior’, ‘posterior’, or multiple views like [‘lateral’, ‘medial’]. Also supports preset layouts: ‘4_views’, ‘6_views’, ‘8_views’ with optional orientation.

  • hemi (str, default "lh") – Hemisphere to visualize: ‘lh’ (left) or ‘rh’ (right).

  • use_opacity (bool, default True) – Whether to use opacity settings from the tractogram overlays.

  • plot_style (str, default "tube") – Style for rendering streamlines: ‘tube’ or ‘line’.

  • vis_percentage (float, default 100) – Percentage of streamlines to visualize (0-100). Reduces number for faster rendering if less than 100.

  • force_reduction (bool, default True) – Whether to force reduction of streamlines when vis_percentage < 100.

  • notebook (bool, default False) – Whether to display in Jupyter notebook. If False, opens interactive window.

  • show_colorbar (bool, default False) – Whether to display colorbar. Automatically determined if None.

  • colorbar_title (str, optional) – Title for the colorbar. Uses overlay name if None.

  • colorbar_position (str, default "bottom") – Colorbar position: ‘bottom’, ‘top’, ‘left’, or ‘right’.

  • save_path (str, optional) – Path to save plot as image. If None, displays interactively.

Returns:

PyVista plotter object for further customization.

Return type:

Plotter

Raises:

ValueError – If overlay not found or invalid view parameter.

Examples

>>> tractogram.plot(overlay_name="fa")
>>> tractogram.plot(overlay_name="fa", cmap="hot", views="medial", show_colorbar=True)
clabtoolkit.tracttools.resample_streamlines(in_streamlines, nb_points=51)[source]

Resample streamlines to a specified number of points.

Parameters:
  • in_streamlines (List[np.ndarray] or nb.streamlines.array_sequence.ArraySequence) – Input streamlines to be resampled.

  • nb_points (int, optional) – Number of points to resample each streamline to. Default is 51.

Returns:

resampled_streamlines – Resampled streamlines in the same format as the input.

Return type:

List[np.ndarray] or nb.streamlines.array_sequence.ArraySequence

Raises:
  • ValueError – If the input streamlines are not in the expected format.

  • ValueError – If the input streamlines are empty.

  • ValueError – If nb_points is not a positive integer.

  • ValueError – If individual streamlines are not valid numpy arrays.

Examples

>>> # With ArraySequence
>>> in_streamlines = nb.streamlines.load('input.trk').streamlines
>>> resampled = resample_streamlines(in_streamlines, nb_points=100)
>>> # With list
>>> streamlines_list = [np.random.rand(50, 3), np.random.rand(30, 3)]
>>> resampled = resample_streamlines(streamlines_list, nb_points=100)
clabtoolkit.tracttools.interpolate_streamline_values(original_coords, original_values, new_coords, method='linear')[source]

Interpolate values from original streamline coordinates to new coordinates.

Parameters:

original_coordsnp.ndarray

Original coordinates with shape (n_points, 3) [X, Y, Z]

original_valuesnp.ndarray

Values at original coordinates with shape (n_points,) or (n_points, n_features)

new_coordsnp.ndarray

New coordinates with shape (m_points, 3) [Xi, Yi, Zi]

methodstr

Interpolation method: ‘linear’, ‘nearest’, ‘cubic’. Default is ‘linear’

Returns:

new_valuesnp.ndarray

Interpolated values at new coordinates

clabtoolkit.tracttools.merge_tractograms(tractograms, color_table=None, map_name='tract_id')[source]

Merges multiple tractograms into a single tractogram.

It combines streamlines and associated data from all input tractograms. If the input list is empty, it returns None. If there’s only one tractogram, it returns it as is.

Parameters:

tractogramsList[Union[str, Path, Tractogram]]

List of Tractogram objects to be merged. Can also include file paths to tractogram files.

color_tabledict, optional

A dictionary defining the color table for the merged tractogram. If None, a default color table will be created.

The dictionary should contain:
  • ‘tractograms_names’: List of names for each tractogram.

  • ‘color_table’: numpy.ndarray of shape (n_tractograms, 5) with RGBA colors and values.

  • ‘lookup_table’: Optional, can be None.

map_namestr, optional

Name of the map to store tract IDs in the merged tractogram. Default is ‘tract_id’.

Returns:

merged_tractogramTractogram

A new Tractogram object containing all streamlines and associated data from the input tractograms.

Raises:

ValueError: If the input list is empty or contains non-Tractogram objects.

Examples:

>>> tract1 = Tractogram('tract1.trk')
>>> tract2 = Tractogram('tract2.trk')
>>> merged_tract = merge_tractograms([tract1, tract2])
>>> print(f"Merged tractogram has {len(merged_tract.tracts)} streamlines")
clabtoolkit.tracttools.trk2tck(in_trk, out_tck, overwrite=False)[source]

Converts a .trk tractogram to .tck format.

clabtoolkit.tracttools.tck2trk(in_tck, ref_image, out_trk, overwrite=False)[source]

Converts a .tck tractogram to .trk format using a reference NIfTI image.

TCK files do not store voxel-grid information (dimensions, voxel sizes, voxel order), which the TRK format requires in its header. This function borrows that information from a reference image that shares the same voxel grid as the tractogram (e.g. the B0 or FA map used for tracking in MRtrix3).

Parameters:
  • in_tck (str or Path) – Path to the input .tck tractogram file.

  • ref_image (str or Path) – Path to a NIfTI image defining the voxel grid (dimensions, voxel sizes, affine) the streamlines were generated in.

  • out_trk (str or Path) – Path to the output .trk file.

  • overwrite (bool, optional) – Whether to overwrite an existing output file. Default is False.

Returns:

A Tractogram object wrapping the newly written .trk file.

Return type:

Tractogram

Raises:
  • FileNotFoundError – If the input TCK file or the reference image does not exist.

  • ValueError – If the input file is not a valid TCK file.

  • FileExistsError – If the output file already exists and overwrite is False.

Examples

>>> tract = tck2trk('streamlines.tck', 'fa.nii.gz', 'streamlines.trk')

The tracttools module provides tractogram loading, manipulation, clustering and visualization, with support for the TRK and TCK formats and per-point or per-streamline scalar maps.

Key Features

  • Load tractograms from file or from nibabel Tractogram objects

  • Per-point and per-streamline scalar maps, with conversion between the two

  • Streamline resampling, smoothing and reduction

  • Bundle clustering with QuickBundles/QuickBundlesX and centroid extraction

  • Scalar interpolation from NIfTI volumes onto streamlines

  • Colortable support and 3D rendering via PyVista

  • TRK/TCK format conversion

Main Classes

Tractogram

The core class for managing tractograms, their streamlines and associated scalar maps.

Key Methods: - load_tractogram_from_file(): Load a tractogram from a .trk or .tck file - load_tractogram_from_object(): Load from an existing nibabel Tractogram object - load_colortable(): Attach a colortable to a named map - resample_streamlines(): Resample all streamlines to a fixed number of points - smooth_streamlines(): Smooth streamlines with a Gaussian filter - reduce_streamlines(): Randomly reduce the streamline count by a percentage - filter(): Filter streamlines by length - compute_streamline_lengths(): Compute the length of every streamline - compute_centroids(): Cluster streamlines and extract bundle centroids - label_streamlines_by_clusters(): Label each streamline with its cluster ID - get_cluster_streamlines(): Retrieve the streamlines of one cluster - centroids_to_tractogram(): Convert computed centroids into a new Tractogram - interpolate_on_tractogram(): Interpolate a NIfTI scalar map onto the streamlines - streamline_to_points(): Expand a per-streamline map to a per-point map - points_to_streamline(): Reduce a per-point map to a per-streamline map - add_tractogram(): Merge one or more Tractogram objects into this one - list_maps(): List the available scalar maps - get_maps_info(): Retrieve information about the stored scalar maps - get_tractogram_info(): Retrieve basic tractogram information - explore_tractogram(): Print a comprehensive summary of the tractogram - save_tractogram(): Save the tractogram to .trk or .tck - plot(): Render the tractogram with an optional scalar overlay

Main Functions

Format Conversion

  • trk2tck(): Convert a .trk tractogram to .tck format

  • tck2trk(): Convert a .tck tractogram to .trk format using a reference image

Streamline Utilities

  • resample_streamlines(): Resample a raw streamline collection to a fixed number of points

  • interpolate_streamline_values(): Interpolate values between streamline coordinates

  • merge_tractograms(): Merge multiple tractograms into a single tractogram

Common Usage Examples

Basic loading and inspection:

from clabtoolkit.tracttools import Tractogram

# Load a tractogram from file
tract = Tractogram("/path/to/tractogram.trk")

# Print a full summary of streamlines, maps and geometry
tract.explore_tractogram()

# Basic information and available scalar maps
info = tract.get_tractogram_info()
tract.list_maps()

# Streamline lengths
lengths = tract.compute_streamline_lengths()

Resampling and filtering:

# Resample every streamline to a fixed number of points
tract.resample_streamlines(nb_points=100)

# Smooth streamline geometry
tract.smooth_streamlines(iterations=5, sigma=1.0)

# Keep only the longer streamlines
tract.filter(condition="length > 50")

# Randomly keep half of the streamlines
tract.reduce_streamlines(percentage=50)

Interpolating scalar maps onto streamlines:

# Interpolate an FA map onto each point of every streamline
tract.interpolate_on_tractogram(
    "/path/to/fa_map.nii.gz",
    map_name="fa",
    storage_mode="data_per_point",
    interp_method="linear"
)

# Store a single mean value per streamline instead
tract.interpolate_on_tractogram(
    "/path/to/md_map.nii.gz",
    map_name="md",
    storage_mode="data_per_streamline",
    reduction="mean"
)

# Convert between per-point and per-streamline representations
tract.points_to_streamline(map_name="fa", streamline_map_name="fa_mean", metric="mean")

Bundle clustering and centroids:

# Cluster streamlines with QuickBundles and extract centroids
centroids, indices = tract.compute_centroids(method="qb", thresholds=[10])

# Multi-threshold QuickBundlesX
centroids, indices = tract.compute_centroids(method="qbx", thresholds=[30, 20, 10])

# Label streamlines by cluster and pull one bundle out
tract.label_streamlines_by_clusters()
bundle = tract.get_cluster_streamlines(cluster_id=0)

# Turn the centroids into a tractogram of their own
centroid_tract = tract.centroids_to_tractogram()

Visualization and saving:

# Attach a colortable and render with an overlay
tract.load_colortable("/path/to/lookup_table.lut", map_name="fa")
tract.plot(
    overlay_name="fa",
    cmap="hot",
    views=["lateral"],
    plot_style="tube",
    show_colorbar=True,
    colorbar_title="FA"
)

# Save in either supported format
tract.save_tractogram("/path/to/output.trk", file_type="trk", overwrite=True)

Merging and format conversion:

from clabtoolkit.tracttools import merge_tractograms, trk2tck, tck2trk

# Merge several tractograms, tagging each with a tract_id map
merged = merge_tractograms(
    [tract_a, tract_b],
    color_table="/path/to/bundles.lut",
    map_name="tract_id"
)

# Or merge in place
tract_a.add_tractogram(tract_b)

# Convert between tractography formats
trk2tck("/path/to/tractogram.trk", "/path/to/tractogram.tck", overwrite=True)
tck2trk("/path/to/tractogram.tck", "/path/to/reference.nii.gz", "/path/to/out.trk")