stats
stats.analysis
AveragePointwiseEuclideanMetric
QuickBundles
Streamlines
cKDTree
cKDTree
cKDTree.__init__()
cKDTree.boxsize
cKDTree.count_neighbors()
cKDTree.data
cKDTree.indices
cKDTree.leafsize
cKDTree.m
cKDTree.maxes
cKDTree.mins
cKDTree.n
cKDTree.query()
cKDTree.query_ball_point()
cKDTree.query_ball_tree()
cKDTree.query_pairs()
cKDTree.size
cKDTree.sparse_distance_matrix()
cKDTree.tree
stats
stats.analysis
Computes the average of pointwise Euclidean distances between two sequential data. 


Clusters streamlines using QuickBundles [Garyfallidis12]. 
alias of 


kdtree for quick nearestneighbor lookup 

Calculates a summarized profile of data for a bundle or tract along its length. 

Calculates dti measure (eg: FA, MD) per point on streamlines and 

Calculates assignment maps of the target bundle with reference to model bundle centroids. 

Calculate weights for each streamline/node in a bundle, based on a Mahalanobis distance from the core the bundle, at that node (mean, per default). 

Compute the Mahalanobis distance between two 1D arrays. 

Map the input array to new coordinates by interpolation. 

Return packagelike thing and module setup for package name 

Orient a bundle of streamlines to a standard streamline. 

Peak_values function finds the generalized fractional anisotropy (gfa) 

Saves the given input dataframe to .h5 file 
Change the number of points of streamlines 


Extract values of a scalar/vector along each streamline from a volume. 
AveragePointwiseEuclideanMetric
Bases: SumPointwiseEuclideanMetric
Computes the average of pointwise Euclidean distances between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.
It is used to extract features before computing the distance.
Notes
The distance between two 2D sequential data:
s1 s2
0* a *0
\ 
\ 
1* 
 b *1
 \
2* \
c *2
is equal to \((a+b+c)/3\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].
feature
Feature object used to extract features from sequential data
is_order_invariant
Is this metric invariant to the sequence’s ordering
Methods

Checks if features can be used by metric.dist based on their shape. 

Computes a distance between two data points based on their features. 
QuickBundles
Bases: Clustering
Clusters streamlines using QuickBundles [Garyfallidis12].
Given a list of streamlines, the QuickBundles algorithm sequentially assigns each streamline to its closest bundle in \(\mathcal{O}(Nk)\) where \(N\) is the number of streamlines and \(k\) is the final number of bundles. If for a given streamline its closest bundle is farther than threshold, a new bundle is created and the streamline is assigned to it except if the number of bundles has already exceeded max_nb_clusters.
The maximum distance from a bundle for a streamline to be still considered as part of it.
The distance metric to use when comparing two streamlines. By default, the Minimum average DirectFlip (MDF) distance [Garyfallidis12] is used and streamlines are automatically resampled so they have 12 points.
Limits the creation of bundles.
References
Examples
>>> from dipy.segment.clustering import QuickBundles
>>> from dipy.data import get_fnames
>>> from dipy.io.streamline import load_tractogram
>>> from dipy.tracking.streamline import Streamlines
>>> fname = get_fnames('fornix')
>>> fornix = load_tractogram(fname, 'same',
... bbox_valid_check=False).streamlines
>>> streamlines = Streamlines(fornix)
>>> # Segment fornix with a threshold of 10mm and streamlines resampled
>>> # to 12 points.
>>> qb = QuickBundles(threshold=10.)
>>> clusters = qb.cluster(streamlines)
>>> len(clusters)
4
>>> list(map(len, clusters))
[61, 191, 47, 1]
>>> # Resampling streamlines differently is done explicitly as follows.
>>> # Note this has an impact on the speed and the accuracy (tradeoff).
>>> from dipy.segment.featurespeed import ResampleFeature
>>> from dipy.segment.metricspeed import AveragePointwiseEuclideanMetric
>>> feature = ResampleFeature(nb_points=2)
>>> metric = AveragePointwiseEuclideanMetric(feature)
>>> qb = QuickBundles(threshold=10., metric=metric)
>>> clusters = qb.cluster(streamlines)
>>> len(clusters)
4
>>> list(map(len, clusters))
[58, 142, 72, 28]
Methods

Clusters streamlines into bundles. 
Clusters streamlines into bundles.
Performs quickbundles algorithm using predefined metric and threshold.
Each 2D array represents a sequence of 3D points (points, 3).
Specifies the order in which data points will be clustered.
Result of the clustering.
Streamlines
cKDTree
Bases: object
kdtree for quick nearestneighbor lookup
This class provides an index into a set of kdimensional points which can be used to rapidly look up the nearest neighbors of any point.
Note
cKDTree is functionally identical to KDTree. Prior to SciPy v1.6.0, cKDTree had better performance and slightly different functionality but now the two names exist only for backwardcompatibility reasons. If compatibility with SciPy < 1.6 is not a concern, prefer KDTree.
The n data points of dimension m to be indexed. This array is not copied unless this is necessary to produce a contiguous array of doubles, and so modifying this data will result in bogus results. The data are also copied if the kdtree is built with copy_data=True.
The number of points at which the algorithm switches over to bruteforce. Default: 16.
If True, the kdtree is built to shrink the hyperrectangles to the actual data range. This usually gives a more compact tree that is robust against degenerated input data and gives faster queries at the expense of longer build time. Default: True.
If True the data is always copied to protect the kdtree against data corruption. Default: False.
If True, the median is used to split the hyperrectangles instead of the midpoint. This usually gives a more compact tree and faster queries at the expense of longer build time. Default: True.
Apply a md toroidal topology to the KDTree.. The topology is generated by \(x_i + n_i L_i\) where \(n_i\) are integers and \(L_i\) is the boxsize along ith dimension. The input data shall be wrapped into \([0, L_i)\). A ValueError is raised if any of the data is outside of this bound.
Notes
The algorithm used is described in Maneewongvatana and Mount 1999. The general idea is that the kdtree is a binary tree, each of whose nodes represents an axisaligned hyperrectangle. Each node specifies an axis and splits the set of points based on whether their coordinate along that axis is greater than or less than a particular value.
During construction, the axis and splitting point are chosen by the “sliding midpoint” rule, which ensures that the cells do not all become long and thin.
The tree can be queried for the r closest neighbors of any given point (optionally returning only those within some maximum distance of the point). It can also be queried, with a substantial gain in efficiency, for the r approximate closest neighbors.
For large dimensions (20 is already large) do not expect this to run significantly faster than brute force. Highdimensional nearestneighbor queries are a substantial open problem in computer science.
The n data points of dimension m to be indexed. This array is not copied unless this is necessary to produce a contiguous array of doubles. The data are also copied if the kdtree is built with copy_data=True.
The number of points at which the algorithm switches over to bruteforce.
The dimension of a single datapoint.
The number of data points.
The maximum value in each dimension of the n data points.
The minimum value in each dimension of the n data points.
This attribute exposes a Python view of the root node in the cKDTree object. A full Python view of the kdtree is created dynamically on the first access. This attribute allows you to create your own query functions in Python.
The number of nodes in the tree.
Methods

Count how many nearby pairs can be formed. 

Query the kdtree for nearest neighbors 

Find all points within distance r of point(s) x. 

Find all pairs of points between self and other whose distance is at most r 

Find all pairs of points in self whose distance is at most r. 

Compute a sparse distance matrix 
Count how many nearby pairs can be formed.
Count the number of pairs (x1,x2)
can be formed, with x1
drawn
from self
and x2
drawn from other
, and where
distance(x1, x2, p) <= r
.
Data points on self
and other
are optionally weighted by the
weights
argument. (See below)
This is adapted from the “twopoint correlation” algorithm described by Gray and Moore [1]. See notes for further discussion.
The other tree to draw points from, can be the same tree as self.
The radius to produce a count for. Multiple radii are searched with
a single tree traversal.
If the count is noncumulative(cumulative=False
), r
defines
the edges of the bins, and must be nondecreasing.
1<=p<=infinity. Which Minkowski pnorm to use. Default 2.0. A finite large p may cause a ValueError if overflow can occur.
If None, the paircounting is unweighted.
If given as a tuple, weights[0] is the weights of points in self
, and
weights[1] is the weights of points in other
; either can be None to
indicate the points are unweighted.
If given as an array_like, weights is the weights of points in self
and other
. For this to make sense, self
and other
must be the
same tree. If self
and other
are two different trees, a ValueError
is raised.
Default: None
Whether the returned counts are cumulative. When cumulative is set to False
the algorithm is optimized to work with a large number of bins (>10) specified
by r
. When cumulative
is set to True, the algorithm is optimized to work
with a small number of r
. Default: True
The number of pairs. For unweighted counts, the result is integer.
For weighted counts, the result is float.
If cumulative is False, result[i]
contains the counts with
(inf if i == 0 else r[i1]) < R <= r[i]
Notes
Paircounting is the basic operation used to calculate the two point correlation functions from a data set composed of position of objects.
Two point correlation function measures the clustering of objects and is widely used in cosmology to quantify the large scale structure in our Universe, but it may be useful for data analysis in other fields where selfsimilar assembly of objects also occur.
The LandySzalay estimator for the two point correlation function of
D
measures the clustering signal in D
. [2]
For example, given the position of two sets of objects,
objects D
(data) contains the clustering signal, and
objects R
(random) that contains no signal,
where the brackets represents counting pairs between two data sets
in a finite bin around r
(distance), corresponding to setting
cumulative=False, and f = float(len(D)) / float(len(R))
is the
ratio between number of objects from data and random.
The algorithm implemented here is loosely based on the dualtree
algorithm described in [1]. We switch between two different
paircumulation scheme depending on the setting of cumulative
.
The computing time of the method we use when for
cumulative == False
does not scale with the total number of bins.
The algorithm for cumulative == True
scales linearly with the
number of bins, though it is slightly faster when only
1 or 2 bins are used. [5].
As an extension to the naive paircounting, weighted paircounting counts the product of weights instead of number of pairs. Weighted paircounting is used to estimate marked correlation functions ([3], section 2.2), or to properly calculate the average of data per distance bin (e.g. [4], section 2.1 on redshift).
Gray and Moore, “Nbody problems in statistical learning”, Mining the sky, 2000, :arxiv:`astroph/0012333`
Landy and Szalay, “Bias and variance of angular correlation functions”, The Astrophysical Journal, 1993, :doi:`10.1086/172900`
Sheth, Connolly and Skibba, “Marked correlations in galaxy formation models”, 2005, :arxiv:`astroph/0511773`
Hawkins, et al., “The 2dF Galaxy Redshift Survey: correlation functions, peculiar velocities and the matter density of the Universe”, Monthly Notices of the Royal Astronomical Society, 2002, :doi:`10.1046/j.13652966.2003.07063.x`
Examples
You can count neighbors number between two kdtrees within a distance:
>>> import numpy as np
>>> from scipy.spatial import cKDTree
>>> rng = np.random.default_rng()
>>> points1 = rng.random((5, 2))
>>> points2 = rng.random((5, 2))
>>> kd_tree1 = cKDTree(points1)
>>> kd_tree2 = cKDTree(points2)
>>> kd_tree1.count_neighbors(kd_tree2, 0.2)
1
This number is same as the total pair number calculated by query_ball_tree:
>>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2)
>>> sum([len(i) for i in indexes])
1
Query the kdtree for nearest neighbors
An array of points to query.
The list of kth nearest neighbors to return. If k is an integer it is treated as a list of [1, … k] (range(1, k+1)). Note that the counting starts from 1.
Return approximate nearest neighbors; the kth returned value is guaranteed to be no further than (1+eps) times the distance to the real kth nearest neighbor.
Which Minkowski pnorm to use. 1 is the sumofabsolutevalues “Manhattan” distance 2 is the usual Euclidean distance infinity is the maximumcoordinatedifference distance A finite large p may cause a ValueError if overflow can occur.
Return only neighbors within this distance. This is used to prune tree searches, so if you are doing a series of nearestneighbor queries, it may help to supply the distance to the nearest neighbor of the most recent point.
Number of workers to use for parallel processing. If 1 is given all CPU threads are used. Default: 1.
Changed in version 1.9.0: The “n_jobs” argument was renamed “workers”. The old name “n_jobs” was deprecated in SciPy 1.6.0 and was removed in SciPy 1.9.0.
The distances to the nearest neighbors.
If x
has shape tuple+(self.m,)
, then d
has shape tuple+(k,)
.
When k == 1, the last dimension of the output is squeezed.
Missing neighbors are indicated with infinite distances.
The index of each neighbor in self.data
.
If x
has shape tuple+(self.m,)
, then i
has shape tuple+(k,)
.
When k == 1, the last dimension of the output is squeezed.
Missing neighbors are indicated with self.n
.
Notes
If the KDTree is periodic, the position x
is wrapped into the
box.
When the input k is a list, a query for arange(max(k)) is performed, but only columns that store the requested values of k are preserved. This is implemented in a manner that reduces memory usage.
Examples
>>> import numpy as np
>>> from scipy.spatial import cKDTree
>>> x, y = np.mgrid[0:5, 2:8]
>>> tree = cKDTree(np.c_[x.ravel(), y.ravel()])
To query the nearest neighbours and return squeezed result, use
>>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=1)
>>> print(dd, ii, sep='\n')
[2. 0.2236068]
[ 0 13]
To query the nearest neighbours and return unsqueezed result, use
>>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1])
>>> print(dd, ii, sep='\n')
[[2. ]
[0.2236068]]
[[ 0]
[13]]
To query the second nearest neighbours and return unsqueezed result, use
>>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[2])
>>> print(dd, ii, sep='\n')
[[2.23606798]
[0.80622577]]
[[ 6]
[19]]
To query the first and second nearest neighbours, use
>>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=2)
>>> print(dd, ii, sep='\n')
[[2. 2.23606798]
[0.2236068 0.80622577]]
[[ 0 6]
[13 19]]
or, be more specific
>>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1, 2])
>>> print(dd, ii, sep='\n')
[[2. 2.23606798]
[0.2236068 0.80622577]]
[[ 0 6]
[13 19]]
Find all points within distance r of point(s) x.
The point or points to search for neighbors of.
The radius of points to return, shall broadcast to the length of x.
Which Minkowski pnorm to use. Should be in the range [1, inf]. A finite large p may cause a ValueError if overflow can occur.
Approximate search. Branches of the tree are not explored if their
nearest points are further than r / (1 + eps)
, and branches are
added in bulk if their furthest points are nearer than
r * (1 + eps)
.
Number of jobs to schedule for parallel processing. If 1 is given all processors are used. Default: 1.
Changed in version 1.9.0: The “n_jobs” argument was renamed “workers”. The old name “n_jobs” was deprecated in SciPy 1.6.0 and was removed in SciPy 1.9.0.
Sorts returned indicies if True and does not sort them if False. If None, does not sort single point queries, but does sort multipoint queries which was the behavior before this option was added.
New in version 1.2.0.
Return the number of points inside the radius instead of a list of the indices. .. versionadded:: 1.3.0
If x is a single point, returns a list of the indices of the neighbors of x. If x is an array of points, returns an object array of shape tuple containing lists of neighbors.
Notes
If you have many points whose neighbors you want to find, you may save substantial amounts of time by putting them in a cKDTree and using query_ball_tree.
Examples
>>> import numpy as np
>>> from scipy import spatial
>>> x, y = np.mgrid[0:4, 0:4]
>>> points = np.c_[x.ravel(), y.ravel()]
>>> tree = spatial.cKDTree(points)
>>> tree.query_ball_point([2, 0], 1)
[4, 8, 9, 12]
Query multiple points and plot the results:
>>> import matplotlib.pyplot as plt
>>> points = np.asarray(points)
>>> plt.plot(points[:,0], points[:,1], '.')
>>> for results in tree.query_ball_point(([2, 0], [3, 3]), 1):
... nearby_points = points[results]
... plt.plot(nearby_points[:,0], nearby_points[:,1], 'o')
>>> plt.margins(0.1, 0.1)
>>> plt.show()
Find all pairs of points between self and other whose distance is at most r
The tree containing points to search against.
The maximum distance, has to be positive.
Which Minkowski norm to use. p has to meet the condition
1 <= p <= infinity
.
A finite large p may cause a ValueError if overflow can occur.
Approximate search. Branches of the tree are not explored
if their nearest points are further than r/(1+eps)
, and
branches are added in bulk if their furthest points are nearer
than r * (1+eps)
. eps has to be nonnegative.
For each element self.data[i]
of this tree, results[i]
is a
list of the indices of its neighbors in other.data
.
Examples
You can search all pairs of points between two kdtrees within a distance:
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.spatial import cKDTree
>>> rng = np.random.default_rng()
>>> points1 = rng.random((15, 2))
>>> points2 = rng.random((15, 2))
>>> plt.figure(figsize=(6, 6))
>>> plt.plot(points1[:, 0], points1[:, 1], "xk", markersize=14)
>>> plt.plot(points2[:, 0], points2[:, 1], "og", markersize=14)
>>> kd_tree1 = cKDTree(points1)
>>> kd_tree2 = cKDTree(points2)
>>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2)
>>> for i in range(len(indexes)):
... for j in indexes[i]:
... plt.plot([points1[i, 0], points2[j, 0]],
... [points1[i, 1], points2[j, 1]], "r")
>>> plt.show()
Find all pairs of points in self whose distance is at most r.
The maximum distance.
Which Minkowski norm to use. p
has to meet the condition
1 <= p <= infinity
.
A finite large p may cause a ValueError if overflow can occur.
Approximate search. Branches of the tree are not explored
if their nearest points are further than r/(1+eps)
, and
branches are added in bulk if their furthest points are nearer
than r * (1+eps)
. eps has to be nonnegative.
Choose the output container, ‘set’ or ‘ndarray’. Default: ‘set’
Set of pairs (i,j)
, with i < j
, for which the corresponding
positions are close. If output_type is ‘ndarray’, an ndarry is
returned instead of a set.
Examples
You can search all pairs of points in a kdtree within a distance:
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.spatial import cKDTree
>>> rng = np.random.default_rng()
>>> points = rng.random((20, 2))
>>> plt.figure(figsize=(6, 6))
>>> plt.plot(points[:, 0], points[:, 1], "xk", markersize=14)
>>> kd_tree = cKDTree(points)
>>> pairs = kd_tree.query_pairs(r=0.2)
>>> for (i, j) in pairs:
... plt.plot([points[i, 0], points[j, 0]],
... [points[i, 1], points[j, 1]], "r")
>>> plt.show()
Compute a sparse distance matrix
Computes a distance matrix between two cKDTrees, leaving as zero any distance greater than max_distance.
Which Minkowski pnorm to use. A finite large p may cause a ValueError if overflow can occur.
Which container to use for output data. Options: ‘dok_matrix’, ‘coo_matrix’, ‘dict’, or ‘ndarray’. Default: ‘dok_matrix’.
Sparse matrix representing the results in “dictionary of keys” format. If a dict is returned the keys are (i,j) tuples of indices. If output_type is ‘ndarray’ a record array with fields ‘i’, ‘j’, and ‘v’ is returned,
Examples
You can compute a sparse distance matrix between two kdtrees:
>>> import numpy as np
>>> from scipy.spatial import cKDTree
>>> rng = np.random.default_rng()
>>> points1 = rng.random((5, 2))
>>> points2 = rng.random((5, 2))
>>> kd_tree1 = cKDTree(points1)
>>> kd_tree2 = cKDTree(points2)
>>> sdm = kd_tree1.sparse_distance_matrix(kd_tree2, 0.3)
>>> sdm.toarray()
array([[0. , 0. , 0.12295571, 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0.28942611, 0. , 0. , 0.2333084 , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0.24617575, 0.29571802, 0.26836782, 0. , 0. ]])
You can check distances above the max_distance are zeros:
>>> from scipy.spatial import distance_matrix
>>> distance_matrix(points1, points2)
array([[0.56906522, 0.39923701, 0.12295571, 0.8658745 , 0.79428925],
[0.37327919, 0.7225693 , 0.87665969, 0.32580855, 0.75679479],
[0.28942611, 0.30088013, 0.6395831 , 0.2333084 , 0.33630734],
[0.31994999, 0.72658602, 0.71124834, 0.55396483, 0.90785663],
[0.24617575, 0.29571802, 0.26836782, 0.57714465, 0.6473269 ]])
Calculates a summarized profile of data for a bundle or tract along its length.
Follows the approach outlined in [Yeatman2012].
The statistic to sample with the streamlines.
for each to have the same length) with which we are resampling. See Note below about orienting the streamlines.
The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.
The number of points to sample along the bundle. Default: 100.
A streamline to use as a standard to orient all of the streamlines in the bundle according to.
Weight each streamline (1D) or each node (2D) when calculating the tractprofiles. Must sum to 1 across streamlines (in each node if relevant). If callable, this is a function that calculates weights.
The statistic used to average the profile across streamlines. If weights is not None, this must take weights as a keyword argument. The default, np.average, is the same as np.mean but takes weights as a keyword argument.
Additional keyword arguments to pass to the weightcalculating function. Only to be used if weights is a callable.
bundle
Notes
Before providing a bundle as input to this function, you will need to make
sure that the streamlines in the bundle are all oriented in the same
orientation relative to the bundle (use orient_by_streamline()
).
References
Yeatman, Jason D., Robert F. Dougherty, Nathaniel J. Myall, Brian A. Wandell, and Heidi M. Feldman. 2012. “Tract Profiles of White Matter Properties: Automating FiberTract Quantification” PloS One 7 (11): e49790.
save it in hd5 file.
Name of bundle being analyzed
dti metric e.g. FA, MD
DataFrame to be populated
Name of the dti metric
Name of bundle being analyzed.
subject number as a string (e.g. 10001)
which group subject belongs to 1 for patient and 0 control
ind tells which disk number a point belong.
path of output directory
Calculates assignment maps of the target bundle with reference to model bundle centroids.
target bundle extracted from subject data in common space
atlas bundle used as reference
Number of disks used for dividing bundle into disks. (Default 100)
References
Chandio, B.Q., Risacher, S.L., Pestilli, F., Bullock, D.,
Yeh, FC., Koudoro, S., Rokem, A., Harezlak, J., and Garyfallidis, E. Bundle analytics, a computational framework for investigating the shapes and profiles of brain pathways across populations. Sci Rep 10, 17149 (2020)
Calculate weights for each streamline/node in a bundle, based on a Mahalanobis distance from the core the bundle, at that node (mean, per default).
The streamlines to weight.
The number of points to resample to. If the `bundle` is an array, this input is ignored. Default: 100.
Whether to return the Mahalanobis distance instead of the weights. Default: False.
The statistic used to calculate the central tendency of streamlines in each node. Can be one of {np.mean, np.median} or other functions that have similar API. Default: np.mean
Weights for each node in each streamline, calculated as its relative inverse of the Mahalanobis distance, relative to the distribution of coordinates at that node position across streamlines.
Compute the Mahalanobis distance between two 1D arrays.
The Mahalanobis distance between 1D arrays u and v, is defined as
where V
is the covariance matrix. Note that the argument VI
is the inverse of V
.
Input array.
Input array.
The inverse of the covariance matrix.
The Mahalanobis distance between vectors u and v.
Examples
>>> from scipy.spatial import distance
>>> iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
>>> distance.mahalanobis([1, 0, 0], [0, 1, 0], iv)
1.0
>>> distance.mahalanobis([0, 2, 0], [0, 1, 0], iv)
1.0
>>> distance.mahalanobis([2, 0, 0], [0, 1, 0], iv)
1.7320508075688772
Map the input array to new coordinates by interpolation.
The array of coordinates is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order.
The shape of the output is derived from that of the coordinate array by dropping the first axis. The values of the array along the first axis are the coordinates in the input array at which the output value is found.
The input array.
The coordinates at which input is evaluated.
The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.
The order of the spline interpolation, default is 3. The order has to be in the range 05.
The mode parameter determines how the input array is extended beyond its boundaries. Default is ‘constant’. Behavior for each valid value is as follows (see additional plots and details on boundary modes):
The input is extended by reflecting about the edge of the last pixel. This mode is also sometimes referred to as halfsample symmetric.
This is a synonym for ‘reflect’.
The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter. No interpolation is performed beyond the edges of the input.
The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter. Interpolation occurs for samples outside the input’s extent as well.
The input is extended by replicating the last pixel.
The input is extended by reflecting about the center of the last pixel. This mode is also sometimes referred to as wholesample symmetric.
The input is extended by wrapping around to the opposite edge.
The input is extended by wrapping around to the opposite edge, but in a way such that the last point and initial point exactly overlap. In this case it is not well defined which sample will be chosen at the point of overlap.
Value to fill past edges of input if mode is ‘constant’. Default is 0.0.
Determines if the input array is prefiltered with spline_filter before interpolation. The default is True, which will create a temporary float64 array of filtered values if order > 1. If setting this to False, the output will be slightly blurred if order > 1, unless the input is prefiltered, i.e. it is the result of calling spline_filter on the original input.
The result of transforming the input. The shape of the output is derived from that of coordinates by dropping the first axis.
See also
spline_filter
, geometric_transform
, scipy.interpolate
Notes
For complexvalued input, this function maps the real and imaginary components independently.
New in version 1.6.0: Complexvalued support added.
Examples
>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.arange(12.).reshape((4, 3))
>>> a
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.]])
>>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
array([ 2., 7.])
Above, the interpolated value of a[0.5, 0.5] gives output[0], while a[2, 1] is output[1].
>>> inds = np.array([[0.5, 2], [0.5, 4]])
>>> ndimage.map_coordinates(a, inds, order=1, cval=33.3)
array([ 2. , 33.3])
>>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
array([ 2., 8.])
>>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
array([ True, False], dtype=bool)
Return packagelike thing and module setup for package name
package name
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
TripWire
instanceIf we can import the package, return it. Otherwise return an object raising an error when accessed
True if import for package was successful, false otherwise
callable usually set as setup_module
in calling namespace, to allow
skipping tests.
Examples
Typical use would be something like this at the top of a module using an optional package:
>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')
Of course in this case the package doesn’t exist, and so, in the module:
>>> have_pkg
False
and
>>> pkg.some_function()
Traceback (most recent call last):
...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError
If the module does exist  we get the module
>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True
Or a submodule if that’s what we asked for
>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True
Orient a bundle of streamlines to a standard streamline.
The input streamlines to orient.
This provides the standard orientation according to which the streamlines in the provided bundle should be reoriented.
The number of samples to apply to each of the streamlines.
Whether to make the change inplace 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. Default: False.
Whether to return a generator as output. Default: False
possible to the standard.
and quantitative anisotropy (qa) values from peaks object (eg: csa) for every point on a streamline used while tracking and saves it in hd5 file.
Name of bundle being analyzed
contains peak directions and values
DataFrame to be populated
Name of the dti metric
Name of bundle being analyzed.
subject number as a string (e.g. 10001)
which group subject belongs to 1 patient and 0 for control
ind tells which disk number a point belong.
path of output directory
(either by downsampling or upsampling)
Change the number of points of streamlines in order to obtain nb_points1 segments of equal length. Points of streamlines will be modified along the curve.
dipy.tracking.Streamlines
If ndarray, must have shape (N,3) where N is the number of points
of the streamline.
If list, each item must be ndarray shape (Ni,3) where Ni is the number
of points of streamline i.
If dipy.tracking.Streamlines
, its common_shape must be 3.
integer representing number of points wanted along the curve.
dipy.tracking.Streamlines
Results of the downsampling or upsampling process.
Examples
>>> from dipy.tracking.streamline import set_number_of_points
>>> import numpy as np
One streamline, a semicircle:
>>> theta = np.pi*np.linspace(0, 1, 100)
>>> x = np.cos(theta)
>>> y = np.sin(theta)
>>> z = 0 * x
>>> streamline = np.vstack((x, y, z)).T
>>> modified_streamline = set_number_of_points(streamline, 3)
>>> len(modified_streamline)
3
Multiple streamlines:
>>> streamlines = [streamline, streamline[::2]]
>>> new_streamlines = set_number_of_points(streamlines, 10)
>>> [len(s) for s in streamlines]
[100, 50]
>>> [len(s) for s in new_streamlines]
[10, 10]
Extract values of a scalar/vector along each streamline from a volume.
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.
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.
The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.
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.