-
Notifications
You must be signed in to change notification settings - Fork 51
/
ants.py
513 lines (443 loc) · 19.7 KB
/
ants.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Nipype interfaces for ANTs commands
"""
import os
from glob import glob
from nipype.interfaces import base
from nipype.interfaces.ants.base import ANTSCommandInputSpec, ANTSCommand
from nipype.interfaces.base import traits, isdefined
class ImageMathInputSpec(ANTSCommandInputSpec):
dimension = traits.Int(3, usedefault=True, position=1, argstr='%d',
desc='dimension of output image')
output_image = base.File(position=2, argstr='%s', name_source=['op1'],
name_template='%s_maths', desc='output image file',
keep_extension=True)
operation = base.Str(mandatory=True, position=3, argstr='%s',
desc='operations and intputs')
op1 = base.File(exists=True, mandatory=True, position=-2, argstr='%s',
desc='first operator')
op2 = traits.Either(base.File(exists=True), base.Str, position=-1,
argstr='%s', desc='second operator')
class ImageMathOuputSpec(base.TraitedSpec):
output_image = base.File(exists=True, desc='output image file')
class ImageMath(ANTSCommand):
"""
Operations over images
Example:
--------
"""
_cmd = 'ImageMath'
input_spec = ImageMathInputSpec
output_spec = ImageMathOuputSpec
class ResampleImageBySpacingInputSpec(ANTSCommandInputSpec):
dimension = traits.Int(3, usedefault=True, position=1, argstr='%d',
desc='dimension of output image')
input_image = base.File(exists=True, mandatory=True, position=2, argstr='%s',
desc='input image file')
output_image = base.File(position=3, argstr='%s', name_source=['input_image'],
name_template='%s_resampled', desc='output image file',
keep_extension=True)
out_spacing = traits.Either(
traits.List(traits.Float, minlen=2, maxlen=3),
traits.Tuple(traits.Float, traits.Float, traits.Float),
traits.Tuple(traits.Float, traits.Float),
position=4, argstr='%s', mandatory=True, desc='output spacing'
)
apply_smoothing = traits.Bool(False, argstr='%d', position=5,
desc='smooth before resampling')
addvox = traits.Int(argstr='%d', position=6, requires=['apply_smoothing'],
desc='addvox pads each dimension by addvox')
nn_interp = traits.Bool(argstr='%d', desc='nn interpolation',
position=-1, requires=['addvox'])
class ResampleImageBySpacingOutputSpec(base.TraitedSpec):
output_image = traits.File(exists=True, desc='resampled file')
class ResampleImageBySpacing(ANTSCommand):
"""
Resamples an image with a given spacing
Example:
--------
>>> res = ResampleImageBySpacing(dimension=3)
>>> res.inputs.input_image = 'input.nii.gz'
>>> res.inputs.output_image = 'output.nii.gz'
>>> res.inputs.out_spacing = (4, 4, 4)
'ResampleImageBySpacing input.nii.gz output.nii.gz 4 4 4'
>>> res = ResampleImageBySpacing(dimension=3)
>>> res.inputs.input_image = 'input.nii.gz'
>>> res.inputs.output_image = 'output.nii.gz'
>>> res.inputs.out_spacing = (4, 4, 4)
>>> res.inputs.apply_smoothing = True
'ResampleImageBySpacing input.nii.gz output.nii.gz 4 4 4 1'
>>> res = ResampleImageBySpacing(dimension=3)
>>> res.inputs.input_image = 'input.nii.gz'
>>> res.inputs.output_image = 'output.nii.gz'
>>> res.inputs.out_spacing = (4, 4, 4)
>>> res.inputs.apply_smoothing = True
>>> res.inputs.addvox = 2
>>> res.inputs.nn_interp = False
'ResampleImageBySpacing input.nii.gz output.nii.gz 4 4 4 1 2 0'
"""
_cmd = 'ResampleImageBySpacing'
input_spec = ResampleImageBySpacingInputSpec
output_spec = ResampleImageBySpacingOutputSpec
def _format_arg(self, name, trait_spec, value):
if name == 'out_spacing':
if len(value) != self.inputs.dimension:
raise ValueError('out_spacing dimensions should match dimension')
value = ' '.join(['%d' % d for d in value])
return super(ResampleImageBySpacing, self)._format_arg(
name, trait_spec, value)
class ThresholdImageInputSpec(ANTSCommandInputSpec):
dimension = traits.Int(3, usedefault=True, position=1, argstr='%d',
desc='dimension of output image')
input_image = base.File(exists=True, mandatory=True, position=2, argstr='%s',
desc='input image file')
output_image = base.File(position=3, argstr='%s', name_source=['input_image'],
name_template='%s_resampled', desc='output image file',
keep_extension=True)
mode = traits.Enum('Otsu', 'Kmeans', argstr='%s', position=4,
requires=['num_thresholds'], xor=['th_low', 'th_high'],
desc='whether to run Otsu / Kmeans thresholding')
num_thresholds = traits.Int(position=5, argstr='%d',
desc='number of thresholds')
input_mask = base.File(exists=True, requires=['num_thresholds'], argstr='%s',
desc='input mask for Otsu, Kmeans')
th_low = traits.Float(position=4, argstr='%f', xor=['mode'],
desc='lower threshold')
th_high = traits.Float(position=5, argstr='%f', xor=['mode'],
desc='upper threshold')
inside_value = traits.Float(1, position=6, argstr='%f', requires=['th_low'],
desc='inside value')
outside_value = traits.Float(0, position=7, argstr='%f', requires=['th_low'],
desc='outside value')
class ThresholdImageOutputSpec(base.TraitedSpec):
output_image = traits.File(exists=True, desc='resampled file')
class ThresholdImage(ANTSCommand):
"""
Apply thresholds on images
Example:
--------
>>> res = ThresholdImage(dimension=3)
>>> res.inputs.input_image = 'input.nii.gz'
>>> res.inputs.output_image = 'output.nii.gz'
>>> res.inputs.th_low = 0.5
>>> res.inputs.th_high = 1.0
>>> res.inputs.inside_val = 1.0
>>> res.inputs.outside_val = 0.0
'ThresholdImage input.nii.gz output.nii.gz 0.50000 1.00000 1.00000 0.00000'
>>> res = ThresholdImage(dimension=3)
>>> res.inputs.input_image = 'input.nii.gz'
>>> res.inputs.output_image = 'output.nii.gz'
>>> res.inputs.mode = 'Kmeans'
>>> res.inputs.num_thresholds = 4
'ThresholdImage input.nii.gz output.nii.gz Kmeans 4'
"""
_cmd = 'ThresholdImage'
input_spec = ThresholdImageInputSpec
output_spec = ThresholdImageOutputSpec
class AIInputSpec(ANTSCommandInputSpec):
dimension = traits.Int(3, usedefault=True, argstr='-d %d',
desc='dimension of output image')
verbose = traits.Bool(False, usedefault=True, argstr='-v %d',
desc='enable verbosity')
fixed_image = traits.File(
exists=True, mandatory=True,
desc='Image to which the moving_image should be transformed')
moving_image = traits.File(
exists=True, mandatory=True,
desc='Image that will be transformed to fixed_image')
fixed_image_mask = traits.File(
exists=True, argstr='-x %s', desc='fixed mage mask')
moving_image_mask = traits.File(
exists=True, requires=['fixed_image_mask'],
desc='moving mage mask')
metric_trait = (
traits.Enum("Mattes", "GC", "MI"),
traits.Int(32),
traits.Enum('Regular', 'Random', 'None'),
traits.Range(value=0.2, low=0.0, high=1.0)
)
metric = traits.Tuple(*metric_trait, argstr='-m %s', mandatory=True,
desc='the metric(s) to use.')
transform = traits.Tuple(
traits.Enum('Affine', 'Rigid', 'Similarity'),
traits.Range(value=0.1, low=0.0, exclude_low=True),
argstr='-t %s[%f]', usedefault=True,
desc='Several transform options are available')
principal_axes = traits.Bool(False, usedefault=True, argstr='-p %d', xor=['blobs'],
desc='align using principal axes')
search_factor = traits.Tuple(
traits.Float(20), traits.Range(value=0.12, low=0.0, high=1.0),
usedefault=True, argstr='-s [%f,%f]', desc='search factor')
search_grid = traits.Either(
traits.Tuple(traits.Float, traits.Tuple(traits.Float, traits.Float, traits.Float)),
traits.Tuple(traits.Float, traits.Tuple(traits.Float, traits.Float)),
argstr='-g %s', desc='Translation search grid in mm')
convergence = traits.Tuple(
traits.Range(low=1, high=10000, value=10),
traits.Float(1e-6),
traits.Range(low=1, high=100, value=10),
usedefault=True, argstr='-c [%d,%f,%d]', desc='convergence')
output_transform = traits.File(
'initialization.mat', usedefault=True, argstr='-o %s',
desc='output file name')
class AIOuputSpec(base.TraitedSpec):
output_transform = traits.File(exists=True, desc='output file name')
class AI(ANTSCommand):
"""
The replacement for ``AffineInitializer``.
Example:
--------
"""
_cmd = 'antsAI'
input_spec = AIInputSpec
output_spec = AIOuputSpec
def _run_interface(self, runtime, correct_return_codes=(0, )):
runtime = super(AI, self)._run_interface(
runtime, correct_return_codes)
setattr(self, '_output', {
'output_transform': os.path.join(
runtime.cwd,
os.path.basename(self.inputs.output_transform))
})
return runtime
def _format_arg(self, opt, spec, val):
if opt == 'metric':
val = '%s[{fixed_image},{moving_image},%d,%s,%f]' % val
val = val.format(
fixed_image=self.inputs.fixed_image,
moving_image=self.inputs.moving_image)
return spec.argstr % val
if opt == 'search_grid':
val1 = 'x'.join(['%f' % v for v in val[1]])
fmtval = '[%s]' % ','.join([str(val[0]), val1])
return spec.argstr % fmtval
if opt == 'fixed_image_mask':
if isdefined(self.inputs.moving_image_mask):
return spec.argstr % ('[%s,%s]' % (
val, self.inputs.moving_image_mask))
return super(AI, self)._format_arg(opt, spec, val)
def _list_outputs(self):
return getattr(self, '_output')
class AntsJointFusionInputSpec(ANTSCommandInputSpec):
dimension = traits.Enum(
3,
2,
4,
argstr='-d %d',
desc='This option forces the image to be treated '
'as a specified-dimensional image. If not '
'specified, the program tries to infer the '
'dimensionality from the input image.')
target_image = traits.List(
base.InputMultiPath(base.File(exists=True)),
argstr='-t %s',
mandatory=True,
desc='The target image (or '
'multimodal target images) assumed to be '
'aligned to a common image domain.')
atlas_image = traits.List(
base.InputMultiPath(base.File(exists=True)),
argstr="-g %s...",
mandatory=True,
desc='The atlas image (or '
'multimodal atlas images) assumed to be '
'aligned to a common image domain.')
atlas_segmentation_image = base.InputMultiPath(
base.File(exists=True),
argstr="-l %s...",
mandatory=True,
desc='The atlas segmentation '
'images. For performing label fusion the number '
'of specified segmentations should be identical '
'to the number of atlas image sets.')
alpha = traits.Float(
default_value=0.1,
usedefault=True,
argstr='-a %s',
desc=(
'Regularization '
'term added to matrix Mx for calculating the inverse. Default = 0.1'
))
beta = traits.Float(
default_value=2.0,
usedefault=True,
argstr='-b %s',
desc=('Exponent for mapping '
'intensity difference to the joint error. Default = 2.0'))
retain_label_posterior_images = traits.Bool(
False,
argstr='-r',
usedefault=True,
requires=['atlas_segmentation_image'],
desc=('Retain label posterior probability images. Requires '
'atlas segmentations to be specified. Default = false'))
retain_atlas_voting_images = traits.Bool(
False,
argstr='-f',
usedefault=True,
desc=('Retain atlas voting images. Default = false'))
constrain_nonnegative = traits.Bool(
False,
argstr='-c',
usedefault=True,
desc=('Constrain solution to non-negative weights.'))
patch_radius = traits.ListInt(
minlen=3,
maxlen=3,
argstr='-p %s',
desc=('Patch radius for similarity measures.'
'Default: 2x2x2'))
patch_metric = traits.Enum(
'PC',
'MSQ',
argstr='-m %s',
desc=('Metric to be used in determining the most similar '
'neighborhood patch. Options include Pearson\'s '
'correlation (PC) and mean squares (MSQ). Default = '
'PC (Pearson correlation).'))
search_radius = traits.List(
[3, 3, 3],
minlen=1,
maxlen=3,
argstr='-s %s',
usedefault=True,
desc=('Search radius for similarity measures. Default = 3x3x3. '
'One can also specify an image where the value at the '
'voxel specifies the isotropic search radius at that voxel.'))
exclusion_image_label = traits.List(
traits.Str(),
argstr='-e %s',
requires=['exclusion_image'],
desc=('Specify a label for the exclusion region.'))
exclusion_image = traits.List(
base.File(exists=True),
desc=('Specify an exclusion region for the given label.'))
mask_image = base.File(
argstr='-x %s',
exists=True,
desc='If a mask image '
'is specified, fusion is only performed in the mask region.')
out_label_fusion = base.File(
argstr="%s", hash_files=False, desc='The output label fusion image.')
out_intensity_fusion_name_format = traits.Str(
argstr="",
desc='Optional intensity fusion '
'image file name format. '
'(e.g. "antsJointFusionIntensity_%d.nii.gz")')
out_label_post_prob_name_format = traits.Str(
'antsJointFusionPosterior_%d.nii.gz',
requires=['out_label_fusion', 'out_intensity_fusion_name_format'],
desc='Optional label posterior probability '
'image file name format.')
out_atlas_voting_weight_name_format = traits.Str(
'antsJointFusionVotingWeight_%d.nii.gz',
requires=[
'out_label_fusion', 'out_intensity_fusion_name_format',
'out_label_post_prob_name_format'
],
desc='Optional atlas voting weight image '
'file name format.')
verbose = traits.Bool(False, argstr="-v", desc=('Verbose output.'))
class AntsJointFusionOutputSpec(base.TraitedSpec):
out_label_fusion = base.File(exists=True)
out_intensity_fusion = base.OutputMultiPath(
base.File(exists=True))
out_label_post_prob = base.OutputMultiPath(
base.File(exists=True))
out_atlas_voting_weight = base.OutputMultiPath(
base.File(exists=True))
class AntsJointFusion(ANTSCommand):
"""
"""
input_spec = AntsJointFusionInputSpec
output_spec = AntsJointFusionOutputSpec
_cmd = 'antsJointFusion'
def _format_arg(self, opt, spec, val):
if opt == 'exclusion_image_label':
retval = []
for ii in range(len(self.inputs.exclusion_image_label)):
retval.append(
'-e {0}[{1}]'.format(self.inputs.exclusion_image_label[ii],
self.inputs.exclusion_image[ii]))
retval = ' '.join(retval)
elif opt == 'patch_radius':
retval = '-p {0}'.format(self._format_xarray(val))
elif opt == 'search_radius':
retval = '-s {0}'.format(self._format_xarray(val))
elif opt == 'out_label_fusion':
if isdefined(self.inputs.out_intensity_fusion_name_format):
if isdefined(self.inputs.out_label_post_prob_name_format):
if isdefined(
self.inputs.out_atlas_voting_weight_name_format):
retval = '-o [{0}, {1}, {2}, {3}]'.format(
self.inputs.out_label_fusion,
self.inputs.out_intensity_fusion_name_format,
self.inputs.out_label_post_prob_name_format,
self.inputs.out_atlas_voting_weight_name_format)
else:
retval = '-o [{0}, {1}, {2}]'.format(
self.inputs.out_label_fusion,
self.inputs.out_intensity_fusion_name_format,
self.inputs.out_label_post_prob_name_format)
else:
retval = '-o [{0}, {1}]'.format(
self.inputs.out_label_fusion,
self.inputs.out_intensity_fusion_name_format)
else:
retval = '-o {0}'.format(self.inputs.out_label_fusion)
elif opt == 'out_intensity_fusion_name_format':
retval = ''
if not isdefined(self.inputs.out_label_fusion):
retval = '-o {0}'.format(
self.inputs.out_intensity_fusion_name_format)
elif opt == 'atlas_image':
atlas_image_cmd = " ".join([
'-g [{0}]'.format(", ".join("'%s'" % fn for fn in ai))
for ai in self.inputs.atlas_image
])
retval = atlas_image_cmd
elif opt == 'target_image':
target_image_cmd = " ".join([
'-t [{0}]'.format(", ".join("'%s'" % fn for fn in ai))
for ai in self.inputs.target_image
])
retval = target_image_cmd
elif opt == 'atlas_segmentation_image':
if len(val) != len(self.inputs.atlas_image):
raise ValueError(
"Number of specified segmentations should be identical to the number "
"of atlas image sets {0}!={1}".format(
len(val), len(self.inputs.atlas_image)))
atlas_segmentation_image_cmd = " ".join([
'-l {0}'.format(fn)
for fn in self.inputs.atlas_segmentation_image
])
retval = atlas_segmentation_image_cmd
else:
return super(AntsJointFusion, self)._format_arg(opt, spec, val)
return retval
def _list_outputs(self):
outputs = self._outputs().get()
if isdefined(self.inputs.out_label_fusion):
outputs['out_label_fusion'] = os.path.abspath(
self.inputs.out_label_fusion)
if isdefined(self.inputs.out_intensity_fusion_name_format):
outputs['out_intensity_fusion'] = glob(os.path.abspath(
self.inputs.out_intensity_fusion_name_format.replace(
'%d', '*'))
)
if isdefined(self.inputs.out_label_post_prob_name_format):
outputs['out_label_post_prob'] = glob(os.path.abspath(
self.inputs.out_label_post_prob_name_format.replace(
'%d', '*'))
)
if isdefined(self.inputs.out_atlas_voting_weight_name_format):
outputs['out_atlas_voting_weight'] = glob(os.path.abspath(
self.inputs.out_atlas_voting_weight_name_format.replace(
'%d', '*'))
)
return outputs