Comprehensive Python library for diffusion MRI analysis including tensor imaging, tractography, and visualization
—
Streamline clustering, bundle segmentation, and white matter bundle extraction algorithms for organizing and analyzing tractography results. DIPY provides comprehensive tools for grouping similar streamlines and extracting anatomically meaningful fiber bundles.
Fast streamline clustering algorithm using centroid-based similarity metrics.
class QuickBundles:
"""Fast streamline clustering using centroid-based approach."""
def __init__(self, threshold, metric='average'):
"""
Initialize QuickBundles clustering.
Parameters:
threshold (float): distance threshold for clustering
metric (str): distance metric ('average', 'hausdorff', 'mdf')
"""
def cluster(self, streamlines):
"""
Cluster streamlines into bundles.
Parameters:
streamlines (list): streamlines to cluster
Returns:
ClusterMapCentroid: clustering results with centroids
"""
class ClusterMapCentroid:
"""Container for clustering results."""
@property
def centroids(self):
"""list: cluster centroid streamlines"""
@property
def clusters(self):
"""list: cluster assignments for each streamline"""
def __len__(self):
"""Number of clusters."""
def __getitem__(self, key):
"""Access individual clusters."""Advanced metrics for comparing bundle shapes and analyzing bundle properties.
def bundle_shape_similarity(bundle1, bundle2, rng=None, clust_thr=5, threshold=5):
"""
Calculate shape similarity between two bundles.
Parameters:
bundle1 (list): first bundle streamlines
bundle2 (list): second bundle streamlines
rng (RandomState): random number generator
clust_thr (float): clustering threshold
threshold (float): shape similarity threshold
Returns:
tuple: (similarity_score, matched_pairs)
"""
def bundle_adjacency(dtracks0, dtracks1, threshold):
"""
Calculate adjacency between streamline bundles.
Parameters:
dtracks0 (list): first set of streamlines
dtracks1 (list): second set of streamlines
threshold (float): distance threshold
Returns:
array: adjacency matrix between bundles
"""
def length_similarity(bundle1, bundle2, alpha=0.5):
"""
Compare bundle length distributions.
Parameters:
bundle1 (list): first bundle
bundle2 (list): second bundle
alpha (float): length weighting factor
Returns:
float: length similarity score
"""Automated recognition and extraction of anatomical bundles using atlas-based approaches.
class RecoBundles:
"""Bundle recognition using streamline-based atlas."""
def __init__(self, streamlines_atlas, greater_than=50, less_than=1000,
cluster_map=None, clust_thr=15, nb_pts=20):
"""
Initialize RecoBundles recognition.
Parameters:
streamlines_atlas (list): atlas streamlines for each bundle
greater_than (int): minimum streamlines per bundle
less_than (int): maximum streamlines per bundle
cluster_map (ClusterMap): optional pre-computed clustering
clust_thr (float): clustering threshold
nb_pts (int): number of points for resampling
"""
def recognize(self, streamlines, model_bundle, model_clust_thr=1.25,
reduction_thr=10, reduction_distance='mdf', slr=True, slr_metric='symmetric'):
"""
Recognize bundle in target streamlines.
Parameters:
streamlines (list): target streamlines to search
model_bundle (list): model bundle for recognition
model_clust_thr (float): model clustering threshold
reduction_thr (float): streamline reduction threshold
reduction_distance (str): distance metric for reduction
slr (bool): use Streamline-based Linear Registration
slr_metric (str): SLR distance metric
Returns:
tuple: (recognized_bundle, bundle_labels)
"""Distance metrics and similarity measures for streamline comparison and segmentation.
class AveragePointwiseEuclideanMetric:
"""Average pointwise Euclidean distance metric."""
def __init__(self):
"""Initialize metric."""
def distance(self, s1, s2):
"""Calculate distance between two streamlines."""
class MinimumAverageDirectFlipMetric:
"""Minimum average direct-flip distance metric."""
def __init__(self):
"""Initialize MDF metric."""
def distance(self, s1, s2):
"""Calculate MDF distance between streamlines."""
def set_number_of_points(streamlines, nb_points=20):
"""
Resample streamlines to fixed number of points.
Parameters:
streamlines (list): input streamlines
nb_points (int): target number of points
Returns:
list: resampled streamlines
"""
def length(streamlines):
"""
Calculate streamline lengths.
Parameters:
streamlines (list): input streamlines
Returns:
array: length of each streamline
"""Tools for working with anatomical bundle atlases and bundle-specific analysis.
def read_bundles_2_subjects():
"""
Load example bundle data from 2 subjects.
Returns:
tuple: (bundles_subj1, bundles_subj2)
"""
def read_five_af_bundles():
"""
Load arcuate fasciculus bundles.
Returns:
tuple: bundle data and bundle names
"""
class BundleAnalysis:
"""Bundle-specific analysis tools."""
def __init__(self, bundles, bundle_names=None):
"""
Initialize bundle analysis.
Parameters:
bundles (list): list of bundles
bundle_names (list): names for each bundle
"""
def compute_bundle_stats(self):
"""Compute statistics for each bundle."""
def compare_bundles(self, other_bundles):
"""Compare with another set of bundles."""# QuickBundles clustering example
from dipy.segment.clustering import QuickBundles
from dipy.segment.metric import AveragePointwiseEuclideanMetric
from dipy.data import read_bundles_2_subjects
# Load example streamlines
bundle1, bundle2 = read_bundles_2_subjects()
streamlines = bundle1 + bundle2
# Perform clustering
feature = AveragePointwiseEuclideanMetric()
qb = QuickBundles(threshold=10.0, metric=feature)
clusters = qb.cluster(streamlines)
print(f"Number of clusters: {len(clusters)}")
print(f"Cluster sizes: {[len(cluster) for cluster in clusters]}")
# Access cluster centroids
centroids = clusters.centroids
largest_cluster = clusters[0] # Largest cluster
# Bundle recognition with RecoBundles
from dipy.segment.bundles import RecoBundles
from dipy.data import read_five_af_bundles
# Load atlas bundles
atlas_bundles, bundle_names = read_five_af_bundles()
# Initialize RecoBundles
rb = RecoBundles(atlas_bundles, greater_than=20, less_than=1000000)
# Recognize bundles in new data
recognized = rb.recognize(streamlines, atlas_bundles[0])
print(f"Recognized {len(recognized[0])} streamlines for bundle: {bundle_names[0]}")
# Bundle shape similarity
from dipy.segment.bundles import bundle_shape_similarity
similarity = bundle_shape_similarity(bundle1, bundle2)
print(f"Bundle shape similarity: {similarity[0]:.3f}")
# Streamline metrics
from dipy.segment.metric import length, set_number_of_points
# Calculate lengths
lengths = length(streamlines)
print(f"Mean streamline length: {lengths.mean():.2f} mm")
# Resample to fixed number of points
resampled = set_number_of_points(streamlines, nb_points=100)
print(f"Resampled to {len(resampled[0])} points per streamline")Install with Tessl CLI
npx tessl i tessl/pypi-dipy