0
# Tractography and Fiber Tracking
1
2
Deterministic and probabilistic tractography algorithms with various direction selection methods, streamline generation, and tracking utilities. DIPY provides comprehensive tools for reconstructing white matter pathways from diffusion MRI data.
3
4
## Capabilities
5
6
### Direction Selection
7
8
Direction getter classes that determine fiber orientations for tractography algorithms.
9
10
```python { .api }
11
class DeterministicMaximumDirectionGetter:
12
"""Deterministic direction selection using peak maxima."""
13
def __init__(self, from_shm, max_angle=60.0, sphere=None):
14
"""
15
Initialize deterministic direction getter.
16
17
Parameters:
18
from_shm (array): spherical harmonic coefficients
19
max_angle (float): maximum turning angle in degrees
20
sphere (Sphere): sphere for direction sampling
21
"""
22
23
class ProbabilisticDirectionGetter:
24
"""Probabilistic direction selection with angular uncertainty."""
25
def __init__(self, from_shm, max_angle=60.0, sphere=None, sh_to_pmf=False):
26
"""
27
Initialize probabilistic direction getter.
28
29
Parameters:
30
from_shm (array): spherical harmonic coefficients
31
max_angle (float): maximum turning angle in degrees
32
sphere (Sphere): sphere for direction sampling
33
sh_to_pmf (bool): convert SH to probability mass function
34
"""
35
36
class ClosestPeakDirectionGetter:
37
"""Direction selection using closest peak to previous direction."""
38
def __init__(self, from_shm, max_angle=60.0, sphere=None):
39
"""Initialize closest peak direction getter."""
40
41
class BootDirectionGetter:
42
"""Bootstrap direction selection for uncertainty estimation."""
43
def __init__(self, from_shm, max_angle=60.0, sphere=None, sh_order=None):
44
"""Initialize bootstrap direction getter."""
45
46
class PTTDirectionGetter:
47
"""Particle Tracking Tractography direction getter."""
48
def __init__(self, ptt_interp, vertices, mode='prob'):
49
"""Initialize PTT direction getter."""
50
```
51
52
### Peak Extraction
53
54
Functions for extracting directional peaks from orientation distribution functions.
55
56
```python { .api }
57
def peaks_from_model(model, data, sphere, *, relative_peak_threshold=0.5, min_separation_angle=25, mask=None, return_odf=False, return_sh=False, gfa_thr=0.0, normalize_peaks=False, sh_order_max=8, sh_basis_type=None, npeaks=5, B=None, invB=None, parallel=None, num_processes=None):
58
"""
59
Generate peaks from fitted model.
60
61
Parameters:
62
model: fitted reconstruction model (e.g., CSD)
63
data (array): diffusion data
64
sphere (Sphere): sphere for peak extraction
65
relative_peak_threshold (float): minimum peak height relative to max
66
min_separation_angle (float): minimum angle between peaks (degrees)
67
mask (array): binary mask for processing
68
return_odf (bool): return orientation distribution function
69
return_sh (bool): return spherical harmonic coefficients
70
gfa_thr (float): generalized fractional anisotropy threshold
71
normalize_peaks (bool): normalize peak magnitudes
72
sh_order_max (int): maximum spherical harmonic order
73
sh_basis_type (str): spherical harmonic basis type
74
npeaks (int): maximum number of peaks per voxel
75
B (array): spherical harmonic matrix
76
invB (array): inverse spherical harmonic matrix
77
parallel (bool): use parallel processing
78
num_processes (int): number of processes for parallel execution
79
80
Returns:
81
PeaksAndMetrics: container with peaks, values, and metrics
82
"""
83
84
def peak_directions(odf, sphere, *, relative_peak_threshold=0.5, min_separation_angle=25, **kwargs):
85
"""
86
Extract peak directions from ODF.
87
88
Parameters:
89
odf (array): orientation distribution function values
90
sphere (Sphere): sphere defining ODF sampling
91
relative_peak_threshold (float): peak detection threshold
92
min_separation_angle (float): minimum peak separation angle
93
94
Returns:
95
tuple: (peaks, peak_values) directions and magnitudes
96
"""
97
98
def reshape_peaks_for_visualization(peaks):
99
"""
100
Reshape peak data for visualization.
101
102
Parameters:
103
peaks (PeaksAndMetrics): peak data container
104
105
Returns:
106
array: reshaped peak directions for rendering
107
"""
108
109
class PeaksAndMetrics:
110
"""Container for peak directions and associated metrics."""
111
def __init__(self):
112
"""Initialize peaks and metrics container."""
113
114
@property
115
def peak_dirs(self):
116
"""array: peak directions (4D: x, y, z, directions)"""
117
118
@property
119
def peak_values(self):
120
"""array: peak magnitudes"""
121
122
@property
123
def peak_indices(self):
124
"""array: sphere indices of peaks"""
125
126
@property
127
def gfa(self):
128
"""array: generalized fractional anisotropy"""
129
130
@property
131
def qa(self):
132
"""array: quantitative anisotropy"""
133
134
@property
135
def shm_coeff(self):
136
"""array: spherical harmonic coefficients"""
137
```
138
139
### Streamline Container
140
141
Main container class for streamline data with iteration and manipulation methods.
142
143
```python { .api }
144
class Streamlines:
145
"""Container for streamline data."""
146
def __init__(self, streamlines=None):
147
"""
148
Initialize streamlines container.
149
150
Parameters:
151
streamlines (list): list of streamline arrays
152
"""
153
154
def __len__(self):
155
"""Number of streamlines."""
156
157
def __getitem__(self, key):
158
"""Access streamlines by index or slice."""
159
160
def __iter__(self):
161
"""Iterate over streamlines."""
162
163
def append(self, streamline):
164
"""Add streamline to container."""
165
166
def extend(self, streamlines):
167
"""Add multiple streamlines."""
168
```
169
170
### Tracking Algorithms
171
172
Core tractography algorithms for deterministic and probabilistic fiber tracking.
173
174
```python { .api }
175
def LocalTracking(direction_getter, classifier, seeds, affine, step_size=0.5, max_cross=None, maxlen=1000000, fixedstep=True, return_all=True):
176
"""
177
Local streamline tracking algorithm.
178
179
Parameters:
180
direction_getter: direction selection object
181
classifier: tissue classifier for tracking
182
seeds (array): seed point coordinates
183
affine (array): voxel-to-world transformation matrix
184
step_size (float): tracking step size in mm
185
max_cross (int): maximum fiber crossings per voxel
186
maxlen (int): maximum streamline length
187
fixedstep (bool): use fixed step size
188
return_all (bool): return all streamlines including short ones
189
190
Returns:
191
generator: streamline generator
192
"""
193
194
def ParticleFilteringTracking(direction_getter, classifier, seeds, affine, max_cross=None, step_size=0.5, maxlen=1000000, pft_back_tracking_dist=2.0, pft_front_tracking_dist=1.0, particle_count=15, return_all=True):
195
"""
196
Particle Filtering Tractography algorithm.
197
198
Parameters:
199
direction_getter: direction selection object
200
classifier: tissue classifier
201
seeds (array): seed coordinates
202
affine (array): affine transformation
203
max_cross (int): maximum crossings
204
step_size (float): step size in mm
205
maxlen (int): maximum length
206
pft_back_tracking_dist (float): back tracking distance
207
pft_front_tracking_dist (float): front tracking distance
208
particle_count (int): number of particles per streamline
209
return_all (bool): return all streamlines
210
211
Returns:
212
generator: streamline generator
213
"""
214
```
215
216
### Tissue Classification
217
218
Classifiers that determine tracking behavior based on tissue properties.
219
220
```python { .api }
221
class ThresholdClassifier:
222
"""Binary classifier based on scalar threshold."""
223
def __init__(self, metric_map, threshold):
224
"""
225
Initialize threshold classifier.
226
227
Parameters:
228
metric_map (array): scalar map (e.g., FA)
229
threshold (float): classification threshold
230
"""
231
232
class BinaryClassifier:
233
"""Binary tissue classifier."""
234
def __init__(self, mask):
235
"""Initialize with binary mask."""
236
237
class ACTClassifier:
238
"""Anatomically Constrained Tractography classifier."""
239
def __init__(self, include_map, exclude_map=None):
240
"""
241
Initialize ACT classifier.
242
243
Parameters:
244
include_map (array): inclusion probability map
245
exclude_map (array): exclusion probability map
246
"""
247
```
248
249
### Streamline Utilities
250
251
Utility functions for streamline processing and analysis.
252
253
```python { .api }
254
def set_number_of_points(streamlines, nb_points=3):
255
"""
256
Resample streamlines to fixed number of points.
257
258
Parameters:
259
streamlines: input streamlines
260
nb_points (int): target number of points
261
262
Returns:
263
list: resampled streamlines
264
"""
265
266
def length(streamlines):
267
"""
268
Calculate streamline lengths.
269
270
Parameters:
271
streamlines: input streamlines
272
273
Returns:
274
array: streamline lengths in mm
275
"""
276
277
def transform_streamlines(streamlines, mat, in_place=False):
278
"""
279
Transform streamlines by affine matrix.
280
281
Parameters:
282
streamlines: input streamlines
283
mat (array): 4x4 transformation matrix
284
in_place (bool): modify streamlines in place
285
286
Returns:
287
list: transformed streamlines
288
"""
289
290
def select_random_set_of_streamlines(streamlines, select):
291
"""
292
Randomly select subset of streamlines.
293
294
Parameters:
295
streamlines: input streamlines
296
select (int): number to select
297
298
Returns:
299
list: selected streamlines
300
"""
301
```
302
303
### Usage Examples
304
305
```python
306
# Complete tractography workflow
307
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, auto_response_ssst
308
from dipy.direction import DeterministicMaximumDirectionGetter
309
from dipy.tracking.local import LocalTracking, ThresholdClassifier
310
from dipy.tracking.streamline import Streamlines
311
from dipy.data import read_stanford_hardi, get_sphere
312
import numpy as np
313
314
# Load and prepare data
315
img, gtab = read_stanford_hardi()
316
data = img.get_fdata()
317
318
# Fit CSD model for fiber orientations
319
response, ratio = auto_response_ssst(gtab, data)
320
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
321
csd_fit = csd_model.fit(data)
322
323
# Extract peaks for direction getting
324
sphere = get_sphere('symmetric724')
325
from dipy.direction import peaks_from_model
326
327
peaks = peaks_from_model(csd_model, data, sphere,
328
relative_peak_threshold=0.5,
329
min_separation_angle=25,
330
npeaks=2)
331
332
# Set up direction getter and classifier
333
dg = DeterministicMaximumDirectionGetter.from_shm(peaks.shm_coeff,
334
max_angle=30,
335
sphere=sphere)
336
337
# Use FA for tracking termination
338
from dipy.reconst.dti import TensorModel
339
tensor_model = TensorModel(gtab)
340
tensor_fit = tensor_model.fit(data)
341
fa = tensor_fit.fa
342
343
classifier = ThresholdClassifier(fa, 0.1)
344
345
# Generate seeds throughout the brain
346
from dipy.tracking import utils
347
seeds = utils.seeds_from_mask(fa > 0.3, affine=img.affine, density=1)
348
349
# Perform tractography
350
streamlines = LocalTracking(dg, classifier, seeds, img.affine,
351
step_size=0.5, return_all=False)
352
353
# Convert to streamlines object
354
streamlines = Streamlines(streamlines)
355
356
print(f"Generated {len(streamlines)} streamlines")
357
358
# Filter by length
359
from dipy.tracking.streamline import length
360
lengths = length(streamlines)
361
long_streamlines = [s for s, l in zip(streamlines, lengths) if l > 20]
362
363
print(f"Kept {len(long_streamlines)} streamlines longer than 20mm")
364
365
# Probabilistic tractography
366
from dipy.direction import ProbabilisticDirectionGetter
367
368
prob_dg = ProbabilisticDirectionGetter.from_shm(peaks.shm_coeff,
369
max_angle=30,
370
sphere=sphere)
371
372
prob_streamlines = LocalTracking(prob_dg, classifier, seeds[:1000],
373
img.affine, step_size=0.5)
374
375
prob_streamlines = Streamlines(prob_streamlines)
376
print(f"Probabilistic tracking generated {len(prob_streamlines)} streamlines")
377
```