stats#

Statistical analysis of diffusion data.

Tools for statistical analysis, group studies, and quality assessment of dMRI results.

Module: stats.analysis#

SpectraGrid(atlas_bundle, *[, ...])

SPECTRA grid defined by an atlas bundle.

peak_values(bundle, peaks, dt, pname, bname, ...)

Peak_values function finds the generalized fractional anisotropy (gfa)

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.

buan_profile(model_bundle, bundle, ...[, ...])

Create BUAN weighted mean bundle profiles (lite).

get_centroid(bundle, *[, n_points, threshold])

Compute a representative QuickBundles centroid for a bundle.

get_n_segment_by_length(bundle, *[, ...])

Estimate the number of along-tract segments from bundle length.

compute_robust_centroid(bundle, *[, ...])

Compute a centroid that covers the full extent of a bundle.

create_radial_bins(radial_distance, *[, ...])

Create bins from signed radial distances.

get_grid_from_atlas(atlas_bundle, *[, ...])

Construct a SPECTRA grid from an atlas bundle.

parameterize_bundle(bundle, centroid, ...[, ...])

Map a bundle onto a SPECTRA grid.

spectra_assignment_map(target_bundle, ...[, ...])

Assign bundle points to an atlas-defined SPECTRA grid.

grid_profile(orig_bundle, s_index, r_index, ...)

Compute mean metric values within a SPECTRA grid.

spectra_profile(model_bundle, bundle, ...[, ...])

Create a two-dimensional SPECTRA bundle profile.

gaussian_weights(bundle, *[, n_points, ...])

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

afq_profile(data, bundle, affine, *[, ...])

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

Module: stats.qc#

find_qspace_neighbors(gtab)

Create a mapping of dwi volume index to its nearest neighbor.

neighboring_dwi_correlation(dwi_data, gtab, *)

Calculate the Neighboring DWI Correlation (NDC) from dMRI data.

Module: stats.sketching#

count_sketch(matrixa_name, matrixa_dtype, ...)

Count Sketching algorithm to reduce the size of the matrix.

SpectraGrid#

class dipy.stats.analysis.SpectraGrid(atlas_bundle, *, segment_length=5.0, radial_length=5.0, n_segments=None, n_radial=None, threshold=100.0, use_robust_centroid=True, robust_method='linear')[source]#

Bases: object

SPECTRA grid defined by an atlas bundle.

See [1] for further details about the method.

The grid is built once from the atlas bundle and can then be applied to any number of subject bundles, so users do not have to carry the centroid, radial vectors and radial edges between function calls.

Parameters:
atlas_bundleStreamlines

Atlas or template bundle used to define the grid.

segment_lengthfloat, optional

Desired along-tract segment length in millimeters.

radial_lengthfloat, optional

Desired radial-bin width in millimeters.

n_segmentsint, optional

Number of along-tract segments.

n_radialint, optional

Number of radial bins. If n_segments is given without n_radial, a single radial bin is used (1D profile).

thresholdfloat, optional

QuickBundles threshold used to estimate the atlas centroid.

use_robust_centroidbool, optional

If True, use an extended centroid that covers the bundle endpoints.

robust_method{“linear”, “spline”}, optional

Endpoint extension method used by compute_robust_centroid.

Attributes:
centroidndarray, shape (n_segments, 3)

Atlas centroid.

radial_vectorsndarray, shape (n_segments, 3)

Radial direction at each along-tract segment.

radial_edgesndarray, shape (n_radial + 1,)

Radial-bin boundaries.

n_segmentsint

Number of along-tract segments.

n_radialint

Number of radial bins.

segment_length_actualfloat

Mean spacing between neighboring centroid points.

radial_length_actualfloat

Mean radial-bin width.

Methods

assign(bundle, **kwargs)

Assign bundle points to the grid.

profile(bundle, orig_bundle, metric, affine, ...)

Create a two-dimensional SPECTRA profile of a subject bundle.

References

assign(bundle, **kwargs)[source]#

Assign bundle points to the grid.

Parameters:
bundleStreamlines

Subject bundle in the same space as the atlas bundle.

**kwargsdict, optional

Sparse-cell masking options passed to parameterize_bundle (mask_threshold, min_count, max_count).

Returns:
s_index, r_index, s_distance, valid_mask, counts

See parameterize_bundle.

profile(bundle, orig_bundle, metric, affine, **kwargs)[source]#

Create a two-dimensional SPECTRA profile of a subject bundle.

Parameters:
bundleStreamlines

Subject bundle in the atlas space. Used for grid assignment.

orig_bundleStreamlines

Corresponding subject bundle in native/world space. Must correspond point-for-point to bundle.

metricndarray

3D scalar volume sampled along orig_bundle.

affinendarray, shape (4, 4)

Voxel-to-world affine of metric.

**kwargsdict, optional

Sparse-cell masking options passed to parameterize_bundle.

Returns:
profilendarray, shape (n_segments, n_radial)

Mean metric value in each grid cell.

peak_values#

dipy.stats.analysis.peak_values(bundle, peaks, dt, pname, bname, subject, group_id, ind, dir_name)[source]#
Peak_values function finds the generalized fractional anisotropy (gfa)

and quantitative anisotropy (qa) values from peaks object (eg: csa) for every point on a streamline used while tracking and saves it in hd5 file.

Parameters:
bundlestring

Name of bundle being analyzed

peakspeaks

contains peak directions and values

dtDataFrame

DataFrame to be populated

pnamestring

Name of the dti metric

bnamestring

Name of bundle being analyzed.

subjectstring

subject number as a string (e.g. 10001)

group_idinteger

which group subject belongs to 1 patient and 0 for control

indinteger list

ind tells which disk number a point belong.

dir_namestring

path of output directory

anatomical_measures#

dipy.stats.analysis.anatomical_measures(bundle, metric, dt, pname, bname, subject, group_id, ind, dir_name)[source]#
Calculates dti measure (eg: FA, MD) per point on streamlines and

save it in hd5 file.

Parameters:
bundlestring

Name of bundle being analyzed

metricmatrix of float values

dti metric e.g. FA, MD

dtDataFrame

DataFrame to be populated

pnamestring

Name of the dti metric

bnamestring

Name of bundle being analyzed.

subjectstring

subject number as a string (e.g. 10001)

group_idinteger

which group subject belongs to 1 for patient and 0 control

indinteger list

ind tells which disk number a point belong.

dir_namestring

path of output directory

assignment_map#

dipy.stats.analysis.assignment_map(target_bundle, model_bundle, no_disks)[source]#

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

See [2] for further details about the method.

Parameters:
target_bundleStreamlines

target bundle extracted from subject data in common space

model_bundleStreamlines

atlas bundle used as reference

no_disksinteger, optional

Number of disks used for dividing bundle into disks.

Returns:
distndarray

Distance of each target bundle point to its nearest model bundle centroid point.

indxndarray

Assignment map of the target bundle streamline point indices to the model bundle centroid points.

References

buan_profile#

dipy.stats.analysis.buan_profile(model_bundle, bundle, orig_bundle, metric, affine, *, no_disks=100)[source]#

Create BUAN weighted mean bundle profiles (lite).

See [2] and [3] for further details about the method.

Parameters:
model_bundleStreamlines

The atlas/template bundle used as the along-tract reference. Must be in the same space as bundle (common/MNI space).

bundleStreamlines

The subject bundle in common space (e.g., MNI). Used for segment assignment against the model centroids.

orig_bundleStreamlines

The same subject bundle in native/world (RAS) space. Used for sampling the metric volume. Must correspond point-for-point to bundle.

metricndarray

3-D scalar volume (e.g., FA) in the same voxel space as affine.

affinendarray

Voxel-to-world affine of the metric volume (as returned by nib.load(...).affine). Used to convert orig_bundle from world to voxel coordinates for metric interpolation.

no_disksint, optional

Number of alongtract segments/disks used for dividing bundle into segments.

Returns:
bundle_profilendarray, shape (no_disks,)

Inverse-distance-weighted mean metric value for each disk segment. Disks with no valid data points are set to NaN.

References

get_centroid#

dipy.stats.analysis.get_centroid(bundle, *, n_points=50, threshold=100.0)[source]#

Compute a representative QuickBundles centroid for a bundle.

Parameters:
bundleStreamlines

Input streamline bundle.

n_pointsint, optional

Number of points used to resample streamlines before clustering.

thresholdfloat, optional

QuickBundles clustering threshold.

Returns:
centroidndarray, shape (n_points, 3)

Representative centroid streamline.

get_n_segment_by_length#

dipy.stats.analysis.get_n_segment_by_length(bundle, *, segment_length=5.0)[source]#

Estimate the number of along-tract segments from bundle length.

Parameters:
bundleStreamlines

Input streamline bundle.

segment_lengthfloat, optional

Desired segment length in millimeters.

Returns:
n_segmentsint

Number of along-tract segments.

compute_robust_centroid#

dipy.stats.analysis.compute_robust_centroid(bundle, *, segment_length=5.0, n_segments=None, threshold=100.0, extrapolate_prop=0.3, method='linear')[source]#

Compute a centroid that covers the full extent of a bundle.

Parameters:
bundleStreamlines

Atlas or model bundle.

segment_lengthfloat, optional

Desired along-tract segment length in millimeters.

n_segmentsint, optional

Number of along-tract segments. If provided, this takes precedence over segment_length.

thresholdfloat, optional

QuickBundles threshold used to estimate the initial centroid.

extrapolate_propfloat, optional

Maximum fraction of the centroid length used for endpoint extension.

method{“linear”, “spline”}, optional

Endpoint extension method.

Returns:
centroidndarray, shape (n_segments, 3)

Centroid sampled uniformly by arc length.

create_radial_bins#

dipy.stats.analysis.create_radial_bins(radial_distance, *, radial_length=5.0, n_radial=None, merge_threshold=0.2)[source]#

Create bins from signed radial distances.

Parameters:
radial_distancendarray, shape (n_points,)

Signed radial position of each atlas point.

radial_lengthfloat, optional

Desired radial-bin width in millimeters.

n_radialint, optional

Number of radial bins. If provided, automatic edge-bin merging is disabled.

merge_thresholdfloat, optional

Edge bins holding fewer points than merge_threshold times the median count of non-empty bins are merged into their neighbor.

Returns:
radial_indexndarray

Radial-bin index for each point.

n_radialint

Final number of radial bins.

radial_edgesndarray

Radial-bin boundaries.

get_grid_from_atlas#

dipy.stats.analysis.get_grid_from_atlas(atlas_bundle, *, segment_length=5.0, radial_length=5.0, n_segments=None, n_radial=None, threshold=100.0, use_robust_centroid=True, robust_method='linear')[source]#

Construct a SPECTRA grid from an atlas bundle.

Parameters:
atlas_bundleStreamlines

Atlas or template bundle used to define the SPECTRA grid.

segment_lengthfloat, optional

Desired along-tract segment length in millimeters.

radial_lengthfloat, optional

Desired radial-bin width in millimeters.

n_segmentsint, optional

Number of along-tract segments.

n_radialint, optional

Number of radial bins. If n_segments is given without n_radial, a single radial bin is used (1D profile).

thresholdfloat, optional

QuickBundles threshold used to estimate the atlas centroid.

use_robust_centroidbool, optional

If True, use an extended centroid that covers the bundle endpoints.

robust_method{“linear”, “spline”}, optional

Endpoint extension method used by compute_robust_centroid.

Returns:
s_indexndarray

Along-tract assignment for each atlas point.

r_indexndarray

Radial assignment for each atlas point.

centroidndarray

Atlas centroid.

radial_vectorsndarray

Radial direction at each along-tract segment.

radial_edgesndarray

Radial-bin boundaries.

segment_length_actualfloat

Mean spacing between neighboring centroid points.

radial_length_actualfloat

Mean radial-bin width.

parameterize_bundle#

dipy.stats.analysis.parameterize_bundle(bundle, centroid, radial_vectors, radial_edges, *, mask_threshold=0.2, min_count=50, max_count=200)[source]#

Map a bundle onto a SPECTRA grid.

Parameters:
bundleStreamlines

Subject bundle in the same space as the atlas bundle.

centroidndarray, shape (n_segments, 3)

Atlas centroid.

radial_vectorsndarray, shape (n_segments, 3)

Atlas radial directions.

radial_edgesndarray

Atlas radial-bin boundaries.

mask_thresholdfloat, optional

Fraction of the median non-empty cell count below which a cell is considered sparse.

min_countint, optional

Lower bound of the sparse-cell count cutoff.

max_countint, optional

Upper bound of the sparse-cell count cutoff.

Returns:
s_indexndarray

Along-tract assignment for each bundle point.

r_indexndarray

Radial assignment for each bundle point.

s_distancendarray

Distance from each bundle point to the nearest centroid point.

valid_maskndarray

Boolean mask identifying points retained for profiling.

countsndarray

Number of points in each SPECTRA grid cell.

spectra_assignment_map#

dipy.stats.analysis.spectra_assignment_map(target_bundle, model_bundle, *, segment_length=5.0, radial_length=5.0, n_segments=None, n_radial=None, threshold=100.0, use_robust_centroid=True, robust_method='linear')[source]#

Assign bundle points to an atlas-defined SPECTRA grid.

See [1] for further details about the method.

Parameters:
target_bundleStreamlines

Subject bundle in common space.

model_bundleStreamlines

Atlas bundle used to define the SPECTRA grid.

segment_lengthfloat, optional

Desired along-tract segment length in millimeters.

radial_lengthfloat, optional

Desired radial-bin width in millimeters.

n_segmentsint, optional

Number of along-tract segments.

n_radialint, optional

Number of radial bins.

thresholdfloat, optional

QuickBundles threshold used to estimate the atlas centroid.

use_robust_centroidbool, optional

If True, use an extended centroid that covers the bundle endpoints.

robust_method{“linear”, “spline”}, optional

Endpoint extension method used by compute_robust_centroid.

Returns:
s_indexndarray

Along-tract assignment for each target-bundle point.

r_indexndarray

Radial assignment for each target-bundle point.

s_distancendarray

Distance from each target-bundle point to the nearest centroid point.

valid_maskndarray

Boolean mask identifying points retained for profiling.

countsndarray

Number of points in each SPECTRA grid cell.

References

grid_profile#

dipy.stats.analysis.grid_profile(orig_bundle, s_index, r_index, valid_mask, n_segments, n_radial, metric, affine)[source]#

Compute mean metric values within a SPECTRA grid.

Parameters:
orig_bundleStreamlines

Subject bundle in the metric volume’s world space.

s_indexndarray

Along-tract assignment for each bundle point.

r_indexndarray

Radial assignment for each bundle point.

valid_maskndarray

Boolean mask identifying points retained for profiling.

n_segmentsint

Number of along-tract segments.

n_radialint

Number of radial bins.

metricndarray

3D scalar volume sampled along the bundle.

affinendarray, shape (4, 4)

Voxel-to-world affine of metric.

Returns:
profilendarray, shape (n_segments, n_radial)

Mean metric value in each SPECTRA grid cell.

spectra_profile#

dipy.stats.analysis.spectra_profile(model_bundle, bundle, orig_bundle, metric, affine, *, segment_length=5.0, radial_length=5.0, n_segments=None, n_radial=None, threshold=100.0, use_robust_centroid=True, robust_method='linear')[source]#

Create a two-dimensional SPECTRA bundle profile.

See [1] for further details about the method.

Parameters:
model_bundleStreamlines

Atlas bundle used to define the SPECTRA grid. Must be in the same space as bundle.

bundleStreamlines

Subject bundle in common space. Used for SPECTRA grid assignment.

orig_bundleStreamlines

Corresponding subject bundle in native/world space. Must correspond point-for-point to bundle.

metricndarray

3D scalar volume sampled along orig_bundle.

affinendarray, shape (4, 4)

Voxel-to-world affine of metric.

segment_lengthfloat, optional

Desired along-tract segment length in millimeters.

radial_lengthfloat, optional

Desired radial-bin width in millimeters.

n_segmentsint, optional

Number of along-tract segments.

n_radialint, optional

Number of radial bins.

thresholdfloat, optional

QuickBundles threshold used to estimate the atlas centroid.

use_robust_centroidbool, optional

If True, use an extended centroid that covers the bundle endpoints.

robust_method{“linear”, “spline”}, optional

Endpoint extension method used by compute_robust_centroid.

Returns:
profilendarray

Two-dimensional bundle profile with shape (n_segments, n_radial).

References

gaussian_weights#

dipy.stats.analysis.gaussian_weights(bundle, *, n_points=100, return_mahalnobis=False, stat=<function mean>)[source]#

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

Parameters:
bundleStreamlines

The streamlines to weight.

n_pointsint, optional

The number of points to resample to. If the `bundle` is an array, this input is ignored.

return_mahalanobisbool, optional

Whether to return the Mahalanobis distance instead of the weights.

statcallable, optional.

The statistic used to calculate the central tendency of streamlines in each node. Can be one of {np.mean, np.median} or other functions that have similar API.`

Returns:
warray of shape (n_streamlines, n_points)

Weights for each node in each streamline, calculated as its relative inverse of the Mahalanobis distance, relative to the distribution of coordinates at that node position across streamlines.

afq_profile#

dipy.stats.analysis.afq_profile(data, bundle, affine, *, n_points=100, profile_stat=<function average>, orient_by=None, weights=None, **weights_kwarg)[source]#

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

Follows the approach outlined in [4].

Parameters:
data3D volume

The statistic to sample with the streamlines.

bundleStreamLines class instance
The collection of streamlines (possibly already resampled into an array

for each to have the same length) with which we are resampling. See Note below about orienting the streamlines.

affinearray_like (4, 4)

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

n_points: int, optional

The number of points to sample along the bundle. Default: 100.

orient_by: streamline, optional

A streamline to use as a standard to orient all of the streamlines in the bundle according to.

weights1D array or 2D array or callable, optional

Weight each streamline (1D) or each node (2D) when calculating the tract-profiles. Must sum to 1 across streamlines (in each node if relevant). If callable, this is a function that calculates weights. When using gaussian_weights directly, its node count matches n_points. Other callables receive the bundle and weights_kwarg.

profile_statcallable, optional

The statistic used to average the profile across streamlines. If weights is not None, this must take weights as a keyword argument. The default, np.average, is the same as np.mean but takes weights as a keyword argument.

weights_kwargkey-word arguments

Additional key-word arguments to pass to the weight-calculating function. Only to be used if weights is a callable.

Returns:
ndarraya 1D array with the profile of data along the length of

bundle

Notes

Before providing a bundle as input to this function, you will need to make sure that the streamlines in the bundle are all oriented in the same orientation relative to the bundle (use orient_by_streamline()).

References

find_qspace_neighbors#

dipy.stats.qc.find_qspace_neighbors(gtab)[source]#

Create a mapping of dwi volume index to its nearest neighbor.

An approximate q-space is used (the deltas are not included). Note that neighborhood is not necessarily bijective. One neighbor is found per dwi volume.

Parameters:
gtab: dipy.core.gradients.GradientTable

Gradient table.

Returns:
neighbors: list of tuple

A list of 2-tuples indicating the nearest q-space neighbor of each dwi volume.

Examples

>>> from dipy.core.gradients import gradient_table
>>> import numpy as np
>>> gtab = gradient_table(
...     np.array([0, 1000, 1000, 2000]),
...     bvecs=np.array([
...         [1, 0, 0],
...         [1, 0, 0],
...         [0.99, 0.0001, 0.0001],
...         [1, 0, 0]]))
>>> find_qspace_neighbors(gtab)
[(1, 2), (2, 1), (3, 1)]

neighboring_dwi_correlation#

dipy.stats.qc.neighboring_dwi_correlation(dwi_data, gtab, *, mask=None)[source]#

Calculate the Neighboring DWI Correlation (NDC) from dMRI data.

Using a mask is highly recommended, otherwise the FOV will influence the correlations. According to Yeh et al.[5], an NDC less than 0.4 indicates a low quality image.

Parameters:
dwi_data4D ndarray

dwi data on which to calculate NDC

gtabdipy.core.gradients.GradientTable

Gradient table.

mask3D ndarray, optional

Mask of voxels to include in the NDC calculation

Returns:
ndcfloat

The neighboring DWI correlation

References

count_sketch#

dipy.stats.sketching.count_sketch(matrixa_name, matrixa_dtype, matrixa_shape, sketch_rows, tmp_dir)[source]#

Count Sketching algorithm to reduce the size of the matrix.

Parameters:
matrixa_namestr

The name of the memmap file containing the matrix A.

matrixa_dtypedtype

The dtype of the matrix A.

matrixa_shapetuple

The shape of the matrix A.

sketch_rowsint

The number of rows in the sketch matrix.

tmp_dirstr

The directory to save the temporary files.

Returns:
matrixc_file.namestr

The name of the memmap file containing the sketch matrix.

matrixc.dtypedtype

The dtype of the sketch matrix.

matrixc.shapetuple

The shape of the sketch matrix.