Comprehensive Python library for diffusion MRI analysis including tensor imaging, tractography, and visualization
npx @tessl/cli install tessl/pypi-dipy@1.11.00
# DIPY
1
2
DIPY (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.
3
4
## Package Information
5
6
- **Package Name**: dipy
7
- **Language**: Python
8
- **Installation**: `pip install dipy`
9
- **Documentation**: https://docs.dipy.org/stable/
10
11
## Core Imports
12
13
```python
14
import dipy
15
```
16
17
Common workflow imports:
18
19
```python
20
# Core objects
21
from dipy.core.gradients import gradient_table, GradientTable
22
from dipy.core.sphere import get_sphere, Sphere
23
from dipy.core.geometry import sphere2cart, cart2sphere
24
25
# Data access
26
from dipy.data import read_stanford_hardi, read_sherbrooke_3shell, read_ivim
27
28
# Signal reconstruction
29
from dipy.reconst.dti import TensorModel, TensorFit
30
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
31
from dipy.reconst.dki import DiffusionKurtosisModel
32
33
# Registration and alignment
34
from dipy.align import syn_registration, affine_registration, center_of_mass
35
36
# Tractography
37
from dipy.tracking.streamline import Streamlines
38
from dipy.direction import DeterministicMaximumDirectionGetter, ProbabilisticDirectionGetter
39
from dipy.tracking.local_tracking import LocalTracking
40
41
# Visualization
42
from dipy.viz import window, actor
43
44
# I/O operations
45
from dipy.io.streamline import save_tractogram, load_tractogram
46
from dipy.io.image import load_nifti, save_nifti
47
from dipy.io.gradients import read_bvals_bvecs
48
49
# Utilities
50
from dipy.utils.arrfuncs import normalize_v3
51
```
52
53
## Basic Usage
54
55
```python
56
import dipy
57
from dipy.data import read_stanford_hardi
58
from dipy.core.gradients import gradient_table
59
from dipy.reconst.dti import TensorModel
60
import numpy as np
61
62
# Load example diffusion data
63
img, gtab = read_stanford_hardi()
64
data = img.get_fdata()
65
66
# Create gradient table
67
gtab = gradient_table(gtab.bvals, gtab.bvecs)
68
69
# Fit diffusion tensor model
70
tenmodel = TensorModel(gtab)
71
tenfit = tenmodel.fit(data)
72
73
# Extract fractional anisotropy (FA)
74
fa = tenfit.fa
75
76
# Extract apparent diffusion coefficient (ADC)
77
adc = tenfit.adc
78
79
print(f"FA shape: {fa.shape}")
80
print(f"Mean FA: {np.mean(fa[fa > 0]):.3f}")
81
```
82
83
## Architecture
84
85
DIPY's modular architecture provides a comprehensive framework for diffusion MRI analysis:
86
87
- **Core Objects**: Fundamental data structures (spheres, gradient tables, geometry utilities)
88
- **Data Access**: Extensive example datasets and I/O utilities for various formats
89
- **Signal Reconstruction**: Model-based analysis (DTI, DKI, CSD, MAPMRI, IVIM) with consistent Model/Fit interfaces
90
- **Registration**: Image and streamline alignment with multiple transformation types
91
- **Tractography**: Deterministic and probabilistic fiber tracking with direction selection
92
- **Segmentation**: Streamline clustering and bundle segmentation algorithms
93
- **Statistics**: Tractometry and statistical analysis of diffusion metrics
94
- **Simulations**: Phantom data generation and signal simulation
95
- **Neural Networks**: Deep learning models for denoising and enhancement
96
- **Visualization**: 3D rendering and interactive visualization tools
97
- **Workflows**: Pre-built command-line interfaces for common analysis pipelines
98
- **Utilities**: Array manipulation, coordinate transformations, and helper functions
99
100
This design enables flexible analysis pipelines from raw data through model fitting to visualization and statistical analysis.
101
102
## Capabilities
103
104
### Data Access and Management
105
106
Comprehensive data loading, example datasets, and I/O operations for diffusion MRI data formats including gradient tables, streamlines, and various neuroimaging file types.
107
108
```python { .api }
109
def read_stanford_hardi():
110
"""Load Stanford HARDI dataset."""
111
112
def gradient_table(bvals, *, bvecs=None, big_delta=None, small_delta=None, b0_threshold=50, atol=1e-2, btens=None):
113
"""Create gradient table from b-values and b-vectors."""
114
115
def read_bvals_bvecs(fbvals, fbvecs):
116
"""Read b-values and b-vectors from files."""
117
118
class GradientTable:
119
def __init__(self, gradients, b0_threshold=50): ...
120
@property
121
def bvals(self): ...
122
@property
123
def bvecs(self): ...
124
125
def get_sphere(*, name="symmetric362"):
126
"""Provide triangulated spheres."""
127
```
128
129
[Data Access](./data-access.md)
130
131
### Signal Reconstruction Models
132
133
Model-based analysis of diffusion MRI signals including diffusion tensor imaging (DTI), diffusion kurtosis imaging (DKI), constrained spherical deconvolution (CSD), and advanced microstructure models.
134
135
```python { .api }
136
class TensorModel:
137
def __init__(self, gtab, fit_method="WLS", return_S0_hat=False): ...
138
def fit(self, data, mask=None): ...
139
140
class ConstrainedSphericalDeconvModel:
141
def __init__(self, gtab, response, reg_sphere=None, sh_order=8): ...
142
def fit(self, data, mask=None): ...
143
144
class DiffusionKurtosisModel:
145
def __init__(self, gtab, fit_method="WLS", **kwargs): ...
146
def fit(self, data, mask=None): ...
147
148
class TensorFit:
149
@property
150
def fa(self): ... # Fractional anisotropy
151
@property
152
def adc(self): ... # Apparent diffusion coefficient
153
@property
154
def md(self): ... # Mean diffusivity
155
def predict(self, gtab=None, S0=None): ...
156
```
157
158
[Signal Reconstruction](./signal-reconstruction.md)
159
160
### Registration and Alignment
161
162
Image registration algorithms for aligning diffusion data, including affine and non-linear registration methods, motion correction, and streamline registration.
163
164
```python { .api }
165
def syn_registration(moving, static, moving_affine=None, static_affine=None, prealign=None, **kwargs):
166
"""Symmetric diffeomorphic registration."""
167
168
def affine_registration(moving, static, moving_affine=None, static_affine=None, **kwargs):
169
"""Multi-resolution affine registration."""
170
171
def register_dwi_series(data, gtab, affine=None, b0_ref=0, **kwargs):
172
"""Register DWI series for motion correction."""
173
174
def streamline_registration(moving, static, moving_affine=None, static_affine=None, **kwargs):
175
"""Register streamlines using bundle-based approach."""
176
177
def resample(moving, static, moving_affine=None, static_affine=None, **kwargs):
178
"""Resample image using transformation."""
179
180
def center_of_mass(moving, static):
181
"""Align images using center of mass."""
182
```
183
184
[Registration](./registration.md)
185
186
### Tractography and Fiber Tracking
187
188
Deterministic and probabilistic tractography algorithms with various direction selection methods, streamline generation, and tracking utilities.
189
190
```python { .api }
191
class DeterministicMaximumDirectionGetter:
192
def __init__(self, from_shm, max_angle=60.0, sphere=None, pmf_threshold=0.1): ...
193
194
class ProbabilisticDirectionGetter:
195
def __init__(self, from_shm, max_angle=60.0, sphere=None, pmf_threshold=0.1): ...
196
197
class LocalTracking:
198
def __init__(self, direction_getter, stopping_criterion, seeds, affine=None, step_size=0.5): ...
199
200
class Streamlines:
201
def __init__(self, streamlines=None, affine_to_rasmm=None): ...
202
def __len__(self): ...
203
def __getitem__(self, key): ...
204
205
def peaks_from_model(model, data, sphere, relative_peak_threshold=0.25, min_separation_angle=25, **kwargs):
206
"""Extract peaks from fitted model."""
207
```
208
209
[Tractography](./tractography.md)
210
211
### Visualization and Analysis
212
213
3D visualization tools for diffusion data, streamlines, and scalar maps with interactive rendering capabilities and statistical analysis methods.
214
215
```python { .api }
216
class Scene:
217
def __init__(self, bg=(0, 0, 0)): ...
218
def add(self, actor): ...
219
def rm(self, actor): ...
220
221
def line(lines, colors=None, opacity=1, linewidth=1):
222
"""Create line actor for streamlines."""
223
224
def slicer(data, affine=None, value_range=None, opacity=1, lookup_colormap=None):
225
"""Create slicer actor for volume data."""
226
227
def tensor_slicer(evals, evecs, scalar_colors=None, sphere=None, scale=0.3):
228
"""Create tensor ellipsoid slicer."""
229
```
230
231
[Visualization](./visualization.md)
232
233
### Image Processing and Filtering
234
235
Denoising algorithms, filtering methods, and preprocessing tools for diffusion MRI data quality improvement.
236
237
```python { .api }
238
def nlmeans(arr, sigma=None, mask=None, patch_radius=1, block_radius=5, rician=True):
239
"""Non-local means denoising."""
240
241
def localpca(arr, sigma, mask=None, patch_radius=2, pca_method='eig', **kwargs):
242
"""PCA-based denoising."""
243
244
def mppca(arr, mask=None, patch_radius=2, return_sigma=False, **kwargs):
245
"""Marchenko-Pastur PCA denoising."""
246
247
def gibbs_removal(vol, slice_axis=2, n_points=3):
248
"""Gibbs ringing artifact removal."""
249
```
250
251
[Image Processing](./image-processing.md)
252
253
### Segmentation and Clustering
254
255
Streamline clustering, bundle segmentation, and white matter bundle extraction algorithms for organizing and analyzing tractography results.
256
257
```python { .api }
258
class QuickBundles:
259
def __init__(self, threshold, metric='average'): ...
260
def cluster(self, streamlines): ...
261
262
def bundle_shape_similarity(bundle1, bundle2, rng=None, clust_thr=5): ...
263
def bundle_adjacency(dtracks0, dtracks1, threshold): ...
264
```
265
266
[Segmentation and Clustering](./segmentation.md)
267
268
### Statistics and Tractometry
269
270
Statistical analysis tools for diffusion metrics, tractometry analysis, and group-level comparisons of white matter properties.
271
272
```python { .api }
273
def afq_profile(data, bundle, affine=None, n_points=100): ...
274
def gaussian_weights(bundle, n_points=100, return_mahalnobis=False): ...
275
def values_from_volume(data, streamlines, affine=None): ...
276
```
277
278
[Statistics and Tractometry](./statistics.md)
279
280
### Simulations and Phantoms
281
282
Signal simulation tools for generating synthetic diffusion MRI data, phantoms, and testing algorithms with known ground truth.
283
284
```python { .api }
285
def single_tensor(gtab, S0=1, evals=None, evecs=None, snr=None): ...
286
def multi_tensor(gtab, mevals, angles, fractions, S0=100, snr=None): ...
287
def sticks_and_ball(gtab, d=0.0015, S0=1, angles=[(0, 0)], fractions=[100], snr=None): ...
288
```
289
290
[Simulations and Phantoms](./simulations.md)
291
292
### Neural Networks and Deep Learning
293
294
Deep learning models for image denoising, enhancement, and reconstruction of diffusion MRI data.
295
296
```python { .api }
297
class DummyNeuralNetwork:
298
def __init__(self): ...
299
def predict(self, data, **kwargs): ...
300
301
def deepn4(data, **kwargs): ...
302
def patch2self(data, bvals, patch_radius=0): ...
303
```
304
305
[Neural Networks and Deep Learning](./neural-networks.md)
306
307
### Workflows and Command-Line Tools
308
309
Pre-built workflows and command-line interfaces for common diffusion MRI analysis pipelines and batch processing.
310
311
```python { .api }
312
class Workflow:
313
def run(self, **kwargs): ...
314
315
class IoInfoFlow(Workflow): ...
316
class DenoisingFlow(Workflow): ...
317
class ReconstDtiFlow(Workflow): ...
318
class TrackingFlow(Workflow): ...
319
```
320
321
[Workflows and Command-Line Tools](./workflows.md)
322
323
### Core Utilities
324
325
Essential utility functions for array manipulation, coordinate transformations, and mathematical operations.
326
327
```python { .api }
328
def normalize_v3(vec): ...
329
def as_native_array(arr): ...
330
def sphere2cart(r, theta, phi): ...
331
def cart2sphere(x, y, z): ...
332
```
333
334
[Core Utilities](./core-utilities.md)
335
336
## Types
337
338
```python { .api }
339
class GradientTable:
340
"""Container for diffusion gradient information."""
341
def __init__(self, bvals, bvecs=None, **kwargs): ...
342
@property
343
def bvals(self): ... # b-values array
344
@property
345
def bvecs(self): ... # b-vectors array
346
@property
347
def b0s_mask(self): ... # Boolean mask for b=0 images
348
349
class Streamlines:
350
"""Container for streamline data."""
351
def __init__(self, streamlines=None): ...
352
def __len__(self): ...
353
def __getitem__(self, key): ...
354
355
class Sphere:
356
"""3D sphere representation with vertices and faces."""
357
def __init__(self, xyz=None, faces=None): ...
358
@property
359
def vertices(self): ...
360
@property
361
def faces(self): ...
362
```