scilpy.tractograms package

scilpy.tractograms.dps_and_dpp_management module

scilpy.tractograms.dps_and_dpp_management.add_data_as_color_dpp(sft, cmap, data, clip_outliers=False, min_range=None, max_range=None, min_cmap=None, max_cmap=None, log=False, LUT=None)[source]

Normalizes data between 0 and 1 for an easier management with colormaps. The real lower bound and upperbound are returned.

Data can be clipped to (min_range, max_range) before normalization. Alternatively, data can be kept as is, but the colormap be fixed to (min_cmap, max_cmap).

Parameters:
  • sft (StatefulTractogram) – The tractogram

  • cmap (plt colormap) – The colormap. Ex, see scilpy.viz.utils.get_colormap().

  • data (np.ndarray or list[list] or list[np.ndarray]) – The data to convert to color. Expecting one value per point to add as dpp. If instead data has one value per streamline, setting the same color to all points of the streamline (as dpp). Either a vector numpy array (all streamlines concatenated), or a list of arrays per streamline.

  • clip_outliers (bool) – See description of the following parameters in clip_and_normalize_data_for_cmap.

  • min_range (float) – Data values below min_range will be clipped.

  • max_range (float) – Data values above max_range will be clipped.

  • min_cmap (float) – Minimum value of the colormap. Most useful when min_range and max_range are not set; to fix the colormap range without modifying the data.

  • max_cmap (float) – Maximum value of the colormap. Idem.

  • log (bool) – If True, apply a logarithmic scale to the data.

  • LUT (np.ndarray) – If set, replaces the data values by the Look-Up Table values. In order, the first value of the LUT is set everywhere where data==1, etc.

Returns:

  • sft (StatefulTractogram) – The tractogram, with dpp ‘color’ added.

  • lbound (float) – The lower bound of the associated colormap.

  • ubound (float) – The upper bound of the associated colormap.

scilpy.tractograms.dps_and_dpp_management.convert_dps_to_dpp(sft, keys, overwrite=False)[source]

Copy the value of the data_per_streamline to each point of the streamline, as data_per_point. The dps key is removed and added as dpp key.

Parameters:
  • sft (StatefulTractogram)

  • keys (str or List[str], optional) – The list of dps keys to convert to dpp.

  • overwrite (bool) – If true, allow continuing even if the key already existed as dpp.

scilpy.tractograms.dps_and_dpp_management.perform_correlation_on_endpoints(sft, dpp_name='metric')[source]

Peforms correlation across endpoints for each streamline. The data_per_point at each point must be a vector.

Parameters:
  • sft (StatefulTractogram) – The streamlines used in the operation.

  • dpp_name (str) – The name of the data per point to be used in the operation.

Returns:

new_data_per_streamline – The correlation values that could now be associated to a new data_per_streamline key.

Return type:

List

scilpy.tractograms.dps_and_dpp_management.perform_operation_dpp_to_dps(op_name, sft, dpp_name, endpoints_only=False)[source]

Converts dpp to dps, using a chosen operation.

Performs an operation across all data_per_points for each streamline (mean, sum, min, max). The result is a data_per_streamline.

If the data_per_point at each point is a vector, operation is done on each feature individually. The data_per_streamline will have the same shape.

Parameters:
  • op_name (str) – A callable that takes a list of streamline data per streamline and returns a list of data per streamline.

  • sft (StatefulTractogram) – The streamlines used in the operation.

  • dpp_name (str) – The name of the data per point to be used in the operation.

  • endpoints_only (bool) – If True, will only perform operation on endpoints. Other points will be ignored in the operation.

Returns:

new_data_per_streamline – The values that could now be associated to a new data_per_streamline key.

Return type:

list

scilpy.tractograms.dps_and_dpp_management.perform_operation_on_dpp(op_name, sft, dpp_name, endpoints_only=False)[source]

Peforms an operation on the data per point for all streamlines (mean, sum, min, max). The operation is applied on each point invidiually, and thus makes sense if the data_per_point at each point is a vector. The result is a new data_per_point.

Parameters:
  • op_name (str) – Name of one possible operation (mean, sum, min, max). Will refer to a callable that takes a list of streamline data per point (4D) and returns a list of streamline data per point.

  • sft (StatefulTractogram) – The streamlines used in the operation.

  • dpp_name (str) – The name of the data per point to be used in the operation. sft.data_per_point[dpp_name][s] must be a 2D vector: (N, M) with s, a given streamline; N the number of points; M the number of features in the dpp.

  • endpoints_only (bool) – If True, will only perform operation on endpoints. Values at other points will be set to NaN.

Returns:

new_data_per_point – The values that could now be associated to a new data_per_point key.

Return type:

ArraySequence

scilpy.tractograms.dps_and_dpp_management.project_dpp_to_map(sft, dpp_key, sum_lines=False, endpoints_only=False)[source]

Saves the values of data_per_point keys to the underlying voxels. Averages the values of various streamlines in each voxel. Returns one map per key. The streamlines are not preprocessed here. You should probably first uncompress your streamlines to have smoother maps. Note: If a streamline has two points in the same voxel, it counts twice!

Parameters:
  • sft (StatefulTractogram) – The tractogram

  • dpp_key (str) – The data_per_point key to project to a map.

  • sum_lines (bool) – Do not average values of streamlines that cross a same voxel; sum them instead.

  • endpoints_only (bool) – If true, only project the streamline’s endpoints.

Returns:

the_map – The 3D resulting map.

Return type:

np.ndarray

scilpy.tractograms.dps_and_dpp_management.project_map_to_streamlines(sft, map_volume, endpoints_only=False)[source]

Projects a map onto the points of streamlines. The result is a data_per_point.

Parameters:
  • sft (StatefulTractogram) – Input tractogram.

  • map_volume (DataVolume) – Input map.

  • endpoints_only (bool, optional) – If True, will only project the map_volume onto the endpoints of the streamlines (all values along streamlines set to NaN). If False, will project the map_volume onto all points of the streamlines.

Returns:

streamline_data – The values that could now be associated to a data_per_point key. The map_volume projected to each point of the streamlines.

Return type:

List[List]

scilpy.tractograms.intersection_finder module

class scilpy.tractograms.intersection_finder.IntersectionFinder(in_sft: StatefulTractogram, diameters: list, shuffle_segments=True, rng_seed=0, verbose=False)[source]

Bases: object

Utility class for finding intersections in a given StatefulTractogram with a diameter for each streamline.

FLOAT_EPSILON = 1e-07
build_tractograms(save_colliding)[source]

Builds and saves the various tractograms obtained from find_intersections().

Parameters:

save_colliding (bool) – If set, will return invalid_sft and obstacle_sft in addition to out_sft.

Returns:

  • out_sft (StatefulTractogram) – Tractogram containing final streamlines void of collision.

  • invalid_sft (StatefulTractogram | None) – Tractogram containing the invalid streamlines that have been removed.

  • obstacle_sft (StatefulTractogram | None) – Tractogram containing the streamlines that the invalid streamlines collided with. May or may not have been removed afterwards during filtering.

property collisions

Collision point of each invalid streamline.

property excluded

Streamlines that don’t collide, but should be excluded for other reasons.

find_intersections(min_distance=0)[source]

Finds intersections within the initialized data of the object

Produces and stores:
invalidndarray[bool]

Bit map identifying streamlines that hit another streamline and should be filtered out.

collisionsndarray[float32]

Collision point of each collider.

obstaclendarray[bool]

Streamlines hit by invalid. They should not be filtered and are flagged simply for visualization.

excludedndarray[bool]

Streamlines that don’t collide, but should be excluded for other reasons. (ex: distance does not respect min_distance)

Parameters:

min_distance (float) – If set, streamlines will be filtered more aggressively so that even if they don’t collide, being below [min_distance] apart (external to their diameter) will be interpreted as a collision. This option is the same as filtering with a large diameter but only saving a small diameter in out_tractogram. (Value in mm)

property invalid

Streamlines that hit another streamline and should be filtered out.

property obstacle

Streamlines hit by an invalid streamline. They should not be filtered and are saved separately merely for visualization.

scilpy.tractograms.lazy_tractogram_operations module

scilpy.tractograms.lazy_tractogram_operations.lazy_concatenate(in_tractograms, out_ext)[source]

Concatenates tractograms, if they can be concatenated. Headers must be compatible.

Parameters:
  • in_tractograms (list) – List of filenames to concatenate

  • out_ext (str) – Output format. Accepting .trk and .tck.

Returns:

  • out_tractogram (LazyTractogram) – The concatenated data

  • header (nibabel header or None) – Depending on the data type.

scilpy.tractograms.lazy_tractogram_operations.lazy_streamlines_count(in_tractogram_path)[source]

Gets the number of streamlines as written in the tractogram header.

Parameters:

in_tractogram_path (str) – Tractogram filepath, must be .trk or .tck.

Returns:

count – Number of streamlines present in the tractogram.

Return type:

int

scilpy.tractograms.streamline_and_mask_operations module

class scilpy.tractograms.streamline_and_mask_operations.CuttingStyle(*values)[source]

Bases: Enum

DEFAULT = (0,)
KEEP_LONGEST = 1
TRIM_ENDPOINTS = 2
scilpy.tractograms.streamline_and_mask_operations.compute_streamline_segment(orig_strl, inter_vox, in_vox_idx, out_vox_idx, points_to_indices)[source]

Compute the segment of a streamline that is in a given ROI or between two ROIs.

If the streamline does not have points in the ROI(s) but intersects it, new points are generated.

Parameters:
  • orig_strl (np.ndarray) – The original streamline.

  • inter_vox (np.ndarray) – The intersection points of the streamline with the voxel grid.

  • in_vox_idx (int) – The index of the voxel where the streamline enters.

  • out_vox_idx (int) – The index of the voxel where the streamline exits.

  • points_to_indices (np.ndarray) – The indices of the voxels in the voxel grid.

Returns:

segment – The segment of the streamline that is in the voxel.

Return type:

np.ndarray

scilpy.tractograms.streamline_and_mask_operations.cut_streamlines_between_labels(sft, label_data, label_ids=None, min_len=0, one_point_in_roi=False, no_point_in_roi=False, processes=1)[source]

Cut streamlines so their segment are going from blob #1 to blob #2 in a binary mask. This function presumes strictly two blobs are present in the mask.

This function erases the data_per_point.

Parameters:
  • sft (StatefulTractogram) – The sft to cut streamlines (using a single mask with 2 entities) from.

  • label_data (np.ndarray) – Label map representing the two regions.

  • label_ids (list of int, optional) – The two labels to cut between. If not provided, the two unique labels in the label map will be used.

  • min_len (float) – Minimum length from the resulting streamlines.

  • one_point_in_roi (bool) – If True, one point in each ROI will be kept.

  • no_point_in_roi (bool) – If True, no point in the ROIs will be kept.

Returns:

new_sft – New object with the streamlines trimmed within the masks.

Return type:

StatefulTractogram

scilpy.tractograms.streamline_and_mask_operations.cut_streamlines_with_mask(sft, mask, cutting_style=CuttingStyle.DEFAULT, min_len=0, processes=1)[source]

Cut streamlines according to a binary mask. This function erases the data_per_point.

If keep_longest is set, the longest segment of the streamline that crosses the mask will be kept. Otherwise, the streamline will be cut at the mask.

Parameters:
  • sft (StatefulTractogram) – The sft to cut streamlines (using a single mask with 1 entity) from.

  • mask (np.ndarray) – Boolean array representing the region (must contain 1 entity)

  • cutting_style (CuttingStyle) – How to cut the streamlines. Default is to cut the streamlines at the mask. If keep_longest is set, the longest segment of the streamline that crosses the mask will be kept. If trim_endpoints is set, the endpoints of the streamlines will be cut but the middle part of the streamline may go outside the mask.

  • min_len (float) – Minimum length from the resulting streamlines.

  • processes (int) – Number of processes to use.

Returns:

new_sft – New object with the streamlines trimmed within the mask.

Return type:

StatefulTractogram

scilpy.tractograms.streamline_and_mask_operations.get_endpoints_density_map(sft, point_to_select=1, to_millimeters=False, binary=False)[source]

Compute an endpoints density map, supports selecting more than one points at each end.

Parameters:
  • sft (StatefulTractogram) – The streamlines to compute endpoints density from.

  • point_to_select (int) – Instead of computing the density based on the first and last points, select more than one at each end.

  • to_millimeters (bool) – Resample the streamlines to have a step size of 1 mm. This allows the user to compute endpoints with mms instead of points. Especially useful with compressed streamlines.

  • binary (bool) – Return a binary mask.

Returns:

np.ndarray – endpoints.

Return type:

A np.ndarray where voxel values represent the density of

scilpy.tractograms.streamline_and_mask_operations.get_head_tail_density_maps(sft, point_to_select=1, to_millimeters=False, binary=False, swap=False)[source]

Compute two separate endpoints density maps for the head and tail of a list of streamlines.

Parameters:
  • sft (StatefulTractogram) – The streamlines to compute endpoints density from.

  • point_to_select (int) – Instead of computing the density based on the first and last points, select more than one at each end.

  • to_millimeters (bool) – Resample the streamlines to have a step size of 1 mm. This allows the user to compute endpoints with mms instead of points. Especially useful with compressed streamlines.

  • binary (bool) – Return binary maps

  • swap (bool) – Swap head and tail conventions

Returns:

  • endpoints_map_head (np.ndarray) – A volume where voxel values represent the density of head endpoints.

  • endpoints_map_tail (np.ndarray) – A volume where voxel values represent the density of tail endpoints.

scilpy.tractograms.streamline_operations module

scilpy.tractograms.streamline_operations.compress_sft(sft, tol_error=0.01)[source]

Compress a stateful tractogram. Uses Dipy’s compress_streamlines, but deals with space better.

Dipy’s description: The compression consists in merging consecutive segments that are nearly collinear. The merging is achieved by removing the point the two segments have in common.

The linearization process [Presseau15] ensures that every point being removed are within a certain margin (in mm) of the resulting streamline. Recommendations for setting this margin can be found in [Presseau15] (in which they called it tolerance error).

The compression also ensures that two consecutive points won’t be too far from each other (precisely less or equal than max_segment_length mm). This is a tradeoff to speed up the linearization process [Rheault15]. A low value will result in a faster linearization but low compression, whereas a high value will result in a slower linearization but high compression.

[Presseau C. et al., A new compression format for fiber tracking datasets, NeuroImage, no 109, 73-83, 2015.]

Parameters:
  • sft (StatefulTractogram) – The sft to compress.

  • tol_error (float (optional)) – Tolerance error in mm (default: 0.01). A rule of thumb is to set it to 0.01mm for deterministic streamlines and 0.1mm for probabilitic streamlines.

Returns:

compressed_sft

Return type:

StatefulTractogram

scilpy.tractograms.streamline_operations.cut_invalid_streamlines(sft, epsilon=0.001)[source]

Cut streamlines so their longest segment are within the bounding box. This function keeps the data_per_point and data_per_streamline.

Parameters:
  • sft (StatefulTractogram) – The sft to remove invalid points from.

  • epsilon (float) – Error allowed when verifying the bounding box.

Returns:

  • new_sft (StatefulTractogram) – New object with the invalid points removed from each streamline.

  • cutting_counter (int) – Number of streamlines that were cut.

scilpy.tractograms.streamline_operations.filter_streamlines_by_length(sft, min_length=0.0, max_length=inf, return_rejected=False)[source]

Filter streamlines using minimum and max length.

Parameters:
  • sft (StatefulTractogram) – SFT containing the streamlines to filter.

  • min_length (float) – Minimum length of streamlines, in mm.

  • max_length (float) – Maximum length of streamlines, in mm.

  • return_rejected (bool) – If true, also returns the sft of rejected streamlines.

Returns:

  • filtered_sft (StatefulTractogram) – A tractogram without short/long streamlines.

  • valid_length_ids (list) – The ids of kept streamlines.

  • rejected_sft (StatefulTractogram) – The rejected (short/long) streamlines. (If return_rejected) A tractogram without short streamlines.

scilpy.tractograms.streamline_operations.filter_streamlines_by_nb_points(sft, min_nb_points=2)[source]

Remove streamlines from a StatefulTractogram with fewer nb_points.

Parameters:
  • sft (StatefulTractogram) – The sft to remove single point streamlines from.

  • min_nb_points (int) – Minimum number of point a streamline needs to have to kept.

Returns:

new_sft – New object with the single point streamlines removed.

Return type:

StatefulTractogram

scilpy.tractograms.streamline_operations.filter_streamlines_by_total_length_per_dim(sft, limits_x, limits_y, limits_z, use_abs, save_rejected)[source]

Filter streamlines using sum of abs length per dimension.

Note: we consider that x, y, z are the coordinates of the streamlines; we do not verify if they are aligned with the brain’s orientation.

Parameters:
  • sft (StatefulTractogram) – SFT containing the streamlines to filter.

  • limits_x ([float float]) – The list of [min, max] for the x coordinates.

  • limits_y ([float float]) – The list of [min, max] for the y coordinates.

  • limits_z ([float float]) – The list of [min, max] for the z coordinates.

  • use_abs (bool) – If True, will use the total of distances in absolute value (ex, coming back on yourself will contribute to the total distance instead of cancelling it).

  • save_rejected (bool) – If true, also returns the SFT of rejected streamlines. Else, returns None.

Returns:

  • filtered_sft (StatefulTractogram) – A tractogram of accepted streamlines.

  • ids (list) – The list of good ids.

  • rejected_sft (StatefulTractogram or None) – A tractogram of rejected streamlines.

scilpy.tractograms.streamline_operations.find_seed_indexes_on_streamlines(seeds, streamlines, atol=1e-08)[source]

Given a list of seeds and a corresponding list of streamlines, finds the index of each seed on its respective streamline.

Parameters:
  • seeds (list) – List of seeds to locate on streamlines

  • streamlines (list) – List of streamlines produced from seeds

  • atol (float) – Absolute tolerance of the comparison between a seed and each of the streamline coordinates.

Returns:

seed_indexes – A list containing the index of each seed on its streamline.

Return type:

list

scilpy.tractograms.streamline_operations.generate_matched_points(sft)[source]

Generates an array where each element i is set to the index of the streamline to which it belongs

Parameters:

sft (StatefulTractogram) – The stateful tractogram containing the streamlines.

Returns:

matched_points – An array where each element is set to the index of the streamline to which it belongs

Return type:

ndarray

scilpy.tractograms.streamline_operations.get_angles(sft, degrees=True, add_zeros=False)[source]

Returns the angle between each segment of the streamlines.

Parameters:
  • sft (StatefulTractogram) – The tractogram, with N streamlines.

  • degrees (bool) – If True, returns angles in degree. Else, in radian.

  • add_zeros (bool) – For a streamline of length M, there are M-1 segments, and M-2 angles. If add_zeros is set to True, a 0 angle is added at both ends of the returned values, to get M values.

Returns:

angles – List of N numpy arrays. The angles per streamline, in degree.

Return type:

list[np.ndarray]

scilpy.tractograms.streamline_operations.get_streamlines_as_fixed_array(streamlines)[source]

Obtain streamlines as a fixed array of shape (nbr of streamlines, max streamline length, 3).

Useful for optimization with code precompiling. (See Numba)

Parameters:

streamlines (list) – The list of streamlines to convert into a fixed length array

Returns:

  • streamlines_fixed (ndarray) – Streamlines as a fixed length array, padded with 0.

  • lengths (ndarray) – Single dimensional array of all the streamline lengths.

scilpy.tractograms.streamline_operations.get_streamlines_as_linspaces(sft)[source]

For each streamline, returns a list of M values ranging between 0 and 1, where M is the number of points in the streamline. This gives the position of each coordinate per respect to the streamline’s length.

Parameters:

sft (StatefulTractogram) – The tractogram that contains the list of streamlines to be colored

Returns:

positions – For each streamline, the linear distribution of its length.

Return type:

list[list]

scilpy.tractograms.streamline_operations.get_streamlines_bounding_box(streamlines)[source]

Classify inliers and outliers from a list of streamlines.

Parameters:

streamlines (list of ndarray) – The list of streamlines from which inliers and outliers are separated.

Returns:

tuple – bounding box

Return type:

Minimum and maximum corner coordinate of the streamlines

scilpy.tractograms.streamline_operations.parallel_transport_streamline(streamline, nb_streamlines, radius, rng=None)[source]

Generate new streamlines by parallel transport of the input streamline. See [0] and [1] for more details.

[0]: Hanson, A.J., & Ma, H. (1995). Parallel Transport Approach to

Curve Framing. # noqa E501

[1]: TD Essentials: Parallel Transport.

https://www.youtube.com/watch?v=5LedteSEgOE

Parameters:
  • streamline (ndarray (N, 3)) – The streamline to transport.

  • nb_streamlines (int) – The number of streamlines to generate.

  • radius (float) – The radius of the circle around the original streamline in which the new streamlines will be generated.

  • rng (numpy.random.Generator, optional) – The random number generator to use. If None, the default numpy random number generator will be used.

Returns:

new_streamlines – The generated streamlines.

Return type:

list of ndarray (N, 3)

scilpy.tractograms.streamline_operations.remove_loops(streamlines, max_angle, num_processes=1)[source]

Remove loops from a list of streamlines.

Parameters:
  • streamlines (list or ndarray) – The list of streamlines from which to remove loops and sharp turns.

  • max_angle (float) – Maximal winding angle a streamline can have before being classified as a loop (in degree).

  • num_processes (int) – Split the calculation to a pool of children processes.

Returns:

  • ids (list) – Ids of the streamlines with no loop.

  • streamlines_clean (list or ndarray) – The remaining streamlines.

scilpy.tractograms.streamline_operations.remove_loops_and_sharp_turns(streamlines, max_angle, qb_threshold=None, qb_seed=0, num_processes=1)[source]

Remove loops and sharp turns from a list of streamlines.

Parameters:
  • streamlines (list or ndarray) – The list of streamlines from which to remove loops and sharp turns.

  • max_angle (float) – Maximal winding angle a streamline can have before being classified as a loop (in degree)

  • qb_threshold (float, optional) – If not None, do the additional QuickBundles pass. This will help remove sharp turns. Should only be used on bundled streamlines, not on whole-brain tractograms. If set, value is the Quickbundles distance threshold. Suggested default: 15.

  • qb_seed (int) – Seed to initialize randomness in QuickBundles

  • num_processes (int) – Split the calculation to a pool of children processes.

Returns:

ids – Ids of good streamlines. Only the ids are returned so proper filtering can be done afterwards.

Return type:

list

scilpy.tractograms.streamline_operations.remove_overlapping_points_streamlines(sft, threshold=0.001)[source]

Remove overlapping points from streamlines in a StatefulTractogram, i.e. points forming a segment of length < threshold in a given streamline.

Parameters:
  • sft (StatefulTractogram) – The sft to remove overlapping points from.

  • threshold (float (optional)) – Maximum distance between two points to be considered overlapping. Default: 0.001 mm.

Returns:

new_sft – New object with the overlapping points removed from each streamline.

Return type:

StatefulTractogram

scilpy.tractograms.streamline_operations.remove_sharp_turns_qb(streamlines, qb_threshold=15.0, qb_seed=0)[source]

Remove sharp turns from a list of streamlines. Should only be used on bundled streamlines, not on whole-brain tractograms.

Parameters:
  • streamlines (list or ndarray) – The list of streamlines from which to remove loops and sharp turns.

  • qb_threshold (float) – The Quickbundles distance threshold.

  • qb_seed (int) – Seed to initialize randomness in QuickBundles

Returns:

ids – Ids of good streamlines.

Return type:

list

scilpy.tractograms.streamline_operations.remove_streamlines_with_overlapping_points(sft, eps=0.001)[source]

Remove streamlines with overlapping points (step size < eps)

Parameters:
  • sft (StatefulTractogram) – The tractogram.

  • eps (float) – The minimal step size.

Returns:

sft

Return type:

StatefulTractogram

scilpy.tractograms.streamline_operations.resample_streamlines_num_points(sft, num_points)[source]

Resample streamlines using number of points per streamline

Parameters:
  • sft (StatefulTractogram) – SFT containing the streamlines to subsample.

  • num_points (int) – Number of points per streamline in the output.

Returns:

resampled_sft – The resampled streamlines as a sft.

Return type:

StatefulTractogram

scilpy.tractograms.streamline_operations.resample_streamlines_step_size(sft, step_size)[source]

Resample streamlines using a fixed step size.

Parameters:
  • sft (StatefulTractogram) – SFT containing the streamlines to subsample.

  • step_size (float) – Size of the new steps, in mm.

Returns:

resampled_sft – The resampled streamlines as a sft.

Return type:

StatefulTractogram

scilpy.tractograms.streamline_operations.smooth_line_gaussian(streamline, sigma)[source]

Smooths a streamline using a gaussian filter. Enforces the endpoints to remain the same.

Parameters:
  • streamline (np.ndarray) – The streamline to smooth.

  • sigma (float) – The sigma of the gaussian filter.

Returns:

smoothed_streamline – The smoothed streamline.

Return type:

np.ndarray

scilpy.tractograms.streamline_operations.smooth_line_spline(streamline, smoothing_parameter, nb_ctrl_points)[source]

Smooths a streamline using a spline. The number of control points can be specified, but must be at least 3. The final streamline will have the same number of points as the input streamline. Enforces the endpoints to remain the same.

Parameters:
  • streamline (np.ndarray) – The streamline to smooth.

  • smoothing_parameter (float) – The sigma of the spline.

  • nb_ctrl_points (int) – The number of control points.

Returns:

smoothed_streamline – The smoothed streamline.

Return type:

np.ndarray

scilpy.tractograms.tractogram_operations module

This module regroups small operations and util functions for tractogram. Meaning that these operations are applied on the streamlines as wholes (ex, registration, suffling, etc), not on each point of the streamlines separately / individually. See scilpy.tractograms.streamline_operations.py for the latter.

scilpy.tractograms.tractogram_operations.compress_streamlines_wrapper(tractogram, error_rate)[source]

Compresses the streamlines of a tractogram. Supports both nibabel.Tractogram dipy.StatefulTractogram or list of streamlines.

Parameters:
  • tractogram (TrkFile, TckFile, ArraySequence, list) – The tractogram to compress.

  • error_rate (float) – The maximum distance (in mm) for point displacement during compression.

Returns:

compressed_streamlines – The compressed streamlines.

Return type:

list of np.ndarray

scilpy.tractograms.tractogram_operations.concatenate_sft(sft_list, erase_metadata=False, metadata_fake_init=False)[source]

Concatenate a list of StatefulTractogram together

scilpy.tractograms.tractogram_operations.cut_streamlines_alter(sft, min_dice=0.9, epsilon=0.01, from_end=False)[source]

Cut streamlines based on a dice similarity metric. The function will keep removing points from the streamlines until the dice similarity between the original and the cut tractogram is close to min_dice.

Parameters:
  • sft (StatefulTractogram) – The tractogram to cut.

  • min_dice (float) – The minimum dice similarity to reach before stopping the cutting.

  • epsilon (float) – Stopping criteria for convergence. The maximum difference between the dice similarity and min_dice.

  • from_end (bool) – If True, the streamlines will be cut from the end. Else, the streamlines will be cut from the start.

Returns:

new_sft – The tractogram with cut streamlines in the same space as the input tractogram.

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.difference(left, right)[source]

Difference of two streamlines dict (see hash_streamlines)

scilpy.tractograms.tractogram_operations.difference_robust(streamlines_list, precision=3)[source]

Difference of a list of StatefulTractogram from the first element

scilpy.tractograms.tractogram_operations.flip_sft(sft, flip_axes)[source]
Parameters:
  • sft (StatefulTractogram)

  • flip_axes (List[str]) – The list of axes to flip. Ex: [‘x’, ‘y’, ‘z’]. The axes correspond to the coordinates of the sft as it is stored in memory, not to axes of the image.

Returns:

flipped_sft

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.get_axis_flip_vector(flip_axes)[source]

Create a flip vector from a list of axes.

Parameters:

flip_axes (list) – List of axes you want to flip

Returns:

shift_vector – Vector with flipped axes

Return type:

list[3,]

scilpy.tractograms.tractogram_operations.intersection(left, right)[source]

Intersection of two streamlines dict (see hash_streamlines)

scilpy.tractograms.tractogram_operations.intersection_robust(streamlines_list, precision=3)[source]

Intersection of a list of StatefulTractogram

scilpy.tractograms.tractogram_operations.perform_tractogram_operation_on_lines(operation, streamlines, precision=None)[source]

Peforms an operation on a list of list of streamlines.

Given a list of list of streamlines, this function applies the operation to the first two lists of streamlines. The result in then used recursively with the third, fourth, etc. lists of streamlines.

A valid operation is any function that takes two streamlines dict as input and produces a new streamlines dict (see hash_streamlines). Union, difference, and intersection are valid examples of operations.

Parameters:
  • operation (callable) – A callable that takes two streamlines dicts as inputs and preduces a new streamline dict.

  • streamlines (list of list of streamlines) – The streamlines used in the operation.

  • precision (int, optional) – The number of decimals to keep when hashing the points of the streamlines. Allows a soft comparison of streamlines. If None, no rounding is performed.

Returns:

  • streamlines (list of nib.streamline.Streamlines) – The streamlines obtained after performing the operation on all the input streamlines.

  • indices (np.ndarray) – The indices of the streamlines that are used in the output.

scilpy.tractograms.tractogram_operations.perform_tractogram_operation_on_sft(op_name, sft_list, precision, no_metadata, fake_metadata)[source]

Peforms an operation on a list of tractograms.

Parameters:
  • op_name (str) – A callable that takes two streamlines dicts as inputs and preduces a new streamline dict.

  • sft_list (list[StatefulTractogram]) – The tractograms used in the operation.

  • precision (int, optional) – The number of decimals to keep when hashing the points of the streamlines. Allows a soft comparison of streamlines. If None, no rounding is performed. Precision should be in the same space as sfts (ex, mm).

  • no_metadata (bool) – If true, remove all metadata.

  • fake_metadata (bool) – If true, fake metadata for SFTs that do not contain the keys available in other SFTs.

Returns:

sft – The final SFT

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.replace_streamlines_alter(sft, min_dice=0.9, epsilon=0.01)[source]

Replace streamlines based on a dice similarity metric. The function will upsample the streamlines (with parallel transport), then downsample them until the dice similarity is close to min_dice. This effectively replaces the streamlines with new ones.

Parameters:
  • sft (StatefulTractogram) – The tractogram to replace streamlines from.

  • min_dice (float) – The minimum dice similarity to reach before stopping the replacement.

  • epsilon (float) – Stopping criteria for convergence. The maximum difference between the dice similarity and min_dice.

Returns:

new_sft – The tractogram with replaced streamlines in the same space as the input tractogram.

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.shuffle_streamlines(sft, rng_seed=None)[source]

Shuffle the streamlines of a tractogram.

Parameters:
  • sft (StatefulTractogram) – The tractogram to shuffle (will slice the streamline, DPS and DPP).

  • rng_seed (int)

Returns:

shuffled_sft – The shuffled tractogram.

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.shuffle_streamlines_orientation(sft, rng_seed=None)[source]

Shuffle the orientation of the streamlines. Iterate over streamlines and randomly decide (50/50) if the streamline’s head and tail should be swapped.

Parameters:
  • sft (StatefulTractogram) – The tractogram that will have its streamlines’ orientation shuffled.

  • rng_seed (int) – Random seed.

Returns:

shuffled_sft – The shuffled tractogram.

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.split_sft_randomly(orig_sft, chunk_sizes, rng_seed, return_indices_only=False)[source]

Divides a stateful tractogram into n sub-tractograms of sizes defined by chunk_sizes. Streamlines are separated randomly from the initial streamlines.

Parameters:
  • orig_sft (StatefulTractogram) – Initial tractogram to subdivide

  • chunk_sizes (int or list[int]) – Number of streamlines to keep (per sub-tractogram if it is a list).

  • rng_seed (int) – Random seed.

  • return_indices_only (bool) – If true, return a random list of indices. Else, return the Stateful Tractogram containing the chosen streamlines.

Returns:

all_chunks – The list of sub-tractograms as sfts. The number of tractograms returned is len(chunk_sizes) + 1, where the last item of the list contains streamlines that were not included in any. (Or the lists of indices if return_indices_only.)

Return type:

list[StatefulTractogram] or list[list[int]]

scilpy.tractograms.tractogram_operations.split_sft_randomly_per_cluster(orig_sft, chunk_sizes, seed, thresholds)[source]

Divides a stateful tractogram into n sub-tractograms of sizes defined by chunk_sizes. Streamlines are separated randomly from each Quickbundle cluster created from the initial streamlines (trying to help the randomization to ensure there are streamlines from all bundles in each subset).

Parameters:
  • orig_sft (StatefulTractogram) – Initial tractogram to subdivide

  • chunk_sizes (list[int]) – Number of streamlines to keep per chunk. We will ensure that the number of streamlines kept per cluster is proportional to the cluster’s size. Final number will be a good approximation of nb_streamlines, but not exact.

  • seed (int) – Random seed.

  • thresholds (list[float]) – QBx threshold values. Suggestion: [40, 30, 20].

Returns:

all_sfts – The list of sub-tractograms as sfts. The number of tractograms returned is len(chunk_sizes) + 1, where the last item of the list contains streamlines that were not included in any.

Return type:

list[StatefulTractogram]

scilpy.tractograms.tractogram_operations.split_sft_sequentially(orig_sft, chunk_sizes)[source]

Divides a stateful tractogram into n sub-tractograms of sizes defined by chunk_sizes. Streamlines are separated sequentially from the initial streamlines.

Parameters:
  • orig_sft (StatefulTractogram) – Initial tractogram to subdivide.

  • chunk_sizes (list[int]) – Number of streamlines to keep per chunk.

Returns:

all_chunks – The list of sub-tractograms as sfts. The number of tractograms returned is len(chunk_sizes).

Return type:

list[StatefulTractogram]

scilpy.tractograms.tractogram_operations.subsample_streamlines_alter(sft, min_dice=0.9, epsilon=0.01, baseline_sft=None)[source]

Function to subsample streamlines based on a dice similarity metric. The function will keep removing streamlines until the dice similarity between the original and the subsampled tractogram is close to min_dice.

Parameters:
  • sft (StatefulTractogram) – The tractogram to subsample.

  • min_dice (float) – The minimum dice similarity to reach before stopping the subsampling.

  • epsilon (float) – Stopping criteria for convergence. The maximum difference between the dice similarity and min_dice.

  • baseline_sft (StatefulTractogram) – The tractogram to use as a reference for the dice similarity. If None, the original tractogram will be used.

Returns:

new_sft – The tractogram with a subset of streamlines in the same space as the input tractogram.

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.transform_streamlines_alter(sft, min_dice=0.9, epsilon=0.01)[source]

The function will apply random rotations to the streamlines until the dice similarity between the original and the transformed tractogram is close to min_dice.

Start with a large XYZ rotation, then reduce the rotation step by half one axis at a time until the dice similarity is close to min_dice.

Parameters:
  • sft (StatefulTractogram) – The tractogram to transform.

  • min_dice (float) – The minimum dice similarity to reach before stopping the transformation.

  • epsilon (float) – Stopping criteria for convergence. The maximum difference between the dice similarity and min_dice.

Returns:

new_sft – The tractogram with transformed streamlines in the same space as the input tractogram.

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.transform_warp_sft(sft, linear_transfo, target, inverse=False, reverse_op=False, deformation_data=None, remove_invalid=True, cut_invalid=False)[source]

Transform tractogram using an affine Subsequently apply a warp from antsRegistration (optional). Remove/Cut invalid streamlines to preserve sft validity.

Parameters:
  • sft (StatefulTractogram) – Stateful tractogram object containing the streamlines to transform.

  • linear_transfo (numpy.ndarray) – Linear transformation matrix to apply to the tractogram.

  • target (Nifti filepath, image object, header) – Final reference for the tractogram after registration.

  • inverse (boolean) – Apply the inverse linear transformation.

  • reverse_op (boolean) – Apply both transformation in the reverse order

  • deformation_data (np.ndarray) – 4D array containing a 3D displacement vector in each voxel.

  • remove_invalid (boolean) – Remove the streamlines landing out of the bounding box.

  • cut_invalid (boolean) – Cut invalid streamlines rather than removing them. Keep the longest segment only.

Returns:

new_sft

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.trim_streamlines_alter(sft, min_dice=0.9, epsilon=0.01)[source]

Trim streamlines based on a dice similarity metric. The function will remove low density voxels to trim streamlines until the similarity between the original and the trimmed tractogram is close to min_dice.

Parameters:
  • sft (StatefulTractogram) – The tractogram to trim.

  • min_dice (float) – The minimum dice similarity to reach before stopping the trimming.

  • epsilon (float) – Stopping criteria for convergence. The maximum difference between the dice similarity and min_dice.

Returns:

new_sft – The tractogram with trimmed streamlines in the same space as the input tract

Return type:

StatefulTractogram

scilpy.tractograms.tractogram_operations.union(left, right)[source]

Union of two streamlines dict (see hash_streamlines)

scilpy.tractograms.tractogram_operations.union_robust(streamlines_list, precision=3)[source]

Union of a list of StatefulTractogram

scilpy.tractograms.tractogram_operations.upsample_tractogram(sft, nb, point_wise_std=None, tube_radius=None, gaussian=None, error_rate=None, seed=None)[source]

Generates new streamlines by either adding gaussian noise around streamlines’ points, or by translating copies of existing streamlines by a random amount.

The first streamlines of the returned tractogram are the initial streamlines, unchanged (if error_rate is None).

Parameters:
  • sft (StatefulTractogram) – The tractogram to upsample

  • nb (int) – The target number of streamlines in the tractogram.

  • point_wise_std (float, optional) – The standard deviation of the gaussian to use to generate point-wise noise on the streamlines. If None or zero, this is skipped.

  • tube_radius (float, optional) – The radius of the tube used to model the streamlines. If None or zero, this is skipped.

  • gaussian (float, optional) – The sigma used for smoothing streamlines. Only the newly created streamlines are smoothed. If None, streamlines are not smoothed.

  • error_rate (float, optional) – The compression error. The whole final tractogram is compressed. If None, no compression is done.

  • seed (int, optional) – Seed for RNG. If None, uses random seed.

Returns:

new_sft – The upsampled tractogram.

Return type:

StatefulTractogram

scilpy.tractograms.uncompress module

scilpy.tractograms.uncompress.streamlines_to_voxel_coordinates(streamlines, return_mapping=False)

Get the indices of the voxels traversed by each streamline; then returns an ArraySequence of indices, i.e. [i, j, k] coordinates.

Parameters:
  • streamlines (nibabel.streamlines.array_sequence.ArraySequence) – Should be in voxel space, aligned to corner.

  • return_mapping (bool) – If true, also returns the points_to_idx.

Returns:

  • indices (nibabel.streamlines.array_sequence.ArraySequence) – An array of length nb_streamlines. Each element is a np.ndarray of shape (nb_voxels, 3) containing indices. All 3D coordinates are unique. Note. ArraySequence.get_data() is always of type float32 and contains points except here: it’s of type uint16 and contain indices. You can use this object exactly as you would use a normal ArraySequence.

  • points_to_idx (nibabel.streamlines.array_sequence.ArraySequence (optional)) – An array of length nb_streamlines. Each element is a np.ndarray of shape (nb_points) containing, for each streamline point, the associated voxel in indices. Note: Some points are associated to the same index, if they were in the same voxel. Some voxels are associated to no point, if they were traversed by a segment but contained no point.