Comprehensive Python library for diffusion MRI analysis including tensor imaging, tractography, and visualization
npx @tessl/cli install tessl/pypi-dipy@1.11.0DIPY (Diffusion Imaging in Python) is a comprehensive Python library for the analysis of diffusion MRI (Magnetic Resonance Imaging) data. It provides scientists and researchers with powerful tools for processing, analyzing, and visualizing diffusion-weighted imaging datasets, enabling advanced brain connectivity studies and white matter research.
pip install dipyimport dipyCommon workflow imports:
# Core objects
from dipy.core.gradients import gradient_table, GradientTable
from dipy.core.sphere import get_sphere, Sphere
from dipy.core.geometry import sphere2cart, cart2sphere
# Data access
from dipy.data import read_stanford_hardi, read_sherbrooke_3shell, read_ivim
# Signal reconstruction
from dipy.reconst.dti import TensorModel, TensorFit
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
from dipy.reconst.dki import DiffusionKurtosisModel
# Registration and alignment
from dipy.align import syn_registration, affine_registration, center_of_mass
# Tractography
from dipy.tracking.streamline import Streamlines
from dipy.direction import DeterministicMaximumDirectionGetter, ProbabilisticDirectionGetter
from dipy.tracking.local_tracking import LocalTracking
# Visualization
from dipy.viz import window, actor
# I/O operations
from dipy.io.streamline import save_tractogram, load_tractogram
from dipy.io.image import load_nifti, save_nifti
from dipy.io.gradients import read_bvals_bvecs
# Utilities
from dipy.utils.arrfuncs import normalize_v3import dipy
from dipy.data import read_stanford_hardi
from dipy.core.gradients import gradient_table
from dipy.reconst.dti import TensorModel
import numpy as np
# Load example diffusion data
img, gtab = read_stanford_hardi()
data = img.get_fdata()
# Create gradient table
gtab = gradient_table(gtab.bvals, gtab.bvecs)
# Fit diffusion tensor model
tenmodel = TensorModel(gtab)
tenfit = tenmodel.fit(data)
# Extract fractional anisotropy (FA)
fa = tenfit.fa
# Extract apparent diffusion coefficient (ADC)
adc = tenfit.adc
print(f"FA shape: {fa.shape}")
print(f"Mean FA: {np.mean(fa[fa > 0]):.3f}")DIPY's modular architecture provides a comprehensive framework for diffusion MRI analysis:
This design enables flexible analysis pipelines from raw data through model fitting to visualization and statistical analysis.
Comprehensive data loading, example datasets, and I/O operations for diffusion MRI data formats including gradient tables, streamlines, and various neuroimaging file types.
def read_stanford_hardi():
"""Load Stanford HARDI dataset."""
def gradient_table(bvals, *, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=1e-2, btens=None):
"""Create gradient table from b-values and b-vectors."""
def read_bvals_bvecs(fbvals, fbvecs):
"""Read b-values and b-vectors from files."""
class GradientTable:
def __init__(self, gradients, b0_threshold=50): ...
@property
def bvals(self): ...
@property
def bvecs(self): ...
def get_sphere(*, name="symmetric362"):
"""Provide triangulated spheres."""Model-based analysis of diffusion MRI signals including diffusion tensor imaging (DTI), diffusion kurtosis imaging (DKI), constrained spherical deconvolution (CSD), and advanced microstructure models.
class TensorModel:
def __init__(self, gtab, fit_method="WLS", return_S0_hat=False): ...
def fit(self, data, mask=None): ...
class ConstrainedSphericalDeconvModel:
def __init__(self, gtab, response, reg_sphere=None, sh_order=8): ...
def fit(self, data, mask=None): ...
class DiffusionKurtosisModel:
def __init__(self, gtab, fit_method="WLS", **kwargs): ...
def fit(self, data, mask=None): ...
class TensorFit:
@property
def fa(self): ... # Fractional anisotropy
@property
def adc(self): ... # Apparent diffusion coefficient
@property
def md(self): ... # Mean diffusivity
def predict(self, gtab=None, S0=None): ...Image registration algorithms for aligning diffusion data, including affine and non-linear registration methods, motion correction, and streamline registration.
def syn_registration(moving, static, moving_affine=None, static_affine=None, prealign=None, **kwargs):
"""Symmetric diffeomorphic registration."""
def affine_registration(moving, static, moving_affine=None, static_affine=None, **kwargs):
"""Multi-resolution affine registration."""
def register_dwi_series(data, gtab, affine=None, b0_ref=0, **kwargs):
"""Register DWI series for motion correction."""
def streamline_registration(moving, static, moving_affine=None, static_affine=None, **kwargs):
"""Register streamlines using bundle-based approach."""
def resample(moving, static, moving_affine=None, static_affine=None, **kwargs):
"""Resample image using transformation."""
def center_of_mass(moving, static):
"""Align images using center of mass."""Deterministic and probabilistic tractography algorithms with various direction selection methods, streamline generation, and tracking utilities.
class DeterministicMaximumDirectionGetter:
def __init__(self, from_shm, max_angle=60.0, sphere=None, pmf_threshold=0.1): ...
class ProbabilisticDirectionGetter:
def __init__(self, from_shm, max_angle=60.0, sphere=None, pmf_threshold=0.1): ...
class LocalTracking:
def __init__(self, direction_getter, stopping_criterion, seeds, affine=None, step_size=0.5): ...
class Streamlines:
def __init__(self, streamlines=None, affine_to_rasmm=None): ...
def __len__(self): ...
def __getitem__(self, key): ...
def peaks_from_model(model, data, sphere, relative_peak_threshold=0.25, min_separation_angle=25, **kwargs):
"""Extract peaks from fitted model."""3D visualization tools for diffusion data, streamlines, and scalar maps with interactive rendering capabilities and statistical analysis methods.
class Scene:
def __init__(self, bg=(0, 0, 0)): ...
def add(self, actor): ...
def rm(self, actor): ...
def line(lines, colors=None, opacity=1, linewidth=1):
"""Create line actor for streamlines."""
def slicer(data, affine=None, value_range=None, opacity=1, lookup_colormap=None):
"""Create slicer actor for volume data."""
def tensor_slicer(evals, evecs, scalar_colors=None, sphere=None, scale=0.3):
"""Create tensor ellipsoid slicer."""Denoising algorithms, filtering methods, and preprocessing tools for diffusion MRI data quality improvement.
def nlmeans(arr, sigma=None, mask=None, patch_radius=1, block_radius=5, rician=True):
"""Non-local means denoising."""
def localpca(arr, sigma, mask=None, patch_radius=2, pca_method='eig', **kwargs):
"""PCA-based denoising."""
def mppca(arr, mask=None, patch_radius=2, return_sigma=False, **kwargs):
"""Marchenko-Pastur PCA denoising."""
def gibbs_removal(vol, slice_axis=2, n_points=3):
"""Gibbs ringing artifact removal."""Streamline clustering, bundle segmentation, and white matter bundle extraction algorithms for organizing and analyzing tractography results.
class QuickBundles:
def __init__(self, threshold, metric='average'): ...
def cluster(self, streamlines): ...
def bundle_shape_similarity(bundle1, bundle2, rng=None, clust_thr=5): ...
def bundle_adjacency(dtracks0, dtracks1, threshold): ...Statistical analysis tools for diffusion metrics, tractometry analysis, and group-level comparisons of white matter properties.
def afq_profile(data, bundle, affine=None, n_points=100): ...
def gaussian_weights(bundle, n_points=100, return_mahalnobis=False): ...
def values_from_volume(data, streamlines, affine=None): ...Signal simulation tools for generating synthetic diffusion MRI data, phantoms, and testing algorithms with known ground truth.
def single_tensor(gtab, S0=1, evals=None, evecs=None, snr=None): ...
def multi_tensor(gtab, mevals, angles, fractions, S0=100, snr=None): ...
def sticks_and_ball(gtab, d=0.0015, S0=1, angles=[(0, 0)], fractions=[100], snr=None): ...Deep learning models for image denoising, enhancement, and reconstruction of diffusion MRI data.
class DummyNeuralNetwork:
def __init__(self): ...
def predict(self, data, **kwargs): ...
def deepn4(data, **kwargs): ...
def patch2self(data, bvals, patch_radius=0): ...Neural Networks and Deep Learning
Pre-built workflows and command-line interfaces for common diffusion MRI analysis pipelines and batch processing.
class Workflow:
def run(self, **kwargs): ...
class IoInfoFlow(Workflow): ...
class DenoisingFlow(Workflow): ...
class ReconstDtiFlow(Workflow): ...
class TrackingFlow(Workflow): ...Workflows and Command-Line Tools
Essential utility functions for array manipulation, coordinate transformations, and mathematical operations.
def normalize_v3(vec): ...
def as_native_array(arr): ...
def sphere2cart(r, theta, phi): ...
def cart2sphere(x, y, z): ...class GradientTable:
"""Container for diffusion gradient information."""
def __init__(self, bvals, bvecs=None, **kwargs): ...
@property
def bvals(self): ... # b-values array
@property
def bvecs(self): ... # b-vectors array
@property
def b0s_mask(self): ... # Boolean mask for b=0 images
class Streamlines:
"""Container for streamline data."""
def __init__(self, streamlines=None): ...
def __len__(self): ...
def __getitem__(self, key): ...
class Sphere:
"""3D sphere representation with vertices and faces."""
def __init__(self, xyz=None, faces=None): ...
@property
def vertices(self): ...
@property
def faces(self): ...