tracking#

Tracking objects

Module: tracking._utils#

This is a helper module for dipy.tracking.utils.

Module: tracking.learning#

Learning algorithms for tractography

detect_corresponding_tracks(indices, ...)

Detect corresponding tracks from list tracks1 to list tracks2 where tracks1 & tracks2 are lists of tracks

detect_corresponding_tracks_plus(indices, ...)

Detect corresponding tracks from 1 to 2 where tracks1 & tracks2 are sequences of tracks

Module: tracking.life#

This is an implementation of the Linear Fascicle Evaluation (LiFE) algorithm described in [1].

References#

LifeSignalMaker(gtab, *[, evals, sphere])

A class for generating signals from streamlines in an efficient and speedy manner.

FiberModel(gtab)

A class for representing and solving predictive models based on tractography solutions.

FiberFit(fiber_model, life_matrix, ...)

A fit of the LiFE model to diffusion data

gradient(f)

Return the gradient of an N-dimensional array.

streamline_gradients(streamline)

Calculate the gradients of the streamline along the spatial dimension

grad_tensor(grad, evals)

Calculate the 3 by 3 tensor for a given spatial gradient, given a canonical tensor shape (also as a 3 by 3), pointing at [1,0,0]

streamline_tensors(streamline, *[, evals])

The tensors generated by this fiber.

streamline_signal(streamline, gtab, *[, evals])

The signal from a single streamline estimate along each of its nodes.

voxel2streamline(streamline, affine, *[, ...])

Maps voxels to streamlines and streamlines to voxels, for setting up the LiFE equations matrix

Module: tracking.local_tracking#

LocalTracking(direction_getter, ...[, ...])

ParticleFilteringTracking(direction_getter, ...)

Module: tracking.mesh#

random_coordinates_from_surface(...[, ...])

Generate random triangles_indices and trilinear_coord

seeds_from_surface_coordinates(triangles, ...)

Compute points from triangles_indices and trilinear_coord

triangles_area(triangles, vts)

Compute the local area of each triangle

vertices_to_triangles_values(triangles, ...)

Change from values per vertex to values per triangle

Module: tracking.metrics#

Metrics for tracks, where tracks are arrays of points

winding(xyz)

Total turning angle projected.

length(xyz, *[, along])

Euclidean length of track line

bytes(xyz)

Size of track in bytes.

midpoint(xyz)

Midpoint of track

center_of_mass(xyz)

Center of mass of streamline

magn(xyz, *[, n])

magnitude of vector

frenet_serret(xyz)

Frenet-Serret Space Curve Invariants

mean_curvature(xyz)

Calculates the mean curvature of a curve

mean_orientation(xyz)

Calculates the mean orientation of a curve

generate_combinations(items, n)

Combine sets of size n from items

longest_track_bundle(bundle, *[, sort])

Return longest track or length sorted track indices in bundle

intersect_sphere(xyz, center, radius)

If any segment of the track is intersecting with a sphere of specific center and radius return True otherwise False

inside_sphere(xyz, center, radius)

If any point of the track is inside a sphere of a specified center and radius return True otherwise False.

inside_sphere_points(xyz, center, radius)

If a track intersects with a sphere of a specified center and radius return the points that are inside the sphere otherwise False.

spline(xyz, *[, s, k, nest])

Generate B-splines as documented in https://scipy-cookbook.readthedocs.io/items/Interpolation.html

startpoint(xyz)

First point of the track

endpoint(xyz)

Parameters:

arbitrarypoint(xyz, distance)

Select an arbitrary point along distance on the track (curve)

principal_components(xyz)

We use PCA to calculate the 3 principal directions for a track

midpoint2point(xyz, p)

Calculate distance from midpoint of a curve to arbitrary point p

Module: tracking.streamline#

unlist_streamlines(streamlines)

Return the streamlines not as a list but as an array and an offset

relist_streamlines(points, offsets)

Given a representation of a set of streamlines as a large array and an offsets array return the streamlines as a list of shorter arrays.

center_streamlines(streamlines)

Move streamlines to the origin

deform_streamlines(streamlines, ...)

Apply deformation field to streamlines

transform_streamlines(streamlines, mat, *[, ...])

Apply affine transformation to streamlines

select_random_set_of_streamlines(...[, rng])

Select a random set of streamlines

select_by_rois(streamlines, affine, rois, ...)

Select streamlines based on logical relations with several regions of interest (ROIs).

cluster_confidence(streamlines, *[, ...])

Computes the cluster confidence index (cci), which is an estimation of the support a set of streamlines gives to a particular pathway.

orient_by_rois(streamlines, affine, roi1, ...)

Orient a set of streamlines according to a pair of ROIs

orient_by_streamline(streamlines, standard, *)

Orient a bundle of streamlines to a standard streamline.

values_from_volume(data, streamlines, affine)

Extract values of a scalar/vector along each streamline from a volume.

nbytes(streamlines)

Module: tracking.tracker#

generic_tracking(seed_positions, ...[, ...])

probabilistic_tracking(seed_positions, sc, ...)

Probabilistic tracking algorithm.

deterministic_tracking(seed_positions, sc, ...)

Deterministic tracking algorithm.

ptt_tracking(seed_positions, sc, affine, *)

Parallel Transport Tractography (PTT) tracking algorithm.

closestpeak_tracking(seed_positions, sc, ...)

Closest peak tracking algorithm.

bootstrap_tracking(seed_positions, sc, affine, *)

Bootstrap tracking algorithm.

eudx_tracking(seed_positions, sc, affine, *)

EuDX tracking algorithm.

pft_tracking(seed_positions, sc, affine, *)

Particle Filtering Tracking (PFT) tracking algorithm.

Module: tracking.utils#

Various tools related to creating and working with streamlines.

This module provides tools for targeting streamlines using ROIs, for making connectivity matrices from whole brain fiber tracking and some other tools that allow streamlines to interact with image data.

Important Notes#

Dipy uses affine matrices to represent the relationship between streamline points, which are defined as points in a continuous 3d space, and image voxels, which are typically arranged in a discrete 3d grid. Dipy uses a convention similar to nifti files to interpret these affine matrices. This convention is that the point at the center of voxel [i, j, k] is represented by the point [x, y, z] where [x, y, z, 1] = affine * [i, j, k, 1]. Also when the phrase “voxel coordinates” is used, it is understood to be the same as affine = eye(4).

As an example, let’s take a 2d image where the affine is:

[[1., 0., 0.],
 [0., 2., 0.],
 [0., 0., 1.]]

The pixels of an image with this affine would look something like:

A------------
|   |   |   |
| C |   |   |
|   |   |   |
----B--------
|   |   |   |
|   |   |   |
|   |   |   |
-------------
|   |   |   |
|   |   |   |
|   |   |   |
------------D

And the letters A-D represent the following points in “real world coordinates”:

A = [-.5, -1.]
B = [ .5,  1.]
C = [ 0.,  0.]
D = [ 2.5,  5.]

density_map(streamlines, affine, vol_dims)

Count the number of unique streamlines that pass through each voxel.

connectivity_matrix(streamlines, affine, ...)

Count the streamlines that start and end at each label pair.

ndbincount(x, *[, weights, shape])

Like bincount, but for nd-indices.

reduce_labels(label_volume)

Reduce an array of labels to the integers from 0 to n with smallest possible n.

subsegment(streamlines, max_segment_length)

Split the segments of the streamlines into small segments.

seeds_from_mask(mask, affine, *[, density])

Create seeds for fiber tracking from a binary mask.

random_seeds_from_mask(mask, affine, *[, ...])

Create randomly placed seeds for fiber tracking from a binary mask.

target(streamlines, affine, target_mask, *)

Filter streamlines based on whether or not they pass through an ROI.

target_line_based(streamlines, affine, ...)

Filter streamlines based on whether or not they pass through a ROI, using a line-based algorithm.

streamline_near_roi(streamline, roi_coords, ...)

Is a streamline near an ROI.

near_roi(streamlines, affine, ...[, tol, mode])

Provide filtering criteria for a set of streamlines based on whether they fall within a tolerance distance from an ROI.

length(streamlines)

Calculate the lengths of many streamlines in a bundle.

unique_rows(in_array, *[, dtype])

Find the unique rows in an array.

transform_tracking_output(tracking_output, ...)

Apply a linear transformation, given by affine, to streamlines.

reduce_rois(rois, include)

Reduce multiple ROIs to one inclusion and one exclusion ROI.

path_length(streamlines, affine, aoi, *[, ...])

Compute the shortest path, along any streamline, between aoi and each voxel.

max_angle_from_curvature(...)

Get the maximum deviation angle from the minimum radius curvature.

min_radius_curvature_from_angle(max_angle, ...)

Get minimum radius of curvature from a deviation angle.

seeds_directions_pairs(positions, peaks, *)

Pair each seed to the corresponding peaks.

detect_corresponding_tracks#

dipy.tracking.learning.detect_corresponding_tracks(indices, tracks1, tracks2)[source]#

Detect corresponding tracks from list tracks1 to list tracks2 where tracks1 & tracks2 are lists of tracks

Parameters:
indicessequence

of indices of tracks1 that are to be detected in tracks2

tracks1sequence

of tracks as arrays, shape (N1,3) .. (Nm,3)

tracks2sequence

of tracks as arrays, shape (M1,3) .. (Mm,3)

Returns:
track2trackarray (N,2) where N is len(indices) of int

it shows the correspondence in the following way: the first column is the current index in tracks1 the second column is the corresponding index in tracks2

Notes

To find the corresponding tracks we use mam_distances with ‘avg’ option. Then we calculate the argmin of all the calculated distances and return it for every index. (See 3rd column of arr in the example given below.)

Examples

>>> import numpy as np
>>> import dipy.tracking.learning as tl
>>> A = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
>>> B = np.array([[1, 0, 0], [2, 0, 0], [3, 0, 0]])
>>> C = np.array([[0, 0, -1], [0, 0, -2], [0, 0, -3]])
>>> bundle1 = [A, B, C]
>>> bundle2 = [B, A]
>>> indices = [0, 1]
>>> arr = tl.detect_corresponding_tracks(indices, bundle1, bundle2)

detect_corresponding_tracks_plus#

dipy.tracking.learning.detect_corresponding_tracks_plus(indices, tracks1, indices2, tracks2)[source]#

Detect corresponding tracks from 1 to 2 where tracks1 & tracks2 are sequences of tracks

Parameters:
indicessequence

of indices of tracks1 that are to be detected in tracks2

tracks1sequence

of tracks as arrays, shape (N1,3) .. (Nm,3)

indices2sequence

of indices of tracks2 in the initial brain

tracks2sequence

of tracks as arrays, shape (M1,3) .. (Mm,3)

Returns:
track2trackarray (N,2) where N is len(indices)

of int showing the correspondence in th following way the first column is the current index of tracks1 the second column is the corresponding index in tracks2

See also

distances.mam_distances

Notes

To find the corresponding tracks we use mam_distances with ‘avg’ option. Then we calculate the argmin of all the calculated distances and return it for every index. (See 3rd column of arr in the example given below.)

Examples

>>> import numpy as np
>>> import dipy.tracking.learning as tl
>>> A = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
>>> B = np.array([[1, 0, 0], [2, 0, 0], [3, 0, 0]])
>>> C = np.array([[0, 0, -1], [0, 0, -2], [0, 0, -3]])
>>> bundle1 = [A, B, C]
>>> bundle2 = [B, A]
>>> indices = [0, 1]
>>> indices2 = indices
>>> arr = tl.detect_corresponding_tracks_plus(indices, bundle1, indices2, bundle2)

LifeSignalMaker#

class dipy.tracking.life.LifeSignalMaker(gtab, *, evals=(0.001, 0, 0), sphere=None)[source]#

Bases: object

A class for generating signals from streamlines in an efficient and speedy manner.

Methods

streamline_signal(streamline)

Approximate the signal for a given streamline

calc_signal

calc_signal(xyz)[source]#
streamline_signal(streamline)[source]#

Approximate the signal for a given streamline

FiberModel#

class dipy.tracking.life.FiberModel(gtab)[source]#

Bases: ReconstModel

A class for representing and solving predictive models based on tractography solutions.

Methods

fit(data, streamline, affine, *[, evals, sphere])

Fit the LiFE FiberModel for data and a set of streamlines associated with this data

setup(streamline, affine, *[, evals, sphere])

Set up the necessary components for the LiFE model: the matrix of fiber-contributions to the DWI signal, and the coordinates of voxels for which the equations will be solved

Notes

This is an implementation of the LiFE model described in [1].

References

fit(data, streamline, affine, *, evals=(0.001, 0, 0), sphere=None)[source]#

Fit the LiFE FiberModel for data and a set of streamlines associated with this data

Parameters:
data4D array

Diffusion-weighted data

streamlinelist

A bunch of streamlines

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

evalsarray-like, optional

The eigenvalues of the tensor response function used in constructing the model signal. Default: [0.001, 0, 0]

sphere: `dipy.core.Sphere` instance or False, optional

Whether to approximate (and cache) the signal on a discrete sphere. This may confer a significant speed-up in setting up the problem, but is not as accurate. If False, we use the exact gradients along the streamlines to calculate the matrix, instead of an approximation.

Returns:
FiberFit class instance
setup(streamline, affine, *, evals=(0.001, 0, 0), sphere=None)[source]#

Set up the necessary components for the LiFE model: the matrix of fiber-contributions to the DWI signal, and the coordinates of voxels for which the equations will be solved

Parameters:
streamlinelist

Streamlines, each is an array of shape (n, 3)

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

evalsarray-like (3 items, optional)

The eigenvalues of the canonical tensor used as a response function. Default:[0.001, 0, 0].

sphere: `dipy.core.Sphere` instance, optional

Whether to approximate (and cache) the signal on a discrete sphere. This may confer a significant speed-up in setting up the problem, but is not as accurate. If False, we use the exact gradients along the streamlines to calculate the matrix, instead of an approximation. Defaults to use the 724-vertex symmetric sphere from dipy.data

FiberFit#

class dipy.tracking.life.FiberFit(fiber_model, life_matrix, vox_coords, to_fit, beta, weighted_signal, b0_signal, relative_signal, mean_sig, vox_data, streamline, affine, evals)[source]#

Bases: ReconstFit

A fit of the LiFE model to diffusion data

Methods

predict(*[, gtab, S0])

Predict the signal

predict(*, gtab=None, S0=None)[source]#

Predict the signal

Parameters:
gtabGradientTable

Default: use self.gtab

S0float or array

The non-diffusion-weighted signal in the voxels for which a prediction is made. Default: use self.b0_signal

Returns:
predictionndarray of shape (voxels, bvecs)

An array with a prediction of the signal in each voxel/direction

gradient#

dipy.tracking.life.gradient(f)[source]#

Return the gradient of an N-dimensional array.

The gradient is computed using central differences in the interior and first differences at the boundaries. The returned gradient hence has the same shape as the input array.

Parameters:
farray_like

An N-dimensional array containing samples of a scalar function.

Returns:
gradientndarray

N arrays of the same shape as f giving the derivative of f with respect to each dimension.

Notes

This is a simplified implementation of gradient that is part of numpy 1.8. In order to mitigate the effects of changes added to this implementation in version 1.9 of numpy, we include this implementation here.

Examples

>>> x = np.array([1, 2, 4, 7, 11, 16], dtype=float)
>>> gradient(x)
array([ 1. ,  1.5,  2.5,  3.5,  4.5,  5. ])
>>> gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float))
[array([[ 2.,  2., -1.],
       [ 2.,  2., -1.]]), array([[ 1. ,  2.5,  4. ],
       [ 1. ,  1. ,  1. ]])]

streamline_gradients#

dipy.tracking.life.streamline_gradients(streamline)[source]#

Calculate the gradients of the streamline along the spatial dimension

Parameters:
streamlinearray-like of shape (n, 3)

The 3d coordinates of a single streamline

Returns:
Array of shape (3, n): Spatial gradients along the length of the
streamline.

grad_tensor#

dipy.tracking.life.grad_tensor(grad, evals)[source]#

Calculate the 3 by 3 tensor for a given spatial gradient, given a canonical tensor shape (also as a 3 by 3), pointing at [1,0,0]

Parameters:
grad1d array of shape (3,)

The spatial gradient (e.g between two nodes of a streamline).

evals: 1d array of shape (3,)

The eigenvalues of a canonical tensor to be used as a response function.

streamline_tensors#

dipy.tracking.life.streamline_tensors(streamline, *, evals=(0.001, 0, 0))[source]#

The tensors generated by this fiber.

Parameters:
streamlinearray-like of shape (n, 3)

The 3d coordinates of a single streamline

evalsiterable with three entries, optional

The estimated eigenvalues of a single fiber tensor.

Returns:
An n_nodes by 3 by 3 array with the tensor for each node in the fiber.

Notes

Estimates of the radial/axial diffusivities may rely on empirical measurements (for example, the AD in the Corpus Callosum), or may be based on a biophysical model of some kind.

streamline_signal#

dipy.tracking.life.streamline_signal(streamline, gtab, *, evals=(0.001, 0, 0))[source]#

The signal from a single streamline estimate along each of its nodes.

Parameters:
streamlinea single streamline

Streamline data.

gtabGradientTable class instance

Gradient table.

evalsarray-like of length 3, optional

The eigenvalues of the canonical tensor used as an estimate of the signal generated by each node of the streamline.

voxel2streamline#

dipy.tracking.life.voxel2streamline(streamline, affine, *, unique_idx=None)[source]#

Maps voxels to streamlines and streamlines to voxels, for setting up the LiFE equations matrix

Parameters:
streamlinelist

A collection of streamlines, each n by 3, with n being the number of nodes in the fiber.

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

unique_idxarray, optional.

The unique indices in the streamlines

Returns:
v2f, v2fntuple of dicts
The first dict in the tuple answers the question: Given a voxel (from
the unique indices in this model), which fibers pass through it?
The second answers the question: Given a streamline, for each voxel that
this streamline passes through, which nodes of that streamline are in that
voxel?

LocalTracking#

class dipy.tracking.local_tracking.LocalTracking(direction_getter, stopping_criterion, seeds, affine, step_size, *, max_cross=None, maxlen=500, minlen=2, fixedstep=True, return_all=True, random_seed=None, save_seeds=False, unidirectional=False, randomize_forward_direction=False, initial_directions=None)[source]#

Bases: object

ParticleFilteringTracking#

class dipy.tracking.local_tracking.ParticleFilteringTracking(direction_getter, stopping_criterion, seeds, affine, step_size, *, max_cross=None, maxlen=500, minlen=2, pft_back_tracking_dist=2, pft_front_tracking_dist=1, pft_max_trial=20, particle_count=15, return_all=True, random_seed=None, save_seeds=False, min_wm_pve_before_stopping=0, unidirectional=False, randomize_forward_direction=False, initial_directions=None)[source]#

Bases: LocalTracking

random_coordinates_from_surface#

dipy.tracking.mesh.random_coordinates_from_surface(nb_triangles, nb_seed, *, triangles_mask=None, triangles_weight=None, rand_gen=None)[source]#

Generate random triangles_indices and trilinear_coord

Triangles_indices probability are weighted by triangles_weight,

for each triangles inside the given triangles_mask

Parameters:
nb_trianglesint (n)

The amount of triangles in the mesh

nb_seedint

The number of random indices and coordinates generated.

triangles_mask[n] numpy array

Specifies which triangles should be chosen (or not)

triangles_weight[n] numpy array

Specifies the weight/probability of choosing each triangle

rand_genint

The seed for the random seed generator (numpy.random.seed).

Returns:
triangles_idx: [s] array

Randomly chosen triangles_indices

trilin_coord: [s,3] array

Randomly chosen trilinear_coordinates

See also

seeds_from_surface_coordinates, random_seeds_from_mask

seeds_from_surface_coordinates#

dipy.tracking.mesh.seeds_from_surface_coordinates(triangles, vts_values, triangles_idx, trilinear_coord)[source]#

Compute points from triangles_indices and trilinear_coord

Parameters:
triangles[n, 3] -> m array

A list of triangles from a mesh

vts_values[m, .] array

List of values to interpolates from coordinates along vertices, (vertices, vertices_normal, vertices_colors …)

triangles_idx[s] array

Specifies which triangles should be chosen (or not)

trilinear_coord[s, 3] array

Specifies the weight/probability of choosing each triangle

Returns:
pts[s, …] array

Interpolated values of vertices with triangles_idx and trilinear_coord

triangles_area#

dipy.tracking.mesh.triangles_area(triangles, vts)[source]#

Compute the local area of each triangle

Parameters:
triangles[n, 3] -> m array

A list of triangles from a mesh

vts[m, .] array

List of vertices

Returns:
triangles_area[m] array

List of area for each triangle in the mesh

vertices_to_triangles_values#

dipy.tracking.mesh.vertices_to_triangles_values(triangles, vts_values)[source]#

Change from values per vertex to values per triangle

Parameters:
triangles[n, 3] -> m array

A list of triangles from a mesh

vts_values[m, .] array

List of values to interpolates from coordinates along vertices, (vertices, vertices_normal, vertices_colors …)

Returns:
triangles_values[m] array

List of values for each triangle in the mesh

winding#

dipy.tracking.metrics.winding(xyz)[source]#

Total turning angle projected.

Project space curve to best fitting plane. Calculate the cumulative signed angle between each line segment and the previous one.

Parameters:
xyzarray-like shape (N,3)

Array representing x,y,z of N points in a track.

Returns:
ascalar

Total turning angle in degrees.

length#

dipy.tracking.metrics.length(xyz, *, along=False)[source]#

Euclidean length of track line

This will give length in mm if tracks are expressed in world coordinates.

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a track

alongbool, optional

If True, return array giving cumulative length along track, otherwise (default) return scalar giving total length.

Returns:
Lscalar or array shape (N-1,)

scalar in case of along == False, giving total length, array if along == True, giving cumulative lengths.

Examples

>>> from dipy.tracking.metrics import length
>>> xyz = np.array([[1,1,1],[2,3,4],[0,0,0]])
>>> expected_lens = np.sqrt([1+2**2+3**2, 2**2+3**2+4**2])
>>> length(xyz) == expected_lens.sum()
True
>>> len_along = length(xyz, along=True)
>>> np.allclose(len_along, expected_lens.cumsum())
True
>>> length([])
0
>>> length([[1, 2, 3]])
0
>>> length([], along=True)
array([0])

bytes#

dipy.tracking.metrics.bytes(xyz)[source]#

Size of track in bytes.

Parameters:
xyzarray-like shape (N,3)

Array representing x,y,z of N points in a track.

Returns:
bint

Number of bytes.

midpoint#

dipy.tracking.metrics.midpoint(xyz)[source]#

Midpoint of track

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a track

Returns:
mparray shape (3,)

Middle point of line, such that, if L is the line length then np is the point such that the length xyz[0] to mp and from mp to xyz[-1] is L/2. If the middle point is not a point in xyz, then we take the interpolation between the two nearest xyz points. If xyz is empty, return a ValueError

Examples

>>> from dipy.tracking.metrics import midpoint
>>> midpoint([])
Traceback (most recent call last):
   ...
ValueError: xyz array cannot be empty
>>> midpoint([[1, 2, 3]])
array([1, 2, 3])
>>> xyz = np.array([[1,1,1],[2,3,4]])
>>> midpoint(xyz)
array([ 1.5,  2. ,  2.5])
>>> xyz = np.array([[0,0,0],[1,1,1],[2,2,2]])
>>> midpoint(xyz)
array([ 1.,  1.,  1.])
>>> xyz = np.array([[0,0,0],[1,0,0],[3,0,0]])
>>> midpoint(xyz)
array([ 1.5,  0. ,  0. ])
>>> xyz = np.array([[0,9,7],[1,9,7],[3,9,7]])
>>> midpoint(xyz)
array([ 1.5,  9. ,  7. ])

center_of_mass#

dipy.tracking.metrics.center_of_mass(xyz)[source]#

Center of mass of streamline

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a track

Returns:
comarray shape (3,)

center of mass of streamline

Examples

>>> from dipy.tracking.metrics import center_of_mass
>>> center_of_mass([])
Traceback (most recent call last):
   ...
ValueError: xyz array cannot be empty
>>> center_of_mass([[1,1,1]])
array([ 1.,  1.,  1.])
>>> xyz = np.array([[0,0,0],[1,1,1],[2,2,2]])
>>> center_of_mass(xyz)
array([ 1.,  1.,  1.])

magn#

dipy.tracking.metrics.magn(xyz, *, n=1)[source]#

magnitude of vector

frenet_serret#

dipy.tracking.metrics.frenet_serret(xyz)[source]#

Frenet-Serret Space Curve Invariants

Calculates the 3 vector and 2 scalar invariants of a space curve defined by vectors r = (x,y,z). If z is omitted (i.e. the array xyz has shape (N,2)), then the curve is only 2D (planar), but the equations are still valid.

Similar to https://www.mathworks.com/matlabcentral/fileexchange/11169-frenet

In the following equations the prime (\('\)) indicates differentiation with respect to the parameter \(s\) of a parametrised curve \(\mathbf{r}(s)\).

  • \(\mathbf{T}=\mathbf{r'}/|\mathbf{r'}|\qquad\) (Tangent vector)}

  • \(\mathbf{N}=\mathbf{T'}/|\mathbf{T'}|\qquad\) (Normal vector)

  • \(\mathbf{B}=\mathbf{T}\times\mathbf{N}\qquad\) (Binormal vector)

  • \(\kappa=|\mathbf{T'}|\qquad\) (Curvature)

  • \(\mathrm{\tau}=-\mathbf{B'}\cdot\mathbf{N}\) (Torsion)

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a track

Returns:
Tarray shape (N,3)

array representing the tangent of the curve xyz

Narray shape (N,3)

array representing the normal of the curve xyz

Barray shape (N,3)

array representing the binormal of the curve xyz

karray shape (N,1)

array representing the curvature of the curve xyz

tarray shape (N,1)

array representing the torsion of the curve xyz

Examples

Create a helix and calculate its tangent, normal, binormal, curvature and torsion

>>> from dipy.tracking import metrics as tm
>>> import numpy as np
>>> theta = 2*np.pi*np.linspace(0,2,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=theta/(2*np.pi)
>>> xyz=np.vstack((x,y,z)).T
>>> T,N,B,k,t=tm.frenet_serret(xyz)

mean_curvature#

dipy.tracking.metrics.mean_curvature(xyz)[source]#

Calculates the mean curvature of a curve

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a curve

Returns:
mfloat

Mean curvature.

Examples

Create a straight line and a semi-circle and print their mean curvatures

>>> from dipy.tracking import metrics as tm
>>> import numpy as np
>>> x=np.linspace(0,1,100)
>>> y=0*x
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> m=tm.mean_curvature(xyz) #mean curvature straight line
>>> theta=np.pi*np.linspace(0,1,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> _= tm.mean_curvature(xyz) #mean curvature for semi-circle

mean_orientation#

dipy.tracking.metrics.mean_orientation(xyz)[source]#

Calculates the mean orientation of a curve

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a curve

Returns:
mfloat

Mean orientation.

generate_combinations#

dipy.tracking.metrics.generate_combinations(items, n)[source]#

Combine sets of size n from items

Parameters:
itemssequence
nint
Returns:
iciterator

Examples

>>> from dipy.tracking.metrics import generate_combinations
>>> ic=generate_combinations(range(3),2)
>>> for i in ic: print(i)
[0, 1]
[0, 2]
[1, 2]

longest_track_bundle#

dipy.tracking.metrics.longest_track_bundle(bundle, *, sort=False)[source]#

Return longest track or length sorted track indices in bundle

If sort == True, return the indices of the sorted tracks in the bundle, otherwise return the longest track.

Parameters:
bundlesequence

of tracks as arrays, shape (N1,3) … (Nm,3)

sortbool, optional

If False (default) return longest track. If True, return length sorted indices for tracks in bundle

Returns:
longest_or_indicesarray

longest track - shape (N,3) - (if sort is False), or indices of length sorted tracks (if sort is True)

Examples

>>> from dipy.tracking.metrics import longest_track_bundle
>>> import numpy as np
>>> bundle = [np.array([[0,0,0],[2,2,2]]),np.array([[0,0,0],[4,4,4]])]
>>> longest_track_bundle(bundle)
array([[0, 0, 0],
       [4, 4, 4]])
>>> longest_track_bundle(bundle, sort=True) 
array([0, 1]...)

intersect_sphere#

dipy.tracking.metrics.intersect_sphere(xyz, center, radius)[source]#

If any segment of the track is intersecting with a sphere of specific center and radius return True otherwise False

Parameters:
xyzarray, shape (N,3)

representing x,y,z of the N points of the track

centerarray, shape (3,)

center of the sphere

radiusfloat

radius of the sphere

Returns:
tf{True, False}

True if track xyz intersects sphere

>>> from dipy.tracking.metrics import intersect_sphere
    ..
>>> line=np.array(([0,0,0],[1,1,1],[2,2,2]))
    ..
>>> sph_cent=np.array([1,1,1])
    ..
>>> sph_radius = 1
    ..
>>> intersect_sphere(line,sph_cent,sph_radius)
    ..
True

Notes

The ray to sphere intersection method used here is similar with https://paulbourke.net/geometry/circlesphere/ https://paulbourke.net/geometry/circlesphere/source.cpp we just applied it for every segment neglecting the intersections where the intersecting points are not inside the segment

inside_sphere#

dipy.tracking.metrics.inside_sphere(xyz, center, radius)[source]#

If any point of the track is inside a sphere of a specified center and radius return True otherwise False. Mathematically this can be simply described by \(|x-c|\le r\) where \(x\) a point \(c\) the center of the sphere and \(r\) the radius of the sphere.

Parameters:
xyzarray, shape (N,3)

representing x,y,z of the N points of the track

centerarray, shape (3,)

center of the sphere

radiusfloat

radius of the sphere

Returns:
tf{True,False}

Whether point is inside sphere.

Examples

>>> from dipy.tracking.metrics import inside_sphere
>>> line=np.array(([0,0,0],[1,1,1],[2,2,2]))
>>> sph_cent=np.array([1,1,1])
>>> sph_radius = 1
>>> inside_sphere(line,sph_cent,sph_radius)
True

inside_sphere_points#

dipy.tracking.metrics.inside_sphere_points(xyz, center, radius)[source]#

If a track intersects with a sphere of a specified center and radius return the points that are inside the sphere otherwise False. Mathematically this can be simply described by \(|x-c| \le r\) where \(x\) a point \(c\) the center of the sphere and \(r\) the radius of the sphere.

Parameters:
xyzarray, shape (N,3)

representing x,y,z of the N points of the track

centerarray, shape (3,)

center of the sphere

radiusfloat

radius of the sphere

Returns:
xyznarray, shape(M,3)

array representing x,y,z of the M points inside the sphere

Examples

>>> from dipy.tracking.metrics import inside_sphere_points
>>> line=np.array(([0,0,0],[1,1,1],[2,2,2]))
>>> sph_cent=np.array([1,1,1])
>>> sph_radius = 1
>>> inside_sphere_points(line,sph_cent,sph_radius)
array([[1, 1, 1]])

spline#

dipy.tracking.metrics.spline(xyz, *, s=3, k=2, nest=-1)[source]#

Generate B-splines as documented in https://scipy-cookbook.readthedocs.io/items/Interpolation.html

The scipy.interpolate packages wraps the netlib FITPACK routines (Dierckx) for calculating smoothing splines for various kinds of data and geometries. Although the data is evenly spaced in this example, it need not be so to use this routine.

Parameters:
xyzarray, shape (N,3)

array representing x,y,z of N points in 3d space

sfloat, optional

A smoothing condition. The amount of smoothness is determined by satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x) is the smoothed interpolation of (x,y). The user can use s to control the tradeoff between closeness and smoothness of fit. Larger satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x) is the smoothed interpolation of (x,y). The user can use s to control the tradeoff between closeness and smoothness of fit. Larger s means more smoothing while smaller values of s indicate less smoothing. Recommended values of s depend on the weights, w. If the weights represent the inverse of the standard-deviation of y, then a: good s value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is the number of datapoints in x, y, and w.

kint, optional

Degree of the spline. Cubic splines are recommended. Even values of k should be avoided especially with a small s-value. for the same set of data. If task=-1 find the weighted least square spline for a given set of knots, t.

nestNone or int, optional

An over-estimate of the total number of knots of the spline to help in determining the storage space. None results in value m+2*k. -1 results in m+k+1. Always large enough is nest=m+k+1. Default is -1.

Returns:
xyznarray, shape (M,3)

array representing x,y,z of the M points inside the sphere

See also

scipy.interpolate.splprep
scipy.interpolate.splev

Examples

>>> import numpy as np
>>> t=np.linspace(0,1.75*2*np.pi,100)# make ascending spiral in 3-space
>>> x = np.sin(t)
>>> y = np.cos(t)
>>> z = t
>>> x+= np.random.normal(scale=0.1, size=x.shape) # add noise
>>> y+= np.random.normal(scale=0.1, size=y.shape)
>>> z+= np.random.normal(scale=0.1, size=z.shape)
>>> xyz=np.vstack((x,y,z)).T
>>> xyzn=spline(xyz,s=3,k=2,nest=-1)
>>> len(xyzn) > len(xyz)
True

startpoint#

dipy.tracking.metrics.startpoint(xyz)[source]#

First point of the track

Parameters:
xyzarray, shape(N,3)

Track.

Returns:
sparray, shape(3,)

First track point.

Examples

>>> from dipy.tracking.metrics import startpoint
>>> import numpy as np
>>> theta=np.pi*np.linspace(0,1,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> sp=startpoint(xyz)
>>> sp.any()==xyz[0].any()
True

endpoint#

dipy.tracking.metrics.endpoint(xyz)[source]#
Parameters:
xyzarray, shape(N,3)

Track.

Returns:
eparray, shape(3,)

First track point.

Examples

>>> from dipy.tracking.metrics import endpoint
>>> import numpy as np
>>> theta=np.pi*np.linspace(0,1,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> ep=endpoint(xyz)
>>> ep.any()==xyz[-1].any()
True

arbitrarypoint#

dipy.tracking.metrics.arbitrarypoint(xyz, distance)[source]#

Select an arbitrary point along distance on the track (curve)

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a track

distancefloat

float representing distance travelled from the xyz[0] point of the curve along the curve.

Returns:
aparray shape (3,)

Arbitrary point of line, such that, if the arbitrary point is not a point in xyz, then we take the interpolation between the two nearest xyz points. If xyz is empty, return a ValueError

Examples

>>> import numpy as np
>>> from dipy.tracking.metrics import arbitrarypoint, length
>>> theta=np.pi*np.linspace(0,1,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> ap=arbitrarypoint(xyz,length(xyz)/3)

principal_components#

dipy.tracking.metrics.principal_components(xyz)[source]#

We use PCA to calculate the 3 principal directions for a track

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a track

Returns:
vaarray_like

eigenvalues

vearray_like

eigenvectors

Examples

>>> import numpy as np
>>> from dipy.tracking.metrics import principal_components
>>> theta=np.pi*np.linspace(0,1,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> va, ve = principal_components(xyz)
>>> np.allclose(va, [0.51010101, 0.09883545, 0])
True

midpoint2point#

dipy.tracking.metrics.midpoint2point(xyz, p)[source]#

Calculate distance from midpoint of a curve to arbitrary point p

Parameters:
xyzarray-like shape (N,3)

array representing x,y,z of N points in a track

parray shape (3,)

array representing an arbitrary point with x,y,z coordinates in space.

Returns:
dfloat

a float number representing Euclidean distance

Examples

>>> import numpy as np
>>> from dipy.tracking.metrics import midpoint2point, midpoint
>>> theta=np.pi*np.linspace(0,1,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> dist=midpoint2point(xyz,np.array([0,0,0]))

unlist_streamlines#

dipy.tracking.streamline.unlist_streamlines(streamlines)[source]#

Return the streamlines not as a list but as an array and an offset

Parameters:
streamlines: sequence

Streamlines.

Returns:
pointsarray

Streamlines’ points.

offsetsarray

Streamlines’ offsets.

relist_streamlines#

dipy.tracking.streamline.relist_streamlines(points, offsets)[source]#

Given a representation of a set of streamlines as a large array and an offsets array return the streamlines as a list of shorter arrays.

Parameters:
pointsarray

Streamlines’ points.

offsetsarray

Streamlines’ offsets.

Returns:
streamlines: sequence

Streamlines.

center_streamlines#

dipy.tracking.streamline.center_streamlines(streamlines)[source]#

Move streamlines to the origin

Parameters:
streamlineslist

List of 2D ndarrays of shape[-1]==3

Returns:
new_streamlineslist

List of 2D ndarrays of shape[-1]==3

inv_shiftndarray

Translation in x,y,z to go back in the initial position

deform_streamlines#

dipy.tracking.streamline.deform_streamlines(streamlines, deform_field, stream_to_current_grid, current_grid_to_world, stream_to_ref_grid, ref_grid_to_world)[source]#

Apply deformation field to streamlines

Parameters:
streamlineslist

List of 2D ndarrays of shape[-1]==3

deform_field4D numpy array

x,y,z displacements stored in volume, shape[-1]==3

stream_to_current_gridarray, (4, 4)

transform matrix voxmm space to original grid space

current_grid_to_worldarray (4, 4)

transform matrix original grid space to world coordinates

stream_to_ref_gridarray (4, 4)

transform matrix voxmm space to new grid space

ref_grid_to_worldarray(4, 4)

transform matrix new grid space to world coordinates

Returns:
new_streamlineslist

List of the transformed 2D ndarrays of shape[-1]==3

transform_streamlines#

dipy.tracking.streamline.transform_streamlines(streamlines, mat, *, in_place=False)[source]#

Apply affine transformation to streamlines

Parameters:
streamlinesStreamlines

Streamlines object

matarray, (4, 4)

transformation matrix

in_placebool

If True then change data in place. Be careful changes input streamlines.

Returns:
new_streamlinesStreamlines

Sequence transformed 2D ndarrays of shape[-1]==3

select_random_set_of_streamlines#

dipy.tracking.streamline.select_random_set_of_streamlines(streamlines, select, *, rng=None)[source]#

Select a random set of streamlines

Parameters:
streamlinesStreamlines

Object of 2D ndarrays of shape[-1]==3

selectint

Number of streamlines to select. If there are less streamlines than select then select=len(streamlines).

rngnp.random.Generator

Default None.

Returns:
selected_streamlineslist

Notes

The same streamline will not be selected twice.

select_by_rois#

dipy.tracking.streamline.select_by_rois(streamlines, affine, rois, include, *, mode=None, tol=None)[source]#

Select streamlines based on logical relations with several regions of interest (ROIs). For example, select streamlines that pass near ROI1, but only if they do not pass near ROI2.

Parameters:
streamlineslist

A list of candidate streamlines for selection

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

roislist or ndarray

A list of 3D arrays, each with shape (x, y, z) corresponding to the shape of the brain volume, or a 4D array with shape (n_rois, x, y, z). Non-zeros in each volume are considered to be within the region

includearray or list

A list or 1D array of boolean values marking inclusion or exclusion criteria. If a streamline is near any of the inclusion ROIs, it should evaluate to True, unless it is also near any of the exclusion ROIs.

modestring, optional

One of {“any”, “all”, “either_end”, “both_end”}, where a streamline is associated with an ROI if:

“any” : any point is within tol from ROI. Default.

“all” : all points are within tol from ROI.

“either_end” : either of the end-points is within tol from ROI

“both_end” : both end points are within tol from ROI.

tolfloat

Distance (in the units of the streamlines, usually mm). If any coordinate in the streamline is within this distance from the center of any voxel in the ROI, the filtering criterion is set to True for this streamline, otherwise False. Defaults to the distance between the center of each voxel and the corner of the voxel.

Returns:
generator

Generates the streamlines to be included based on these criteria.

Notes

The only operation currently possible is “(A or B or …) and not (X or Y or …)”, where A, B are inclusion regions and X, Y are exclusion regions.

Examples

>>> streamlines = [np.array([[0, 0., 0.9],
...                          [1.9, 0., 0.]]),
...                np.array([[0., 0., 0],
...                          [0, 1., 1.],
...                          [0, 2., 2.]]),
...                np.array([[2, 2, 2],
...                          [3, 3, 3]])]
>>> mask1 = np.zeros((4, 4, 4), dtype=bool)
>>> mask2 = np.zeros_like(mask1)
>>> mask1[0, 0, 0] = True
>>> mask2[1, 0, 0] = True
>>> selection = select_by_rois(streamlines, np.eye(4), [mask1, mask2],
...                            [True, True],
...                            tol=1)
>>> list(selection) # The result is a generator
[array([[ 0. ,  0. ,  0.9],
       [ 1.9,  0. ,  0. ]]), array([[ 0.,  0.,  0.],
       [ 0.,  1.,  1.],
       [ 0.,  2.,  2.]])]
>>> selection = select_by_rois(streamlines, np.eye(4), [mask1, mask2],
...                            [True, False],
...                            tol=0.87)
>>> list(selection)
[array([[ 0.,  0.,  0.],
       [ 0.,  1.,  1.],
       [ 0.,  2.,  2.]])]
>>> selection = select_by_rois(streamlines, np.eye(4), [mask1, mask2],
...                            [True, True],
...                            mode="both_end",
...                            tol=1.0)
>>> list(selection)
[array([[ 0. ,  0. ,  0.9],
       [ 1.9,  0. ,  0. ]])]
>>> mask2[0, 2, 2] = True
>>> selection = select_by_rois(streamlines, np.eye(4), [mask1, mask2],
...                            [True, True],
...                            mode="both_end",
...                            tol=1.0)
>>> list(selection)
[array([[ 0. ,  0. ,  0.9],
       [ 1.9,  0. ,  0. ]]), array([[ 0.,  0.,  0.],
       [ 0.,  1.,  1.],
       [ 0.,  2.,  2.]])]

cluster_confidence#

dipy.tracking.streamline.cluster_confidence(streamlines, *, max_mdf=5, subsample=12, power=1, override=False)[source]#

Computes the cluster confidence index (cci), which is an estimation of the support a set of streamlines gives to a particular pathway.

Ex: A single streamline with no others in the dataset following a similar pathway has a low cci. A streamline in a bundle of 100 streamlines that follow similar pathways has a high cci.

See [2] (based on the streamline MDF distance from Garyfallidis et al.[3]).

Parameters:
streamlineslist of 2D (N, 3) arrays

A sequence of streamlines of length N (# streamlines)

max_mdfint

The maximum MDF distance (mm) that will be considered a “supporting” streamline and included in cci calculation

subsample: int

The number of points that are considered for each streamline in the calculation. To save on calculation time, each streamline is subsampled to subsampleN points.

power: int

The power to which the MDF distance for each streamline will be raised to determine how much it contributes to the cci. High values of power make the contribution value degrade much faster. E.g., a streamline with 5mm MDF similarity contributes 1/5 to the cci if power is 1, but only contributes 1/5^2 = 1/25 if power is 2.

override: bool, False by default

override means that the cci calculation will still occur even though there are short streamlines in the dataset that may alter expected behaviour.

Returns:
Returns an array of CCI scores

References

orient_by_rois#

dipy.tracking.streamline.orient_by_rois(streamlines, affine, roi1, roi2, *, in_place=False, as_generator=False)[source]#

Orient a set of streamlines according to a pair of ROIs

Parameters:
streamlineslist or generator

List or generator of 2d arrays of 3d coordinates. Each array contains the xyz coordinates of a single streamline.

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

roi1, roi2ndarray

Binary masks designating the location of the regions of interest, or coordinate arrays (n-by-3 array with ROI coordinate in each row).

in_placebool

Whether to make the change in-place in the original list (and return a reference to the list), or to make a copy of the list and return this copy, with the relevant streamlines reoriented.

as_generatorbool

Whether to return a generator as output.

Returns:
streamlineslist or generator

The same 3D arrays as a list or generator, but reoriented with respect to the ROIs

Examples

>>> streamlines = [np.array([[0, 0., 0],
...                          [1, 0., 0.],
...                          [2, 0., 0.]]),
...                np.array([[2, 0., 0.],
...                          [1, 0., 0],
...                          [0, 0,  0.]])]
>>> roi1 = np.zeros((4, 4, 4), dtype=bool)
>>> roi2 = np.zeros_like(roi1)
>>> roi1[0, 0, 0] = True
>>> roi2[1, 0, 0] = True
>>> orient_by_rois(streamlines, np.eye(4), roi1, roi2)
[array([[ 0.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 2.,  0.,  0.]]), array([[ 0.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 2.,  0.,  0.]])]

orient_by_streamline#

dipy.tracking.streamline.orient_by_streamline(streamlines, standard, *, n_points=12, in_place=False, as_generator=False)[source]#

Orient a bundle of streamlines to a standard streamline.

Parameters:
streamlinesStreamlines, list

The input streamlines to orient.

standardStreamlines, list, or ndarrray

This provides the standard orientation according to which the streamlines in the provided bundle should be reoriented.

n_points: int, optional

The number of samples to apply to each of the streamlines.

in_placebool

Whether to make the change in-place in the original input (and return a reference), or to make a copy of the list and return this copy, with the relevant streamlines reoriented.

as_generatorbool

Whether to return a generator as output.

Returns:
Streamlineswith each individual array oriented to be as similar as

possible to the standard.

values_from_volume#

dipy.tracking.streamline.values_from_volume(data, streamlines, affine)[source]#

Extract values of a scalar/vector along each streamline from a volume.

Parameters:
data3D or 4D array

Scalar (for 3D) and vector (for 4D) values to be extracted. For 4D data, interpolation will be done on the 3 spatial dimensions in each volume.

streamlinesndarray or list

If array, of shape (n_streamlines, n_nodes, 3) If list, len(n_streamlines) with (n_nodes, 3) array in each element of the list.

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

Returns:
array or list (depending on the input)values interpolate to each

coordinate along the length of each streamline.

Notes

Values are extracted from the image based on the 3D coordinates of the nodes that comprise the points in the streamline, without any interpolation into segments between the nodes. Using this function with streamlines that have been resampled into a very small number of nodes will result in very few values.

nbytes#

dipy.tracking.streamline.nbytes(streamlines)[source]#

generic_tracking#

dipy.tracking.tracker.generic_tracking(seed_positions, seed_directions, sc, params, *, affine=None, sh=None, peaks=None, sf=None, sphere=None, basis_type=None, legacy=True, nbr_threads=0, seed_buffer_fraction=1.0, save_seeds=False)[source]#

probabilistic_tracking#

dipy.tracking.tracker.probabilistic_tracking(seed_positions, sc, affine, *, seed_directions=None, sh=None, peaks=None, sf=None, min_len=2, max_len=500, step_size=0.2, voxel_size=None, max_angle=20, pmf_threshold=0.1, sphere=None, basis_type=None, legacy=True, nbr_threads=0, random_seed=0, seed_buffer_fraction=1.0, return_all=True, save_seeds=False)[source]#

Probabilistic tracking algorithm.

Parameters:
seed_positionsndarray

Seed positions in world space.

scStoppingCriterion

Stopping criterion.

affinendarray

Affine matrix.

seed_directionsndarray, optional

Seed directions.

shndarray, optional

Spherical Harmonics (SH).

peaksndarray, optional

Peaks array.

sfndarray, optional

Spherical Function (SF).

min_lenint, optional

Minimum length (Nb points) of the streamlines.

max_lenint, optional

Maximum length (Nb points) of the streamlines.

step_sizefloat, optional

Step size of the tracking.

voxel_sizendarray, optional

Voxel size.

max_anglefloat, optional

Maximum angle.

pmf_thresholdfloat, optional

PMF threshold.

sphereSphere, optional

Sphere.

basis_typename of basis

The basis that shcoeff are associated with. dipy.reconst.shm.real_sh_descoteaux is used by default.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

nbr_threads: int, optional

Number of threads to use for the processing. By default, all available threads will be used.

random_seed: int, optional

Seed for the random number generator, must be >= 0. A value of greater than 0 will all produce the same streamline trajectory for a given seed coordinate. A value of 0 may produces various streamline tracjectories for a given seed coordinate.

seed_buffer_fraction: float, optional

Fraction of the seed buffer to use. A value of 1.0 will use the entire seed buffer. A value of 0.5 will use half of the seed buffer then the other half. a way to reduce memory usage.

return_all: bool, optional

True to return all the streamlines, False to return only the streamlines that reached the stopping criterion.

save_seeds: bool, optional

True to return the seeds with the associated streamline.

Returns:
Tractogram

deterministic_tracking#

dipy.tracking.tracker.deterministic_tracking(seed_positions, sc, affine, *, seed_directions=None, sh=None, peaks=None, sf=None, min_len=2, max_len=500, step_size=0.2, voxel_size=None, max_angle=20, pmf_threshold=0.1, sphere=None, basis_type=None, legacy=True, nbr_threads=0, random_seed=0, seed_buffer_fraction=1.0, return_all=True, save_seeds=False)[source]#

Deterministic tracking algorithm.

Parameters:
seed_positionsndarray

Seed positions in world space.

scStoppingCriterion

Stopping criterion.

affinendarray

Affine matrix.

seed_directionsndarray, optional

Seed directions.

shndarray, optional

Spherical Harmonics (SH).

peaksndarray, optional

Peaks array.

sfndarray, optional

Spherical Function (SF).

min_lenint, optional

Minimum length (nb points) of the streamlines.

max_lenint, optional

Maximum length (nb points) of the streamlines.

step_sizefloat, optional

Step size of the tracking.

voxel_sizendarray, optional

Voxel size.

max_anglefloat, optional

Maximum angle.

pmf_thresholdfloat, optional

PMF threshold.

sphereSphere, optional

Sphere.

basis_typename of basis

The basis that shcoeff are associated with. dipy.reconst.shm.real_sh_descoteaux is used by default.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

nbr_threads: int, optional

Number of threads to use for the processing. By default, all available threads will be used.

random_seed: int, optional

Seed for the random number generator, must be >= 0. A value of greater than 0 will all produce the same streamline trajectory for a given seed coordinate. A value of 0 may produces various streamline tracjectories for a given seed coordinate.

seed_buffer_fraction: float, optional

Fraction of the seed buffer to use. A value of 1.0 will use the entire seed buffer. A value of 0.5 will use half of the seed buffer then the other half. a way to reduce memory usage.

return_all: bool, optional

True to return all the streamlines, False to return only the streamlines that reached the stopping criterion.

save_seeds: bool, optional

True to return the seeds with the associated streamline.

Returns:
Tractogram

ptt_tracking#

dipy.tracking.tracker.ptt_tracking(seed_positions, sc, affine, *, seed_directions=None, sh=None, peaks=None, sf=None, min_len=2, max_len=500, step_size=0.5, voxel_size=None, max_angle=10, pmf_threshold=0.1, probe_length=1.5, probe_radius=0, probe_quality=7, probe_count=1, data_support_exponent=1, sphere=None, basis_type=None, legacy=True, nbr_threads=0, random_seed=0, seed_buffer_fraction=1.0, return_all=True, save_seeds=False)[source]#

Parallel Transport Tractography (PTT) tracking algorithm.

Parameters:
seed_positionsndarray

Seed positions in world space.

scStoppingCriterion

Stopping criterion.

affinendarray

Affine matrix.

seed_directionsndarray, optional

Seed directions.

shndarray, optional

Spherical Harmonics (SH) data.

peaksndarray, optional

Peaks array

sfndarray, optional

Spherical Function (SF).

min_lenint, optional

Minimum length of the streamlines.

max_lenint, optional

Maximum length of the streamlines.

step_sizefloat, optional

Step size of the tracking.

voxel_sizendarray, optional

Voxel size.

max_anglefloat, optional

Maximum angle.

pmf_thresholdfloat, optional

PMF threshold.

probe_lengthfloat, optional

Probe length.

probe_radiusfloat, optional

Probe radius.

probe_qualityint, optional

Probe quality.

probe_countint, optional

Probe count.

data_support_exponentint, optional

Data support exponent.

sphereSphere, optional

Sphere.

basis_typename of basis

The basis that shcoeff are associated with. dipy.reconst.shm.real_sh_descoteaux is used by default.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

nbr_threads: int, optional

Number of threads to use for the processing. By default, all available threads will be used.

random_seed: int, optional

Seed for the random number generator, must be >= 0. A value of greater than 0 will all produce the same streamline trajectory for a given seed coordinate. A value of 0 may produces various streamline tracjectories for a given seed coordinate.

seed_buffer_fraction: float, optional

Fraction of the seed buffer to use. A value of 1.0 will use the entire seed buffer. A value of 0.5 will use half of the seed buffer then the other half. a way to reduce memory usage.

return_all: bool, optional

True to return all the streamlines, False to return only the streamlines that reached the stopping criterion.

save_seeds: bool, optional

True to return the seeds with the associated streamline.

Returns
——-
Tractogram

closestpeak_tracking#

dipy.tracking.tracker.closestpeak_tracking(seed_positions, sc, affine, *, seed_directions=None, sh=None, peaks=None, sf=None, min_len=2, max_len=500, step_size=0.5, voxel_size=None, max_angle=60, pmf_threshold=0.1, sphere=None, basis_type=None, legacy=True, nbr_threads=0, random_seed=0, seed_buffer_fraction=1.0, return_all=True, save_seeds=False)[source]#

Closest peak tracking algorithm.

Parameters:
seed_positionsndarray

Seed positions in world space.

scStoppingCriterion

Stopping criterion.

affinendarray

Affine matrix.

seed_directionsndarray, optional

Seed directions.

shndarray, optional

Spherical Harmonics (SH).

peaksndarray, optional

Peaks array.

sfndarray, optional

Spherical Function (SF).

min_lenint, optional

Minimum length (nb points) of the streamlines.

max_lenint, optional

Maximum length (nb points) of the streamlines.

step_sizefloat, optional

Step size of the tracking.

voxel_sizendarray, optional

Voxel size.

max_anglefloat, optional

Maximum angle.

pmf_thresholdfloat, optional

PMF threshold.

sphereSphere, optional

Sphere.

basis_typename of basis

The basis that shcoeff are associated with. dipy.reconst.shm.real_sh_descoteaux is used by default.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

nbr_threads: int, optional

Number of threads to use for the processing. By default, all available threads will be used.

random_seed: int, optional

Seed for the random number generator, must be >= 0. A value of greater than 0 will all produce the same streamline trajectory for a given seed coordinate. A value of 0 may produces various streamline tracjectories for a given seed coordinate.

seed_buffer_fraction: float, optional

Fraction of the seed buffer to use. A value of 1.0 will use the entire seed buffer. A value of 0.5 will use half of the seed buffer then the other half. a way to reduce memory usage.

return_all: bool, optional

True to return all the streamlines, False to return only the streamlines that reached the stopping criterion.

save_seeds: bool, optional

True to return the seeds with the associated streamline.

Returns:
Tractogram

bootstrap_tracking#

dipy.tracking.tracker.bootstrap_tracking(seed_positions, sc, affine, *, seed_directions=None, data=None, model=None, sh=None, peaks=None, sf=None, min_len=2, max_len=500, step_size=0.5, voxel_size=None, max_angle=60, pmf_threshold=0.1, sphere=None, basis_type=None, legacy=True, nbr_threads=0, random_seed=0, seed_buffer_fraction=1.0, return_all=True, save_seeds=False)[source]#

Bootstrap tracking algorithm.

seed_positionsndarray

Seed positions in world space.

scStoppingCriterion

Stopping criterion.

affinendarray

Affine matrix.

seed_directionsndarray, optional

Seed directions.

datandarray, optional

Diffusion data.

modelModel, optional

Reconstruction model.

shndarray, optional

Spherical Harmonics (SH).

peaksndarray, optional

Peaks array.

sfndarray, optional

Spherical Function (SF).

min_lenint, optional

Minimum length (nb points) of the streamlines.

max_lenint, optional

Maximum length (nb points) of the streamlines.

step_sizefloat, optional

Step size of the tracking.

voxel_sizendarray, optional

Voxel size.

max_anglefloat, optional

Maximum angle.

pmf_thresholdfloat, optional

PMF threshold.

sphereSphere, optional

Sphere.

basis_typename of basis

The basis that shcoeff are associated with. dipy.reconst.shm.real_sh_descoteaux is used by default.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

nbr_threads: int, optional

Number of threads to use for the processing. By default, all available threads will be used.

random_seed: int, optional

Seed for the random number generator, must be >= 0. A value of greater than 0 will all produce the same streamline trajectory for a given seed coordinate. A value of 0 may produces various streamline tracjectories for a given seed coordinate.

seed_buffer_fraction: float, optional

Fraction of the seed buffer to use. A value of 1.0 will use the entire seed buffer. A value of 0.5 will use half of the seed buffer then the other half. a way to reduce memory usage.

return_all: bool, optional

True to return all the streamlines, False to return only the streamlines that reached the stopping criterion.

save_seeds: bool, optional

True to return the seeds with the associated streamline.

Returns:
Tractogram

eudx_tracking#

dipy.tracking.tracker.eudx_tracking(seed_positions, sc, affine, *, seed_directions=None, sh=None, peaks=None, sf=None, pam=None, min_len=2, max_len=500, step_size=0.5, voxel_size=None, max_angle=60, pmf_threshold=0.1, sphere=None, basis_type=None, legacy=True, nbr_threads=0, random_seed=0, seed_buffer_fraction=1.0, return_all=True, save_seeds=False)[source]#

EuDX tracking algorithm.

seed_positionsndarray

Seed positions in world space.

scStoppingCriterion

Stopping criterion.

affinendarray

Affine matrix.

seed_directionsndarray, optional

Seed directions.

shndarray, optional

Spherical Harmonics (SH).

peaksndarray, optional

Peaks array.

sfndarray, optional

Spherical Function (SF).

pamPeakAndMetrics, optional

Peaks and Metrics object

min_lenint, optional

Minimum length (nb points) of the streamlines.

max_lenint, optional

Maximum length (nb points) of the streamlines.

step_sizefloat, optional

Step size of the tracking.

voxel_sizendarray, optional

Voxel size.

max_anglefloat, optional

Maximum angle.

pmf_thresholdfloat, optional

PMF threshold.

sphereSphere, optional

Sphere.

basis_typename of basis

The basis that shcoeff are associated with. dipy.reconst.shm.real_sh_descoteaux is used by default.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

nbr_threads: int, optional

Number of threads to use for the processing. By default, all available threads will be used.

random_seed: int, optional

Seed for the random number generator, must be >= 0. A value of greater than 0 will all produce the same streamline trajectory for a given seed coordinate. A value of 0 may produces various streamline tracjectories for a given seed coordinate.

seed_buffer_fraction: float, optional

Fraction of the seed buffer to use. A value of 1.0 will use the entire seed buffer. A value of 0.5 will use half of the seed buffer then the other half. a way to reduce memory usage.

return_all: bool, optional

True to return all the streamlines, False to return only the streamlines that reached the stopping criterion.

save_seeds: bool, optional

True to return the seeds with the associated streamline.

Returns:
Tractogram

pft_tracking#

dipy.tracking.tracker.pft_tracking(seed_positions, sc, affine, *, seed_directions=None, sh=None, peaks=None, sf=None, pam=None, max_cross=None, min_len=2, max_len=500, step_size=0.2, voxel_size=None, max_angle=20, pmf_threshold=0.1, sphere=None, basis_type=None, legacy=True, nbr_threads=0, random_seed=0, seed_buffer_fraction=1.0, return_all=True, pft_back_tracking_dist=2, pft_front_tracking_dist=1, pft_max_trial=20, particle_count=15, save_seeds=False, min_wm_pve_before_stopping=0, unidirectional=False, randomize_forward_direction=False)[source]#

Particle Filtering Tracking (PFT) tracking algorithm.

seed_positionsndarray

Seed positions in world space.

scStoppingCriterion

Stopping criterion.

affinendarray

Affine matrix.

seed_directionsndarray, optional

Seed directions.

shndarray, optional

Spherical Harmonics (SH).

peaksndarray, optional

Peaks array.

sfndarray, optional

Spherical Function (SF).

pamPeakAndMetrics, optional

Peaks and Metrics object.

max_crossint, optional

Maximum number of crossing fibers.

min_lenint, optional

Minimum length (nb points) of the streamlines.

max_lenint, optional

Maximum length (nb points) of the streamlines.

step_sizefloat, optional

Step size of the tracking.

voxel_sizendarray, optional

Voxel size.

max_anglefloat, optional

Maximum angle.

pmf_thresholdfloat, optional

PMF threshold.

sphereSphere, optional

Sphere.

basis_typename of basis

The basis that shcoeff are associated with. dipy.reconst.shm.real_sh_descoteaux is used by default.

legacy: bool, optional

True to use a legacy basis definition for backward compatibility with previous tournier07 and descoteaux07 implementations.

nbr_threads: int, optional

Number of threads to use for the processing. By default, all available threads will be used.

random_seed: int, optional

Seed for the random number generator, must be >= 0. A value of greater than 0 will all produce the same streamline trajectory for a given seed coordinate. A value of 0 may produces various streamline tracjectories for a given seed coordinate.

seed_buffer_fraction: float, optional

Fraction of the seed buffer to use. A value of 1.0 will use the entire seed buffer. A value of 0.5 will use half of the seed buffer then the other half. a way to reduce memory usage.

return_all: bool, optional

True to return all the streamlines, False to return only the streamlines that reached the stopping criterion.

pft_back_tracking_distfloat, optional

Back tracking distance.

pft_front_tracking_distfloat, optional

Front tracking distance.

pft_max_trialint, optional

Maximum number of trials.

particle_countint, optional

Number of particles.

save_seeds: bool, optional

True to return the seeds with the associated streamline.

min_wm_pve_before_stoppingfloat, optional

Minimum white matter partial volume estimation before stopping.

unidirectionalbool, optional

True to use unidirectional tracking.

randomize_forward_directionbool, optional

True to randomize forward direction

Returns:
Tractogram

density_map#

dipy.tracking.utils.density_map(streamlines, affine, vol_dims)[source]#

Count the number of unique streamlines that pass through each voxel.

Parameters:
streamlinesiterable

A sequence of streamlines.

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

vol_dims3 ints

The shape of the volume to be returned containing the streamlines counts

Returns:
image_volumendarray, shape=vol_dims

The number of streamline points in each voxel of volume.

Raises:
IndexError

When the points of the streamlines lie outside of the return volume.

Notes

A streamline can pass through a voxel even if one of the points of the streamline does not lie in the voxel. For example a step from [0,0,0] to [0,0,2] passes through [0,0,1]. Consider subsegmenting the streamlines when the edges of the voxels are smaller than the steps of the streamlines.

connectivity_matrix#

dipy.tracking.utils.connectivity_matrix(streamlines, affine, label_volume, *, inclusive=False, symmetric=True, return_mapping=False, mapping_as_streamlines=False)[source]#

Count the streamlines that start and end at each label pair.

Parameters:
streamlinessequence

A sequence of streamlines.

affinearray_like (4, 4)

The mapping from voxel coordinates to streamline coordinates. The voxel_to_rasmm matrix, typically from a NIFTI file.

label_volumendarray

An image volume with an integer data type, where the intensities in the volume map to anatomical structures.

inclusive: bool

Whether to analyze the entire streamline, as opposed to just the endpoints. False by default.

symmetricbool, True by default

Symmetric means we don’t distinguish between start and end points. If symmetric is True, matrix[i, j] == matrix[j, i].

return_mappingbool, False by default

If True, a mapping is returned which maps matrix indices to streamlines.

mapping_as_streamlinesbool, False by default

If True voxel indices map to lists of streamline objects. Otherwise voxel indices map to lists of integers.

Returns:
matrixndarray

The number of connection between each pair of regions in label_volume.

mappingdefaultdict(list)

mapping[i, j] returns all the streamlines that connect region i to region j. If symmetric is True mapping will only have one key for each start end pair such that if i < j mapping will have key (i, j) but not key (j, i).

ndbincount#

dipy.tracking.utils.ndbincount(x, *, weights=None, shape=None)[source]#

Like bincount, but for nd-indices.

Parameters:
xarray_like (N, M)

M indices to a an Nd-array

weightsarray_like (M,), optional

Weights associated with indices

shapeoptional

the shape of the output

reduce_labels#

dipy.tracking.utils.reduce_labels(label_volume)[source]#

Reduce an array of labels to the integers from 0 to n with smallest possible n.

Examples

>>> labels = np.array([[1, 3, 9],
...                    [1, 3, 8],
...                    [1, 3, 7]])
>>> new_labels, lookup = reduce_labels(labels)
>>> lookup
array([1, 3, 7, 8, 9])
>>> new_labels 
array([[0, 1, 4],
       [0, 1, 3],
       [0, 1, 2]]...)
>>> (lookup[new_labels] == labels).all()
True

subsegment#

dipy.tracking.utils.subsegment(streamlines, max_segment_length)[source]#

Split the segments of the streamlines into small segments.

Replaces each segment of each of the streamlines with the smallest possible number of equally sized smaller segments such that no segment is longer than max_segment_length. Among other things, this can useful for getting streamline counts on a grid that is smaller than the length of the streamline segments.

Parameters:
streamlinessequence of ndarrays

The streamlines to be subsegmented.

max_segment_lengthfloat

The longest allowable segment length.

Returns:
output_streamlinesgenerator

A set of streamlines.

Notes

Segments of 0 length are removed. If unchanged

Examples

>>> streamlines = [np.array([[0,0,0],[2,0,0],[5,0,0]])]
>>> list(subsegment(streamlines, 3.))
[array([[ 0.,  0.,  0.],
       [ 2.,  0.,  0.],
       [ 5.,  0.,  0.]])]
>>> list(subsegment(streamlines, 1))
[array([[ 0.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 2.,  0.,  0.],
       [ 3.,  0.,  0.],
       [ 4.,  0.,  0.],
       [ 5.,  0.,  0.]])]
>>> list(subsegment(streamlines, 1.6))
[array([[ 0. ,  0. ,  0. ],
       [ 1. ,  0. ,  0. ],
       [ 2. ,  0. ,  0. ],
       [ 3.5,  0. ,  0. ],
       [ 5. ,  0. ,  0. ]])]

seeds_from_mask#

dipy.tracking.utils.seeds_from_mask(mask, affine, *, density=(1, 1, 1))[source]#

Create seeds for fiber tracking from a binary mask.

Seeds points are placed evenly distributed in all voxels of mask which are True.

Parameters:
maskbinary 3d array_like

A binary array specifying where to place the seeds for fiber tracking.

affinearray, (4, 4)

The mapping between voxel indices and the point space for seeds. The voxel_to_rasmm matrix, typically from a NIFTI file. A seed point at the center the voxel [i, j, k] will be represented as [x, y, z] where [x, y, z, 1] == np.dot(affine, [i, j, k , 1]).

densityint or array_like (3,)

Specifies the number of seeds to place along each dimension. A density of 2 is the same as [2, 2, 2] and will result in a total of 8 seeds per voxel.

Raises:
ValueError

When mask is not a three-dimensional array

Examples

>>> mask = np.zeros((3,3,3), 'bool')
>>> mask[0,0,0] = 1
>>> seeds_from_mask(mask, np.eye(4), density=[1,1,1])
array([[ 0.,  0.,  0.]])

random_seeds_from_mask#

dipy.tracking.utils.random_seeds_from_mask(mask, affine, *, seeds_count=1, seed_count_per_voxel=True, random_seed=None)[source]#

Create randomly placed seeds for fiber tracking from a binary mask.

Seeds points are placed randomly distributed in voxels of mask which are True. If seed_count_per_voxel is True, this function is similar to seeds_from_mask(), with the difference that instead of evenly distributing the seeds, it randomly places the seeds within the voxels specified by the mask.

Parameters:
maskbinary 3d array_like

A binary array specifying where to place the seeds for fiber tracking.

affinearray, (4, 4)

The mapping between voxel indices and the point space for seeds. The voxel_to_rasmm matrix, typically from a NIFTI file. A seed point at the center the voxel [i, j, k] will be represented as [x, y, z] where [x, y, z, 1] == np.dot(affine, [i, j, k , 1]).

seeds_countint

The number of seeds to generate. If seed_count_per_voxel is True, specifies the number of seeds to place in each voxel. Otherwise, specifies the total number of seeds to place in the mask.

seed_count_per_voxel: bool

If True, seeds_count is per voxel, else seeds_count is the total number of seeds.

random_seedint

The seed for the random seed generator (numpy.random.Generator).

Raises:
ValueError

When mask is not a three-dimensional array

See also

seeds_from_mask

Examples

>>> mask = np.zeros((3,3,3), 'bool')
>>> mask[0,0,0] = 1
>>> random_seeds_from_mask(mask, np.eye(4), seeds_count=1,
... seed_count_per_voxel=True, random_seed=1)
array([[-0.23838787, -0.20150886,  0.31422574]])
>>> random_seeds_from_mask(mask, np.eye(4), seeds_count=6,
... seed_count_per_voxel=True, random_seed=1)
array([[-0.23838787, -0.20150886,  0.31422574],
       [-0.41435083, -0.26318949,  0.30127447],
       [ 0.44305611,  0.01132755,  0.47624371],
       [ 0.30500292,  0.30794079,  0.01532556],
       [ 0.03816435, -0.15672913, -0.13093276],
       [ 0.12509547,  0.3972138 ,  0.27568569]])
>>> mask[0,1,2] = 1
>>> random_seeds_from_mask(mask, np.eye(4),
... seeds_count=2, seed_count_per_voxel=True, random_seed=1)
array([[ 0.30500292,  1.30794079,  2.01532556],
       [-0.23838787, -0.20150886,  0.31422574],
       [ 0.3702492 ,  0.78681721,  2.10314815],
       [-0.41435083, -0.26318949,  0.30127447]])

target#

dipy.tracking.utils.target(streamlines, affine, target_mask, *, include=True)[source]#

Filter streamlines based on whether or not they pass through an ROI.

Parameters:
streamlinesiterable

A sequence of streamlines. Each streamline should be a (N, 3) array, where N is the length of the streamline.

affinearray (4, 4)

The mapping between voxel indices and the point space for seeds. The voxel_to_rasmm matrix, typically from a NIFTI file.

target_maskarray-like

A mask used as a target. Non-zero values are considered to be within the target region.

includebool, default True

If True, streamlines passing through target_mask are kept. If False, the streamlines not passing through target_mask are kept.

Returns:
streamlinesgenerator

A sequence of streamlines that pass through target_mask.

Raises:
ValueError

When the points of the streamlines lie outside of the target_mask.

See also

density_map

target_line_based#

dipy.tracking.utils.target_line_based(streamlines, affine, target_mask, *, include=True)[source]#

Filter streamlines based on whether or not they pass through a ROI, using a line-based algorithm. Mostly used as a replacement of target for compressed streamlines.

This function never returns single-point streamlines, whatever the value of include.

See [4] and [5] for further details about the method.

Parameters:
streamlinesiterable

A sequence of streamlines. Each streamline should be a (N, 3) array, where N is the length of the streamline.

affinearray (4, 4)

The mapping between voxel indices and the point space for seeds. The voxel_to_rasmm matrix, typically from a NIFTI file.

target_maskarray-like

A mask used as a target. Non-zero values are considered to be within the target region.

includebool, default True

If True, streamlines passing through target_mask are kept. If False, the streamlines not passing through target_mask are kept.

Returns:
streamlinesgenerator

A sequence of streamlines that pass through target_mask.

See also

dipy.tracking.utils.density_map
dipy.tracking.streamline.compress_streamlines

References

streamline_near_roi#

dipy.tracking.utils.streamline_near_roi(streamline, roi_coords, tol, *, mode='any')[source]#

Is a streamline near an ROI.

Implements the inner loops of the near_roi() function.

Parameters:
streamlinearray, shape (N, 3)

A single streamline

roi_coordsarray, shape (M, 3)

ROI coordinates transformed to the streamline coordinate frame.

tolfloat

Distance (in the units of the streamlines, usually mm). If any coordinate in the streamline is within this distance from the center of any voxel in the ROI, this function returns True.

modestring

One of {“any”, “all”, “either_end”, “both_end”}, where return True if:

“any” : any point is within tol from ROI.

“all” : all points are within tol from ROI.

“either_end” : either of the end-points is within tol from ROI

“both_end” : both end points are within tol from ROI.

Returns:
outboolean

near_roi#

dipy.tracking.utils.near_roi(streamlines, affine, region_of_interest, *, tol=None, mode='any')[source]#

Provide filtering criteria for a set of streamlines based on whether they fall within a tolerance distance from an ROI.

Parameters:
streamlineslist or generator

A sequence of streamlines. Each streamline should be a (N, 3) array, where N is the length of the streamline.

affinearray (4, 4)

The mapping between voxel indices and the point space for seeds. The voxel_to_rasmm matrix, typically from a NIFTI file.

region_of_interestndarray

A mask used as a target. Non-zero values are considered to be within the target region.

tolfloat

Distance (in the units of the streamlines, usually mm). If any coordinate in the streamline is within this distance from the center of any voxel in the ROI, the filtering criterion is set to True for this streamline, otherwise False. Defaults to the distance between the center of each voxel and the corner of the voxel.

modestring, optional

One of {“any”, “all”, “either_end”, “both_end”}, where return True if:

“any” : any point is within tol from ROI. Default.

“all” : all points are within tol from ROI.

“either_end” : either of the end-points is within tol from ROI

“both_end” : both end points are within tol from ROI.

Returns:
1D array of boolean dtype, shape (len(streamlines), )
This contains True for indices corresponding to each streamline
that passes within a tolerance distance from the target ROI, False
otherwise.

length#

dipy.tracking.utils.length(streamlines)[source]#

Calculate the lengths of many streamlines in a bundle.

Parameters:
streamlineslist

Each item in the list is an array with 3D coordinates of a streamline.

Returns:
Iterator object which then computes the length of each
streamline in the bundle, upon iteration.

unique_rows#

dipy.tracking.utils.unique_rows(in_array, *, dtype='f4')[source]#

Find the unique rows in an array.

Parameters:
in_array: ndarray

The array for which the unique rows should be found

dtype: str, optional

This determines the intermediate representation used for the values. Should at least preserve the values of the input array.

Returns:
u_return: ndarray

Array with the unique rows of the original array.

transform_tracking_output#

dipy.tracking.utils.transform_tracking_output(tracking_output, affine, *, save_seeds=False)[source]#

Apply a linear transformation, given by affine, to streamlines.

Parameters:
tracking_outputStreamlines generator

Either streamlines (list, ArraySequence) or a tuple with streamlines and seeds together

affinearray (4, 4)

The mapping between voxel indices and the point space for seeds. The voxel_to_rasmm matrix, typically from a NIFTI file.

save_seedsbool, optional

If set, seeds associated to streamlines will be also moved and returned

Returns:
streamlinesgenerator

A generator for the sequence of transformed streamlines. If save_seeds is True, also return a generator for the transformed seeds.

reduce_rois#

dipy.tracking.utils.reduce_rois(rois, include)[source]#

Reduce multiple ROIs to one inclusion and one exclusion ROI.

Parameters:
roislist or ndarray

A list of 3D arrays, each with shape (x, y, z) corresponding to the shape of the brain volume, or a 4D array with shape (n_rois, x, y, z). Non-zeros in each volume are considered to be within the region.

includearray or list

A list or 1D array of boolean marking inclusion or exclusion criteria.

Returns:
include_roiboolean 3D array

An array marking the inclusion mask.

exclude_roiboolean 3D array

An array marking the exclusion mask

Notes

The include_roi and exclude_roi can be used to perform the operation: “(A or B or …) and not (X or Y or …)”, where A, B are inclusion regions and X, Y are exclusion regions.

path_length#

dipy.tracking.utils.path_length(streamlines, affine, aoi, *, fill_value=-1)[source]#

Compute the shortest path, along any streamline, between aoi and each voxel.

Parameters:
streamlinesseq of (N, 3) arrays

A sequence of streamlines, path length is given in mm along the curve of the streamline.

aoiarray, 3d

A mask (binary array) of voxels from which to start computing distance.

affinearray (4, 4)

The mapping between voxel indices and the point space for seeds. The voxel_to_rasmm matrix, typically from a NIFTI file.

fill_valuefloat

The value of voxel in the path length map that are not connected to the aoi.

Returns:
plmarray

Same shape as aoi. The minimum distance between every point and aoi along the path of a streamline.

max_angle_from_curvature#

dipy.tracking.utils.max_angle_from_curvature(min_radius_curvature, step_size)[source]#

Get the maximum deviation angle from the minimum radius curvature.

See [6] for further details about the method.

Parameters:
min_radius_curvature: float

Minimum radius of curvature in mm.

step_size: float

The tracking step size in mm.

Returns:
max_angle: float

The maximum deviation angle in radian, given the radius curvature and the step size.

References

min_radius_curvature_from_angle#

dipy.tracking.utils.min_radius_curvature_from_angle(max_angle, step_size)[source]#

Get minimum radius of curvature from a deviation angle.

See [6] for further details about the method.

Parameters:
max_angle: float

The maximum deviation angle in radian. theta should be between [0 - pi/2] otherwise default will be pi/2.

step_size: float

The tracking step size in mm.

Returns:
min_radius_curvature: float

Minimum radius of curvature in mm, given the maximum deviation angle theta and the step size.

References

seeds_directions_pairs#

dipy.tracking.utils.seeds_directions_pairs(positions, peaks, *, max_cross=-1)[source]#

Pair each seed to the corresponding peaks. If multiple peaks are available the seed is repeated for each.

Parameters:
positionsarray, (N, 3)

Coordinates of the N positions.

peaksarray (N, M, 3)

Peaks at each position

max_crossint, optional

The maximum number of direction to track from each seed in crossing voxels. By default all voxel peaks are used.

Returns:
seedsarray (K, 3)
directionsarray (K, 3)