-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
sct_dmri_compute_dti.py
executable file
·208 lines (183 loc) · 6.47 KB
/
sct_dmri_compute_dti.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python
#########################################################################################
#
# Compute DTI.
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2015 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: Julien Cohen-Adad
#
# About the license: see the file LICENSE.TXT
#########################################################################################
from __future__ import absolute_import
import os, sys, argparse
import sct_utils as sct
from spinalcordtoolbox.utils import Metavar, SmartFormatter
class Param:
def __init__(self):
self.verbose = 1
# PARSER
# ==========================================================================================
def get_parser():
param = Param()
# Initialize the parser
parser = argparse.ArgumentParser(
description='Compute Diffusion Tensor Images (DTI) using dipy.',
formatter_class=SmartFormatter,
add_help=None,
prog=os.path.basename(__file__).strip(".py"))
mandatory = parser.add_argument_group("MANDATORY ARGMENTS")
mandatory.add_argument(
"-i",
required=True,
help='Input 4d file. Example: dmri.nii.gz',
metavar=Metavar.file,
)
mandatory.add_argument(
"-bval",
required=True,
help='Bvals file. Example: bvals.txt',
metavar=Metavar.file,
)
mandatory.add_argument(
"-bvec",
required=True,
help='Bvecs file. Example: bvecs.txt',
metavar=Metavar.file,
)
optional = parser.add_argument_group("OPTIONAL ARGUMENTS")
optional.add_argument(
"-h",
"--help",
action="help",
help="Show this help message and exit")
optional.add_argument(
'-method',
help='R|Type of method to calculate the diffusion tensor:\n'
' standard: Standard equation [Basser, Biophys J 1994]\n'
' restore: Robust fitting with outlier detection [Chang, MRM 2005]',
default='standard',
choices=('standard', 'restore'))
optional.add_argument(
"-evecs",
type=int,
help='Output tensor eigenvectors and eigenvalues.',
default=0,
choices=(0, 1))
optional.add_argument(
'-m',
metavar=Metavar.file,
help='Mask used to compute DTI in for faster processing. Example: mask.nii.gz')
optional.add_argument(
'-o',
help='Output prefix.',
metavar=Metavar.str,
required=False,
default='dti_')
optional.add_argument(
"-v",
help="Verbose. 0: nothing. 1: basic. 2: extended.",
type=int,
required=False,
default=param.verbose,
choices=(0, 1, 2))
return parser
# MAIN
# ==========================================================================================
def main(args=None):
# initialization
file_mask = ''
# Get parser info
parser = get_parser()
arguments = parser.parse_args(args=None if sys.argv[1:] else ['--help'])
fname_in = arguments.i
fname_bvals = arguments.bval
fname_bvecs = arguments.bvec
prefix = arguments.o
method = arguments.method
evecs = arguments.evecs
if arguments.m is not None:
file_mask = arguments.m
param.verbose = arguments.v
sct.init_sct(log_level=param.verbose, update=True) # Update log level
# compute DTI
if not compute_dti(fname_in, fname_bvals, fname_bvecs, prefix, method, evecs, file_mask):
sct.printv('ERROR in compute_dti()', 1, 'error')
# compute_dti
# ==========================================================================================
def compute_dti(fname_in, fname_bvals, fname_bvecs, prefix, method, evecs, file_mask):
"""
Compute DTI.
:param fname_in: input 4d file.
:param bvals: bvals txt file
:param bvecs: bvecs txt file
:param prefix: output prefix. Example: "dti_"
:param method: algo for computing dti
:param evecs: bool: output diffusion tensor eigenvectors and eigenvalues
:return: True/False
"""
# Open file.
from spinalcordtoolbox.image import Image
nii = Image(fname_in)
data = nii.data
sct.printv('data.shape (%d, %d, %d, %d)' % data.shape)
# open bvecs/bvals
from dipy.io import read_bvals_bvecs
bvals, bvecs = read_bvals_bvecs(fname_bvals, fname_bvecs)
from dipy.core.gradients import gradient_table
gtab = gradient_table(bvals, bvecs)
# mask and crop the data. This is a quick way to avoid calculating Tensors on the background of the image.
if not file_mask == '':
sct.printv('Open mask file...', param.verbose)
# open mask file
nii_mask = Image(file_mask)
mask = nii_mask.data
# fit tensor model
sct.printv('Computing tensor using "' + method + '" method...', param.verbose)
import dipy.reconst.dti as dti
if method == 'standard':
tenmodel = dti.TensorModel(gtab)
if file_mask == '':
tenfit = tenmodel.fit(data)
else:
tenfit = tenmodel.fit(data, mask)
elif method == 'restore':
import dipy.denoise.noise_estimate as ne
sigma = ne.estimate_sigma(data)
dti_restore = dti.TensorModel(gtab, fit_method='RESTORE', sigma=sigma)
if file_mask == '':
tenfit = dti_restore.fit(data)
else:
tenfit = dti_restore.fit(data, mask)
# Compute metrics
sct.printv('Computing metrics...', param.verbose)
# FA
nii.data = tenfit.fa
nii.save(prefix + 'FA.nii.gz', dtype='float32')
# MD
nii.data = tenfit.md
nii.save(prefix + 'MD.nii.gz', dtype='float32')
# RD
nii.data = tenfit.rd
nii.save(prefix + 'RD.nii.gz', dtype='float32')
# AD
nii.data = tenfit.ad
nii.save(prefix + 'AD.nii.gz', dtype='float32')
if evecs:
data_evecs = tenfit.evecs
data_evals = tenfit.evals
# output 1st (V1), 2nd (V2) and 3rd (V3) eigenvectors as 4d data
for idim in range(3):
nii.data = data_evecs[:, :, :, :, idim]
nii.save(prefix + 'V' + str(idim + 1) + '.nii.gz', dtype="float32")
nii.data = data_evals[:, :, :, idim]
nii.save(prefix + 'E' + str(idim + 1) + '.nii.gz', dtype="float32")
return True
# START PROGRAM
# ==========================================================================================
if __name__ == "__main__":
sct.init_sct()
# initialize parameters
param = Param()
# call main function
main()