segment

Module: segment.benchmarks

Module: segment.benchmarks.bench_quickbundles

Benchmarks for QuickBundles

Run all benchmarks with:

import dipy.segment as dipysegment
dipysegment.bench()

With Pytest, Run this benchmark with:

pytest -svv -c bench.ini /path/to/bench_quickbundles.py

MDFpy

Attributes:

Metric

Computes a distance between two sequential data.

QB_New

alias of QuickBundles

Streamlines

alias of ArraySequence

assert_array_equal(x, y[, err_msg, verbose, ...])

Raises an AssertionError if two array_like objects are not equal.

assert_arrays_equal(arrays1, arrays2)

assert_equal(actual, desired[, err_msg, verbose])

Raises an AssertionError if two objects are not equal.

bench_quickbundles()

get_fnames([name])

Provide full paths to example or test datasets.

load_tractogram(filename, reference[, ...])

Load the stateful tractogram from any format (trk/tck/vtk/vtp/fib/dpy)

measure(code_str[, times, label])

Return elapsed time for executing code in the namespace of the caller.

set_number_of_points

Change the number of points of streamlines

Module: segment.bundles

BundleMinDistanceAsymmetricMetric([num_threads])

Asymmetric Bundle-based Minimum distance.

BundleMinDistanceMetric([num_threads])

Bundle-based Minimum Distance aka BMD

BundleSumDistanceMatrixMetric([num_threads])

Bundle-based Sum Distance aka BMD

RecoBundles(streamlines[, greater_than, ...])

Methods

StreamlineLinearRegistration([metric, x0, ...])

Methods

Streamlines

alias of ArraySequence

chain

chain(*iterables) --> chain object

apply_affine(aff, pts[, inplace])

Apply affine matrix aff to points pts

ba_analysis(recognized_bundle, expert_bundle)

Calculates bundle adjacency score between two given bundles

bundle_adjacency(dtracks0, dtracks1, threshold)

Find bundle adjacency between two given tracks/bundles

bundle_shape_similarity(bundle1, bundle2, rng)

Calculates bundle shape similarity between two given bundles using bundle adjacency (BA) metric

bundles_distances_mam

Calculate distances between list of tracks A and list of tracks B

bundles_distances_mdf

Calculate distances between list of tracks A and list of tracks B

check_range(streamline, gt, lt)

cluster_bundle(bundle, clust_thr, rng[, ...])

Clusters bundles

deprecated_params(old_name[, new_name, ...])

Deprecate a renamed or removed function argument.

length

Euclidean length of streamlines

nbytes(streamlines)

qbx_and_merge(streamlines, thresholds[, ...])

Run QuickBundlesX and then run again on the centroids of the last layer

select_random_set_of_streamlines(...[, rng])

Select a random set of streamlines

set_number_of_points

Change the number of points of streamlines

time()

Return the current time in seconds since the Epoch.

Module: segment.clustering

ABCMeta(name, bases, namespace, **kwargs)

Metaclass for defining Abstract Base Classes (ABCs).

AveragePointwiseEuclideanMetric

Computes the average of pointwise Euclidean distances between two sequential data.

Cluster([id, indices, refdata])

Provides functionalities for interacting with a cluster.

ClusterCentroid(centroid[, id, indices, refdata])

Provides functionalities for interacting with a cluster.

ClusterMap([refdata])

Provides functionalities for interacting with clustering outputs.

ClusterMapCentroid([refdata])

Provides functionalities for interacting with clustering outputs that have centroids.

Clustering()

Methods

Identity()

Provides identity indexing functionality.

Metric

Computes a distance between two sequential data.

MinimumAverageDirectFlipMetric

Computes the MDF distance (minimum average direct-flip) between two sequential data.

QuickBundles(threshold[, metric, ...])

Clusters streamlines using QuickBundles [Garyfallidis12].

QuickBundlesX(thresholds[, metric])

Clusters streamlines using QuickBundlesX.

ResampleFeature

Extracts features from a sequential datum.

TreeCluster(threshold, centroid[, indices])

Attributes:

TreeClusterMap(root)

Attributes:

abstractmethod(funcobj)

A decorator indicating abstract methods.

nbytes(streamlines)

qbx_and_merge(streamlines, thresholds[, ...])

Run QuickBundlesX and then run again on the centroids of the last layer

set_number_of_points

Change the number of points of streamlines

time()

Return the current time in seconds since the Epoch.

Module: segment.clustering_algorithms

ClusterCentroid(centroid[, id, indices, refdata])

Provides functionalities for interacting with a cluster.

ClusterMapCentroid([refdata])

Provides functionalities for interacting with clustering outputs that have centroids.

DTYPE

alias of float32

clusters_centroid2clustermap_centroid

Converts a ClustersCentroid object (Cython) to a ClusterMapCentroid object (Python).

peek

Returns the first element of an iterable and the iterator.

quickbundles

Clusters streamlines using QuickBundles.

quickbundlesx

Clusters streamlines using QuickBundlesX.

Module: segment.clusteringspeed

ClusterCentroid(centroid[, id, indices, refdata])

Provides functionalities for interacting with a cluster.

ClusterMapCentroid([refdata])

Provides functionalities for interacting with clustering outputs that have centroids.

Clusters

Provides Cython functionalities to interact with clustering outputs.

ClustersCentroid

Provides Cython functionalities to interact with clustering outputs having the notion of cluster's centroid.

DTYPE

alias of float32

QuickBundles

Methods

QuickBundlesX

Methods

TreeCluster(threshold, centroid[, indices])

Attributes:

TreeClusterMap(root)

Attributes:

evaluate_aabb_checks

Module: segment.cythonutils

Module: segment.featurespeed

ArcLengthFeature

Extracts features from a sequential datum.

CenterOfMassFeature

Extracts features from a sequential datum.

CythonFeature

Extracts features from a sequential datum.

Feature

Extracts features from a sequential datum.

IdentityFeature

Extracts features from a sequential datum.

MidpointFeature

Extracts features from a sequential datum.

ResampleFeature

Extracts features from a sequential datum.

VectorOfEndpointsFeature

Extracts features from a sequential datum.

extract

Extracts features from data.

infer_shape

Infers shape of the features extracted from data.

Module: segment.mask

applymask(vol, mask)

Mask vol with mask.

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.

clean_cc_mask(mask)

Cleans a segmentation of the corpus callosum so no random pixels are included.

color_fa(fa, evecs)

Color fractional anisotropy of diffusion tensor

crop(vol, mins, maxs)

Crops the input volume.

fractional_anisotropy(evals[, axis])

Return Fractional anisotropy (FA) of a diffusion tensor.

generate_binary_structure(rank, connectivity)

Generate a binary structure for binary morphological operations.

median_filter(input[, size, footprint, ...])

Calculate a multidimensional median filter.

median_otsu(input_volume[, vol_idx, ...])

Simple brain extraction tool method for images from DWI data.

multi_median(data, median_radius, numpass)

Applies median filter multiple times on input data.

otsu([image, nbins, hist])

Return threshold value based on Otsu's method.

segment_from_cfa(tensor_fit, roi, threshold)

Segment the cfa inside roi using the values from threshold as bounds.

warn(/, message[, category, stacklevel, source])

Issue a warning, or maybe ignore it or raise an exception.

Module: segment.metric

AveragePointwiseEuclideanMetric

Computes the average of pointwise Euclidean distances between two sequential data.

CosineMetric

Computes the cosine distance between two vectors.

EuclideanMetric

alias of SumPointwiseEuclideanMetric

Metric

Computes a distance between two sequential data.

MinimumAverageDirectFlipMetric

Computes the MDF distance (minimum average direct-flip) between two sequential data.

SumPointwiseEuclideanMetric

Computes the sum of pointwise Euclidean distances between two sequential data.

dist

Computes a distance between datum1 and datum2.

mdf(s1, s2)

Computes the MDF (Minimum average Direct-Flip) distance [Garyfallidis12] between two streamlines.

Module: segment.metricspeed

AveragePointwiseEuclideanMetric

Computes the average of pointwise Euclidean distances between two sequential data.

CosineMetric

Computes the cosine distance between two vectors.

CythonMetric

Computes a distance between two sequential data.

Metric

Computes a distance between two sequential data.

MinimumAverageDirectFlipMetric

Computes the MDF distance (minimum average direct-flip) between two sequential data.

SumPointwiseEuclideanMetric

Computes the sum of pointwise Euclidean distances between two sequential data.

dist

Computes a distance between datum1 and datum2.

distance_matrix

Computes the distance matrix between two lists of sequential data.

Module: segment.mrf

ConstantObservationModel()

Observation model assuming that the intensity of each class is constant.

IteratedConditionalModes()

Methods

Module: segment.threshold

otsu(image[, nbins])

Return threshold value based on Otsu's method.

upper_bound_by_percent(data[, percent])

Find the upper bound for visualization of medical images

upper_bound_by_rate(data[, rate])

Adjusts upper intensity boundary using rates

Module: segment.tissue

ConstantObservationModel()

Observation model assuming that the intensity of each class is constant.

IteratedConditionalModes()

Methods

TissueClassifierHMRF([save_history, verbose])

This class contains the methods for tissue classification using the Markov Random Fields modeling approach

add_noise(signal, snr, S0[, noise_type])

Add noise of specified distribution to the signal from a single voxel.

MDFpy

class dipy.segment.benchmarks.bench_quickbundles.MDFpy

Bases: Metric

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible(shape1, shape2)

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

dist(features1, features2)

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
are_compatible(shape1, shape2)

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

Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).

Parameters:
shape1int, 1-tuple or 2-tuple

shape of the first data point’s features

shape2int, 1-tuple or 2-tuple

shape of the second data point’s features

Returns:
are_compatiblebool

whether or not shapes are compatible

dist(features1, features2)

Computes a distance between two data points based on their features.

Parameters:
features12D array

Features of the first data point.

features22D array

Features of the second data point.

Returns:
double

Distance between two data points.

Metric

class dipy.segment.benchmarks.bench_quickbundles.Metric

Bases: object

Computes a distance between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

When subclassing Metric, one only needs to override the dist and are_compatible methods.

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
are_compatible()

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

Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).

Parameters:
shape1int, 1-tuple or 2-tuple

shape of the first data point’s features

shape2int, 1-tuple or 2-tuple

shape of the second data point’s features

Returns:
are_compatiblebool

whether or not shapes are compatible

dist()

Computes a distance between two data points based on their features.

Parameters:
features12D array

Features of the first data point.

features22D array

Features of the second data point.

Returns:
double

Distance between two data points.

feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

QB_New

dipy.segment.benchmarks.bench_quickbundles.QB_New

alias of QuickBundles

Streamlines

dipy.segment.benchmarks.bench_quickbundles.Streamlines

alias of ArraySequence

assert_array_equal

dipy.segment.benchmarks.bench_quickbundles.assert_array_equal(x, y, err_msg='', verbose=True, *, strict=False)

Raises an AssertionError if two array_like objects are not equal.

Given two array_like objects, check that the shape is equal and all elements of these objects are equal (but see the Notes for the special handling of a scalar). An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.

The usual caution for verifying equality with floating point numbers is advised.

Parameters:
xarray_like

The actual object to check.

yarray_like

The desired, expected object.

err_msgstr, optional

The error message to be printed in case of failure.

verbosebool, optional

If True, the conflicting values are appended to the error message.

strictbool, optional

If True, raise an AssertionError when either the shape or the data type of the array_like objects does not match. The special handling for scalars mentioned in the Notes section is disabled.

Raises:
AssertionError

If actual and desired objects are not equal.

See also

assert_allclose

Compare two array_like objects for equality with desired relative and/or absolute precision.

assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

Notes

When one of x and y is a scalar and the other is array_like, the function checks that each element of the array_like object is equal to the scalar. This behaviour can be disabled with the strict parameter.

Examples

The first assert does not raise an exception:

>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
...                               [np.exp(0),2.33333, np.nan])

Assert fails with numerical imprecision with floats:

>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
...                               [1, np.sqrt(np.pi)**2, np.nan])
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not equal

Mismatched elements: 1 / 3 (33.3%)
Max absolute difference: 4.4408921e-16
Max relative difference: 1.41357986e-16
 x: array([1.      , 3.141593,      nan])
 y: array([1.      , 3.141593,      nan])

Use assert_allclose or one of the nulp (number of floating point values) functions for these cases instead:

>>> np.testing.assert_allclose([1.0,np.pi,np.nan],
...                            [1, np.sqrt(np.pi)**2, np.nan],
...                            rtol=1e-10, atol=0)

As mentioned in the Notes section, assert_array_equal has special handling for scalars. Here the test checks that each value in x is 3:

>>> x = np.full((2, 5), fill_value=3)
>>> np.testing.assert_array_equal(x, 3)

Use strict to raise an AssertionError when comparing a scalar with an array:

>>> np.testing.assert_array_equal(x, 3, strict=True)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not equal

(shapes (2, 5), () mismatch)
 x: array([[3, 3, 3, 3, 3],
       [3, 3, 3, 3, 3]])
 y: array(3)

The strict parameter also ensures that the array data types match:

>>> x = np.array([2, 2, 2])
>>> y = np.array([2., 2., 2.], dtype=np.float32)
>>> np.testing.assert_array_equal(x, y, strict=True)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not equal

(dtypes int64, float32 mismatch)
 x: array([2, 2, 2])
 y: array([2., 2., 2.], dtype=float32)

assert_arrays_equal

dipy.segment.benchmarks.bench_quickbundles.assert_arrays_equal(arrays1, arrays2)

assert_equal

dipy.segment.benchmarks.bench_quickbundles.assert_equal(actual, desired, err_msg='', verbose=True)

Raises an AssertionError if two objects are not equal.

Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), check that all elements of these objects are equal. An exception is raised at the first conflicting values.

When one of actual and desired is a scalar and the other is array_like, the function checks that each element of the array_like object is equal to the scalar.

This function handles NaN comparisons as if NaN was a “normal” number. That is, AssertionError is not raised if both objects have NaNs in the same positions. This is in contrast to the IEEE standard on NaNs, which says that NaN compared to anything must return False.

Parameters:
actualarray_like

The object to check.

desiredarray_like

The expected object.

err_msgstr, optional

The error message to be printed in case of failure.

verbosebool, optional

If True, the conflicting values are appended to the error message.

Raises:
AssertionError

If actual and desired are not equal.

Examples

>>> np.testing.assert_equal([4,5], [4,6])
Traceback (most recent call last):
    ...
AssertionError:
Items are not equal:
item=1
 ACTUAL: 5
 DESIRED: 6

The following comparison does not raise an exception. There are NaNs in the inputs, but they are in the same positions.

>>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])

bench_quickbundles

dipy.segment.benchmarks.bench_quickbundles.bench_quickbundles()

get_fnames

dipy.segment.benchmarks.bench_quickbundles.get_fnames(name='small_64D')

Provide full paths to example or test datasets.

Parameters:
namestr

the filename/s of which dataset to return, one of:

  • ‘small_64D’ small region of interest nifti,bvecs,bvals 64 directions

  • ‘small_101D’ small region of interest nifti, bvecs, bvals 101 directions

  • ‘aniso_vox’ volume with anisotropic voxel size as Nifti

  • ‘fornix’ 300 tracks in Trackvis format (from Pittsburgh Brain Competition)

  • ‘gqi_vectors’ the scanner wave vectors needed for a GQI acquisitions of 101 directions tested on Siemens 3T Trio

  • ‘small_25’ small ROI (10x8x2) DTI data (b value 2000, 25 directions)

  • ‘test_piesno’ slice of N=8, K=14 diffusion data

  • ‘reg_c’ small 2D image used for validating registration

  • ‘reg_o’ small 2D image used for validation registration

  • ‘cb_2’ two vectorized cingulum bundles

Returns:
fnamestuple

filenames for dataset

Examples

>>> import numpy as np
>>> from dipy.io.image import load_nifti
>>> from dipy.data import get_fnames
>>> fimg, fbvals, fbvecs = get_fnames('small_101D')
>>> bvals=np.loadtxt(fbvals)
>>> bvecs=np.loadtxt(fbvecs).T
>>> data, affine = load_nifti(fimg)
>>> data.shape == (6, 10, 10, 102)
True
>>> bvals.shape == (102,)
True
>>> bvecs.shape == (102, 3)
True

load_tractogram

dipy.segment.benchmarks.bench_quickbundles.load_tractogram(filename, reference, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True)

Load the stateful tractogram from any format (trk/tck/vtk/vtp/fib/dpy)

Parameters:
filenamestring

Filename with valid extension

referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or

trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation

to_spaceEnum (dipy.io.stateful_tractogram.Space)

Space to which the streamlines will be transformed after loading

to_originEnum (dipy.io.stateful_tractogram.Origin)
Origin to which the streamlines will be transformed after loading

NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)

bbox_valid_checkbool

Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.

trk_header_checkbool

Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded

Returns:
outputStatefulTractogram

The tractogram to load (must have been saved properly)

measure

dipy.segment.benchmarks.bench_quickbundles.measure(code_str, times=1, label=None)

Return elapsed time for executing code in the namespace of the caller.

The supplied code string is compiled with the Python builtin compile. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy.

Parameters:
code_strstr

The code to be timed.

timesint, optional

The number of times the code is executed. Default is 1. The code is only compiled once.

labelstr, optional

A label to identify code_str with. This is passed into compile as the second argument (for run-time error messages).

Returns:
elapsedfloat

Total elapsed time in seconds for executing code_str times times.

Examples

>>> times = 10
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
>>> print("Time for a single execution : ", etime / times, "s")  
Time for a single execution :  0.005 s

set_number_of_points

dipy.segment.benchmarks.bench_quickbundles.set_number_of_points()
Change the number of points of streamlines

(either by downsampling or upsampling)

Change the number of points of streamlines in order to obtain nb_points-1 segments of equal length. Points of streamlines will be modified along the curve.

Parameters:
streamlinesndarray or a list or dipy.tracking.Streamlines

If ndarray, must have shape (N,3) where N is the number of points of the streamline. If list, each item must be ndarray shape (Ni,3) where Ni is the number of points of streamline i. If dipy.tracking.Streamlines, its common_shape must be 3.

nb_pointsint

integer representing number of points wanted along the curve.

Returns:
new_streamlinesndarray or a list or dipy.tracking.Streamlines

Results of the downsampling or upsampling process.

Examples

>>> from dipy.tracking.streamline import set_number_of_points
>>> import numpy as np

One streamline, a semi-circle:

>>> theta = np.pi*np.linspace(0, 1, 100)
>>> x = np.cos(theta)
>>> y = np.sin(theta)
>>> z = 0 * x
>>> streamline = np.vstack((x, y, z)).T
>>> modified_streamline = set_number_of_points(streamline, 3)
>>> len(modified_streamline)
3

Multiple streamlines:

>>> streamlines = [streamline, streamline[::2]]
>>> new_streamlines = set_number_of_points(streamlines, 10)
>>> [len(s) for s in streamlines]
[100, 50]
>>> [len(s) for s in new_streamlines]
[10, 10]

BundleMinDistanceAsymmetricMetric

class dipy.segment.bundles.BundleMinDistanceAsymmetricMetric(num_threads=None)

Bases: BundleMinDistanceMetric

Asymmetric Bundle-based Minimum distance.

This is a cost function that can be used by the StreamlineLinearRegistration class.

Methods

distance(xopt)

Distance calculated from this Metric.

setup(static, moving)

Setup static and moving sets of streamlines.

__init__(num_threads=None)

An abstract class for the metric used for streamline registration.

If the two sets of streamlines match exactly then method distance of this object should be minimum.

Parameters:
num_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.

distance(xopt)

Distance calculated from this Metric.

Parameters:
xoptsequence

List of affine parameters as an 1D vector

BundleMinDistanceMetric

class dipy.segment.bundles.BundleMinDistanceMetric(num_threads=None)

Bases: StreamlineDistanceMetric

Bundle-based Minimum Distance aka BMD

This is the cost function used by the StreamlineLinearRegistration.

References

[Garyfallidis14]

Garyfallidis et al., “Direct native-space fiber bundle alignment for group comparisons”, ISMRM, 2014.

Methods

setup(static, moving)

distance(xopt)

__init__(num_threads=None)

An abstract class for the metric used for streamline registration.

If the two sets of streamlines match exactly then method distance of this object should be minimum.

Parameters:
num_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.

distance(xopt)

Distance calculated from this Metric.

Parameters:
xoptsequence

List of affine parameters as an 1D vector,

setup(static, moving)

Setup static and moving sets of streamlines.

Parameters:
staticstreamlines

Fixed or reference set of streamlines.

movingstreamlines

Moving streamlines.

Notes

Call this after the object is initiated and before distance.

BundleSumDistanceMatrixMetric

class dipy.segment.bundles.BundleSumDistanceMatrixMetric(num_threads=None)

Bases: BundleMinDistanceMatrixMetric

Bundle-based Sum Distance aka BMD

This is a cost function that can be used by the StreamlineLinearRegistration class.

Notes

The difference with BundleMinDistanceMatrixMetric is that it uses uses the sum of the distance matrix and not the sum of mins.

Methods

setup(static, moving)

distance(xopt)

__init__(num_threads=None)

An abstract class for the metric used for streamline registration.

If the two sets of streamlines match exactly then method distance of this object should be minimum.

Parameters:
num_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.

distance(xopt)

Distance calculated from this Metric

Parameters:
xoptsequence

List of affine parameters as an 1D vector

RecoBundles

class dipy.segment.bundles.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:
  1. 6

    x0 = np.array([0, 0, 0, 0, 0, 0])

  2. 7

    x0 = np.array([0, 0, 0, 0, 0, 0, 1.])

  3. 12

    x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])

If str:
  1. “rigid”

    x0 = np.array([0, 0, 0, 0, 0, 0])

  2. “similarity”

    x0 = np.array([0, 0, 0, 0, 0, 0, 1.])

  3. “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:
  1. 6

    x0 = np.array([0, 0, 0, 0, 0, 0])

  2. 7

    x0 = np.array([0, 0, 0, 0, 0, 0, 1.])

  3. 12

    x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])

If str:
  1. “rigid”

    x0 = np.array([0, 0, 0, 0, 0, 0])

  2. “similarity”

    x0 = np.array([0, 0, 0, 0, 0, 0, 1.])

  3. “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)

StreamlineLinearRegistration

class dipy.segment.bundles.StreamlineLinearRegistration(metric=None, x0='rigid', method='L-BFGS-B', bounds=None, verbose=False, options=None, evolution=False, num_threads=None)

Bases: object

Methods

optimize(static, moving[, mat])

Find the minimum of the provided metric.

__init__(metric=None, x0='rigid', method='L-BFGS-B', bounds=None, verbose=False, options=None, evolution=False, num_threads=None)

Linear registration of 2 sets of streamlines [Garyfallidis15].

Parameters:
metricStreamlineDistanceMetric,

If None and fast is False then the BMD distance is used. If fast is True then a faster implementation of BMD is used. Otherwise, use the given distance metric.

x0array or int or str

Initial parametrization for the optimization.

If 1D array with:

a) 6 elements then only rigid registration is performed with the 3 first elements for translation and 3 for rotation. b) 7 elements also isotropic scaling is performed (similarity). c) 12 elements then translation, rotation (in degrees), scaling and shearing is performed (affine).

Here is an example of x0 with 12 elements: x0=np.array([0, 10, 0, 40, 0, 0, 2., 1.5, 1, 0.1, -0.5, 0])

This has translation (0, 10, 0), rotation (40, 0, 0) in degrees, scaling (2., 1.5, 1) and shearing (0.1, -0.5, 0).

If int:
  1. 6

    x0 = np.array([0, 0, 0, 0, 0, 0])

  2. 7

    x0 = np.array([0, 0, 0, 0, 0, 0, 1.])

  3. 12

    x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])

If str:
  1. “rigid”

    x0 = np.array([0, 0, 0, 0, 0, 0])

  2. “similarity”

    x0 = np.array([0, 0, 0, 0, 0, 0, 1.])

  3. “affine”

    x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])

methodstr,

‘L_BFGS_B’ or ‘Powell’ optimizers can be used. Default is ‘L_BFGS_B’.

boundslist of tuples or None,

If method == ‘L_BFGS_B’ then we can use bounded optimization. For example for the six parameters of rigid rotation we can set the bounds = [(-30, 30), (-30, 30), (-30, 30),

(-45, 45), (-45, 45), (-45, 45)]

That means that we have set the bounds for the three translations and three rotation axes (in degrees).

verbosebool, optional.

If True, if True then information about the optimization is shown. Default: False.

optionsNone or dict,

Extra options to be used with the selected method.

evolutionboolean

If True save the transformation for each iteration of the optimizer. Default is False. Supported only with Scipy >= 0.11.

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.

References

[Garyfallidis15]

Garyfallidis et al. “Robust and efficient linear 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.

optimize(static, moving, mat=None)

Find the minimum of the provided metric.

Parameters:
staticstreamlines

Reference or fixed set of streamlines.

movingstreamlines

Moving set of streamlines.

matarray

Transformation (4, 4) matrix to start the registration. mat is applied to moving. Default value None which means that initial transformation will be generated by shifting the centers of moving and static sets of streamlines to the origin.

Returns:
mapStreamlineRegistrationMap

Streamlines

dipy.segment.bundles.Streamlines

alias of ArraySequence

chain

class dipy.segment.bundles.chain

Bases: object

chain(*iterables) –> chain object

Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted.

Methods

from_iterable(iterable, /)

Alternative chain() constructor taking a single iterable argument that evaluates lazily.

__init__(*args, **kwargs)
from_iterable(iterable, /)

Alternative chain() constructor taking a single iterable argument that evaluates lazily.

apply_affine

dipy.segment.bundles.apply_affine(aff, pts, inplace=False)

Apply affine matrix aff to points pts

Returns result of application of aff to the right of pts. The coordinate dimension of pts should be the last.

For the 3D case, aff will be shape (4,4) and pts will have final axis length 3 - maybe it will just be N by 3. The return value is the transformed points, in this case:

res = np.dot(aff[:3,:3], pts.T) + aff[:3,3:4]
transformed_pts = res.T

This routine is more general than 3D, in that aff can have any shape (N,N), and pts can have any shape, as long as the last dimension is for the coordinates, and is therefore length N-1.

Parameters:
aff(N, N) array-like

Homogeneous affine, for 3D points, will be 4 by 4. Contrary to first appearance, the affine will be applied on the left of pts.

pts(…, N-1) array-like

Points, where the last dimension contains the coordinates of each point. For 3D, the last dimension will be length 3.

inplacebool, optional

If True, attempt to apply the affine directly to pts. If False, or in-place application fails, a freshly allocated array will be returned.

Returns:
transformed_pts(…, N-1) array

transformed points

Examples

>>> aff = np.array([[0,2,0,10],[3,0,0,11],[0,0,4,12],[0,0,0,1]])
>>> pts = np.array([[1,2,3],[2,3,4],[4,5,6],[6,7,8]])
>>> apply_affine(aff, pts) 
array([[14, 14, 24],
       [16, 17, 28],
       [20, 23, 36],
       [24, 29, 44]]...)

Just to show that in the simple 3D case, it is equivalent to:

>>> (np.dot(aff[:3,:3], pts.T) + aff[:3,3:4]).T 
array([[14, 14, 24],
       [16, 17, 28],
       [20, 23, 36],
       [24, 29, 44]]...)

But pts can be a more complicated shape:

>>> pts = pts.reshape((2,2,3))
>>> apply_affine(aff, pts) 
array([[[14, 14, 24],
        [16, 17, 28]],

       [[20, 23, 36],
        [24, 29, 44]]]...)

ba_analysis

dipy.segment.bundles.ba_analysis(recognized_bundle, expert_bundle, nb_pts=20, threshold=6.0)

Calculates bundle adjacency score between two given bundles

Parameters:
recognized_bundleStreamlines

Extracted bundle from the whole brain tractogram (eg: AF_L)

expert_bundleStreamlines

Model bundle used as reference while extracting similar type bundle from inout tractogram

nb_ptsinteger (default 20)

Discretizing streamlines to have nb_pts number of points

thresholdfloat (default 6)

Threshold used for in computing bundle adjacency. Threshold controls how much strictness user wants while calculating bundle adjacency between two bundles. Smaller threshold means bundles should be strictly adjacent to get higher BA score.

Returns:
Bundle adjacency score between two tracts

References

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

bundle_adjacency

dipy.segment.bundles.bundle_adjacency(dtracks0, dtracks1, threshold)

Find bundle adjacency between two given tracks/bundles

Parameters:
dtracks0Streamlines

White matter tract from one subject

dtracks1Streamlines

White matter tract from another subject

thresholdfloat

Threshold controls how much strictness user wants while calculating bundle adjacency between two bundles. Smaller threshold means bundles should be strictly adjacent to get higher BA score.

Returns:
resFloat

Bundle adjacency score between two tracts

References

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

bundle_shape_similarity

dipy.segment.bundles.bundle_shape_similarity(bundle1, bundle2, rng, clust_thr=(5, 3, 1.5), threshold=6)

Calculates bundle shape similarity between two given bundles using bundle adjacency (BA) metric

Parameters:
bundle1Streamlines

White matter tract from one subject (eg: AF_L)

bundle2Streamlines

White matter tract from another subject (eg: AF_L)

rngRandomState
clust_thrarray-like, optional

list of clustering thresholds used in quickbundlesX

thresholdfloat, optional

Threshold used for in computing bundle adjacency. Threshold controls how much strictness user wants while calculating shape similarity between two bundles. Smaller threshold means bundles should be strictly similar to get higher shape similarity score.

Returns:
ba_valueFloat

Bundle similarity score between two tracts

References

[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)

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

bundles_distances_mam

dipy.segment.bundles.bundles_distances_mam()

Calculate distances between list of tracks A and list of tracks B

Parameters:
tracksAsequence

of tracks as arrays, shape (N1,3) .. (Nm,3)

tracksBsequence

of tracks as arrays, shape (N1,3) .. (Nm,3)

metricstr

‘avg’, ‘min’, ‘max’

Returns:
DMarray, shape (len(tracksA), len(tracksB))

distances between tracksA and tracksB according to metric

bundles_distances_mdf

dipy.segment.bundles.bundles_distances_mdf()

Calculate distances between list of tracks A and list of tracks B

All tracks need to have the same number of points

Parameters:
tracksAsequence

of tracks as arrays, [(N,3) .. (N,3)]

tracksBsequence

of tracks as arrays, [(N,3) .. (N,3)]

Returns:
DMarray, shape (len(tracksA), len(tracksB))

distances between tracksA and tracksB according to metric

check_range

dipy.segment.bundles.check_range(streamline, gt, lt)

cluster_bundle

dipy.segment.bundles.cluster_bundle(bundle, clust_thr, rng, nb_pts=20, select_randomly=500000)

Clusters bundles

Parameters:
bundleStreamlines

White matter tract

clust_thrfloat

clustering threshold used in quickbundlesX

rngRandomState
nb_pts: integer (default 20)

Discretizing streamlines to have nb_points number of points

select_randomly: integer (default 500000)

Randomly select streamlines from the input bundle

Returns:
centroidsStreamlines

clustered centroids of the input bundle

References

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

deprecated_params

dipy.segment.bundles.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)

length

dipy.segment.bundles.length()

Euclidean length of streamlines

Length is in mm only if streamlines are expressed in world coordinates.

Parameters:
streamlinesndarray or a list or dipy.tracking.Streamlines

If ndarray, must have shape (N,3) where N is the number of points of the streamline. If list, each item must be ndarray shape (Ni,3) where Ni is the number of points of streamline i. If dipy.tracking.Streamlines, its common_shape must be 3.

Returns:
lengthsscalar or ndarray shape (N,)

If there is only one streamline, a scalar representing the length of the streamline. If there are several streamlines, ndarray containing the length of every streamline.

Examples

>>> from dipy.tracking.streamline import length
>>> import numpy as np
>>> streamline = np.array([[1, 1, 1], [2, 3, 4], [0, 0, 0]])
>>> expected_length = np.sqrt([1+2**2+3**2, 2**2+3**2+4**2]).sum()
>>> length(streamline) == expected_length
True
>>> streamlines = [streamline, np.vstack([streamline, streamline[::-1]])]
>>> expected_lengths = [expected_length, 2*expected_length]
>>> lengths = [length(streamlines[0]), length(streamlines[1])]
>>> np.allclose(lengths, expected_lengths)
True
>>> length([])
0.0
>>> length(np.array([[1, 2, 3]]))
0.0

nbytes

dipy.segment.bundles.nbytes(streamlines)

qbx_and_merge

dipy.segment.bundles.qbx_and_merge(streamlines, thresholds, nb_pts=20, select_randomly=None, rng=None, verbose=False)

Run QuickBundlesX and then run again on the centroids of the last layer

Running again QuickBundles at a layer has the effect of merging some of the clusters that may be originally divided because of branching. This function help obtain a result at a QuickBundles quality but with QuickBundlesX speed. The merging phase has low cost because it is applied only on the centroids rather than the entire dataset.

Parameters:
streamlinesStreamlines
thresholdssequence

List of distance thresholds for QuickBundlesX.

nb_ptsint

Number of points for discretizing each streamline

select_randomlyint

Randomly select a specific number of streamlines. If None all the streamlines are used.

rngRandomState

If None then RandomState is initialized internally.

verbosebool, optional.

If True, log information. Default False.

Returns:
clustersobj

Contains the clusters of the last layer of QuickBundlesX after merging.

References

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

[Garyfallidis16]

Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016.

select_random_set_of_streamlines

dipy.segment.bundles.select_random_set_of_streamlines(streamlines, select, rng=None)

Select a random set of streamlines

Parameters:
streamlinesStreamlines

Object of 2D ndarrays of shape[-1]==3

selectint

Number of streamlines to select. If there are less streamlines than select then select=len(streamlines).

rngRandomState

Default None.

Returns:
selected_streamlineslist

Notes

The same streamline will not be selected twice.

set_number_of_points

dipy.segment.bundles.set_number_of_points()
Change the number of points of streamlines

(either by downsampling or upsampling)

Change the number of points of streamlines in order to obtain nb_points-1 segments of equal length. Points of streamlines will be modified along the curve.

Parameters:
streamlinesndarray or a list or dipy.tracking.Streamlines

If ndarray, must have shape (N,3) where N is the number of points of the streamline. If list, each item must be ndarray shape (Ni,3) where Ni is the number of points of streamline i. If dipy.tracking.Streamlines, its common_shape must be 3.

nb_pointsint

integer representing number of points wanted along the curve.

Returns:
new_streamlinesndarray or a list or dipy.tracking.Streamlines

Results of the downsampling or upsampling process.

Examples

>>> from dipy.tracking.streamline import set_number_of_points
>>> import numpy as np

One streamline, a semi-circle:

>>> theta = np.pi*np.linspace(0, 1, 100)
>>> x = np.cos(theta)
>>> y = np.sin(theta)
>>> z = 0 * x
>>> streamline = np.vstack((x, y, z)).T
>>> modified_streamline = set_number_of_points(streamline, 3)
>>> len(modified_streamline)
3

Multiple streamlines:

>>> streamlines = [streamline, streamline[::2]]
>>> new_streamlines = set_number_of_points(streamlines, 10)
>>> [len(s) for s in streamlines]
[100, 50]
>>> [len(s) for s in new_streamlines]
[10, 10]

time

dipy.segment.bundles.time() floating point number

Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.

ABCMeta

class dipy.segment.clustering.ABCMeta(name, bases, namespace, **kwargs)

Bases: type

Metaclass for defining Abstract Base Classes (ABCs).

Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as ‘virtual subclasses’ – these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won’t show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()).

Methods

__call__(*args, **kwargs)

Call self as a function.

mro(/)

Return a type's method resolution order.

register(subclass)

Register a virtual subclass of an ABC.

__init__(*args, **kwargs)
register(subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

AveragePointwiseEuclideanMetric

class dipy.segment.clustering.AveragePointwiseEuclideanMetric

Bases: SumPointwiseEuclideanMetric

Computes the average of pointwise Euclidean distances between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \((a+b+c)/3\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)

Cluster

class dipy.segment.clustering.Cluster(id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)

Bases: object

Provides functionalities for interacting with a cluster.

Useful container to retrieve index of elements grouped together. If a reference to the data is provided to cluster_map, elements will be returned instead of their index when possible.

Parameters:
cluster_mapClusterMap object

Reference to the set of clusters this cluster is being part of.

idint

Id of this cluster in its associated cluster_map object.

refdatalist (optional)

Actual elements that clustered indices refer to.

Notes

A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMap object.

Methods

assign(*indices)

Assigns indices to this cluster.

__init__(id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)
assign(*indices)

Assigns indices to this cluster.

Parameters:
*indiceslist of indices

Indices to add to this cluster.

ClusterCentroid

class dipy.segment.clustering.ClusterCentroid(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)

Bases: Cluster

Provides functionalities for interacting with a cluster.

Useful container to retrieve the indices of elements grouped together and the cluster’s centroid. If a reference to the data is provided to cluster_map, elements will be returned instead of their index when possible.

Parameters:
cluster_mapClusterMapCentroid object

Reference to the set of clusters this cluster is being part of.

idint

Id of this cluster in its associated cluster_map object.

refdatalist (optional)

Actual elements that clustered indices refer to.

Notes

A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMapCentroid object.

Methods

assign(id_datum, features)

Assigns a data point to this cluster.

update()

Update centroid of this cluster.

__init__(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)
assign(id_datum, features)

Assigns a data point to this cluster.

Parameters:
id_datumint

Index of the data point to add to this cluster.

features2D array

Data point’s features to modify this cluster’s centroid.

update()

Update centroid of this cluster.

Returns:
convergedbool

Tells if the centroid has moved.

ClusterMap

class dipy.segment.clustering.ClusterMap(refdata=<dipy.segment.clustering.Identity object>)

Bases: object

Provides functionalities for interacting with clustering outputs.

Useful container to create, remove, retrieve and filter clusters. If refdata is given, elements will be returned instead of their index when using Cluster objects.

Parameters:
refdatalist

Actual elements that clustered indices refer to.

Attributes:
clusters
refdata

Methods

add_cluster(*clusters)

Adds one or multiple clusters to this cluster map.

clear()

Remove all clusters from this cluster map.

clusters_sizes()

Gets the size of every cluster contained in this cluster map.

get_large_clusters(min_size)

Gets clusters which contains at least min_size elements.

get_small_clusters(max_size)

Gets clusters which contains at most max_size elements.

remove_cluster(*clusters)

Remove one or multiple clusters from this cluster map.

size()

Gets number of clusters contained in this cluster map.

__init__(refdata=<dipy.segment.clustering.Identity object>)
add_cluster(*clusters)

Adds one or multiple clusters to this cluster map.

Parameters:
*clustersCluster object, …

Cluster(s) to be added in this cluster map.

clear()

Remove all clusters from this cluster map.

property clusters
clusters_sizes()

Gets the size of every cluster contained in this cluster map.

Returns:
list of int

Sizes of every cluster in this cluster map.

get_large_clusters(min_size)

Gets clusters which contains at least min_size elements.

Parameters:
min_sizeint

Minimum number of elements a cluster needs to have to be selected.

Returns:
list of Cluster objects

Clusters having at least min_size elements.

get_small_clusters(max_size)

Gets clusters which contains at most max_size elements.

Parameters:
max_sizeint

Maximum number of elements a cluster can have to be selected.

Returns:
list of Cluster objects

Clusters having at most max_size elements.

property refdata
remove_cluster(*clusters)

Remove one or multiple clusters from this cluster map.

Parameters:
*clustersCluster object, …

Cluster(s) to be removed from this cluster map.

size()

Gets number of clusters contained in this cluster map.

ClusterMapCentroid

class dipy.segment.clustering.ClusterMapCentroid(refdata=<dipy.segment.clustering.Identity object>)

Bases: ClusterMap

Provides functionalities for interacting with clustering outputs that have centroids.

Allows to retrieve easily the centroid of every cluster. Also, it is a useful container to create, remove, retrieve and filter clusters. If refdata is given, elements will be returned instead of their index when using ClusterCentroid objects.

Parameters:
refdatalist

Actual elements that clustered indices refer to.

Attributes:
centroids
clusters
refdata

Methods

add_cluster(*clusters)

Adds one or multiple clusters to this cluster map.

clear()

Remove all clusters from this cluster map.

clusters_sizes()

Gets the size of every cluster contained in this cluster map.

get_large_clusters(min_size)

Gets clusters which contains at least min_size elements.

get_small_clusters(max_size)

Gets clusters which contains at most max_size elements.

remove_cluster(*clusters)

Remove one or multiple clusters from this cluster map.

size()

Gets number of clusters contained in this cluster map.

__init__(refdata=<dipy.segment.clustering.Identity object>)
property centroids

Clustering

class dipy.segment.clustering.Clustering

Bases: object

Methods

cluster(data[, ordering])

Clusters data.

__init__(*args, **kwargs)
abstract cluster(data, ordering=None)

Clusters data.

Subclasses will perform their clustering algorithm here.

Parameters:
datalist of N-dimensional arrays

Each array represents a data point.

orderingiterable of indices, optional

Specifies the order in which data points will be clustered.

Returns:
ClusterMap object

Result of the clustering.

Identity

class dipy.segment.clustering.Identity

Bases: object

Provides identity indexing functionality.

This can replace any class supporting indexing used for referencing (e.g. list, tuple). Indexing an instance of this class will return the index provided instead of the element. It does not support slicing.

__init__(*args, **kwargs)

Metric

class dipy.segment.clustering.Metric

Bases: object

Computes a distance between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

When subclassing Metric, one only needs to override the dist and are_compatible methods.

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
are_compatible()

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

Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).

Parameters:
shape1int, 1-tuple or 2-tuple

shape of the first data point’s features

shape2int, 1-tuple or 2-tuple

shape of the second data point’s features

Returns:
are_compatiblebool

whether or not shapes are compatible

dist()

Computes a distance between two data points based on their features.

Parameters:
features12D array

Features of the first data point.

features22D array

Features of the second data point.

Returns:
double

Distance between two data points.

feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

MinimumAverageDirectFlipMetric

class dipy.segment.clustering.MinimumAverageDirectFlipMetric

Bases: AveragePointwiseEuclideanMetric

Computes the MDF distance (minimum average direct-flip) between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \(\min((a+b+c)/3, (a'+b'+c')/3)\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1], \(c\) between s1[2] and s2[2], \(a'\) between s1[0] and s2[2], \(b'\) between s1[1] and s2[1] and \(c'\) between s1[2] and s2[0].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
is_order_invariant

Is this metric invariant to the sequence’s ordering

QuickBundles

class dipy.segment.clustering.QuickBundles(threshold, metric='MDF_12points', max_nb_clusters=2147483647)

Bases: Clustering

Clusters streamlines using QuickBundles [Garyfallidis12].

Given a list of streamlines, the QuickBundles algorithm sequentially assigns each streamline to its closest bundle in \(\mathcal{O}(Nk)\) where \(N\) is the number of streamlines and \(k\) is the final number of bundles. If for a given streamline its closest bundle is farther than threshold, a new bundle is created and the streamline is assigned to it except if the number of bundles has already exceeded max_nb_clusters.

Parameters:
thresholdfloat

The maximum distance from a bundle for a streamline to be still considered as part of it.

metricstr or Metric object (optional)

The distance metric to use when comparing two streamlines. By default, the Minimum average Direct-Flip (MDF) distance [Garyfallidis12] is used and streamlines are automatically resampled so they have 12 points.

max_nb_clustersint

Limits the creation of bundles.

References

[Garyfallidis12] (1,2,3)

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

Examples

>>> from dipy.segment.clustering import QuickBundles
>>> from dipy.data import get_fnames
>>> from dipy.io.streamline import load_tractogram
>>> from dipy.tracking.streamline import Streamlines
>>> fname = get_fnames('fornix')
>>> fornix = load_tractogram(fname, 'same',
...                          bbox_valid_check=False).streamlines
>>> streamlines = Streamlines(fornix)
>>> # Segment fornix with a threshold of 10mm and streamlines resampled
>>> # to 12 points.
>>> qb = QuickBundles(threshold=10.)
>>> clusters = qb.cluster(streamlines)
>>> len(clusters)
4
>>> list(map(len, clusters))
[61, 191, 47, 1]
>>> # Resampling streamlines differently is done explicitly as follows.
>>> # Note this has an impact on the speed and the accuracy (tradeoff).
>>> from dipy.segment.featurespeed import ResampleFeature
>>> from dipy.segment.metricspeed import AveragePointwiseEuclideanMetric
>>> feature = ResampleFeature(nb_points=2)
>>> metric = AveragePointwiseEuclideanMetric(feature)
>>> qb = QuickBundles(threshold=10., metric=metric)
>>> clusters = qb.cluster(streamlines)
>>> len(clusters)
4
>>> list(map(len, clusters))
[58, 142, 72, 28]

Methods

cluster(streamlines[, ordering])

Clusters streamlines into bundles.

__init__(threshold, metric='MDF_12points', max_nb_clusters=2147483647)
cluster(streamlines, ordering=None)

Clusters streamlines into bundles.

Performs quickbundles algorithm using predefined metric and threshold.

Parameters:
streamlineslist of 2D arrays

Each 2D array represents a sequence of 3D points (points, 3).

orderingiterable of indices

Specifies the order in which data points will be clustered.

Returns:
ClusterMapCentroid object

Result of the clustering.

QuickBundlesX

class dipy.segment.clustering.QuickBundlesX(thresholds, metric='MDF_12points')

Bases: Clustering

Clusters streamlines using QuickBundlesX.

Parameters:
thresholdslist of float

Thresholds to use for each clustering layer. A threshold represents the maximum distance from a cluster for a streamline to be still considered as part of it.

metricstr or Metric object (optional)

The distance metric to use when comparing two streamlines. By default, the Minimum average Direct-Flip (MDF) distance [Garyfallidis12] is used and streamlines are automatically resampled so they have 12 points.

References

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

[Garyfallidis16]

Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016.

Methods

cluster(streamlines[, ordering])

Clusters streamlines into bundles.

__init__(thresholds, metric='MDF_12points')
cluster(streamlines, ordering=None)

Clusters streamlines into bundles.

Performs QuickbundleX using a predefined metric and thresholds.

Parameters:
streamlineslist of 2D arrays

Each 2D array represents a sequence of 3D points (points, 3).

orderingiterable of indices

Specifies the order in which data points will be clustered.

Returns:
TreeClusterMap object

Result of the clustering.

ResampleFeature

class dipy.segment.clustering.ResampleFeature

Bases: CythonFeature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

The features being extracted are the points of the sequence once resampled. This is useful for metrics requiring a constant number of points for all

streamlines.

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)

TreeCluster

class dipy.segment.clustering.TreeCluster(threshold, centroid, indices=None)

Bases: ClusterCentroid

Attributes:
is_leaf

Methods

assign(id_datum, features)

Assigns a data point to this cluster.

update()

Update centroid of this cluster.

add

return_indices

__init__(threshold, centroid, indices=None)
add(child)
property is_leaf
return_indices()

TreeClusterMap

class dipy.segment.clustering.TreeClusterMap(root)

Bases: ClusterMap

Attributes:
clusters
refdata

Methods

add_cluster(*clusters)

Adds one or multiple clusters to this cluster map.

clear()

Remove all clusters from this cluster map.

clusters_sizes()

Gets the size of every cluster contained in this cluster map.

get_large_clusters(min_size)

Gets clusters which contains at least min_size elements.

get_small_clusters(max_size)

Gets clusters which contains at most max_size elements.

remove_cluster(*clusters)

Remove one or multiple clusters from this cluster map.

size()

Gets number of clusters contained in this cluster map.

get_clusters

iter_preorder

traverse_postorder

__init__(root)
get_clusters(wanted_level)
iter_preorder(node)
property refdata
traverse_postorder(node, visit)

abstractmethod

dipy.segment.clustering.abstractmethod(funcobj)

A decorator indicating abstract methods.

Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.

Usage:

class C(metaclass=ABCMeta):

@abstractmethod def my_abstract_method(self, …):

nbytes

dipy.segment.clustering.nbytes(streamlines)

qbx_and_merge

dipy.segment.clustering.qbx_and_merge(streamlines, thresholds, nb_pts=20, select_randomly=None, rng=None, verbose=False)

Run QuickBundlesX and then run again on the centroids of the last layer

Running again QuickBundles at a layer has the effect of merging some of the clusters that may be originally divided because of branching. This function help obtain a result at a QuickBundles quality but with QuickBundlesX speed. The merging phase has low cost because it is applied only on the centroids rather than the entire dataset.

Parameters:
streamlinesStreamlines
thresholdssequence

List of distance thresholds for QuickBundlesX.

nb_ptsint

Number of points for discretizing each streamline

select_randomlyint

Randomly select a specific number of streamlines. If None all the streamlines are used.

rngRandomState

If None then RandomState is initialized internally.

verbosebool, optional.

If True, log information. Default False.

Returns:
clustersobj

Contains the clusters of the last layer of QuickBundlesX after merging.

References

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

[Garyfallidis16]

Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016.

set_number_of_points

dipy.segment.clustering.set_number_of_points()
Change the number of points of streamlines

(either by downsampling or upsampling)

Change the number of points of streamlines in order to obtain nb_points-1 segments of equal length. Points of streamlines will be modified along the curve.

Parameters:
streamlinesndarray or a list or dipy.tracking.Streamlines

If ndarray, must have shape (N,3) where N is the number of points of the streamline. If list, each item must be ndarray shape (Ni,3) where Ni is the number of points of streamline i. If dipy.tracking.Streamlines, its common_shape must be 3.

nb_pointsint

integer representing number of points wanted along the curve.

Returns:
new_streamlinesndarray or a list or dipy.tracking.Streamlines

Results of the downsampling or upsampling process.

Examples

>>> from dipy.tracking.streamline import set_number_of_points
>>> import numpy as np

One streamline, a semi-circle:

>>> theta = np.pi*np.linspace(0, 1, 100)
>>> x = np.cos(theta)
>>> y = np.sin(theta)
>>> z = 0 * x
>>> streamline = np.vstack((x, y, z)).T
>>> modified_streamline = set_number_of_points(streamline, 3)
>>> len(modified_streamline)
3

Multiple streamlines:

>>> streamlines = [streamline, streamline[::2]]
>>> new_streamlines = set_number_of_points(streamlines, 10)
>>> [len(s) for s in streamlines]
[100, 50]
>>> [len(s) for s in new_streamlines]
[10, 10]

time

dipy.segment.clustering.time() floating point number

Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.

ClusterCentroid

class dipy.segment.clustering_algorithms.ClusterCentroid(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)

Bases: Cluster

Provides functionalities for interacting with a cluster.

Useful container to retrieve the indices of elements grouped together and the cluster’s centroid. If a reference to the data is provided to cluster_map, elements will be returned instead of their index when possible.

Parameters:
cluster_mapClusterMapCentroid object

Reference to the set of clusters this cluster is being part of.

idint

Id of this cluster in its associated cluster_map object.

refdatalist (optional)

Actual elements that clustered indices refer to.

Notes

A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMapCentroid object.

Methods

assign(id_datum, features)

Assigns a data point to this cluster.

update()

Update centroid of this cluster.

__init__(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)
assign(id_datum, features)

Assigns a data point to this cluster.

Parameters:
id_datumint

Index of the data point to add to this cluster.

features2D array

Data point’s features to modify this cluster’s centroid.

update()

Update centroid of this cluster.

Returns:
convergedbool

Tells if the centroid has moved.

ClusterMapCentroid

class dipy.segment.clustering_algorithms.ClusterMapCentroid(refdata=<dipy.segment.clustering.Identity object>)

Bases: ClusterMap

Provides functionalities for interacting with clustering outputs that have centroids.

Allows to retrieve easily the centroid of every cluster. Also, it is a useful container to create, remove, retrieve and filter clusters. If refdata is given, elements will be returned instead of their index when using ClusterCentroid objects.

Parameters:
refdatalist

Actual elements that clustered indices refer to.

Attributes:
centroids
clusters
refdata

Methods

add_cluster(*clusters)

Adds one or multiple clusters to this cluster map.

clear()

Remove all clusters from this cluster map.

clusters_sizes()

Gets the size of every cluster contained in this cluster map.

get_large_clusters(min_size)

Gets clusters which contains at least min_size elements.

get_small_clusters(max_size)

Gets clusters which contains at most max_size elements.

remove_cluster(*clusters)

Remove one or multiple clusters from this cluster map.

size()

Gets number of clusters contained in this cluster map.

__init__(refdata=<dipy.segment.clustering.Identity object>)
property centroids

DTYPE

dipy.segment.clustering_algorithms.DTYPE

alias of float32

clusters_centroid2clustermap_centroid

dipy.segment.clustering_algorithms.clusters_centroid2clustermap_centroid()

Converts a ClustersCentroid object (Cython) to a ClusterMapCentroid object (Python).

Only basic functionalities are provided with a Clusters object. To have more flexibility, one should use ClusterMap object, hence this conversion function.

Parameters:
clusters_listClustersCentroid object

Result of the clustering contained in a Cython’s object.

Returns:
ClusterMapCentroid object

Result of the clustering contained in a Python’s object.

peek

dipy.segment.clustering_algorithms.peek()

Returns the first element of an iterable and the iterator.

quickbundles

dipy.segment.clustering_algorithms.quickbundles()

Clusters streamlines using QuickBundles.

Parameters:
streamlineslist of 2D arrays

List of streamlines to cluster.

metricMetric object

Tells how to compute the distance between two streamlines.

thresholddouble

The maximum distance from a cluster for a streamline to be still considered as part of it.

max_nb_clustersint, optional

Limits the creation of bundles. (Default: inf)

orderingiterable of indices, optional

Iterate through data using the given ordering.

Returns:
ClusterMapCentroid object

Result of the clustering.

References

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

quickbundlesx

dipy.segment.clustering_algorithms.quickbundlesx()

Clusters streamlines using QuickBundlesX.

Parameters:
streamlineslist of 2D arrays

List of streamlines to cluster.

metricMetric object

Tells how to compute the distance between two streamlines.

thresholdslist of double

Thresholds to use for each clustering layer. A threshold represents the maximum distance from a cluster for a streamline to be still considered as part of it.

orderingiterable of indices, optional

Iterate through data using the given ordering.

Returns:
TreeClusterMap object

Result of the clustering. Use get_clusters() to get the clusters at a specific level of the hierarchy.

References

[Garyfallidis16]
Garyfallidis E. et al. QuickBundlesX: Sequential

clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016.

[Garyfallidis12]

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

ClusterCentroid

class dipy.segment.clusteringspeed.ClusterCentroid(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)

Bases: Cluster

Provides functionalities for interacting with a cluster.

Useful container to retrieve the indices of elements grouped together and the cluster’s centroid. If a reference to the data is provided to cluster_map, elements will be returned instead of their index when possible.

Parameters:
cluster_mapClusterMapCentroid object

Reference to the set of clusters this cluster is being part of.

idint

Id of this cluster in its associated cluster_map object.

refdatalist (optional)

Actual elements that clustered indices refer to.

Notes

A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMapCentroid object.

Methods

assign(id_datum, features)

Assigns a data point to this cluster.

update()

Update centroid of this cluster.

__init__(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)
assign(id_datum, features)

Assigns a data point to this cluster.

Parameters:
id_datumint

Index of the data point to add to this cluster.

features2D array

Data point’s features to modify this cluster’s centroid.

update()

Update centroid of this cluster.

Returns:
convergedbool

Tells if the centroid has moved.

ClusterMapCentroid

class dipy.segment.clusteringspeed.ClusterMapCentroid(refdata=<dipy.segment.clustering.Identity object>)

Bases: ClusterMap

Provides functionalities for interacting with clustering outputs that have centroids.

Allows to retrieve easily the centroid of every cluster. Also, it is a useful container to create, remove, retrieve and filter clusters. If refdata is given, elements will be returned instead of their index when using ClusterCentroid objects.

Parameters:
refdatalist

Actual elements that clustered indices refer to.

Attributes:
centroids
clusters
refdata

Methods

add_cluster(*clusters)

Adds one or multiple clusters to this cluster map.

clear()

Remove all clusters from this cluster map.

clusters_sizes()

Gets the size of every cluster contained in this cluster map.

get_large_clusters(min_size)

Gets clusters which contains at least min_size elements.

get_small_clusters(max_size)

Gets clusters which contains at most max_size elements.

remove_cluster(*clusters)

Remove one or multiple clusters from this cluster map.

size()

Gets number of clusters contained in this cluster map.

__init__(refdata=<dipy.segment.clustering.Identity object>)
property centroids

Clusters

class dipy.segment.clusteringspeed.Clusters

Bases: object

Provides Cython functionalities to interact with clustering outputs.

This class allows to create clusters and assign elements to them. Assignements of a cluster are represented as a list of element indices.

__init__(*args, **kwargs)

ClustersCentroid

class dipy.segment.clusteringspeed.ClustersCentroid

Bases: Clusters

Provides Cython functionalities to interact with clustering outputs having the notion of cluster’s centroid.

This class allows to create clusters, assign elements to them and update their centroid.

Parameters:
centroid_shapeint, tuple of int

Information about the shape of the centroid.

epsfloat, optional

Consider the centroid has not changed if the changes per dimension are less than this epsilon. (Default: 1e-6)

__init__(*args, **kwargs)

DTYPE

dipy.segment.clusteringspeed.DTYPE

alias of float32

QuickBundles

class dipy.segment.clusteringspeed.QuickBundles

Bases: object

Methods

get_cluster_map

get_stats

__init__(*args, **kwargs)
get_cluster_map()
get_stats()

QuickBundlesX

class dipy.segment.clusteringspeed.QuickBundlesX

Bases: object

Methods

get_stats

get_tree_cluster_map

insert

__init__(*args, **kwargs)
get_stats()
get_tree_cluster_map()
insert()

TreeCluster

class dipy.segment.clusteringspeed.TreeCluster(threshold, centroid, indices=None)

Bases: ClusterCentroid

Attributes:
is_leaf

Methods

assign(id_datum, features)

Assigns a data point to this cluster.

update()

Update centroid of this cluster.

add

return_indices

__init__(threshold, centroid, indices=None)
add(child)
property is_leaf
return_indices()

TreeClusterMap

class dipy.segment.clusteringspeed.TreeClusterMap(root)

Bases: ClusterMap

Attributes:
clusters
refdata

Methods

add_cluster(*clusters)

Adds one or multiple clusters to this cluster map.

clear()

Remove all clusters from this cluster map.

clusters_sizes()

Gets the size of every cluster contained in this cluster map.

get_large_clusters(min_size)

Gets clusters which contains at least min_size elements.

get_small_clusters(max_size)

Gets clusters which contains at most max_size elements.

remove_cluster(*clusters)

Remove one or multiple clusters from this cluster map.

size()

Gets number of clusters contained in this cluster map.

get_clusters

iter_preorder

traverse_postorder

__init__(root)
get_clusters(wanted_level)
iter_preorder(node)
property refdata
traverse_postorder(node, visit)

evaluate_aabb_checks

dipy.segment.clusteringspeed.evaluate_aabb_checks()

ArcLengthFeature

class dipy.segment.featurespeed.ArcLengthFeature

Bases: CythonFeature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

The feature being extracted consists of one scalar representing the arc length of the sequence (i.e. the sum of the length of all segments).

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)

CenterOfMassFeature

class dipy.segment.featurespeed.CenterOfMassFeature

Bases: CythonFeature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

The feature being extracted consists of one N-dimensional point representing the mean of the points, i.e. the center of mass.

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)

CythonFeature

class dipy.segment.featurespeed.CythonFeature

Bases: Feature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Parameters:
is_order_invariantbool, optional

Tells if this feature is invariant to the sequence’s ordering (Default: True).

Notes

By default, when inheriting from CythonFeature, Python methods will call their C version (e.g. CythonFeature.extract -> self.c_extract).

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)
extract()

Extracts features from a sequential datum.

Parameters:
datum2D array

Sequence of N-dimensional points.

Returns:
2D array

Features extracted from datum.

Notes

This method calls its Cython version self.c_extract accordingly.

infer_shape()

Infers the shape of features extracted from a sequential datum.

Parameters:
datum2D array

Sequence of N-dimensional points.

Returns:
tuple

Shape of the features.

Notes

This method calls its Cython version self.c_infer_shape accordingly.

Feature

class dipy.segment.featurespeed.Feature

Bases: object

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Parameters:
is_order_invariantbool (optional)

tells if this feature is invariant to the sequence’s ordering. This means starting from either extremities produces the same features. (Default: True)

Notes

When subclassing Feature, one only needs to override the extract and infer_shape methods.

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)
extract()

Extracts features from a sequential datum.

Parameters:
datum2D array

Sequence of N-dimensional points.

Returns:
2D array

Features extracted from datum.

infer_shape()

Infers the shape of features extracted from a sequential datum.

Parameters:
datum2D array

Sequence of N-dimensional points.

Returns:
int, 1-tuple or 2-tuple

Shape of the features.

is_order_invariant

Is this feature invariant to the sequence’s ordering

IdentityFeature

class dipy.segment.featurespeed.IdentityFeature

Bases: CythonFeature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

The features being extracted are the actual sequence’s points. This is useful for metric that does not require any pre-processing.

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)

MidpointFeature

class dipy.segment.featurespeed.MidpointFeature

Bases: CythonFeature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

The feature being extracted consists of one N-dimensional point representing the middle point of the sequence (i.e. `nb_points//2`th point).

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)

ResampleFeature

class dipy.segment.featurespeed.ResampleFeature

Bases: CythonFeature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

The features being extracted are the points of the sequence once resampled. This is useful for metrics requiring a constant number of points for all

streamlines.

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)

VectorOfEndpointsFeature

class dipy.segment.featurespeed.VectorOfEndpointsFeature

Bases: CythonFeature

Extracts features from a sequential datum.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

The feature being extracted consists of one vector in the N-dimensional space pointing from one end-point of the sequence to the other (i.e. S[-1]-S[0]).

Attributes:
is_order_invariant

Is this feature invariant to the sequence’s ordering

Methods

extract

Extracts features from a sequential datum.

infer_shape

Infers the shape of features extracted from a sequential datum.

__init__(*args, **kwargs)

extract

dipy.segment.featurespeed.extract()

Extracts features from data.

Parameters:
featureFeature object

Tells how to extract features from the data.

datumlist of 2D arrays

List of sequence of N-dimensional points.

Returns:
list of 2D arrays

List of features extracted from data.

infer_shape

dipy.segment.featurespeed.infer_shape()

Infers shape of the features extracted from data.

Parameters:
featureFeature object

Tells how to infer shape of the features.

datalist of 2D arrays

List of sequences of N-dimensional points.

Returns:
list of tuples

Shapes of the features inferred from data.

applymask

dipy.segment.mask.applymask(vol, mask)

Mask vol with mask.

Parameters:
volndarray

Array with \(V\) dimensions

maskndarray

Binary mask. Has \(M\) dimensions where \(M <= V\). When \(M < V\), we append \(V - M\) dimensions with axis length 1 to mask so that mask will broadcast against vol. In the typical case vol can be 4D, mask can be 3D, and we append a 1 to the mask shape which (via numpy broadcasting) has the effect of appling the 3D mask to each 3D slice in vol (vol[..., 0] to vol[..., -1).

Returns:
masked_volndarray

vol multiplied by mask where mask may have been extended to match extra dimensions in vol

binary_dilation

dipy.segment.mask.binary_dilation(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False)

Multidimensional binary dilation with the given structuring element.

Parameters:
inputarray_like

Binary array_like to be dilated. Non-zero (True) elements form the subset to be dilated.

structurearray_like, optional

Structuring element used for the dilation. Non-zero elements are considered True. If no structuring element is provided an element is generated with a square connectivity equal to one.

iterationsint, optional

The dilation is repeated iterations times (one, by default). If iterations is less than 1, the dilation is repeated until the result does not change anymore. Only an integer of iterations is accepted.

maskarray_like, optional

If a mask is given, only those elements with a True value at the corresponding mask element are modified at each iteration.

outputndarray, optional

Array of the same shape as input, into which the output is placed. By default, a new array is created.

border_valueint (cast to 0 or 1), optional

Value at the border in the output array.

originint or tuple of ints, optional

Placement of the filter, by default 0.

brute_forceboolean, optional

Memory condition: if False, only the pixels whose value was changed in the last iteration are tracked as candidates to be updated (dilated) in the current iteration; if True all pixels are considered as candidates for dilation, regardless of what happened in the previous iteration. False by default.

Returns:
binary_dilationndarray of bools

Dilation of the input by the structuring element.

See also

grey_dilation, binary_erosion, binary_closing, binary_opening
generate_binary_structure

Notes

Dilation [1] is a mathematical morphology operation [2] that uses a structuring element for expanding the shapes in an image. The binary dilation of an image by a structuring element is the locus of the points covered by the structuring element, when its center lies within the non-zero points of the image.

References

Examples

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5, 5))
>>> a[2, 2] = 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a)
array([[False, False, False, False, False],
       [False, False,  True, False, False],
       [False,  True,  True,  True, False],
       [False, False,  True, False, False],
       [False, False, False, False, False]], dtype=bool)
>>> ndimage.binary_dilation(a).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> # 3x3 structuring element with connectivity 1, used by default
>>> struct1 = ndimage.generate_binary_structure(2, 1)
>>> struct1
array([[False,  True, False],
       [ True,  True,  True],
       [False,  True, False]], dtype=bool)
>>> # 3x3 structuring element with connectivity 2
>>> struct2 = ndimage.generate_binary_structure(2, 2)
>>> struct2
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a, structure=struct1,\
... iterations=2).astype(a.dtype)
array([[ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.]])

bounding_box

dipy.segment.mask.bounding_box(vol)

Compute the bounding box of nonzero intensity voxels in the volume.

Parameters:
volndarray

Volume to compute bounding box on.

Returns:
npminslist

Array containg minimum index of each dimension

npmaxslist

Array containg maximum index of each dimension

clean_cc_mask

dipy.segment.mask.clean_cc_mask(mask)

Cleans a segmentation of the corpus callosum so no random pixels are included.

Parameters:
maskndarray

Binary mask of the coarse segmentation.

Returns:
new_cc_maskndarray

Binary mask of the cleaned segmentation.

color_fa

dipy.segment.mask.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\]

crop

dipy.segment.mask.crop(vol, mins, maxs)

Crops the input volume.

Parameters:
volndarray

Volume to crop.

minsarray

Array containing minimum index of each dimension.

maxsarray

Array containing maximum index of each dimension.

Returns:
volndarray

The cropped volume.

fractional_anisotropy

dipy.segment.mask.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}}\]

generate_binary_structure

dipy.segment.mask.generate_binary_structure(rank, connectivity)

Generate a binary structure for binary morphological operations.

Parameters:
rankint

Number of dimensions of the array to which the structuring element will be applied, as returned by np.ndim.

connectivityint

connectivity determines which elements of the output array belong to the structure, i.e., are considered as neighbors of the central element. Elements up to a squared distance of connectivity from the center are considered neighbors. connectivity may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors).

Returns:
outputndarray of bools

Structuring element which may be used for binary morphological operations, with rank dimensions and all dimensions equal to 3.

See also

iterate_structure, binary_dilation, binary_erosion

Notes

generate_binary_structure can only create structuring elements with dimensions equal to 3, i.e., minimal dimensions. For larger structuring elements, that are useful e.g., for eroding large objects, one may either use iterate_structure, or create directly custom arrays with numpy functions such as numpy.ones.

Examples

>>> from scipy import ndimage
>>> import numpy as np
>>> struct = ndimage.generate_binary_structure(2, 1)
>>> struct
array([[False,  True, False],
       [ True,  True,  True],
       [False,  True, False]], dtype=bool)
>>> a = np.zeros((5,5))
>>> a[2, 2] = 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
>>> b
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
array([[ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  0.]])
>>> struct = ndimage.generate_binary_structure(2, 2)
>>> struct
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> struct = ndimage.generate_binary_structure(3, 1)
>>> struct # no diagonal elements
array([[[False, False, False],
        [False,  True, False],
        [False, False, False]],
       [[False,  True, False],
        [ True,  True,  True],
        [False,  True, False]],
       [[False, False, False],
        [False,  True, False],
        [False, False, False]]], dtype=bool)

median_filter

dipy.segment.mask.median_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0)

Calculate a multidimensional median filter.

Parameters:
inputarray_like

The input array.

sizescalar or tuple, optional

See footprint, below. Ignored if footprint is given.

footprintarray, optional

Either size or footprint must be defined. size gives the shape that is taken from the input array, at every element position, to define the input to the filter function. footprint is a boolean array that specifies (implicitly) a shape, but also which of the elements within this shape will get passed to the filter function. Thus size=(n,m) is equivalent to footprint=np.ones((n,m)). We adjust size to the number of dimensions of the input array, so that, if the input array is shape (10,10,10), and size is 2, then the actual size used is (2,2,2). When footprint is given, size is ignored.

outputarray or dtype, optional

The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.

mode{‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional

The mode parameter determines how the input array is extended beyond its boundaries. Default is ‘reflect’. Behavior for each valid value is as follows:

‘reflect’ (d c b a | a b c d | d c b a)

The input is extended by reflecting about the edge of the last pixel. This mode is also sometimes referred to as half-sample symmetric.

‘constant’ (k k k k | a b c d | k k k k)

The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter.

‘nearest’ (a a a a | a b c d | d d d d)

The input is extended by replicating the last pixel.

‘mirror’ (d c b | a b c d | c b a)

The input is extended by reflecting about the center of the last pixel. This mode is also sometimes referred to as whole-sample symmetric.

‘wrap’ (a b c d | a b c d | a b c d)

The input is extended by wrapping around to the opposite edge.

For consistency with the interpolation functions, the following mode names can also be used:

‘grid-mirror’

This is a synonym for ‘reflect’.

‘grid-constant’

This is a synonym for ‘constant’.

‘grid-wrap’

This is a synonym for ‘wrap’.

cvalscalar, optional

Value to fill past edges of input if mode is ‘constant’. Default is 0.0.

originint or sequence, optional

Controls the placement of the filter on the input array’s pixels. A value of 0 (the default) centers the filter over the pixel, with positive values shifting the filter to the left, and negative ones to the right. By passing a sequence of origins with length equal to the number of dimensions of the input array, different shifts can be specified along each axis.

Returns:
median_filterndarray

Filtered array. Has the same shape as input.

See also

scipy.signal.medfilt2d

Notes

For 2-dimensional images with uint8, float32 or float64 dtypes the specialised function scipy.signal.medfilt2d may be faster. It is however limited to constant mode with cval=0.

Examples

>>> from scipy import ndimage, datasets
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> plt.gray()  # show the filtered result in grayscale
>>> ax1 = fig.add_subplot(121)  # left side
>>> ax2 = fig.add_subplot(122)  # right side
>>> ascent = datasets.ascent()
>>> result = ndimage.median_filter(ascent, size=20)
>>> ax1.imshow(ascent)
>>> ax2.imshow(result)
>>> plt.show()

median_otsu

dipy.segment.mask.median_otsu(input_volume, vol_idx=None, median_radius=4, numpass=4, autocrop=False, dilate=None)

Simple brain extraction tool method for images from DWI data.

It uses a median filter smoothing of the input_volumes vol_idx and an automatic histogram Otsu thresholding technique, hence the name median_otsu.

This function is inspired from Mrtrix’s bet which has default values median_radius=3, numpass=2. However, from tests on multiple 1.5T and 3T data from GE, Philips, Siemens, the most robust choice is median_radius=4, numpass=4.

Parameters:
input_volumendarray

3D or 4D array of the brain volume.

vol_idxNone or array, optional.

1D array representing indices of axis=3 of a 4D input_volume. None is only an acceptable input if input_volume is 3D.

median_radiusint

Radius (in voxels) of the applied median filter (default: 4).

numpass: int

Number of pass of the median filter (default: 4).

autocrop: bool, optional

if True, the masked input_volume will also be cropped using the bounding box defined by the masked data. Should be on if DWI is upsampled to 1x1x1 resolution. (default: False).

dilateNone or int, optional

number of iterations for binary dilation

Returns:
maskedvolumendarray

Masked input_volume

mask3D ndarray

The binary brain mask

Notes

Copyright (C) 2011, the scikit-image team All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. 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.

  3. Neither the name of skimage nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

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.

multi_median

dipy.segment.mask.multi_median(data, median_radius, numpass)

Applies median filter multiple times on input data.

Parameters:
datandarray

The input volume to apply filter on.

median_radiusint

Radius (in voxels) of the applied median filter

numpass: int

Number of pass of the median filter

Returns:
datandarray

Filtered input volume.

otsu

dipy.segment.mask.otsu(image=None, nbins=256, *, hist=None)

Return threshold value based on Otsu’s method.

Either image or hist must be provided. If hist is provided, the actual histogram of the image is ignored.

Parameters:
image(N, M[, …, P]) ndarray, optional

Grayscale input image.

nbinsint, optional

Number of bins used to calculate histogram. This value is ignored for integer arrays.

histarray, or 2-tuple of arrays, optional

Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. If no hist provided, this function will compute it from the image.

Returns:
thresholdfloat

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

Notes

The input image must be grayscale.

References

Examples

>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_otsu(image)
>>> binary = image <= thresh

segment_from_cfa

dipy.segment.mask.segment_from_cfa(tensor_fit, roi, threshold, return_cfa=False)

Segment the cfa inside roi using the values from threshold as bounds.

Parameters:
tensor_fitTensorFit object

TensorFit object

roindarray

A binary mask, which contains the bounding box for the segmentation.

thresholdarray-like

An iterable that defines the min and max values to use for the thresholding. The values are specified as (R_min, R_max, G_min, G_max, B_min, B_max)

return_cfabool, optional

If True, the cfa is also returned.

Returns:
maskndarray

Binary mask of the segmentation.

cfandarray, optional

Array with shape = (…, 3), where … is the shape of tensor_fit. The color fractional anisotropy, ordered as a nd array with the last dimension of size 3 for the R, G and B channels.

warn

dipy.segment.mask.warn(/, message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception.

AveragePointwiseEuclideanMetric

class dipy.segment.metric.AveragePointwiseEuclideanMetric

Bases: SumPointwiseEuclideanMetric

Computes the average of pointwise Euclidean distances between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \((a+b+c)/3\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)

CosineMetric

class dipy.segment.metric.CosineMetric

Bases: CythonMetric

Computes the cosine distance between two vectors.

A vector (i.e. a N-dimensional point) is represented as a 2D array with shape (1, nb_dimensions).

Notes

The distance between two vectors \(v_1\) and \(v_2\) is equal to \(\frac{1}{\pi} \arccos\left(\frac{v_1 \cdot v_2}{\|v_1\| \|v_2\|}\right)\) and is bounded within \([0,1]\).

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)

EuclideanMetric

dipy.segment.metric.EuclideanMetric

alias of SumPointwiseEuclideanMetric

Metric

class dipy.segment.metric.Metric

Bases: object

Computes a distance between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

When subclassing Metric, one only needs to override the dist and are_compatible methods.

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
are_compatible()

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

Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).

Parameters:
shape1int, 1-tuple or 2-tuple

shape of the first data point’s features

shape2int, 1-tuple or 2-tuple

shape of the second data point’s features

Returns:
are_compatiblebool

whether or not shapes are compatible

dist()

Computes a distance between two data points based on their features.

Parameters:
features12D array

Features of the first data point.

features22D array

Features of the second data point.

Returns:
double

Distance between two data points.

feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

MinimumAverageDirectFlipMetric

class dipy.segment.metric.MinimumAverageDirectFlipMetric

Bases: AveragePointwiseEuclideanMetric

Computes the MDF distance (minimum average direct-flip) between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \(\min((a+b+c)/3, (a'+b'+c')/3)\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1], \(c\) between s1[2] and s2[2], \(a'\) between s1[0] and s2[2], \(b'\) between s1[1] and s2[1] and \(c'\) between s1[2] and s2[0].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
is_order_invariant

Is this metric invariant to the sequence’s ordering

SumPointwiseEuclideanMetric

class dipy.segment.metric.SumPointwiseEuclideanMetric

Bases: CythonMetric

Computes the sum of pointwise Euclidean distances between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \(a+b+c\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)

dist

dipy.segment.metric.dist()

Computes a distance between datum1 and datum2.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Parameters:
metricMetric object

Tells how to compute the distance between datum1 and datum2.

datum12D array

Sequence of N-dimensional points.

datum22D array

Sequence of N-dimensional points.

Returns:
double

Distance between two data points.

mdf

dipy.segment.metric.mdf(s1, s2)

Computes the MDF (Minimum average Direct-Flip) distance [Garyfallidis12] between two streamlines.

Streamlines must have the same number of points.

Parameters:
s12D array

A streamline (sequence of N-dimensional points).

s22D array

A streamline (sequence of N-dimensional points).

Returns:
double

Distance between two streamlines.

References

[Garyfallidis12] (1,2)

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

AveragePointwiseEuclideanMetric

class dipy.segment.metricspeed.AveragePointwiseEuclideanMetric

Bases: SumPointwiseEuclideanMetric

Computes the average of pointwise Euclidean distances between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \((a+b+c)/3\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)

CosineMetric

class dipy.segment.metricspeed.CosineMetric

Bases: CythonMetric

Computes the cosine distance between two vectors.

A vector (i.e. a N-dimensional point) is represented as a 2D array with shape (1, nb_dimensions).

Notes

The distance between two vectors \(v_1\) and \(v_2\) is equal to \(\frac{1}{\pi} \arccos\left(\frac{v_1 \cdot v_2}{\|v_1\| \|v_2\|}\right)\) and is bounded within \([0,1]\).

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)

CythonMetric

class dipy.segment.metricspeed.CythonMetric

Bases: Metric

Computes a distance between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

When subclassing CythonMetric, one only needs to override the c_dist and c_are_compatible methods.

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
are_compatible()

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

Basically this method exists so we don’t have to do this check inside method dist (speedup).

Parameters:
shape1int, 1-tuple or 2-tuple

Shape of the first data point’s features.

shape2int, 1-tuple or 2-tuple

Shape of the second data point’s features.

Returns:
bool

Whether or not shapes are compatible.

Notes

This method calls its Cython version self.c_are_compatible accordingly.

dist()

Computes a distance between two data points based on their features.

Parameters:
features12D array

Features of the first data point.

features22D array

Features of the second data point.

Returns:
double

Distance between two data points.

Notes

This method calls its Cython version self.c_dist accordingly.

Metric

class dipy.segment.metricspeed.Metric

Bases: object

Computes a distance between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

When subclassing Metric, one only needs to override the dist and are_compatible methods.

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
are_compatible()

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

Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).

Parameters:
shape1int, 1-tuple or 2-tuple

shape of the first data point’s features

shape2int, 1-tuple or 2-tuple

shape of the second data point’s features

Returns:
are_compatiblebool

whether or not shapes are compatible

dist()

Computes a distance between two data points based on their features.

Parameters:
features12D array

Features of the first data point.

features22D array

Features of the second data point.

Returns:
double

Distance between two data points.

feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

MinimumAverageDirectFlipMetric

class dipy.segment.metricspeed.MinimumAverageDirectFlipMetric

Bases: AveragePointwiseEuclideanMetric

Computes the MDF distance (minimum average direct-flip) between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \(\min((a+b+c)/3, (a'+b'+c')/3)\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1], \(c\) between s1[2] and s2[2], \(a'\) between s1[0] and s2[2], \(b'\) between s1[1] and s2[1] and \(c'\) between s1[2] and s2[0].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)
is_order_invariant

Is this metric invariant to the sequence’s ordering

SumPointwiseEuclideanMetric

class dipy.segment.metricspeed.SumPointwiseEuclideanMetric

Bases: CythonMetric

Computes the sum of pointwise Euclidean distances between two sequential data.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.

Parameters:
featureFeature object, optional

It is used to extract features before computing the distance.

Notes

The distance between two 2D sequential data:

s1       s2

0*   a    *0
  \       |
   \      |
   1*     |
    |  b  *1
    |      \
    2*      \
        c    *2

is equal to \(a+b+c\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].

Attributes:
feature

Feature object used to extract features from sequential data

is_order_invariant

Is this metric invariant to the sequence’s ordering

Methods

are_compatible

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

dist

Computes a distance between two data points based on their features.

__init__(*args, **kwargs)

dist

dipy.segment.metricspeed.dist()

Computes a distance between datum1 and datum2.

A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Parameters:
metricMetric object

Tells how to compute the distance between datum1 and datum2.

datum12D array

Sequence of N-dimensional points.

datum22D array

Sequence of N-dimensional points.

Returns:
double

Distance between two data points.

distance_matrix

dipy.segment.metricspeed.distance_matrix()

Computes the distance matrix between two lists of sequential data.

The distance matrix is obtained by computing the pairwise distance of all tuples spawn by the Cartesian product of data1 with data2. If data2 is not provided, the Cartesian product of data1 with itself is used instead. A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).

Parameters:
metricMetric object

Tells how to compute the distance between two sequential data.

data1list of 2D arrays

List of sequences of N-dimensional points.

data2list of 2D arrays

Llist of sequences of N-dimensional points.

Returns:
2D array (double)

Distance matrix.

ConstantObservationModel

class dipy.segment.mrf.ConstantObservationModel

Bases: object

Observation model assuming that the intensity of each class is constant. The model parameters are the means \(\mu_{k}\) and variances \(\sigma_{k}\) associated with each tissue class. According to this model, the observed intensity at voxel \(x\) is given by \(I(x) = \mu_{k} + \eta_{k}\) where \(k\) is the tissue class of voxel \(x\), and \(\eta_{k}\) is a Gaussian random variable with zero mean and variance \(\sigma_{k}^{2}\). The observation model is responsible for computing the negative log-likelihood of observing any given intensity \(z\) at each voxel \(x\) assuming the voxel belongs to each class \(k\). It also provides a default parameter initialization.

Methods

initialize_param_uniform(image, nclasses)

Initializes the means and variances uniformly

negloglikelihood(image, mu, sigmasq, nclasses)

Computes the gaussian negative log-likelihood of each class at each voxel of image assuming a gaussian distribution with means and variances given by mu and sigmasq, respectively (constant models along the full volume).

prob_image(img, nclasses, mu, sigmasq, P_L_N)

Conditional probability of the label given the image

seg_stats(input_image, seg_image, nclass)

Mean and standard variation for N desired tissue classes

update_param(image, P_L_Y, mu, nclasses)

Updates the means and the variances in each iteration for all the labels.

__init__()

Initializes an instance of the ConstantObservationModel class

initialize_param_uniform(image, nclasses)

Initializes the means and variances uniformly

The means are initialized uniformly along the dynamic range of image. The variances are set to 1 for all classes

Parameters:
imagearray

3D structural image

nclassesint

number of desired classes

Returns:
muarray

1 x nclasses, mean for each class

sigmaarray

1 x nclasses, standard deviation for each class. Set up to 1.0 for all classes.

negloglikelihood(image, mu, sigmasq, nclasses)

Computes the gaussian negative log-likelihood of each class at each voxel of image assuming a gaussian distribution with means and variances given by mu and sigmasq, respectively (constant models along the full volume). The negative log-likelihood will be written in nloglike.

Parameters:
imagendarray

3D gray scale structural image

mundarray

mean of each class

sigmasqndarray

variance of each class

nclassesint

number of classes

Returns:
nloglikendarray

4D negloglikelihood for each class in each volume

prob_image(img, nclasses, mu, sigmasq, P_L_N)

Conditional probability of the label given the image

Parameters:
imgndarray

3D structural gray-scale image

nclassesint

number of tissue classes

mundarray

1 x nclasses, current estimate of the mean of each tissue class

sigmasqndarray

1 x nclasses, current estimate of the variance of each tissue class

P_L_Nndarray

4D probability map of the label given the neighborhood.

Previously computed by function prob_neighborhood
Returns:
P_L_Yndarray

4D probability of the label given the input image

seg_stats(input_image, seg_image, nclass)

Mean and standard variation for N desired tissue classes

Parameters:
input_imagendarray

3D structural image

seg_imagendarray

3D segmented image

nclassint

number of classes (3 in most cases)

Returns:
mu, varndarrays

1 x nclasses dimension Mean and variance for each class

update_param(image, P_L_Y, mu, nclasses)

Updates the means and the variances in each iteration for all the labels. This is for equations 25 and 26 of Zhang et. al., IEEE Trans. Med. Imag, Vol. 20, No. 1, Jan 2001.

Parameters:
imagendarray

3D structural gray-scale image

P_L_Yndarray

4D probability map of the label given the input image computed by the expectation maximization (EM) algorithm

mundarray

1 x nclasses, current estimate of the mean of each tissue class.

nclassesint

number of tissue classes

Returns:
mu_updndarray

1 x nclasses, updated mean of each tissue class

var_updndarray

1 x nclasses, updated variance of each tissue class

IteratedConditionalModes

class dipy.segment.mrf.IteratedConditionalModes

Bases: object

Methods

icm_ising(nloglike, beta, seg)

Executes one iteration of the ICM algorithm for MRF MAP estimation.

initialize_maximum_likelihood(nloglike)

Initializes the segmentation of an image with given

prob_neighborhood(seg, beta, nclasses)

Conditional probability of the label given the neighborhood Equation 2.18 of the Stan Z.

__init__()
icm_ising(nloglike, beta, seg)

Executes one iteration of the ICM algorithm for MRF MAP estimation. The prior distribution of the MRF is a Gibbs distribution with the Potts/Ising model with parameter beta:

https://en.wikipedia.org/wiki/Potts_model

Parameters:
nloglikendarray

4D shape, nloglike[x, y, z, k] is the negative log likelihood of class k at voxel (x, y, z)

betafloat

positive scalar, it is the parameter of the Potts/Ising model. Determines the smoothness of the output segmentation.

segndarray

3D initial segmentation. This segmentation will change by one iteration of the ICM algorithm

Returns:
new_segndarray

3D final segmentation

energyndarray

3D final energy

initialize_maximum_likelihood(nloglike)
Initializes the segmentation of an image with given

neg-loglikelihood

Initializes the segmentation of an image with neglog-likelihood field given by nloglike. The class of each voxel is selected as the one with the minimum neglog-likelihood (i.e. maximum-likelihood segmentation).

Parameters:
nloglikendarray

4D shape, nloglike[x, y, z, k] is the likelihhood of class k for voxel (x, y, z)

Returns:
segndarray

3D initial segmentation

prob_neighborhood(seg, beta, nclasses)

Conditional probability of the label given the neighborhood Equation 2.18 of the Stan Z. Li book (Stan Z. Li, Markov Random Field Modeling in Image Analysis, 3rd ed., Advances in Pattern Recognition Series, Springer Verlag 2009.)

Parameters:
segndarray

3D tissue segmentation derived from the ICM model

betafloat

scalar that determines the importance of the neighborhood and the spatial smoothness of the segmentation. Usually between 0 to 0.5

nclassesint

number of tissue classes

Returns:
PLNndarray

4D probability map of the label given the neighborhood of the voxel.

otsu

dipy.segment.threshold.otsu(image, nbins=256)

Return threshold value based on Otsu’s method. Copied from scikit-image to remove dependency.

Parameters:
imagearray

Input image.

nbinsint

Number of bins used to calculate histogram. This value is ignored for integer arrays.

Returns:
thresholdfloat

Threshold value.

upper_bound_by_percent

dipy.segment.threshold.upper_bound_by_percent(data, percent=1)

Find the upper bound for visualization of medical images

Calculate the histogram of the image and go right to left until you find the bound that contains more than a percentage of the image.

Parameters:
datandarray
percentfloat
Returns:
upper_boundfloat

upper_bound_by_rate

dipy.segment.threshold.upper_bound_by_rate(data, rate=0.05)

Adjusts upper intensity boundary using rates

It calculates the image intensity histogram, and based on the rate value it decide what is the upperbound value for intensity normalization, usually lower bound is 0. The rate is the ratio between the amount of pixels in every bins and the bins with highest pixel amount

Parameters:
datafloat

Input intensity value data

ratefloat

representing the threshold whether a spicific histogram bin that should be count in the normalization range

Returns:
highfloat

the upper_bound value for normalization

ConstantObservationModel

class dipy.segment.tissue.ConstantObservationModel

Bases: object

Observation model assuming that the intensity of each class is constant. The model parameters are the means \(\mu_{k}\) and variances \(\sigma_{k}\) associated with each tissue class. According to this model, the observed intensity at voxel \(x\) is given by \(I(x) = \mu_{k} + \eta_{k}\) where \(k\) is the tissue class of voxel \(x\), and \(\eta_{k}\) is a Gaussian random variable with zero mean and variance \(\sigma_{k}^{2}\). The observation model is responsible for computing the negative log-likelihood of observing any given intensity \(z\) at each voxel \(x\) assuming the voxel belongs to each class \(k\). It also provides a default parameter initialization.

Methods

initialize_param_uniform(image, nclasses)

Initializes the means and variances uniformly

negloglikelihood(image, mu, sigmasq, nclasses)

Computes the gaussian negative log-likelihood of each class at each voxel of image assuming a gaussian distribution with means and variances given by mu and sigmasq, respectively (constant models along the full volume).

prob_image(img, nclasses, mu, sigmasq, P_L_N)

Conditional probability of the label given the image

seg_stats(input_image, seg_image, nclass)

Mean and standard variation for N desired tissue classes

update_param(image, P_L_Y, mu, nclasses)

Updates the means and the variances in each iteration for all the labels.

__init__()

Initializes an instance of the ConstantObservationModel class

initialize_param_uniform(image, nclasses)

Initializes the means and variances uniformly

The means are initialized uniformly along the dynamic range of image. The variances are set to 1 for all classes

Parameters:
imagearray

3D structural image

nclassesint

number of desired classes

Returns:
muarray

1 x nclasses, mean for each class

sigmaarray

1 x nclasses, standard deviation for each class. Set up to 1.0 for all classes.

negloglikelihood(image, mu, sigmasq, nclasses)

Computes the gaussian negative log-likelihood of each class at each voxel of image assuming a gaussian distribution with means and variances given by mu and sigmasq, respectively (constant models along the full volume). The negative log-likelihood will be written in nloglike.

Parameters:
imagendarray

3D gray scale structural image

mundarray

mean of each class

sigmasqndarray

variance of each class

nclassesint

number of classes

Returns:
nloglikendarray

4D negloglikelihood for each class in each volume

prob_image(img, nclasses, mu, sigmasq, P_L_N)

Conditional probability of the label given the image

Parameters:
imgndarray

3D structural gray-scale image

nclassesint

number of tissue classes

mundarray

1 x nclasses, current estimate of the mean of each tissue class

sigmasqndarray

1 x nclasses, current estimate of the variance of each tissue class

P_L_Nndarray

4D probability map of the label given the neighborhood.

Previously computed by function prob_neighborhood
Returns:
P_L_Yndarray

4D probability of the label given the input image

seg_stats(input_image, seg_image, nclass)

Mean and standard variation for N desired tissue classes

Parameters:
input_imagendarray

3D structural image

seg_imagendarray

3D segmented image

nclassint

number of classes (3 in most cases)

Returns:
mu, varndarrays

1 x nclasses dimension Mean and variance for each class

update_param(image, P_L_Y, mu, nclasses)

Updates the means and the variances in each iteration for all the labels. This is for equations 25 and 26 of Zhang et. al., IEEE Trans. Med. Imag, Vol. 20, No. 1, Jan 2001.

Parameters:
imagendarray

3D structural gray-scale image

P_L_Yndarray

4D probability map of the label given the input image computed by the expectation maximization (EM) algorithm

mundarray

1 x nclasses, current estimate of the mean of each tissue class.

nclassesint

number of tissue classes

Returns:
mu_updndarray

1 x nclasses, updated mean of each tissue class

var_updndarray

1 x nclasses, updated variance of each tissue class

IteratedConditionalModes

class dipy.segment.tissue.IteratedConditionalModes

Bases: object

Methods

icm_ising(nloglike, beta, seg)

Executes one iteration of the ICM algorithm for MRF MAP estimation.

initialize_maximum_likelihood(nloglike)

Initializes the segmentation of an image with given

prob_neighborhood(seg, beta, nclasses)

Conditional probability of the label given the neighborhood Equation 2.18 of the Stan Z.

__init__()
icm_ising(nloglike, beta, seg)

Executes one iteration of the ICM algorithm for MRF MAP estimation. The prior distribution of the MRF is a Gibbs distribution with the Potts/Ising model with parameter beta:

https://en.wikipedia.org/wiki/Potts_model

Parameters:
nloglikendarray

4D shape, nloglike[x, y, z, k] is the negative log likelihood of class k at voxel (x, y, z)

betafloat

positive scalar, it is the parameter of the Potts/Ising model. Determines the smoothness of the output segmentation.

segndarray

3D initial segmentation. This segmentation will change by one iteration of the ICM algorithm

Returns:
new_segndarray

3D final segmentation

energyndarray

3D final energy

initialize_maximum_likelihood(nloglike)
Initializes the segmentation of an image with given

neg-loglikelihood

Initializes the segmentation of an image with neglog-likelihood field given by nloglike. The class of each voxel is selected as the one with the minimum neglog-likelihood (i.e. maximum-likelihood segmentation).

Parameters:
nloglikendarray

4D shape, nloglike[x, y, z, k] is the likelihhood of class k for voxel (x, y, z)

Returns:
segndarray

3D initial segmentation

prob_neighborhood(seg, beta, nclasses)

Conditional probability of the label given the neighborhood Equation 2.18 of the Stan Z. Li book (Stan Z. Li, Markov Random Field Modeling in Image Analysis, 3rd ed., Advances in Pattern Recognition Series, Springer Verlag 2009.)

Parameters:
segndarray

3D tissue segmentation derived from the ICM model

betafloat

scalar that determines the importance of the neighborhood and the spatial smoothness of the segmentation. Usually between 0 to 0.5

nclassesint

number of tissue classes

Returns:
PLNndarray

4D probability map of the label given the neighborhood of the voxel.

TissueClassifierHMRF

class dipy.segment.tissue.TissueClassifierHMRF(save_history=False, verbose=True)

Bases: object

This class contains the methods for tissue classification using the Markov Random Fields modeling approach

Methods

classify(image, nclasses, beta[, tolerance, ...])

This method uses the Maximum a posteriori - Markov Random Field approach for segmentation by using the Iterative Conditional Modes and Expectation Maximization to estimate the parameters.

__init__(save_history=False, verbose=True)
classify(image, nclasses, beta, tolerance=None, max_iter=None)

This method uses the Maximum a posteriori - Markov Random Field approach for segmentation by using the Iterative Conditional Modes and Expectation Maximization to estimate the parameters.

Parameters:
imagendarray,

3D structural image.

nclassesint,

number of desired classes.

betafloat,

smoothing parameter, the higher this number the smoother the output will be.

tolerance: float,

value that defines the percentage of change tolerated to prevent the ICM loop to stop. Default is 1e-05.

max_iterfloat,

fixed number of desired iterations. Default is 100. If the user only specifies this parameter, the tolerance value will not be considered. If none of these two parameters

Returns:
initial_segmentationndarray,

3D segmented image with all tissue types specified in nclasses.

final_segmentationndarray,

3D final refined segmentation containing all tissue types.

PVEndarray,

3D probability map of each tissue type.

add_noise

dipy.segment.tissue.add_noise(signal, snr, S0, noise_type='rician')

Add noise of specified distribution to the signal from a single voxel.

Parameters:
signal1-d ndarray

The signal in the voxel.

snrfloat

The desired signal-to-noise ratio. (See notes below.) If snr is None, return the signal as-is.

S0float

Reference signal for specifying snr.

noise_typestring, optional

The distribution of noise added. Can be either ‘gaussian’ for Gaussian distributed noise, ‘rician’ for Rice-distributed noise (default) or ‘rayleigh’ for a Rayleigh distribution.

Returns:
signalarray, same shape as the input

Signal with added noise.

Notes

SNR is defined here, following [1], as S0 / sigma, where sigma is the standard deviation of the two Gaussian distributions forming the real and imaginary components of the Rician noise distribution (see [2]).

References

[1]

Descoteaux, Angelino, Fitzgibbons and Deriche (2007) Regularized, fast and robust q-ball imaging. MRM, 58: 497-510

[2]

Gudbjartson and Patz (2008). The Rician distribution of noisy MRI data. MRM 34: 910-914.

Examples

>>> signal = np.arange(800).reshape(2, 2, 2, 100)
>>> signal_w_noise = add_noise(signal, 10., 100., noise_type='rician')