align
align._public
align.cpd
align.imaffine
align.imwarp
align.metrics
align.reslice
align.scalespace
align.streamlinear
align.streamwarp
Bunch
DeformableRegistration
DeformableRegistration
DeformableRegistration.__init__()
DeformableRegistration.expectation()
DeformableRegistration.get_registration_parameters()
DeformableRegistration.iterate()
DeformableRegistration.maximization()
DeformableRegistration.register()
DeformableRegistration.transform_point_cloud()
DeformableRegistration.update_transform()
DeformableRegistration.update_variance()
AffineInversionError
AffineInvalidValuesError
AffineMap
MutualInformationMetric
AffineRegistration
DiffeomorphicMap
DiffeomorphicMap
DiffeomorphicMap.__init__()
DiffeomorphicMap.allocate()
DiffeomorphicMap.compute_inversion_error()
DiffeomorphicMap.expand_fields()
DiffeomorphicMap.get_backward_field()
DiffeomorphicMap.get_forward_field()
DiffeomorphicMap.get_simplified_transform()
DiffeomorphicMap.interpret_matrix()
DiffeomorphicMap.inverse()
DiffeomorphicMap.shallow_copy()
DiffeomorphicMap.transform()
DiffeomorphicMap.transform_inverse()
DiffeomorphicMap.transform_points()
DiffeomorphicMap.transform_points_inverse()
DiffeomorphicMap.warp_endomorphism()
DiffeomorphicRegistration
SymmetricDiffeomorphicRegistration
SimilarityMetric
SimilarityMetric
SimilarityMetric.__init__()
SimilarityMetric.compute_backward()
SimilarityMetric.compute_forward()
SimilarityMetric.free_iteration()
SimilarityMetric.get_energy()
SimilarityMetric.initialize_iteration()
SimilarityMetric.set_levels_above()
SimilarityMetric.set_levels_below()
SimilarityMetric.set_moving_image()
SimilarityMetric.set_static_image()
SimilarityMetric.use_moving_image_dynamics()
SimilarityMetric.use_static_image_dynamics()
CCMetric
EMMetric
SSDMetric
ScaleSpace
IsotropicScaleSpace
StreamlineDistanceMetric
BundleMinDistanceMetric
BundleMinDistanceMatrixMetric
BundleMinDistanceAsymmetricMetric
BundleSumDistanceMatrixMetric
JointBundleMinDistanceMetric
StreamlineLinearRegistration
StreamlineRegistrationMap
JointStreamlineRegistrationMap
align


VerbosityLevels This enum defines the four levels of verbosity we use in the align module. 
align._public
Registration API: simplified API for registration of MRI data and of streamlines.

Register a 2D/3D source image (moving) to a 2D/3D target image (static). 

Register DWI data to a template through the B0 volumes. 

Write out a syn registration mapping to a nifti file. 

Read a syn registration mapping from a nifti file. 

Resample an image (moving) from one space to another (static). 

Find the affine transformation between two 3D images. 

Implements a center of mass transform. 

Implements a translation transform. 

Implements a rigid transform. 

Implements a rigid isoscaling transform. 

Implements a rigid scaling transform. 

Implements an affine transform. 
dict() > new empty dictionary dict(mapping) > new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) > new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) > new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2). 


Register a series to a reference image. 

Register a DWI series to the mean of the B0 images in that series. 

Apply a motion correction to a DWI dataset (BetweenVolumes Motion correction) 

Register two collections of streamlines ('bundles') to each other. 
align.cpd
This file is copied (possibly with major modifications) from the sources of the pycpd project  https://github.com/siavashk/pycpd. It remains licensed as the rest of PyCPD (MIT license as of October 2010).
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyCPD package for the # copyright and license terms. # # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

Deformable point cloud registration. 



Calculate num_eig eigenvectors and eigenvalues of gaussian matrix G. 

Initialize the variance (sigma2). 

Calculate eigenvectors and eigenvalues of gaussian matrix G. 
align.imaffine
Affine image registration module consisting of the following classes:
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.
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.
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.
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.
function and the mode. Annals of Mathematical Statistics, 33(3), 10651076, 1962.
& Eubank, W. PETCT image registration in the chest using freeform deformations. IEEE Transactions on Medical Imaging, 22(1), 1208, 2003.






dict() > new empty dictionary dict(mapping) > new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) > new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) > new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2). 


Transformation to align the center of mass of the input images. 

Transformation to align the geometric center of the input images. 

Transformation to align the origins of the input images. 
align.imwarp
Classes and functions for Symmetric Diffeomorphic Registration






Registration Stages 

Instances of the Logger class represent a single logging channel. 


Returns the matrix product A.dot(B) considering None as the identity 

Extracts the rotational and spacing components from a matrix 
align.metrics
Metrics for Symmetric Diffeomorphic Registration









Multiresolution GaussSeidel solver using Vtype cycles 

Multiresolution GaussSeidel solver using Vtype cycles 
align.reslice

Reslice data with new voxel resolution defined by 
align.scalespace




Instances of the Logger class represent a single logging channel. 
align.streamlinear



Bundlebased Minimum Distance aka BMD 

Bundlebased Minimum Distance aka BMD 

Asymmetric Bundlebased Minimum distance. 

Bundlebased Sum Distance aka BMD 

Bundlebased Minimum Distance for joint optimization. 






Instances of the Logger class represent a single logging channel. 


MDF distance optimization function (SUM). 

MDFbased pairwise distance optimization function (MIN). 

MDFbased pairwise distance optimization function (MIN). 
MDFbased pairwise distance optimization function (MIN). 




Progressive SLR. 

Utility function for registering large tractograms. 

Function to perform unbiased groupwise bundle registration. 

Make unique pairs from n_bundle bundles. 

Compose a 4x4 transformation matrix. 

Given a 4x4 homogeneous matrix return the parameter vector. 
align.streamwarp

Find average Euclidean length of the bundle in mm. 

Find unmatched streamline indices in moving bundle. 

Register two bundles using nonlinear method. 

Calculate vector fields. 

Calculate bundle shape difference profile. 
Bunch
Bases: object
VerbosityLevels This enum defines the four levels of verbosity we use in the align module. NONE : do not print anything STATUS : print information about the current status of the algorithm DIAGNOSE : print high level information of the components involved in the registration that can be used to detect a failing component. DEBUG : print as much information as possible to isolate the cause of a bug.
Register a 2D/3D source image (moving) to a 2D/3D target image (static).
Either as a 2D/3D array or as a nifti image object, or as a string containing the full path to a nifti file.
Must be provided for data provided as an array. If provided together with Nifti1Image or str data, this input will override the affine that is stored in the data input. Default: use the affine stored in data.
The metric to be optimized. One of CC, EM, SSD, Default: ‘CC’ => CCMetric.
The dimensions of the image domain. Default: 3
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). Default: [10, 10, 5].
Parameters for initialization of the metric object. If not provided, uses the default settings of each metric.
The data in moving, warped towards the static data.
The vector field describing the forward warping from the source to the target.
The vector field describing the backward warping from the target to the source.
Register DWI data to a template through the B0 volumes.
Containing the DWI data, or full path to a nifti file with DWI.
The gradients associated with the DWI data, or a sequence with (fbval, fbvec), full paths to bvals and bvecs files.
An affine transformation associated with the DWI. Required if data is provided as an array. If provided together with nifti/path, will override the affine that is in the nifti.
Containing the data for the template, or full path to a nifti file with the template data.
An affine transformation associated with the template. Required if data is provided as an array. If provided together with nifti/path, will override the affine that is in the nifti.
One of “syn” or “aff”, which designates which registration method is
used. Either syn, which uses the syn_registration()
function
or affine_registration()
function. Default: “syn”.
syn_registration()
orwarped_b0, mapping: The fist is an array with the b0 volume warped to the template. If reg_method is “syn”, the second is a DiffeomorphicMap class instance that can be used to transform between the two spaces. Otherwise, if reg_method is “aff”, this is a 4x4 matrix encoding the affine transform.
This function assumes that the DWI data is already internally registered.
See register_dwi_series()
.
Write out a syn registration mapping to a nifti file.
mapping : a DiffeomorphicMap object derived from syn_registration()
fname : str
Full path to the nifti file storing the mapping
The data in the file is organized with shape (X, Y, Z, 3, 2), such that the forward mapping in each voxel is in data[i, j, k, :, 0] and the backward mapping in each voxel is in data[i, j, k, :, 1].
Read a syn registration mapping from a nifti file.
A file of image containing the mapping displacement field in each voxel Shape (x, y, z, 3, 2)
domain_img : str or Nifti1Image
codomain_img : str or Nifti1Image
A DiffeomorphicMap
object.
See write_mapping()
for the data format expected.
Resample an image (moving) from one space to another (static).
Containing the data for the moving object, or full path to a nifti file with the moving data.
An affine transformation associated with the moving object. Required if data is provided as an array. If provided together with nifti/path, will override the affine that is in the nifti.
Containing the data for the static object, or full path to a nifti file with the moving data.
An affine transformation associated with the static object. Required if data is provided as an array. If provided together with nifti/path, will override the affine that is in the nifti.
If an additional affine is needed between the two spaces. Default: identity (no additional registration).
A Nifti1Image class instance with the data from the moving object resampled into the space of the static object.
Find the affine transformation between two 3D images. Alternatively, find the combination of several linear transformations.
Containing the data for the moving object, or full path to a nifti file with the moving data.
Containing the data for the static object, or full path to a nifti file with the moving data.
An affine transformation associated with the moving object. Required if data is provided as an array. If provided together with nifti/path, will override the affine that is in the nifti.
An affine transformation associated with the static object. Required if data is provided as an array. If provided together with nifti/path, will override the affine that is in the nifti.
Sequence of transforms to use in the gradual fitting. Default: gradual
fit of the full affine (executed from left to right):
["center_of_mass", "translation", "rigid", "affine"]
Alternatively, any other combination of the following registration
methods might be used: center_of_mass, translation, rigid,
rigid_isoscaling, rigid_scaling and affine.
Initial guess for the transformation between the spaces. Default: identity.
Currently only supports ‘MI’ for MutualInformationMetric.
AffineRegistration keyword argument: 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.
AffineRegistration keyword argument: custom smoothing parameter to build the scale space (one parameter for each scale). By default, the sequence of sigmas will be [3, 1, 0].
AffineRegistration keyword argument: custom scale factors to build the scale space (one factor for each scale). By default, the sequence of factors will be [4, 2, 1].
Set it to True to return the value of the optimized coefficients and the optimization quality metric.
moving image mask that defines which pixels in the moving image are used to calculate the mutual information.
static image mask that defines which pixels in the static image are used to calculate the mutual information.
MutualInformationMetric keyword argument: the number of bins to be used for computing the intensity histograms. The default is 32.
MutualInformationMetric keyword argument: 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 (dense sampling).
transformed : array with moving data resampled to the static space after computing the affine transformation affine : the affine 4x4 associated with the transformation. xopt : the value of the optimized coefficients. fopt : the value of the optimization quality metric.
Performs a gradual registration between the two inputs, using a pipeline that gradually approximates the final registration. If the final default step (affine) is omitted, the resulting affine may not have all 12 degrees of freedom adjusted.
Implements a center of mass transform. Based on affine_registration().
Implements a translation transform. Based on affine_registration().
Implements a rigid transform. Based on affine_registration().
Implements a rigid isoscaling transform. Based on affine_registration().
Implements a rigid scaling transform. Based on affine_registration().
Implements an affine transform. Based on affine_registration().
dict() > new empty dictionary dict(mapping) > new dictionary initialized from a mapping object’s
(key, value) pairs
d = {} for k, v in iterable:
d[k] = v
in the keyword argument list. For example: dict(one=1, two=2)
Register a series to a reference image.
The data is 4D with the last dimension separating different 3D volumes
If this is an int, this is the index of the reference image within the series. Otherwise it is an array of data to register with (associated with a ref_affine required) or a nifti img or full path to a file containing one.
Sequence of transforms to do for each volume in the series. Default: (executed from left to right): [center_of_mass, translation, rigid, affine]
The affine. If provided, this input will override the affine provided together with the nifti img or file.
static image mask that defines which pixels in the static image are used to calculate the mutual information.
xformed, affines : 4D array with transformed data and a (4,4,n) array with 4x4 matrices associated with each of the volumes of the input moving data that was used to transform it into register with the static data.
Register a DWI series to the mean of the B0 images in that series.
all first registered to the first B0 volume
Diffusion data. Either as a 4D array or as a nifti image object, or as a string containing the full path to a nifti file.
If provided as a tuple of strings, these are assumed to be full paths to the bvals and bvecs files (in that order).
Must be provided for data provided as an array. If provided together with Nifti1Image or str data, this input will override the affine that is stored in the data input. Default: use the affine stored in data.
Which b0 volume to use as reference. Default: 0
The transformations to perform in sequence (from left to right):
Default: [center_of_mass, translation, rigid, affine]
static image mask that defines which pixels in the static image are used to calculate the mutual information.
xform_img, affine_array: a Nifti1Image containing the registered data and using the affine of the original data and a list containing the affine transforms associated with each of the
Apply a motion correction to a DWI dataset (BetweenVolumes Motion correction)
Diffusion data. Either as a 4D array or as a nifti image object, or as a string containing the full path to a nifti file.
If provided as a tuple of strings, these are assumed to be full paths to the bvals and bvecs files (in that order).
Must be provided for data provided as an array. If provided together with Nifti1Image or str data, this input will override the affine that is stored in the data input. Default: use the affine stored in data.
Which b0 volume to use as reference. Default: 0
The transformations to perform in sequence (from left to right):
Default: [center_of_mass, translation, rigid, affine]
static image mask that defines which pixels in the static image are used to calculate the mutual information.
xform_img, affine_array: a Nifti1Image containing the registered data and using the affine of the original data and a list containing the affine transforms associated with each of the
Register two collections of streamlines (‘bundles’) to each other.
The two bundles to be registered. Given either as lists of arrays with 3D coordinates, or strings containing full paths to these files.
How many points to resample to. Default: 100.
Whether to return the moving bundle in the original space, but resampled in the static space to n_points.
Streamlines from the moving group, moved to be closely matched to the static group.
The affine transformation that takes us from ‘moving’ to ‘static’
DeformableRegistration
Bases: object
Deformable point cloud registration.
NxD array of target points.
MxD array of source points.
MxD array of transformed source points.
Initial variance of the Gaussian mixture model.
Number of target points.
Number of source points.
Dimensionality of source and target points
The current iteration throughout registration.
Registration will terminate once the algorithm has taken this many iterations.
Registration will terminate once the difference between consecutive objective function values falls within this tolerance.
Contribution of the uniform distribution to account for outliers. Valid values span 0 (inclusive) and 1 (exclusive).
The objective function value that represents the misalignment between source and target point clouds.
The absolute difference between the current and previous objective function values.
MxN array of probabilities. P[m, n] represents the probability that the mth source point corresponds to the nth target point.
Nx1 column array. Multiplication result between the transpose of P and a column vector of all 1s.
Mx1 column array. Multiplication result between P and a column vector of all 1s.
The sum of all elements in P.
Represents the tradeoff between the goodness of maximum likelihoo fit and regularization.
Width of the Gaussian kernel.
Whether to use low rank approximation.
Number of eigenvectors to use in lowrank calculation.
Return the current estimate of the deformable transformation parameters.
Gaussian kernel matrix.
Deformable transformation matrix.
Perform the EM registration.
A function that will be called after each iteration. Can be used to visualize the registration process.
MxD array of transformed source points.
Returned params dependent on registration method used.
Update a point cloud using the new estimate of the deformable transformation.
Array of points to transform  use to predict on new set of points. Best for predicting on new points not used to run initial registration. If None, self.Y used.
If Y is None, returns None. Otherwise, returns the transformed Y.
Calculate a new estimate of the deformable transformation. See Eq. 22 of https://arxiv.org/pdf/0905.2635.pdf.
Update the variance of the mixture model.
This is using the new estimate of the deformable transformation. See the update rule for sigma2 in Eq. 23 of of https://arxiv.org/pdf/0905.2635.pdf.
Calculate eigenvectors and eigenvalues of gaussian matrix G.
!!! This function is a placeholder for implementing the fast gauss transform. It is not yet implemented. !!!
Gaussian kernel matrix.
Width of the Gaussian kernel.
Number of eigenvectors to use in lowrank calculation of G
If True, use fast gauss transform method to speed up.
AffineInversionError
Bases: Exception
AffineInvalidValuesError
Bases: Exception
AffineMap
Bases: object
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.
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.
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.
the gridtoworld transform associated with the domain grid. If None (the default), then the gridtoworld transform is assumed to be the identity.
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.
the gridtoworld transform associated with the codomain grid. If None (the default), then the gridtoworld transform is assumed to be the identity.
Return the value of the transformation, not a reference.
Copy of the transform, not a reference.
Set the affine transform (operating in physical space).
Also sets self.affine_inv  the inverse of affine, or None if there is no inverse.
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 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.
the image to be transformed
the type of interpolation to be used, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
the gridtoworld transform associated with image. If None (the default), then the gridtoworld transform is assumed to be the identity.
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).
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.
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.
self.codomain_shape
the transformed image, sampled at the requested grid
Transform 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.
the image to be transformed
the type of interpolation to be used, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
the gridtoworld transform associated with image. If None (the default), then the gridtoworld transform is assumed to be the identity.
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).
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.
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.
self.codomain_shape
the transformed image, sampled at the requested grid
MutualInformationMetric
Bases: object
Initialize an instance of the Mutual Information metric.
This class implements the methods required by Optimizer to drive the registration process.
the number of bins to be used for computing the intensity histograms. The default is 32.
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.
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.
Numeric value of the negative Mutual Information.
We need to change the sign so we can use standard minimization algorithms.
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
the negative mutual information of the input images after transforming the moving image by the currently set transform with params parameters
Numeric value of the metric and its gradient at given parameters.
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
the negative mutual information of the input images after transforming the moving image by the currently set transform with params parameters
the gradient of the negative Mutual Information
Numeric value of the metric’s gradient at the given parameters.
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
the gradient of the negative Mutual Information
Prepare 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
the transformation with respect to whose parameters the gradient must be computed
static image
moving image. The dimensions of the static (S, R, C) and moving (S’, R’, C’) images do not need to be the same.
the gridtospace transform of the static image. The default is None, implying the transform is the identity.
the gridtospace transform of the moving image. The default is None, implying the spacing along all axes is 1.
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.
static image mask that defines which pixels in the static image are used to calculate the mutual information.
moving image mask that defines which pixels in the moving image are used to calculate the mutual information.
AffineRegistration
Bases: object
Initialize 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
Start the optimization process.
the image to be used as reference during optimization.
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
the transformation with respect to whose parameters the gradient must be computed
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.
the voxeltospace transformation associated with the static image. The default is None, implying the transform is the identity.
the voxeltospace transformation associated with the moving image. The default is None, implying the transform is the identity.
‘mass’: align centers of gravity ‘voxelorigin’: align physical coordinates of voxel (0,0,0) ‘centers’: align physical coordinates of central voxels
array, shape (dim+1, dim+1).
Start from identity.
The default is None.
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.
static image mask that defines which pixels in the static image are used to calculate the mutual information.
moving image mask that defines which pixels in the moving image are used to calculate the mutual information.
the affine resulting affine transformation
the optimal parameters (translation, rotation shear etc.)
the value of the function at the optimal parameters.
dict() > new empty dictionary dict(mapping) > new dictionary initialized from a mapping object’s
(key, value) pairs
d = {} for k, v in iterable:
d[k] = v
in the keyword argument list. For example: dict(one=1, two=2)
Transformation to align the center of mass of the input images.
static image
the voxeltospace transformation of the static image
moving image
the voxeltospace transformation of the moving image
the affine transformation (translation only, in this case) aligning the center of mass of the moving image towards the one of the static image
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
static image
the voxeltospace transformation of the static image
moving image
the voxeltospace transformation of the moving image
the affine transformation (translation only, in this case) aligning the geometric center of the moving image towards the one of the static image
Transformation to align the origins of the input images.
With “origin” of a volume we mean the physical coordinates of voxel (0,0,0)
static image
the voxeltospace transformation of the static image
moving image
the voxeltospace transformation of the moving image
the affine transformation (translation only, in this case) aligning the origin of the moving image towards the one of the static image
DiffeomorphicMap
Bases: object
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.
the transformation’s dimension
the number of slices (if 3D), rows and columns of the deformation field’s discretization
grid and space
the number of slices (if 3D), rows and columns of the default discretization of this map’s domain
the default voxeltospace transformation between this map’s discretization and physical space
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.
the voxeltospace transformation of images that are ‘normally’ warped using this transformation (in the forward direction).
the linear transformation to be applied to align input images to the reference space before warping under the deformation field.
Creates a zero displacement field
Creates a zero displacement field (the identity transformation).
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.
the displacement field resulting from composing the forward and backward displacement fields of this transformation (the residual should be zero for a perfect diffeomorphism)
statistics from the norms of the vectors of the residual displacement field: maximum, mean and standard deviation
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
Expands the displacement fields from current shape to new_shape
Upsamples the discretization of the displacement fields to be of new_shape shape.
the factors scaling current spacings (voxel sizes) to spacings in the expanded discretization.
the shape of the arrays holding the upsampled discretization
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).
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).
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.
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.
any object
the same object given as argument if obj is None or a numpy array. None if obj is the ‘identity’ string.
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.
the inverse of this diffeomorphic map.
Shallow copy of this DiffeomorphicMap instance
Creates a shallow copy of this diffeomorphic map (the arrays are not copied but just referenced)
the shallow copy of this diffeomorphic map
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).
the image to be warped under this transformation in the forward direction
the type of interpolation to be used for warping, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
the transformation bringing world (space) coordinates to voxel coordinates of the image given as input
the number of slices, rows and columns of the desired warped image
warped image to physical space
the warped image under this transformation in the forward direction
See _warp_forward and _warp_backward documentation for further information.
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)
the image to be warped under this transformation in the forward direction
the type of interpolation to be used for warping, either ‘linear’ (for klinear interpolation) or ‘nearest’ for nearest neighbor
the transformation bringing world (space) coordinates to voxel coordinates of the image given as input
the number of slices, rows, and columns of the desired warped image
warped image to physical space
warped image under this transformation in the backward direction
See _warp_forward and _warp_backward documentation for further information.
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).
the endomorphism to be warped by this diffeomorphic map
endomorphism given as input
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
Bases: object
Diffeomorphic Registration
This abstract class defines the interface to be implemented by any optimization algorithm for diffeomorphic registration.
the object measuring the similarity of the two images. The registration algorithm will minimize (or maximize) the provided similarity.
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.
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.
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
SymmetricDiffeomorphicRegistration
Bases: DiffeomorphicRegistration
Symmetric Diffeomorphic Registration (SyN) Algorithm
Performs the multiresolution optimization algorithm for nonlinear registration using a given similarity metric.
the metric to be optimized
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)
the optimization will stop when the estimated derivative of the energy profile w.r.t. time falls below this threshold
the number of iterations to be performed by the displacement field inversion algorithm
the length of the maximum displacement vector of the update displacement field at each iteration
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
the displacement field inversion algorithm will stop iterating when the inversion error falls below this threshold
a function receiving a SymmetricDiffeomorphicRegistration object to be called after each iteration (this optimizer will call this function passing self as parameter)
Return the resulting diffeomorphic map.
Returns the DiffeomorphicMap registering the moving image towards the static image.
Starts the optimization
the image to be used as reference during optimization. The displacement fields will have the same discretization as the static image.
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
the voxeltospace transformation associated to the static image
the voxeltospace transformation associated to the moving image
the affine transformation (operating on the physical space) prealigning the moving image towards the static
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).
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).
the displacement field defining where to interpolate new_displacement
the displacement field to be warped by current_displacement
the spacetogrid transform associated with the displacements’ grid (we assume that both displacements are discretized over the same grid)
scaling factor applied to d2. The effect may be interpreted as moving d1 displacements along a factor (time_scaling) of d2.
the warped displacement field
mean_norm : the mean norm of all vectors in current_displacement
Instances of the Logger class represent a single logging channel. A “logging channel” indicates an area of an application. Exactly how an “area” is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of “input processing” might include subareas “read CSV files”, “read XLS files” and “read Gnumeric files”). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be “input” for the upper level, and “input.csv”, “input.xls” and “input.gnu” for the sublevels. There is no arbitrary limit to the depth of nesting.
Returns the matrix product A.dot(B) considering None as the identity
A : array, shape (n,k) B : array, shape (k,m)
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
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.
the matrix transforming grid coordinates to physical space.
the rotational component of the input matrix
the scaling component (voxel size) of the matrix
SimilarityMetric
Bases: object
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
the dimension of the image domain
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
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
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
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
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.
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
the number of levels above the current Gaussian Pyramid level
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
the number of levels below the current Gaussian Pyramid level
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
the moving image
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
the static image
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.
original image from which the current moving image was generated
the transformation that was applied to the original image to generate the current moving image
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.
original image from which the current static image was generated
the transformation that was applied to original image to generate the current static image
CCMetric
Bases: SimilarityMetric
Normalized CrossCorrelation Similarity metric.
the dimension of the image domain
be applied to the update field at each iteration
the radius of the squared (cubic) neighborhood at each voxel to be considered to compute the cross correlation
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
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
Numerical value assigned by this metric to the current image pair
Returns the Cross Correlation (data term) energy computed at the largest 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
Bases: SimilarityMetric
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.
the dimension of the image domain
smoothness parameter, the larger the value the smoother the deformation field
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)
variables in the EM algorithm)
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.
the optimization schedule to be used in the multiresolution GaussSeidel optimization algorithm (not used if Demons Step is selected)
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
Demons step for EM metric
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)
the Demons step
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
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]
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)
the Newton step
estimation: combining highest accuracy with realtime performance”, 10th IEEE International Conference on Computer Vision, 2005. ICCV 2005.
The numerical value assigned by this metric to the current image pair
Returns the EM (data term) energy computed at the largest 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.
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)
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.
the transformation that was applied to the original_moving_image to generate the current moving image
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)
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).
the transformation that was applied to the original_static_image to generate the current static image
SSDMetric
Bases: SimilarityMetric
Sum of Squared Differences (SSD) Metric
Similarity metric for (monomodal) nonlinear image registration defined by the sum of squared differences (SSD)
the dimension of the image domain
smoothness parameter, the larger the value the smoother the deformation field
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)
the displacement field step to be computed when ‘compute_forward’ and ‘compute_backward’ are called. Either ‘demons’ or ‘gauss_newton’
Computes one step bringing the static image towards the moving.
Computes the updated displacement field to be used for registration of the static image towards the moving image
Demons step for SSD metric
Computes the demons step proposed by Vercauteren et al.[Vercauteren09] for the SSD metric.
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)
the Demons step
Nicholas Ayache, “Diffeomorphic Demons: Efficient Nonparametric Image Registration”, Neuroimage 2009
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
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.
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)
if forward_step==True, the forward SSD GaussNewton step, else, the backward step
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].
number of levels of the multiresolution algorithm (it will be called recursively until level n == 0)
the number of iterations at each multiresolution level
the difference between the static and moving image (the ‘derivative w.r.t. time’ in the optical flow model)
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.
the gradient of the moving image
righthand side of the linear system to be solved in the Weickert’s multiresolution algorithm
smoothness parameter, the larger its value the smoother the displacement field
the displacement field to start the optimization from
iteration
estimation: combining the highest accuracy with realtime performance”, 10th IEEE International Conference on Computer Vision, 2005. ICCV 2005.
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.
number of levels of the multiresolution algorithm (it will be called recursively until level n == 0)
the number of iterations at each multiresolution level
the difference between the static and moving image (the ‘derivative w.r.t. time’ in the optical flow model)
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.
the gradient of the moving image
righthand side of the linear system to be solved in the Weickert’s multiresolution algorithm
smoothness parameter, the larger its value the smoother the displacement field
the displacement field to start the optimization from
iteration
Reslice data with new voxel resolution defined by new_zooms
.
3d volume or 4d volume with datasets
mapping from voxel coordinates to world coordinates
voxel size for (i,j,k) dimensions
new voxel size for (i,j,k) after resampling
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.
Points outside the boundaries of the input are filled according to the given mode.
Value used for points outside the boundaries of the input if mode=’constant’.
Split the calculation to a pool of children processes. This only
applies to 4D data arrays. Default is 1. If < 0 the maximal number
of cores minus num_processes + 1
is used (enter 1 to use as many
cores as possible). 0 raises an error.
datasets resampled into isotropic voxel size
new affine for the resampled image
>>> from dipy.io.image import load_nifti
>>> from dipy.align.reslice import reslice
>>> from dipy.data import get_fnames
>>> f_name = get_fnames('aniso_vox')
>>> data, affine, zooms = load_nifti(f_name, return_voxsize=True)
>>> data.shape == (58, 58, 24)
True
>>> 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
ScaleSpace
Bases: object
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.
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).
the scale space level to get affine transform from
the affine (voxeltospace) transform at the requested resolution or None if an invalid level was requested
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).
the scale space level to get the inverse transform from
the inverse (spacetovoxel) transform at the requested resolution or None if an invalid level was requested
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).
the scale space level to get the subsampled shape from
the subsampled shape at the requested resolution or None if an invalid level was requested
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).
the resolution to expand voxels from
the resolution to expand voxels to
the expand factors (a scalar for each voxel dimension)
Smoothed image at a given level.
Returns the smoothed image at the requested level in the Scale Space.
the scale space level to get the smooth image from
the smooth image at the requested resolution or None if an invalid level was requested
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.
the scale space level to get the scalings from
the scaling factors from the original spacing to the spacings at the requested 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
the scale space level to get the smoothing parameters from
the smoothing parameters at the requested 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).
the scale space level to get the subsampled shape from
the spacings (voxel sizes) at the requested resolution or None if an invalid level was requested
IsotropicScaleSpace
Bases: ScaleSpace
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.
slices, r is the number of rows and c is the number of columns of the input image.
custom scale factors to build the scale space (one factor for each scale).
custom smoothing parameter to build the scale space (one parameter for each scale).
the gridtospace transform of the image grid. The default is the identity matrix.
the spacing (voxel size) between voxels in physical space. The default if 1.0 along all axes.
if True, all smoothed images will be zero at all voxels that are zero in the input image. The default is False.
Instances of the Logger class represent a single logging channel. A “logging channel” indicates an area of an application. Exactly how an “area” is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of “input processing” might include subareas “read CSV files”, “read XLS files” and “read Gnumeric files”). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be “input” for the upper level, and “input.csv”, “input.xls” and “input.gnu” for the sublevels. There is no arbitrary limit to the depth of nesting.
StreamlineDistanceMetric
Bases: object
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.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
BundleMinDistanceMetric
Bases: StreamlineDistanceMetric
Bundlebased Minimum Distance aka BMD
This is the cost function used by the StreamlineLinearRegistration.
setup(static, moving) distance(xopt)
Garyfallidis et al., “Direct nativespace fiber bundle alignment for group comparisons”, ISMRM, 2014.
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.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
BundleMinDistanceMatrixMetric
Bases: StreamlineDistanceMetric
Bundlebased Minimum Distance aka BMD
This is the cost function used by the StreamlineLinearRegistration
setup(static, moving) distance(xopt)
The difference with BundleMinDistanceMetric is that this creates the entire distance matrix and therefore requires more memory.
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.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
Distance calculated from this Metric.
List of affine parameters as an 1D vector
Setup static and moving sets of streamlines.
Fixed or reference set of streamlines.
Moving streamlines.
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
BundleMinDistanceAsymmetricMetric
Bases: BundleMinDistanceMetric
Asymmetric Bundlebased Minimum distance.
This is a cost function that can be used by the StreamlineLinearRegistration class.
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.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
BundleSumDistanceMatrixMetric
Bases: BundleMinDistanceMatrixMetric
Bundlebased Sum Distance aka BMD
This is a cost function that can be used by the StreamlineLinearRegistration class.
setup(static, moving) distance(xopt)
The difference with BundleMinDistanceMatrixMetric is that it uses uses the sum of the distance matrix and not the sum of mins.
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.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
JointBundleMinDistanceMetric
Bases: StreamlineDistanceMetric
Bundlebased Minimum Distance for joint optimization.
This cost function is used by the StreamlineLinearRegistration class when running halfway streamline linear registration for unbiased groupwise bundle registration and atlasing.
It computes the BMD distance after moving both static and moving bundles to a halfway space in between both.
setup(static, moving) distance(xopt)
In this metric both static and moving bundles are treated equally (i.e., there is no static reference bundle as both are intended to move). The naming convention is kept for consistency.
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.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
StreamlineLinearRegistration
Bases: object
Linear registration of 2 sets of streamlines [Garyfallidis15].
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.
Initial parametrization for the optimization.
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).
x0 = np.array([0, 0, 0, 0, 0, 0])
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
x0 = np.array([0, 0, 0, 0, 0, 0])
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
‘L_BFGS_B’ or ‘Powell’ optimizers can be used. Default is ‘L_BFGS_B’.
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).
If True, if True then information about the optimization is shown. Default: False.
Extra options to be used with the selected method.
If True save the transformation for each iteration of the optimizer. Default is False. Supported only with Scipy >= 0.11.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
Garyfallidis et al. “Robust and efficient linear registration of whitematter fascicles in the space of streamlines”, NeuroImage, 117, 124–140, 2015
Garyfallidis et al., “Direct nativespace fiber bundle alignment for group comparisons”, ISMRM, 2014.
Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017.
Find the minimum of the provided metric.
Reference or fixed set of streamlines.
Moving set of streamlines.
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.
map : StreamlineRegistrationMap
StreamlineRegistrationMap
Bases: object
A map holding the optimum affine matrix and some other parameters of the optimization
4x4 affine matrix which transforms the moving to the static streamlines
1d array with the parameters of the transformation after centering
final value of the metric
All transformation matrices created during the optimization
Number of function evaluations of the optimizer
Number of iterations of the optimizer
JointStreamlineRegistrationMap
Bases: object
A map holding the optimum affine matrices for halfway streamline linear registration and some other parameters of the optimization.
xopt is optimized by StreamlineLinearRegistration using the JointBundleMinDistanceMetric. In that case the mat argument of the optimize method needs to be np.eye(4) to avoid streamline centering.
This constructor derives and stores the transformations to move both static and moving bundles to the halfway space.
1d array with the parameters of the transformation.
Final value of the metric.
All transformation matrices created during the optimization.
Number of function evaluations of the optimizer.
Number of iterations of the optimizer.
Instances of the Logger class represent a single logging channel. A “logging channel” indicates an area of an application. Exactly how an “area” is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of “input processing” might include subareas “read CSV files”, “read XLS files” and “read Gnumeric files”). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be “input” for the upper level, and “input.csv”, “input.xls” and “input.gnu” for the sublevels. There is no arbitrary limit to the depth of nesting.
MDF distance optimization function (SUM).
We minimize the distance between moving streamlines as they align with the static streamlines.
t is a vector of affine transformation parameters with size at least 6. If the size is 6, t is interpreted as translation + rotation. If the size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
Static streamlines
Moving streamlines. These will be transformed to align with the static streamlines
Number of threads. If 1 then all available threads will be used.
cost: float
MDFbased pairwise distance optimization function (MIN).
We minimize the distance between moving streamlines as they align with the static streamlines.
t is a vector 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 streamlines
Moving streamlines.
cost: float
MDFbased pairwise distance optimization function (MIN).
We minimize the distance between moving streamlines as they align with the static streamlines.
1D array. t is a vector of affine transformation parameters with size at least 6. If the size is 6, t is interpreted as translation + rotation. If the size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
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.
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.
Number of points per streamline. All streamlines in static and moving should have the same number of points M.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error.
cost: float
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.
MDFbased pairwise distance optimization function (MIN).
We minimize the distance between moving streamlines as they align with the static streamlines.
1D array. t is a vector of affine transformation parameters with size at least 6. If the size is 6, t is interpreted as translation + rotation. If the size is 7, t is interpreted as translation + rotation + isotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
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.
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.
Number of points per streamline. All streamlines in static and moving should have the same number of points M.
cost: float
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.
static : Streamlines moving : Streamlines metric : StreamlineDistanceMetric x0 : string
Could be any of ‘translation’, ‘rigid’, ‘similarity’, ‘scaling’, ‘affine’
Boundaries of registration parameters. See variable DEFAULT_BOUNDS for example.
L_BFGS_B’ or ‘Powell’ optimizers can be used. Default is ‘L_BFGS_B’.
If True, log messages. Default:
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
Garyfallidis et al. “Robust and efficient linear registration of whitematter fascicles in the space of streamlines”, NeuroImage, 117, 124–140, 2015
Utility function for registering large tractograms.
For efficiency, we apply the registration on cluster centroids and remove small clusters.
static : Streamlines moving : Streamlines
rigid, similarity or affine transformation model (default affine)
Remove clusters that have less than rm_small_clusters
Maximum number of iterations to perform.
If not, None selects a random number of streamlines to apply clustering Default None.
If True, logs information about optimization. Default: False
Keep streamlines that have length greater than this value (default 50)
Keep streamlines have length less than this value (default 250)
Thresholds for QuickBundlesX (default [40, 30, 20, 15])
Number of points for discretizing each streamline (default 20)
(default True)
If None creates RandomState in function.
Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus num_threads + 1 is used (enter 1 to use as many threads as possible). 0 raises an error. Only metrics using OpenMP will use this variable.
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.
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.
Garyfallidis et al. Recognition of white matter
bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017.
Function to perform unbiased groupwise bundle registration.
All bundles are moved to the same space by iteratively applying halfway streamline linear registration in pairs. With each iteration, bundles get closer to each other until the procedure converges and there is no more improvement.
List with streamlines of the bundles to be registered.
rigid, similarity or affine transformation model. Default: affine.
Tolerance value to be used to assume convergence. Default: 0.
Maximum number of iterations. Depending on the number of bundles to be registered this may need to be larger. Default: 20.
Thresholds for Quickbundles used for clustering streamlines and reduce computational time. If None, no clustering is performed. Higher values cluster streamlines into a smaller number of centroids. Default: [4].
Number of points for discretizing each streamline. Default: 20.
Maximum number of streamlines for each bundle. If None, all the streamlines are used. Default: 10000.
If True, logs information. Default: False.
If None, creates RandomState in function. Default: None.
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.
Garyfallidis et al. Recognition of white matter
bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017.
Make unique pairs from n_bundle bundles.
The function allows to input a previous pairs assignment so that the new pairs are different.
Number of bundles to be matched in pairs.
array containing the indexes of previous pairs.
Compose a 4x4 transformation matrix.
This is a 1D vector of affine transformation parameters with size at least 3. If the size is 3, t is interpreted as translation. If the size is 6, t is interpreted as translation + rotation. If the size is 7, t is interpreted as translation + rotation + isotropic scaling. If the size is 9, t is interpreted as translation + rotation + anisotropic scaling. If size is 12, t is interpreted as translation + rotation + scaling + shearing.
Homogeneous transformation matrix of size 4x4.
Given a 4x4 homogeneous matrix return the parameter vector.
Homogeneous 4x4 transformation matrix
Size of the output vector. 3, for translation, 6 for rigid, 7 for similarity, 9 for scaling and 12 for affine. Default is 12.
One dimensional ndarray of 3, 6, 7, 9 or 12 affine parameters.
Find unmatched streamline indices in moving bundle.
List of integers containing all the streamlines indices in moving bundle.
List of integers containing streamline indices of the moving bundle that were not matched to any streamline in static bundle.
List containing unmatched streamlines from moving bundle
Register two bundles using nonlinear method.
Reference/fixed bundle
Target bundle that will be moved/registered to match the static bundle
Precomputed distance matrix (default None)
Represents the tradeoff between regularizing the deformation and having points match very closely. Lower value of alpha means high deformations (default 0.3)
Represents the strength of the interaction between points Gaussian kernel size (default 20)
Maximum number of iterations for deformation process in mlCPD method (default 15)
If False, use rigid registration as starting point (default True)
Nonlinearly moved bundle (warped bundle)
Linearly moved bundle (affinely moved)
Float array containing distance between moving and static bundle
Int array containing streamline correspondences between two bundles
Nonlinear warp map generated by BundleWarp
Chandio et al. “BundleWarp, streamlinebased nonlinear registration of white matter tracts.” bioRxiv (2023): 202301.
Calculate vector fields.
Vector field computation as the difference between each streamline point in the deformed and linearly aligned bundles
Linearly (affinely) moved bundle
Nonlinearly (warped) bundle
Vector field modules
Unitary vector directions
colors : List
Calculate bundle shape difference profile.
Bundle shape difference analysis using magnitude from BundleWarp displacements and BUAN
Linearly (affinely) moved bundle
Nonlinearly (warped) bundle
Number of segments to be created along the length of the bundle (Default 10)
Plot bundle shape profile (default False)
Float array containing bundlewarp displacement magnitudes along the length of the bundle
Float array containing standard deviations