-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadditional_interfaces.py
executable file
·1267 lines (994 loc) · 53.3 KB
/
additional_interfaces.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
from nipype.interfaces.base import BaseInterface
from nipype.interfaces.base import BaseInterfaceInputSpec
from nipype.interfaces.base import CommandLineInputSpec
from nipype.interfaces.base import CommandLine
from nipype.interfaces.base import File
from nipype.interfaces.base import traits
from nipype.interfaces.base import TraitedSpec
# ==================================================================
"""
This function calculates additional DTI measures, i.e. AD and RD, that
FSL dtifi does not automatically generate
"""
class AdditionalDTIMeasuresInputSpec(BaseInterfaceInputSpec):
L1 = File(exists=True, desc='First eigenvalue image', mandatory=True)
L2 = File(exists=True, desc='Second eigenvalue image', mandatory=True)
L3 = File(exists=True, desc='Third eigenvalue image', mandatory=True)
class AdditionalDTIMeasuresOutputSpec(TraitedSpec):
AD = File(exists=True, desc="axial diffusivity (AD) image")
RD = File(exists=True, desc="radial diffusivity (RD) image")
class AdditionalDTIMeasures(BaseInterface):
input_spec = AdditionalDTIMeasuresInputSpec
output_spec = AdditionalDTIMeasuresOutputSpec
def _run_interface(self, runtime):
import nibabel as nib
from nipype.utils.filemanip import split_filename
L1 = nib.load(self.inputs.L1).get_data()
L2 = nib.load(self.inputs.L2).get_data()
L3 = nib.load(self.inputs.L3).get_data()
affine = nib.load(self.inputs.L1).get_affine()
RD = (L2 + L3) / 2
fname = self.inputs.L1
_, base, _ = split_filename(fname)
nib.save(nib.Nifti1Image(L1, affine), base + '_AD.nii.gz')
nib.save(nib.Nifti1Image(RD, affine), base + '_RD.nii.gz')
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
fname = self.inputs.L1
_, base, _ = split_filename(fname)
outputs["AD"] = os.path.abspath(base + '_AD.nii.gz')
outputs["RD"] = os.path.abspath(base + '_RD.nii.gz')
return outputs
# ==================================================================
"""
Surface to volume transformation
This function calls FreeSurfer's aparc2aseg to transform surface annotations to an image volume.
"""
class Aparc2Aseg_InputSpec(BaseInterfaceInputSpec):
annotation_file = traits.String(desc='annotation file', mandatory=True)
hemi = traits.String(desc='hemisphere: lh or rh', mandatory=True)
subjects_dir = traits.String(
desc='FreeSurfer subject directory generated by recon-all', mandatory=True)
subject_id = traits.String(
desc='subject ID', mandatory=True)
class Aparc2Aseg_OutputSpec(TraitedSpec):
subject_id = traits.String(desc='FreeSurfer subject ID')
volume_parcellation = File(
exists=True, desc="annotation file in target space")
class Aparc2Aseg(BaseInterface):
input_spec = Aparc2Aseg_InputSpec
output_spec = Aparc2Aseg_OutputSpec
def _run_interface(self, runtime):
import os
from subprocess import call
os.environ['SUBJECTS_DIR'] = self.inputs.subjects_dir
if not os.path.isdir(self.inputs.subjects_dir + self.inputs.subject_id + '/parcellation/'):
os.mkdir(self.inputs.subjects_dir +
self.inputs.subject_id + '/parcellation/')
cmd = "mri_aparc2aseg --s " + self.inputs.subject_id + \
" --annot " + self.inputs.annotation_file + \
" --o " + self.inputs.subjects_dir + self.inputs.subject_id + \
'/parcellation/' + self.inputs.annotation_file + '.nii.gz'
" --rip-unknown --hypo-as-wm"
call(cmd, shell=True)
return runtime
def _list_outputs(self):
import os
outputs = self._outputs().get()
outputs['subject_id'] = self.inputs.subject_id
outputs['volume_parcellation'] = os.path.abspath(
self.inputs.subjects_dir + '/' + self.inputs.subject_id + '/parcellation/' + self.inputs.annotation_file + '.nii.gz')
return outputs
# ==================================================================
"""
Extract statistics for surface parcellation
"""
class AparcStats_InputSpec(BaseInterfaceInputSpec):
subjects_dir = traits.String(
desc='FreeSurfer subject directory generated by recon-all', mandatory=True)
subject_id = traits.String(
desc='subject ID', mandatory=True)
parcellation_name = traits.String(desc='parcellation name', mandatory=True)
class AparcStats_OutputSpec(TraitedSpec):
lh_stats = File(
exists=True, desc="statistics for regions in the left hemisphere")
rh_stats = File(
exists=True, desc="statistics for regions in the right hemisphere")
parcellation_name = traits.String(desc='parcellation name', mandatory=True)
class AparcStats(BaseInterface):
input_spec = AparcStats_InputSpec
output_spec = AparcStats_OutputSpec
def _run_interface(self, runtime):
import os
from subprocess import call
subjects_dir = self.inputs.subjects_dir + '/'
subject_id = self.inputs.subject_id
parcellation_name = self.inputs.parcellation_name
cmd = 'mris_anatomical_stats -a ' + subjects_dir + subject_id + '/label/lh.' + parcellation_name + '.annot -f ' + \
subjects_dir + subject_id + '/stats/lh.' + parcellation_name + '.stats ' + subject_id + ' lh'
call(cmd, shell=True)
cmd = 'mris_anatomical_stats -a ' + subjects_dir + subject_id + '/label/rh.' + parcellation_name + '.annot -f ' + \
subjects_dir + subject_id + '/stats/rh.' + parcellation_name + '.stats ' + subject_id + ' rh'
call(cmd, shell=True)
return runtime
def _list_outputs(self):
subjects_dir = self.inputs.subjects_dir
subject_id = self.inputs.subject_id
parcellation_name = self.inputs.parcellation_name
outputs = self._outputs().get()
outputs['lh_stats'] = subjects_dir + '/' +\
subject_id + '/stats/lh.' + parcellation_name + '.stats'
outputs['rh_stats'] = subjects_dir + '/' +\
subject_id + '/stats/rh.' + parcellation_name + '.stats'
outputs['parcellation_name'] = parcellation_name
return outputs
# ==================================================================
"""
Extract values for regions in an atlas (volume data)
"""
class AtlasValues_InputSpec(BaseInterfaceInputSpec):
atlas_filename = File(exists=True, desc="filename of atlas data")
morpho_filename = File(exists=True, desc="filename of morphometry image")
class AtlasValues_OutputSpec(TraitedSpec):
atlas_values = File(
exists=True, desc="CSV file containing values for each region in the atlas")
class AtlasValues(BaseInterface):
input_spec = AtlasValues_InputSpec
output_spec = AtlasValues_OutputSpec
def _run_interface(self, runtime):
import nibabel as nib
from nipype.utils.filemanip import split_filename
import numpy as np
import pandas as pd
atlas_filename = self.inputs.atlas_filename
morpho_filename = self.inputs.morpho_filename
atlas = nib.load(atlas_filename).get_data()
morpho = nib.load(morpho_filename).get_data()
results = pd.DataFrame()
metric = morpho_filename.split('/')[-1].split('_')[1]
atlas_name = atlas_filename.split('/')[-1].split('.nii.gz')[0]
for region in np.unique(atlas):
region_mask = np.asarray(atlas == region).astype('float64')
results.set_value(
region - 1, 'value', np.sum(morpho * region_mask) / np.sum(region_mask))
_, base, _ = split_filename(morpho_filename)
results.to_csv(base + '_' + metric + '_' + atlas_name + '.csv')
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
atlas_filename = self.inputs.atlas_filename
morpho_filename = self.inputs.morpho_filename
_, base, _ = split_filename(morpho_filename)
metric = morpho_filename.split('/')[-1].split('_')[1]
atlas_name = atlas_filename.split('/')[-1].split('.nii.gz')[0]
atlas_name = atlas_filename.split('/')[-1].split('.nii.gz')[0]
outputs['atlas_values'] = os.path.abspath(base + '_' + metric + '_' + atlas_name + '.csv')
return outputs
# ======================================================================
# Calculate the connectivity matrix
class CalcMatrixInputSpec(BaseInterfaceInputSpec):
track_file = File(
exists=True, desc='whole-brain tractography in .trk format', mandatory=True)
ROI_file = File(
exists=True, desc='image containing the ROIs', mandatory=True)
scalar_file = File(
exists=True, desc='fractional anisotropy map in the same soace as the track file', mandatory=True)
output_file = File(
"scalar_matrix.txt", desc="Adjacency matrix of ROIs with scalar as conenction weight", usedefault=True)
threshold = traits.Int(desc="Threshold of number of streamlines to retain")
class CalcMatrixOutputSpec(TraitedSpec):
density_matrix = File(exists=True, desc="connectivity matrix based on the number of streamlines between each pair of ROIs")
length_normalized_matrix = File(exists=True, desc="streamline density matrix normalized by the length of the streamlines between ROIs")
scalar_matrix = File(exists=True, desc="connectivity matrix of scalar between each pair of ROIs")
size_normalized_matrix = File(exists=True, desc="streamline density matrix normalized by the combined volume of the ROIs")
class CalcMatrix(BaseInterface):
input_spec = CalcMatrixInputSpec
output_spec = CalcMatrixOutputSpec
def _run_interface(self, runtime):
import nibabel as nib
import numpy as np
from dipy.tracking import utils
# Identity matrix affine
affine = np.eye(4)
# Loading the ROI file
img = nib.load(self.inputs.ROI_file)
labels = nib.Nifti1Image(img.get_data(), affine).get_data()
# Getting the scalar data
img = nib.load(self.inputs.scalar_file)
scalar_data = nib.Nifti1Image(img.get_data(), affine).get_data()
# Loading the streamlines
streamlines = np.load(self.inputs.track_file)
# Only keeping streamlines that pass through the ROIs
ROI_mask = labels > 0
target_streamlines = utils.target(streamlines, ROI_mask, affine=affine)
# Constructing the streamlines matrix
matrix, mapping = utils.connectivity_matrix(
streamlines=target_streamlines, label_volume=labels.astype('int'), affine=affine, symmetric=True, return_mapping=True, mapping_as_streamlines=True)
matrix[matrix < self.inputs.threshold] = 0
# Removing the background label
matrix = matrix[1:, :]
matrix = matrix[:, 1:]
# Saving the density matrix
from nipype.utils.filemanip import split_filename
_, base, _ = split_filename(self.inputs.track_file)
np.savetxt(base + '_' + str(self.inputs.threshold) + '_matrix.txt', matrix, delimiter='\t')
# Density matrix normalized by ROI size
ROI_sizes = [np.sum(labels[labels == ROI]) for ROI in np.unique(labels)[1:]]
size_matrix = np.zeros(shape=np.repeat(len(np.unique(labels)[1:]),2))
for ROI1 in range(0,len(np.unique(labels)[1:])):
for ROI2 in range(0,len(np.unique(labels)[1:])):
size_matrix[ROI1, ROI2] = ROI_sizes[ROI1] + ROI_sizes[ROI2]
np.savetxt(base + '_' + str(self.inputs.threshold) + '_matrix_ROI_normalized.txt', matrix/size_matrix, delimiter='\t')
# Density matrix normalized by streamline length
length_matrix = np.zeros(shape=np.repeat(len(np.unique(labels)[1:]),2))
for ROI1 in range(0,len(np.unique(labels)[1:])):
for ROI2 in range(0,len(np.unique(labels)[1:])):
length_matrix[ROI1, ROI2] = np.median(list(utils.length(mapping[ROI1, ROI2])))
length_matrix[np.tril_indices(n=len(length_matrix))] = 0
length_matrix = length_matrix.T + length_matrix - np.diagonal(length_matrix)
np.savetxt(base + '_' + str(self.inputs.threshold) + '_matrix_length_normalized.txt', matrix/length_matrix, delimiter='\t')
# Constructing the scalar matrix
dimensions = matrix.shape
scalar_matrix = np.empty(shape=dimensions)
for i in range(0, dimensions[0]):
for j in range(0, dimensions[1]):
if matrix[i, j]:
dm = utils.density_map(
mapping[i, j], scalar_data.shape, affine=affine)
scalar_matrix[i, j] = np.mean(scalar_data[dm > 5])
else:
scalar_matrix[i, j] = 0
scalar_matrix[np.tril_indices(n=len(scalar_matrix))] = 0
scalar_matrix = scalar_matrix.T + scalar_matrix - np.diagonal(scalar_matrix)
# Saving the scalar matrix
from nipype.utils.filemanip import split_filename
_, base, _ = split_filename(self.inputs.scalar_file)
np.savetxt(base + '_matrix.txt', scalar_matrix, delimiter='\t')
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
_, base, _ = split_filename(self.inputs.scalar_file)
outputs["scalar_matrix"] = os.path.abspath(base + '_matrix.txt')
_, base, _ = split_filename(self.inputs.track_file)
outputs["density_matrix"] = os.path.abspath(base + '_' + str(self.inputs.threshold) + '_matrix.txt')
outputs["length_normalized_matrix"] = os.path.abspath(base + '_' + str(self.inputs.threshold) + '_matrix_length_normalized.txt')
outputs["size_normalized_matrix"] = os.path.abspath(base + '_' + str(self.inputs.threshold) + '_matrix_ROI_normalized.txt')
return outputs
# ==================================================================
# Write FreeSurfer parcellation results in separate CSV files
class FreeSurferValues_InputSpec(BaseInterfaceInputSpec):
lh_filename = File(desc='FreeSurfer stats file with morphometric values for left hemisphere', mandatory=True, exist=True)
rh_filename = File(desc='FreeSurfer stats file with morphometric values for right hemisphere', mandatory=True, exist=True)
parcellation_name = traits.String(desc='name of the parcellation')
class FreeSurferValues_OutputSpec(TraitedSpec):
SurfArea = File(exist=True, desc="CSV file with surface area values")
GrayVol = File(dexist=True, esc="CSV file with gray matter area values")
ThickAvg = File(exist=True, desc="CSV file with thickness average values")
ThickStd = File(exist=True, desc="CSV file with thickness standard deviation valuese")
MeanCurv = File(exist=True, desc="CSV file with mean curvature values")
GausCurv = File(exist=True, desc="CSV file with gaussian curvature values")
FoldInd = File(dexist=True, esc="CSV file with folding index values")
CurvInd = File(dexist=True, esc="CSV file with curvature index values")
class FreeSurferValues(BaseInterface):
input_spec = FreeSurferValues_InputSpec
output_spec = FreeSurferValues_OutputSpec
def _run_interface(self, runtime):
import pandas as pd
import re
lh_filename = self.inputs.lh_filename
rh_filename = self.inputs.rh_filename
parcellation_name = self.inputs.parcellation_name
SurfArea = pd.DataFrame()
GrayVol = pd.DataFrame()
ThickAvg = pd.DataFrame()
ThickStd = pd.DataFrame()
MeanCurv = pd.DataFrame()
GausCurv = pd.DataFrame()
FoldInd = pd.DataFrame()
CurvInd = pd.DataFrame()
index = 0
for filename in [lh_filename, rh_filename]:
file = open(filename, 'r')
for line in file:
if not re.search('#', line) and not re.search('unknown', line):
values = line.split()
SurfArea.set_value(index, 'value', values[1])
GrayVol.set_value(index, 'value', values[2])
ThickAvg.set_value(index, 'value', values[3])
ThickStd.set_value(index, 'value', values[4])
MeanCurv.set_value(index, 'value', values[5])
GausCurv.set_value(index, 'value', values[6])
FoldInd.set_value(index, 'value', values[7])
CurvInd.set_value(index, 'value', values[8])
index += 1
SurfArea.to_csv(parcellation_name + '_SurfArea.csv')
GrayVol.to_csv(parcellation_name + '_GrayVol.csv')
ThickAvg.to_csv(parcellation_name + '_ThickAvg.csv')
ThickStd.to_csv(parcellation_name + '_ThickStd.csv')
MeanCurv.to_csv(parcellation_name + '_MeanCurv.csv')
GausCurv.to_csv(parcellation_name + '_GausCurv.csv')
FoldInd.to_csv(parcellation_name + '_FoldInd.csv')
CurvInd.to_csv(parcellation_name + '_CurvInd.csv')
return runtime
def _list_outputs(self):
import os
outputs = self._outputs().get()
lh_filename = self.inputs.lh_filename
parcellation_name = self.inputs.parcellation_name
outputs['SurfArea'] = os.path.abspath(parcellation_name + '_SurfArea.csv')
outputs['GrayVol'] = os.path.abspath(parcellation_name + '_GrayVol.csv')
outputs['ThickAvg'] = os.path.abspath(parcellation_name + '_ThickAvg.csv')
outputs['ThickStd'] = os.path.abspath(parcellation_name + '_ThickStd.csv')
outputs['MeanCurv'] = os.path.abspath(parcellation_name + '_MeanCurv.csv')
outputs['GausCurv'] = os.path.abspath(parcellation_name + '_GausCurv.csv')
outputs['FoldInd'] = os.path.abspath(parcellation_name + '_FoldInd.csv')
outputs['CurvInd'] = os.path.abspath(parcellation_name + '_CurvInd.csv')
return outputs
# ==================================================================
# Deterministic trackign with a CSD model
class TractographyInputSpec(BaseInterfaceInputSpec):
in_file = File(exists=True, desc='diffusion weighted volume', mandatory=True)
bval = File(exists=True, desc='FSL-style b-value file', mandatory=True)
bvec = File(exists=True, desc='FSL-style b-vector file', mandatory=True)
FA = File(exists=True, desc='FA map', mandatory=True)
brain_mask = File(exists=True, desc='FA map', mandatory=True)
model = traits.String(desc='model to use for reconstruction, either CSA, CSD')
class TractographyOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="streamlines in NumPy format")
out_track = File(exists=True, desc="tracks in Trackvis format")
GFA = File(exist=True, desc="Generalized fractional anisotropy image")
class Tractography(BaseInterface):
input_spec = TractographyInputSpec
output_spec = TractographyOutputSpec
def _run_interface(self, runtime):
import numpy as np
import nibabel as nib
from dipy.core.gradients import gradient_table
from nipype.utils.filemanip import split_filename
from dipy.tracking import utils
from dipy.reconst.shm import CsaOdfModel
from dipy.data import default_sphere
from dipy.direction import peaks_from_model
from dipy.tracking.local import ThresholdTissueClassifier
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
from dipy.reconst.csdeconv import auto_response
from dipy.direction import DeterministicMaximumDirectionGetter
from dipy.tracking.local import LocalTracking
from dipy.io.trackvis import save_trk
bvec = self.inputs.bvec
bval = self.inputs.bval
FA_fname = self.inputs.FA
fname = self.inputs.in_file
mask_fname = self.inputs.brain_mask
model = self.inputs.model
# Loading the data
img = nib.load(fname)
data = img.get_data()
FA_img = nib.load(FA_fname)
fa = FA_img.get_data()
mask_img = nib.load(mask_fname)
mask = mask_img.get_data()
bval_fname = self.inputs.bval
bvals = np.loadtxt(bval_fname)
bvec_fname = self.inputs.bvec
bvecs = np.loadtxt(bvec_fname)
#bvecs = np.vstack([-1*bvecs[0,:],bvecs[1,:],bvecs[2,:]]).T
bvecs = np.vstack([bvecs[0,:],bvecs[1,:],bvecs[2,:]]).T
gtab = gradient_table(bvals, bvecs)
# Creating a white matter mask
fa = fa*mask
white_matter = fa >= 0.2
affine = np.eye(4)
# Creating a seed mask
seeds = utils.seeds_from_mask(white_matter, density=[1,1,1])
# Fitting the CSA model
csa_model = CsaOdfModel(gtab, sh_order=8)
csa_peaks = peaks_from_model(csa_model, data, default_sphere,
relative_peak_threshold=.8,
min_separation_angle=30,
mask=white_matter)
classifier = ThresholdTissueClassifier(csa_peaks.gfa, .1)
if model == 'CSA':
streamlines = LocalTracking(csa_peaks, classifier, seeds, np.eye(4), step_size=.5)
if model == 'CSD':
# CSD model
from dipy.reconst.csdeconv import auto_response
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
from dipy.direction import ProbabilisticDirectionGetter
response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=8)
csd_fit = csd_model.fit(data, mask=white_matter)
prob_dg = ProbabilisticDirectionGetter.from_shcoeff(csd_fit.shm_coeff, max_angle=45., sphere=default_sphere)
# Tracking
streamlines = LocalTracking(prob_dg, classifier, seeds, affine,step_size=.5, max_cross=2)
# Compute streamlines and store as a list.
streamlines = list(streamlines)
# Saving the tracks in NumPy format
_, base, _ = split_filename(fname)
np.save(base + '_' + self.inputs.model + '.npy', np.array(streamlines, dtype=np.object))
# Saving the GFA image
nib.save(nib.Nifti1Image(csa_peaks.gfa, FA_img.affine), base + '_GFA.nii.gz')
# Make a trackvis header so we can save streamlines
voxel_size = FA_img.get_header().get_zooms()
trackvis_header = nib.trackvis.empty_header()
trackvis_header['voxel_size'] = voxel_size
trackvis_header['dim'] = np.shape(fa)
trackvis_header['voxel_order'] = "RAS"
# Move streamlines to "trackvis space"
trackvis_point_space = utils.affine_for_trackvis(voxel_size)
streamlines = utils.move_streamlines(streamlines, trackvis_point_space, input_space=affine)
streamlines = list(streamlines)
nib.trackvis.aff_to_hdr(trackvis_point_space, trackvis_header)
# Save streamlines in Trackvis format
for_save = [(sl, None, None) for sl in streamlines]
nib.trackvis.write(base + '_' + self.inputs.model + '.trk', for_save, trackvis_header)
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
fname = self.inputs.in_file
_, base, _ = split_filename(fname)
outputs["out_file"] = os.path.abspath(base + '_' + self.inputs.model + '.npy')
outputs["out_track"] = os.path.abspath(base + '_' + self.inputs.model +'.trk')
outputs["GFA"] = os.path.abspath(base + '_GFA.nii.gz')
return outputs
# ==================================================================
"""
Expand parcels
This function expands the parcellation labels into the white matter
"""
class ExpandParcelsInputSpec(BaseInterfaceInputSpec):
dilatationVoxel = traits.Int(0, desc='Number of voxels to dilate the parcellation by', mandatory=True)
parcellation_name = traits.String(
desc='parcellation name', mandatory=True)
parcellation_file = File(
exists=True, desc='volume parcellation file', mandatory=True)
subjects_dir = traits.String(
desc='FreeSurfer subjects directory', mandatory=True)
subject_id = traits.String(desc='subject ID', mandatory=True)
white_matter_image = File(exists=True, desc='white matter image', mandatory=True)
class ExpandParcelsOutputSpec(TraitedSpec):
out_file = File(desc="dilated parcellation image")
subject_id = traits.String(desc='FreeSurfer subject ID')
class ExpandParcels(BaseInterface):
input_spec = ExpandParcelsInputSpec
output_spec = ExpandParcelsOutputSpec
def _run_interface(self, runtime):
import nibabel as nib
import numpy as np
from nipype.utils.filemanip import split_filename
parcellation_file = self.inputs.parcellation_file
white_matter_image = self.inputs.white_matter_image
dilatationVoxel = self.inputs.dilatationVoxel
parcellation_name = self.inputs.parcellation_name
volGM = nib.load(parcellation_file).get_data()
affine = nib.load(parcellation_file).affine
volWM = nib.load(white_matter_image).get_data()
wmCode = [2,41];
# Selecting cortical areas
newVol = volGM.copy()
parcelSetlh = np.asarray(np.where(volGM == wmCode[0]))
parcelSetrh = np.asarray(np.where(volGM == wmCode[1]))
parcelWhite = np.hstack([parcelSetlh, parcelSetrh])
parcelSet = np.unique(volGM);
parcelSet = parcelSet[parcelSet > 1000]
# Calculating the parcel centroids
centroids = list()
for parcel in parcelSet:
ci,cj,ck = np.where(newVol == parcel)
centroids.append([np.mean(ci), np.mean(cj), np.mean(ck)])
centroids = np.asarray(centroids)
for nv in range(0, np.shape(parcelWhite)[1]):
ci,cj,ck = parcelWhite[..., nv]
candidates = list()
for ni in range(-dilatationVoxel, dilatationVoxel + 1):
for nj in range(-dilatationVoxel, dilatationVoxel + 1):
for nk in range(-dilatationVoxel, dilatationVoxel + 1):
nci = ci + ni
ncj = cj + nj
nck = ck + nk
if (nci>0) & (nci<257) & (ncj>0) & (ncj<257) & (nck>0) & (nck<257):
if volGM[nci, ncj, nck] > 1000:
candidates.append(volGM[nci, ncj, nck])
candidates = np.unique(candidates).transpose()
distances = list()
for nc in range(0, np.shape(candidates)[0]):
candPos = np.where(parcelSet == candidates[nc])
distances.append([((centroids[candPos, 0] - ci)**2)[0][0],
((centroids[candPos, 1] - ci)**2)[0][0],
((centroids[candPos, 2] - ci)**2)[0][0]])
if distances:
newVol[ci, cj, ck] = candidates[np.where(distances == np.min(distances))[0]]
else:
newVol[ci, cj, ck] = volGM[ci, cj, ck]
path_subj = self.inputs.subjects_dir + self.inputs.subject_id
nib.save(nib.Nifti1Image(newVol, affine),
self.inputs.subjects_dir + self.inputs.subject_id + '/parcellation/' + self.inputs.parcellation_name + '_expanded.nii.gz')
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
outputs["out_file"] = os.path.abspath(self.inputs.subjects_dir + self.inputs.subject_id + '/parcellation/' + self.inputs.parcellation_name + '_expanded.nii.gz')
outputs["subject_id"] = self.inputs.subject_id
return outputs
# ==================================================================
"""
Denoising with non-local means
This function is based on the example in the Dipy preprocessing tutorial:
http://nipy.org/dipy/examples_built/denoise_nlmeans.html#example-denoise-nlmeans
"""
class DipyDenoiseInputSpec(BaseInterfaceInputSpec):
in_file = File(
exists=True, desc='diffusion weighted volume for denoising', mandatory=True)
class DipyDenoiseOutputSpec(TraitedSpec):
out_file = File(exists=True, desc="denoised diffusion-weighted volume")
class DipyDenoise(BaseInterface):
input_spec = DipyDenoiseInputSpec
output_spec = DipyDenoiseOutputSpec
def _run_interface(self, runtime):
import nibabel as nib
import numpy as np
from dipy.denoise.nlmeans import nlmeans
from nipype.utils.filemanip import split_filename
fname = self.inputs.in_file
img = nib.load(fname)
data = img.get_data()
affine = img.get_affine()
mask = data[..., 0] > 80
a = data.shape
denoised_data = np.ndarray(shape=data.shape)
for image in range(0, a[3]):
print(str(image + 1) + '/' + str(a[3] + 1))
dat = data[..., image]
# Calculating the standard deviation of the noise
sigma = np.std(dat[~mask])
den = nlmeans(dat, sigma=sigma, mask=mask)
denoised_data[:, :, :, image] = den
_, base, _ = split_filename(fname)
nib.save(nib.Nifti1Image(denoised_data, affine),
base + '_denoised.nii.gz')
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
fname = self.inputs.in_file
_, base, _ = split_filename(fname)
outputs["out_file"] = os.path.abspath(base + '_denoised.nii.gz')
return outputs
# ==================================================================
"""
Denoising with non-local means for 3D images
This function is based on the example in the Dipy preprocessing tutorial:
http://nipy.org/dipy/examples_built/denoise_nlmeans.html#example-denoise-nlmeans
"""
class DipyDenoiseT1InputSpec(BaseInterfaceInputSpec):
in_file = File(
exists=True, desc='diffusion weighted volume for denoising', mandatory=True)
class DipyDenoiseT1OutputSpec(TraitedSpec):
out_file = File(exists=True, desc="denoised diffusion-weighted volume")
class DipyDenoiseT1(BaseInterface):
input_spec = DipyDenoiseT1InputSpec
output_spec = DipyDenoiseT1OutputSpec
def _run_interface(self, runtime):
import nibabel as nib
import numpy as np
from dipy.denoise.nlmeans import nlmeans
from nipype.utils.filemanip import split_filename
fname = self.inputs.in_file
img = nib.load(fname)
data = img.get_data()
affine = img.get_affine()
mask = data > 20
# Calculating the standard deviation of the noise
sigma = np.std(data[~mask])
denoised_data = nlmeans(data, sigma=sigma, mask=mask)
_, base, _ = split_filename(fname)
nib.save(nib.Nifti1Image(denoised_data, affine),
base + '_denoised.nii')
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
fname = self.inputs.in_file
_, base, _ = split_filename(fname)
outputs["out_file"] = os.path.abspath(base + '_denoised.nii')
return outputs
# ==================================================================
"""
Expand parcels
This function expands the parcellation labels into the white matter
"""
class ExpandParcelsInputSpec(BaseInterfaceInputSpec):
dilatationVoxel = traits.Int(0, desc='Number of voxels to dilate the parcellation by', mandatory=True)
parcellation_name = traits.String(
desc='parcellation name', mandatory=True)
parcellation_file = File(
exists=True, desc='volume parcellation file', mandatory=True)
subjects_dir = traits.String(
desc='FreeSurfer subjects directory', mandatory=True)
subject_id = traits.String(desc='subject ID', mandatory=True)
white_matter_image = File(exists=True, desc='white matter image', mandatory=True)
class ExpandParcelsOutputSpec(TraitedSpec):
out_file = File(desc="dilated parcellation image")
subject_id = traits.String(desc='FreeSurfer subject ID')
class ExpandParcels(BaseInterface):
input_spec = ExpandParcelsInputSpec
output_spec = ExpandParcelsOutputSpec
def _run_interface(self, runtime):
import nibabel as nib
import numpy as np
from nipype.utils.filemanip import split_filename
parcellation_file = self.inputs.parcellation_file
white_matter_image = self.inputs.white_matter_image
dilatationVoxel = self.inputs.dilatationVoxel
parcellation_name = self.inputs.parcellation_name
volGM = nib.load(parcellation_file).get_data()
affine = nib.load(parcellation_file).affine
volWM = nib.load(white_matter_image).get_data()
wmCode = [2,41];
# Selecting cortical areas
newVol = volGM.copy()
parcelSetlh = np.asarray(np.where(volGM == wmCode[0]))
parcelSetrh = np.asarray(np.where(volGM == wmCode[1]))
parcelWhite = np.hstack([parcelSetlh, parcelSetrh])
parcelSet = np.unique(volGM);
parcelSet = parcelSet[parcelSet > 1000]
# Calculating the parcel centroids
centroids = list()
for parcel in parcelSet:
ci,cj,ck = np.where(newVol == parcel)
centroids.append([np.mean(ci), np.mean(cj), np.mean(ck)])
centroids = np.asarray(centroids)
for nv in range(0, np.shape(parcelWhite)[1]):
ci,cj,ck = parcelWhite[..., nv]
candidates = list()
for ni in range(-dilatationVoxel, dilatationVoxel + 1):
for nj in range(-dilatationVoxel, dilatationVoxel + 1):
for nk in range(-dilatationVoxel, dilatationVoxel + 1):
nci = ci + ni
ncj = cj + nj
nck = ck + nk
if (nci>0) & (nci<257) & (ncj>0) & (ncj<257) & (nck>0) & (nck<257):
if volGM[nci, ncj, nck] > 1000:
candidates.append(volGM[nci, ncj, nck])
candidates = np.unique(candidates).transpose()
distances = list()
for nc in range(0, np.shape(candidates)[0]):
candPos = np.where(parcelSet == candidates[nc])
distances.append([((centroids[candPos, 0] - ci)**2)[0][0],
((centroids[candPos, 1] - ci)**2)[0][0],
((centroids[candPos, 2] - ci)**2)[0][0]])
if distances:
newVol[ci, cj, ck] = candidates[np.where(distances == np.min(distances))[0]]
else:
newVol[ci, cj, ck] = volGM[ci, cj, ck]
path_subj = self.inputs.subjects_dir + self.inputs.subject_id
nib.save(nib.Nifti1Image(newVol, affine),
self.inputs.subjects_dir + '/' + self.inputs.subject_id + '/parcellation/' + self.inputs.parcellation_name + '_expanded.nii.gz')
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
outputs["out_file"] = os.path.abspath(self.inputs.subjects_dir + '/' +self.inputs.subject_id + '/parcellation/' + self.inputs.parcellation_name + '_expanded.nii.gz')
outputs["subject_id"] = self.inputs.subject_id
return outputs
# ======================================================================
# Extract b0
class Extractb0InputSpec(BaseInterfaceInputSpec):
in_file = File(
exists=True, desc='diffusion-weighted image (4D)', mandatory=True)
class Extractb0OutputSpec(TraitedSpec):
out_file = File(exists=True, desc="First volume of the dwi file")
class Extractb0(BaseInterface):
input_spec = Extractb0InputSpec
output_spec = Extractb0OutputSpec
def _run_interface(self, runtime):
import nibabel as nib
img = nib.load(self.inputs.in_file)
data = img.get_data()
affine = img.get_affine()
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
fname = self.inputs.in_file
_, base, _ = split_filename(fname)
nib.save(nib.Nifti1Image(data[..., 0], affine),
os.path.abspath(base + '_b0.nii.gz'))
return runtime
def _list_outputs(self):
from nipype.utils.filemanip import split_filename
import os
outputs = self._outputs().get()
fname = self.inputs.in_file
_, base, _ = split_filename(fname)
outputs["out_file"] = os.path.abspath(base + '_b0.nii.gz')
return outputs
# ==================================================================
"""
Rename files when a skull-stripped image is used in the recon-all pipeline
"""
class FSRenameInputSpec(BaseInterfaceInputSpec):
subjects_dir = traits.String(
desc='FreeSurfer subjects directory', mandatory=True)
subject_id = traits.String(desc='subject ID', mandatory=True)
class FSRenameOutputSpec(TraitedSpec):
brainmaskauto = File(exists=True, desc="thresholded volume")
brainmask = File(exists=True, desc="thresholded volume")
class FSRename(BaseInterface):
input_spec = FSRenameInputSpec
output_spec = FSRenameOutputSpec
def _run_interface(self, runtime):
import shutil
subjects_dir = self.inputs.subjects_dir
subject_id = self.inputs.subject_id
shutil.copyfile(subjects_dir + '/' + subject_id + '/mri/T1.mgz',
subjects_dir + '/' + subject_id + '/mri/brainmask.auto.mgz')
shutil.copyfile(subjects_dir + '/' + subject_id + '/mri/T1.mgz', subjects_dir + '/' + subject_id + '/mri/brainmask.mgz')
return runtime
def _list_outputs(self):
import os
outputs = self._outputs().get()
subjects_dir = self.inputs.subjects_dir
subject_id = self.inputs.subject_id
outputs["brainmaskauto"] = os.path.abspath(
subjects_dir + '/' + subject_id + '/mri/brainmask.auto.mgz')
outputs["brainmask"] = os.path.abspath(subjects_dir + '/' + subject_id + '/mri/brainmask.mgz')
return outputs
# ==================================================================
"""
Renumber parcels
This function renumbers the parcels and creates maps for cortical and subcortical parcellation
"""
class ReunumberParcelsInputSpec(BaseInterfaceInputSpec):
subjects_dir = traits.String(
desc='FreeSurfer subject directory generated by recon-all', mandatory=True)
subject_id = traits.String(
desc='subject ID', mandatory=True)
parcellation_name = traits.String(
desc='parcellation name', mandatory=True)
class ReunumberParcelsOutputSpec(TraitedSpec):
cortical = File(exists=True, desc="cortical parcellation")
cortical_consecutive = File(exists=True, desc="cortical parcellation with consecutive numbering")
cortical_expanded = File(exists=True, desc="cortical parcellation expanded into WM")
cortical_expanded_consecutive = File(exists=True, desc="cortical parcellation expanded into WM with consecutive numbering")
leftHemisphere = File(exists=True, desc="left hemisphere parcellation")
leftHemisphere_expanded = File(exists=True, desc="left hemisphere parcellation expanded into WM")
orig = File(exists=True, desc="original parcellation image")
renum = File(exists=True, desc="renumbered parcellation")
renum_expanded = File(exists=True, desc="renumbered parcellation expanded into WM")
renum_subMask = File(exists=True, desc="renumbered parcellation with subcortical regions masked out")
rightHemisphere = File(exists=True, desc="parcellation of the right hemisphere")
rightHemisphere_expanded = File(exists=True, desc="parcellation of the right hemisphere expanded into WM")