workflows
Module: workflows.align
AffineMap (affine[, domain_grid_shape, ...])
|
Methods
|
ApplyTransformFlow ([output_strategy, ...])
|
Methods
|
CCMetric (dim[, sigma_diff, radius])
|
Methods
|
DiffeomorphicMap (dim, disp_shape[, ...])
|
Methods
|
EMMetric (dim[, smooth, inner_iter, ...])
|
Methods
|
ImageRegistrationFlow ([output_strategy, ...])
|
The registration workflow allows the user to use only one type of registration (such as center of mass or rigid body registration only). |
MotionCorrectionFlow ([output_strategy, ...])
|
The Motion Correction workflow allows the user to align between-volumes DWI dataset. |
ResliceFlow ([output_strategy, mix_names, ...])
|
Methods
|
SSDMetric (dim[, smooth, inner_iter, step_type])
|
Methods
|
SlrWithQbxFlow ([output_strategy, mix_names, ...])
|
Methods
|
SymmetricDiffeomorphicRegistration (metric[, ...])
|
Methods
|
SynRegistrationFlow ([output_strategy, ...])
|
Methods
|
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
affine_registration (moving, static[, ...])
|
Find the affine transformation between two 3D images. |
check_dimensions (static, moving)
|
Check the dimensions of the input images. |
gradient_table (bvals[, bvecs, big_delta, ...])
|
A general function for creating diffusion MR gradients. |
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
read_bvals_bvecs (fbvals, fbvecs)
|
Read b-values and b-vectors from disk. |
reslice (data, affine, zooms, new_zooms[, ...])
|
Reslice data with new voxel resolution defined by new_zooms . |
save_nifti (fname, data, affine[, hdr, dtype])
|
Save a data array into a nifti file. |
save_qa_metric (fname, xopt, fopt)
|
Save Quality Assurance metrics. |
slr_with_qbx (static, moving[, x0, ...])
|
Utility function for registering large tractograms. |
transform_streamlines (streamlines, mat[, ...])
|
Apply affine transformation to streamlines |
warn (/, message[, category, stacklevel, source])
|
Issue a warning, or maybe ignore it or raise an exception. |
Module: workflows.combined_workflow
Module: workflows.denoise
GibbsRingingFlow ([output_strategy, ...])
|
Methods
|
LPCAFlow ([output_strategy, mix_names, ...])
|
Methods
|
MPPCAFlow ([output_strategy, mix_names, ...])
|
Methods
|
NLMeansFlow ([output_strategy, mix_names, ...])
|
Methods
|
Patch2SelfFlow ([output_strategy, mix_names, ...])
|
Methods
|
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
deprecated_params (old_name[, new_name, ...])
|
Deprecate a renamed or removed function argument. |
estimate_sigma (arr[, ...])
|
Standard deviation estimation from local patches |
gibbs_removal (vol[, slice_axis, n_points, ...])
|
Suppresses Gibbs ringing artefacts of images volumes. |
gradient_table (bvals[, bvecs, big_delta, ...])
|
A general function for creating diffusion MR gradients. |
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
localpca (arr, sigma[, mask, patch_radius, ...])
|
Performs local PCA denoising according to Manjon et al. [1]. |
mppca (arr[, mask, patch_radius, pca_method, ...])
|
Performs PCA-based denoising using the Marcenko-Pastur distribution [1]. |
nlmeans (arr, sigma[, mask, patch_radius, ...])
|
Non-local means for denoising 3D and 4D images |
patch2self (data, bvals[, patch_radius, ...])
|
Patch2Self Denoiser. |
pca_noise_estimate
|
PCA based local noise estimation. |
read_bvals_bvecs (fbvals, fbvecs)
|
Read b-values and b-vectors from disk. |
save_nifti (fname, data, affine[, hdr, dtype])
|
Save a data array into a nifti file. |
Module: workflows.docstring_parser
This was taken directly from the file docscrape.py of numpydoc package.
Copyright (C) 2008 Stefan van der Walt <stefan@mentat.za.net>,
Pauli Virtanen <pav@iki.fi>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS’’ AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
NumpyDocString (docstring[, config])
|
|
Reader (data)
|
A line-based string reader. |
dedent_lines (lines)
|
Deindent a list of lines maximally |
warn (/, message[, category, stacklevel, source])
|
Issue a warning, or maybe ignore it or raise an exception. |
Module: workflows.flow_runner
IntrospectiveArgumentParser ([prog, usage, ...])
|
- Attributes:
|
get_level (lvl)
|
Transforms the logging level passed on the commandline into a proper logging level name. |
run_flow (flow)
|
Wraps the process of building an argparser that reflects the workflow that we want to run along with some generic parameters like logging, force and output strategies. |
Module: workflows.io
FetchFlow ([output_strategy, mix_names, ...])
|
Methods
|
IoInfoFlow ([output_strategy, mix_names, ...])
|
Methods
|
SplitFlow ([output_strategy, mix_names, ...])
|
Methods
|
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
getmembers (object[, predicate])
|
Return all members of an object as (name, value) pairs sorted by name. |
isfunction (object)
|
Return true if the object is a user-defined function. |
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
save_nifti (fname, data, affine[, hdr, dtype])
|
Save a data array into a nifti file. |
Module: workflows.mask
MaskFlow ([output_strategy, mix_names, ...])
|
Methods
|
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
save_nifti (fname, data, affine[, hdr, dtype])
|
Save a data array into a nifti file. |
Module: workflows.multi_io
IOIterator ([output_strategy, mix_names])
|
Create output filenames that work nicely with multiple input files from multiple directories (processing multiple subjects with one command) |
basename_without_extension (fname)
|
|
common_start (sa, sb)
|
Return the longest common substring from the beginning of sa and sb. |
concatenate_inputs (multi_inputs)
|
Concatenate list of inputs. |
connect_output_paths (inputs, out_dir, out_files)
|
Generate a list of output files paths based on input files and output strategies. |
get_args_default (func)
|
|
glob (pathname, *[, recursive])
|
Return a list of paths matching a pathname pattern. |
io_iterator (inputs, out_dir, fnames[, ...])
|
Create an IOIterator from the parameters. |
io_iterator_ (frame, fnc[, output_strategy, ...])
|
Create an IOIterator using introspection. |
slash_to_under (dir_str)
|
|
Module: workflows.reconst
ConstrainedSphericalDeconvModel (gtab, response)
|
Methods
|
CsaOdfModel (gtab, sh_order[, smooth, ...])
|
Implementation of Constant Solid Angle reconstruction method. |
DiffusionKurtosisModel (gtab[, fit_method])
|
Class for the Diffusion Kurtosis Model |
ReconstCSAFlow ([output_strategy, mix_names, ...])
|
Methods
|
ReconstCSDFlow ([output_strategy, mix_names, ...])
|
Methods
|
ReconstDkiFlow ([output_strategy, mix_names, ...])
|
Methods
|
ReconstDtiFlow ([output_strategy, mix_names, ...])
|
Methods
|
ReconstIvimFlow ([output_strategy, ...])
|
Methods
|
ReconstMAPMRIFlow ([output_strategy, ...])
|
Methods
|
ReconstRUMBAFlow ([output_strategy, ...])
|
Methods
|
RumbaSDModel (gtab[, wm_response, ...])
|
Methods
|
TensorModel (gtab[, fit_method, return_S0_hat])
|
Diffusion Tensor |
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
IvimModel (gtab[, fit_method])
|
Selector function to switch between the 2-stage Trust-Region Reflective based NLLS fitting method (also containing the linear fit): trr and the Variable Projections based fitting method: varpro. |
auto_response_ssst (gtab, data[, roi_center, ...])
|
Automatic estimation of single-shell single-tissue (ssst) response |
axial_diffusivity (evals[, axis])
|
Axial Diffusivity (AD) of a diffusion tensor. |
color_fa (fa, evecs)
|
Color fractional anisotropy of diffusion tensor |
deprecated_params (old_name[, new_name, ...])
|
Deprecate a renamed or removed function argument. |
fractional_anisotropy (evals[, axis])
|
Return Fractional anisotropy (FA) of a diffusion tensor. |
geodesic_anisotropy (evals[, axis])
|
Geodesic anisotropy (GA) of a diffusion tensor. |
get_mode (q_form)
|
Mode (MO) of a diffusion tensor [1]. |
get_sphere ([name])
|
provide triangulated spheres |
gradient_table (bvals[, bvecs, big_delta, ...])
|
A general function for creating diffusion MR gradients. |
literal_eval (node_or_string)
|
Safely evaluate an expression node or a string containing a Python expression. |
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
load_nifti_data (fname[, as_ndarray])
|
Load only the data array from a nifti file. |
lower_triangular (tensor[, b0])
|
Returns the six lower triangular values of the tensor ordered as (Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) and a dummy variable if b0 is not None. |
mean_diffusivity (evals[, axis])
|
Mean Diffusivity (MD) of a diffusion tensor. |
nifti1_symmat (image_data, *args, **kwargs)
|
Returns a Nifti1Image with a symmetric matrix intent |
peaks_from_model (model, data, sphere, ...[, ...])
|
Fit the model to data and computes peaks and metrics |
peaks_to_niftis (pam, fname_shm, fname_dirs, ...)
|
Save SH, directions, indices and values of peaks to Nifti. |
radial_diffusivity (evals[, axis])
|
Radial Diffusivity (RD) of a diffusion tensor. |
read_bvals_bvecs (fbvals, fbvecs)
|
Read b-values and b-vectors from disk. |
save_nifti (fname, data, affine[, hdr, dtype])
|
Save a data array into a nifti file. |
save_peaks (fname, pam[, affine, verbose])
|
Save all important attributes of object PeaksAndMetrics in a PAM5 file (HDF5). |
split_dki_param (dki_params)
|
Extract the diffusion tensor eigenvalues, the diffusion tensor eigenvector matrix, and the 15 independent elements of the kurtosis tensor from the model parameters estimated from the DKI model |
warn (/, message[, category, stacklevel, source])
|
Issue a warning, or maybe ignore it or raise an exception. |
Module: workflows.segment
LabelsBundlesFlow ([output_strategy, ...])
|
Methods
|
MedianOtsuFlow ([output_strategy, mix_names, ...])
|
Methods
|
RecoBundles (streamlines[, greater_than, ...])
|
Methods
|
RecoBundlesFlow ([output_strategy, ...])
|
Methods
|
Space (value)
|
Enum to simplify future change to convention |
StatefulTractogram (streamlines, reference, space)
|
Class for stateful representation of collections of streamlines Object designed to be identical no matter the file format (trk, tck, vtk, fib, dpy). |
Streamlines
|
alias of ArraySequence |
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
load_tractogram (filename, reference[, ...])
|
Load the stateful tractogram from any format (trk/tck/vtk/vtp/fib/dpy) |
median_otsu (input_volume[, vol_idx, ...])
|
Simple brain extraction tool method for images from DWI data. |
save_nifti (fname, data, affine[, hdr, dtype])
|
Save a data array into a nifti file. |
save_tractogram (sft, filename[, ...])
|
Save the stateful tractogram in any format (trk/tck/vtk/vtp/fib/dpy) |
time ()
|
Return the current time in seconds since the Epoch. |
Module: workflows.stats
BundleAnalysisTractometryFlow ([...])
|
Methods
|
BundleShapeAnalysis ([output_strategy, ...])
|
Methods
|
LinearMixedModelsFlow ([output_strategy, ...])
|
Methods
|
SNRinCCFlow ([output_strategy, mix_names, ...])
|
Methods
|
TensorModel (gtab[, fit_method, return_S0_hat])
|
Diffusion Tensor |
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
anatomical_measures (bundle, metric, dt, ...)
|
Calculates dti measure (eg: FA, MD) per point on streamlines and |
assignment_map (target_bundle, model_bundle, ...)
|
Calculates assignment maps of the target bundle with reference to model bundle centroids. |
binary_dilation (input[, structure, ...])
|
Multidimensional binary dilation with the given structuring element. |
bounding_box (vol)
|
Compute the bounding box of nonzero intensity voxels in the volume. |
buan_bundle_profiles (model_bundle_folder, ...)
|
Applies statistical analysis on bundles and saves the results in a directory specified by out_dir . |
bundle_shape_similarity (bundle1, bundle2, rng)
|
Calculates bundle shape similarity between two given bundles using bundle adjacency (BA) metric |
glob (pathname, *[, recursive])
|
Return a list of paths matching a pathname pattern. |
gradient_table (bvals[, bvecs, big_delta, ...])
|
A general function for creating diffusion MR gradients. |
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
load_peaks (fname[, verbose])
|
Load a PeaksAndMetrics HDF5 file (PAM5) |
load_tractogram (filename, reference[, ...])
|
Load the stateful tractogram from any format (trk/tck/vtk/vtp/fib/dpy) |
optional_package (name[, trip_msg])
|
Return package-like thing and module setup for package name |
peak_values (bundle, peaks, dt, pname, bname, ...)
|
Peak_values function finds the generalized fractional anisotropy (gfa) |
read_bvals_bvecs (fbvals, fbvecs)
|
Read b-values and b-vectors from disk. |
save_nifti (fname, data, affine[, hdr, dtype])
|
Save a data array into a nifti file. |
segment_from_cfa (tensor_fit, roi, threshold)
|
Segment the cfa inside roi using the values from threshold as bounds. |
time ()
|
Return the current time in seconds since the Epoch. |
transform_streamlines (streamlines, mat[, ...])
|
Apply affine transformation to streamlines |
Module: workflows.tracking
BinaryStoppingCriterion
|
cdef: |
ClosestPeakDirectionGetter
|
A direction getter that returns the closest odf peak to previous tracking direction. |
CmcStoppingCriterion
|
Continuous map criterion (CMC) stopping criterion from [1]. |
DeterministicMaximumDirectionGetter
|
Return direction of a sphere with the highest probability mass function (pmf). |
LocalFiberTrackingPAMFlow ([output_strategy, ...])
|
Methods
|
LocalTracking (direction_getter, ...[, ...])
|
|
PFTrackingPAMFlow ([output_strategy, ...])
|
Methods
|
ParticleFilteringTracking (direction_getter, ...)
|
|
ProbabilisticDirectionGetter
|
Randomly samples direction of a sphere based on probability mass function (pmf). |
Space (value)
|
Enum to simplify future change to convention |
StatefulTractogram (streamlines, reference, space)
|
Class for stateful representation of collections of streamlines Object designed to be identical no matter the file format (trk, tck, vtk, fib, dpy). |
ThresholdStoppingCriterion
|
# Declarations from stopping_criterion.pxd bellow cdef: double threshold, interp_out_double[1] double[:] interp_out_view = interp_out_view double[:, :, :] metric_map |
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
load_peaks (fname[, verbose])
|
Load a PeaksAndMetrics HDF5 file (PAM5) |
save_tractogram (sft, filename[, ...])
|
Save the stateful tractogram in any format (trk/tck/vtk/vtp/fib/dpy) |
Module: workflows.viz
HorizonFlow ([output_strategy, mix_names, ...])
|
Methods
|
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
assignment_map (target_bundle, model_bundle, ...)
|
Calculates assignment maps of the target bundle with reference to model bundle centroids. |
create_nifti_header (affine, dimensions, ...)
|
Write a standard nifti header from spatial attribute |
horizon ([tractograms, images, pams, ...])
|
Interactive medical visualization - Invert the Horizon! |
line_colors (streamlines[, cmap])
|
Create colors for streamlines to be used in actor.line. |
load_nifti (fname[, return_img, ...])
|
Load data and other information from a nifti file. |
load_peaks (fname[, verbose])
|
Load a PeaksAndMetrics HDF5 file (PAM5) |
load_tractogram (filename, reference[, ...])
|
Load the stateful tractogram from any format (trk/tck/vtk/vtp/fib/dpy) |
numpy_to_vtk_colors (colors)
|
Convert Numpy color array to a vtk color array. |
optional_package (name[, trip_msg])
|
Return package-like thing and module setup for package name |
pjoin (a, *p)
|
Join two or more pathname components, inserting '/' as needed. |
setup_module ()
|
|
Module: workflows.workflow
Workflow ([output_strategy, mix_names, ...])
|
Methods
|
io_iterator_ (frame, fnc[, output_strategy, ...])
|
Create an IOIterator using introspection. |
-
class dipy.workflows.align.AffineMap(affine, domain_grid_shape=None, domain_grid2world=None, codomain_grid_shape=None, codomain_grid2world=None)
Bases: object
Methods
get_affine ()
|
Return the value of the transformation, not a reference. |
set_affine (affine)
|
Set the affine transform (operating in physical space). |
transform (image[, interpolation, ...])
|
Transform the input image from co-domain to domain space. |
transform_inverse (image[, interpolation, ...])
|
Transform the input image from domain to co-domain space. |
-
__init__(affine, domain_grid_shape=None, domain_grid2world=None, codomain_grid_shape=None, codomain_grid2world=None)
AffineMap.
Implements an affine transformation whose domain is given by
domain_grid and domain_grid2world, and whose co-domain 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/co-domain information is not provided (None) then the
sampling information needs to be specified each time the transform
or transform_inverse is called to transform images. Note that such
sampling information is not necessary to transform points defined in
physical space, such as stream lines.
- Parameters:
- affinearray, shape (dim + 1, dim + 1)
the matrix defining the affine transform, where dim is the
dimension of the space this map operates in (2 for 2D images,
3 for 3D images). If None, then self represents the identity
transformation.
- domain_grid_shapesequence, shape (dim,), optional
the shape of the default domain sampling grid. When transform
is called to transform an image, the resulting image will have
this shape, unless a different sampling information is provided.
If None, then the sampling grid shape must be specified each time
the transform method is called.
- domain_grid2worldarray, shape (dim + 1, dim + 1), optional
the grid-to-world transform associated with the domain grid.
If None (the default), then the grid-to-world transform is assumed
to be the identity.
- codomain_grid_shapesequence of integers, shape (dim,)
the shape of the default co-domain sampling grid. When
transform_inverse is called to transform an image, the resulting
image will have this shape, unless a different sampling
information is provided. If None (the default), then the sampling
grid shape must be specified each time the transform_inverse
method is called.
- codomain_grid2worldarray, shape (dim + 1, dim + 1)
the grid-to-world transform associated with the co-domain grid.
If None (the default), then the grid-to-world transform is assumed
to be the identity.
-
get_affine()
Return the value of the transformation, not a reference.
- Returns:
- affinendarray
Copy of the transform, not a reference.
-
set_affine(affine)
Set the affine transform (operating in physical space).
Also sets self.affine_inv - the inverse of affine, or None if
there is no inverse.
- Parameters:
- affinearray, shape (dim + 1, dim + 1)
the matrix representing the affine transform operating in
physical space. The domain and co-domain information
remains unchanged. If None, then self represents the identity
transformation.
-
transform(image, interpolation='linear', image_grid2world=None, sampling_grid_shape=None, sampling_grid2world=None, resample_only=False)
Transform the input image from co-domain to domain space.
By default, the transformed image is sampled at a grid defined by
self.domain_shape and self.domain_grid2world. If such
information was not provided then sampling_grid_shape is mandatory.
- Parameters:
- image2D or 3D array
the image to be transformed
- interpolationstring, either ‘linear’ or ‘nearest’
the type of interpolation to be used, either ‘linear’
(for k-linear interpolation) or ‘nearest’ for nearest neighbor
- image_grid2worldarray, shape (dim + 1, dim + 1), optional
the grid-to-world transform associated with image.
If None (the default), then the grid-to-world transform is assumed
to be the identity.
- sampling_grid_shapesequence, shape (dim,), optional
the shape of the grid where the transformed image must be sampled.
If None (the default), then self.codomain_shape is used instead
(which must have been set at initialization, otherwise an exception
will be raised).
- sampling_grid2worldarray, shape (dim + 1, dim + 1), optional
the grid-to-world transform associated with the sampling grid
(specified by sampling_grid_shape, or by default
self.codomain_shape). If None (the default), then the
grid-to-world transform is assumed to be the identity.
- resample_onlyBoolean, optional
If False (the default) the affine transform is applied normally.
If True, then the affine transform is not applied, and the input
image is just re-sampled on the domain grid of this transform.
- Returns:
- transformedarray, shape sampling_grid_shape or
the transformed image, sampled at the requested grid
-
transform_inverse(image, interpolation='linear', image_grid2world=None, sampling_grid_shape=None, sampling_grid2world=None, resample_only=False)
Transform the input image from domain to co-domain space.
By default, the transformed image is sampled at a grid defined by
self.codomain_shape and self.codomain_grid2world. If such
information was not provided then sampling_grid_shape is mandatory.
- Parameters:
- image2D or 3D array
the image to be transformed
- interpolationstring, either ‘linear’ or ‘nearest’
the type of interpolation to be used, either ‘linear’
(for k-linear interpolation) or ‘nearest’ for nearest neighbor
- image_grid2worldarray, shape (dim + 1, dim + 1), optional
the grid-to-world transform associated with image.
If None (the default), then the grid-to-world transform is assumed
to be the identity.
- sampling_grid_shapesequence, shape (dim,), optional
the shape of the grid where the transformed image must be sampled.
If None (the default), then self.codomain_shape is used instead
(which must have been set at initialization, otherwise an exception
will be raised).
- sampling_grid2worldarray, shape (dim + 1, dim + 1), optional
the grid-to-world transform associated with the sampling grid
(specified by sampling_grid_shape, or by default
self.codomain_shape). If None (the default), then the
grid-to-world transform is assumed to be the identity.
- resample_onlyBoolean, optional
If False (the default) the affine transform is applied normally.
If True, then the affine transform is not applied, and the input
image is just re-sampled on the domain grid of this transform.
- Returns:
- transformedarray, shape sampling_grid_shape or
the transformed image, sampled at the requested grid
-
class dipy.workflows.align.CCMetric(dim, sigma_diff=2.0, radius=4)
Bases: SimilarityMetric
Methods
compute_backward ()
|
Computes one step bringing the static image towards the moving. |
compute_forward ()
|
Computes one step bringing the moving image towards the static. |
free_iteration ()
|
Frees the resources allocated during initialization |
get_energy ()
|
Numerical value assigned by this metric to the current image pair |
initialize_iteration ()
|
Prepares the metric to compute one displacement field iteration. |
set_levels_above (levels)
|
Informs the metric how many pyramid levels are above the current one |
set_levels_below (levels)
|
Informs the metric how many pyramid levels are below the current one |
set_moving_image (moving_image, ...)
|
Sets the moving image being compared against the static one. |
set_static_image (static_image, ...)
|
Sets the static image being compared against the moving one. |
use_moving_image_dynamics (...)
|
This is called by the optimizer just after setting the moving image |
use_static_image_dynamics (...)
|
This is called by the optimizer just after setting the static image. |
-
__init__(dim, sigma_diff=2.0, radius=4)
Normalized Cross-Correlation Similarity metric.
- Parameters:
- dimint (either 2 or 3)
the dimension of the image domain
- sigma_diffthe standard deviation of the Gaussian smoothing kernel to
be applied to the update field at each iteration
- radiusint
the radius of the squared (cubic) neighborhood at each voxel to be
considered to compute the cross correlation
-
compute_backward()
Computes one step bringing the static image towards the moving.
Computes the update displacement field to be used for registration of
the static image towards the moving image
-
compute_forward()
Computes one step bringing the moving image towards the static.
Computes the update displacement field to be used for registration of
the moving image towards the static image
-
free_iteration()
Frees the resources allocated during initialization
-
get_energy()
Numerical value assigned by this metric to the current image pair
Returns the Cross Correlation (data term) energy computed at the
largest iteration
-
initialize_iteration()
Prepares the metric to compute one displacement field iteration.
Pre-computes the cross-correlation factors for efficient computation
of the gradient of the Cross Correlation w.r.t. the displacement field.
It also pre-computes the image gradients in the physical space by
re-orienting the gradients in the voxel space using the corresponding
affine transformations.
-
class dipy.workflows.align.DiffeomorphicMap(dim, disp_shape, disp_grid2world=None, domain_shape=None, domain_grid2world=None, codomain_shape=None, codomain_grid2world=None, prealign=None)
Bases: object
Methods
transform_points |
|
transform_points_inverse |
|
-
__init__(dim, disp_shape, disp_grid2world=None, domain_shape=None, domain_grid2world=None, codomain_shape=None, codomain_grid2world=None, prealign=None)
DiffeomorphicMap
Implements a diffeomorphic transformation on the physical space. The
deformation fields encoding the direct and inverse transformations
share the same domain discretization (both the discretization grid
shape and voxel-to-space matrix). The input coordinates (physical
coordinates) are first aligned using prealign, and then displaced
using the corresponding vector field interpolated at the aligned
coordinates.
- Parameters:
- dimint, 2 or 3
the transformation’s dimension
- disp_shapearray, shape (dim,)
the number of slices (if 3D), rows and columns of the deformation
field’s discretization
- disp_grid2worldthe voxel-to-space transform between the def. fields
grid and space
- domain_shapearray, shape (dim,)
the number of slices (if 3D), rows and columns of the default
discretization of this map’s domain
- domain_grid2worldarray, shape (dim+1, dim+1)
the default voxel-to-space transformation between this map’s
discretization and physical space
- codomain_shapearray, shape (dim,)
the number of slices (if 3D), rows and columns of the images that
are ‘normally’ warped using this transformation in the forward
direction (this will provide default transformation parameters to
warp images under this transformation). By default, we assume that
the inverse transformation is ‘normally’ used to warp images with
the same discretization and voxel-to-space transformation as the
deformation field grid.
- codomain_grid2worldarray, shape (dim+1, dim+1)
the voxel-to-space transformation of images that are ‘normally’
warped using this transformation (in the forward direction).
- prealignarray, shape (dim+1, dim+1)
the linear transformation to be applied to align input images to
the reference space before warping under the deformation field.
-
allocate()
Creates a zero displacement field
Creates a zero displacement field (the identity transformation).
-
compute_inversion_error()
Inversion error of the displacement fields
Estimates the inversion error of the displacement fields by computing
statistics of the residual vectors obtained after composing the forward
and backward displacement fields.
- Returns:
- residualarray, shape (R, C) or (S, R, C)
the displacement field resulting from composing the forward and
backward displacement fields of this transformation (the residual
should be zero for a perfect diffeomorphism)
- statsarray, shape (3,)
statistics from the norms of the vectors of the residual
displacement field: maximum, mean and standard deviation
Notes
Since the forward and backward displacement fields have the same
discretization, the final composition is given by
comp[i] = forward[ i + Dinv * backward[i]]
where Dinv is the space-to-grid transformation of the displacement
fields
-
expand_fields(expand_factors, new_shape)
Expands the displacement fields from current shape to new_shape
Up-samples the discretization of the displacement fields to be of
new_shape shape.
- Parameters:
- expand_factorsarray, shape (dim,)
the factors scaling current spacings (voxel sizes) to spacings in
the expanded discretization.
- new_shapearray, shape (dim,)
the shape of the arrays holding the up-sampled discretization
-
get_backward_field()
Deformation field to transform an image in the backward direction
Returns the deformation field that must be used to warp an image under
this transformation in the backward direction (note the ‘is_inverse’
flag).
-
get_forward_field()
Deformation field to transform an image in the forward direction
Returns the deformation field that must be used to warp an image under
this transformation in the forward direction (note the ‘is_inverse’
flag).
-
get_simplified_transform()
Constructs a simplified version of this Diffeomorhic Map
The simplified version incorporates the pre-align transform, as well as
the domain and codomain affine transforms into the displacement field.
The resulting transformation may be regarded as operating on the
image spaces given by the domain and codomain discretization. As a
result, self.prealign, self.disp_grid2world, self.domain_grid2world and
self.codomain affine will be None (denoting Identity) in the resulting
diffeomorphic map.
-
interpret_matrix(obj)
Try to interpret obj as a matrix
Some operations are performed faster if we know in advance if a matrix
is the identity (so we can skip the actual matrix-vector
multiplication). This function returns None if the given object
is None or the ‘identity’ string. It returns the same object if it is
a numpy array. It raises an exception otherwise.
- Parameters:
- objobject
any object
- Returns:
- objobject
the same object given as argument if obj is None or a numpy
array. None if obj is the ‘identity’ string.
-
inverse()
Inverse of this DiffeomorphicMap instance
Returns a diffeomorphic map object representing the inverse of this
transformation. The internal arrays are not copied but just referenced.
- Returns:
- invDiffeomorphicMap object
the inverse of this diffeomorphic map.
-
shallow_copy()
Shallow copy of this DiffeomorphicMap instance
Creates a shallow copy of this diffeomorphic map (the arrays are not
copied but just referenced)
- Returns:
- new_mapDiffeomorphicMap object
the shallow copy of this diffeomorphic map
-
transform(image, interpolation='linear', image_world2grid=None, out_shape=None, out_grid2world=None)
Warps an image in the forward direction
Transforms the input image under this transformation in the forward
direction. It uses the “is_inverse” flag to switch between “forward”
and “backward” (if is_inverse is False, then transform(…) warps the
image forwards, else it warps the image backwards).
- Parameters:
- imagearray, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the forward
direction
- interpolationstring, either ‘linear’ or ‘nearest’
the type of interpolation to be used for warping, either ‘linear’
(for k-linear interpolation) or ‘nearest’ for nearest neighbor
- image_world2gridarray, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel
coordinates of the image given as input
- out_shapearray, shape (dim,)
the number of slices, rows and columns of the desired warped image
- out_grid2worldthe transformation bringing voxel coordinates of the
warped image to physical space
- Returns:
- warpedarray, shape = out_shape or self.codomain_shape if None
the warped image under this transformation in the forward direction
Notes
See _warp_forward and _warp_backward documentation for further
information.
-
transform_inverse(image, interpolation='linear', image_world2grid=None, out_shape=None, out_grid2world=None)
Warps an image in the backward direction
Transforms the input image under this transformation in the backward
direction. It uses the “is_inverse” flag to switch between “forward”
and “backward” (if is_inverse is False, then transform_inverse(…)
warps the image backwards, else it warps the image forwards)
- Parameters:
- imagearray, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the forward
direction
- interpolationstring, either ‘linear’ or ‘nearest’
the type of interpolation to be used for warping, either ‘linear’
(for k-linear interpolation) or ‘nearest’ for nearest neighbor
- image_world2gridarray, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel
coordinates of the image given as input
- out_shapearray, shape (dim,)
the number of slices, rows, and columns of the desired warped image
- out_grid2worldthe transformation bringing voxel coordinates of the
warped image to physical space
- Returns:
- warpedarray, shape = out_shape or self.codomain_shape if None
warped image under this transformation in the backward direction
Notes
See _warp_forward and _warp_backward documentation for further
information.
-
transform_points(points, coord2world=None, world2coord=None)
-
transform_points_inverse(points, coord2world=None, world2coord=None)
-
warp_endomorphism(phi)
Composition of this DiffeomorphicMap with a given endomorphism
Creates a new DiffeomorphicMap C with the same properties as self and
composes its displacement fields with phi’s corresponding fields.
The resulting diffeomorphism is of the form C(x) = phi(self(x)) with
inverse C^{-1}(y) = self^{-1}(phi^{-1}(y)). We assume that phi is an
endomorphism with the same discretization and domain affine as self
to ensure that the composition inherits self’s properties (we also
assume that the pre-aligning matrix of phi is None or identity).
- Parameters:
- phiDiffeomorphicMap object
the endomorphism to be warped by this diffeomorphic map
- Returns:
- compositionthe composition of this diffeomorphic map with the
endomorphism given as input
Notes
The problem with our current representation of a DiffeomorphicMap is
that the set of Diffeomorphism that can be represented this way (a
pre-aligning matrix followed by a non-linear 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’ mid-point algorithm (SyN)
are much simpler.
-
class dipy.workflows.align.EMMetric(dim, smooth=1.0, inner_iter=5, q_levels=256, double_gradient=True, step_type='gauss_newton')
Bases: SimilarityMetric
Methods
compute_backward ()
|
Computes one step bringing the static image towards the moving. |
compute_demons_step ([forward_step])
|
Demons step for EM metric |
compute_forward ()
|
Computes one step bringing the reference image towards the static. |
compute_gauss_newton_step ([forward_step])
|
Computes the Gauss-Newton energy minimization step |
free_iteration ()
|
Frees the resources allocated during initialization |
get_energy ()
|
The numerical value assigned by this metric to the current image pair |
initialize_iteration ()
|
Prepares the metric to compute one displacement field iteration. |
set_levels_above (levels)
|
Informs the metric how many pyramid levels are above the current one |
set_levels_below (levels)
|
Informs the metric how many pyramid levels are below the current one |
set_moving_image (moving_image, ...)
|
Sets the moving image being compared against the static one. |
set_static_image (static_image, ...)
|
Sets the static image being compared against the moving one. |
use_moving_image_dynamics (...)
|
This is called by the optimizer just after setting the moving image. |
use_static_image_dynamics (...)
|
This is called by the optimizer just after setting the static image. |
-
__init__(dim, smooth=1.0, inner_iter=5, q_levels=256, double_gradient=True, step_type='gauss_newton')
Expectation-Maximization Metric
Similarity metric based on the Expectation-Maximization algorithm to
handle multi-modal images. The transfer function is modeled as a set of
hidden random variables that are estimated at each iteration of the
algorithm.
- Parameters:
- dimint (either 2 or 3)
the dimension of the image domain
- smoothfloat
smoothness parameter, the larger the value the smoother the
deformation field
- inner_iterint
number of iterations to be performed at each level of the multi-
resolution Gauss-Seidel optimization algorithm (this is not the
number of steps per Gaussian Pyramid level, that parameter must
be set for the optimizer, not the metric)
- q_levelsnumber of quantization levels (equal to the number of hidden
variables in the EM algorithm)
- double_gradientboolean
if True, the gradient of the expected static image under the moving
modality will be added to the gradient of the moving image,
similarly, the gradient of the expected moving image under the
static modality will be added to the gradient of the static image.
- step_typestring (‘gauss_newton’, ‘demons’)
the optimization schedule to be used in the multi-resolution
Gauss-Seidel optimization algorithm (not used if Demons Step is
selected)
-
compute_backward()
Computes one step bringing the static image towards the moving.
Computes the update displacement field to be used for registration of
the static image towards the moving image
-
compute_demons_step(forward_step=True)
Demons step for EM metric
- Parameters:
- forward_stepboolean
if True, computes the Demons step in the forward direction
(warping the moving towards the static image). If False,
computes the backward step (warping the static image to the
moving image)
- Returns:
- displacementarray, shape (R, C, 2) or (S, R, C, 3)
the Demons step
-
compute_forward()
Computes one step bringing the reference image towards the static.
Computes the forward update field to register the moving image towards
the static image in a gradient-based optimization algorithm
-
compute_gauss_newton_step(forward_step=True)
Computes the Gauss-Newton 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
post-smoothing, as opposed to the demons step, which does not include
regularization). To accelerate convergence we use the multi-grid
Gauss-Seidel algorithm proposed by Bruhn and Weickert et al [Bruhn05]
- Parameters:
- forward_stepboolean
if True, computes the Newton step in the forward direction
(warping the moving towards the static image). If False,
computes the backward step (warping the static image to the
moving image)
- Returns:
- displacementarray, shape (R, C, 2) or (S, R, C, 3)
the Newton step
References
- [Bruhn05] Andres Bruhn and Joachim Weickert, “Towards ultimate motion
estimation: combining highest accuracy with real-time
performance”, 10th IEEE International Conference on Computer
Vision, 2005. ICCV 2005.
-
free_iteration()
Frees the resources allocated during initialization
-
get_energy()
The numerical value assigned by this metric to the current image pair
Returns the EM (data term) energy computed at the largest
iteration
-
initialize_iteration()
Prepares the metric to compute one displacement field iteration.
Pre-computes the transfer functions (hidden random variables) and
variances of the estimators. Also pre-computes 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
diff-demons does for mono-modality images. If the flag
self.use_double_gradient is True these gradients are averaged.
-
use_moving_image_dynamics(original_moving_image, transformation)
This is called by the optimizer just after setting the moving image.
EMMetric takes advantage of the image dynamics by computing the
current moving image mask from the original_moving_image mask (warped
by nearest neighbor interpolation)
- Parameters:
- original_moving_imagearray, shape (R, C) or (S, R, C)
the original moving image from which the current moving image was
generated, the current moving image is the one that was provided
via ‘set_moving_image(…)’, which may not be the same as the
original moving image but a warped version of it.
- transformationDiffeomorphicMap object
the transformation that was applied to the original_moving_image
to generate the current moving image
-
use_static_image_dynamics(original_static_image, transformation)
This is called by the optimizer just after setting the static image.
EMMetric takes advantage of the image dynamics by computing the
current static image mask from the originalstaticImage mask (warped
by nearest neighbor interpolation)
- Parameters:
- original_static_imagearray, shape (R, C) or (S, R, C)
the original static image from which the current static image was
generated, the current static image is the one that was provided
via ‘set_static_image(…)’, which may not be the same as the
original static image but a warped version of it (even the static
image changes during Symmetric Normalization, not only the moving
one).
- transformationDiffeomorphicMap object
the transformation that was applied to the original_static_image
to generate the current static image
-
class dipy.workflows.align.ImageRegistrationFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
The registration workflow allows the user to use only one type of
registration (such as center of mass or rigid body registration only).
Alternatively, a registration can be done in a progressive manner.
For example, using affine registration with progressive set to ‘True’
will involve center of mass, translation, rigid body and full affine
registration. Whereas, when progressive is False the registration will
include only center of mass and affine registration. The progressive
registration will be slower but will improve the quality.
This can be controlled by using the progressive flag (True by default).
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (static_image_files, moving_image_files)
|
- Parameters:
|
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
run(static_image_files, moving_image_files, transform='affine', nbins=32, sampling_prop=None, metric='mi', level_iters=(10000, 1000, 100), sigmas=(3.0, 1.0, 0.0), factors=(4, 2, 1), progressive=True, save_metric=False, out_dir='', out_moved='moved.nii.gz', out_affine='affine.txt', out_quality='quality_metric.txt')
- Parameters:
- static_image_filesstring
Path to the static image file.
- moving_image_filesstring
Path to the moving image file.
- transformstring, optional
com: center of mass, trans: translation, rigid: rigid body,
rigid_isoscaling: rigid body + isotropic scaling, rigid_scaling:
rigid body + scaling, affine: full affine including translation,
rotation, shearing and scaling.
- nbinsint, optional
Number of bins to discretize the joint and marginal PDF.
- sampling_propint, optional
- Number ([0-100]) of voxels for calculating the PDF.
‘None’ implies all voxels.
- metricstring, optional
Similarity metric for gathering mutual information).
- level_itersvariable int, 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
- sigmasvariable floats, optional
- Custom smoothing parameter to build the scale space (one parameter
for each scale).
- factorsvariable floats, optional
- Custom scale factors to build the scale space (one factor for each
scale).
- progressiveboolean, optional
Enable/Disable the progressive registration.
- save_metricboolean, optional
If true, quality assessment metric are saved in
‘quality_metric.txt’.
- out_dirstring, optional
- Directory to save the transformed image and the affine matrix
(default current directory).
- out_movedstring, optional
Name for the saved transformed image.
- out_affinestring, optional
Name for the saved affine matrix.
- out_qualitystring, optional
- Name of the file containing the saved quality
metric.
-
class dipy.workflows.align.MotionCorrectionFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
The Motion Correction workflow allows the user to align between-volumes
DWI dataset.
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, bvectors_files)
|
- Parameters:
|
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
run(input_files, bvalues_files, bvectors_files, b0_threshold=50, bvecs_tol=0.01, out_dir='', out_moved='moved.nii.gz', out_affine='affine.txt')
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvectors files. This path may contain wildcards to use
multiple bvectors files at once.
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- bvecs_tolfloat, optional
Threshold used to check that norm(bvec) = 1 +/- bvecs_tol
b-vectors are unit vectors
- out_dirstring, optional
- Directory to save the transformed image and the affine matrix
(default current directory).
- out_movedstring, optional
Name for the saved transformed image.
- out_affinestring, optional
Name for the saved affine matrix.
-
class dipy.workflows.align.ResliceFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, new_vox_size[, order, ...])
|
Reslice data with new voxel resolution defined by new_vox_sz |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, new_vox_size, order=1, mode='constant', cval=0, num_processes=1, out_dir='', out_resliced='resliced.nii.gz')
Reslice data with new voxel resolution defined by new_vox_sz
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- new_vox_sizevariable float
new voxel size.
- orderint, optional
order of interpolation, from 0 to 5, for resampling/reslicing,
0 nearest interpolation, 1 trilinear etc.. if you don’t want any
smoothing 0 is the option you need.
- modestring, optional
Points outside the boundaries of the input are filled according
to the given mode ‘constant’, ‘nearest’, ‘reflect’ or ‘wrap’.
- cvalfloat, optional
Value used for points outside the boundaries of the input if
mode=’constant’.
- num_processesint, optional
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.
- out_dirstring, optional
Output directory. (default current directory)
- out_reslicedstring, optional
Name of the resliced dataset to be saved.
-
class dipy.workflows.align.SSDMetric(dim, smooth=4, inner_iter=10, step_type='demons')
Bases: SimilarityMetric
Methods
compute_backward ()
|
Computes one step bringing the static image towards the moving. |
compute_demons_step ([forward_step])
|
Demons step for SSD metric |
compute_forward ()
|
Computes one step bringing the reference image towards the static. |
compute_gauss_newton_step ([forward_step])
|
Computes the Gauss-Newton energy minimization step |
free_iteration ()
|
Nothing to free for the SSD metric |
get_energy ()
|
The numerical value assigned by this metric to the current image pair |
initialize_iteration ()
|
Prepares the metric to compute one displacement field iteration. |
set_levels_above (levels)
|
Informs the metric how many pyramid levels are above the current one |
set_levels_below (levels)
|
Informs the metric how many pyramid levels are below the current one |
set_moving_image (moving_image, ...)
|
Sets the moving image being compared against the static one. |
set_static_image (static_image, ...)
|
Sets the static image being compared against the moving one. |
use_moving_image_dynamics (...)
|
This is called by the optimizer just after setting the moving image |
use_static_image_dynamics (...)
|
This is called by the optimizer just after setting the static image. |
-
__init__(dim, smooth=4, inner_iter=10, step_type='demons')
Sum of Squared Differences (SSD) Metric
Similarity metric for (mono-modal) nonlinear image registration defined
by the sum of squared differences (SSD)
- Parameters:
- dimint (either 2 or 3)
the dimension of the image domain
- smoothfloat
smoothness parameter, the larger the value the smoother the
deformation field
- inner_iterint
number of iterations to be performed at each level of the multi-
resolution Gauss-Seidel optimization algorithm (this is not the
number of steps per Gaussian Pyramid level, that parameter must
be set for the optimizer, not the metric)
- step_typestring
the displacement field step to be computed when ‘compute_forward’
and ‘compute_backward’ are called. Either ‘demons’ or
‘gauss_newton’
-
compute_backward()
Computes one step bringing the static image towards the moving.
Computes the updated displacement field to be used for registration of
the static image towards the moving image
-
compute_demons_step(forward_step=True)
Demons step for SSD metric
Computes the demons step proposed by Vercauteren et al.[Vercauteren09]
for the SSD metric.
- Parameters:
- forward_stepboolean
if True, computes the Demons step in the forward direction
(warping the moving towards the static image). If False,
computes the backward step (warping the static image to the
moving image)
- Returns:
- displacementarray, shape (R, C, 2) or (S, R, C, 3)
the Demons step
References
- [Vercauteren09] Tom Vercauteren, Xavier Pennec, Aymeric Perchant,
Nicholas Ayache, “Diffeomorphic Demons: Efficient
Non-parametric Image Registration”, Neuroimage 2009
-
compute_forward()
Computes one step bringing the reference image towards the static.
Computes the update displacement field to be used for registration of
the moving image towards the static image
-
compute_gauss_newton_step(forward_step=True)
Computes the Gauss-Newton energy minimization step
Minimizes the linearized energy function (Newton step) defined by the
sum of squared differences of corresponding pixels of the input images
with respect to the displacement field.
- Parameters:
- forward_stepboolean
if True, computes the Newton step in the forward direction
(warping the moving towards the static image). If False,
computes the backward step (warping the static image to the
moving image)
- Returns:
- displacementarray, shape = static_image.shape + (3,)
if forward_step==True, the forward SSD Gauss-Newton step,
else, the backward step
-
free_iteration()
Nothing to free for the SSD metric
-
get_energy()
The numerical value assigned by this metric to the current image pair
Returns the Sum of Squared Differences (data term) energy computed at
the largest iteration
-
initialize_iteration()
Prepares the metric to compute one displacement field iteration.
Pre-computes the gradient of the input images to be used in the
computation of the forward and backward steps.
-
class dipy.workflows.align.SlrWithQbxFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (static_files, moving_files[, x0, ...])
|
Streamline-based linear registration. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(static_files, moving_files, x0='affine', rm_small_clusters=50, qbx_thr=(40, 30, 20, 15), num_threads=None, greater_than=50, less_than=250, nb_pts=20, progressive=True, out_dir='', out_moved='moved.trk', out_affine='affine.txt', out_stat_centroids='static_centroids.trk', out_moving_centroids='moving_centroids.trk', out_moved_centroids='moved_centroids.trk')
Streamline-based linear registration.
For efficiency we apply the registration on cluster centroids and
remove small clusters.
- Parameters:
- static_filesstring
- moving_filesstring
- x0string, optional
rigid, similarity or affine transformation model.
- rm_small_clustersint, optional
Remove clusters that have less than rm_small_clusters.
- qbx_thrvariable int, optional
Thresholds for QuickBundlesX.
- num_threadsint, optional
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.
- greater_thanint, optional
Keep streamlines that have length greater than
this value.
- less_thanint, optional
Keep streamlines have length less than this value.
- nb_ptsint, optional
Number of points for discretizing each streamline.
- progressiveboolean, optional
- out_dirstring, optional
Output directory. (default current directory)
- out_movedstring, optional
Filename of moved tractogram.
- out_affinestring, optional
Filename of affine for SLR transformation.
- out_stat_centroidsstring, optional
Filename of static centroids.
- out_moving_centroidsstring, optional
Filename of moving centroids.
- out_moved_centroidsstring, optional
Filename of moved centroids.
Notes
The order of operations is the following. First short or long
streamlines are removed. Second the tractogram or a random selection
of the tractogram is clustered with QuickBundlesX. Then SLR
[Garyfallidis15] is applied.
References
registration of white-matter fascicles in the space of
streamlines”, NeuroImage, 117, 124–140, 2015
[Garyfallidis14]
Garyfallidis et al., “Direct native-space fiber
bundle alignment for group comparisons”, ISMRM, 2014.
[Garyfallidis17]
Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration
and clustering, NeuroImage, 2017.
-
class dipy.workflows.align.SymmetricDiffeomorphicRegistration(metric, level_iters=None, step_length=0.25, ss_sigma_factor=0.2, opt_tol=1e-05, inv_iter=20, inv_tol=0.001, callback=None)
Bases: DiffeomorphicRegistration
Methods
get_map ()
|
Return the resulting diffeomorphic map. |
optimize (static, moving[, ...])
|
Starts the optimization |
set_level_iters (level_iters)
|
Sets the number of iterations at each pyramid level |
update (current_displacement, ...)
|
Composition of the current displacement field with the given field |
-
__init__(metric, level_iters=None, step_length=0.25, ss_sigma_factor=0.2, opt_tol=1e-05, inv_iter=20, inv_tol=0.001, callback=None)
Symmetric Diffeomorphic Registration (SyN) Algorithm
Performs the multi-resolution optimization algorithm for non-linear
registration using a given similarity metric.
- Parameters:
- metricSimilarityMetric object
the metric to be optimized
- level_iterslist of int
the number of iterations at each level of the Gaussian Pyramid (the
length of the list defines the number of pyramid levels to be
used)
- opt_tolfloat
the optimization will stop when the estimated derivative of the
energy profile w.r.t. time falls below this threshold
- inv_iterint
the number of iterations to be performed by the displacement field
inversion algorithm
- step_lengthfloat
the length of the maximum displacement vector of the update
displacement field at each iteration
- ss_sigma_factorfloat
parameter of the scale-space smoothing kernel. For example, the
std. dev. of the kernel will be factor*(2^i) in the isotropic case
where i = 0, 1, …, n_scales is the scale
- inv_tolfloat
the displacement field inversion algorithm will stop iterating
when the inversion error falls below this threshold
- callbackfunction(SymmetricDiffeomorphicRegistration)
a function receiving a SymmetricDiffeomorphicRegistration object
to be called after each iteration (this optimizer will call this
function passing self as parameter)
-
get_map()
Return the resulting diffeomorphic map.
Returns the DiffeomorphicMap registering the moving image towards
the static image.
-
optimize(static, moving, static_grid2world=None, moving_grid2world=None, prealign=None)
Starts the optimization
- Parameters:
- staticarray, shape (S, R, C) or (R, C)
the image to be used as reference during optimization. The
displacement fields will have the same discretization as the static
image.
- movingarray, shape (S, R, C) or (R, C)
the image to be used as “moving” during optimization. Since the
deformation fields’ discretization is the same as the static image,
it is necessary to pre-align the moving image to ensure its domain
lies inside the domain of the deformation fields. This is assumed
to be accomplished by “pre-aligning” the moving image towards the
static using an affine transformation given by the ‘prealign’
matrix
- static_grid2worldarray, shape (dim+1, dim+1)
the voxel-to-space transformation associated to the static image
- moving_grid2worldarray, shape (dim+1, dim+1)
the voxel-to-space transformation associated to the moving image
- prealignarray, shape (dim+1, dim+1)
the affine transformation (operating on the physical space)
pre-aligning the moving image towards the static
- Returns:
- static_to_refDiffeomorphicMap object
the diffeomorphic map that brings the moving image towards the
static one in the forward direction (i.e. by calling
static_to_ref.transform) and the static image towards the
moving one in the backward direction (i.e. by calling
static_to_ref.transform_inverse).
-
update(current_displacement, new_displacement, disp_world2grid, time_scaling)
Composition of the current displacement field with the given field
Interpolates new displacement at the locations defined by
current_displacement. Equivalently, computes the composition C of the
given displacement fields as C(x) = B(A(x)), where A is
current_displacement and B is new_displacement. This function is
intended to be used with deformation fields of the same sampling
(e.g. to be called by a registration algorithm).
- Parameters:
- current_displacementarray, shape (R’, C’, 2) or (S’, R’, C’, 3)
the displacement field defining where to interpolate
new_displacement
- new_displacementarray, shape (R, C, 2) or (S, R, C, 3)
the displacement field to be warped by current_displacement
- disp_world2gridarray, shape (dim+1, dim+1)
the space-to-grid transform associated with the displacements’
grid (we assume that both displacements are discretized over the
same grid)
- time_scalingfloat
scaling factor applied to d2. The effect may be interpreted as
moving d1 displacements along a factor (time_scaling) of d2.
- Returns:
- updatedarray, shape (the same as new_displacement)
the warped displacement field
- mean_normthe mean norm of all vectors in current_displacement
-
class dipy.workflows.align.SynRegistrationFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (static_image_files, moving_image_files)
|
- Parameters:
|
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
run(static_image_files, moving_image_files, prealign_file='', inv_static=False, level_iters=(10, 10, 5), metric='cc', mopt_sigma_diff=2.0, mopt_radius=4, mopt_smooth=0.0, mopt_inner_iter=0, mopt_q_levels=256, mopt_double_gradient=True, mopt_step_type='', step_length=0.25, ss_sigma_factor=0.2, opt_tol=1e-05, inv_iter=20, inv_tol=0.001, out_dir='', out_warped='warped_moved.nii.gz', out_inv_static='inc_static.nii.gz', out_field='displacement_field.nii.gz')
- Parameters:
- static_image_filesstring
Path of the static image file.
- moving_image_filesstring
Path to the moving image file.
- prealign_filestring, optional
- The text file containing pre alignment information via an
affine matrix.
- inv_staticboolean, optional
Apply the inverse mapping to the static image.
- level_itersvariable int, optional
The number of iterations at each level of the gaussian pyramid.
- metricstring, optional
The metric to be used.
metric available: cc (Cross Correlation), ssd (Sum Squared
Difference), em (Expectation-Maximization).
- mopt_sigma_difffloat, optional
Metric option applied on Cross correlation (CC).
The standard deviation of the Gaussian smoothing kernel to be
applied to the update field at each iteration.
- mopt_radiusint, optional
Metric option applied on Cross correlation (CC).
the radius of the squared (cubic) neighborhood at each voxel to
be considered to compute the cross correlation.
- mopt_smoothfloat, optional
Metric option applied on Sum Squared Difference (SSD) and
Expectation Maximization (EM). Smoothness parameter, the
larger the value the smoother the deformation field.
(default 1.0 for EM, 4.0 for SSD)
- mopt_inner_iterint, optional
Metric option applied on Sum Squared Difference (SSD) and
Expectation Maximization (EM). This is number of iterations to be
performed at each level of the multi-resolution Gauss-Seidel
optimization algorithm (this is not the number of steps per
Gaussian Pyramid level, that parameter must be set for the
optimizer, not the metric). Default 5 for EM, 10 for SSD.
- mopt_q_levelsint, optional
Metric option applied on Expectation Maximization (EM).
Number of quantization levels (Default: 256 for EM)
- mopt_double_gradientbool, optional
Metric option applied on Expectation Maximization (EM).
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.
- mopt_step_typestring, optional
Metric option applied on Sum Squared Difference (SSD) and
Expectation Maximization (EM). The optimization schedule to be
used in the multi-resolution Gauss-Seidel optimization algorithm
(not used if Demons Step is selected). Possible value:
(‘gauss_newton’, ‘demons’). default: ‘gauss_newton’ for EM,
‘demons’ for SSD.
- step_lengthfloat, optional
- the length of the maximum displacement vector of the update
displacement field at each iteration.
- ss_sigma_factorfloat, optional
- parameter of the scale-space 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.
- opt_tolfloat, optional
- the optimization will stop when the estimated derivative of the
energy profile w.r.t. time falls below this threshold.
- inv_iterint, optional
- the number of iterations to be performed by the displacement field
inversion algorithm.
- inv_tolfloat, optional
- the displacement field inversion algorithm will stop iterating
when the inversion error falls below this threshold.
- out_dirstring, optional
Directory to save the transformed files (default current directory).
- out_warpedstring, optional
Name of the warped file.
- out_inv_staticstring, optional
- Name of the file to save the static image after applying the
inverse mapping.
- out_fieldstring, optional
Name of the file to save the diffeomorphic map.
-
class dipy.workflows.align.Workflow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: object
Methods
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_io_iterator()
Create an iterator for IO.
Use a couple of inspection tricks to build an IOIterator using the
previous frame (values of local variables and other contextuals) and
the run method’s docstring.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
get_sub_runs()
Return No sub runs since this is a simple workflow.
-
manage_output_overwrite()
Check if a file will be overwritten upon processing the inputs.
If it is bound to happen, an action is taken depending on
self._force_overwrite (or –force via command line). A log message is
output independently of the outcome to tell the user something
happened.
-
run(*args, **kwargs)
Execute the workflow.
Since this is an abstract class, raise exception if this code is
reached (not implemented in child class or literally called on this
class)
affine_registration
-
dipy.workflows.align.affine_registration(moving, static, moving_affine=None, static_affine=None, pipeline=None, starting_affine=None, metric='MI', level_iters=None, sigmas=None, factors=None, ret_metric=False, moving_mask=None, static_mask=None, **metric_kwargs)
Find the affine transformation between two 3D images. Alternatively, find
the combination of several linear transformations.
- Parameters:
- movingarray, nifti image or str
Containing the data for the moving object, or full path to a nifti file
with the moving data.
- staticarray, nifti image or str
Containing the data for the static object, or full path to a nifti file
with the moving data.
- moving_affine4x4 array, optional
An affine transformation associated with the moving object. Required if
data is provided as an array. If provided together with nifti/path,
will over-ride the affine that is in the nifti.
- static_affine4x4 array, optional
An affine transformation associated with the static object. Required if
data is provided as an array. If provided together with nifti/path,
will over-ride the affine that is in the nifti.
- pipelinelist of str, optional
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.
- starting_affine: 4x4 array, optional
Initial guess for the transformation between the spaces.
Default: identity.
- metricstr, optional.
Currently only supports ‘MI’ for MutualInformationMetric.
- level_iterssequence, optional
AffineRegistration key-word 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 3-level scale space with iterations
sequence equal to [10000, 1000, 100] will be used.
- sigmassequence of floats, optional
AffineRegistration key-word 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].
- factorssequence of floats, optional
AffineRegistration key-word 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].
- ret_metricboolean, optional
Set it to True to return the value of the optimized coefficients and
the optimization quality metric.
- moving_maskarray, shape (S’, R’, C’) or (R’, C’), optional
moving image mask that defines which pixels in the moving image
are used to calculate the mutual information.
- static_maskarray, shape (S, R, C) or (R, C), optional
static image mask that defines which pixels in the static image
are used to calculate the mutual information.
- nbinsint, optional
MutualInformationMetric key-word argument: the number of bins to be
used for computing the intensity histograms. The default is 32.
- sampling_proportionNone or float in interval (0, 1], optional
MutualInformationMetric key-word 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).
- Returns:
- transformedarray with moving data resampled to the static space
- after computing the affine transformation
- affinethe affine 4x4 associated with the transformation.
- xoptthe value of the optimized coefficients.
- foptthe value of the optimization quality metric.
Notes
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.
check_dimensions
-
dipy.workflows.align.check_dimensions(static, moving)
Check the dimensions of the input images.
- Parameters:
- static2D or 3D array
the image to be used as reference during optimization.
- moving: 2D or 3D array
the image to be used as “moving” during optimization. It is
necessary to pre-align the moving image to ensure its domain
lies inside the domain of the deformation fields. This is assumed
to be accomplished by “pre-aligning” the moving image towards the
static using an affine transformation given by the
‘starting_affine’ matrix.
gradient_table
-
dipy.workflows.align.gradient_table(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01, btens=None)
A general function for creating diffusion MR gradients.
It reads, loads and prepares scanner parameters like the b-values and
b-vectors so that they can be useful during the reconstruction process.
- Parameters:
- bvalscan be any of the four options
an array of shape (N,) or (1, N) or (N, 1) with the b-values.
a path for the file which contains an array like the above (1).
an array of shape (N, 4) or (4, N). Then this parameter is
considered to be a b-table which contains both bvals and bvecs. In
this case the next parameter is skipped.
a path for the file which contains an array like the one at (3).
- bvecscan be any of two options
an array of shape (N, 3) or (3, N) with the b-vectors.
a path for the file which contains an array like the previous.
- big_deltafloat
acquisition pulse separation time in seconds (default None)
- small_deltafloat
acquisition pulse duration time in seconds (default None)
- b0_thresholdfloat
All b-values with values less than or equal to bo_threshold are
considered as b0s i.e. without diffusion weighting.
- atolfloat
All b-vectors need to be unit vectors up to a tolerance.
- btenscan be any of three options
a string specifying the shape of the encoding tensor for all volumes
in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to
linear, planar, spherical, and “cigar-shaped” tensor encoding.
Tensors are rotated so that linear and cigar tensors are aligned
with the corresponding gradient direction and the planar tensor’s
normal is aligned with the corresponding gradient direction.
Magnitude is scaled to match the b-value.
an array of strings of shape (N,), (N, 1), or (1, N) specifying
encoding tensor shape for each volume separately. N corresponds to
the number volumes in data. Options for elements in array: ‘LTE’,
‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and
“cigar-shaped” tensor encoding. Tensors are rotated so that linear
and cigar tensors are aligned with the corresponding gradient
direction and the planar tensor’s normal is aligned with the
corresponding gradient direction. Magnitude is scaled to match the
b-value.
an array of shape (N,3,3) specifying the b-tensor of each volume
exactly. N corresponds to the number volumes in data. No rotation or
scaling is performed.
- Returns:
- gradientsGradientTable
A GradientTable with all the gradient information.
Notes
Often b0s (b-values which correspond to images without diffusion
weighting) have 0 values however in some cases the scanner cannot
provide b0s of an exact 0 value and it gives a bit higher values
e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.
We assume that the minimum number of b-values is 7.
B-vectors should be unit vectors.
Examples
>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... [sq2, sq2, 0],
... [sq2, 0, sq2],
... [0, sq2, sq2]])
>>> gt = gradient_table(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False
load_nifti
-
dipy.workflows.align.load_nifti(fname, return_img=False, return_voxsize=False, return_coords=False, as_ndarray=True)
Load data and other information from a nifti file.
- Parameters:
- fnamestr
Full path to a nifti file.
- return_imgbool, optional
Whether to return the nibabel nifti img object. Default: False
- return_voxsize: bool, optional
Whether to return the nifti header zooms. Default: False
- return_coordsbool, optional
Whether to return the nifti header aff2axcodes. Default: False
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray.
If you want to save memory and delay this casting, just turn this
option to False (default: True)
- Returns:
- A tuple, with (at the most, if all keyword args are set to True):
- (data, img.affine, img, vox_size, nib.aff2axcodes(img.affine))
read_bvals_bvecs
-
dipy.workflows.align.read_bvals_bvecs(fbvals, fbvecs)
Read b-values and b-vectors from disk.
- Parameters:
- fbvalsstr
Full path to file with b-values. None to not read bvals.
- fbvecsstr
Full path of file with b-vectors. None to not read bvecs.
- Returns:
- bvalsarray, (N,) or None
- bvecsarray, (N, 3) or None
Notes
Files can be either ‘.bvals’/’.bvecs’ or ‘.txt’ or ‘.npy’ (containing
arrays stored with the appropriate values).
reslice
-
dipy.workflows.align.reslice(data, affine, zooms, new_zooms, order=1, mode='constant', cval=0, num_processes=1)
Reslice data with new voxel resolution defined by new_zooms
.
- Parameters:
- dataarray, shape (I,J,K) or (I,J,K,N)
3d volume or 4d volume with datasets
- affinearray, shape (4,4)
mapping from voxel coordinates to world coordinates
- zoomstuple, shape (3,)
voxel size for (i,j,k) dimensions
- new_zoomstuple, shape (3,)
new voxel size for (i,j,k) after resampling
- orderint, from 0 to 5
order of interpolation for resampling/reslicing,
0 nearest interpolation, 1 trilinear etc..
if you don’t want any smoothing 0 is the option you need.
- modestring (‘constant’, ‘nearest’, ‘reflect’ or ‘wrap’)
Points outside the boundaries of the input are filled according
to the given mode.
- cvalfloat
Value used for points outside the boundaries of the input if
mode=’constant’.
- num_processesint, optional
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.
- Returns:
- data2array, shape (I,J,K) or (I,J,K,N)
datasets resampled into isotropic voxel size
- affine2array, shape (4,4)
new affine for the resampled image
Examples
>>> 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
save_nifti
-
dipy.workflows.align.save_nifti(fname, data, affine, hdr=None, dtype=None)
Save a data array into a nifti file.
- Parameters:
- fnamestr
The full path to the file to be saved.
- datandarray
The array with the data to save.
- affine4x4 array
The affine transform associated with the file.
- hdrnifti header, optional
May contain additional information to store in the file header.
- Returns:
- None
save_qa_metric
-
dipy.workflows.align.save_qa_metric(fname, xopt, fopt)
Save Quality Assurance metrics.
- Parameters:
- fname: string
File name to save the metric values.
- xopt: numpy array
The metric containing the
optimal parameters for
image registration.
- fopt: int
The distance between the registered images.
slr_with_qbx
-
dipy.workflows.align.slr_with_qbx(static, moving, x0='affine', rm_small_clusters=50, maxiter=100, select_random=None, verbose=False, greater_than=50, less_than=250, qbx_thr=(40, 30, 20, 15), nb_pts=20, progressive=True, rng=None, num_threads=None)
Utility function for registering large tractograms.
For efficiency, we apply the registration on cluster centroids and remove
small clusters.
- Parameters:
- staticStreamlines
- movingStreamlines
- x0str, optional.
rigid, similarity or affine transformation model (default affine)
- rm_small_clustersint, optional
Remove clusters that have less than rm_small_clusters (default 50)
- maxiterint, optional
Maximum number of iterations to perform.
- select_randomint, optional.
If not, None selects a random number of streamlines to apply clustering
Default None.
- verbosebool, optional
If True, logs information about optimization. Default: False
- greater_thanint, optional
Keep streamlines that have length greater than
this value (default 50)
- less_thanint, optional
Keep streamlines have length less than this value (default 250)
- qbx_thrvariable int
Thresholds for QuickBundlesX (default [40, 30, 20, 15])
- nb_ptsint, optional
Number of points for discretizing each streamline (default 20)
- progressiveboolean, optional
(default True)
- rngRandomState
If None creates RandomState in function.
- num_threadsint, optional
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.
Notes
The order of operations is the following. First short or long streamlines
are removed. Second, the tractogram or a random selection of the tractogram
is clustered with QuickBundles. Then SLR [Garyfallidis15] is applied.
References
registration of white-matter fascicles in the space of streamlines”,
NeuroImage, 117, 124–140, 2015
.. [R890e584ccf15-Garyfallidis14] Garyfallidis et al., “Direct native-space fiber
bundle alignment for group comparisons”, ISMRM, 2014.
[Garyfallidis17]
Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
warn
-
dipy.workflows.align.warn(/, message, category=None, stacklevel=1, source=None)
Issue a warning, or maybe ignore it or raise an exception.
-
class dipy.workflows.base.IntrospectiveArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=(), formatter_class=<class 'argparse.RawTextHelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='resolve', add_help=True)
Bases: ArgumentParser
- Attributes:
- optional_parameters
- output_parameters
- positional_parameters
Methods
add_argument (add_argument)
|
|
add_sub_flow_args (sub_flows)
|
Take an array of workflow objects and use introspection to extract the parameters, types and docstrings of their run method. |
add_subparsers (**kwargs)
|
|
add_workflow (workflow)
|
Take a workflow object and use introspection to extract the parameters, types and docstrings of its run method. |
error (message)
|
Prints a usage message incorporating the message to stderr and exits. |
exit ([status, message])
|
|
format_usage ()
|
|
get_flow_args ([args, namespace])
|
Return the parsed arguments as a dictionary that will be used as a workflow's run method arguments. |
parse_args ([args, namespace])
|
|
print_usage ([file])
|
|
register (registry_name, value, object)
|
|
set_defaults (**kwargs)
|
|
add_argument_group |
|
add_description |
|
add_epilogue |
|
add_mutually_exclusive_group |
|
convert_arg_line_to_args |
|
format_help |
|
get_default |
|
parse_intermixed_args |
|
parse_known_args |
|
parse_known_intermixed_args |
|
print_help |
|
show_argument |
|
update_argument |
|
-
__init__(prog=None, usage=None, description=None, epilog=None, parents=(), formatter_class=<class 'argparse.RawTextHelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='resolve', add_help=True)
Augmenting the argument parser to allow automatic creation of
arguments from workflows
- Parameters:
- progNone
The name of the program. (default: sys.argv[0])
- usageNone
A usage message. (default: auto-generated from arguments)
- descriptionstr
A description of what the program does.
- epilogstr
Text following the argument descriptions.
- parentslist
Parsers whose arguments should be copied into this one.
- formatter_classobj
HelpFormatter class for printing help messages.
- prefix_charsstr
Characters that prefix optional arguments.
- fromfile_prefix_charsNone
Characters that prefix files containing additional arguments.
- argument_defaultNone
The default value for all arguments.
- conflict_handlerstr
String indicating how to handle conflicts.
- add_helpbool
Add a -h/-help option.
-
add_description()
-
add_epilogue()
-
add_sub_flow_args(sub_flows)
Take an array of workflow objects and use introspection to extract
the parameters, types and docstrings of their run method. Only the
optional input parameters are extracted for these as they are treated
as sub workflows.
- Parameters:
- sub_flowsarray of dipy.workflows.workflow.Workflow
Workflows to inspect.
- Returns:
- sub_flow_optionalsdictionary of all sub workflow optional parameters
-
add_workflow(workflow)
Take a workflow object and use introspection to extract the
parameters, types and docstrings of its run method. Then add these
parameters to the current arparser’s own params to parse. If the
workflow is of type combined_workflow, the optional input parameters
of its sub workflows will also be added.
- Parameters:
- workflowdipy.workflows.workflow.Workflow
Workflow from which to infer parameters.
- Returns:
- sub_flow_optionalsdictionary of all sub workflow optional parameters
-
get_flow_args(args=None, namespace=None)
Return the parsed arguments as a dictionary that will be used
as a workflow’s run method arguments.
-
property optional_parameters
-
property output_parameters
-
property positional_parameters
-
show_argument(dest)
-
update_argument(*args, **kargs)
-
class dipy.workflows.base.NumpyDocString(docstring, config={})
Bases: object
-
__init__(docstring, config={})
get_args_default
-
dipy.workflows.base.get_args_default(func)
none_or_dtype
-
dipy.workflows.base.none_or_dtype(dtype)
Check None presence before type casting.
-
class dipy.workflows.combined_workflow.CombinedWorkflow(output_strategy='append', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_optionals (flow, **kwargs)
|
Returns the sub flow's optional arguments merged with those passed as params in kwargs. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Returns a list of tuples (sub flow name, sub flow run method, sub flow short name) to be used in the sub flow parameters extraction. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (*args, **kwargs)
|
Execute the workflow. |
run_sub_flow (flow, *args, **kwargs)
|
Runs the sub flow with the optional parameters passed via the command line. |
set_sub_flows_optionals (opts)
|
Sets the self._optionals variable with all sub flow arguments that were passed in the commandline. |
-
__init__(output_strategy='append', mix_names=False, force=False, skip=False)
Workflow that combines multiple workflows.
The workflow combined together are referred as sub flows in this class.
-
get_optionals(flow, **kwargs)
Returns the sub flow’s optional arguments merged with those passed
as params in kwargs.
-
get_sub_runs()
Returns a list of tuples
(sub flow name, sub flow run method, sub flow short name)
to be used in the sub flow parameters extraction.
-
run_sub_flow(flow, *args, **kwargs)
Runs the sub flow with the optional parameters passed via the
command line. This is a convenience method to make sub flow running
more intuitive on the concrete CombinedWorkflow side.
-
set_sub_flows_optionals(opts)
Sets the self._optionals variable with all sub flow arguments
that were passed in the commandline.
-
class dipy.workflows.combined_workflow.Workflow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: object
Methods
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_io_iterator()
Create an iterator for IO.
Use a couple of inspection tricks to build an IOIterator using the
previous frame (values of local variables and other contextuals) and
the run method’s docstring.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
get_sub_runs()
Return No sub runs since this is a simple workflow.
-
manage_output_overwrite()
Check if a file will be overwritten upon processing the inputs.
If it is bound to happen, an action is taken depending on
self._force_overwrite (or –force via command line). A log message is
output independently of the outcome to tell the user something
happened.
-
run(*args, **kwargs)
Execute the workflow.
Since this is an abstract class, raise exception if this code is
reached (not implemented in child class or literally called on this
class)
-
class dipy.workflows.denoise.GibbsRingingFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files[, slice_axis, n_points, ...])
|
Workflow for applying Gibbs Ringing method. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, slice_axis=2, n_points=3, num_processes=1, out_dir='', out_unring='dwi_unring.nii.gz')
Workflow for applying Gibbs Ringing method.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- slice_axisint, optional
Data axis corresponding to the number of acquired slices.
Could be (0, 1, or 2): for example, a value of 2 would mean the
third axis.
- n_pointsint, optional
Number of neighbour points to access local TV (see note).
- num_processesint or None, optional
Split the calculation to a pool of children processes. Only
applies to 3D or 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.
- out_dirstring, optional
Output directory. (default current directory)
- out_unringstring, optional
Name of the resulting denoised volume.
References
[1]
Neto Henriques, R., 2018. Advanced Methods for Diffusion MRI
Data Analysis and their Application to the Healthy Ageing Brain
(Doctoral thesis). https://doi.org/10.17863/CAM.29356
[2]
Kellner E, Dhital B, Kiselev VG, Reisert M. Gibbs-ringing
artifact removal based on local subvoxel-shifts. Magn Reson Med. 2016
doi: 10.1002/mrm.26054.
-
class dipy.workflows.denoise.LPCAFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, bvectors_files)
|
Workflow wrapping LPCA denoising method. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bvalues_files, bvectors_files, sigma=0, b0_threshold=50, bvecs_tol=0.01, patch_radius=2, pca_method='eig', tau_factor=2.3, out_dir='', out_denoised='dwi_lpca.nii.gz')
Workflow wrapping LPCA denoising method.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvectors files. This path may contain wildcards to use
multiple bvectors files at once.
- sigmafloat, optional
Standard deviation of the noise estimated from the data.
Default 0: it means sigma value estimation with the Manjon2013
algorithm [3].
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- bvecs_tolfloat, optional
Threshold used to check that norm(bvec) = 1 +/- bvecs_tol
b-vectors are unit vectors.
- patch_radiusint, optional
The radius of the local patch to be taken around each voxel (in
voxels) For example, for a patch radius with value 2, and assuming
the input image is a 3D image, the denoising will take place in
blocks of 5x5x5 voxels.
- pca_methodstring, optional
Use either eigenvalue decomposition (‘eig’) or singular value
decomposition (‘svd’) for principal component analysis. The default
method is ‘eig’ which is faster. However, occasionally ‘svd’ might
be more accurate.
- tau_factorfloat, optional
Thresholding of PCA eigenvalues is done by nulling out eigenvalues
that are smaller than:
\[\tau = (\tau_{factor} \sigma)^2\]
tau_{factor} can be change to adjust the relationship between the
noise standard deviation and the threshold tau. If tau_{factor}
is set to None, it will be automatically calculated using the
Marcenko-Pastur distribution [2].
- out_dirstring, optional
Output directory. (default current directory)
- out_denoisedstring, optional
Name of the resulting denoised volume.
References
[1]
Veraart J, Novikov DS, Christiaens D, Ades-aron B, Sijbers,
Fieremans E, 2016. Denoising of Diffusion MRI using random
matrix theory. Neuroimage 142:394-406.
doi: 10.1016/j.neuroimage.2016.08.016
[2]
Veraart J, Fieremans E, Novikov DS. 2016. Diffusion MRI noise
mapping using random matrix theory. Magnetic Resonance in
Medicine.
doi: 10.1002/mrm.26059.
[3]
Manjon JV, Coupe P, Concha L, Buades A, Collins DL (2013)
Diffusion Weighted Image Denoising Using Overcomplete Local
PCA. PLoS ONE 8(9): e73021.
https://doi.org/10.1371/journal.pone.0073021
-
class dipy.workflows.denoise.MPPCAFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files[, patch_radius, pca_method, ...])
|
Workflow wrapping Marcenko-Pastur PCA denoising method. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, patch_radius=2, pca_method='eig', return_sigma=False, out_dir='', out_denoised='dwi_mppca.nii.gz', out_sigma='dwi_sigma.nii.gz')
Workflow wrapping Marcenko-Pastur PCA denoising method.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- patch_radiusvariable int, optional
The radius of the local patch to be taken around each voxel (in
voxels) For example, for a patch radius with value 2, and assuming
the input image is a 3D image, the denoising will take place in
blocks of 5x5x5 voxels.
- pca_methodstring, optional
Use either eigenvalue decomposition (‘eig’) or singular value
decomposition (‘svd’) for principal component analysis. The default
method is ‘eig’ which is faster. However, occasionally ‘svd’ might
be more accurate.
- return_sigmabool, optional
If true, a noise standard deviation estimate based on the
Marcenko-Pastur distribution is returned [2].
- out_dirstring, optional
Output directory. (default current directory)
- out_denoisedstring, optional
Name of the resulting denoised volume.
- out_sigmastring, optional
Name of the resulting sigma volume.
References
[1]
Veraart J, Novikov DS, Christiaens D, Ades-aron B, Sijbers,
Fieremans E, 2016. Denoising of Diffusion MRI using random matrix
theory. Neuroimage 142:394-406.
doi: 10.1016/j.neuroimage.2016.08.016
[2]
Veraart J, Fieremans E, Novikov DS. 2016. Diffusion MRI noise
mapping using random matrix theory. Magnetic Resonance in Medicine.
doi: 10.1002/mrm.26059.
-
class dipy.workflows.denoise.NLMeansFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files[, sigma, patch_radius, ...])
|
Workflow wrapping the nlmeans denoising method. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, sigma=0, patch_radius=1, block_radius=5, rician=True, out_dir='', out_denoised='dwi_nlmeans.nii.gz')
Workflow wrapping the nlmeans denoising method.
It applies nlmeans denoise on each file found by ‘globing’
input_files
and saves the results in a directory specified by
out_dir
.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- sigmafloat, optional
Sigma parameter to pass to the nlmeans algorithm.
- patch_radiusint, optional
patch size is 2 x patch_radius + 1
.
- block_radiusint, optional
block size is 2 x block_radius + 1
.
- ricianbool, optional
If True the noise is estimated as Rician, otherwise Gaussian noise
is assumed.
- out_dirstring, optional
Output directory. (default current directory)
- out_denoisedstring, optional
Name of the resulting denoised volume.
References
[Descoteaux08]
Descoteaux, Maxime and Wiest-Daesslé, Nicolas and
Prima, Sylvain and Barillot, Christian and Deriche, Rachid.
Impact of Rician Adapted Non-Local Means Filtering on
HARDI, MICCAI 2008
-
class dipy.workflows.denoise.Patch2SelfFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bval_files[, model, ...])
|
Workflow for Patch2Self denoising method. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bval_files, model='ols', b0_threshold=50, alpha=1.0, verbose=False, b0_denoising=True, clip_negative_vals=False, shift_intensity=True, out_dir='', out_denoised='dwi_patch2self.nii.gz')
Workflow for Patch2Self denoising method.
It applies patch2self denoising on each file found by ‘globing’
input_file
and bval_file
. It saves the results in a directory
specified by out_dir
.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bval_filesstring
bval file associated with the diffusion data.
- modelstring, or initialized linear model object.
This will determine the algorithm used to solve the set of linear
equations underlying this model. If it is a string it needs to be
one of the following: {‘ols’, ‘ridge’, ‘lasso’}. Otherwise,
it can be an object that inherits from
dipy.optimize.SKLearnLinearSolver or an object with a similar
interface from Scikit-Learn:
sklearn.linear_model.LinearRegression,
sklearn.linear_model.Lasso or sklearn.linear_model.Ridge
and other objects that inherit from sklearn.base.RegressorMixin.
Default: ‘ols’.
- b0_thresholdint, optional
Threshold for considering volumes as b0.
- alphafloat, optional
Regularization parameter only for ridge regression model.
- verbosebool, optional
Show progress of Patch2Self and time taken.
- b0_denoisingbool, optional
Skips denoising b0 volumes if set to False.
- clip_negative_valsbool, optional
Sets negative values after denoising to 0 using np.clip.
- shift_intensitybool, optional
Shifts the distribution of intensities per volume to give
non-negative values
- out_dirstring, optional
Output directory (default current directory)
- out_denoisedstring, optional
Name of the resulting denoised volume
(default: dwi_patch2self.nii.gz)
References
[Fadnavis20]
S. Fadnavis, J. Batson, E. Garyfallidis, Patch2Self:
Denoising Diffusion MRI with Self-supervised Learning,
Advances in Neural Information Processing Systems 33 (2020)
-
class dipy.workflows.denoise.Workflow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: object
Methods
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_io_iterator()
Create an iterator for IO.
Use a couple of inspection tricks to build an IOIterator using the
previous frame (values of local variables and other contextuals) and
the run method’s docstring.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
get_sub_runs()
Return No sub runs since this is a simple workflow.
-
manage_output_overwrite()
Check if a file will be overwritten upon processing the inputs.
If it is bound to happen, an action is taken depending on
self._force_overwrite (or –force via command line). A log message is
output independently of the outcome to tell the user something
happened.
-
run(*args, **kwargs)
Execute the workflow.
Since this is an abstract class, raise exception if this code is
reached (not implemented in child class or literally called on this
class)
deprecated_params
-
dipy.workflows.denoise.deprecated_params(old_name, new_name=None, since='', until='', version_comparator=<function cmp_pkg_version>, arg_in_kwargs=False, warn_class=<class 'dipy.utils.deprecator.ArgsDeprecationWarning'>, error_class=<class 'dipy.utils.deprecator.ExpiredDeprecationError'>, alternative='')
Deprecate a renamed or removed function argument.
The decorator assumes that the argument with the old_name
was removed
from the function signature and the new_name
replaced it at the
same position in the signature. If the old_name
argument is
given when calling the decorated function the decorator will catch it and
issue a deprecation warning and pass it on as new_name
argument.
- Parameters:
- old_namestr or list/tuple thereof
The old name of the argument.
- new_namestr or list/tuple thereof or
None
, optional The new name of the argument. Set this to None to remove the
argument old_name
instead of renaming it.
- sincestr or number or list/tuple thereof, optional
The release at which the old argument became deprecated.
- untilstr or number or list/tuple thereof, optional
Last released version at which this function will still raise a
deprecation warning. Versions higher than this will raise an
error.
- version_comparatorcallable
Callable accepting string as argument, and return 1 if string
represents a higher version than encoded in the version_comparator
,
0 if the version is equal, and -1 if the version is lower. For example,
the version_comparator
may compare the input version string to the
current package version string.
- arg_in_kwargsbool or list/tuple thereof, optional
If the argument is not a named argument (for example it
was meant to be consumed by **kwargs
) set this to
True
. Otherwise the decorator will throw an Exception
if the new_name
cannot be found in the signature of
the decorated function.
Default is False
.
- warn_classwarning, optional
Warning to be issued.
- error_classException, optional
Error to be issued
- alternativestr, optional
An alternative function or class name that the user may use in
place of the deprecated object if new_name
is None. The deprecation
warning will tell the user about this alternative if provided.
- Raises:
- TypeError
If the new argument name cannot be found in the function
signature and arg_in_kwargs was False or if it is used to
deprecate the name of the *args
-, **kwargs
-like arguments.
At runtime such an Error is raised if both the new_name
and old_name were specified when calling the function and
“relax=False”.
Notes
This function is based on the Astropy (major modification).
https://github.com/astropy/astropy. See COPYING file distributed along with
the astropy package for the copyright and license terms.
Examples
The deprecation warnings are not shown in the following examples.
To deprecate a positional or keyword argument::
>>> from dipy.utils.deprecator import deprecated_params
>>> @deprecated_params(‘sig’, ‘sigma’, ‘0.3’)
… def test(sigma):
… return sigma
>>> test(2)
2
>>> test(sigma=2)
2
>>> test(sig=2) # doctest: +SKIP
2
It is also possible to replace multiple arguments. The old_name
,
new_name
and since
have to be tuple or list and contain the
same number of entries::
>>> @deprecated_params([‘a’, ‘b’], [‘alpha’, ‘beta’],
… [‘0.2’, 0.4])
… def test(alpha, beta):
… return alpha, beta
>>> test(a=2, b=3) # doctest: +SKIP
(2, 3)
estimate_sigma
-
dipy.workflows.denoise.estimate_sigma(arr, disable_background_masking=False, N=0)
Standard deviation estimation from local patches
- Parameters:
- arr3D or 4D ndarray
The array to be estimated
- disable_background_maskingbool, default False
If True, uses all voxels for the estimation, otherwise, only non-zeros
voxels are used. Useful if the background is masked by the scanner.
- Nint, default 0
Number of coils of the receiver array. Use N = 1 in case of a SENSE
reconstruction (Philips scanners) or the number of coils for a GRAPPA
reconstruction (Siemens and GE). Use 0 to disable the correction factor,
as for example if the noise is Gaussian distributed. See [1] for more
information.
- Returns:
- sigmandarray
standard deviation of the noise, one estimation per volume.
Notes
This function is the same as manually taking the standard deviation of the
background and gives one value for the whole 3D array.
It also includes the coil-dependent correction factor of Koay 2006
(see [1], equation 18) with theta = 0.
Since this function was introduced in [2] for T1 imaging,
it is expected to perform ok on diffusion MRI data, but might oversmooth
some regions and leave others un-denoised for spatially varying noise
profiles. Consider using piesno()
to estimate sigma instead if visual
inaccuracies are apparent in the denoised result.
References
[1]
Koay, C. G., & Basser, P. J. (2006). Analytically exact correction
scheme for signal extraction from noisy magnitude MR signals.
Journal of Magnetic Resonance), 179(2), 317-22.
[2]
Coupe, P., Yger, P., Prima, S., Hellier, P., Kervrann, C., Barillot,
C., 2008. An optimized blockwise nonlocal means denoising filter for 3-D
magnetic resonance images, IEEE Trans. Med. Imaging 27, 425-41.
gibbs_removal
-
dipy.workflows.denoise.gibbs_removal(vol, slice_axis=2, n_points=3, inplace=True, num_processes=1)
Suppresses Gibbs ringing artefacts of images volumes.
- Parameters:
- volndarray ([X, Y]), ([X, Y, Z]) or ([X, Y, Z, g])
Matrix containing one volume (3D) or multiple (4D) volumes of images.
- slice_axisint (0, 1, or 2)
Data axis corresponding to the number of acquired slices.
Default is set to the third axis.
- n_pointsint, optional
Number of neighbour points to access local TV (see note).
Default is set to 3.
- inplacebool, optional
If True, the input data is replaced with results. Otherwise, returns
a new array.
Default is set to True.
- num_processesint or None, optional
Split the calculation to a pool of children processes. This only
applies to 3D or 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.
- Returns:
- volndarray ([X, Y]), ([X, Y, Z]) or ([X, Y, Z, g])
Matrix containing one volume (3D) or multiple (4D) volumes of corrected
images.
Notes
For 4D matrix last element should always correspond to the number of
diffusion gradient directions.
References
Please cite the following articles
.. [Rae70c6436165-1] Neto Henriques, R., 2018. Advanced Methods for Diffusion MRI Data
[2]
Kellner E, Dhital B, Kiselev VG, Reisert M. Gibbs-ringing artifact
removal based on local subvoxel-shifts. Magn Reson Med. 2016
doi: 10.1002/mrm.26054.
gradient_table
-
dipy.workflows.denoise.gradient_table(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01, btens=None)
A general function for creating diffusion MR gradients.
It reads, loads and prepares scanner parameters like the b-values and
b-vectors so that they can be useful during the reconstruction process.
- Parameters:
- bvalscan be any of the four options
an array of shape (N,) or (1, N) or (N, 1) with the b-values.
a path for the file which contains an array like the above (1).
an array of shape (N, 4) or (4, N). Then this parameter is
considered to be a b-table which contains both bvals and bvecs. In
this case the next parameter is skipped.
a path for the file which contains an array like the one at (3).
- bvecscan be any of two options
an array of shape (N, 3) or (3, N) with the b-vectors.
a path for the file which contains an array like the previous.
- big_deltafloat
acquisition pulse separation time in seconds (default None)
- small_deltafloat
acquisition pulse duration time in seconds (default None)
- b0_thresholdfloat
All b-values with values less than or equal to bo_threshold are
considered as b0s i.e. without diffusion weighting.
- atolfloat
All b-vectors need to be unit vectors up to a tolerance.
- btenscan be any of three options
a string specifying the shape of the encoding tensor for all volumes
in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to
linear, planar, spherical, and “cigar-shaped” tensor encoding.
Tensors are rotated so that linear and cigar tensors are aligned
with the corresponding gradient direction and the planar tensor’s
normal is aligned with the corresponding gradient direction.
Magnitude is scaled to match the b-value.
an array of strings of shape (N,), (N, 1), or (1, N) specifying
encoding tensor shape for each volume separately. N corresponds to
the number volumes in data. Options for elements in array: ‘LTE’,
‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and
“cigar-shaped” tensor encoding. Tensors are rotated so that linear
and cigar tensors are aligned with the corresponding gradient
direction and the planar tensor’s normal is aligned with the
corresponding gradient direction. Magnitude is scaled to match the
b-value.
an array of shape (N,3,3) specifying the b-tensor of each volume
exactly. N corresponds to the number volumes in data. No rotation or
scaling is performed.
- Returns:
- gradientsGradientTable
A GradientTable with all the gradient information.
Notes
Often b0s (b-values which correspond to images without diffusion
weighting) have 0 values however in some cases the scanner cannot
provide b0s of an exact 0 value and it gives a bit higher values
e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.
We assume that the minimum number of b-values is 7.
B-vectors should be unit vectors.
Examples
>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... [sq2, sq2, 0],
... [sq2, 0, sq2],
... [0, sq2, sq2]])
>>> gt = gradient_table(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False
load_nifti
-
dipy.workflows.denoise.load_nifti(fname, return_img=False, return_voxsize=False, return_coords=False, as_ndarray=True)
Load data and other information from a nifti file.
- Parameters:
- fnamestr
Full path to a nifti file.
- return_imgbool, optional
Whether to return the nibabel nifti img object. Default: False
- return_voxsize: bool, optional
Whether to return the nifti header zooms. Default: False
- return_coordsbool, optional
Whether to return the nifti header aff2axcodes. Default: False
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray.
If you want to save memory and delay this casting, just turn this
option to False (default: True)
- Returns:
- A tuple, with (at the most, if all keyword args are set to True):
- (data, img.affine, img, vox_size, nib.aff2axcodes(img.affine))
localpca
-
dipy.workflows.denoise.localpca(arr, sigma, mask=None, patch_radius=2, pca_method='eig', tau_factor=2.3, out_dtype=None, suppress_warning=False)
Performs local PCA denoising according to Manjon et al. [1].
- Parameters:
- arr4D array
Array of data to be denoised. The dimensions are (X, Y, Z, N), where N
are the diffusion gradient directions.
- sigmafloat or 3D array
Standard deviation of the noise estimated from the data.
- mask3D boolean array (optional)
A mask with voxels that are true inside the brain and false outside of
it. The function denoises within the true part and returns zeros
outside of those voxels.
- patch_radiusint or 1D array (optional)
The radius of the local patch to be taken around each voxel (in
voxels). Default: 2 (denoise in blocks of 5x5x5 voxels).
- pca_method‘eig’ or ‘svd’ (optional)
Use either eigenvalue decomposition (eig) or singular value
decomposition (svd) for principal component analysis. The default
method is ‘eig’ which is faster. However, occasionally ‘svd’ might be
more accurate.
- tau_factorfloat (optional)
Thresholding of PCA eigenvalues is done by nulling out eigenvalues that
are smaller than:
\[\tau = (\tau_{factor} \sigma)^2\]
tau_{factor} can be change to adjust the relationship between the
noise standard deviation and the threshold tau. If tau_{factor} is
set to None, it will be automatically calculated using the
Marcenko-Pastur distribution [2].
Default: 2.3 (according to [1])
- out_dtypestr or dtype (optional)
The dtype for the output array. Default: output has the same dtype as
the input.
- suppress_warningbool (optional)
If true, suppress warning caused by patch_size < arr.shape[-1].
Default: False.
- Returns:
- denoised_arr4D array
This is the denoised array of the same size as that of the input data,
clipped to non-negative values
References
[2]
Veraart J, Novikov DS, Christiaens D, Ades-aron B, Sijbers,
Fieremans E, 2016. Denoising of Diffusion MRI using random matrix
theory. Neuroimage 142:394-406.
doi: 10.1016/j.neuroimage.2016.08.016
mppca
-
dipy.workflows.denoise.mppca(arr, mask=None, patch_radius=2, pca_method='eig', return_sigma=False, out_dtype=None, suppress_warning=False)
Performs PCA-based denoising using the Marcenko-Pastur
distribution [1].
- Parameters:
- arr4D array
Array of data to be denoised. The dimensions are (X, Y, Z, N), where N
are the diffusion gradient directions.
- mask3D boolean array (optional)
A mask with voxels that are true inside the brain and false outside of
it. The function denoises within the true part and returns zeros
outside of those voxels.
- patch_radiusint or 1D array (optional)
The radius of the local patch to be taken around each voxel (in
voxels). Default: 2 (denoise in blocks of 5x5x5 voxels).
- pca_method‘eig’ or ‘svd’ (optional)
Use either eigenvalue decomposition (eig) or singular value
decomposition (svd) for principal component analysis. The default
method is ‘eig’ which is faster. However, occasionally ‘svd’ might be
more accurate.
- return_sigmabool (optional)
If true, a noise standard deviation estimate based on the
Marcenko-Pastur distribution is returned [2].
Default: False.
- out_dtypestr or dtype (optional)
The dtype for the output array. Default: output has the same dtype as
the input.
- suppress_warningbool (optional)
If true, suppress warning caused by patch_size < arr.shape[-1].
Default: False.
- Returns:
- denoised_arr4D array
This is the denoised array of the same size as that of the input data,
clipped to non-negative values
- sigma3D array (when return_sigma=True)
Estimate of the spatial varying standard deviation of the noise
References
[1]
(1,2)
Veraart J, Novikov DS, Christiaens D, Ades-aron B, Sijbers,
Fieremans E, 2016. Denoising of Diffusion MRI using random matrix
theory. Neuroimage 142:394-406.
doi: 10.1016/j.neuroimage.2016.08.016
[2]
Veraart J, Fieremans E, Novikov DS. 2016. Diffusion MRI noise
mapping using random matrix theory. Magnetic Resonance in Medicine.
doi: 10.1002/mrm.26059.
nlmeans
-
dipy.workflows.denoise.nlmeans(arr, sigma, mask=None, patch_radius=1, block_radius=5, rician=True, num_threads=None)
Non-local means for denoising 3D and 4D images
- Parameters:
- arr3D or 4D ndarray
The array to be denoised
- mask3D ndarray
- sigmafloat or 3D array
standard deviation of the noise estimated from the data
- patch_radiusint
patch size is 2 x patch_radius + 1
. Default is 1.
- block_radiusint
block size is 2 x block_radius + 1
. Default is 5.
- ricianboolean
If True the noise is estimated as Rician, otherwise Gaussian noise
is assumed.
- num_threadsint, optional
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.
- Returns:
- denoised_arrndarray
the denoised arr
which has the same shape as arr
.
References
[Descoteaux08]
Descoteaux, Maxime and Wiest-Daesslé, Nicolas and Prima,
Sylvain and Barillot, Christian and Deriche, Rachid
Impact of Rician Adapted Non-Local Means Filtering on
HARDI, MICCAI 2008
patch2self
-
dipy.workflows.denoise.patch2self(data, bvals, patch_radius=(0, 0, 0), model='ols', b0_threshold=50, out_dtype=None, alpha=1.0, verbose=False, b0_denoising=True, clip_negative_vals=False, shift_intensity=True)
Patch2Self Denoiser.
- Parameters:
- datandarray
The 4D noisy DWI data to be denoised.
- bvals1D array
Array of the bvals from the DWI acquisition
- patch_radiusint or 1D array, optional
The radius of the local patch to be taken around each voxel (in
voxels). Default: 0 (denoise in blocks of 1x1x1 voxels).
- modelstring, or initialized linear model object.
This will determine the algorithm used to solve the set of linear
equations underlying this model. If it is a string it needs to be
one of the following: {‘ols’, ‘ridge’, ‘lasso’}. Otherwise,
it can be an object that inherits from
dipy.optimize.SKLearnLinearSolver or an object with a similar
interface from Scikit-Learn:
sklearn.linear_model.LinearRegression,
sklearn.linear_model.Lasso or sklearn.linear_model.Ridge
and other objects that inherit from sklearn.base.RegressorMixin.
Default: ‘ols’.
- b0_thresholdint, optional
Threshold for considering volumes as b0.
- out_dtypestr or dtype, optional
The dtype for the output array. Default: output has the same dtype as
the input.
- alphafloat, optional
Regularization parameter only for ridge regression model.
- verbosebool, optional
Show progress of Patch2Self and time taken.
- b0_denoisingbool, optional
Skips denoising b0 volumes if set to False.
- clip_negative_valsbool, optional
Sets negative values after denoising to 0 using np.clip.
- shift_intensitybool, optional
Shifts the distribution of intensities per volume to give
non-negative values
- Returns:
- denoised arrayndarray
This is the denoised array of the same size as that of the input data,
clipped to non-negative values.
References
- [Fadnavis20] S. Fadnavis, J. Batson, E. Garyfallidis, Patch2Self:
Denoising Diffusion MRI with Self-supervised Learning,
Advances in Neural Information Processing Systems 33 (2020)
pca_noise_estimate
-
dipy.workflows.denoise.pca_noise_estimate()
PCA based local noise estimation.
- Parameters:
- data: 4D array
the input dMRI data. The first 3 dimension must have size >= 2 *
patch_radius + 1 or size = 1.
- gtab: gradient table object
gradient information for the data gives us the bvals and bvecs of
diffusion data, which is needed here to select between the noise
estimation methods.
- patch_radiusint
The radius of the local patch to be taken around each voxel (in
voxels). Default: 1 (estimate noise in blocks of 3x3x3 voxels).
- correct_biasbool
Whether to correct for bias due to Rician noise. This is an
implementation of equation 8 in [1].
- smoothint
Radius of a Gaussian smoothing filter to apply to the noise estimate
before returning. Default: 2.
- Returns:
- sigma_corr: 3D array
The local noise standard deviation estimate.
References
[1]
Manjon JV, Coupe P, Concha L, Buades A, Collins DL “Diffusion
Weighted Image Denoising Using Overcomplete Local PCA”. PLoS ONE
8(9): e73021. doi:10.1371/journal.pone.0073021.
read_bvals_bvecs
-
dipy.workflows.denoise.read_bvals_bvecs(fbvals, fbvecs)
Read b-values and b-vectors from disk.
- Parameters:
- fbvalsstr
Full path to file with b-values. None to not read bvals.
- fbvecsstr
Full path of file with b-vectors. None to not read bvecs.
- Returns:
- bvalsarray, (N,) or None
- bvecsarray, (N, 3) or None
Notes
Files can be either ‘.bvals’/’.bvecs’ or ‘.txt’ or ‘.npy’ (containing
arrays stored with the appropriate values).
save_nifti
-
dipy.workflows.denoise.save_nifti(fname, data, affine, hdr=None, dtype=None)
Save a data array into a nifti file.
- Parameters:
- fnamestr
The full path to the file to be saved.
- datandarray
The array with the data to save.
- affine4x4 array
The affine transform associated with the file.
- hdrnifti header, optional
May contain additional information to store in the file header.
- Returns:
- None
-
class dipy.workflows.docstring_parser.NumpyDocString(docstring, config={})
Bases: object
-
__init__(docstring, config={})
-
class dipy.workflows.docstring_parser.Reader(data)
Bases: object
A line-based string reader.
Methods
eof |
|
is_empty |
|
peek |
|
read |
|
read_to_condition |
|
read_to_next_empty_line |
|
read_to_next_unindented_line |
|
reset |
|
seek_next_non_empty_line |
|
-
__init__(data)
- Parameters:
- datastr
String with lines separated by ‘
- ‘.
-
eof()
-
is_empty()
-
peek(n=0)
-
read()
-
read_to_condition(condition_func)
-
read_to_next_empty_line()
-
read_to_next_unindented_line()
-
reset()
-
seek_next_non_empty_line()
dedent_lines
-
dipy.workflows.docstring_parser.dedent_lines(lines)
Deindent a list of lines maximally
warn
-
dipy.workflows.docstring_parser.warn(/, message, category=None, stacklevel=1, source=None)
Issue a warning, or maybe ignore it or raise an exception.
-
class dipy.workflows.flow_runner.IntrospectiveArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=(), formatter_class=<class 'argparse.RawTextHelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='resolve', add_help=True)
Bases: ArgumentParser
- Attributes:
- optional_parameters
- output_parameters
- positional_parameters
Methods
add_argument (add_argument)
|
|
add_sub_flow_args (sub_flows)
|
Take an array of workflow objects and use introspection to extract the parameters, types and docstrings of their run method. |
add_subparsers (**kwargs)
|
|
add_workflow (workflow)
|
Take a workflow object and use introspection to extract the parameters, types and docstrings of its run method. |
error (message)
|
Prints a usage message incorporating the message to stderr and exits. |
exit ([status, message])
|
|
format_usage ()
|
|
get_flow_args ([args, namespace])
|
Return the parsed arguments as a dictionary that will be used as a workflow's run method arguments. |
parse_args ([args, namespace])
|
|
print_usage ([file])
|
|
register (registry_name, value, object)
|
|
set_defaults (**kwargs)
|
|
add_argument_group |
|
add_description |
|
add_epilogue |
|
add_mutually_exclusive_group |
|
convert_arg_line_to_args |
|
format_help |
|
get_default |
|
parse_intermixed_args |
|
parse_known_args |
|
parse_known_intermixed_args |
|
print_help |
|
show_argument |
|
update_argument |
|
-
__init__(prog=None, usage=None, description=None, epilog=None, parents=(), formatter_class=<class 'argparse.RawTextHelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='resolve', add_help=True)
Augmenting the argument parser to allow automatic creation of
arguments from workflows
- Parameters:
- progNone
The name of the program. (default: sys.argv[0])
- usageNone
A usage message. (default: auto-generated from arguments)
- descriptionstr
A description of what the program does.
- epilogstr
Text following the argument descriptions.
- parentslist
Parsers whose arguments should be copied into this one.
- formatter_classobj
HelpFormatter class for printing help messages.
- prefix_charsstr
Characters that prefix optional arguments.
- fromfile_prefix_charsNone
Characters that prefix files containing additional arguments.
- argument_defaultNone
The default value for all arguments.
- conflict_handlerstr
String indicating how to handle conflicts.
- add_helpbool
Add a -h/-help option.
-
add_description()
-
add_epilogue()
-
add_sub_flow_args(sub_flows)
Take an array of workflow objects and use introspection to extract
the parameters, types and docstrings of their run method. Only the
optional input parameters are extracted for these as they are treated
as sub workflows.
- Parameters:
- sub_flowsarray of dipy.workflows.workflow.Workflow
Workflows to inspect.
- Returns:
- sub_flow_optionalsdictionary of all sub workflow optional parameters
-
add_workflow(workflow)
Take a workflow object and use introspection to extract the
parameters, types and docstrings of its run method. Then add these
parameters to the current arparser’s own params to parse. If the
workflow is of type combined_workflow, the optional input parameters
of its sub workflows will also be added.
- Parameters:
- workflowdipy.workflows.workflow.Workflow
Workflow from which to infer parameters.
- Returns:
- sub_flow_optionalsdictionary of all sub workflow optional parameters
-
get_flow_args(args=None, namespace=None)
Return the parsed arguments as a dictionary that will be used
as a workflow’s run method arguments.
-
property optional_parameters
-
property output_parameters
-
property positional_parameters
-
show_argument(dest)
-
update_argument(*args, **kargs)
get_level
-
dipy.workflows.flow_runner.get_level(lvl)
Transforms the logging level passed on the commandline into a proper
logging level name.
run_flow
-
dipy.workflows.flow_runner.run_flow(flow)
Wraps the process of building an argparser that reflects the workflow
that we want to run along with some generic parameters like logging,
force and output strategies. The resulting parameters are then fed to
the workflow’s run method.
-
class dipy.workflows.io.FetchFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_fetcher_datanames ()
|
Gets available dataset and function names. |
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
load_module (module_path)
|
Load / reload an external module. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (data_names[, out_dir])
|
Download files to folder and check their md5 checksums. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
static get_fetcher_datanames()
Gets available dataset and function names.
- Returns:
- available_data: dict
Available dataset and function names.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
static load_module(module_path)
Load / reload an external module.
- Parameters:
- module_path: string
the path to the module relative to the main script
- Returns:
- module: module object
-
run(data_names, out_dir='')
Download files to folder and check their md5 checksums.
To see all available datasets, please type “list” in data_names.
- Parameters:
- data_namesvariable string
Any number of Nifti1, bvals or bvecs files.
- out_dirstring, optional
Output directory. (default current directory)
-
class dipy.workflows.io.IoInfoFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files[, b0_threshold, bvecs_tol, ...])
|
Provides useful information about different files used in medical imaging. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, b0_threshold=50, bvecs_tol=0.01, bshell_thr=100)
Provides useful information about different files used in
medical imaging. Any number of input files can be provided. The
program identifies the type of file by its extension.
- Parameters:
- input_filesvariable string
Any number of Nifti1, bvals or bvecs files.
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- bvecs_tolfloat, optional
Threshold used to check that norm(bvec) = 1 +/- bvecs_tol
b-vectors are unit vectors.
- bshell_thrfloat, optional
Threshold for distinguishing b-values in different shells.
-
class dipy.workflows.io.SplitFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files[, vol_idx, out_dir, out_split])
|
Splits the input 4D file and extracts the required 3D volume. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, vol_idx=0, out_dir='', out_split='split.nii.gz')
Splits the input 4D file and extracts the required 3D volume.
- Parameters:
- input_filesvariable string
Any number of Nifti1 files
- vol_idxint, optional
- out_dirstring, optional
Output directory. (default current directory)
- out_splitstring, optional
Name of the resulting split volume
-
class dipy.workflows.io.Workflow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: object
Methods
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_io_iterator()
Create an iterator for IO.
Use a couple of inspection tricks to build an IOIterator using the
previous frame (values of local variables and other contextuals) and
the run method’s docstring.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
get_sub_runs()
Return No sub runs since this is a simple workflow.
-
manage_output_overwrite()
Check if a file will be overwritten upon processing the inputs.
If it is bound to happen, an action is taken depending on
self._force_overwrite (or –force via command line). A log message is
output independently of the outcome to tell the user something
happened.
-
run(*args, **kwargs)
Execute the workflow.
Since this is an abstract class, raise exception if this code is
reached (not implemented in child class or literally called on this
class)
getmembers
-
dipy.workflows.io.getmembers(object, predicate=None)
Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate.
isfunction
-
dipy.workflows.io.isfunction(object)
Return true if the object is a user-defined function.
- Function objects provide these attributes:
__doc__ documentation string
__name__ name with which this function was defined
__code__ code object containing compiled function bytecode
__defaults__ tuple of any default values for arguments
__globals__ global namespace in which this function was defined
__annotations__ dict of parameter annotations
__kwdefaults__ dict of keyword only parameters with defaults
load_nifti
-
dipy.workflows.io.load_nifti(fname, return_img=False, return_voxsize=False, return_coords=False, as_ndarray=True)
Load data and other information from a nifti file.
- Parameters:
- fnamestr
Full path to a nifti file.
- return_imgbool, optional
Whether to return the nibabel nifti img object. Default: False
- return_voxsize: bool, optional
Whether to return the nifti header zooms. Default: False
- return_coordsbool, optional
Whether to return the nifti header aff2axcodes. Default: False
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray.
If you want to save memory and delay this casting, just turn this
option to False (default: True)
- Returns:
- A tuple, with (at the most, if all keyword args are set to True):
- (data, img.affine, img, vox_size, nib.aff2axcodes(img.affine))
save_nifti
-
dipy.workflows.io.save_nifti(fname, data, affine, hdr=None, dtype=None)
Save a data array into a nifti file.
- Parameters:
- fnamestr
The full path to the file to be saved.
- datandarray
The array with the data to save.
- affine4x4 array
The affine transform associated with the file.
- hdrnifti header, optional
May contain additional information to store in the file header.
- Returns:
- None
-
class dipy.workflows.mask.MaskFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, lb[, ub, out_dir, out_mask])
|
Workflow for creating a binary mask |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, lb, ub=inf, out_dir='', out_mask='mask.nii.gz')
Workflow for creating a binary mask
- Parameters:
- input_filesstring
Path to image to be masked.
- lbfloat
Lower bound value.
- ubfloat, optional
Upper bound value.
- out_dirstring, optional
Output directory. (default current directory)
- out_maskstring, optional
Name of the masked file.
-
class dipy.workflows.mask.Workflow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: object
Methods
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_io_iterator()
Create an iterator for IO.
Use a couple of inspection tricks to build an IOIterator using the
previous frame (values of local variables and other contextuals) and
the run method’s docstring.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
get_sub_runs()
Return No sub runs since this is a simple workflow.
-
manage_output_overwrite()
Check if a file will be overwritten upon processing the inputs.
If it is bound to happen, an action is taken depending on
self._force_overwrite (or –force via command line). A log message is
output independently of the outcome to tell the user something
happened.
-
run(*args, **kwargs)
Execute the workflow.
Since this is an abstract class, raise exception if this code is
reached (not implemented in child class or literally called on this
class)
load_nifti
-
dipy.workflows.mask.load_nifti(fname, return_img=False, return_voxsize=False, return_coords=False, as_ndarray=True)
Load data and other information from a nifti file.
- Parameters:
- fnamestr
Full path to a nifti file.
- return_imgbool, optional
Whether to return the nibabel nifti img object. Default: False
- return_voxsize: bool, optional
Whether to return the nifti header zooms. Default: False
- return_coordsbool, optional
Whether to return the nifti header aff2axcodes. Default: False
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray.
If you want to save memory and delay this casting, just turn this
option to False (default: True)
- Returns:
- A tuple, with (at the most, if all keyword args are set to True):
- (data, img.affine, img, vox_size, nib.aff2axcodes(img.affine))
save_nifti
-
dipy.workflows.mask.save_nifti(fname, data, affine, hdr=None, dtype=None)
Save a data array into a nifti file.
- Parameters:
- fnamestr
The full path to the file to be saved.
- datandarray
The array with the data to save.
- affine4x4 array
The affine transform associated with the file.
- hdrnifti header, optional
May contain additional information to store in the file header.
- Returns:
- None
-
class dipy.workflows.multi_io.IOIterator(output_strategy='absolute', mix_names=False)
Bases: object
Create output filenames that work nicely with multiple input files from
multiple directories (processing multiple subjects with one command)
Use information from input files, out_dir and out_fnames to generate
correct outputs which can come from long lists of multiple or single
inputs.
Methods
create_directories |
|
create_outputs |
|
file_existence_check |
|
set_inputs |
|
set_out_dir |
|
set_out_fnames |
|
set_output_keys |
|
-
__init__(output_strategy='absolute', mix_names=False)
-
create_directories()
-
create_outputs()
-
file_existence_check(args)
-
set_inputs(*args)
-
set_out_dir(out_dir)
-
set_out_fnames(*args)
-
set_output_keys(*args)
basename_without_extension
-
dipy.workflows.multi_io.basename_without_extension(fname)
common_start
-
dipy.workflows.multi_io.common_start(sa, sb)
Return the longest common substring from the beginning of sa and sb.
connect_output_paths
-
dipy.workflows.multi_io.connect_output_paths(inputs, out_dir, out_files, output_strategy='absolute', mix_names=True)
Generate a list of output files paths based on input files and
output strategies.
- Parameters:
- inputsarray
List of input paths.
- out_dirstring
The output directory.
- out_filesarray
List of output files.
- output_strategystring, optional
- Which strategy to use to generate the output paths.
‘append’: Add out_dir to the path of the input.
‘prepend’: Add the input path directory tree to out_dir.
‘absolute’: Put directly in out_dir.
- mix_namesbool, optional
Whether or not prepend a string composed of a mix of the input
names to the final output name.
- Returns:
- A list of output file paths.
get_args_default
-
dipy.workflows.multi_io.get_args_default(func)
glob
-
dipy.workflows.multi_io.glob(pathname, *, recursive=False)
Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by ‘*’ and ‘?’
patterns.
If recursive is true, the pattern ‘**’ will match any files and
zero or more directories and subdirectories.
io_iterator
-
dipy.workflows.multi_io.io_iterator(inputs, out_dir, fnames, output_strategy='absolute', mix_names=False, out_keys=None)
Create an IOIterator from the parameters.
- Parameters:
- inputsarray
List of input files.
- out_dirstring
Output directory.
- fnamesarray
File names of all outputs to be created.
- output_strategystring, optional
Controls the behavior of the IOIterator for output paths.
- mix_namesbool, optional
Whether or not to append a mix of input names at the beginning.
- out_keyslist, optional
Output parameter names.
- Returns:
- Properly instantiated IOIterator object.
-
dipy.workflows.multi_io.io_iterator_(frame, fnc, output_strategy='absolute', mix_names=False)
Create an IOIterator using introspection.
- Parameters:
- frameframeobject
Contains the info about the current local variables values.
- fncfunction
The function to inspect
- output_strategystring
Controls the behavior of the IOIterator for output paths.
- mix_namesbool
Whether or not to append a mix of input names at the beginning.
- Returns:
- Properly instantiated IOIterator object.
slash_to_under
-
dipy.workflows.multi_io.slash_to_under(dir_str)
-
class dipy.workflows.reconst.ConstrainedSphericalDeconvModel(gtab, response, reg_sphere=None, sh_order=8, lambda_=1, tau=0.1, convergence=50)
Bases: SphHarmModel
Methods
cache_clear ()
|
Clear the cache. |
cache_get (tag, key[, default])
|
Retrieve a value from the cache. |
cache_set (tag, key, value)
|
Store a value in the cache. |
fit (data[, mask])
|
Fit method for every voxel in data |
predict (sh_coeff[, gtab, S0])
|
Compute a signal prediction given spherical harmonic coefficients for the provided GradientTable class instance. |
sampling_matrix (sphere)
|
The matrix needed to sample ODFs from coefficients of the model. |
-
__init__(gtab, response, reg_sphere=None, sh_order=8, lambda_=1, tau=0.1, convergence=50)
Constrained Spherical Deconvolution (CSD) [1].
Spherical deconvolution computes a fiber orientation distribution
(FOD), also called fiber ODF (fODF) [2], as opposed to a diffusion ODF
as the QballModel or the CsaOdfModel. This results in a sharper angular
profile with better angular resolution that is the best object to be
used for later deterministic and probabilistic tractography [3].
A sharp fODF is obtained because a single fiber response function is
injected as a priori knowledge. The response function is often
data-driven and is thus provided as input to the
ConstrainedSphericalDeconvModel. It will be used as deconvolution
kernel, as described in [1].
- Parameters:
- gtabGradientTable
- responsetuple or AxSymShResponse object
A tuple with two elements. The first is the eigen-values as an (3,)
ndarray and the second is the signal value for the response
function without diffusion weighting (i.e. S0). This is to be able
to generate a single fiber synthetic signal. The response function
will be used as deconvolution kernel ([1]).
- reg_sphereSphere (optional)
sphere used to build the regularization B matrix.
Default: ‘symmetric362’.
- sh_orderint (optional)
maximal spherical harmonics order. Default: 8
- lambda_float (optional)
weight given to the constrained-positivity regularization part of
the deconvolution equation (see [1]). Default: 1
- taufloat (optional)
threshold controlling the amplitude below which the corresponding
fODF is assumed to be zero. Ideally, tau should be set to
zero. However, to improve the stability of the algorithm, tau is
set to tau*100 % of the mean fODF amplitude (here, 10% by default)
(see [1]). Default: 0.1
- convergenceint
Maximum number of iterations to allow the deconvolution to
converge.
References
[1]
(1,2,3,4,5)
Tournier, J.D., et al. NeuroImage 2007. Robust determination of
the fibre orientation distribution in diffusion MRI:
Non-negativity constrained super-resolved spherical
deconvolution
[2]
Descoteaux, M., et al. IEEE TMI 2009. Deterministic and
Probabilistic Tractography Based on Complex Fibre Orientation
Distributions
[3]
Côté, M-A., et al. Medical Image Analysis 2013. Tractometer:
Towards validation of tractography pipelines
[4]
Tournier, J.D, et al. Imaging Systems and Technology
2012. MRtrix: Diffusion Tractography in Crossing Fiber Regions
-
fit(data, mask=None)
Fit method for every voxel in data
-
predict(sh_coeff, gtab=None, S0=1.0)
Compute a signal prediction given spherical harmonic coefficients
for the provided GradientTable class instance.
- Parameters:
- sh_coeffndarray
The spherical harmonic representation of the FOD from which to make
the signal prediction.
- gtabGradientTable
The gradients for which the signal will be predicted. Uses the
model’s gradient table by default.
- S0ndarray or float
The non diffusion-weighted signal value.
- Returns:
- pred_signdarray
The predicted signal.
-
class dipy.workflows.reconst.CsaOdfModel(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)
Bases: QballBaseModel
Implementation of Constant Solid Angle reconstruction method.
References
[1]
Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging With
Solid Angle Consideration.
Methods
cache_clear ()
|
Clear the cache. |
cache_get (tag, key[, default])
|
Retrieve a value from the cache. |
cache_set (tag, key, value)
|
Store a value in the cache. |
fit (data[, mask])
|
Fits the model to diffusion data and returns the model fit |
sampling_matrix (sphere)
|
The matrix needed to sample ODFs from coefficients of the model. |
-
__init__(gtab, sh_order, smooth=0.006, min_signal=1e-05, assume_normed=False)
Creates a model that can be used to fit or sample diffusion data
- Parameters:
- gtabGradientTable
Diffusion gradients used to acquire data
- sh_ordereven int >= 0
the spherical harmonic order of the model
- smoothfloat between 0 and 1, optional
The regularization parameter of the model
- min_signalfloat, > 0, optional
During fitting, all signal values less than min_signal are
clipped to min_signal. This is done primarily to avoid values
less than or equal to zero when taking logs.
- assume_normedbool, optional
If True, clipping and normalization of the data with respect to the
mean B0 signal are skipped during mode fitting. This is an advanced
feature and should be used with care.
-
max = 0.999
-
min = 0.001
-
class dipy.workflows.reconst.DiffusionKurtosisModel(gtab, fit_method='WLS', *args, **kwargs)
Bases: ReconstModel
Class for the Diffusion Kurtosis Model
Methods
fit (data[, mask])
|
Fit method of the DKI model class |
predict (dki_params[, S0])
|
Predict a signal for this DKI model class instance given parameters. |
-
__init__(gtab, fit_method='WLS', *args, **kwargs)
Diffusion Kurtosis Tensor Model [1]
- Parameters:
- gtabGradientTable class instance
- fit_methodstr or callable
str can be one of the following:
‘OLS’ or ‘ULLS’ for ordinary least squares
- ‘WLS’ or ‘UWLLS’ for weighted ordinary least squares
dki.wls_fit_dki
- callable has to have the signature:
fit_method(design_matrix, data, *args, **kwargs)
- args, kwargsarguments and key-word arguments passed to the
fit_method. See dki.ols_fit_dki, dki.wls_fit_dki for details
References
[1]
Tabesh, A., Jensen, J.H., Ardekani, B.A., Helpern, J.A., 2011.
Estimation of tensors and tensor-derived measures in diffusional
kurtosis imaging. Magn Reson Med. 65(3), 823-836
-
fit(data, mask=None)
Fit method of the DKI model class
- Parameters:
- dataarray
The measured signal from one voxel.
- maskarray
A boolean array used to mark the coordinates in the data that
should be analyzed that has the shape data.shape[-1]
-
predict(dki_params, S0=1.0)
Predict a signal for this DKI model class instance given parameters.
- Parameters:
- dki_paramsndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
2. Three lines of the eigenvector matrix each containing the
first, second and third coordinates of the eigenvector
3. Fifteen elements of the kurtosis tensor
- S0float or ndarray (optional)
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
-
class dipy.workflows.reconst.ReconstCSAFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, ...[, ...])
|
Constant Solid Angle. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bvalues_files, bvectors_files, mask_files, sh_order=6, odf_to_sh_order=8, b0_threshold=50.0, bvecs_tol=0.01, extract_pam_values=False, parallel=False, num_processes=None, out_dir='', out_pam='peaks.pam5', out_shm='shm.nii.gz', out_peaks_dir='peaks_dirs.nii.gz', out_peaks_values='peaks_values.nii.gz', out_peaks_indices='peaks_indices.nii.gz', out_gfa='gfa.nii.gz')
Constant Solid Angle.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvectors files. This path may contain wildcards to use
multiple bvectors files at once.
- mask_filesstring
Path to the input masks. This path may contain wildcards to use
multiple masks at once. (default: No mask used)
- sh_orderint, optional
Spherical harmonics order used in the CSA fit.
- odf_to_sh_orderint, optional
Spherical harmonics order used for peak_from_model to compress
the ODF to spherical harmonics coefficients.
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- bvecs_tolfloat, optional
Threshold used so that norm(bvec)=1.
- extract_pam_valuesbool, optional
Whether or not to save pam volumes as single nifti files.
- parallelbool, optional
Whether to use parallelization in peak-finding during the
calibration procedure.
- num_processesint, optional
If parallel is True, the number of subprocesses to use
(default multiprocessing.cpu_count()). 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.
- out_dirstring, optional
Output directory. (default current directory)
- out_pamstring, optional
Name of the peaks volume to be saved.
- out_shmstring, optional
Name of the spherical harmonics volume to be saved.
- out_peaks_dirstring, optional
Name of the peaks directions volume to be saved.
- out_peaks_valuesstring, optional
Name of the peaks values volume to be saved.
- out_peaks_indicesstring, optional
Name of the peaks indices volume to be saved.
- out_gfastring, optional
Name of the generalized FA volume to be saved.
References
[1]
Aganj, I., et al. 2009. ODF Reconstruction in Q-Ball Imaging
with Solid Angle Consideration.
-
class dipy.workflows.reconst.ReconstCSDFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, ...[, ...])
|
Constrained spherical deconvolution |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bvalues_files, bvectors_files, mask_files, b0_threshold=50.0, bvecs_tol=0.01, roi_center=None, roi_radii=10, fa_thr=0.7, frf=None, extract_pam_values=False, sh_order=8, odf_to_sh_order=8, parallel=False, num_processes=None, out_dir='', out_pam='peaks.pam5', out_shm='shm.nii.gz', out_peaks_dir='peaks_dirs.nii.gz', out_peaks_values='peaks_values.nii.gz', out_peaks_indices='peaks_indices.nii.gz', out_gfa='gfa.nii.gz')
Constrained spherical deconvolution
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvectors files. This path may contain wildcards to use
multiple bvectors files at once.
- mask_filesstring
Path to the input masks. This path may contain wildcards to use
multiple masks at once. (default: No mask used)
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- bvecs_tolfloat, optional
Bvecs should be unit vectors.
- roi_centervariable int, optional
Center of ROI in data. If center is None, it is assumed that it is
the center of the volume with shape data.shape[:3].
- roi_radiiint or array-like, optional
radii of cuboid ROI in voxels.
- fa_thrfloat, optional
FA threshold for calculating the response function.
- frfvariable float, optional
Fiber response function can be for example inputed as 15 4 4
(from the command line) or [15, 4, 4] from a Python script to be
converted to float and multiplied by 10**-4 . If None
the fiber response function will be computed automatically.
- extract_pam_valuesbool, optional
Save or not to save pam volumes as single nifti files.
- sh_orderint, optional
Spherical harmonics order used in the CSA fit.
- odf_to_sh_orderint, optional
Spherical harmonics order used for peak_from_model to compress
the ODF to spherical harmonics coefficients.
- parallelbool, optional
Whether to use parallelization in peak-finding during the
calibration procedure.
- num_processesint, optional
If parallel is True, the number of subprocesses to use
(default multiprocessing.cpu_count()). 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.
- out_dirstring, optional
Output directory. (default current directory)
- out_pamstring, optional
Name of the peaks volume to be saved.
- out_shmstring, optional
Name of the spherical harmonics volume to be saved.
- out_peaks_dirstring, optional
Name of the peaks directions volume to be saved.
- out_peaks_valuesstring, optional
Name of the peaks values volume to be saved.
- out_peaks_indicesstring, optional
Name of the peaks indices volume to be saved.
- out_gfastring, optional
Name of the generalized FA volume to be saved.
References
[1]
Tournier, J.D., et al. NeuroImage 2007. Robust determination of
the fibre orientation distribution in diffusion MRI: Non-negativity
constrained super-resolved spherical deconvolution.
-
class dipy.workflows.reconst.ReconstDkiFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, ...[, ...])
|
Workflow for Diffusion Kurtosis reconstruction and for computing DKI metrics. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_fitted_tensor(data, mask, bval, bvec, b0_threshold=50, fit_method='WLS', optional_args=None)
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bvalues_files, bvectors_files, mask_files, fit_method='WLS', b0_threshold=50.0, sigma=None, save_metrics=None, out_dir='', out_dt_tensor='dti_tensors.nii.gz', out_fa='fa.nii.gz', out_ga='ga.nii.gz', out_rgb='rgb.nii.gz', out_md='md.nii.gz', out_ad='ad.nii.gz', out_rd='rd.nii.gz', out_mode='mode.nii.gz', out_evec='evecs.nii.gz', out_eval='evals.nii.gz', out_dk_tensor='dki_tensors.nii.gz', out_mk='mk.nii.gz', out_ak='ak.nii.gz', out_rk='rk.nii.gz')
Workflow for Diffusion Kurtosis reconstruction and for computing
DKI metrics. Performs a DKI reconstruction on the files by ‘globing’
input_files
and saves the DKI metrics in a directory specified by
out_dir
.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- mask_filesstring
Path to the input masks. This path may contain wildcards to use
multiple masks at once. (default: No mask used)
- fit_methodstring, optional
can be one of the following:
‘OLS’ or ‘ULLS’ for ordinary least squares
‘WLS’ or ‘UWLLS’ for weighted ordinary least squares
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- sigmafloat, optional
An estimate of the variance. [3] recommend to use
1.5267 * std(background_noise), where background_noise is estimated
from some part of the image known to contain no signal (only noise)
- save_metricsvariable string, optional
List of metrics to save.
Possible values: fa, ga, rgb, md, ad, rd, mode, tensor, evec, eval
- out_dirstring, optional
Output directory. (default current directory)
- out_dt_tensorstring, optional
Name of the tensors volume to be saved.
- out_dk_tensorstring, optional
Name of the tensors volume to be saved.
- out_fastring, optional
Name of the fractional anisotropy volume to be saved.
- out_gastring, optional
Name of the geodesic anisotropy volume to be saved.
- out_rgbstring, optional
Name of the color fa volume to be saved.
- out_mdstring, optional
Name of the mean diffusivity volume to be saved.
- out_adstring, optional
Name of the axial diffusivity volume to be saved.
- out_rdstring, optional
Name of the radial diffusivity volume to be saved.
- out_modestring, optional
Name of the mode volume to be saved.
- out_evecstring, optional
Name of the eigenvectors volume to be saved.
- out_evalstring, optional
Name of the eigenvalues to be saved.
- out_mkstring, optional
Name of the mean kurtosis to be saved.
- out_akstring, optional
Name of the axial kurtosis to be saved.
- out_rkstring, optional
Name of the radial kurtosis to be saved.
References
[1]
Tabesh, A., Jensen, J.H., Ardekani, B.A., Helpern, J.A., 2011.
Estimation of tensors and tensor-derived measures in diffusional
kurtosis imaging. Magn Reson Med. 65(3), 823-836
[2]
Jensen, Jens H., Joseph A. Helpern, Anita Ramani, Hanzhang Lu,
and Kyle Kaczynski. 2005. Diffusional Kurtosis Imaging: The
Quantification of Non-Gaussian Water Diffusion by Means of Magnetic
Resonance Imaging. MRM 53 (6):1432-40.
[3]
Chang, L-C, Jones, DK and Pierpaoli, C (2005). RESTORE: robust
estimation of tensors by outlier rejection. MRM, 53: 1088-95.
-
class dipy.workflows.reconst.ReconstDtiFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, ...[, ...])
|
Workflow for tensor reconstruction and for computing DTI metrics. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_fitted_tensor(data, mask, bval, bvec, b0_threshold=50, bvecs_tol=0.01, fit_method='WLS', optional_args=None)
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bvalues_files, bvectors_files, mask_files, fit_method='WLS', b0_threshold=50, bvecs_tol=0.01, sigma=None, save_metrics=None, out_dir='', out_tensor='tensors.nii.gz', out_fa='fa.nii.gz', out_ga='ga.nii.gz', out_rgb='rgb.nii.gz', out_md='md.nii.gz', out_ad='ad.nii.gz', out_rd='rd.nii.gz', out_mode='mode.nii.gz', out_evec='evecs.nii.gz', out_eval='evals.nii.gz', nifti_tensor=True)
Workflow for tensor reconstruction and for computing DTI metrics.
using Weighted Least-Squares.
Performs a tensor reconstruction on the files by ‘globing’
input_files
and saves the DTI metrics in a directory specified by
out_dir
.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvectors files. This path may contain wildcards to use
multiple bvectors files at once.
- mask_filesstring
Path to the input masks. This path may contain wildcards to use
multiple masks at once.
- fit_methodstring, optional
can be one of the following:
‘WLS’ for weighted least squares
‘LS’ or ‘OLS’ for ordinary least squares
‘NLLS’ for non-linear least-squares
‘RT’ or ‘restore’ or ‘RESTORE’ for RESTORE robust tensor fitting
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- bvecs_tolfloat, optional
Threshold used to check that norm(bvec) = 1 +/- bvecs_tol
- sigmafloat, optional
An estimate of the variance. [5] recommend to use
1.5267 * std(background_noise), where background_noise is estimated
from some part of the image known to contain no signal (only noise)
b-vectors are unit vectors.
- save_metricsvariable string, optional
List of metrics to save.
Possible values: fa, ga, rgb, md, ad, rd, mode, tensor, evec, eval
- out_dirstring, optional
Output directory. (default current directory)
- out_tensorstring, optional
Name of the tensors volume to be saved.
Per default, this will be saved following the nifti standard:
with the tensor elements as Dxx, Dxy, Dyy, Dxz, Dyz, Dzz on the
last (5th) dimension of the volume (shape: (i, j, k, 1, 6)). If
nifti_tensor is False, this will be saved in an alternate format
that is used by other software (e.g., FSL): a
4-dimensional volume (shape (i, j, k, 6)) with Dxx, Dxy, Dxz, Dyy,
Dyz, Dzz on the last dimension.
- out_fastring, optional
Name of the fractional anisotropy volume to be saved.
- out_gastring, optional
Name of the geodesic anisotropy volume to be saved.
- out_rgbstring, optional
Name of the color fa volume to be saved.
- out_mdstring, optional
Name of the mean diffusivity volume to be saved.
- out_adstring, optional
Name of the axial diffusivity volume to be saved.
- out_rdstring, optional
Name of the radial diffusivity volume to be saved.
- out_modestring, optional
Name of the mode volume to be saved.
- out_evecstring, optional
Name of the eigenvectors volume to be saved.
- out_evalstring, optional
Name of the eigenvalues to be saved.
- nifti_tensorbool, optional
Whether the tensor is saved in the standard Nifti format or in an
alternate format
that is used by other software (e.g., FSL): a
4-dimensional volume (shape (i, j, k, 6)) with
Dxx, Dxy, Dxz, Dyy, Dyz, Dzz on the last dimension.
References
[1]
Basser, P.J., Mattiello, J., LeBihan, D., 1994. Estimation of
the effective self-diffusion tensor from the NMR spin echo. J Magn
Reson B 103, 247-254.
[2]
Basser, P., Pierpaoli, C., 1996. Microstructural and
physiological features of tissues elucidated by quantitative
diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219.
[3]
Lin-Ching C., Jones D.K., Pierpaoli, C. 2005. RESTORE: Robust
estimation of tensors by outlier rejection. MRM 53: 1088-1095
[4]
hung, SW., Lu, Y., Henry, R.G., 2006. Comparison of bootstrap
approaches for estimation of uncertainties of DTI parameters.
NeuroImage 33, 531-541.
[5]
Chang, L-C, Jones, DK and Pierpaoli, C (2005). RESTORE: robust
estimation of tensors by outlier rejection. MRM, 53: 1088-95.
-
class dipy.workflows.reconst.ReconstIvimFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, ...[, ...])
|
Workflow for Intra-voxel Incoherent Motion reconstruction and for computing IVIM metrics. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_fitted_ivim(data, mask, bval, bvec, b0_threshold=50)
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bvalues_files, bvectors_files, mask_files, split_b_D=400, split_b_S0=200, b0_threshold=0, save_metrics=None, out_dir='', out_S0_predicted='S0_predicted.nii.gz', out_perfusion_fraction='perfusion_fraction.nii.gz', out_D_star='D_star.nii.gz', out_D='D.nii.gz')
Workflow for Intra-voxel Incoherent Motion reconstruction and for
computing IVIM metrics. Performs a IVIM reconstruction on the files
by ‘globing’ input_files
and saves the IVIM metrics in a directory
specified by out_dir
.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- mask_filesstring
Path to the input masks. This path may contain wildcards to use
multiple masks at once. (default: No mask used)
- split_b_Dint, optional
Value to split the bvals to estimate D for the two-stage process of
fitting.
- split_b_S0int, optional
Value to split the bvals to estimate S0 for the two-stage process
of fitting.
- b0_thresholdint, optional
Threshold value for the b0 bval.
- save_metricsvariable string, optional
List of metrics to save.
Possible values: S0_predicted, perfusion_fraction, D_star, D
- out_dirstring, optional
Output directory. (default current directory)
- out_S0_predictedstring, optional
Name of the S0 signal estimated to be saved.
- out_perfusion_fractionstring, optional
Name of the estimated volume fractions to be saved.
- out_D_starstring, optional
Name of the estimated pseudo-diffusion parameter to be saved.
- out_Dstring, optional
Name of the estimated diffusion parameter to be saved.
References
[Stejskal65]
Stejskal, E. O.; Tanner, J. E. (1 January 1965).
“Spin Diffusion Measurements: Spin Echoes in the
Presence of a Time-Dependent Field Gradient”. The
Journal of Chemical Physics 42 (1): 288.
Bibcode: 1965JChPh..42..288S. doi:10.1063/1.1695690.
[LeBihan84]
Le Bihan, Denis, et al. “Separation of diffusion
and perfusion in intravoxel incoherent motion MR
imaging.” Radiology 168.2 (1988): 497-505.
-
class dipy.workflows.reconst.ReconstMAPMRIFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (data_files, bvals_files, bvecs_files, ...)
|
Workflow for fitting the MAPMRI model (with optional Laplacian regularization). |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(data_files, bvals_files, bvecs_files, small_delta, big_delta, b0_threshold=50.0, laplacian=True, positivity=True, bval_threshold=2000, save_metrics=(), laplacian_weighting=0.05, radial_order=6, out_dir='', out_rtop='rtop.nii.gz', out_lapnorm='lapnorm.nii.gz', out_msd='msd.nii.gz', out_qiv='qiv.nii.gz', out_rtap='rtap.nii.gz', out_rtpp='rtpp.nii.gz', out_ng='ng.nii.gz', out_perng='perng.nii.gz', out_parng='parng.nii.gz')
Workflow for fitting the MAPMRI model (with optional Laplacian
regularization). Generates rtop, lapnorm, msd, qiv, rtap, rtpp,
non-gaussian (ng), parallel ng, perpendicular ng saved in a nifti
format in input files provided by data_files and saves the nifti
files to an output directory specified by out_dir.
In order for the MAPMRI workflow to work in the way
intended either the Laplacian or positivity or both must
be set to True.
- Parameters:
- data_filesstring
Path to the input volume.
- bvals_filesstring
Path to the bval files.
- bvecs_filesstring
Path to the bvec files.
- small_deltafloat
Small delta value used in generation of gradient table of provided
bval and bvec.
- big_deltafloat
Big delta value used in generation of gradient table of provided
bval and bvec.
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- laplacianbool, optional
Regularize using the Laplacian of the MAP-MRI basis.
- positivitybool, optional
Constrain the propagator to be positive.
- bval_thresholdfloat, optional
Sets the b-value threshold to be used in the scale factor
estimation. In order for the estimated non-Gaussianity to have
meaning this value should set to a lower value (b<2000 s/mm^2)
such that the scale factors are estimated on signal points that
reasonably represent the spins at Gaussian diffusion.
- save_metricsvariable string, optional
List of metrics to save.
Possible values: rtop, laplacian_signal, msd, qiv, rtap, rtpp,
ng, perng, parng
- laplacian_weightingfloat, optional
Weighting value used in fitting the MAPMRI model in the Laplacian
and both model types.
- radial_orderunsigned int, optional
Even value used to set the order of the basis.
- out_dirstring, optional
Output directory. (default: current directory)
- out_rtopstring, optional
Name of the rtop to be saved.
- out_lapnormstring, optional
Name of the norm of Laplacian signal to be saved.
- out_msdstring, optional
Name of the msd to be saved.
- out_qivstring, optional
Name of the qiv to be saved.
- out_rtapstring, optional
Name of the rtap to be saved.
- out_rtppstring, optional
Name of the rtpp to be saved.
- out_ngstring, optional
Name of the Non-Gaussianity to be saved.
- out_perngstring, optional
Name of the Non-Gaussianity perpendicular to be saved.
- out_parngstring, optional
Name of the Non-Gaussianity parallel to be saved.
-
class dipy.workflows.reconst.ReconstRUMBAFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (input_files, bvalues_files, ...[, ...])
|
Reconstruct the fiber local orientations using the Robust and Unbiased Model-BAsed Spherical Deconvolution (RUMBA-SD) [1] model. |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(input_files, bvalues_files, bvectors_files, mask_files, b0_threshold=50.0, bvecs_tol=0.01, roi_center=None, roi_radii=10, fa_thr=0.7, extract_pam_values=False, sh_order=8, odf_to_sh_order=8, parallel=True, num_processes=None, gm_response=0.0008, csf_response=0.003, n_iter=600, recon_type='smf', n_coils=1, R=1, voxelwise=True, use_tv=False, sphere_name='repulsion724', verbose=False, relative_peak_threshold=0.5, min_separation_angle=25, npeaks=5, out_dir='', out_pam='peaks.pam5', out_shm='shm.nii.gz', out_peaks_dir='peaks_dirs.nii.gz', out_peaks_values='peaks_values.nii.gz', out_peaks_indices='peaks_indices.nii.gz', out_gfa='gfa.nii.gz')
Reconstruct the fiber local orientations using the Robust and
Unbiased Model-BAsed Spherical Deconvolution (RUMBA-SD) [1] model. The
fiber response function (FRF) is computed using the single-shell,
single-tissue model, and the voxel-wise fitting procedure is used for
RUMBA-SD.
- Parameters:
- input_filesstring
Path to the input volumes. This path may contain wildcards to
process multiple inputs at once.
- bvalues_filesstring
Path to the bvalues files. This path may contain wildcards to use
multiple bvalues files at once.
- bvectors_filesstring
Path to the bvectors files. This path may contain wildcards to use
multiple bvectors files at once.
- mask_filesstring
Path to the input masks. This path may contain wildcards to use
multiple masks at once.
- b0_thresholdfloat, optional
Threshold used to find b0 volumes.
- bvecs_tolfloat, optional
Bvecs should be unit vectors.
- roi_centervariable int, optional
Center of ROI in data. If center is None, it is assumed that it is
the center of the volume with shape data.shape[:3].
- roi_radiiint or array-like, optional
radii of cuboid ROI in voxels.
- fa_thrfloat, optional
FA threshold to compute the WM response function.
- extract_pam_valuesbool, optional
Save or not to save pam volumes as single nifti files.
- sh_orderint, optional
Spherical harmonics order used in the CSA fit.
- odf_to_sh_orderint, optional
Spherical harmonics order used for peak_from_model to compress
the ODF to spherical harmonics coefficients.
- parallelbool, optional
Whether to use parallelization in peak-finding during the
calibration procedure.
- num_processesint, optional
If parallel is True, the number of subprocesses to use
(default multiprocessing.cpu_count()). 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.
- gm_responsefloat, optional
Mean diffusivity for GM compartment. If None, then grey
matter volume fraction is not computed.
- csf_responsefloat, optional
Mean diffusivity for CSF compartment. If None, then CSF
volume fraction is not computed.
- n_iterint, optional
Number of iterations for fODF estimation. Must be a positive int.
- recon_typestr, optional
MRI reconstruction method type: spatial matched filter (smf) or
sum-of-squares (sos). SMF reconstruction generates Rician noise
while SoS reconstruction generates Noncentral Chi noise.
- n_coilsint, optional
Number of coils in MRI scanner – only relevant in SoS
reconstruction. Must be a positive int. Default: 1
- Rint, optional
Acceleration factor of the acquisition. For SIEMENS,
R = iPAT factor. For GE, R = ASSET factor. For PHILIPS,
R = SENSE factor. Typical values are 1 or 2. Must be a positive
integer.
- voxelwisebool, optional
If true, performs a voxelwise fit. If false, performs a global fit
on the entire brain at once. The global fit requires a 4D brain
volume in fit.
- use_tvbool, optional
If true, applies total variation regularization. This only takes
effect in a global fit (voxelwise is set to False). TV can only
be applied to 4D brain volumes with no singleton dimensions.
- sphere_namestr, optional
Sphere name on which to reconstruct the fODFs.
- verbosebool, optional
If true, logs updates on estimated signal-to-noise ratio after each
iteration. This only takes effect in a global fit (voxelwise is
set to False).
- relative_peak_thresholdfloat, optional
- Only return peaks greater than
relative_peak_threshold * m
where m is the largest peak.
- min_separation_anglefloat, optional
The minimum distance between directions. If two peaks are too close
only the larger of the two is returned.
- npeaksint, optional
Maximum number of peaks returned for a given voxel.
- out_dirstring, optional
Output directory. (default current directory)
- out_pamstring, optional
Name of the peaks volume to be saved.
- out_shmstring, optional
Name of the spherical harmonics volume to be saved.
- out_peaks_dirstring, optional
Name of the peaks directions volume to be saved.
- out_peaks_valuesstring, optional
Name of the peaks values volume to be saved.
- out_peaks_indicesstring, optional
Name of the peaks indices volume to be saved.
- out_gfastring, optional
Name of the generalized FA volume to be saved.
References
[1]
(1,2)
Canales-Rodríguez, E. J., Daducci, A., Sotiropoulos, S. N.,
Caruyer, E., Aja-Fernández, S., Radua, J., Mendizabal, J. M. Y.,
Iturria-Medina, Y., Melie-García, L., Alemán-Gómez, Y.,
Thiran, J.-P., Sarró, S., Pomarol-Clotet, E., & Salvador, R.
(2015). Spherical Deconvolution of Multichannel Diffusion MRI
Data with Non-Gaussian Noise Models and Spatial Regularization.
PLOS ONE, 10(10), e0138910.
https://doi.org/10.1371/journal.pone.0138910
-
class dipy.workflows.reconst.RumbaSDModel(gtab, wm_response=array([0.0017, 0.0002, 0.0002]), gm_response=0.0008, csf_response=0.003, n_iter=600, recon_type='smf', n_coils=1, R=1, voxelwise=True, use_tv=False, sphere=None, verbose=False)
Bases: OdfModel
Methods
fit (data)
|
To be implemented by specific odf models |
-
__init__(gtab, wm_response=array([0.0017, 0.0002, 0.0002]), gm_response=0.0008, csf_response=0.003, n_iter=600, recon_type='smf', n_coils=1, R=1, voxelwise=True, use_tv=False, sphere=None, verbose=False)
Robust and Unbiased Model-BAsed Spherical Deconvolution (RUMBA-SD) [1]
Modification of the Richardson-Lucy algorithm accounting for Rician
and Noncentral Chi noise distributions, which more accurately
represent MRI noise. Computes a maximum likelihood estimation of the
fiber orientation density function (fODF) at each voxel. Includes
white matter compartments alongside optional GM and CSF compartments
to account for partial volume effects. This fit can be performed
voxelwise or globally. The global fit will proceed more quickly than
the voxelwise fit provided that the computer has adequate RAM (>= 16 GB
should be sufficient for most datasets).
Kernel for deconvolution constructed using a priori knowledge of white
matter response function, as well as the mean diffusivity of GM and/or
CSF. RUMBA-SD is robust against impulse response imprecision, and thus
the default diffusivity values are often adequate [2].
- Parameters:
- gtabGradientTable
- wm_response1d ndarray or 2d ndarray or AxSymShResponse, optional
Tensor eigenvalues as a (3,) ndarray, multishell eigenvalues as
a (len(unique_bvals_tolerance(gtab.bvals))-1, 3) ndarray in
order of smallest to largest b-value, or an AxSymShResponse.
Default: np.array([1.7e-3, 0.2e-3, 0.2e-3])
- gm_responsefloat, optional
Mean diffusivity for GM compartment. If None, then grey
matter volume fraction is not computed. Default: 0.8e-3
- csf_responsefloat, optional
Mean diffusivity for CSF compartment. If None, then CSF
volume fraction is not computed. Default: 3.0e-3
- n_iterint, optional
Number of iterations for fODF estimation. Must be a positive int.
Default: 600
- recon_type{‘smf’, ‘sos’}, optional
MRI reconstruction method: spatial matched filter (SMF) or
sum-of-squares (SoS). SMF reconstruction generates Rician noise
while SoS reconstruction generates Noncentral Chi noise.
Default: ‘smf’
- n_coilsint, optional
Number of coils in MRI scanner – only relevant in SoS
reconstruction. Must be a positive int. Default: 1
- Rint, optional
Acceleration factor of the acquisition. For SIEMENS,
R = iPAT factor. For GE, R = ASSET factor. For PHILIPS,
R = SENSE factor. Typical values are 1 or 2. Must be a positive
int. Default: 1
- voxelwisebool, optional
If true, performs a voxelwise fit. If false, performs a global fit
on the entire brain at once. The global fit requires a 4D brain
volume in fit. Default: True
- use_tvbool, optional
If true, applies total variation regularization. This only takes
effect in a global fit (voxelwise is set to False). TV can only
be applied to 4D brain volumes with no singleton dimensions.
Default: False
- sphereSphere, optional
Sphere on which to construct fODF. If None, uses repulsion724.
Default: None
- verbosebool, optional
If true, logs updates on estimated signal-to-noise ratio after each
iteration. This only takes effect in a global fit (voxelwise is
set to False). Default: False
References
[1]
Canales-Rodríguez, E. J., Daducci, A., Sotiropoulos, S. N.,
Caruyer, E., Aja-Fernández, S., Radua, J., Mendizabal, J. M. Y.,
Iturria-Medina, Y., Melie-García, L., Alemán-Gómez, Y.,
Thiran, J.-P., Sarró, S., Pomarol-Clotet, E., & Salvador, R.
(2015). Spherical Deconvolution of Multichannel Diffusion MRI
Data with Non-Gaussian Noise Models and Spatial Regularization.
PLOS ONE, 10(10), e0138910.
https://doi.org/10.1371/journal.pone.0138910
[2]
Dell’Acqua, F., Rizzo, G., Scifo, P., Clarke, R., Scotti, G., &
Fazio, F. (2007). A Model-Based Deconvolution Approach to Solve
Fiber Crossing in Diffusion-Weighted MR Imaging. IEEE
Transactions on Bio-Medical Engineering, 54, 462–472.
https://doi.org/10.1109/TBME.2006.888830
-
class dipy.workflows.reconst.TensorModel(gtab, fit_method='WLS', return_S0_hat=False, *args, **kwargs)
Bases: ReconstModel
Diffusion Tensor
Methods
fit (data[, mask])
|
Fit method of the DTI model class |
predict (dti_params[, S0])
|
Predict a signal for this TensorModel class instance given parameters. |
-
__init__(gtab, fit_method='WLS', return_S0_hat=False, *args, **kwargs)
A Diffusion Tensor Model [1], [2].
- Parameters:
- gtabGradientTable class instance
- fit_methodstr or callable
str can be one of the following:
- ‘WLS’ for weighted least squares
dti.wls_fit_tensor()
- ‘LS’ or ‘OLS’ for ordinary least squares
dti.ols_fit_tensor()
- ‘NLLS’ for non-linear least-squares
dti.nlls_fit_tensor()
- ‘RT’ or ‘restore’ or ‘RESTORE’ for RESTORE robust tensor
fitting [3]
dti.restore_fit_tensor()
- callable has to have the signature:
fit_method(design_matrix, data, *args, **kwargs)
- return_S0_hatbool
Boolean to return (True) or not (False) the S0 values for the fit.
- args, kwargsarguments and key-word arguments passed to the
fit_method. See dti.wls_fit_tensor, dti.ols_fit_tensor for details
- min_signalfloat
The minimum signal value. Needs to be a strictly positive
number. Default: minimal signal in the data provided to fit.
Notes
In order to increase speed of processing, tensor fitting is done
simultaneously over many voxels. Many fit_methods use the ‘step’
parameter to set the number of voxels that will be fit at once in each
iteration. This is the chunk size as a number of voxels. A larger step
value should speed things up, but it will also take up more memory. It
is advisable to keep an eye on memory consumption as this value is
increased.
E.g., in iter_fit_tensor()
we have a default step value of
1e4
References
[1]
Basser, P.J., Mattiello, J., LeBihan, D., 1994. Estimation of
the effective self-diffusion tensor from the NMR spin echo. J Magn
Reson B 103, 247-254.
[2]
Basser, P., Pierpaoli, C., 1996. Microstructural and
physiological features of tissues elucidated by quantitative
diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219.
[3]
Lin-Ching C., Jones D.K., Pierpaoli, C. 2005. RESTORE: Robust
estimation of tensors by outlier rejection. MRM 53: 1088-1095
-
fit(data, mask=None)
Fit method of the DTI model class
- Parameters:
- dataarray
The measured signal from one voxel.
- maskarray
A boolean array used to mark the coordinates in the data that
should be analyzed that has the shape data.shape[:-1]
-
predict(dti_params, S0=1.0)
Predict a signal for this TensorModel class instance given parameters.
- Parameters:
- dti_paramsndarray
The last dimension should have 12 tensor parameters: 3
eigenvalues, followed by the 3 eigenvectors
- S0float or ndarray
The non diffusion-weighted signal in every voxel, or across all
voxels. Default: 1
-
class dipy.workflows.reconst.Workflow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: object
Methods
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
get_io_iterator()
Create an iterator for IO.
Use a couple of inspection tricks to build an IOIterator using the
previous frame (values of local variables and other contextuals) and
the run method’s docstring.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
get_sub_runs()
Return No sub runs since this is a simple workflow.
-
manage_output_overwrite()
Check if a file will be overwritten upon processing the inputs.
If it is bound to happen, an action is taken depending on
self._force_overwrite (or –force via command line). A log message is
output independently of the outcome to tell the user something
happened.
-
run(*args, **kwargs)
Execute the workflow.
Since this is an abstract class, raise exception if this code is
reached (not implemented in child class or literally called on this
class)
IvimModel
-
dipy.workflows.reconst.IvimModel(gtab, fit_method='trr', **kwargs)
Selector function to switch between the 2-stage Trust-Region Reflective
based NLLS fitting method (also containing the linear fit): trr and the
Variable Projections based fitting method: varpro.
- Parameters:
- fit_methodstring, optional
The value fit_method can either be ‘trr’ or ‘varpro’.
default : trr
auto_response_ssst
-
dipy.workflows.reconst.auto_response_ssst(gtab, data, roi_center=None, roi_radii=10, fa_thr=0.7)
- Automatic estimation of single-shell single-tissue (ssst) response
function using FA.
- Parameters:
- gtabGradientTable
- datandarray
diffusion data
- roi_centerarray-like, (3,)
Center of ROI in data. If center is None, it is assumed that it is
the center of the volume with shape data.shape[:3].
- roi_radiiint or array-like, (3,)
radii of cuboid ROI
- fa_thrfloat
FA threshold
- Returns:
- responsetuple, (2,)
(evals, S0)
- ratiofloat
The ratio between smallest versus largest eigenvalue of the response.
Notes
In CSD there is an important pre-processing step: the estimation of the
fiber response function. In order to do this, we look for voxels with very
anisotropic configurations. We get this information from
csdeconv.mask_for_response_ssst(), which returns a mask of selected voxels
(more details are available in the description of the function).
With the mask, we compute the response function by using
csdeconv.response_from_mask_ssst(), which returns the response and the
ratio (more details are available in the description of the function).
axial_diffusivity
-
dipy.workflows.reconst.axial_diffusivity(evals, axis=-1)
Axial Diffusivity (AD) of a diffusion tensor.
Also called parallel diffusivity.
- Parameters:
- evalsarray-like
Eigenvalues of a diffusion tensor, must be sorted in descending order
along axis.
- axisint
Axis of evals which contains 3 eigenvalues.
- Returns:
- adarray
Calculated AD.
Notes
AD is calculated with the following equation:
\[AD = \lambda_1\]
color_fa
-
dipy.workflows.reconst.color_fa(fa, evecs)
Color fractional anisotropy of diffusion tensor
- Parameters:
- faarray-like
Array of the fractional anisotropy (can be 1D, 2D or 3D)
- evecsarray-like
eigen vectors from the tensor model
- Returns:
- rgbArray with 3 channels for each color as the last dimension.
Colormap of the FA with red for the x value, y for the green
value and z for the blue value.
Notes
It is computed from the clipped FA between 0 and 1 using the following
formula
\[rgb = abs(max(\vec{e})) \times fa\]
deprecated_params
-
dipy.workflows.reconst.deprecated_params(old_name, new_name=None, since='', until='', version_comparator=<function cmp_pkg_version>, arg_in_kwargs=False, warn_class=<class 'dipy.utils.deprecator.ArgsDeprecationWarning'>, error_class=<class 'dipy.utils.deprecator.ExpiredDeprecationError'>, alternative='')
Deprecate a renamed or removed function argument.
The decorator assumes that the argument with the old_name
was removed
from the function signature and the new_name
replaced it at the
same position in the signature. If the old_name
argument is
given when calling the decorated function the decorator will catch it and
issue a deprecation warning and pass it on as new_name
argument.
- Parameters:
- old_namestr or list/tuple thereof
The old name of the argument.
- new_namestr or list/tuple thereof or
None
, optional The new name of the argument. Set this to None to remove the
argument old_name
instead of renaming it.
- sincestr or number or list/tuple thereof, optional
The release at which the old argument became deprecated.
- untilstr or number or list/tuple thereof, optional
Last released version at which this function will still raise a
deprecation warning. Versions higher than this will raise an
error.
- version_comparatorcallable
Callable accepting string as argument, and return 1 if string
represents a higher version than encoded in the version_comparator
,
0 if the version is equal, and -1 if the version is lower. For example,
the version_comparator
may compare the input version string to the
current package version string.
- arg_in_kwargsbool or list/tuple thereof, optional
If the argument is not a named argument (for example it
was meant to be consumed by **kwargs
) set this to
True
. Otherwise the decorator will throw an Exception
if the new_name
cannot be found in the signature of
the decorated function.
Default is False
.
- warn_classwarning, optional
Warning to be issued.
- error_classException, optional
Error to be issued
- alternativestr, optional
An alternative function or class name that the user may use in
place of the deprecated object if new_name
is None. The deprecation
warning will tell the user about this alternative if provided.
- Raises:
- TypeError
If the new argument name cannot be found in the function
signature and arg_in_kwargs was False or if it is used to
deprecate the name of the *args
-, **kwargs
-like arguments.
At runtime such an Error is raised if both the new_name
and old_name were specified when calling the function and
“relax=False”.
Notes
This function is based on the Astropy (major modification).
https://github.com/astropy/astropy. See COPYING file distributed along with
the astropy package for the copyright and license terms.
Examples
The deprecation warnings are not shown in the following examples.
To deprecate a positional or keyword argument::
>>> from dipy.utils.deprecator import deprecated_params
>>> @deprecated_params(‘sig’, ‘sigma’, ‘0.3’)
… def test(sigma):
… return sigma
>>> test(2)
2
>>> test(sigma=2)
2
>>> test(sig=2) # doctest: +SKIP
2
It is also possible to replace multiple arguments. The old_name
,
new_name
and since
have to be tuple or list and contain the
same number of entries::
>>> @deprecated_params([‘a’, ‘b’], [‘alpha’, ‘beta’],
… [‘0.2’, 0.4])
… def test(alpha, beta):
… return alpha, beta
>>> test(a=2, b=3) # doctest: +SKIP
(2, 3)
fractional_anisotropy
-
dipy.workflows.reconst.fractional_anisotropy(evals, axis=-1)
Return Fractional anisotropy (FA) of a diffusion tensor.
- Parameters:
- evalsarray-like
Eigenvalues of a diffusion tensor.
- axisint
Axis of evals which contains 3 eigenvalues.
- Returns:
- faarray
Calculated FA. Range is 0 <= FA <= 1.
Notes
FA is calculated using the following equation:
\[FA = \sqrt{\frac{1}{2}\frac{(\lambda_1-\lambda_2)^2+(\lambda_1-
\lambda_3)^2+(\lambda_2-\lambda_3)^2}{\lambda_1^2+
\lambda_2^2+\lambda_3^2}}\]
geodesic_anisotropy
-
dipy.workflows.reconst.geodesic_anisotropy(evals, axis=-1)
Geodesic anisotropy (GA) of a diffusion tensor.
- Parameters:
- evalsarray-like
Eigenvalues of a diffusion tensor.
- axisint
Axis of evals which contains 3 eigenvalues.
- Returns:
- gaarray
Calculated GA. In the range 0 to +infinity
Notes
GA is calculated using the following equation given in [1]:
\[GA = \sqrt{\sum_{i=1}^3
\log^2{\left ( \lambda_i/<\mathbf{D}> \right )}},
\quad \textrm{where} \quad <\mathbf{D}> =
(\lambda_1\lambda_2\lambda_3)^{1/3}\]
Note that the notation, \(<D>\), is often used as the mean diffusivity (MD)
of the diffusion tensor and can lead to confusions in the literature
(see [1] versus [2] versus [3] for example). Reference [2] defines
geodesic anisotropy (GA) with \(<D>\) as the MD in the denominator of the
sum. This is wrong. The original paper [1] defines GA with
\(<D> = det(D)^{1/3}\), as the isotropic part of the distance. This might be
an explanation for the confusion. The isotropic part of the diffusion
tensor in Euclidean space is the MD whereas the isotropic part of the
tensor in log-Euclidean space is \(det(D)^{1/3}\). The Appendix of [1] and
log-Euclidean derivations from [3] are clear on this. Hence, all that to
say that \(<D> = det(D)^{1/3}\) here for the GA definition and not MD.
References
[1]
(1,2,3,4)
P. G. Batchelor, M. Moakher, D. Atkinson, F. Calamante,
A. Connelly, “A rigorous framework for diffusion tensor calculus”,
Magnetic Resonance in Medicine, vol. 53, pp. 221-225, 2005.
[2]
(1,2)
M. M. Correia, V. F. Newcombe, G.B. Williams.
“Contrast-to-noise ratios for indices of anisotropy obtained from
diffusion MRI: a study with standard clinical b-values at 3T”.
NeuroImage, vol. 57, pp. 1103-1115, 2011.
[3]
(1,2)
A. D. Lee, etal, P. M. Thompson.
“Comparison of fractional and geodesic anisotropy in diffusion tensor
images of 90 monozygotic and dizygotic twins”. 5th IEEE International
Symposium on Biomedical Imaging (ISBI), pp. 943-946, May 2008.
[4]
V. Arsigny, P. Fillard, X. Pennec, N. Ayache.
“Log-Euclidean metrics for fast and simple calculus on diffusion
tensors.” Magnetic Resonance in Medecine, vol 56, pp. 411-421, 2006.
get_mode
-
dipy.workflows.reconst.get_mode(q_form)
Mode (MO) of a diffusion tensor [1].
- Parameters:
- q_formndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (x, y, z, 3, 3) or (n, 3, 3) or (3, 3).
- Returns:
- modearray
Calculated tensor mode in each spatial coordinate.
Notes
Mode ranges between -1 (planar anisotropy) and +1 (linear anisotropy)
with 0 representing orthotropy. Mode is calculated with the
following equation (equation 9 in [1]):
\[Mode = 3*\sqrt{6}*det(\widetilde{A}/norm(\widetilde{A}))\]
Where \(\widetilde{A}\) is the deviatoric part of the tensor quadratic form.
References
[1]
(1,2,3)
Daniel B. Ennis and G. Kindlmann, “Orthogonal Tensor
Invariants and the Analysis of Diffusion Tensor Magnetic Resonance
Images”, Magnetic Resonance in Medicine, vol. 55, no. 1, pp. 136-146,
2006.
get_sphere
-
dipy.workflows.reconst.get_sphere(name='symmetric362')
provide triangulated spheres
- Parameters:
- namestr
which sphere - one of:
* ‘symmetric362’
* ‘symmetric642’
* ‘symmetric724’
* ‘repulsion724’
* ‘repulsion100’
* ‘repulsion200’
- Returns:
- spherea dipy.core.sphere.Sphere class instance
Examples
>>> import numpy as np
>>> from dipy.data import get_sphere
>>> sphere = get_sphere('symmetric362')
>>> verts, faces = sphere.vertices, sphere.faces
>>> verts.shape == (362, 3)
True
>>> faces.shape == (720, 3)
True
>>> verts, faces = get_sphere('not a sphere name')
Traceback (most recent call last):
...
DataError: No sphere called "not a sphere name"
gradient_table
-
dipy.workflows.reconst.gradient_table(bvals, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=0.01, btens=None)
A general function for creating diffusion MR gradients.
It reads, loads and prepares scanner parameters like the b-values and
b-vectors so that they can be useful during the reconstruction process.
- Parameters:
- bvalscan be any of the four options
an array of shape (N,) or (1, N) or (N, 1) with the b-values.
a path for the file which contains an array like the above (1).
an array of shape (N, 4) or (4, N). Then this parameter is
considered to be a b-table which contains both bvals and bvecs. In
this case the next parameter is skipped.
a path for the file which contains an array like the one at (3).
- bvecscan be any of two options
an array of shape (N, 3) or (3, N) with the b-vectors.
a path for the file which contains an array like the previous.
- big_deltafloat
acquisition pulse separation time in seconds (default None)
- small_deltafloat
acquisition pulse duration time in seconds (default None)
- b0_thresholdfloat
All b-values with values less than or equal to bo_threshold are
considered as b0s i.e. without diffusion weighting.
- atolfloat
All b-vectors need to be unit vectors up to a tolerance.
- btenscan be any of three options
a string specifying the shape of the encoding tensor for all volumes
in data. Options: ‘LTE’, ‘PTE’, ‘STE’, ‘CTE’ corresponding to
linear, planar, spherical, and “cigar-shaped” tensor encoding.
Tensors are rotated so that linear and cigar tensors are aligned
with the corresponding gradient direction and the planar tensor’s
normal is aligned with the corresponding gradient direction.
Magnitude is scaled to match the b-value.
an array of strings of shape (N,), (N, 1), or (1, N) specifying
encoding tensor shape for each volume separately. N corresponds to
the number volumes in data. Options for elements in array: ‘LTE’,
‘PTE’, ‘STE’, ‘CTE’ corresponding to linear, planar, spherical, and
“cigar-shaped” tensor encoding. Tensors are rotated so that linear
and cigar tensors are aligned with the corresponding gradient
direction and the planar tensor’s normal is aligned with the
corresponding gradient direction. Magnitude is scaled to match the
b-value.
an array of shape (N,3,3) specifying the b-tensor of each volume
exactly. N corresponds to the number volumes in data. No rotation or
scaling is performed.
- Returns:
- gradientsGradientTable
A GradientTable with all the gradient information.
Notes
Often b0s (b-values which correspond to images without diffusion
weighting) have 0 values however in some cases the scanner cannot
provide b0s of an exact 0 value and it gives a bit higher values
e.g. 6 or 12. This is the purpose of the b0_threshold in the __init__.
We assume that the minimum number of b-values is 7.
B-vectors should be unit vectors.
Examples
>>> from dipy.core.gradients import gradient_table
>>> bvals = 1500 * np.ones(7)
>>> bvals[0] = 0
>>> sq2 = np.sqrt(2) / 2
>>> bvecs = np.array([[0, 0, 0],
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... [sq2, sq2, 0],
... [sq2, 0, sq2],
... [0, sq2, sq2]])
>>> gt = gradient_table(bvals, bvecs)
>>> gt.bvecs.shape == bvecs.shape
True
>>> gt = gradient_table(bvals, bvecs.T)
>>> gt.bvecs.shape == bvecs.T.shape
False
literal_eval
-
dipy.workflows.reconst.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
sets, booleans, and None.
load_nifti
-
dipy.workflows.reconst.load_nifti(fname, return_img=False, return_voxsize=False, return_coords=False, as_ndarray=True)
Load data and other information from a nifti file.
- Parameters:
- fnamestr
Full path to a nifti file.
- return_imgbool, optional
Whether to return the nibabel nifti img object. Default: False
- return_voxsize: bool, optional
Whether to return the nifti header zooms. Default: False
- return_coordsbool, optional
Whether to return the nifti header aff2axcodes. Default: False
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray.
If you want to save memory and delay this casting, just turn this
option to False (default: True)
- Returns:
- A tuple, with (at the most, if all keyword args are set to True):
- (data, img.affine, img, vox_size, nib.aff2axcodes(img.affine))
load_nifti_data
-
dipy.workflows.reconst.load_nifti_data(fname, as_ndarray=True)
Load only the data array from a nifti file.
- Parameters:
- fnamestr
Full path to the file.
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray.
If you want to save memory and delay this casting, just turn this
option to False (default: True)
- Returns:
- data: np.ndarray or nib.ArrayProxy
lower_triangular
-
dipy.workflows.reconst.lower_triangular(tensor, b0=None)
Returns the six lower triangular values of the tensor ordered as
(Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) and a dummy variable if b0 is not None.
- Parameters:
- tensorarray_like (…, 3, 3)
a collection of 3, 3 diffusion tensors
- b0float
if b0 is not none log(b0) is returned as the dummy variable
- Returns:
- Dndarray
If b0 is none, then the shape will be (…, 6) otherwise (…, 7)
mean_diffusivity
-
dipy.workflows.reconst.mean_diffusivity(evals, axis=-1)
Mean Diffusivity (MD) of a diffusion tensor.
- Parameters:
- evalsarray-like
Eigenvalues of a diffusion tensor.
- axisint
Axis of evals which contains 3 eigenvalues.
- Returns:
- mdarray
Calculated MD.
Notes
MD is calculated with the following equation:
\[MD = \frac{\lambda_1 + \lambda_2 + \lambda_3}{3}\]
nifti1_symmat
-
dipy.workflows.reconst.nifti1_symmat(image_data, *args, **kwargs)
Returns a Nifti1Image with a symmetric matrix intent
- Parameters:
- image_dataarray-like
should have lower triangular elements of a symmetric matrix along the
last dimension
- all other arguments and keywords are passed to Nifti1Image
- Returns:
- imageNifti1Image
5d, extra dimensions added before the last. Has symmetric matrix intent
code
peaks_from_model
-
dipy.workflows.reconst.peaks_from_model(model, data, sphere, relative_peak_threshold, min_separation_angle, mask=None, return_odf=False, return_sh=True, gfa_thr=0, normalize_peaks=False, sh_order=8, sh_basis_type=None, npeaks=5, B=None, invB=None, parallel=False, num_processes=None)
Fit the model to data and computes peaks and metrics
- Parameters:
- modela model instance
model will be used to fit the data.
- datandarray
Diffusion data.
- sphereSphere
The Sphere providing discrete directions for evaluation.
- relative_peak_thresholdfloat
Only return peaks greater than relative_peak_threshold * m
where m
is the largest peak.
- min_separation_anglefloat in [0, 90] The minimum distance between
directions. If two peaks are too close only the larger of the two is
returned.
- maskarray, optional
If mask is provided, voxels that are False in mask are skipped and
no peaks are returned.
- return_odfbool
If True, the odfs are returned.
- return_shbool
If True, the odf as spherical harmonics coefficients is returned
- gfa_thrfloat
Voxels with gfa less than gfa_thr are skipped, no peaks are returned.
- normalize_peaksbool
If true, all peak values are calculated relative to max(odf).
- sh_orderint, optional
Maximum SH order in the SH fit. For sh_order, there will be
(sh_order + 1) * (sh_order + 2) / 2
SH coefficients (default 8).
- sh_basis_type{None, ‘tournier07’, ‘descoteaux07’}
None
for the default DIPY basis,
tournier07
for the Tournier 2007 [2] basis, and
descoteaux07
for the Descoteaux 2007 [1] basis
(None
defaults to descoteaux07
).
- npeaksint
Maximum number of peaks found (default 5 peaks).
- Bndarray, optional
Matrix that transforms spherical harmonics to spherical function
sf = np.dot(sh, B)
.
- invBndarray, optional
Inverse of B.
- parallel: bool
If True, use multiprocessing to compute peaks and metric
(default False). Temporary files are saved in the default temporary
directory of the system. It can be changed using import tempfile
and tempfile.tempdir = '/path/to/tempdir'
.
- num_processes: int, optional
If parallel is True, the number of subprocesses to use
(default multiprocessing.cpu_count()). 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.
- Returns:
- pamPeaksAndMetrics
An object with gfa
, peak_directions
, peak_values
,
peak_indices
, odf
, shm_coeffs
as attributes
References
[1]
Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R.
Regularized, Fast, and Robust Analytical Q-ball Imaging.
Magn. Reson. Med. 2007;58:497-510.
[2]
Tournier J.D., Calamante F. and Connelly A. Robust determination
of the fibre orientation distribution in diffusion MRI:
Non-negativity constrained super-resolved spherical deconvolution.
NeuroImage. 2007;35(4):1459-1472.
peaks_to_niftis
-
dipy.workflows.reconst.peaks_to_niftis(pam, fname_shm, fname_dirs, fname_values, fname_indices, fname_gfa, reshape_dirs=False)
Save SH, directions, indices and values of peaks to Nifti.
radial_diffusivity
-
dipy.workflows.reconst.radial_diffusivity(evals, axis=-1)
Radial Diffusivity (RD) of a diffusion tensor.
Also called perpendicular diffusivity.
- Parameters:
- evalsarray-like
Eigenvalues of a diffusion tensor, must be sorted in descending order
along axis.
- axisint
Axis of evals which contains 3 eigenvalues.
- Returns:
- rdarray
Calculated RD.
Notes
RD is calculated with the following equation:
\[RD = \frac{\lambda_2 + \lambda_3}{2}\]
read_bvals_bvecs
-
dipy.workflows.reconst.read_bvals_bvecs(fbvals, fbvecs)
Read b-values and b-vectors from disk.
- Parameters:
- fbvalsstr
Full path to file with b-values. None to not read bvals.
- fbvecsstr
Full path of file with b-vectors. None to not read bvecs.
- Returns:
- bvalsarray, (N,) or None
- bvecsarray, (N, 3) or None
Notes
Files can be either ‘.bvals’/’.bvecs’ or ‘.txt’ or ‘.npy’ (containing
arrays stored with the appropriate values).
save_nifti
-
dipy.workflows.reconst.save_nifti(fname, data, affine, hdr=None, dtype=None)
Save a data array into a nifti file.
- Parameters:
- fnamestr
The full path to the file to be saved.
- datandarray
The array with the data to save.
- affine4x4 array
The affine transform associated with the file.
- hdrnifti header, optional
May contain additional information to store in the file header.
- Returns:
- None
save_peaks
-
dipy.workflows.reconst.save_peaks(fname, pam, affine=None, verbose=False)
Save all important attributes of object PeaksAndMetrics in a PAM5 file
(HDF5).
- Parameters:
- fnamestring
Filename of PAM5 file
- pamPeaksAndMetrics
Object holding peak_dirs, shm_coeffs and other attributes
- affinearray
The 4x4 matrix transforming the date from native to world coordinates.
PeaksAndMetrics should have that attribute but if not it can be
provided here. Default None.
- verbosebool
Print summary information about the saved file.
split_dki_param
-
dipy.workflows.reconst.split_dki_param(dki_params)
Extract the diffusion tensor eigenvalues, the diffusion tensor
eigenvector matrix, and the 15 independent elements of the kurtosis tensor
from the model parameters estimated from the DKI model
- Parameters:
- dki_paramsndarray (x, y, z, 27) or (n, 27)
All parameters estimated from the diffusion kurtosis model.
Parameters are ordered as follows:
Three diffusion tensor’s eigenvalues
Three lines of the eigenvector matrix each containing the first,
second and third coordinates of the eigenvector
Fifteen elements of the kurtosis tensor
- Returns:
- eigvalsarray (x, y, z, 3) or (n, 3)
Eigenvalues from eigen decomposition of the tensor.
- eigvecsarray (x, y, z, 3, 3) or (n, 3, 3)
Associated eigenvectors from eigen decomposition of the tensor.
Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with
eigvals[j])
- ktarray (x, y, z, 15) or (n, 15)
Fifteen elements of the kurtosis tensor
warn
-
dipy.workflows.reconst.warn(/, message, category=None, stacklevel=1, source=None)
Issue a warning, or maybe ignore it or raise an exception.
-
class dipy.workflows.segment.LabelsBundlesFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (streamline_files, labels_files[, ...])
|
Extract bundles using existing indices (labels) |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(streamline_files, labels_files, out_dir='', out_bundle='recognized_orig.trk')
Extract bundles using existing indices (labels)
- Parameters:
- streamline_filesstring
The path of streamline files where you want to recognize bundles.
- labels_filesstring
The path of model bundle files.
- out_dirstring, optional
Output directory. (default current directory)
- out_bundlestring, optional
Recognized bundle in the space of the model bundle.
References
[Garyfallidis17]
Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
-
class dipy.workflows.segment.RecoBundles(streamlines, greater_than=50, less_than=1000000, cluster_map=None, clust_thr=15, nb_pts=20, rng=None, verbose=False)
Bases: object
Methods
evaluate_results (model_bundle, ...)
|
Compare the similiarity between two given bundles, model bundle, and extracted bundle. |
recognize (model_bundle, model_clust_thr[, ...])
|
Recognize the model_bundle in self.streamlines |
refine (model_bundle, pruned_streamlines, ...)
|
Refine and recognize the model_bundle in self.streamlines This method expects once pruned streamlines as input. |
-
__init__(streamlines, greater_than=50, less_than=1000000, cluster_map=None, clust_thr=15, nb_pts=20, rng=None, verbose=False)
Recognition of bundles
Extract bundles from a participants’ tractograms using model bundles
segmented from a different subject or an atlas of bundles.
See [Garyfallidis17] for the details.
- Parameters:
- streamlinesStreamlines
The tractogram in which you want to recognize bundles.
- greater_thanint, optional
Keep streamlines that have length greater than
this value (default 50)
- less_thanint, optional
Keep streamlines have length less than this value (default 1000000)
- cluster_mapQB map, optional.
Provide existing clustering to start RB faster (default None).
- clust_thrfloat, optional.
Distance threshold in mm for clustering streamlines.
Default: 15.
- nb_ptsint, optional.
Number of points per streamline (default 20)
- rngRandomState
If None define RandomState in initialization function.
Default: None
- verbose: bool, optional.
If True, log information.
Notes
Make sure that before creating this class that the streamlines and
the model bundles are roughly in the same space.
Also default thresholds are assumed in RAS 1mm^3 space. You may
want to adjust those if your streamlines are not in world coordinates.
References
[Garyfallidis17]
Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
-
evaluate_results(model_bundle, pruned_streamlines, slr_select)
Compare the similiarity between two given bundles, model bundle,
and extracted bundle.
- Parameters:
- model_bundleStreamlines
- pruned_streamlinesStreamlines
- slr_selecttuple
Select the number of streamlines from model to neirborhood of
model to perform the local SLR.
- Returns:
- ba_valuefloat
bundle adjacency value between model bundle and pruned bundle
- bmd_valuefloat
bundle minimum distance value between model bundle and
pruned bundle
-
recognize(model_bundle, model_clust_thr, reduction_thr=10, reduction_distance='mdf', slr=True, num_threads=None, slr_metric=None, slr_x0=None, slr_bounds=None, slr_select=(400, 600), slr_method='L-BFGS-B', pruning_thr=5, pruning_distance='mdf')
Recognize the model_bundle in self.streamlines
- Parameters:
- model_bundleStreamlines
model bundle streamlines used as a reference to extract similar
streamlines from input tractogram
- model_clust_thrfloat
MDF distance threshold for the model bundles
- reduction_thrfloat, optional
Reduce search space in the target tractogram by (mm) (default 10)
- reduction_distancestring, optional
Reduction distance type can be mdf or mam (default mdf)
- slrbool, optional
Use Streamline-based Linear Registration (SLR) locally
(default True)
- num_threadsint, optional
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.
- slr_metricBundleMinDistanceMetric
- slr_x0array or int or str, optional
Transformation allowed. translation, rigid, similarity or scaling
Initial parametrization for the optimization.
- If 1D array with:
a) 6 elements then only rigid registration is performed with
the 3 first elements for translation and 3 for rotation.
b) 7 elements also isotropic scaling is performed (similarity).
c) 12 elements then translation, rotation (in degrees),
scaling and shearing are performed (affine).
Here is an example of x0 with 12 elements:
x0=np.array([0, 10, 0, 40, 0, 0, 2., 1.5, 1, 0.1, -0.5, 0])
This has translation (0, 10, 0), rotation (40, 0, 0) in
degrees, scaling (2., 1.5, 1) and shearing (0.1, -0.5, 0).
- If int:
- 6
x0 = np.array([0, 0, 0, 0, 0, 0])
- 7
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
- 12
x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
- If str:
- “rigid”
x0 = np.array([0, 0, 0, 0, 0, 0])
- “similarity”
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
- “affine”
``x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
(default None)
- slr_boundsarray, optional
(default None)
- slr_selecttuple, optional
Select the number of streamlines from model to neirborhood of
model to perform the local SLR.
- slr_methodstring, optional
Optimization method ‘L_BFGS_B’ or ‘Powell’ optimizers can be used.
(default ‘L-BFGS-B’)
- pruning_thrfloat, optional
Pruning after reducing the search space (default 5).
- pruning_distancestring, optional
Pruning distance type can be mdf or mam (default mdf)
- Returns:
- recognized_transfStreamlines
Recognized bundle in the space of the model tractogram
- recognized_labelsarray
Indices of recognized bundle in the original tractogram
References
[Garyfallidis17]
Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
-
refine(model_bundle, pruned_streamlines, model_clust_thr, reduction_thr=14, reduction_distance='mdf', slr=True, slr_metric=None, slr_x0=None, slr_bounds=None, slr_select=(400, 600), slr_method='L-BFGS-B', pruning_thr=6, pruning_distance='mdf')
Refine and recognize the model_bundle in self.streamlines
This method expects once pruned streamlines as input. It refines the
first ouput of recobundle by applying second local slr (optional),
and second pruning. This method is useful when we are dealing with
noisy data or when we want to extract small tracks from tractograms.
This time, search space is created using pruned bundle and not model
bundle.
- Parameters:
- model_bundleStreamlines
model bundle streamlines used as a reference to extract similar
streamlines from input tractogram
- pruned_streamlinesStreamlines
Recognized bundle from target tractogram by RecoBundles.
- model_clust_thrfloat
MDF distance threshold for the model bundles
- reduction_thrfloat
Reduce search space by (mm) (default 14)
- reduction_distancestring
Reduction distance type can be mdf or mam (default mdf)
- slrbool
Use Streamline-based Linear Registration (SLR) locally
(default True)
- slr_metricBundleMinDistanceMetric
- slr_x0array or int or str
Transformation allowed. translation, rigid, similarity or scaling
Initial parametrization for the optimization.
- If 1D array with:
a) 6 elements then only rigid registration is performed with
the 3 first elements for translation and 3 for rotation.
b) 7 elements also isotropic scaling is performed (similarity).
c) 12 elements then translation, rotation (in degrees),
scaling and shearing are performed (affine).
Here is an example of x0 with 12 elements:
x0=np.array([0, 10, 0, 40, 0, 0, 2., 1.5, 1, 0.1, -0.5, 0])
This has translation (0, 10, 0), rotation (40, 0, 0) in
degrees, scaling (2., 1.5, 1) and shearing (0.1, -0.5, 0).
- If int:
- 6
x0 = np.array([0, 0, 0, 0, 0, 0])
- 7
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
- 12
x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
- If str:
- “rigid”
x0 = np.array([0, 0, 0, 0, 0, 0])
- “similarity”
x0 = np.array([0, 0, 0, 0, 0, 0, 1.])
- “affine”
``x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])
(default None)
- slr_boundsarray
(default None)
- slr_selecttuple
Select the number of streamlines from model to neirborhood of
model to perform the local SLR.
- slr_methodstring
Optimization method ‘L_BFGS_B’ or ‘Powell’ optimizers can be used.
(default ‘L-BFGS-B’)
- pruning_thrfloat
Pruning after reducing the search space (default 6).
- pruning_distancestring
Pruning distance type can be mdf or mam (default mdf)
- Returns:
- recognized_transfStreamlines
Recognized bundle in the space of the model tractogram
- recognized_labelsarray
Indices of recognized bundle in the original tractogram
References
[Garyfallidis17]
Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
[Chandio2020]
Chandio, B.Q., Risacher, S.L., Pestilli, F.,
Bullock, D., Yeh, FC., Koudoro, S., Rokem, A., Harezlak, J., and
Garyfallidis, E. Bundle analytics, a computational framework for
investigating the shapes and profiles of brain pathways across
populations. Sci Rep 10, 17149 (2020)
-
class dipy.workflows.segment.RecoBundlesFlow(output_strategy='absolute', mix_names=False, force=False, skip=False)
Bases: Workflow
Methods
get_io_iterator ()
|
Create an iterator for IO. |
get_short_name ()
|
Return A short name for the workflow used to subdivide. |
get_sub_runs ()
|
Return No sub runs since this is a simple workflow. |
manage_output_overwrite ()
|
Check if a file will be overwritten upon processing the inputs. |
run (streamline_files, model_bundle_files[, ...])
|
Recognize bundles |
-
__init__(output_strategy='absolute', mix_names=False, force=False, skip=False)
Initialize the basic workflow object.
This object takes care of any workflow operation that is common to all
the workflows. Every new workflow should extend this class.
-
classmethod get_short_name()
Return A short name for the workflow used to subdivide.
The short name is used by CombinedWorkflows and the argparser to
subdivide the commandline parameters avoiding the trouble of having
subworkflows parameters with the same name.
For example, a combined workflow with dti reconstruction and csd
reconstruction might en up with the b0_threshold parameter. Using short
names, we will have dti.b0_threshold and csd.b0_threshold available.
Returns class name by default but it is strongly advised to set it to
something shorter and easier to write on commandline.
-
run(streamline_files, model_bundle_files, greater_than=50, less_than=1000000, no_slr=False, clust_thr=15.0, reduction_thr=15.0, reduction_distance='mdf', model_clust_thr=2.5, pruning_thr=8.0, pruning_distance='mdf', slr_metric='symmetric', slr_transform='similarity', slr_matrix='small', refine=False, r_reduction_thr=12.0, r_pruning_thr=6.0, no_r_slr=False, out_dir='', out_recognized_transf='recognized.trk', out_recognized_labels='labels.npy')
Recognize bundles
- Parameters:
- streamline_filesstring
The path of streamline files where you want to recognize bundles.
- model_bundle_filesstring
The path of model bundle files.
- greater_thanint, optional
Keep streamlines that have length greater than
this value in mm.
- less_thanint, optional
Keep streamlines have length less than this value
in mm.
- no_slrbool, optional
Don’t enable local Streamline-based Linear
Registration.
- clust_thrfloat, optional
MDF distance threshold for all streamlines.
- reduction_thrfloat, optional
Reduce search space by (mm).
- reduction_distancestring, optional
Reduction distance type can be mdf or mam.
- model_clust_thrfloat, optional
MDF distance threshold for the model bundles.
- pruning_thrfloat, optional
Pruning after matching.
- pruning_distancestring, optional
Pruning distance type can be mdf or mam.
- slr_metricstring, optional
Options are None, symmetric, asymmetric or diagonal.
- slr_transformstring, optional
Transformation allowed. translation, rigid, similarity or scaling.
- slr_matrixstring, optional
Options are ‘nano’, ‘tiny’, ‘small’, ‘medium’, ‘large’, ‘huge’.
- refinebool, optional
Enable refine recognized bundle.
- r_reduction_thrfloat, optional
Refine reduce search space by (mm).
- r_pruning_thrfloat, optional
Refine pruning after matching.
- no_r_slrbool, optional
Don’t enable Refine local Streamline-based Linear
Registration.
- out_dirstring, optional
Output directory. (default current directory)
- out_recognized_transfstring, optional
Recognized bundle in the space of the model bundle.
- out_recognized_labelsstring, optional
Indices of recognized bundle in the original tractogram.
References
[Garyfallidis17]
Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
[Chandio2020]
Chandio, B.Q., Risacher, S.L., Pestilli, F.,
Bullock, D., Yeh, FC., Koudoro, S., Rokem, A., Harezlak, J., and
Garyfallidis, E. Bundle analytics, a computational framework for
investigating the shapes and profiles of brain pathways across
populations. Sci Rep 10, 17149 (2020)
-
class dipy.workflows.segment.Space(value)
Bases: Enum
Enum to simplify future change to convention
-
__init__(*args, **kwargs)
-
RASMM = 'rasmm'
-
VOX = 'vox'
-
VOXMM = 'voxmm'
-
class dipy.workflows.segment.StatefulTractogram(streamlines, reference, space, origin=Origin.NIFTI, data_per_point=None, data_per_streamline=None)
Bases: object
Class for stateful representation of collections of streamlines
Object designed to be identical no matter the file format
(trk, tck, vtk, fib, dpy). Facilitate transformation between space and
data manipulation for each streamline / point.
- Attributes:
affine
Getter for the reference affine
data_per_point
Getter for data_per_point
data_per_streamline
Getter for data_per_streamline
dimensions
Getter for the reference dimensions
origin
Getter for origin standard
space
Getter for the current space
space_attributes
Getter for spatial attribute
streamlines
Partially safe getter for streamlines
voxel_order
Getter for the reference voxel order
voxel_sizes
Getter for the reference voxel sizes
Methods
are_compatible (sft_1, sft_2)
|
Compatibility verification of two StatefulTractogram to ensure space, origin, data_per_point and data_per_streamline consistency |
compute_bounding_box ()
|
Compute the bounding box of the streamlines in their current state |
from_sft (streamlines, sft[, data_per_point, ...])
|
Create an instance of StatefulTractogram from another instance of StatefulTractogram. |
get_data_per_point_keys ()
|
Return a list of the data_per_point attribute names |
get_data_per_streamline_keys ()
|
Return a list of the data_per_streamline attribute names |
get_streamlines_copy ()
|
Safe getter for streamlines (for slicing) |
is_bbox_in_vox_valid ()
|
Verify that the bounding box is valid in voxel space. |
remove_invalid_streamlines ([epsilon])
|
Remove streamlines with invalid coordinates from the object. |
to_center ()
|
Safe function to shift streamlines so the center of voxel is the origin |
to_corner ()
|
Safe function to shift streamlines so the corner of voxel is the origin |
to_origin (target_origin)
|
Safe function to change streamlines to a particular origin standard False means NIFTI (center) and True means TrackVis (corner) |
to_rasmm ()
|
Safe function to transform streamlines and update state |
to_space (target_space)
|
Safe function to transform streamlines to a particular space using an enum and update state |
to_vox ()
|
Safe function to transform streamlines and update state |
to_voxmm ()
|
Safe function to transform streamlines and update state |
-
__init__(streamlines, reference, space, origin=Origin.NIFTI, data_per_point=None, data_per_streamline=None)
Create a strict, state-aware, robust tractogram
- Parameters:
- streamlineslist or ArraySequence
Streamlines of the tractogram
- referenceNifti or Trk filename, Nifti1Image or TrkFile,
Nifti1Header, trk.header (dict) or another Stateful Tractogram
Reference that provides the spatial attributes.
Typically a nifti-related object from the native diffusion used for
streamlines generation
- spaceEnum (dipy.io.stateful_tractogram.Space)
Current space in which the streamlines are (vox, voxmm or rasmm)
After tracking the space is VOX, after loading with nibabel
the space is RASMM
- originEnum (dipy.io.stateful_tractogram.Origin), optional
Current origin in which the streamlines are (center or corner)
After loading with nibabel the origin is CENTER
- data_per_pointdict, optional
Dictionary in which each key has X items, each items has Y_i items
X being the number of streamlines
Y_i being the number of points on streamlines #i
- data_per_streamlinedict, optional
Dictionary in which each key has X items
X being the number of streamlines
Notes
Very important to respect the convention, verify that streamlines
match the reference and are effectively in the right space.
Any change to the number of streamlines, data_per_point or
data_per_streamline requires particular verification.
In a case of manipulation not allowed by this object, use Nibabel
directly and be careful.
-
property affine
Getter for the reference affine
-
static are_compatible(sft_1, sft_2)
Compatibility verification of two StatefulTractogram to ensure space,
origin, data_per_point and data_per_streamline consistency
-
compute_bounding_box()
Compute the bounding box of the streamlines in their current state
- Returns:
- outputndarray
8 corners of the XYZ aligned box, all zeros if no streamlines
-
property data_per_point
Getter for data_per_point
-
property data_per_streamline
Getter for data_per_streamline
-
property dimensions
Getter for the reference dimensions
-
static from_sft(streamlines, sft, data_per_point=None, data_per_streamline=None)
Create an instance of StatefulTractogram from another instance
of StatefulTractogram.
- Parameters:
- streamlineslist or ArraySequence
Streamlines of the tractogram
- sftStatefulTractogram,
The other StatefulTractogram to copy the space_attribute AND
state from.
- data_per_pointdict, optional
Dictionary in which each key has X items, each items has Y_i items
X being the number of streamlines
Y_i being the number of points on streamlines #i
- data_per_streamlinedict, optional
Dictionary in which each key has X items
X being the number of streamlines
- —–
-
get_data_per_point_keys()
Return a list of the data_per_point attribute names
-
get_data_per_streamline_keys()
Return a list of the data_per_streamline attribute names
-
get_streamlines_copy()
Safe getter for streamlines (for slicing)
-
is_bbox_in_vox_valid()
Verify that the bounding box is valid in voxel space.
Negative coordinates or coordinates above the volume dimensions
are considered invalid in voxel space.
- Returns:
- outputbool
Are the streamlines within the volume of the associated reference
-
property origin
Getter for origin standard
-
remove_invalid_streamlines(epsilon=0.001)
Remove streamlines with invalid coordinates from the object.
Will also remove the data_per_point and data_per_streamline.
Invalid coordinates are any X,Y,Z values above the reference
dimensions or below zero
- Parameters:
- epsilonfloat (optional)
Epsilon value for the bounding box verification.
Default is 1e-6.
- Returns:
- outputtuple
Tuple of two list, indices_to_remove, indices_to_keep
-
property space
Getter for the current space
-
property space_attributes
Getter for spatial attribute
-
property streamlines
Partially safe getter for streamlines
-
to_center()
Safe function to shift streamlines so the center of voxel is
the origin
-
to_corner()
Safe function to shift streamlines so the corner of voxel is
the origin