align
¶
Bunch (**kwds) 

floating 
alias of numpy.float32 
Module: align.imaffine
¶
Affine image registration module consisting of the following classes:
 AffineMap: encapsulates the necessary information to perform affine
 transforms between two domains, defined by a static and a moving image. The domain of the transform is the set of points in the static image’s grid, and the codomain is the set of points in the moving image. When we call the transform method, AffineMap maps each point x of the domain (static grid) to the codomain (moving grid) and interpolates the moving image at that point to obtain the intensity value to be placed at x in the resulting grid. The transform_inverse method performs the opposite operation mapping points in the codomain to points in the domain.
 ParzenJointHistogram: computes the marginal and joint distributions of
 intensities of a pair of images, using Parzen windows [Parzen62] with a cubic spline kernel, as proposed by Mattes et al. [Mattes03]. It also computes the gradient of the joint histogram w.r.t. the parameters of a given transform.
 MutualInformationMetric: computes the value and gradient of the mutual
 information metric the way Optimizer needs them. That is, given a set of transform parameters, it will use ParzenJointHistogram to compute the value and gradient of the joint intensity histogram evaluated at the given parameters, and evaluate the the value and gradient of the histogram’s mutual information.
 AffineRegistration: it runs the multiresolution registration, putting
 all the pieces together. It needs to create the scale space of the images and run the multiresolution registration by using the Metric and the Optimizer at each level of the Gaussian pyramid. At each level, it will setup the metric to compute value and gradient of the metric with the input images with different levels of smoothing.
References¶
 [Parzen62] E. Parzen. On the estimation of a probability density
 function and the mode. Annals of Mathematical Statistics, 33(3), 10651076, 1962.
 [Mattes03] Mattes, D., Haynor, D. R., Vesselle, H., Lewellen, T. K.,
 & Eubank, W. PETCT image registration in the chest using freeform deformations. IEEE Transactions on Medical Imaging, 22(1), 1208, 2003.
AffineInvalidValuesError 

AffineInversionError 

AffineMap (affine[, domain_grid_shape, …]) 
Methods 

AffineRegistration ([metric, level_iters, …]) 
Methods 

IsotropicScaleSpace (image, factors, sigmas) 
Methods 

MutualInformationMetric ([nbins, …]) 
Methods 

Optimizer (fun, x0[, args, method, jac, …]) 


ParzenJointHistogram 
Methods 

ScaleSpace (image, num_levels[, …]) 
Methods 

align_centers_of_mass (static, …) 

align_geometric_centers (static, …) 

align_origins (static, static_grid2world, …) 

compute_parzen_mi 
Computes the mutual information and its gradient (if requested)  
get_direction_and_spacings (affine, dim) 
Extracts the rotational and spacing components from a matrix  
sample_domain_regular 
Take floor(total_voxels/k) samples from a (2D or 3D) grid  
transform_centers_of_mass (static, …) 
Transformation to align the center of mass of the input images  
transform_geometric_centers (static, …) 
Transformation to align the geometric center of the input images  
transform_origins (static, static_grid2world, …) 
Transformation to align the origins of the input images  
warn 
Issue a warning, or maybe ignore it or raise an exception. 
Module: align.imwarp
¶
Classes and functions for Symmetric Diffeomorphic Registration
Bunch (**kwds) 

DiffeomorphicMap (dim, disp_shape[, …]) 
Methods 
DiffeomorphicRegistration ([metric]) 
Methods 
ScaleSpace (image, num_levels[, …]) 
Methods 
SymmetricDiffeomorphicRegistration (metric[, …]) 
Methods 
floating 
alias of numpy.float32 
get_direction_and_spacings (affine, dim) 
Extracts the rotational and spacing components from a matrix 
mult_aff (A, B) 
Returns the matrix product A.dot(B) considering None as the identity 
with_metaclass (meta, *bases) 
Create a base class with a metaclass. 
Module: align.metrics
¶
Metrics for Symmetric Diffeomorphic Registration
CCMetric (dim[, sigma_diff, radius]) 
Methods 
EMMetric (dim[, smooth, inner_iter, …]) 
Methods 
SSDMetric (dim[, smooth, inner_iter, step_type]) 
Methods 
SimilarityMetric (dim) 
Methods 
floating 
alias of numpy.float32 
gradient (f, *varargs, **kwargs) 
Return the gradient of an Ndimensional array. 
v_cycle_2d (n, k, delta_field, …[, depth]) 
Multiresolution GaussSeidel solver using Vtype cycles 
v_cycle_3d (n, k, delta_field, …[, depth]) 
Multiresolution GaussSeidel solver using Vtype cycles 
with_metaclass (meta, *bases) 
Create a base class with a metaclass. 
Module: align.reslice
¶
Pool 
Returns a process pool object 
affine_transform (input, matrix[, offset, …]) 
Apply an affine transformation. 
cpu_count 
Returns the number of CPUs in the system 
reslice (data, affine, zooms, new_zooms[, …]) 
Reslice data with new voxel resolution defined by new_zooms 
Module: align.scalespace
¶
IsotropicScaleSpace (image, factors, sigmas) 
Methods 
ScaleSpace (image, num_levels[, …]) 
Methods 
floating 
alias of numpy.float32 
Module: align.streamlinear
¶
BundleMinDistanceAsymmetricMetric ([num_threads]) 
Asymmetric Bundlebased Minimum distance  
BundleMinDistanceMatrixMetric ([num_threads]) 
Bundlebased Minimum Distance aka BMD  
BundleMinDistanceMetric ([num_threads]) 
Bundlebased Minimum Distance aka BMD  
BundleSumDistanceMatrixMetric ([num_threads]) 
Bundlebased Sum Distance aka BMD  
Optimizer (fun, x0[, args, method, jac, …]) 


StreamlineDistanceMetric ([num_threads]) 
Methods 

StreamlineLinearRegistration ([metric, x0, …]) 
Methods 

StreamlineRegistrationMap (matopt, xopt, …) 
Methods 

Streamlines 
alias of nibabel.streamlines.array_sequence.ArraySequence 

bundle_min_distance (t, static, moving) 
MDFbased pairwise distance optimization function (MIN)  
bundle_min_distance_asymmetric_fast (t, …) 
MDFbased pairwise distance optimization function (MIN)  
bundle_min_distance_fast (t, static, moving, …) 
MDFbased pairwise distance optimization function (MIN)  
bundle_sum_distance (t, static, moving[, …]) 
MDF distance optimization function (SUM)  
center_streamlines (streamlines) 
Move streamlines to the origin  
compose_matrix ([scale, shear, angles, …]) 
Return 4x4 transformation matrix from sequence of transformations.  
compose_matrix44 (t[, dtype]) 
Compose a 4x4 transformation matrix  
compose_transformations (*mats) 
Compose multiple 4x4 affine transformations in one 4x4 matrix  
decompose_matrix (matrix) 
Return sequence of transformations from transformation matrix.  
decompose_matrix44 (mat[, size]) 
Given a 4x4 homogeneous matrix return the parameter vector  
distance_matrix_mdf 
Minimum direct flipped distance matrix between two streamline sets  
length 
Euclidean length of streamlines  
progressive_slr (static, moving, metric, x0, …) 
Progressive SLR  
qbx_and_merge (streamlines, thresholds[, …]) 
Run QuickBundlesX and then run again on the centroids of the last layer  
remove_clusters_by_size (clusters[, min_size]) 

select_random_set_of_streamlines (…[, rng]) 
Select a random set of streamlines  
set_number_of_points 
Change the number of points of streamlines  
slr_with_qbx (static, moving[, x0, …]) 
Utility function for registering large tractograms.  
time () 
Return the current time in seconds since the Epoch.  
transform_streamlines (streamlines, mat[, …]) 
Apply affine transformation to streamlines  
unlist_streamlines (streamlines) 
Return the streamlines not as a list but as an array and an offset  
whole_brain_slr (static, moving[, x0, …]) 
Utility function for registering large tractograms.  
with_metaclass (meta, *bases) 
Create a base class with a metaclass. 
AffineMap
¶

class
dipy.align.imaffine.
AffineMap
(affine, domain_grid_shape=None, domain_grid2world=None, codomain_grid_shape=None, codomain_grid2world=None)¶ Bases:
object
Methods
get_affine
()Returns the value of the transformation, not a reference! set_affine
(affine)Sets the affine transform (operating in physical space) transform
(image[, interp, image_grid2world, …])Transforms the input image from codomain to domain space transform_inverse
(image[, interp, …])Transforms the input image from domain to codomain space 
__init__
(affine, domain_grid_shape=None, domain_grid2world=None, codomain_grid_shape=None, codomain_grid2world=None)¶ AffineMap
Implements an affine transformation whose domain is given by domain_grid and domain_grid2world, and whose codomain is given by codomain_grid and codomain_grid2world.
The actual transform is represented by the affine matrix, which operate in world coordinates. Therefore, to transform a moving image towards a static image, we first map each voxel (i,j,k) of the static image to world coordinates (x,y,z) by applying domain_grid2world. Then we apply the affine transform to (x,y,z) obtaining (x’, y’, z’) in moving image’s world coordinates. Finally, (x’, y’, z’) is mapped to voxel coordinates (i’, j’, k’) in the moving image by multiplying (x’, y’, z’) by the inverse of codomain_grid2world. The codomain_grid_shape is used analogously to transform the static image towards the moving image when calling transform_inverse.
If the domain/codomain information is not provided (None) then the sampling information needs to be specified each time the transform or transform_inverse is called to transform images. Note that such sampling information is not necessary to transform points defined in physical space, such as stream lines.
Parameters:  affine : array, shape (dim + 1, dim + 1)
the matrix defining the affine transform, where dim is the dimension of the space this map operates in (2 for 2D images, 3 for 3D images). If None, then self represents the identity transformation.
 domain_grid_shape : sequence, shape (dim,), optional
the shape of the default domain sampling grid. When transform is called to transform an image, the resulting image will have this shape, unless a different sampling information is provided. If None, then the sampling grid shape must be specified each time the transform method is called.
 domain_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtoworld transform associated with the domain grid. If None (the default), then the gridtoworld transform is assumed to be the identity.
 codomain_grid_shape : sequence of integers, shape (dim,)
the shape of the default codomain sampling grid. When transform_inverse is called to transform an image, the resulting image will have this shape, unless a different sampling information is provided. If None (the default), then the sampling grid shape must be specified each time the transform_inverse method is called.
 codomain_grid2world : array, shape (dim + 1, dim + 1)
the gridtoworld transform associated with the codomain grid. If None (the default), then the gridtoworld transform is assumed to be the identity.

get_affine
()¶ Returns the value of the transformation, not a reference!
Returns:  affine : ndarray
Copy of the transform, not a reference.

set_affine
(affine)¶ Sets the affine transform (operating in physical space)
Also sets self.affine_inv  the inverse of affine, or None if there is no inverse.
Parameters:  affine : array, shape (dim + 1, dim + 1)
the matrix representing the affine transform operating in physical space. The domain and codomain information remains unchanged. If None, then self represents the identity transformation.

transform
(image, interp='linear', image_grid2world=None, sampling_grid_shape=None, sampling_grid2world=None, resample_only=False)¶ Transforms the input image from codomain to domain space
By default, the transformed image is sampled at a grid defined by self.domain_shape and self.domain_grid2world. If such information was not provided then sampling_grid_shape is mandatory.
Parameters:  image : 2D or 3D array
the image to be transformed
 interp : string, either ‘linear’ or ‘nearest’
the type of interpolation to be used, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
 image_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtoworld transform associated with image. If None (the default), then the gridtoworld transform is assumed to be the identity.
 sampling_grid_shape : sequence, shape (dim,), optional
the shape of the grid where the transformed image must be sampled. If None (the default), then self.codomain_shape is used instead (which must have been set at initialization, otherwise an exception will be raised).
 sampling_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtoworld transform associated with the sampling grid (specified by sampling_grid_shape, or by default self.codomain_shape). If None (the default), then the gridtoworld transform is assumed to be the identity.
 resample_only : Boolean, optional
If False (the default) the affine transform is applied normally. If True, then the affine transform is not applied, and the input image is just resampled on the domain grid of this transform.
 Returns
 ——
 transformed : array, shape sampling_grid_shape or
self.codomain_shape
the transformed image, sampled at the requested grid

transform_inverse
(image, interp='linear', image_grid2world=None, sampling_grid_shape=None, sampling_grid2world=None, resample_only=False)¶ Transforms the input image from domain to codomain space
By default, the transformed image is sampled at a grid defined by self.codomain_shape and self.codomain_grid2world. If such information was not provided then sampling_grid_shape is mandatory.
Parameters:  image : 2D or 3D array
the image to be transformed
 interp : string, either ‘linear’ or ‘nearest’
the type of interpolation to be used, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
 image_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtoworld transform associated with image. If None (the default), then the gridtoworld transform is assumed to be the identity.
 sampling_grid_shape : sequence, shape (dim,), optional
the shape of the grid where the transformed image must be sampled. If None (the default), then self.codomain_shape is used instead (which must have been set at initialization, otherwise an exception will be raised).
 sampling_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtoworld transform associated with the sampling grid (specified by sampling_grid_shape, or by default self.codomain_shape). If None (the default), then the gridtoworld transform is assumed to be the identity.
 resample_only : Boolean, optional
If False (the default) the affine transform is applied normally. If True, then the affine transform is not applied, and the input image is just resampled on the domain grid of this transform.
 Returns
 ——
 transformed : array, shape sampling_grid_shape or
self.codomain_shape
the transformed image, sampled at the requested grid

AffineRegistration
¶

class
dipy.align.imaffine.
AffineRegistration
(metric=None, level_iters=None, sigmas=None, factors=None, method='LBFGSB', ss_sigma_factor=None, options=None, verbosity=1)¶ Bases:
object
Methods
optimize
(static, moving, transform, params0)Starts the optimization process 
__init__
(metric=None, level_iters=None, sigmas=None, factors=None, method='LBFGSB', ss_sigma_factor=None, options=None, verbosity=1)¶ Initializes an instance of the AffineRegistration class
Parameters:  metric : None or object, optional
an instance of a metric. The default is None, implying the Mutual Information metric with default settings.
 level_iters : sequence, optional
the number of iterations at each scale of the scale space. level_iters[0] corresponds to the coarsest scale, level_iters[1] the finest, where n is the length of the sequence. By default, a 3level scale space with iterations sequence equal to [10000, 1000, 100] will be used.
 sigmas : sequence of floats, optional
custom smoothing parameter to build the scale space (one parameter for each scale). By default, the sequence of sigmas will be [3, 1, 0].
 factors : sequence of floats, optional
custom scale factors to build the scale space (one factor for each scale). By default, the sequence of factors will be [4, 2, 1].
 method : string, optional
optimization method to be used. If Scipy version < 0.12, then only LBFGSB is available. Otherwise, method can be any gradientbased method available in dipy.core.Optimize: CG, BFGS, NewtonCG, dogleg or trustncg. The default is ‘LBFGSB’.
 ss_sigma_factor : float, optional
If None, this parameter is not used and an isotropic scale space with the given factors and sigmas will be built. If not None, an anisotropic scale space will be used by automatically selecting the smoothing sigmas along each axis according to the voxel dimensions of the given image. The ss_sigma_factor is used to scale the automatically computed sigmas. For example, in the isotropic case, the sigma of the kernel will be \(factor * (2 ^ i)\) where \(i = 1, 2, ..., n_scales  1\) is the scale (the finest resolution image \(i=0\) is never smoothed). The default is None.
 options : dict, optional
extra optimization options. The default is None, implying no extra options are passed to the optimizer.
 verbosity: int (one of {0, 1, 2, 3}), optional
Set the verbosity level of the algorithm: 0 : do not print anything 1 : print information about the current status of the algorithm 2 : print high level information of the components involved in
the registration that can be used to detect a failing component.
 3 : print as much information as possible to isolate the cause
of a bug.
Default: 1

docstring_addendum
= 'verbosity: int (one of {0, 1, 2, 3}), optional\n Set the verbosity level of the algorithm:\n 0 : do not print anything\n 1 : print information about the current status of the algorithm\n 2 : print high level information of the components involved in\n the registration that can be used to detect a failing\n component.\n 3 : print as much information as possible to isolate the cause\n of a bug.\n Default: 1\n '¶

optimize
(static, moving, transform, params0, static_grid2world=None, moving_grid2world=None, starting_affine=None, ret_metric=False)¶ Starts the optimization process
Parameters:  static : 2D or 3D array
the image to be used as reference during optimization.
 moving : 2D or 3D array
the image to be used as “moving” during optimization. It is necessary to prealign the moving image to ensure its domain lies inside the domain of the deformation fields. This is assumed to be accomplished by “prealigning” the moving image towards the static using an affine transformation given by the ‘starting_affine’ matrix
 transform : instance of Transform
the transformation with respect to whose parameters the gradient must be computed
 params0 : array, shape (n,)
parameters from which to start the optimization. If None, the optimization will start at the identity transform. n is the number of parameters of the specified transformation.
 static_grid2world : array, shape (dim+1, dim+1), optional
the voxeltospace transformation associated with the static image. The default is None, implying the transform is the identity.
 moving_grid2world : array, shape (dim+1, dim+1), optional
the voxeltospace transformation associated with the moving image. The default is None, implying the transform is the identity.
 starting_affine : string, or matrix, or None, optional
 If string:
‘mass’: align centers of gravity ‘voxelorigin’: align physical coordinates of voxel (0,0,0) ‘centers’: align physical coordinates of central voxels
 If matrix:
array, shape (dim+1, dim+1).
 If None:
Start from identity.
The default is None.
 ret_metric : boolean, optional
if True, it returns the parameters for measuring the similarity between the images (default ‘False’). The metric containing optimal parameters and the distance between the images.
Returns:  affine_map : instance of AffineMap
the affine resulting affine transformation
 xopt : optimal parameters
the optimal parameters (translation, rotation shear etc.)
 fopt : Similarity metric
the value of the function at the optimal parameters.

IsotropicScaleSpace
¶

class
dipy.align.imaffine.
IsotropicScaleSpace
(image, factors, sigmas, image_grid2world=None, input_spacing=None, mask0=False)¶ Bases:
dipy.align.scalespace.ScaleSpace
Methods
get_affine
(level)Voxeltospace transformation at a given level get_affine_inv
(level)Spacetovoxel transformation at a given level get_domain_shape
(level)Shape the subsampled image must have at a particular level get_expand_factors
(from_level, to_level)Ratio of voxel size from pyramid level from_level to to_level get_image
(level)Smoothed image at a given level get_scaling
(level)Adjustment factor for inputspacing to reflect voxel sizes at level get_sigmas
(level)Smoothing parameters used at a given level get_spacing
(level)Spacings the subsampled image must have at a particular level print_level
(level)Prints properties of a pyramid level 
__init__
(image, factors, sigmas, image_grid2world=None, input_spacing=None, mask0=False)¶ IsotropicScaleSpace
Computes the Scale Space representation of an image using isotropic smoothing kernels for all scales. The scale space is simply a list of images produced by smoothing the input image with a Gaussian kernel with different smoothing parameters.
This specialization of ScaleSpace allows the user to provide custom scale and smoothing factors for all scales.
Parameters:  image : array, shape (r,c) or (s, r, c) where s is the number of
slices, r is the number of rows and c is the number of columns of the input image.
 factors : list of floats
custom scale factors to build the scale space (one factor for each scale).
 sigmas : list of floats
custom smoothing parameter to build the scale space (one parameter for each scale).
 image_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtospace transform of the image grid. The default is the identity matrix.
 input_spacing : array, shape (dim,), optional
the spacing (voxel size) between voxels in physical space. The default if 1.0 along all axes.
 mask0 : Boolean, optional
if True, all smoothed images will be zero at all voxels that are zero in the input image. The default is False.

MutualInformationMetric
¶

class
dipy.align.imaffine.
MutualInformationMetric
(nbins=32, sampling_proportion=None)¶ Bases:
object
Methods
distance
(params)Numeric value of the negative Mutual Information distance_and_gradient
(params)Numeric value of the metric and its gradient at given parameters gradient
(params)Numeric value of the metric’s gradient at the given parameters setup
(transform, static, moving[, …])Prepares the metric to compute intensity densities and gradients 
__init__
(nbins=32, sampling_proportion=None)¶ Initializes an instance of the Mutual Information metric
This class implements the methods required by Optimizer to drive the registration process.
Parameters:  nbins : int, optional
the number of bins to be used for computing the intensity histograms. The default is 32.
 sampling_proportion : None or float in interval (0, 1], optional
There are two types of sampling: dense and sparse. Dense sampling uses all voxels for estimating the (joint and marginal) intensity histograms, while sparse sampling uses a subset of them. If sampling_proportion is None, then dense sampling is used. If sampling_proportion is a floating point value in (0,1] then sparse sampling is used, where sampling_proportion specifies the proportion of voxels to be used. The default is None.
Notes
Since we use linear interpolation, images are not, in general, differentiable at exact voxel coordinates, but they are differentiable between voxel coordinates. When using sparse sampling, selected voxels are slightly moved by adding a small random displacement within one voxel to prevent sampling points from being located exactly at voxel coordinates. When using dense sampling, this random displacement is not applied.

distance
(params)¶ Numeric value of the negative Mutual Information
We need to change the sign so we can use standard minimization algorithms.
Parameters:  params : array, shape (n,)
the parameter vector of the transform currently used by the metric (the transform name is provided when self.setup is called), n is the number of parameters of the transform
Returns:  neg_mi : float
the negative mutual information of the input images after transforming the moving image by the currently set transform with params parameters

distance_and_gradient
(params)¶ Numeric value of the metric and its gradient at given parameters
Parameters:  params : array, shape (n,)
the parameter vector of the transform currently used by the metric (the transform name is provided when self.setup is called), n is the number of parameters of the transform
Returns:  neg_mi : float
the negative mutual information of the input images after transforming the moving image by the currently set transform with params parameters
 neg_mi_grad : array, shape (n,)
the gradient of the negative Mutual Information

gradient
(params)¶ Numeric value of the metric’s gradient at the given parameters
Parameters:  params : array, shape (n,)
the parameter vector of the transform currently used by the metric (the transform name is provided when self.setup is called), n is the number of parameters of the transform
Returns:  grad : array, shape (n,)
the gradient of the negative Mutual Information

setup
(transform, static, moving, static_grid2world=None, moving_grid2world=None, starting_affine=None)¶ Prepares the metric to compute intensity densities and gradients
The histograms will be setup to compute probability densities of intensities within the minimum and maximum values of static and moving
Parameters:  transform: instance of Transform
the transformation with respect to whose parameters the gradient must be computed
 static : array, shape (S, R, C) or (R, C)
static image
 moving : array, shape (S’, R’, C’) or (R’, C’)
moving image. The dimensions of the static (S, R, C) and moving (S’, R’, C’) images do not need to be the same.
 static_grid2world : array (dim+1, dim+1), optional
the gridtospace transform of the static image. The default is None, implying the transform is the identity.
 moving_grid2world : array (dim+1, dim+1)
the gridtospace transform of the moving image. The default is None, implying the spacing along all axes is 1.
 starting_affine : array, shape (dim+1, dim+1), optional
the prealigning matrix (an affine transform) that roughly aligns the moving image towards the static image. If None, no prealignment is performed. If a prealignment matrix is available, it is recommended to provide this matrix as starting_affine instead of manually transforming the moving image to reduce interpolation artifacts. The default is None, implying no prealignment is performed.

Optimizer
¶

class
dipy.align.imaffine.
Optimizer
(fun, x0, args=(), method='LBFGSB', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)¶ Bases:
object
Attributes:  evolution
 fopt
 message
 nfev
 nit
 xopt
Methods
print_summary 
__init__
(fun, x0, args=(), method='LBFGSB', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)¶ A class for handling minimization of scalar function of one or more variables.
Parameters:  fun : callable
Objective function.
 x0 : ndarray
Initial guess.
 args : tuple, optional
Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian).
 method : str, optional
Type of solver. Should be one of
 ‘NelderMead’
 ‘Powell’
 ‘CG’
 ‘BFGS’
 ‘NewtonCG’
 ‘Anneal’
 ‘LBFGSB’
 ‘TNC’
 ‘COBYLA’
 ‘SLSQP’
 ‘dogleg’
 ‘trustncg’
 jac : bool or callable, optional
Jacobian of objective function. Only for CG, BFGS, NewtonCG, dogleg, trustncg. If jac is a Boolean and is True, fun is assumed to return the value of Jacobian along with the objective function. If False, the Jacobian will be estimated numerically. jac can also be a callable returning the Jacobian of the objective. In this case, it must accept the same arguments as fun.
 hess, hessp : callable, optional
Hessian of objective function or Hessian of objective function times an arbitrary vector p. Only for NewtonCG, dogleg, trustncg. Only one of hessp or hess needs to be given. If hess is provided, then hessp will be ignored. If neither hess nor hessp is provided, then the hessian product will be approximated using finite differences on jac. hessp must compute the Hessian times an arbitrary vector.
 bounds : sequence, optional
Bounds for variables (only for LBFGSB, TNC and SLSQP).
(min, max)
pairs for each element inx
, defining the bounds on that parameter. Use None for one ofmin
ormax
when there is no bound in that direction. constraints : dict or sequence of dict, optional
Constraints definition (only for COBYLA and SLSQP). Each constraint is defined in a dictionary with fields:
 type : str
Constraint type: ‘eq’ for equality, ‘ineq’ for inequality.
 fun : callable
The function defining the constraint.
 jac : callable, optional
The Jacobian of fun (only for SLSQP).
 args : sequence, optional
Extra arguments to be passed to the function and Jacobian.
Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be nonnegative. Note that COBYLA only supports inequality constraints.
 tol : float, optional
Tolerance for termination. For detailed control, use solverspecific options.
 callback : callable, optional
Called after each iteration, as
callback(xk)
, wherexk
is the current parameter vector. Only available using Scipy >= 0.12. options : dict, optional
A dictionary of solver options. All methods accept the following generic options:
 maxiter : int
Maximum number of iterations to perform.
 disp : bool
Set to True to print convergence messages.
For methodspecific options, see show_options(‘minimize’, method).
 evolution : bool, optional
save history of x for each iteration. Only available using Scipy >= 0.12.
See also
scipy.optimize.minimize

evolution
¶

fopt
¶

message
¶

nfev
¶

nit
¶

print_summary
()¶

xopt
¶
ParzenJointHistogram
¶

class
dipy.align.imaffine.
ParzenJointHistogram
¶ Bases:
object
Methods
bin_index
Bin index associated with the given normalized intensity bin_normalize_moving
Maps intensity x to the range covered by the moving histogram bin_normalize_static
Maps intensity x to the range covered by the static histogram setup
Compute histogram settings to store the PDF of input images update_gradient_dense
Computes the Gradient of the joint PDF w.r.t. update_gradient_sparse
Computes the Gradient of the joint PDF w.r.t. update_pdfs_dense
Computes the Probability Density Functions of two images update_pdfs_sparse
Computes the Probability Density Functions from a set of samples 
__init__
()¶ Computes joint histogram and derivatives with Parzen windows
Base class to compute joint and marginal probability density functions and their derivatives with respect to a transform’s parameters. The smooth histograms are computed by using Parzen windows [Parzen62] with a cubic spline kernel, as proposed by Mattes et al. [Mattes03]. This implementation is not tied to any optimization (registration) method, the idea is that informationtheoretic matching functionals (such as Mutual Information) can inherit from this class to perform the lowlevel computations of the joint intensity distributions and its gradient w.r.t. the transform parameters. The derived class can then compute the similarity/dissimilarity measure and gradient, and finally communicate the results to the appropriate optimizer.
Parameters:  nbins : int
the number of bins of the joint and marginal probability density functions (the actual number of bins of the joint PDF is nbins**2)
Notes
We need this class in cython to allow _joint_pdf_gradient_dense_2d and _joint_pdf_gradient_dense_3d to use a nogil Jacobian function (obtained from an instance of the Transform class), which allows us to evaluate Jacobians at all the sampling points (maybe the full grid) inside a nogil loop.
The reason we need a class is to encapsulate all the parameters related to the joint and marginal distributions.
References
 [Parzen62] E. Parzen. On the estimation of a probability density
 function and the mode. Annals of Mathematical Statistics, 33(3), 10651076, 1962.
 [Mattes03] Mattes, D., Haynor, D. R., Vesselle, H., Lewellen, T. K.,
 & Eubank, W. PETCT image registration in the chest using freeform deformations. IEEE Transactions on Medical Imaging, 22(1), 1208, 2003.

bin_index
¶ Bin index associated with the given normalized intensity
The return value is an integer in [padding, nbins  1  padding]
Parameters:  xnorm : float
intensity value normalized to the range covered by the histogram
Returns:  bin : int
the bin index associated with the given normalized intensity

bin_normalize_moving
¶ Maps intensity x to the range covered by the moving histogram
If the input intensity is in [self.mmin, self.mmax] then the normalized intensity will be in [self.padding, self.nbins  self.padding]
Parameters:  x : float
the intensity to be normalized
Returns:  xnorm : float
normalized intensity to the range covered by the moving histogram

bin_normalize_static
¶ Maps intensity x to the range covered by the static histogram
If the input intensity is in [self.smin, self.smax] then the normalized intensity will be in [self.padding, self.nbins  self.padding]
Parameters:  x : float
the intensity to be normalized
Returns:  xnorm : float
normalized intensity to the range covered by the static histogram

setup
¶ Compute histogram settings to store the PDF of input images
Parameters:  static : array
static image
 moving : array
moving image
 smask : array
mask of static object being registered (a binary array with 1’s inside the object of interest and 0’s along the background). If None, the behaviour is equivalent to smask=ones_like(static)
 mmask : array
mask of moving object being registered (a binary array with 1’s inside the object of interest and 0’s along the background). If None, the behaviour is equivalent to mmask=ones_like(static)

update_gradient_dense
¶ Computes the Gradient of the joint PDF w.r.t. transform parameters
Computes the vector of partial derivatives of the joint histogram w.r.t. each transformation parameter.
The gradient is stored in self.joint_grad.
Parameters:  theta : array, shape (n,)
parameters of the transformation to compute the gradient from
 transform : instance of Transform
the transformation with respect to whose parameters the gradient must be computed
 static : array, shape (S, R, C)
static image
 moving : array, shape (S, R, C)
moving image
 grid2world : array, shape (4, 4)
we assume that both images have already been sampled at a common grid. This transform must map voxel coordinates of this common grid to physical coordinates of its corresponding voxel in the moving image. For example, if the moving image was sampled on the static image’s grid (this is the typical setting) using an aligning matrix A, then
 grid2world = A.dot(static_affine)
where static_affine is the transformation mapping static image’s grid coordinates to physical space.
 mgradient : array, shape (S, R, C, 3)
the gradient of the moving image
 smask : array, shape (S, R, C), optional
mask of static object being registered (a binary array with 1’s inside the object of interest and 0’s along the background). The default is None, indicating all voxels are considered.
 mmask : array, shape (S, R, C), optional
mask of moving object being registered (a binary array with 1’s inside the object of interest and 0’s along the background). The default is None, indicating all voxels are considered.

update_gradient_sparse
¶ Computes the Gradient of the joint PDF w.r.t. transform parameters
Computes the vector of partial derivatives of the joint histogram w.r.t. each transformation parameter.
The list of intensities sval and mval are assumed to be sampled from the static and moving images, respectively, at the same physical points. Of course, the images may not be perfectly aligned at the moment the sampling was performed. The resulting gradient corresponds to the paired intensities according to the alignment at the moment the images were sampled.
The gradient is stored in self.joint_grad.
Parameters:  theta : array, shape (n,)
parameters to compute the gradient at
 transform : instance of Transform
the transformation with respect to whose parameters the gradient must be computed
 sval : array, shape (m,)
sampled intensities from the static image at sampled_points
 mval : array, shape (m,)
sampled intensities from the moving image at sampled_points
 sample_points : array, shape (m, 3)
coordinates (in physical space) of the points the images were sampled at
 mgradient : array, shape (m, 3)
the gradient of the moving image at the sample points

update_pdfs_dense
¶ Computes the Probability Density Functions of two images
The joint PDF is stored in self.joint. The marginal distributions corresponding to the static and moving images are computed and stored in self.smarginal and self.mmarginal, respectively.
Parameters:  static : array, shape (S, R, C)
static image
 moving : array, shape (S, R, C)
moving image
 smask : array, shape (S, R, C)
mask of static object being registered (a binary array with 1’s inside the object of interest and 0’s along the background). If None, ones_like(static) is used as mask.
 mmask : array, shape (S, R, C)
mask of moving object being registered (a binary array with 1’s inside the object of interest and 0’s along the background). If None, ones_like(moving) is used as mask.

update_pdfs_sparse
¶ Computes the Probability Density Functions from a set of samples
The list of intensities sval and mval are assumed to be sampled from the static and moving images, respectively, at the same physical points. Of course, the images may not be perfectly aligned at the moment the sampling was performed. The resulting distributions corresponds to the paired intensities according to the alignment at the moment the images were sampled.
The joint PDF is stored in self.joint. The marginal distributions corresponding to the static and moving images are computed and stored in self.smarginal and self.mmarginal, respectively.
Parameters:  sval : array, shape (n,)
sampled intensities from the static image at sampled_points
 mval : array, shape (n,)
sampled intensities from the moving image at sampled_points

ScaleSpace
¶

class
dipy.align.imaffine.
ScaleSpace
(image, num_levels, image_grid2world=None, input_spacing=None, sigma_factor=0.2, mask0=False)¶ Bases:
object
Methods
get_affine
(level)Voxeltospace transformation at a given level get_affine_inv
(level)Spacetovoxel transformation at a given level get_domain_shape
(level)Shape the subsampled image must have at a particular level get_expand_factors
(from_level, to_level)Ratio of voxel size from pyramid level from_level to to_level get_image
(level)Smoothed image at a given level get_scaling
(level)Adjustment factor for inputspacing to reflect voxel sizes at level get_sigmas
(level)Smoothing parameters used at a given level get_spacing
(level)Spacings the subsampled image must have at a particular level print_level
(level)Prints properties of a pyramid level 
__init__
(image, num_levels, image_grid2world=None, input_spacing=None, sigma_factor=0.2, mask0=False)¶ ScaleSpace
Computes the Scale Space representation of an image. The scale space is simply a list of images produced by smoothing the input image with a Gaussian kernel with increasing smoothing parameter. If the image’s voxels are isotropic, the smoothing will be the same along all directions: at level L = 0, 1, …, the sigma is given by \(s * ( 2^L  1 )\). If the voxel dimensions are not isotropic, then the smoothing is weaker along low resolution directions.
Parameters:  image : array, shape (r,c) or (s, r, c) where s is the number of
slices, r is the number of rows and c is the number of columns of the input image.
 num_levels : int
the desired number of levels (resolutions) of the scale space
 image_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtospace transform of the image grid. The default is the identity matrix
 input_spacing : array, shape (dim,), optional
the spacing (voxel size) between voxels in physical space. The default is 1.0 along all axes
 sigma_factor : float, optional
the smoothing factor to be used in the construction of the scale space. The default is 0.2
 mask0 : Boolean, optional
if True, all smoothed images will be zero at all voxels that are zero in the input image. The default is False.

get_affine
(level)¶ Voxeltospace transformation at a given level
Returns the voxeltospace transformation associated with the subsampled image at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get affine transform from
Returns:  the affine (voxeltospace) transform at the requested resolution
or None if an invalid level was requested

get_affine_inv
(level)¶ Spacetovoxel transformation at a given level
Returns the spacetovoxel transformation associated with the subsampled image at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the inverse transform from
Returns:  the inverse (spacetovoxel) transform at the requested resolution or
 None if an invalid level was requested

get_domain_shape
(level)¶ Shape the subsampled image must have at a particular level
Returns the shape the subsampled image must have at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the subsampled shape from
Returns:  the subsampled shape at the requested resolution or None if an
invalid level was requested

get_expand_factors
(from_level, to_level)¶ Ratio of voxel size from pyramid level from_level to to_level
Given two scale space resolutions a = from_level, b = to_level, returns the ratio of voxels size at level b to voxel size at level a (the factor that must be used to multiply voxels at level a to ‘expand’ them to level b).
Parameters:  from_level : int, 0 <= from_level < L, (L = number of resolutions)
the resolution to expand voxels from
 to_level : int, 0 <= to_level < from_level
the resolution to expand voxels to
Returns:  factors : array, shape (k,), k = 2, 3
the expand factors (a scalar for each voxel dimension)

get_image
(level)¶ Smoothed image at a given level
Returns the smoothed image at the requested level in the Scale Space.
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smooth image from
Returns:  the smooth image at the requested resolution or None if an invalid
level was requested

get_scaling
(level)¶ Adjustment factor for inputspacing to reflect voxel sizes at level
Returns the scaling factor that needs to be applied to the input spacing (the voxel sizes of the image at level 0 of the scale space) to transform them to voxel sizes at the requested level.
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the scalings from
Returns:  the scaling factors from the original spacing to the spacings at the
 requested level

get_sigmas
(level)¶ Smoothing parameters used at a given level
Returns the smoothing parameters (a scalar for each axis) used at the requested level of the scale space
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smoothing parameters from
Returns:  the smoothing parameters at the requested level

get_spacing
(level)¶ Spacings the subsampled image must have at a particular level
Returns the spacings (voxel sizes) the subsampled image must have at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the subsampled shape from
Returns:  the spacings (voxel sizes) at the requested resolution or None if an
 invalid level was requested

print_level
(level)¶ Prints properties of a pyramid level
Prints the properties of a level of this scale space to standard output
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to be printed

align_centers_of_mass¶

dipy.align.imaffine.
align_centers_of_mass
(static, static_grid2world, moving, moving_grid2world)¶
align_geometric_centers¶

dipy.align.imaffine.
align_geometric_centers
(static, static_grid2world, moving, moving_grid2world)¶
align_origins¶

dipy.align.imaffine.
align_origins
(static, static_grid2world, moving, moving_grid2world)¶
compute_parzen_mi¶

dipy.align.imaffine.
compute_parzen_mi
()¶ Computes the mutual information and its gradient (if requested)
Parameters:  joint : array, shape (nbins, nbins)
the joint intensity distribution
 joint_gradient : array, shape (nbins, nbins, n)
the gradient of the joint distribution w.r.t. the transformation parameters
 smarginal : array, shape (nbins,)
the marginal intensity distribution of the static image
 mmarginal : array, shape (nbins,)
the marginal intensity distribution of the moving image
 mi_gradient : array, shape (n,)
the buffer in which to write the gradient of the mutual information. If None, the gradient is not computed
get_direction_and_spacings¶

dipy.align.imaffine.
get_direction_and_spacings
(affine, dim)¶ Extracts the rotational and spacing components from a matrix
Extracts the rotational and spacing (voxel dimensions) components from a matrix. An image gradient represents the local variation of the image’s gray values per voxel. Since we are iterating on the physical space, we need to compute the gradients as variation per millimeter, so we need to divide each gradient’s component by the voxel size along the corresponding axis, that’s what the spacings are used for. Since the image’s gradients are oriented along the grid axes, we also need to reorient the gradients to be given in physical space coordinates.
Parameters:  affine : array, shape (k, k), k = 3, 4
the matrix transforming grid coordinates to physical space.
Returns:  direction : array, shape (k1, k1)
the rotational component of the input matrix
 spacings : array, shape (k1,)
the scaling component (voxel size) of the matrix
sample_domain_regular¶

dipy.align.imaffine.
sample_domain_regular
()¶ Take floor(total_voxels/k) samples from a (2D or 3D) grid
The sampling is made by taking all pixels whose index (in lexicographical order) is a multiple of k. Each selected point is slightly perturbed by adding a realization of a normally distributed random variable and then mapped to physical space by the given gridtospace transform.
The lexicographical order of a pixels in a grid of shape (a, b, c) is defined by assigning to each voxel position (i, j, k) the integer index
F((i, j, k)) = i * (b * c) + j * (c) + k
and sorting increasingly by this index.
Parameters:  k : int
the sampling rate, as described before
 shape : array, shape (dim,)
the shape of the grid to be sampled
 grid2world : array, shape (dim+1, dim+1)
the gridtospace transform
 sigma : float
the standard deviation of the Normal random distortion to be applied to the sampled points
Returns:  samples : array, shape (total_pixels//k, dim)
the matrix whose rows are the sampled points
transform_centers_of_mass¶

dipy.align.imaffine.
transform_centers_of_mass
(static, static_grid2world, moving, moving_grid2world)¶ Transformation to align the center of mass of the input images
Parameters:  static : array, shape (S, R, C)
static image
 static_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation of the static image
 moving : array, shape (S, R, C)
moving image
 moving_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation of the moving image
Returns:  affine_map : instance of AffineMap
the affine transformation (translation only, in this case) aligning the center of mass of the moving image towards the one of the static image
transform_geometric_centers¶

dipy.align.imaffine.
transform_geometric_centers
(static, static_grid2world, moving, moving_grid2world)¶ Transformation to align the geometric center of the input images
With “geometric center” of a volume we mean the physical coordinates of its central voxel
Parameters:  static : array, shape (S, R, C)
static image
 static_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation of the static image
 moving : array, shape (S, R, C)
moving image
 moving_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation of the moving image
Returns:  affine_map : instance of AffineMap
the affine transformation (translation only, in this case) aligning the geometric center of the moving image towards the one of the static image
transform_origins¶

dipy.align.imaffine.
transform_origins
(static, static_grid2world, moving, moving_grid2world)¶ Transformation to align the origins of the input images
With “origin” of a volume we mean the physical coordinates of voxel (0,0,0)
Parameters:  static : array, shape (S, R, C)
static image
 static_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation of the static image
 moving : array, shape (S, R, C)
moving image
 moving_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation of the moving image
Returns:  affine_map : instance of AffineMap
the affine transformation (translation only, in this case) aligning the origin of the moving image towards the one of the static image
DiffeomorphicMap
¶

class
dipy.align.imwarp.
DiffeomorphicMap
(dim, disp_shape, disp_grid2world=None, domain_shape=None, domain_grid2world=None, codomain_shape=None, codomain_grid2world=None, prealign=None)¶ Bases:
object
Methods
allocate
()Creates a zero displacement field compute_inversion_error
()Inversion error of the displacement fields expand_fields
(expand_factors, new_shape)Expands the displacement fields from current shape to new_shape get_backward_field
()Deformation field to transform an image in the backward direction get_forward_field
()Deformation field to transform an image in the forward direction get_simplified_transform
()Constructs a simplified version of this Diffeomorhic Map interpret_matrix
(obj)Try to interpret obj as a matrix inverse
()Inverse of this DiffeomorphicMap instance shallow_copy
()Shallow copy of this DiffeomorphicMap instance transform
(image[, interpolation, …])Warps an image in the forward direction transform_inverse
(image[, interpolation, …])Warps an image in the backward direction warp_endomorphism
(phi)Composition of this DiffeomorphicMap with a given endomorphism 
__init__
(dim, disp_shape, disp_grid2world=None, domain_shape=None, domain_grid2world=None, codomain_shape=None, codomain_grid2world=None, prealign=None)¶ DiffeomorphicMap
Implements a diffeomorphic transformation on the physical space. The deformation fields encoding the direct and inverse transformations share the same domain discretization (both the discretization grid shape and voxeltospace matrix). The input coordinates (physical coordinates) are first aligned using prealign, and then displaced using the corresponding vector field interpolated at the aligned coordinates.
Parameters:  dim : int, 2 or 3
the transformation’s dimension
 disp_shape : array, shape (dim,)
the number of slices (if 3D), rows and columns of the deformation field’s discretization
 disp_grid2world : the voxeltospace transform between the def. fields
grid and space
 domain_shape : array, shape (dim,)
the number of slices (if 3D), rows and columns of the default discretizatio of this map’s domain
 domain_grid2world : array, shape (dim+1, dim+1)
the default voxeltospace transformation between this map’s discretization and physical space
 codomain_shape : array, shape (dim,)
the number of slices (if 3D), rows and columns of the images that are ‘normally’ warped using this transformation in the forward direction (this will provide default transformation parameters to warp images under this transformation). By default, we assume that the inverse transformation is ‘normally’ used to warp images with the same discretization and voxeltospace transformation as the deformation field grid.
 codomain_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation of images that are ‘normally’ warped using this transformation (in the forward direction).
 prealign : array, shape (dim+1, dim+1)
the linear transformation to be applied to align input images to the reference space before warping under the deformation field.

allocate
()¶ Creates a zero displacement field
Creates a zero displacement field (the identity transformation).

compute_inversion_error
()¶ Inversion error of the displacement fields
Estimates the inversion error of the displacement fields by computing statistics of the residual vectors obtained after composing the forward and backward displacement fields.
Returns:  residual : array, shape (R, C) or (S, R, C)
the displacement field resulting from composing the forward and backward displacement fields of this transformation (the residual should be zero for a perfect diffeomorphism)
 stats : array, shape (3,)
statistics from the norms of the vectors of the residual displacement field: maximum, mean and standard deviation
Notes
Since the forward and backward displacement fields have the same discretization, the final composition is given by
comp[i] = forward[ i + Dinv * backward[i]]
where Dinv is the spacetogrid transformation of the displacement fields

expand_fields
(expand_factors, new_shape)¶ Expands the displacement fields from current shape to new_shape
Upsamples the discretization of the displacement fields to be of new_shape shape.
Parameters:  expand_factors : array, shape (dim,)
the factors scaling current spacings (voxel sizes) to spacings in the expanded discretization.
 new_shape : array, shape (dim,)
the shape of the arrays holding the upsampled discretization

get_backward_field
()¶ Deformation field to transform an image in the backward direction
Returns the deformation field that must be used to warp an image under this transformation in the backward direction (note the ‘is_inverse’ flag).

get_forward_field
()¶ Deformation field to transform an image in the forward direction
Returns the deformation field that must be used to warp an image under this transformation in the forward direction (note the ‘is_inverse’ flag).

get_simplified_transform
()¶ Constructs a simplified version of this Diffeomorhic Map
The simplified version incorporates the prealign transform, as well as the domain and codomain affine transforms into the displacement field. The resulting transformation may be regarded as operating on the image spaces given by the domain and codomain discretization. As a result, self.prealign, self.disp_grid2world, self.domain_grid2world and self.codomain affine will be None (denoting Identity) in the resulting diffeomorphic map.

interpret_matrix
(obj)¶ Try to interpret obj as a matrix
Some operations are performed faster if we know in advance if a matrix is the identity (so we can skip the actual matrixvector multiplication). This function returns None if the given object is None or the ‘identity’ string. It returns the same object if it is a numpy array. It raises an exception otherwise.
Parameters:  obj : object
any object
Returns:  obj : object
the same object given as argument if obj is None or a numpy array. None if obj is the ‘identity’ string.

inverse
()¶ Inverse of this DiffeomorphicMap instance
Returns a diffeomorphic map object representing the inverse of this transformation. The internal arrays are not copied but just referenced.
Returns:  inv : DiffeomorphicMap object
the inverse of this diffeomorphic map.

shallow_copy
()¶ Shallow copy of this DiffeomorphicMap instance
Creates a shallow copy of this diffeomorphic map (the arrays are not copied but just referenced)
Returns:  new_map : DiffeomorphicMap object
the shallow copy of this diffeomorphic map

transform
(image, interpolation='linear', image_world2grid=None, out_shape=None, out_grid2world=None)¶ Warps an image in the forward direction
Transforms the input image under this transformation in the forward direction. It uses the “is_inverse” flag to switch between “forward” and “backward” (if is_inverse is False, then transform(…) warps the image forwards, else it warps the image backwards).
Parameters:  image : array, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the forward direction
 interpolation : string, either ‘linear’ or ‘nearest’
the type of interpolation to be used for warping, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
 image_world2grid : array, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel coordinates of the image given as input
 out_shape : array, shape (dim,)
the number of slices, rows and columns of the desired warped image
 out_grid2world : the transformation bringing voxel coordinates of the
warped image to physical space
Returns:  warped : array, shape = out_shape or self.codomain_shape if None
the warped image under this transformation in the forward direction
Notes
See _warp_forward and _warp_backward documentation for further information.

transform_inverse
(image, interpolation='linear', image_world2grid=None, out_shape=None, out_grid2world=None)¶ Warps an image in the backward direction
Transforms the input image under this transformation in the backward direction. It uses the “is_inverse” flag to switch between “forward” and “backward” (if is_inverse is False, then transform_inverse(…) warps the image backwards, else it warps the image forwards)
Parameters:  image : array, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the forward direction
 interpolation : string, either ‘linear’ or ‘nearest’
the type of interpolation to be used for warping, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
 image_world2grid : array, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel coordinates of the image given as input
 out_shape : array, shape (dim,)
the number of slices, rows and columns of the desired warped image
 out_grid2world : the transformation bringing voxel coordinates of the
warped image to physical space
Returns:  warped : array, shape = out_shape or self.codomain_shape if None
warped image under this transformation in the backward direction
Notes
See _warp_forward and _warp_backward documentation for further information.

warp_endomorphism
(phi)¶ Composition of this DiffeomorphicMap with a given endomorphism
Creates a new DiffeomorphicMap C with the same properties as self and composes its displacement fields with phi’s corresponding fields. The resulting diffeomorphism is of the form C(x) = phi(self(x)) with inverse C^{1}(y) = self^{1}(phi^{1}(y)). We assume that phi is an endomorphism with the same discretization and domain affine as self to ensure that the composition inherits self’s properties (we also assume that the prealigning matrix of phi is None or identity).
Parameters:  phi : DiffeomorphicMap object
the endomorphism to be warped by this diffeomorphic map
Returns:  composition : the composition of this diffeomorphic map with the
endomorphism given as input
Notes
The problem with our current representation of a DiffeomorphicMap is that the set of Diffeomorphism that can be represented this way (a prealigning matrix followed by a nonlinear endomorphism given as a displacement field) is not closed under the composition operation.
Supporting a general DiffeomorphicMap class, closed under composition, may be extremely costly computationally, and the kind of transformations we actually need for Avants’ midpoint algorithm (SyN) are much simpler.

DiffeomorphicRegistration
¶

class
dipy.align.imwarp.
DiffeomorphicRegistration
(metric=None)¶ Bases:
abc.NewBase
Methods
get_map
()Returns the resulting diffeomorphic map after optimization optimize
()Starts the metric optimization set_level_iters
(level_iters)Sets the number of iterations at each pyramid level 
__init__
(metric=None)¶ Diffeomorphic Registration
This abstract class defines the interface to be implemented by any optimization algorithm for diffeomorphic registration.
Parameters:  metric : SimilarityMetric object
the object measuring the similarity of the two images. The registration algorithm will minimize (or maximize) the provided similarity.

get_map
()¶ Returns the resulting diffeomorphic map after optimization

optimize
()¶ Starts the metric optimization
This is the main function each specialized class derived from this must implement. Upon completion, the deformation field must be available from the forward transformation model.

set_level_iters
(level_iters)¶ Sets the number of iterations at each pyramid level
Establishes the maximum number of iterations to be performed at each level of the Gaussian pyramid, similar to ANTS.
Parameters:  level_iters : list
the number of iterations at each level of the Gaussian pyramid. level_iters[0] corresponds to the finest level, level_iters[n1] the coarsest, where n is the length of the list

ScaleSpace
¶

class
dipy.align.imwarp.
ScaleSpace
(image, num_levels, image_grid2world=None, input_spacing=None, sigma_factor=0.2, mask0=False)¶ Bases:
object
Methods
get_affine
(level)Voxeltospace transformation at a given level get_affine_inv
(level)Spacetovoxel transformation at a given level get_domain_shape
(level)Shape the subsampled image must have at a particular level get_expand_factors
(from_level, to_level)Ratio of voxel size from pyramid level from_level to to_level get_image
(level)Smoothed image at a given level get_scaling
(level)Adjustment factor for inputspacing to reflect voxel sizes at level get_sigmas
(level)Smoothing parameters used at a given level get_spacing
(level)Spacings the subsampled image must have at a particular level print_level
(level)Prints properties of a pyramid level 
__init__
(image, num_levels, image_grid2world=None, input_spacing=None, sigma_factor=0.2, mask0=False)¶ ScaleSpace
Computes the Scale Space representation of an image. The scale space is simply a list of images produced by smoothing the input image with a Gaussian kernel with increasing smoothing parameter. If the image’s voxels are isotropic, the smoothing will be the same along all directions: at level L = 0, 1, …, the sigma is given by \(s * ( 2^L  1 )\). If the voxel dimensions are not isotropic, then the smoothing is weaker along low resolution directions.
Parameters:  image : array, shape (r,c) or (s, r, c) where s is the number of
slices, r is the number of rows and c is the number of columns of the input image.
 num_levels : int
the desired number of levels (resolutions) of the scale space
 image_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtospace transform of the image grid. The default is the identity matrix
 input_spacing : array, shape (dim,), optional
the spacing (voxel size) between voxels in physical space. The default is 1.0 along all axes
 sigma_factor : float, optional
the smoothing factor to be used in the construction of the scale space. The default is 0.2
 mask0 : Boolean, optional
if True, all smoothed images will be zero at all voxels that are zero in the input image. The default is False.

get_affine
(level)¶ Voxeltospace transformation at a given level
Returns the voxeltospace transformation associated with the subsampled image at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get affine transform from
Returns:  the affine (voxeltospace) transform at the requested resolution
or None if an invalid level was requested

get_affine_inv
(level)¶ Spacetovoxel transformation at a given level
Returns the spacetovoxel transformation associated with the subsampled image at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the inverse transform from
Returns:  the inverse (spacetovoxel) transform at the requested resolution or
 None if an invalid level was requested

get_domain_shape
(level)¶ Shape the subsampled image must have at a particular level
Returns the shape the subsampled image must have at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the subsampled shape from
Returns:  the subsampled shape at the requested resolution or None if an
invalid level was requested

get_expand_factors
(from_level, to_level)¶ Ratio of voxel size from pyramid level from_level to to_level
Given two scale space resolutions a = from_level, b = to_level, returns the ratio of voxels size at level b to voxel size at level a (the factor that must be used to multiply voxels at level a to ‘expand’ them to level b).
Parameters:  from_level : int, 0 <= from_level < L, (L = number of resolutions)
the resolution to expand voxels from
 to_level : int, 0 <= to_level < from_level
the resolution to expand voxels to
Returns:  factors : array, shape (k,), k = 2, 3
the expand factors (a scalar for each voxel dimension)

get_image
(level)¶ Smoothed image at a given level
Returns the smoothed image at the requested level in the Scale Space.
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smooth image from
Returns:  the smooth image at the requested resolution or None if an invalid
level was requested

get_scaling
(level)¶ Adjustment factor for inputspacing to reflect voxel sizes at level
Returns the scaling factor that needs to be applied to the input spacing (the voxel sizes of the image at level 0 of the scale space) to transform them to voxel sizes at the requested level.
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the scalings from
Returns:  the scaling factors from the original spacing to the spacings at the
 requested level

get_sigmas
(level)¶ Smoothing parameters used at a given level
Returns the smoothing parameters (a scalar for each axis) used at the requested level of the scale space
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smoothing parameters from
Returns:  the smoothing parameters at the requested level

get_spacing
(level)¶ Spacings the subsampled image must have at a particular level
Returns the spacings (voxel sizes) the subsampled image must have at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the subsampled shape from
Returns:  the spacings (voxel sizes) at the requested resolution or None if an
 invalid level was requested

print_level
(level)¶ Prints properties of a pyramid level
Prints the properties of a level of this scale space to standard output
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to be printed

SymmetricDiffeomorphicRegistration
¶

class
dipy.align.imwarp.
SymmetricDiffeomorphicRegistration
(metric, level_iters=None, step_length=0.25, ss_sigma_factor=0.2, opt_tol=1e05, inv_iter=20, inv_tol=0.001, callback=None)¶ Bases:
dipy.align.imwarp.DiffeomorphicRegistration
Methods
get_map
()Returns the resulting diffeomorphic map Returns the DiffeomorphicMap registering the moving image towards the static image. optimize
(static, moving[, …])Starts the optimization set_level_iters
(level_iters)Sets the number of iterations at each pyramid level update
(current_displacement, …)Composition of the current displacement field with the given field 
__init__
(metric, level_iters=None, step_length=0.25, ss_sigma_factor=0.2, opt_tol=1e05, inv_iter=20, inv_tol=0.001, callback=None)¶ Symmetric Diffeomorphic Registration (SyN) Algorithm
Performs the multiresolution optimization algorithm for nonlinear registration using a given similarity metric.
Parameters:  metric : SimilarityMetric object
the metric to be optimized
 level_iters : list of int
the number of iterations at each level of the Gaussian Pyramid (the length of the list defines the number of pyramid levels to be used)
 opt_tol : float
the optimization will stop when the estimated derivative of the energy profile w.r.t. time falls below this threshold
 inv_iter : int
the number of iterations to be performed by the displacement field inversion algorithm
 step_length : float
the length of the maximum displacement vector of the update displacement field at each iteration
 ss_sigma_factor : float
parameter of the scalespace smoothing kernel. For example, the std. dev. of the kernel will be factor*(2^i) in the isotropic case where i = 0, 1, …, n_scales is the scale
 inv_tol : float
the displacement field inversion algorithm will stop iterating when the inversion error falls below this threshold
 callback : function(SymmetricDiffeomorphicRegistration)
a function receiving a SymmetricDiffeomorphicRegistration object to be called after each iteration (this optimizer will call this function passing self as parameter)

get_map
()¶ Returns the resulting diffeomorphic map Returns the DiffeomorphicMap registering the moving image towards the static image.

optimize
(static, moving, static_grid2world=None, moving_grid2world=None, prealign=None)¶ Starts the optimization
Parameters:  static : array, shape (S, R, C) or (R, C)
the image to be used as reference during optimization. The displacement fields will have the same discretization as the static image.
 moving : array, shape (S, R, C) or (R, C)
the image to be used as “moving” during optimization. Since the deformation fields’ discretization is the same as the static image, it is necessary to prealign the moving image to ensure its domain lies inside the domain of the deformation fields. This is assumed to be accomplished by “prealigning” the moving image towards the static using an affine transformation given by the ‘prealign’ matrix
 static_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation associated to the static image
 moving_grid2world : array, shape (dim+1, dim+1)
the voxeltospace transformation associated to the moving image
 prealign : array, shape (dim+1, dim+1)
the affine transformation (operating on the physical space) prealigning the moving image towards the static
Returns:  static_to_ref : DiffeomorphicMap object
the diffeomorphic map that brings the moving image towards the static one in the forward direction (i.e. by calling static_to_ref.transform) and the static image towards the moving one in the backward direction (i.e. by calling static_to_ref.transform_inverse).

update
(current_displacement, new_displacement, disp_world2grid, time_scaling)¶ Composition of the current displacement field with the given field
Interpolates new displacement at the locations defined by current_displacement. Equivalently, computes the composition C of the given displacement fields as C(x) = B(A(x)), where A is current_displacement and B is new_displacement. This function is intended to be used with deformation fields of the same sampling (e.g. to be called by a registration algorithm).
Parameters:  current_displacement : array, shape (R’, C’, 2) or (S’, R’, C’, 3)
the displacement field defining where to interpolate new_displacement
 new_displacement : array, shape (R, C, 2) or (S, R, C, 3)
the displacement field to be warped by current_displacement
 disp_world2grid : array, shape (dim+1, dim+1)
the spacetogrid transform associated with the displacements’ grid (we assume that both displacements are discretized over the same grid)
 time_scaling : float
scaling factor applied to d2. The effect may be interpreted as moving d1 displacements along a factor (time_scaling) of d2.
Returns:  updated : array, shape (the same as new_displacement)
the warped displacement field
 mean_norm : the mean norm of all vectors in current_displacement

get_direction_and_spacings¶

dipy.align.imwarp.
get_direction_and_spacings
(affine, dim)¶ Extracts the rotational and spacing components from a matrix
Extracts the rotational and spacing (voxel dimensions) components from a matrix. An image gradient represents the local variation of the image’s gray values per voxel. Since we are iterating on the physical space, we need to compute the gradients as variation per millimeter, so we need to divide each gradient’s component by the voxel size along the corresponding axis, that’s what the spacings are used for. Since the image’s gradients are oriented along the grid axes, we also need to reorient the gradients to be given in physical space coordinates.
Parameters:  affine : array, shape (k, k), k = 3, 4
the matrix transforming grid coordinates to physical space.
Returns:  direction : array, shape (k1, k1)
the rotational component of the input matrix
 spacings : array, shape (k1,)
the scaling component (voxel size) of the matrix
mult_aff¶

dipy.align.imwarp.
mult_aff
(A, B)¶ Returns the matrix product A.dot(B) considering None as the identity
Parameters:  A : array, shape (n,k)
 B : array, shape (k,m)
Returns:  The matrix product A.dot(B). If any of the input matrices is None, it is
 treated as the identity matrix. If both matrices are None, None is returned
with_metaclass¶

dipy.align.imwarp.
with_metaclass
(meta, *bases)¶ Create a base class with a metaclass.
CCMetric
¶

class
dipy.align.metrics.
CCMetric
(dim, sigma_diff=2.0, radius=4)¶ Bases:
dipy.align.metrics.SimilarityMetric
Methods
compute_backward
()Computes one step bringing the static image towards the moving. compute_forward
()Computes one step bringing the moving image towards the static. free_iteration
()Frees the resources allocated during initialization get_energy
()Numerical value assigned by this metric to the current image pair initialize_iteration
()Prepares the metric to compute one displacement field iteration. set_levels_above
(levels)Informs the metric how many pyramid levels are above the current one set_levels_below
(levels)Informs the metric how many pyramid levels are below the current one set_moving_image
(moving_image, …)Sets the moving image being compared against the static one. set_static_image
(static_image, …)Sets the static image being compared against the moving one. use_moving_image_dynamics
(…)This is called by the optimizer just after setting the moving image use_static_image_dynamics
(…)This is called by the optimizer just after setting the static image. 
__init__
(dim, sigma_diff=2.0, radius=4)¶ Normalized CrossCorrelation Similarity metric.
Parameters:  dim : int (either 2 or 3)
the dimension of the image domain
 sigma_diff : the standard deviation of the Gaussian smoothing kernel to
be applied to the update field at each iteration
 radius : int
the radius of the squared (cubic) neighborhood at each voxel to be considered to compute the cross correlation

compute_backward
()¶ Computes one step bringing the static image towards the moving.
Computes the update displacement field to be used for registration of the static image towards the moving image

compute_forward
()¶ Computes one step bringing the moving image towards the static.
Computes the update displacement field to be used for registration of the moving image towards the static image

free_iteration
()¶ Frees the resources allocated during initialization

get_energy
()¶ Numerical value assigned by this metric to the current image pair
Returns the Cross Correlation (data term) energy computed at the largest iteration

initialize_iteration
()¶ Prepares the metric to compute one displacement field iteration.
Precomputes the crosscorrelation factors for efficient computation of the gradient of the Cross Correlation w.r.t. the displacement field. It also precomputes the image gradients in the physical space by reorienting the gradients in the voxel space using the corresponding affine transformations.

EMMetric
¶

class
dipy.align.metrics.
EMMetric
(dim, smooth=1.0, inner_iter=5, q_levels=256, double_gradient=True, step_type='gauss_newton')¶ Bases:
dipy.align.metrics.SimilarityMetric
Methods
compute_backward
()Computes one step bringing the static image towards the moving. compute_demons_step
([forward_step])Demons step for EM metric compute_forward
()Computes one step bringing the reference image towards the static. compute_gauss_newton_step
([forward_step])Computes the GaussNewton energy minimization step free_iteration
()Frees the resources allocated during initialization get_energy
()The numerical value assigned by this metric to the current image pair initialize_iteration
()Prepares the metric to compute one displacement field iteration. set_levels_above
(levels)Informs the metric how many pyramid levels are above the current one set_levels_below
(levels)Informs the metric how many pyramid levels are below the current one set_moving_image
(moving_image, …)Sets the moving image being compared against the static one. set_static_image
(static_image, …)Sets the static image being compared against the moving one. use_moving_image_dynamics
(…)This is called by the optimizer just after setting the moving image. use_static_image_dynamics
(…)This is called by the optimizer just after setting the static image. 
__init__
(dim, smooth=1.0, inner_iter=5, q_levels=256, double_gradient=True, step_type='gauss_newton')¶ ExpectationMaximization Metric
Similarity metric based on the ExpectationMaximization algorithm to handle multimodal images. The transfer function is modeled as a set of hidden random variables that are estimated at each iteration of the algorithm.
Parameters:  dim : int (either 2 or 3)
the dimension of the image domain
 smooth : float
smoothness parameter, the larger the value the smoother the deformation field
 inner_iter : int
number of iterations to be performed at each level of the multi resolution GaussSeidel optimization algorithm (this is not the number of steps per Gaussian Pyramid level, that parameter must be set for the optimizer, not the metric)
 q_levels : number of quantization levels (equal to the number of hidden
variables in the EM algorithm)
 double_gradient : boolean
if True, the gradient of the expected static image under the moving modality will be added to the gradient of the moving image, similarly, the gradient of the expected moving image under the static modality will be added to the gradient of the static image.
 step_type : string (‘gauss_newton’, ‘demons’)
the optimization schedule to be used in the multiresolution GaussSeidel optimization algorithm (not used if Demons Step is selected)

compute_backward
()¶ Computes one step bringing the static image towards the moving.
Computes the update displacement field to be used for registration of the static image towards the moving image

compute_demons_step
(forward_step=True)¶ Demons step for EM metric
Parameters:  forward_step : boolean
if True, computes the Demons step in the forward direction (warping the moving towards the static image). If False, computes the backward step (warping the static image to the moving image)
Returns:  displacement : array, shape (R, C, 2) or (S, R, C, 3)
the Demons step

compute_forward
()¶ Computes one step bringing the reference image towards the static.
Computes the forward update field to register the moving image towards the static image in a gradientbased optimization algorithm

compute_gauss_newton_step
(forward_step=True)¶ Computes the GaussNewton energy minimization step
Computes the Newton step to minimize this energy, i.e., minimizes the linearized energy function with respect to the regularized displacement field (this step does not require postsmoothing, as opposed to the demons step, which does not include regularization). To accelerate convergence we use the multigrid GaussSeidel algorithm proposed by Bruhn and Weickert et al [Bruhn05]
Parameters:  forward_step : boolean
if True, computes the Newton step in the forward direction (warping the moving towards the static image). If False, computes the backward step (warping the static image to the moving image)
Returns:  displacement : array, shape (R, C, 2) or (S, R, C, 3)
the Newton step
References
 [Bruhn05] Andres Bruhn and Joachim Weickert, “Towards ultimate motion
 estimation: combining highest accuracy with realtime performance”, 10th IEEE International Conference on Computer Vision, 2005. ICCV 2005.

free_iteration
()¶ Frees the resources allocated during initialization

get_energy
()¶ The numerical value assigned by this metric to the current image pair
Returns the EM (data term) energy computed at the largest iteration

initialize_iteration
()¶ Prepares the metric to compute one displacement field iteration.
Precomputes the transfer functions (hidden random variables) and variances of the estimators. Also precomputes the gradient of both input images. Note that once the images are transformed to the opposite modality, the gradient of the transformed images can be used with the gradient of the corresponding modality in the same fashion as diffdemons does for monomodality images. If the flag self.use_double_gradient is True these gradients are averaged.

use_moving_image_dynamics
(original_moving_image, transformation)¶ This is called by the optimizer just after setting the moving image.
EMMetric takes advantage of the image dynamics by computing the current moving image mask from the original_moving_image mask (warped by nearest neighbor interpolation)
Parameters:  original_moving_image : array, shape (R, C) or (S, R, C)
the original moving image from which the current moving image was generated, the current moving image is the one that was provided via ‘set_moving_image(…)’, which may not be the same as the original moving image but a warped version of it.
 transformation : DiffeomorphicMap object
the transformation that was applied to the original_moving_image to generate the current moving image

use_static_image_dynamics
(original_static_image, transformation)¶ This is called by the optimizer just after setting the static image.
EMMetric takes advantage of the image dynamics by computing the current static image mask from the originalstaticImage mask (warped by nearest neighbor interpolation)
Parameters:  original_static_image : array, shape (R, C) or (S, R, C)
the original static image from which the current static image was generated, the current static image is the one that was provided via ‘set_static_image(…)’, which may not be the same as the original static image but a warped version of it (even the static image changes during Symmetric Normalization, not only the moving one).
 transformation : DiffeomorphicMap object
the transformation that was applied to the original_static_image to generate the current static image

SSDMetric
¶

class
dipy.align.metrics.
SSDMetric
(dim, smooth=4, inner_iter=10, step_type='demons')¶ Bases:
dipy.align.metrics.SimilarityMetric
Methods
compute_backward
()Computes one step bringing the static image towards the moving. compute_demons_step
([forward_step])Demons step for SSD metric compute_forward
()Computes one step bringing the reference image towards the static. compute_gauss_newton_step
([forward_step])Computes the GaussNewton energy minimization step free_iteration
()Nothing to free for the SSD metric get_energy
()The numerical value assigned by this metric to the current image pair initialize_iteration
()Prepares the metric to compute one displacement field iteration. set_levels_above
(levels)Informs the metric how many pyramid levels are above the current one set_levels_below
(levels)Informs the metric how many pyramid levels are below the current one set_moving_image
(moving_image, …)Sets the moving image being compared against the static one. set_static_image
(static_image, …)Sets the static image being compared against the moving one. use_moving_image_dynamics
(…)This is called by the optimizer just after setting the moving image use_static_image_dynamics
(…)This is called by the optimizer just after setting the static image. 
__init__
(dim, smooth=4, inner_iter=10, step_type='demons')¶ Sum of Squared Differences (SSD) Metric
Similarity metric for (monomodal) nonlinear image registration defined by the sum of squared differences (SSD)
Parameters:  dim : int (either 2 or 3)
the dimension of the image domain
 smooth : float
smoothness parameter, the larger the value the smoother the deformation field
 inner_iter : int
number of iterations to be performed at each level of the multi resolution GaussSeidel optimization algorithm (this is not the number of steps per Gaussian Pyramid level, that parameter must be set for the optimizer, not the metric)
 step_type : string
the displacement field step to be computed when ‘compute_forward’ and ‘compute_backward’ are called. Either ‘demons’ or ‘gauss_newton’

compute_backward
()¶ Computes one step bringing the static image towards the moving.
Computes the update displacement field to be used for registration of the static image towards the moving image

compute_demons_step
(forward_step=True)¶ Demons step for SSD metric
Computes the demons step proposed by Vercauteren et al.[Vercauteren09] for the SSD metric.
Parameters:  forward_step : boolean
if True, computes the Demons step in the forward direction (warping the moving towards the static image). If False, computes the backward step (warping the static image to the moving image)
Returns:  displacement : array, shape (R, C, 2) or (S, R, C, 3)
the Demons step
References
 [Vercauteren09] Tom Vercauteren, Xavier Pennec, Aymeric Perchant,
 Nicholas Ayache, “Diffeomorphic Demons: Efficient Nonparametric Image Registration”, Neuroimage 2009

compute_forward
()¶ Computes one step bringing the reference image towards the static.
Computes the update displacement field to be used for registration of the moving image towards the static image

compute_gauss_newton_step
(forward_step=True)¶ Computes the GaussNewton energy minimization step
Minimizes the linearized energy function (Newton step) defined by the sum of squared differences of corresponding pixels of the input images with respect to the displacement field.
Parameters:  forward_step : boolean
if True, computes the Newton step in the forward direction (warping the moving towards the static image). If False, computes the backward step (warping the static image to the moving image)
Returns:  displacement : array, shape = static_image.shape + (3,)
if forward_step==True, the forward SSD GaussNewton step, else, the backward step

free_iteration
()¶ Nothing to free for the SSD metric

get_energy
()¶ The numerical value assigned by this metric to the current image pair
Returns the Sum of Squared Differences (data term) energy computed at the largest iteration

initialize_iteration
()¶ Prepares the metric to compute one displacement field iteration.
Precomputes the gradient of the input images to be used in the computation of the forward and backward steps.

SimilarityMetric
¶

class
dipy.align.metrics.
SimilarityMetric
(dim)¶ Bases:
abc.NewBase
Methods
compute_backward
()Computes one step bringing the static image towards the moving. compute_forward
()Computes one step bringing the reference image towards the static. free_iteration
()Releases the resources no longer needed by the metric get_energy
()Numerical value assigned by this metric to the current image pair initialize_iteration
()Prepares the metric to compute one displacement field iteration. set_levels_above
(levels)Informs the metric how many pyramid levels are above the current one set_levels_below
(levels)Informs the metric how many pyramid levels are below the current one set_moving_image
(moving_image, …)Sets the moving image being compared against the static one. set_static_image
(static_image, …)Sets the static image being compared against the moving one. use_moving_image_dynamics
(…)This is called by the optimizer just after setting the moving image use_static_image_dynamics
(…)This is called by the optimizer just after setting the static image. 
__init__
(dim)¶ Similarity Metric abstract class
A similarity metric is in charge of keeping track of the numerical value of the similarity (or distance) between the two given images. It also computes the update field for the forward and inverse displacement fields to be used in a gradientbased optimization algorithm. Note that this metric does not depend on any transformation (affine or nonlinear) so it assumes the static and moving images are already warped
Parameters:  dim : int (either 2 or 3)
the dimension of the image domain

compute_backward
()¶ Computes one step bringing the static image towards the moving.
Computes the backward update field to register the static image towards the moving image in a gradientbased optimization algorithm

compute_forward
()¶ Computes one step bringing the reference image towards the static.
Computes the forward update field to register the moving image towards the static image in a gradientbased optimization algorithm

free_iteration
()¶ Releases the resources no longer needed by the metric
This method is called by the RegistrationOptimizer after the required iterations have been computed (forward and / or backward) so that the SimilarityMetric can safely delete any data it computed as part of the initialization

get_energy
()¶ Numerical value assigned by this metric to the current image pair
Must return the numeric value of the similarity between the given static and moving images

initialize_iteration
()¶ Prepares the metric to compute one displacement field iteration.
This method will be called before any compute_forward or compute_backward call, this allows the Metric to precompute any useful information for speeding up the update computations. This initialization was needed in ANTS because the updates are called once per voxel. In Python this is unpractical, though.

set_levels_above
(levels)¶ Informs the metric how many pyramid levels are above the current one
Informs this metric the number of pyramid levels above the current one. The metric may change its behavior (e.g. number of inner iterations) accordingly
Parameters:  levels : int
the number of levels above the current Gaussian Pyramid level

set_levels_below
(levels)¶ Informs the metric how many pyramid levels are below the current one
Informs this metric the number of pyramid levels below the current one. The metric may change its behavior (e.g. number of inner iterations) accordingly
Parameters:  levels : int
the number of levels below the current Gaussian Pyramid level

set_moving_image
(moving_image, moving_affine, moving_spacing, moving_direction)¶ Sets the moving image being compared against the static one.
Sets the moving image. The default behavior (of this abstract class) is simply to assign the reference to an attribute, but generalizations of the metric may need to perform other operations
Parameters:  moving_image : array, shape (R, C) or (S, R, C)
the moving image

set_static_image
(static_image, static_affine, static_spacing, static_direction)¶ Sets the static image being compared against the moving one.
Sets the static image. The default behavior (of this abstract class) is simply to assign the reference to an attribute, but generalizations of the metric may need to perform other operations
Parameters:  static_image : array, shape (R, C) or (S, R, C)
the static image

use_moving_image_dynamics
(original_moving_image, transformation)¶ This is called by the optimizer just after setting the moving image
This method allows the metric to compute any useful information from knowing how the current static image was generated (as the transformation of an original static image). This method is called by the optimizer just after it sets the static image. Transformation will be an instance of DiffeomorficMap or None if the original_moving_image equals self.moving_image.
Parameters:  original_moving_image : array, shape (R, C) or (S, R, C)
original image from which the current moving image was generated
 transformation : DiffeomorphicMap object
the transformation that was applied to original image to generate the current moving image

use_static_image_dynamics
(original_static_image, transformation)¶ This is called by the optimizer just after setting the static image.
This method allows the metric to compute any useful information from knowing how the current static image was generated (as the transformation of an original static image). This method is called by the optimizer just after it sets the static image. Transformation will be an instance of DiffeomorficMap or None if the original_static_image equals self.moving_image.
Parameters:  original_static_image : array, shape (R, C) or (S, R, C)
original image from which the current static image was generated
 transformation : DiffeomorphicMap object
the transformation that was applied to original image to generate the current static image

gradient¶

dipy.align.metrics.
gradient
(f, *varargs, **kwargs)¶ Return the gradient of an Ndimensional array.
The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate onesides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array.
Parameters:  f : array_like
An Ndimensional array containing samples of a scalar function.
 varargs : list of scalar or array, optional
Spacing between f values. Default unitary spacing for all dimensions. Spacing can be specified using:
 single scalar to specify a sample distance for all dimensions.
 N scalars to specify a constant sample distance for each dimension. i.e. dx, dy, dz, …
 N arrays to specify the coordinates of the values along each dimension of F. The length of the array must match the size of the corresponding dimension
 Any combination of N scalars/arrays with the meaning of 2. and 3.
If axis is given, the number of varargs must equal the number of axes. Default: 1.
 edge_order : {1, 2}, optional
Gradient is calculated using Nth order accurate differences at the boundaries. Default: 1.
New in version 1.9.1.
 axis : None or int or tuple of ints, optional
Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array. axis may be negative, in which case it counts from the last to the first axis.
New in version 1.11.0.
Returns:  gradient : ndarray or list of ndarray
A set of ndarrays (or a single ndarray if there is only one dimension) corresponding to the derivatives of f with respect to each dimension. Each derivative has the same shape as f.
Notes
Assuming that \(f\in C^{3}\) (i.e., \(f\) has at least 3 continuous derivatives) and let \(h_{*}\) be a nonhomogeneous stepsize, we minimize the “consistency error” \(\eta_{i}\) between the true gradient and its estimate from a linear combination of the neighboring gridpoints:
\[\eta_{i} = f_{i}^{\left(1\right)}  \left[ \alpha f\left(x_{i}\right) + \beta f\left(x_{i} + h_{d}\right) + \gamma f\left(x_{i}h_{s}\right) \right]\]By substituting \(f(x_{i} + h_{d})\) and \(f(x_{i}  h_{s})\) with their Taylor series expansion, this translates into solving the following the linear system:
\[\begin{split}\left\{ \begin{array}{r} \alpha+\beta+\gamma=0 \\ \beta h_{d}\gamma h_{s}=1 \\ \beta h_{d}^{2}+\gamma h_{s}^{2}=0 \end{array} \right.\end{split}\]The resulting approximation of \(f_{i}^{(1)}\) is the following:
\[\hat f_{i}^{(1)} = \frac{ h_{s}^{2}f\left(x_{i} + h_{d}\right) + \left(h_{d}^{2}  h_{s}^{2}\right)f\left(x_{i}\right)  h_{d}^{2}f\left(x_{i}h_{s}\right)} { h_{s}h_{d}\left(h_{d} + h_{s}\right)} + \mathcal{O}\left(\frac{h_{d}h_{s}^{2} + h_{s}h_{d}^{2}}{h_{d} + h_{s}}\right)\]It is worth noting that if \(h_{s}=h_{d}\) (i.e., data are evenly spaced) we find the standard second order approximation:
\[\hat f_{i}^{(1)}= \frac{f\left(x_{i+1}\right)  f\left(x_{i1}\right)}{2h} + \mathcal{O}\left(h^{2}\right)\]With a similar procedure the forward/backward approximations used for boundaries can be derived.
References
[1] Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics (Texts in Applied Mathematics). New York: Springer. [2] Durran D. R. (1999) Numerical Methods for Wave Equations in Geophysical Fluid Dynamics. New York: Springer. [3] Fornberg B. (1988) Generation of Finite Difference Formulas on Arbitrarily Spaced Grids, Mathematics of Computation 51, no. 184 : 699706. PDF. Examples
>>> f = np.array([1, 2, 4, 7, 11, 16], dtype=float) >>> np.gradient(f) array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ]) >>> np.gradient(f, 2) array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
Spacing can be also specified with an array that represents the coordinates of the values F along the dimensions. For instance a uniform spacing:
>>> x = np.arange(f.size) >>> np.gradient(f, x) array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
Or a non uniform one:
>>> x = np.array([0., 1., 1.5, 3.5, 4., 6.], dtype=float) >>> np.gradient(f, x) array([ 1. , 3. , 3.5, 6.7, 6.9, 2.5])
For two dimensional arrays, the return will be two arrays ordered by axis. In this example the first array stands for the gradient in rows and the second one in columns direction:
>>> np.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. ]])]
In this example the spacing is also specified: uniform for axis=0 and non uniform for axis=1
>>> dx = 2. >>> y = [1., 1.5, 3.5] >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), dx, y) [array([[ 1. , 1. , 0.5], [ 1. , 1. , 0.5]]), array([[ 2. , 2. , 2. ], [ 2. , 1.7, 0.5]])]
It is possible to specify how boundaries are treated using edge_order
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([ 1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
The axis keyword can be used to specify a subset of axes of which the gradient is calculated
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), axis=0) array([[ 2., 2., 1.], [ 2., 2., 1.]])
v_cycle_2d¶

dipy.align.metrics.
v_cycle_2d
(n, k, delta_field, sigma_sq_field, gradient_field, target, lambda_param, displacement, depth=0)¶ Multiresolution GaussSeidel solver using Vtype cycles
Multiresolution GaussSeidel solver: solves the GaussNewton linear system by first filtering (GSiterate) the current level, then solves for the residual at a coarser resolution and finally refines the solution at the current resolution. This scheme corresponds to the Vcycle proposed by Bruhn and Weickert[Bruhn05].
Parameters:  n : int
number of levels of the multiresolution algorithm (it will be called recursively until level n == 0)
 k : int
the number of iterations at each multiresolution level
 delta_field : array, shape (R, C)
the difference between the static and moving image (the ‘derivative w.r.t. time’ in the optical flow model)
 sigma_sq_field : array, shape (R, C)
the variance of the gray level value at each voxel, according to the EM model (for SSD, it is 1 for all voxels). Inf and 0 values are processed specially to support infinite and zero variance.
 gradient_field : array, shape (R, C, 2)
the gradient of the moving image
 target : array, shape (R, C, 2)
righthand side of the linear system to be solved in the Weickert’s multiresolution algorithm
 lambda_param : float
smoothness parameter, the larger its value the smoother the displacement field
 displacement : array, shape (R, C, 2)
the displacement field to start the optimization from
Returns:  energy : the energy of the EM (or SSD if sigmafield[…]==1) metric at this
iteration
References
 [Bruhn05] Andres Bruhn and Joachim Weickert, “Towards ultimate motion
 estimation: combining highest accuracy with realtime performance”, 10th IEEE International Conference on Computer Vision, 2005. ICCV 2005.
v_cycle_3d¶

dipy.align.metrics.
v_cycle_3d
(n, k, delta_field, sigma_sq_field, gradient_field, target, lambda_param, displacement, depth=0)¶ Multiresolution GaussSeidel solver using Vtype cycles
Multiresolution GaussSeidel solver: solves the linear system by first filtering (GSiterate) the current level, then solves for the residual at a coarser resolution and finally refines the solution at the current resolution. This scheme corresponds to the Vcycle proposed by Bruhn and Weickert[1]. [1] Andres Bruhn and Joachim Weickert, “Towards ultimate motion estimation:
combining highest accuracy with realtime performance”, 10th IEEE International Conference on Computer Vision, 2005. ICCV 2005.Parameters:  n : int
number of levels of the multiresolution algorithm (it will be called recursively until level n == 0)
 k : int
the number of iterations at each multiresolution level
 delta_field : array, shape (S, R, C)
the difference between the static and moving image (the ‘derivative w.r.t. time’ in the optical flow model)
 sigma_sq_field : array, shape (S, R, C)
the variance of the gray level value at each voxel, according to the EM model (for SSD, it is 1 for all voxels). Inf and 0 values are processed specially to support infinite and zero variance.
 gradient_field : array, shape (S, R, C, 3)
the gradient of the moving image
 target : array, shape (S, R, C, 3)
righthand side of the linear system to be solved in the Weickert’s multiresolution algorithm
 lambda_param : float
smoothness parameter, the larger its value the smoother the displacement field
 displacement : array, shape (S, R, C, 3)
the displacement field to start the optimization from
Returns:  energy : the energy of the EM (or SSD if sigmafield[…]==1) metric at this
iteration
with_metaclass¶

dipy.align.metrics.
with_metaclass
(meta, *bases)¶ Create a base class with a metaclass.
Pool¶

dipy.align.reslice.
Pool
(processes=None, initializer=None, initargs=(), maxtasksperchild=None)¶ Returns a process pool object
affine_transform¶

dipy.align.reslice.
affine_transform
(input, matrix, offset=0.0, output_shape=None, output=None, order=3, mode='constant', cval=0.0, prefilter=True)¶ Apply an affine transformation.
Given an output image pixel index vector
o
, the pixel value is determined from the input image at positionnp.dot(matrix, o) + offset
.Parameters:  input : array_like
The input array.
 matrix : ndarray
The inverse coordinate transformation matrix, mapping output coordinates to input coordinates. If
ndim
is the number of dimensions ofinput
, the given matrix must have one of the following shapes:(ndim, ndim)
: the linear transformation matrix for each output coordinate.(ndim,)
: assume that the 2D transformation matrix is diagonal, with the diagonal specified by the given value. A more efficient algorithm is then used that exploits the separability of the problem.(ndim + 1, ndim + 1)
: assume that the transformation is specified using homogeneous coordinates [1]. In this case, any value passed tooffset
is ignored.(ndim, ndim + 1)
: as above, but the bottom row of a homogeneous transformation matrix is always[0, 0, ..., 1]
, and may be omitted.
 offset : float or sequence, optional
The offset into the array where the transform is applied. If a float, offset is the same for each axis. If a sequence, offset should contain one value for each axis.
 output_shape : tuple of ints, optional
Shape tuple.
 output : array or dtype, optional
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.
 order : int, optional
The order of the spline interpolation, default is 3. The order has to be in the range 05.
 mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional
The mode parameter determines how the input array is extended when the filter overlaps a border. Default is ‘reflect’. Behavior for each valid value is as follows:
 ‘reflect’ (d c b a  a b c d  d c b a)
The input is extended by reflecting about the edge of the last pixel.
 ‘constant’ (k k k k  a b c d  k k k k)
The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter.
 ‘nearest’ (a a a a  a b c d  d d d d)
The input is extended by replicating the last pixel.
 ‘mirror’ (d c b  a b c d  c b a)
The input is extended by reflecting about the center of the last pixel.
 ‘wrap’ (a b c d  a b c d  a b c d)
The input is extended by wrapping around to the opposite edge.
 cval : scalar, optional
Value to fill past edges of input if mode is ‘constant’. Default is 0.0.
 prefilter : bool, optional
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.
Returns:  affine_transform : ndarray
The transformed input.
Notes
The given matrix and offset are used to find for each point in the output the corresponding coordinates in the input by an affine transformation. The value of the input at those coordinates is determined by spline interpolation of the requested order. Points outside the boundaries of the input are filled according to the given mode.
Changed in version 0.18.0: Previously, the exact interpretation of the affine transformation depended on whether the matrix was supplied as a onedimensional or twodimensional array. If a onedimensional array was supplied to the matrix parameter, the output pixel value at index
o
was determined from the input image at positionmatrix * (o + offset)
.References
[1] (1, 2) https://en.wikipedia.org/wiki/Homogeneous_coordinates
reslice¶

dipy.align.reslice.
reslice
(data, affine, zooms, new_zooms, order=1, mode='constant', cval=0, num_processes=1)¶ Reslice data with new voxel resolution defined by
new_zooms
Parameters:  data : array, shape (I,J,K) or (I,J,K,N)
3d volume or 4d volume with datasets
 affine : array, shape (4,4)
mapping from voxel coordinates to world coordinates
 zooms : tuple, shape (3,)
voxel size for (i,j,k) dimensions
 new_zooms : tuple, shape (3,)
new voxel size for (i,j,k) after resampling
 order : int, from 0 to 5
order of interpolation for resampling/reslicing, 0 nearest interpolation, 1 trilinear etc.. if you don’t want any smoothing 0 is the option you need.
 mode : string (‘constant’, ‘nearest’, ‘reflect’ or ‘wrap’)
Points outside the boundaries of the input are filled according to the given mode.
 cval : float
Value used for points outside the boundaries of the input if mode=’constant’.
 num_processes : int
Split the calculation to a pool of children processes. This only applies to 4D data arrays. If a positive integer then it defines the size of the multiprocessing pool that will be used. If 0, then the size of the pool will equal the number of cores available.
Returns:  data2 : array, shape (I,J,K) or (I,J,K,N)
datasets resampled into isotropic voxel size
 affine2 : array, shape (4,4)
new affine for the resampled image
Examples
>>> import nibabel as nib >>> from dipy.align.reslice import reslice >>> from dipy.data import get_fnames >>> fimg = get_fnames('aniso_vox') >>> img = nib.load(fimg) >>> data = img.get_data() >>> data.shape == (58, 58, 24) True >>> affine = img.affine >>> zooms = img.header.get_zooms()[:3] >>> zooms (4.0, 4.0, 5.0) >>> new_zooms = (3.,3.,3.) >>> new_zooms (3.0, 3.0, 3.0) >>> data2, affine2 = reslice(data, affine, zooms, new_zooms) >>> data2.shape == (77, 77, 40) True
IsotropicScaleSpace
¶

class
dipy.align.scalespace.
IsotropicScaleSpace
(image, factors, sigmas, image_grid2world=None, input_spacing=None, mask0=False)¶ Bases:
dipy.align.scalespace.ScaleSpace
Methods
get_affine
(level)Voxeltospace transformation at a given level get_affine_inv
(level)Spacetovoxel transformation at a given level get_domain_shape
(level)Shape the subsampled image must have at a particular level get_expand_factors
(from_level, to_level)Ratio of voxel size from pyramid level from_level to to_level get_image
(level)Smoothed image at a given level get_scaling
(level)Adjustment factor for inputspacing to reflect voxel sizes at level get_sigmas
(level)Smoothing parameters used at a given level get_spacing
(level)Spacings the subsampled image must have at a particular level print_level
(level)Prints properties of a pyramid level 
__init__
(image, factors, sigmas, image_grid2world=None, input_spacing=None, mask0=False)¶ IsotropicScaleSpace
Computes the Scale Space representation of an image using isotropic smoothing kernels for all scales. The scale space is simply a list of images produced by smoothing the input image with a Gaussian kernel with different smoothing parameters.
This specialization of ScaleSpace allows the user to provide custom scale and smoothing factors for all scales.
Parameters:  image : array, shape (r,c) or (s, r, c) where s is the number of
slices, r is the number of rows and c is the number of columns of the input image.
 factors : list of floats
custom scale factors to build the scale space (one factor for each scale).
 sigmas : list of floats
custom smoothing parameter to build the scale space (one parameter for each scale).
 image_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtospace transform of the image grid. The default is the identity matrix.
 input_spacing : array, shape (dim,), optional
the spacing (voxel size) between voxels in physical space. The default if 1.0 along all axes.
 mask0 : Boolean, optional
if True, all smoothed images will be zero at all voxels that are zero in the input image. The default is False.

ScaleSpace
¶

class
dipy.align.scalespace.
ScaleSpace
(image, num_levels, image_grid2world=None, input_spacing=None, sigma_factor=0.2, mask0=False)¶ Bases:
object
Methods
get_affine
(level)Voxeltospace transformation at a given level get_affine_inv
(level)Spacetovoxel transformation at a given level get_domain_shape
(level)Shape the subsampled image must have at a particular level get_expand_factors
(from_level, to_level)Ratio of voxel size from pyramid level from_level to to_level get_image
(level)Smoothed image at a given level get_scaling
(level)Adjustment factor for inputspacing to reflect voxel sizes at level get_sigmas
(level)Smoothing parameters used at a given level get_spacing
(level)Spacings the subsampled image must have at a particular level print_level
(level)Prints properties of a pyramid level 
__init__
(image, num_levels, image_grid2world=None, input_spacing=None, sigma_factor=0.2, mask0=False)¶ ScaleSpace
Computes the Scale Space representation of an image. The scale space is simply a list of images produced by smoothing the input image with a Gaussian kernel with increasing smoothing parameter. If the image’s voxels are isotropic, the smoothing will be the same along all directions: at level L = 0, 1, …, the sigma is given by \(s * ( 2^L  1 )\). If the voxel dimensions are not isotropic, then the smoothing is weaker along low resolution directions.
Parameters:  image : array, shape (r,c) or (s, r, c) where s is the number of
slices, r is the number of rows and c is the number of columns of the input image.
 num_levels : int
the desired number of levels (resolutions) of the scale space
 image_grid2world : array, shape (dim + 1, dim + 1), optional
the gridtospace transform of the image grid. The default is the identity matrix
 input_spacing : array, shape (dim,), optional
the spacing (voxel size) between voxels in physical space. The default is 1.0 along all axes
 sigma_factor : float, optional
the smoothing factor to be used in the construction of the scale space. The default is 0.2
 mask0 : Boolean, optional
if True, all smoothed images will be zero at all voxels that are zero in the input image. The default is False.

get_affine
(level)¶ Voxeltospace transformation at a given level
Returns the voxeltospace transformation associated with the subsampled image at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get affine transform from
Returns:  the affine (voxeltospace) transform at the requested resolution
or None if an invalid level was requested

get_affine_inv
(level)¶ Spacetovoxel transformation at a given level
Returns the spacetovoxel transformation associated with the subsampled image at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the inverse transform from
Returns:  the inverse (spacetovoxel) transform at the requested resolution or
 None if an invalid level was requested

get_domain_shape
(level)¶ Shape the subsampled image must have at a particular level
Returns the shape the subsampled image must have at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the subsampled shape from
Returns:  the subsampled shape at the requested resolution or None if an
invalid level was requested

get_expand_factors
(from_level, to_level)¶ Ratio of voxel size from pyramid level from_level to to_level
Given two scale space resolutions a = from_level, b = to_level, returns the ratio of voxels size at level b to voxel size at level a (the factor that must be used to multiply voxels at level a to ‘expand’ them to level b).
Parameters:  from_level : int, 0 <= from_level < L, (L = number of resolutions)
the resolution to expand voxels from
 to_level : int, 0 <= to_level < from_level
the resolution to expand voxels to
Returns:  factors : array, shape (k,), k = 2, 3
the expand factors (a scalar for each voxel dimension)

get_image
(level)¶ Smoothed image at a given level
Returns the smoothed image at the requested level in the Scale Space.
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smooth image from
Returns:  the smooth image at the requested resolution or None if an invalid
level was requested

get_scaling
(level)¶ Adjustment factor for inputspacing to reflect voxel sizes at level
Returns the scaling factor that needs to be applied to the input spacing (the voxel sizes of the image at level 0 of the scale space) to transform them to voxel sizes at the requested level.
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the scalings from
Returns:  the scaling factors from the original spacing to the spacings at the
 requested level

get_sigmas
(level)¶ Smoothing parameters used at a given level
Returns the smoothing parameters (a scalar for each axis) used at the requested level of the scale space
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smoothing parameters from
Returns:  the smoothing parameters at the requested level

get_spacing
(level)¶ Spacings the subsampled image must have at a particular level
Returns the spacings (voxel sizes) the subsampled image must have at a particular resolution of the scale space (note that this object does not explicitly subsample the smoothed images, but only provides the properties the subsampled images must have).
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the subsampled shape from
Returns:  the spacings (voxel sizes) at the requested resolution or None if an
 invalid level was requested

print_level
(level)¶ Prints properties of a pyramid level
Prints the properties of a level of this scale space to standard output
Parameters:  level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to be printed

BundleMinDistanceAsymmetricMetric
¶

class
dipy.align.streamlinear.
BundleMinDistanceAsymmetricMetric
(num_threads=None)¶ Bases:
dipy.align.streamlinear.BundleMinDistanceMetric
Asymmetric Bundlebased Minimum distance
This is a cost function that can be used by the StreamlineLinearRegistration class.
Methods
distance
(xopt)Distance calculated from this Metric setup
(static, moving)Setup static and moving sets of streamlines 
__init__
(num_threads=None)¶ An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method
distance
of this object should be minimum.Parameters:  num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.

distance
(xopt)¶ Distance calculated from this Metric
Parameters:  xopt : sequence
List of affine parameters as an 1D vector

BundleMinDistanceMatrixMetric
¶

class
dipy.align.streamlinear.
BundleMinDistanceMatrixMetric
(num_threads=None)¶ Bases:
dipy.align.streamlinear.StreamlineDistanceMetric
Bundlebased Minimum Distance aka BMD
This is the cost function used by the StreamlineLinearRegistration
Notes
The difference with BundleMinDistanceMetric is that this creates the entire distance matrix and therefore requires more memory.
Methods
setup(static, moving) distance(xopt) 
__init__
(num_threads=None)¶ An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method
distance
of this object should be minimum.Parameters:  num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.

distance
(xopt)¶ Distance calculated from this Metric
Parameters:  xopt : sequence
List of affine parameters as an 1D vector

setup
(static, moving)¶ Setup static and moving sets of streamlines
Parameters:  static : streamlines
Fixed or reference set of streamlines.
 moving : streamlines
Moving streamlines.
Notes
Call this after the object is initiated and before distance.
Num_threads is not used in this class. Use
BundleMinDistanceMetric
for a faster, threaded and less memory hungry metric

BundleMinDistanceMetric
¶

class
dipy.align.streamlinear.
BundleMinDistanceMetric
(num_threads=None)¶ Bases:
dipy.align.streamlinear.StreamlineDistanceMetric
Bundlebased Minimum Distance aka BMD
This is the cost function used by the StreamlineLinearRegistration
References
[Garyfallidis14] Garyfallidis et al., “Direct nativespace fiber bundle alignment for group comparisons”, ISMRM, 2014. Methods
setup(static, moving) distance(xopt) 
__init__
(num_threads=None)¶ An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method
distance
of this object should be minimum.Parameters:  num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.

distance
(xopt)¶ Distance calculated from this Metric
Parameters:  xopt : sequence
List of affine parameters as an 1D vector,

setup
(static, moving)¶ Setup static and moving sets of streamlines
Parameters:  static : streamlines
Fixed or reference set of streamlines.
 moving : streamlines
Moving streamlines.
 num_threads : int
Number of threads. If None (default) then all available threads will be used.
Notes
Call this after the object is initiated and before distance.

BundleSumDistanceMatrixMetric
¶

class
dipy.align.streamlinear.
BundleSumDistanceMatrixMetric
(num_threads=None)¶ Bases:
dipy.align.streamlinear.BundleMinDistanceMatrixMetric
Bundlebased Sum Distance aka BMD
This is a cost function that can be used by the StreamlineLinearRegistration class.
Notes
The difference with BundleMinDistanceMatrixMetric is that it uses uses the sum of the distance matrix and not the sum of mins.
Methods
setup(static, moving) distance(xopt) 
__init__
(num_threads=None)¶ An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method
distance
of this object should be minimum.Parameters:  num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.

distance
(xopt)¶ Distance calculated from this Metric
Parameters:  xopt : sequence
List of affine parameters as an 1D vector

Optimizer
¶

class
dipy.align.streamlinear.
Optimizer
(fun, x0, args=(), method='LBFGSB', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)¶ Bases:
object
Attributes:  evolution
 fopt
 message
 nfev
 nit
 xopt
Methods
print_summary 
__init__
(fun, x0, args=(), method='LBFGSB', jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None, evolution=False)¶ A class for handling minimization of scalar function of one or more variables.
Parameters:  fun : callable
Objective function.
 x0 : ndarray
Initial guess.
 args : tuple, optional
Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian).
 method : str, optional
Type of solver. Should be one of
 ‘NelderMead’
 ‘Powell’
 ‘CG’
 ‘BFGS’
 ‘NewtonCG’
 ‘Anneal’
 ‘LBFGSB’
 ‘TNC’
 ‘COBYLA’
 ‘SLSQP’
 ‘dogleg’
 ‘trustncg’
 jac : bool or callable, optional
Jacobian of objective function. Only for CG, BFGS, NewtonCG, dogleg, trustncg. If jac is a Boolean and is True, fun is assumed to return the value of Jacobian along with the objective function. If False, the Jacobian will be estimated numerically. jac can also be a callable returning the Jacobian of the objective. In this case, it must accept the same arguments as fun.
 hess, hessp : callable, optional
Hessian of objective function or Hessian of objective function times an arbitrary vector p. Only for NewtonCG, dogleg, trustncg. Only one of hessp or hess needs to be given. If hess is provided, then hessp will be ignored. If neither hess nor hessp is provided, then the hessian product will be approximated using finite differences on jac. hessp must compute the Hessian times an arbitrary vector.
 bounds : sequence, optional
Bounds for variables (only for LBFGSB, TNC and SLSQP).
(min, max)
pairs for each element inx
, defining the bounds on that parameter. Use None for one ofmin
ormax
when there is no bound in that direction. constraints : dict or sequence of dict, optional
Constraints definition (only for COBYLA and SLSQP). Each constraint is defined in a dictionary with fields:
 type : str
Constraint type: ‘eq’ for equality, ‘ineq’ for inequality.
 fun : callable
The function defining the constraint.
 jac : callable, optional
The Jacobian of fun (only for SLSQP).
 args : sequence, optional
Extra arguments to be passed to the function and Jacobian.
Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be nonnegative. Note that COBYLA only supports inequality constraints.
 tol : float, optional
Tolerance for termination. For detailed control, use solverspecific options.
 callback : callable, optional
Called after each iteration, as
callback(xk)
, wherexk
is the current parameter vector. Only available using Scipy >= 0.12. options : dict, optional
A dictionary of solver options. All methods accept the following generic options:
 maxiter : int
Maximum number of iterations to perform.
 disp : bool
Set to True to print convergence messages.
For methodspecific options, see show_options(‘minimize’, method).
 evolution : bool, optional
save history of x for each iteration. Only available using Scipy >= 0.12.
See also
scipy.optimize.minimize

evolution
¶

fopt
¶

message
¶

nfev
¶

nit
¶

print_summary
()¶

xopt
¶
StreamlineDistanceMetric
¶

class
dipy.align.streamlinear.
StreamlineDistanceMetric
(num_threads=None)¶ Bases:
abc.NewBase
Methods
distance
(xopt)calculate distance for current set of parameters setup 
__init__
(num_threads=None)¶ An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method
distance
of this object should be minimum.Parameters:  num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.

distance
(xopt)¶ calculate distance for current set of parameters

setup
(static, moving)¶

StreamlineLinearRegistration
¶

class
dipy.align.streamlinear.
StreamlineLinearRegistration
(metric=None, x0='rigid', method='LBFGSB', bounds=None, verbose=False, options=None, evolution=False, num_threads=None)¶ Bases:
object
Methods
optimize
(static, moving[, mat])Find the minimum of the provided metric. 
__init__
(metric=None, x0='rigid', method='LBFGSB', bounds=None, verbose=False, options=None, evolution=False, num_threads=None)¶ Linear registration of 2 sets of streamlines [Garyfallidis15].
Parameters:  metric : StreamlineDistanceMetric,
If None and fast is False then the BMD distance is used. If fast is True then a faster implementation of BMD is used. Otherwise, use the given distance metric.
 x0 : array or int or str
Initial parametrization for the optimization.
 If 1D array with:
a) 6 elements then only rigid registration is performed with the 3 first elements for translation and 3 for rotation. b) 7 elements also isotropic scaling is performed (similarity). c) 12 elements then translation, rotation (in degrees), scaling and shearing is performed (affine).
Here is an example of x0 with 12 elements:
x0=np.array([0, 10, 0, 40, 0, 0, 2., 1.5, 1, 0.1, 0.5, 0])
This has translation (0, 10, 0), rotation (40, 0, 0) in degrees, scaling (2., 1.5, 1) and shearing (0.1, 0.5, 0).
 If int:
 6
x0 = np.array([0, 0, 0, 0, 0, 0])
 7
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
 12
x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
 If str:
 “rigid”
x0 = np.array([0, 0, 0, 0, 0, 0])
 “similarity”
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
 “affine”
x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
 method : str,
‘L_BFGS_B’ or ‘Powell’ optimizers can be used. Default is ‘L_BFGS_B’.
 bounds : list of tuples or None,
If method == ‘L_BFGS_B’ then we can use bounded optimization. For example for the six parameters of rigid rotation we can set the bounds = [(30, 30), (30, 30), (30, 30),
(45, 45), (45, 45), (45, 45)]
That means that we have set the bounds for the three translations and three rotation axes (in degrees).
 verbose : bool,
If True then information about the optimization is shown.
 options : None or dict,
Extra options to be used with the selected method.
 evolution : boolean
If True save the transformation for each iteration of the optimizer. Default is False. Supported only with Scipy >= 0.11.
 num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.
References
[Garyfallidis15] (1, 2) Garyfallidis et al. “Robust and efficient linear registration of whitematter fascicles in the space of streamlines”, NeuroImage, 117, 124–140, 2015 [Garyfallidis14] Garyfallidis et al., “Direct nativespace fiber bundle alignment for group comparisons”, ISMRM, 2014. [Garyfallidis17] Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017.

optimize
(static, moving, mat=None)¶ Find the minimum of the provided metric.
Parameters:  static : streamlines
Reference or fixed set of streamlines.
 moving : streamlines
Moving set of streamlines.
 mat : array
Transformation (4, 4) matrix to start the registration.
mat
is applied to moving. Default value None which means that initial transformation will be generated by shifting the centers of moving and static sets of streamlines to the origin.
Returns:  map : StreamlineRegistrationMap

StreamlineRegistrationMap
¶

class
dipy.align.streamlinear.
StreamlineRegistrationMap
(matopt, xopt, fopt, matopt_history, funcs, iterations)¶ Bases:
object
Methods
transform
(moving)Transform moving streamlines to the static. 
__init__
(matopt, xopt, fopt, matopt_history, funcs, iterations)¶ A map holding the optimum affine matrix and some other parameters of the optimization
Parameters:  matrix : array,
4x4 affine matrix which transforms the moving to the static streamlines
 xopt : array,
1d array with the parameters of the transformation after centering
 fopt : float,
final value of the metric
 matrix_history : array
All transformation matrices created during the optimization
 funcs : int,
Number of function evaluations of the optimizer
 iterations : int
Number of iterations of the optimizer

transform
(moving)¶ Transform moving streamlines to the static.
Parameters:  moving : streamlines
Returns:  moved : streamlines
Notes
All this does is apply
self.matrix
to the input streamlines.

Streamlines
¶

dipy.align.streamlinear.
Streamlines
¶ alias of
nibabel.streamlines.array_sequence.ArraySequence
bundle_min_distance¶

dipy.align.streamlinear.
bundle_min_distance
(t, static, moving)¶ MDFbased pairwise distance optimization function (MIN)
We minimize the distance between moving streamlines as they align with the static streamlines.
Parameters:  t : ndarray
t is a vector of of affine transformation parameters with size at least 6. If size is 6, t is interpreted as translation + rotation. If size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
 static : list
Static streamlines
 moving : list
Moving streamlines.
 num_threads : int
Number of threads. If None (default) then all available threads will be used.
Returns:  cost: float
bundle_min_distance_asymmetric_fast¶

dipy.align.streamlinear.
bundle_min_distance_asymmetric_fast
(t, static, moving, block_size)¶ MDFbased pairwise distance optimization function (MIN)
We minimize the distance between moving streamlines as they align with the static streamlines.
Parameters:  t : array
1D array. t is a vector of of affine transformation parameters with size at least 6. If size is 6, t is interpreted as translation + rotation. If size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
 static : array
N*M x 3 array. All the points of the static streamlines. With order of streamlines intact. Where N is the number of streamlines and M is the number of points per streamline.
 moving : array
K*M x 3 array. All the points of the moving streamlines. With order of streamlines intact. Where K is the number of streamlines and M is the number of points per streamline.
 block_size : int
Number of points per streamline. All streamlines in static and moving should have the same number of points M.
Returns:  cost: float
bundle_min_distance_fast¶

dipy.align.streamlinear.
bundle_min_distance_fast
(t, static, moving, block_size, num_threads)¶ MDFbased pairwise distance optimization function (MIN)
We minimize the distance between moving streamlines as they align with the static streamlines.
Parameters:  t : array
1D array. t is a vector of of affine transformation parameters with size at least 6. If size is 6, t is interpreted as translation + rotation. If size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
 static : array
N*M x 3 array. All the points of the static streamlines. With order of streamlines intact. Where N is the number of streamlines and M is the number of points per streamline.
 moving : array
K*M x 3 array. All the points of the moving streamlines. With order of streamlines intact. Where K is the number of streamlines and M is the number of points per streamline.
 block_size : int
Number of points per streamline. All streamlines in static and moving should have the same number of points M.
 num_threads : int
Number of threads. If None (default) then all available threads will be used.
Returns:  cost: float
Notes
This is a faster implementation of
bundle_min_distance
, which requires that all the points of each streamline are allocated into an ndarray (of shape N*M by 3, with N the number of points per streamline and M the number of streamlines). This can be done by calling dipy.tracking.streamlines.unlist_streamlines.
bundle_sum_distance¶

dipy.align.streamlinear.
bundle_sum_distance
(t, static, moving, num_threads=None)¶ MDF distance optimization function (SUM)
We minimize the distance between moving streamlines as they align with the static streamlines.
Parameters:  t : ndarray
t is a vector of of affine transformation parameters with size at least 6. If size is 6, t is interpreted as translation + rotation. If size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
 static : list
Static streamlines
 moving : list
Moving streamlines. These will be transform to align with the static streamlines
Returns:  cost: float
center_streamlines¶

dipy.align.streamlinear.
center_streamlines
(streamlines)¶ Move streamlines to the origin
Parameters:  streamlines : list
List of 2D ndarrays of shape[1]==3
Returns:  new_streamlines : list
List of 2D ndarrays of shape[1]==3
 inv_shift : ndarray
Translation in x,y,z to go back in the initial position
compose_matrix¶

dipy.align.streamlinear.
compose_matrix
(scale=None, shear=None, angles=None, translate=None, perspective=None)¶ Return 4x4 transformation matrix from sequence of transformations.
Code modified from the work of Christoph Gohlke link provided here http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
This is the inverse of the
decompose_matrix
function.Parameters:  scale : (3,) array_like
Scaling factors.
 shear : array_like
Shear factors for xy, xz, yz axes.
 angles : array_like
Euler angles about static x, y, z axes.
 translate : array_like
Translation vector along x, y, z axes.
 perspective : array_like
Perspective partition of matrix.
Returns:  matrix : 4x4 array
Examples
>>> import math >>> import numpy as np >>> import dipy.core.geometry as gm >>> scale = np.random.random(3)  0.5 >>> shear = np.random.random(3)  0.5 >>> angles = (np.random.random(3)  0.5) * (2*math.pi) >>> trans = np.random.random(3)  0.5 >>> persp = np.random.random(4)  0.5 >>> M0 = gm.compose_matrix(scale, shear, angles, trans, persp)
compose_matrix44¶

dipy.align.streamlinear.
compose_matrix44
(t, dtype=<class 'numpy.float64'>)¶ Compose a 4x4 transformation matrix
Parameters:  t : ndarray
This is a 1D vector of of affine transformation parameters with size at least 3. If size is 3, t is interpreted as translation. If size is 6, t is interpreted as translation + rotation. If size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 9, t is interpreted as translation + rotation + anisotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
Returns:  T : ndarray
Homogeneous transformation matrix of size 4x4.
compose_transformations¶

dipy.align.streamlinear.
compose_transformations
(*mats)¶ Compose multiple 4x4 affine transformations in one 4x4 matrix
Parameters:  mat1 : array, (4, 4)
 mat2 : array, (4, 4)
 …
 matN : array, (4, 4)
Returns:  matN x … x mat2 x mat1 : array, (4, 4)
decompose_matrix¶

dipy.align.streamlinear.
decompose_matrix
(matrix)¶ Return sequence of transformations from transformation matrix.
Code modified from the excellent work of Christoph Gohlke link provided here: http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
Parameters:  matrix : array_like
Nondegenerative homogeneous transformation matrix
Returns:  scale : (3,) ndarray
Three scaling factors.
 shear : (3,) ndarray
Shear factors for xy, xz, yz axes.
 angles : (3,) ndarray
Euler angles about static x, y, z axes.
 translate : (3,) ndarray
Translation vector along x, y, z axes.
 perspective : ndarray
Perspective partition of matrix.
Raises:  ValueError
If matrix is of wrong type or degenerative.
Examples
>>> import numpy as np >>> T0=np.diag([2,1,1,1]) >>> scale, shear, angles, trans, persp = decompose_matrix(T0)
decompose_matrix44¶

dipy.align.streamlinear.
decompose_matrix44
(mat, size=12)¶ Given a 4x4 homogeneous matrix return the parameter vector
Parameters:  mat : array
Homogeneous 4x4 transformation matrix
 size : int
Size of output vector. 3, for translation, 6 for rigid, 7 for similarity, 9 for scaling and 12 for affine. Default is 12.
Returns:  t : ndarray
One dimensional ndarray of 3, 6, 7, 9 or 12 affine parameters.
distance_matrix_mdf¶

dipy.align.streamlinear.
distance_matrix_mdf
()¶ Minimum direct flipped distance matrix between two streamline sets
All streamlines need to have the same number of points
Parameters:  streamlines_a : sequence
of streamlines as arrays, [(N, 3) .. (N, 3)]
 streamlines_b : sequence
of streamlines as arrays, [(N, 3) .. (N, 3)]
Returns:  DM : array, shape (len(streamlines_a), len(streamlines_b))
distance matrix
length¶

dipy.align.streamlinear.
length
()¶ Euclidean length of streamlines
Length is in mm only if streamlines are expressed in world coordinates.
Parameters:  streamlines : ndarray or a list or
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.
Returns:  lengths : scalar or ndarray shape (N,)
If there is only one streamline, a scalar representing the length of the streamline. If there are several streamlines, ndarray containing the length of every streamline.
Examples
>>> from dipy.tracking.streamline import length >>> import numpy as np >>> streamline = np.array([[1, 1, 1], [2, 3, 4], [0, 0, 0]]) >>> expected_length = np.sqrt([1+2**2+3**2, 2**2+3**2+4**2]).sum() >>> length(streamline) == expected_length True >>> streamlines = [streamline, np.vstack([streamline, streamline[::1]])] >>> expected_lengths = [expected_length, 2*expected_length] >>> lengths = [length(streamlines[0]), length(streamlines[1])] >>> np.allclose(lengths, expected_lengths) True >>> length([]) 0.0 >>> length(np.array([[1, 2, 3]])) 0.0
 streamlines : ndarray or a list or
progressive_slr¶

dipy.align.streamlinear.
progressive_slr
(static, moving, metric, x0, bounds, method='LBFGSB', verbose=True, num_threads=None)¶ Progressive SLR
This is an utility function that allows for example to do affine registration using Streamlinebased Linear Registration (SLR) [Garyfallidis15] by starting with translation first, then rigid, then similarity, scaling and finally affine.
Similarly, if for example you want to perform rigid then you start with translation first. This progressive strategy can helps with finding the optimal parameters of the final transformation.
Parameters:  static : Streamlines
 moving : Streamlines
 metric : StreamlineDistanceMetric
 x0 : string
Could be any of ‘translation’, ‘rigid’, ‘similarity’, ‘scaling’, ‘affine’
 bounds : array
Boundaries of registration parameters. See variable DEFAULT_BOUNDS for example.
 method : string
L_BFGS_B’ or ‘Powell’ optimizers can be used. Default is ‘L_BFGS_B’.
 verbose : bool
If True show messages in stdout (default True).
 num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.
References
[Garyfallidis15] (1, 2) Garyfallidis et al. “Robust and efficient linear registration of whitematter fascicles in the space of streamlines”, NeuroImage, 117, 124–140, 2015
qbx_and_merge¶

dipy.align.streamlinear.
qbx_and_merge
(streamlines, thresholds, nb_pts=20, select_randomly=None, rng=None, verbose=True)¶ Run QuickBundlesX and then run again on the centroids of the last layer
Running again QuickBundles at a layer has the effect of merging some of the clusters that maybe originally devided because of branching. This function help obtain a result at a QuickBundles quality but with QuickBundlesX speed. The merging phase has low cost because it is applied only on the centroids rather than the entire dataset.
Parameters:  streamlines : Streamlines
 thresholds : sequence
List of distance thresholds for QuickBundlesX.
 nb_pts : int
Number of points for discretizing each streamline
 select_randomly : int
Randomly select a specific number of streamlines. If None all the streamlines are used.
 rng : RandomState
If None then RandomState is initialized internally.
 verbose : bool
If True print information in stdout.
Returns:  clusters : obj
Contains the clusters of the last layer of QuickBundlesX after merging.
References
[Garyfallidis12] Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012. [Garyfallidis16] Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016.
select_random_set_of_streamlines¶

dipy.align.streamlinear.
select_random_set_of_streamlines
(streamlines, select, rng=None)¶ Select a random set of streamlines
Parameters:  streamlines : Steamlines
Object of 2D ndarrays of shape[1]==3
 select : int
Number of streamlines to select. If there are less streamlines than
select
thenselect=len(streamlines)
. rng : RandomState
Default None.
Returns:  selected_streamlines : list
Notes
The same streamline will not be selected twice.
set_number_of_points¶

dipy.align.streamlinear.
set_number_of_points
()¶  Change the number of points of streamlines
 (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.
Parameters:  streamlines : ndarray or a list or
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. nb_points : int
integer representing number of points wanted along the curve.
Returns:  new_streamlines : ndarray or a list or
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]
slr_with_qbx¶

dipy.align.streamlinear.
slr_with_qbx
(static, moving, x0='affine', rm_small_clusters=50, maxiter=100, select_random=None, verbose=False, greater_than=50, less_than=250, qbx_thr=[40, 30, 20, 15], nb_pts=20, progressive=True, rng=None, num_threads=None)¶ Utility function for registering large tractograms.
For efficiency we apply the registration on cluster centroids and remove small clusters.
Parameters:  static : Streamlines
 moving : Streamlines
 x0 : str
rigid, similarity or affine transformation model (default affine)
 rm_small_clusters : int
Remove clusters that have less than rm_small_clusters (default 50)
 select_random : int
If not None select a random number of streamlines to apply clustering Default None.
 verbose : bool,
If True then information about the optimization is shown.
 greater_than : int, optional
Keep streamlines that have length greater than this value (default 50)
 less_than : int, optional
Keep streamlines have length less than this value (default 250)
 qbx_thr : variable int
Thresholds for QuickBundlesX (default [40, 30, 20, 15])
 np_pts : int, optional
Number of points for discretizing each streamline (default 20)
 progressive : boolean, optional
(default True)
 rng : RandomState
If None creates RandomState in function.
 num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.
Notes
The order of operations is the following. First short or long streamlines are removed. Second the tractogram or a random selection of the tractogram is clustered with QuickBundles. Then SLR [Garyfallidis15] is applied.
References
[Garyfallidis15] (1, 2) Garyfallidis et al. “Robust and efficient linear registration of whitematter fascicles in the space of streamlines”, NeuroImage, 117, 124–140, 2015 .. [R778a6c20f622Garyfallidis14] Garyfallidis et al., “Direct nativespace fiber
bundle alignment for group comparisons”, ISMRM, 2014.[Garyfallidis17] Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017.
time¶

dipy.align.streamlinear.
time
() → floating point number¶ Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.
transform_streamlines¶

dipy.align.streamlinear.
transform_streamlines
(streamlines, mat, in_place=False)¶ Apply affine transformation to streamlines
Parameters:  streamlines : Streamlines
Streamlines object
 mat : array, (4, 4)
transformation matrix
 in_place : bool
If True then change data in place. Be careful changes input streamlines.
Returns:  new_streamlines : Streamlines
Sequence transformed 2D ndarrays of shape[1]==3
unlist_streamlines¶

dipy.align.streamlinear.
unlist_streamlines
(streamlines)¶ Return the streamlines not as a list but as an array and an offset
Parameters:  streamlines: sequence
Returns:  points : array
 offsets : array
whole_brain_slr¶

dipy.align.streamlinear.
whole_brain_slr
(static, moving, x0='affine', rm_small_clusters=50, maxiter=100, select_random=None, verbose=False, greater_than=50, less_than=250, qbx_thr=[40, 30, 20, 15], nb_pts=20, progressive=True, rng=None, num_threads=None)¶ Utility function for registering large tractograms.
For efficiency we apply the registration on cluster centroids and remove small clusters.
Parameters:  static : Streamlines
 moving : Streamlines
 x0 : str
rigid, similarity or affine transformation model (default affine)
 rm_small_clusters : int
Remove clusters that have less than rm_small_clusters (default 50)
 select_random : int
If not None select a random number of streamlines to apply clustering Default None.
 verbose : bool,
If True then information about the optimization is shown.
 greater_than : int, optional
Keep streamlines that have length greater than this value (default 50)
 less_than : int, optional
Keep streamlines have length less than this value (default 250)
 qbx_thr : variable int
Thresholds for QuickBundlesX (default [40, 30, 20, 15])
 np_pts : int, optional
Number of points for discretizing each streamline (default 20)
 progressive : boolean, optional
(default True)
 rng : RandomState
If None creates RandomState in function.
 num_threads : int
Number of threads. If None (default) then all available threads will be used. Only metrics using OpenMP will use this variable.
Notes
The order of operations is the following. First short or long streamlines are removed. Second the tractogram or a random selection of the tractogram is clustered with QuickBundles. Then SLR [Garyfallidis15] is applied.
References
[Garyfallidis15] (1, 2) Garyfallidis et al. “Robust and efficient linear registration of whitematter fascicles in the space of streamlines”, NeuroImage, 117, 124–140, 2015 .. [R9eb8c2315518Garyfallidis14] Garyfallidis et al., “Direct nativespace fiber
bundle alignment for group comparisons”, ISMRM, 2014.[Garyfallidis17] Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017.