forked from bids-apps/MRtrix3_connectome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mrtrix3_connectome.py
executable file
·4191 lines (3801 loc) · 185 KB
/
mrtrix3_connectome.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import glob
import json
import math
import os
import re
import shutil
from collections import namedtuple
from distutils.spawn import find_executable
import mrtrix3 #pylint: disable=import-error
from mrtrix3 import CONFIG, MRtrixError #pylint: disable=import-error
from mrtrix3 import app, fsl, image, matrix, path, run, utils #pylint: disable=import-error
IS_CONTAINER = os.path.exists('/version') \
and os.path.exists('/mrtrix3_version')
__version__ = 'BIDS-App \'MRtrix3_connectome\' version {}' \
.format(open('/version').read()) \
if IS_CONTAINER \
else 'BIDS-App \'MRtrix3_connectome\' standalone'
OPTION_PREFIX = '--' if IS_CONTAINER else '-'
OUT_DWI_JSON_DATA = {'SkullStripped': False}
OUT_5TT_JSON_DATA = {'LabelMap': ['CGM', 'SGM', 'WM', 'CSF', 'Path']}
# Use a threshold on the balanced tissue sum image
# as a replacement of dwi2mask within the iterative
# bias field correction / brain masking loop in preprpoc
TISSUESUM_THRESHOLD = 0.5 / math.sqrt(4.0 * math.pi)
# Seem that for problematic data, running more than two iterations may
# cause divergence from the ideal mask; therefore cap at two iterations
DWIBIASCORRECT_MAX_ITERS = 2
class T1wShared(object): #pylint: disable=useless-object-inheritance
def __init__(self):
try:
self.fsl_anat_cmd = find_executable(fsl.exe_name('fsl_anat'))
except MRtrixError:
self.fsl_anat_cmd = None
if find_executable('ROBEX'):
self.robex_cmd = find_executable('runROBEX.sh')
else:
self.robex_cmd = None
self.N4_cmd = find_executable('N4BiasFieldCorrection')
if not self.fsl_anat_cmd and not self.robex_cmd:
app.warn('No commands for T1 image processing found; '
'will be unable to proceed for any session without '
'pre-processed T1-weighted data')
class PreprocShared(object): #pylint: disable=useless-object-inheritance
def __init__(self):
fsl_path = os.environ.get('FSLDIR', '')
if not fsl_path:
raise MRtrixError(
'Environment variable FSLDIR is not set; '
'please run appropriate FSL configuration script')
self.t1w_shared = T1wShared()
self.dwibiascorrect_algo = 'ants'
if not self.t1w_shared.N4_cmd:
self.dwibiascorrect_algo = None
app.warn('Could not find ANTs program "N4BiasFieldCorrection"; '
'will proceed without performing initial b=0 - based '
'DWI bias field correction')
def get_eddy_help(binary_name):
try:
return run.command([binary_name, '--help'], show=False).stderr
except run.MRtrixCmdError as eddy_except:
return eddy_except.stderr
self.eddy_binary = fsl.eddy_binary(True)
if self.eddy_binary:
self.eddy_cuda = True
eddy_help = get_eddy_help(self.eddy_binary)
if 'error while loading shared libraries' in eddy_help:
app.warn('CUDA version of FSL "eddy" present on system, '
'but does not execute successfully; OpenMP version '
'will instead be used')
self.eddy_binary = None
self.eddy_cuda = False
eddy_help = ''
if not self.eddy_binary:
self.eddy_binary = fsl.eddy_binary(False)
if not self.eddy_binary:
raise MRtrixError('Could not find FSL program "eddy"')
self.eddy_cuda = False
eddy_help = get_eddy_help(self.eddy_binary)
app.debug('Eddy binary: ' + str(self.eddy_binary))
app.debug('Eddy is CUDA version: ' + str(self.eddy_cuda))
self.eddy_repol = False
self.eddy_mporder = False
self.eddy_mbs = False
for line in eddy_help.splitlines():
line = line.lstrip()
if line.startswith('--repol'):
self.eddy_repol = True
elif line.startswith('--mporder') and self.eddy_cuda:
self.eddy_mporder = True
elif line.startswith('--estimate_move_by_susceptibility'):
self.eddy_mbs = True
# End of PreprocShared() class
class ParticipantShared(object): #pylint: disable=useless-object-inheritance
def __init__(self, atlas_path, parcellation,
streamlines, template_reg):
if not parcellation:
raise MRtrixError(
'For participant-level analysis, '
'desired parcellation must be provided using the '
+ OPTION_PREFIX + 'parcellation option')
self.parcellation = parcellation
self.streamlines = streamlines
fsl_path = os.environ.get('FSLDIR', '')
if not fsl_path:
raise MRtrixError(
'Environment variable FSLDIR is not set; '
'please run appropriate FSL configuration script')
self.t1w_shared = T1wShared()
self.do_freesurfer = parcellation in ['brainnetome246fs',
'desikan',
'destrieux',
'hcpmmp1',
'yeo7fs',
'yeo17fs']
self.do_mni = parcellation in ['aal',
'aal2',
'brainnetome246mni',
'craddock200',
'craddock400',
'perry512',
'yeo7mni',
'yeo17mni']
if parcellation != 'none':
assert self.do_freesurfer or self.do_mni
if template_reg:
if self.do_mni:
self.template_registration_software = template_reg
else:
app.warn('Volumetric template registration '
'not being performed; '
+ OPTION_PREFIX + 'template_reg option ignored')
self.template_registration_software = ''
else:
self.template_registration_software = 'ants' if self.do_mni else ''
if self.template_registration_software == 'ants':
if not find_executable('antsRegistration') \
or not find_executable('antsApplyTransforms'):
raise MRtrixError(
'Commands \'antsRegistration\' and \'antsApplyTransforms\' '
'must be present in PATH to use '
'ANTs software for template registration')
elif self.template_registration_software == 'fsl':
self.flirt_cmd = fsl.exe_name('flirt')
self.fnirt_cmd = fsl.exe_name('fnirt')
self.invwarp_cmd = fsl.exe_name('invwarp')
self.applywarp_cmd = fsl.exe_name('applywarp')
self.fnirt_config_basename = 'T1_2_MNI152_2mm.cnf'
self.fnirt_config_path = os.path.join(fsl_path,
'etc',
'flirtsch',
self.fnirt_config_basename)
if not os.path.isfile(self.fnirt_config_path):
raise MRtrixError(
'Unable to find configuration file for FNI FNIRT '
+ '(expected location: '
+ self.fnirt_config_path + ')')
self.template_image_path = ''
self.template_mask_path = ''
self.parc_image_path = ''
self.parc_lut_file = ''
self.mrtrix_lut_file = ''
mrtrix_lut_dir = os.path.normpath(
os.path.join(
os.path.dirname(os.path.abspath(app.__file__)),
os.pardir,
os.pardir,
'share',
'mrtrix3',
'labelconvert'))
if self.do_freesurfer:
self.freesurfer_home = os.environ.get('FREESURFER_HOME', None)
if not self.freesurfer_home:
raise MRtrixError(
'Environment variable FREESURFER_HOME not set; '
'please verify FreeSurfer installation')
if not find_executable('recon-all'):
raise MRtrixError(
'Could not find FreeSurfer script "recon-all"; '
'please verify FreeSurfer installation')
self.freesurfer_subjects_dir = os.environ['SUBJECTS_DIR'] \
if 'SUBJECTS_DIR' in os.environ \
else os.path.join(
self.freesurfer_home,
'subjects')
if not os.path.isdir(self.freesurfer_subjects_dir):
raise MRtrixError(
'Could not find FreeSurfer subjects directory '
'(expected location: '
+ self.freesurfer_subjects_dir + ')')
for subdir in ['fsaverage',
'fsaverage5',
'lh.EC_average',
'rh.EC_average']:
if not os.path.isdir(os.path.join(self.freesurfer_subjects_dir,
subdir)):
raise MRtrixError(
'Could not find requisite FreeSurfer subject '
'directory \'' + subdir + '\' '
'(expected location: '
+ os.path.join(self.freesurfer_subjects_dir,
subdir) + ')')
self.reconall_path = find_executable('recon-all')
if not self.reconall_path:
raise MRtrixError(
'Could not find FreeSurfer script "recon-all"; '
'please verify FreeSurfer installation')
if parcellation in ['hcpmmp1', 'yeo7fs', 'yeo17fs']:
if parcellation == 'hcpmmp1':
def hcpmmp_annot_path(hemi):
return os.path.join(self.freesurfer_subjects_dir,
'fsaverage',
'label',
hemi + 'h.HCPMMP1.annot')
self.hcpmmp1_annot_paths = [hcpmmp_annot_path(hemi)
for hemi in ['l', 'r']]
if not all([os.path.isfile(path) \
for path in self.hcpmmp1_annot_paths]):
raise MRtrixError(
'Could not find necessary annotation labels '
'for applying HCPMMP1 parcellation '
'(expected location: '
+ hcpmmp_annot_path('?') + ')')
else: # yeo7fs, yeo17fs
def yeo_annot_path(hemi):
return os.path.join(
self.freesurfer_subjects_dir,
'fsaverage5',
'label',
hemi + 'h.Yeo2011_'
+ ('7' if parcellation == 'yeo7fs' else '17')
+ 'Networks_N1000.split_components.annot')
self.yeo_annot_paths = [yeo_annot_path(hemi) \
for hemi in ['l', 'r']]
if not all([os.path.isfile(path) \
for path in self.yeo_annot_paths]):
raise MRtrixError(
'Could not find necessary annotation labels '
'for applying Yeo2011 parcellation '
'(expected location: '
+ yeo_annot_path('?') + ')')
for cmd in ['mri_surf2surf', 'mri_aparc2aseg']:
if not find_executable(cmd):
raise MRtrixError(
'Could not find FreeSurfer command '
+ cmd + ' '
'(necessary for applying '
'HCPMMP1 parcellation); '
'please verify FreeSurfer installation')
elif parcellation == 'brainnetome246fs':
def brainnetome_gcs_path(hemi):
return os.path.join(self.freesurfer_home,
'average',
hemi + 'h.BN_Atlas.gcs')
self.brainnetome_cortex_gcs_paths = [
brainnetome_gcs_path(hemi)
for hemi in ['l', 'r']]
if not all([os.path.isfile(path)
for path in self.brainnetome_cortex_gcs_paths]):
raise MRtrixError(
'Could not find necessary GCS files for '
'applying Brainnetome cortical parcellation via '
'FreeSurfer (expected location: '
+ brainnetome_gcs_path('?') + ')')
self.brainnetome_sgm_gca_path = \
os.path.join(self.freesurfer_home,
'average',
'BN_Atlas_subcortex.gca')
if not os.path.isfile(self.brainnetome_sgm_gca_path):
raise MRtrixError(
'Could not find necessary GCA file for applying '
'Brainnetome sub-cortical parcellation '
'via FreeSurfer (expected location: '
+ self.brainnetome_sgm_gca_path + ')')
for cmd in ['mri_label2vol',
'mri_ca_label',
'mris_ca_label']:
if not find_executable(cmd):
raise MRtrixError(
'Could not find FreeSurfer command '
+ cmd + ' '
'(necessary for applying '
'Brainnetome parcellation); '
'please verify FreeSurfer installation')
# Query contents of recon-all script,
# looking for "-openmp" and "-parallel" occurences
# Add options to end of recon-all -all call,
# based on which of these options are available
# as well as the value of app.numThreads
# - In 5.3.0, just the -openmp option is available
# - In 6.0.0, -openmp needs to be preceded by -parallel
self.reconall_multithread_options = []
if app.NUM_THREADS is None or app.NUM_THREADS > 1:
with open(self.reconall_path, 'r') as f:
reconall_text = f.read().splitlines()
for line in reconall_text:
line = line.strip()
if line == 'case "-parallel":':
self.reconall_multithread_options = \
['-parallel'] + self.reconall_multithread_options
# If number of threads in this script is not being
# explicitly controlled, allow recon-all to use
# its own default number of threads
elif line == 'case "-openmp":' \
and app.NUM_THREADS is not None:
self.reconall_multithread_options.extend(
['-openmp', str(app.NUM_THREADS)])
if self.reconall_multithread_options:
self.reconall_multithread_options = \
' ' + ' '.join(self.reconall_multithread_options)
else:
self.reconall_multithread_options = ''
app.debug(self.reconall_multithread_options)
if parcellation == 'brainnetome246fs':
self.parc_lut_file = os.path.join(self.freesurfer_home,
'BN_Atlas_246_LUT.txt')
self.mrtrix_lut_file = ''
elif parcellation == 'desikan':
self.parc_lut_file = os.path.join(self.freesurfer_home,
'FreeSurferColorLUT.txt')
self.mrtrix_lut_file = os.path.join(mrtrix_lut_dir,
'fs_default.txt')
elif parcellation == 'destrieux':
self.parc_lut_file = os.path.join(self.freesurfer_home,
'FreeSurferColorLUT.txt')
self.mrtrix_lut_file = os.path.join(mrtrix_lut_dir,
'fs_a2009s.txt')
elif parcellation == 'hcpmmp1':
self.parc_lut_file = os.path.join(mrtrix_lut_dir,
'hcpmmp1_original.txt')
self.mrtrix_lut_file = os.path.join(mrtrix_lut_dir,
'hcpmmp1_ordered.txt')
elif parcellation in ['yeo7fs', 'yeo17fs']:
self.parc_lut_file = \
os.path.join(self.freesurfer_home,
'Yeo2011_'
+ ('7' if parcellation == 'yeo7fs' else '17')
+ 'networks_Split_Components_LUT.txt')
self.mrtrix_lut_file = \
os.path.join(mrtrix_lut_dir,
'Yeo2011_'
+ ('7' if parcellation == 'yeo7fs' else '17')
+ 'N_split.txt')
else:
assert False
# If running in a container environment, and --debug is used
# (resulting in the scratch directory being a mounted drive),
# it's possible that attempting to construct a softlink may
# lead to an OSError
# As such, run a test to determine whether or not it is
# possible to construct a softlink within the scratch
# directory; if it is not possible, revert to performing
# deep copies of the relevant FreeSurfer template directories
self.freesurfer_template_link_function = os.symlink
try:
self.freesurfer_template_link_function(
self.freesurfer_subjects_dir,
'test_softlink')
os.remove('test_softlink')
app.debug('Using softlinks to FreeSurfer template directories')
except OSError:
app.debug('Unable to create softlinks; '
'will perform deep copies of FreeSurfer '
'template directories')
self.freesurfer_template_link_function = shutil.copytree
elif self.do_mni:
self.template_image_path = \
os.path.join(fsl_path,
'data',
'standard',
'MNI152_T1_2mm.nii.gz')
self.template_mask_path = \
os.path.join(fsl_path,
'data',
'standard',
'MNI152_T1_2mm_brain_mask.nii.gz')
if parcellation == 'aal':
self.parc_image_path = \
os.path.abspath(os.path.join(os.sep,
'opt',
'aal',
'ROI_MNI_V4.nii'))
self.parc_lut_file = \
os.path.abspath(os.path.join(os.sep,
'opt',
'aal',
'ROI_MNI_V4.txt'))
self.mrtrix_lut_file = os.path.join(mrtrix_lut_dir,
'aal.txt')
elif parcellation == 'aal2':
self.parc_image_path = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'aal',
'ROI_MNI_V5.nii'))
self.parc_lut_file = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'aal',
'ROI_MNI_V5.txt'))
self.mrtrix_lut_file = os.path.join(mrtrix_lut_dir,
'aal2.txt')
elif parcellation == 'brainnetome246mni':
self.parc_image_path = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'brainnetome',
'BNA_MPM_thr25_1.25mm.nii.gz'))
self.parc_lut_file = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'brainnetome',
'BN_Atlas_246_LUT.txt'))
self.mrtrix_lut_file = ''
elif parcellation == 'craddock200':
self.parc_image_path = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'ADHD200_parcellate_200.nii.gz'))
self.parc_lut_file = ''
self.mrtrix_lut_file = ''
elif parcellation == 'craddock400':
self.parc_image_path = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'ADHD200_parcellate_400.nii.gz'))
self.parc_lut_file = ''
self.mrtrix_lut_file = ''
elif parcellation == 'perry512':
self.parc_image_path = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'512inMNI.nii'))
self.parc_lut_file = ''
self.mrtrix_lut_file = ''
elif parcellation == 'yeo7mni':
self.parc_image_path = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'Yeo2011',
'Yeo2011_7Networks_N1000.split_components'
+ '.FSL_MNI152_1mm.nii.gz'))
self.parc_lut_file = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'Yeo2011',
'7Networks_ColorLUT_freeview.txt'))
self.mrtrix_lut_file = ''
elif parcellation == 'yeo17mni':
self.parc_image_path = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'Yeo2011',
'Yeo2011_17Networks_N1000'
+ '.split_components'
+ '.FSL_MNI152_1mm.nii.gz'))
self.parc_lut_file = \
os.path.abspath(
os.path.join(os.sep,
'opt',
'Yeo2011',
'17Networks_ColorLUT_freeview.txt'))
self.mrtrix_lut_file = ''
else:
assert False
def find_atlas_file(filepath, description):
if not filepath:
return ''
if os.path.isfile(filepath):
return filepath
if not atlas_path:
raise MRtrixError('Could not find ' + description + ' '
'(expected location: ' + filepath + ')')
newpath = os.path.join(os.path.dirname(atlas_path),
os.path.basename(filepath))
if os.path.isfile(newpath):
return newpath
raise MRtrixError('Could not find ' + description + ' '
'(tested locations: '
'\'' + filepath + '\', '
'\'' + newpath + '\')')
self.template_image_path = \
find_atlas_file(self.template_image_path,
'template image')
self.template_mask_path = \
find_atlas_file(self.template_mask_path,
'template brain mask image')
self.parc_image_path = \
find_atlas_file(self.parc_image_path,
'parcellation image')
self.parc_lut_file = \
find_atlas_file(self.parc_lut_file,
'parcellation lookup table file')
if self.mrtrix_lut_file and not os.path.exists(self.mrtrix_lut_file):
raise MRtrixError(
'Could not find MRtrix3 connectome lookup table file '
'(expected location: ' + self.mrtrix_lut_file + ')')
# End of ParticipantShared() class
# Regardless of the source of T1-weighted image information,
# scratch directory will contain at completion of this function:
# - Either:
# - T1.mif
# or
# - T1_premasked.mif
# , depending on software used (full unmasked T1-weighted image data
# may not be available)
# - T1_mask.mif
#
# TODO Think after all that this does need to export a greater
# amount of information with respect to what was done & how it was derived
def get_t1w_preproc_images(import_path,
session,
t1w_shared,
t1w_preproc):
session_label = '_'.join(session)
preproc_image_path = None
preproc_image_is_masked = None
preproc_mask_path = None
raw_image_path = None
if t1w_preproc:
# Multiple possibilities for how such data may have been provided:
# - Raw path to the image itself
# - Path to anat/ directory
# - Path to subject directory within BIDS Derivatives dataset
# - Path to BIDS Derivatives dataset
if os.path.isfile(t1w_preproc):
preproc_image_path = t1w_preproc
else:
expected_image_basename = session_label + '*_T1w.nii*'
for candidate in [
os.path.join(t1w_preproc,
expected_image_basename),
os.path.join(t1w_preproc,
'anat',
expected_image_basename),
os.path.join(os.path.join(t1w_preproc, *session),
'anat',
expected_image_basename)]:
glob_result = glob.glob(candidate)
if glob_result:
if len(glob_result) == 1:
preproc_image_path = glob_result[0]
break
glob_refined_result = \
[item for item in glob_result \
if not '_space-' in item]
if len(glob_refined_result) == 1:
preproc_image_path = glob_refined_result[0]
break
raise MRtrixError('Unable to unambiguously select pre-'
'processed T1-weighted image due to '
'multiple candidates in location "'
+ candidate
+ '": '
+ ';'.join(glob_result))
if preproc_image_path is None:
raise MRtrixError('No pre-processed T1w image found from '
'specified path "' + t1w_preproc + '"')
else:
# Look inside of import_path to see if there is a pre-processed
# T1w image already there
glob_result = glob.glob(os.path.join(os.path.join(import_path,
*session),
'anat',
session_label
+ '*_desc-preproc*_T1w.nii*'))
if glob_result:
if len(glob_result) == 1:
preproc_image_path = glob_result[0]
else:
raise MRtrixError('Multiple pre-processed T1w images found in '
+ 'import directory "'
+ import_path
+ '": '
+ ';'.join(glob_result))
# Same checks regardless of whether the existing pre-processed image
# comes from the output directory or a user-specified location
if preproc_image_path:
if '_desc-preproc' not in preproc_image_path:
raise MRtrixError('Selected T1-weighted image "'
+ preproc_image_path
+ '" not flagged as pre-processed')
# Check to see if there's a JSON file along with the T1-weighted
# image; if they is, parse it to find out whether or not the
# pre-processed image has been brain-extracted
expected_json_path = preproc_image_path \
.rstrip('.gz') \
.rstrip('.nii') \
+ '.json'
try:
with open(expected_json_path, 'r') as t1_json_file:
t1_json_data = json.load(t1_json_file)
preproc_image_is_masked = t1_json_data.get('SkullStripped', None)
except IOError:
pass
if preproc_image_is_masked is None:
# Try to assess whether or not skull-stripping has occurred
# based on the prevalence of NaNs or zero values
# - Obtain mask that contains:
# - All voxels with non-finite value
# and:
# - All voxels with a value of zero
# - Feed to mrstats, extracting the mean
# - If this is > 25% of the image, it's skull-stripped
frac_voxels_outside_mask = \
float(run.command('mrcalc '
+ preproc_image_path
+ ' 0 -eq 1 '
+ preproc_image_path
+ ' -finite -sub -add - '
+ '| '
+ ' mrstats - -output mean').stdout)
preproc_image_is_masked = \
frac_voxels_outside_mask > 0.25
app.warn('No sidecar information for pre-processed '
+ 'T1-weighted image "'
+ preproc_image_path
+ '" regarding skull-stripping; '
+ 'image has been inferred to '
+ ('be' if preproc_image_is_masked else 'not be')
+ ' pre-masked based on image data ('
+ str(int(round(100.0 * frac_voxels_outside_mask)))
+ '% of voxels contain no data)')
# Copy pre-procesed T1-weighted image into scratch directory
run.command('mrconvert '
+ preproc_image_path
+ ' '
+ path.to_scratch('T1_premasked.mif' \
if preproc_image_is_masked \
else 'T1.mif'))
# If we have been provided with a pre-processed T1-weighted image
# (regardless of where it has come from), check to see if there
# is a corresponding mask image
preproc_mask_path = preproc_image_path \
.replace('_desc-preproc', '_desc-brain') \
.replace('_T1w.nii', '_mask.nii')
if os.path.isfile(preproc_mask_path):
run.command('mrconvert '
+ preproc_mask_path
+ ' '
+ path.to_scratch('T1_mask.mif')
+ ' -datatype bit')
elif preproc_image_is_masked:
run.command('mrcalc '
+ preproc_image_path
+ ' 0 -gt '
+ path.to_scratch('T1_mask.mif')
+ ' -datatype bit')
# No pre-existing mask image, but we also don't want to
# run our own brain extraction
preproc_mask_path = ''
else:
app.console('No brain mask image found alongside '
'pre-processed T1-weighted image "'
+ preproc_image_path
+ '"; will generate one manually')
preproc_mask_path = None
else:
# Check input path for raw un-processed T1w image
glob_result = glob.glob(os.path.join(os.path.join(import_path,
*session),
'anat',
session_label + '*_T1w.nii*'))
if not glob_result:
raise MRtrixError('No raw or pre-processed T1-weighted images '
+ 'could be found in input directory "'
+ import_path
+ '" for session '
+ session_label)
if len(glob_result) > 1:
raise MRtrixError('Multiple raw T1w images found in '
+ 'input directory "'
+ import_path
+ '" for session '
+ session_label
+ ': '
+ ';'.join(glob_result))
raw_image_path = glob_result[0]
# Do we need to do any pre-processing of our own at all?
if preproc_mask_path is None:
app.console('Performing requisite processing of '
'T1-weighted data')
cwd = os.getcwd()
run.function(os.makedirs,
path.to_scratch('t1w_preproc'))
run.function(os.chdir, path.to_scratch('t1w_preproc'))
if preproc_image_path:
if t1w_shared.robex_cmd:
app.console('Using ROBEX for brain extraction for session '
+ session_label
+ ', operating on existing pre-processed '
+ 'T1-weighted image')
elif t1w_shared.fsl_anat_path:
app.console('Using fsl_anat for brain extraction for session '
+ session_label
+ ' (due to ROBEX not being installed)'
+ ', operating on existing pre-processed '
+ 'T1-weighted image')
else:
raise MRtrixError('Unable to continue processing for session '
+ session_label
+ ': no pre-processed T1-weighted image mask '
+ 'available / provided, and no appropriate '
+ 'brain masking software installed')
run.command('mrconvert '
+ preproc_image_path
+ ' T1.nii -strides '
+ ('+1,+2,+3' if t1w_shared.robex_cmd else '-1,+2,+3'))
if t1w_shared.robex_cmd:
run.command(t1w_shared.robex_cmd
+ ' T1.nii T1_brain.nii T1_mask.nii')
run.command('mrconvert T1_mask.nii '
+ path.to_scratch('T1_mask.mif')
+ ' -datatype bit')
elif t1w_shared.fsl_anat_cmd:
run.command(t1w_shared.fsl_anat_cmd
+ ' -i T1.nii --noseg --nosubcortseg --nobias')
run.command('mrconvert '
+ fsl.find_image(
os.path.join('T1.anat',
'T1_brain_mask'))
+ ' '
+ path.to_scratch('T1_mask.mif')
+ ' -datatype bit')
else:
assert False
else:
# No pre-processed T1-weighted image available:
# do everything based on the raw T1-weighted image
if t1w_shared.robex_cmd and t1w_shared.N4_cmd:
app.console('No pre-processed T1-weighted image '
+ 'found for session '
+ session_label
+ '; will use ROBEX and N4 for '
+ 'iterative brain extraction and bias field '
+ 'correction from raw T1-weighted image input')
elif t1w_shared.fsl_anat_cmd:
app.console('No pre-processed T1-weighted image '
+ 'found for session '
+ session_label
+ '; will use fsl_anat for brain extraction and '
+ 'bias field correction from raw T1-weighted '
+ 'image input'
+ (''
if t1w_shared.robex_cmd
else ' (ROBEX not installed)')
+ (''
if t1w_shared.N4_cmd
else ' (N4 not installed)'))
else:
raise MRtrixError('Cannot complete processing for session '
+ session_label
+ ': no pre-processed T1-weighted image '
+ 'available, and software tools for '
+ 'processing raw T1-weighted image '
+ 'not installed')
run.command('mrconvert '
+ raw_image_path
+ ' T1.nii -strides +1,+2,+3')
if t1w_shared.robex_cmd and t1w_shared.N4_cmd:
# Do a semi-iterative approach here:
# Get an initial brain mask, use that mask to estimate a
# bias field, then re-compute the brain mask
# TODO Consider making this fully iterative, just like the
# approach in preproc with dwi2mask and mtnormalise
run.command(t1w_shared.robex_cmd
+ ' T1.nii T1_initial_brain.nii'
+ ' T1_initial_mask.nii')
app.cleanup('T1_initial_brain.nii')
run.command(t1w_shared.N4_cmd
+ ' -i T1.nii'
+ ' -w T1_initial_mask.nii'
+ ' -o T1_biascorr.nii')
app.cleanup('T1_initial_mask.nii')
run.command(t1w_shared.robex_cmd
+ ' T1_biascorr.nii T1_biascorr_brain.nii'
+ ' T1_biascorr_brain_mask.nii')
app.cleanup('T1_biascorr_brain.nii')
run.command('mrconvert T1_biascorr.nii '
+ path.to_scratch('T1.mif'))
app.cleanup('T1_biascorr.nii')
run.command('mrconvert T1_biascorr_brain_mask.nii '
+ path.to_scratch('T1_mask.mif')
+ ' -datatype bit')
app.cleanup('T1_biascorr_brain_mask.nii')
elif t1w_shared.fsl_anat_cmd:
run.command(t1w_shared.fsl_anat_cmd
+ ' -i T1.nii --noseg --nosubcortseg')
run.command('mrconvert '
+ fsl.find_image(
os.path.join('T1.anat',
'T1_biascorr'))
+ ' '
+ path.to_scratch('T1_premasked.mif'))
run.command('mrconvert '
+ fsl.find_image(
os.path.join('T1.anat',
'T1_biascorr_brain_mask'))
+ ' '
+ path.to_scratch('T1_mask.mif')
+ ' -datatype bit')
app.cleanup('T1.anat')
else:
assert False
run.function(shutil.move, 'T1.nii', path.to_scratch('T1_raw.nii', False))
run.function(os.chdir, cwd)
app.cleanup(path.to_scratch('t1w_preproc'))
# Completed function get_t1w_preproc_images()
def run_preproc(bids_dir, session, shared,
t1w_preproc_path, output_verbosity, output_app_dir):
session_label = '_'.join(session)
output_subdir = os.path.join(output_app_dir,
'MRtrix3_connectome-preproc',
*session)
if os.path.exists(output_subdir):
app.warn('Output directory for session "' + session_label + '" '
'already exists; all contents will be erased when this '
'execution completes')
app.make_scratch_dir()
# Need to perform an initial import of JSON data using mrconvert;
# so let's grab the diffusion gradient table as well
# If no bvec/bval present, need to go down the directory listing
# Only try to import JSON file if it's actually present
# direction in the acquisition they'll need to be split
# across multiple files
# May need to concatenate more than one input DWI, since if there's
# more than one phase-encode direction in the acquired DWIs
# (i.e. not just those used for estimating the inhomogeneity field),
# they will need to be stored as separate NIfTI files in the
# 'dwi/' directory.
app.console('Importing DWI data into scratch directory')
in_dwi_path = os.path.join(os.path.join(bids_dir, *session),
'dwi',
'*_dwi.nii*')
in_dwi_image_list = sorted(glob.glob(in_dwi_path))
if not in_dwi_image_list:
raise MRtrixError('No DWI data found for session \''
+ session_label
+ '\' (search location: ' + in_dwi_path)
dwi_index = 0
re_is_complex = re.compile(r'_part-(mag|phase)_')
for entry in in_dwi_image_list:
# Is this one image in a magnitude-phase pair?
is_complex = re_is_complex.search(os.path.basename(entry))
if is_complex:
matching_text = is_complex.group(1)
complex_part = matching_text.strip('_').split('-')[-1]
assert complex_part in ['mag', 'phase']
if complex_part == 'mag':
# Find corresponding phase image
in_phase_image = entry.replace('_part-mag_', '_part-phase_')
if in_phase_image not in in_dwi_image_list:
raise MRtrixError(
'Image '
+ entry
+ ' does not have corresponding phase image')
# Check if phase image is stored in radians
phase_stats = image.statistics(in_phase_image, allvolumes=True)
if abs(2.0*math.pi - (phase_stats.max - phase_stats.min)) \
> 0.01:
app.warn('Phase image '
+ in_phase_image
+ ' is not stored in radian units '
+ '(values from '
+ str(phase_stats.min)
+ ' to '
+ str(phase_stats.max)
+ '); data will be rescaled automatically')
# Are the values stored as integers? If so, assume that
# taking the maximum phase value observed in the image
# intensities, incrementing it by one, and having it
# offset + scaled based on the header properties, would
# result in a phase that is 2pi greater than the minimum
# It would be better to do this rescaling based on testing
# whether the image datatype is an integer; but there
# does not yet exist a module for interpreting MRtrix3
# data types
phase_header = image.Header(in_phase_image)
add_to_max_phase = phase_header.intensity_scale() \
if phase_stats.min.is_integer() \
and phase_stats.max.is_integer() \