-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprac.py
1438 lines (1199 loc) · 55.4 KB
/
prac.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 __future__ import unicode_literals
import numpy as np
import pandas as pd
import nibabel as nb
import os
from os.path import join, basename, dirname, isfile, isdir
import re
import shutil
import matplotlib.pyplot as plt
import seaborn as sns
import nilearn.plotting as plotting
# pipeline
import nipype
from nipype.interfaces.freesurfer import MRIConvert
from nipype.interfaces.fsl import UnaryMaths
from nipype.interfaces.fsl import ExtractROI
from nipype.interfaces import fsl
from nipype.interfaces.ants import Registration
from nipype.interfaces.ants import ApplyTransforms
from multiprocessing import Pool
import GPUtil # CCNC GPU server
import sys
sys.path.append('/Volumes/CCNC_4T/psyscan/thalamus_project')
import roiExtraction
# Ipython notebook
from matplotlib.widgets import Slider, Button, RadioButtons
from matplotlib.backends.backend_pdf import PdfPages
import math
from tabulate import tabulate
from ipywidgets import *
#get_ipython().run_line_magic('matplotlib', 'notebook') # Jupyter notebook
def plot_4d_pdf(img_loc, outname, z_gap=3, ncols=15, page_num=7):
'''
Plot 4d dwi data. Save as PDF.
- vmin / vmax percentile
'''
print('Summary pdf of {}'.format(img_loc))
img_data = nb.load(img_loc).get_data()
# Match brightness of the diffusion weighted volumes
vmin = img_data[:,:,:,-1].min() # vmin and vmax estimation in the last volume
vmax = img_data[:,:,:,-1].max() # which is likely be non-b0 image
# Initialise fig and ax
# Columns : different z-slices
# Rows : differnt volumes of the dwi data
vol_num_s = 0
pdf = PdfPages(outname)
nrows = math.ceil(img_data.shape[3] / page_num)
for page in range(0, page_num): # for each page
fig, axes = plt.subplots(ncols=ncols,
nrows=nrows,
figsize=(11.69, 8.27),
dpi=300)
fig.suptitle('{}'.format(img_loc),
fontsize=14,
fontweight='bold')
for vol_num, row_axes in enumerate(axes, vol_num_s): # for each row
slice_num = 5
for col_num, ax in enumerate(row_axes): # for each column
img = ax.imshow(img_data[:,:,slice_num,vol_num], cmap='gray', vmin=vmin, vmax=vmax)#, aspect=img_data[0]/img_data[1])
ax.set_axis_off()
slice_num += z_gap
row_axes[0].text(0, 0.5,
vol_num+1,
verticalalignment='center', horizontalalignment='right',
rotation=90,
transform=row_axes[0].transAxes,
fontsize=15)
vol_num_s = vol_num
plt.subplots_adjust(wspace=0, hspace=0)
pdf.savefig(fig) # saves the current figure into a pdf page
plt.close()
pdf.close()
print('PDF saved at {}'.format(outname))
def plot_3d_pdf(img_loc, outname, ncols=6, nrows=4):
'''
Plot 3d dwi data. Save as PDF.
- vmin / vmax percentile
'''
print('Summary pdf of {}'.format(img_loc))
img_data = nb.load(img_loc).get_data()
# Initialise fig and ax
# Columns : different z-slices
# Rows : differnt volumes of the dwi data
pdf = PdfPages(outname)
#nrows = math.ceil(img_data.shape[2] / ncols)
page_num = math.ceil(img_data.shape[2] / ncols / nrows)
# Match brightness of the diffusion weighted volumes
vmin = img_data[img_data!=0].min() # vmin and vmax estimation in the last volume
vmax = img_data.max() # which is likely be non-b0 image
slice_num_s = 0
for page in range(0, page_num): # for each page
fig, axes = plt.subplots(ncols=ncols,
nrows=nrows,
figsize=(11.69, 8.27),
dpi=300)
fig.suptitle('{}'.format(img_loc),
fontsize=14,
fontweight='bold')
for slice_num, ax in enumerate(np.ravel(axes), slice_num_s): # for each axes
try:
img = ax.imshow(img_data[:,:,slice_num], cmap='gray', vmin=vmin, vmax=vmax)#, aspect=img_data[0]/img_data[1])
ax.text(0.5, 0.1,
slice_num+1,
verticalalignment='bottom', horizontalalignment='center',
#rotation=90,
transform=ax.transAxes,
fontsize=10, color='white')
ax.set_axis_off()
except:
#pass
img = ax.imshow(np.zeros_like(img_data)[:,:,0], cmap='gray')#, vmin=vmin, vmax=vmax)
ax.set_axis_off()
plt.subplots_adjust(wspace=0, hspace=0)
pdf.savefig(fig) # saves the current figure into a pdf page
plt.close()
slice_num_s = slice_num+1
pdf.close()
print('PDF saved at {}'.format(outname))
def plot_two_3d_pdf(img_loc1, img_loc2, outname, ncols=6, nrows=4):
'''
Plot two 3d maps. Save as PDF.
- vmin / vmax percentile
'''
print('Summary pdf of {} & {}'.format(img_loc1, img_loc2))
img_data1 = nb.load(img_loc1).get_data()
img_data2 = nb.load(img_loc2).get_data()
#img_data1 = np.ma.masked_where(img_data1==0, img_data1)
img_data2 = np.ma.masked_where(img_data2==0, img_data2)
# Initialise fig and ax
# Columns : different z-slices
# Rows : differnt volumes of the dwi data
pdf = PdfPages(outname)
#nrows = math.ceil(img_data.shape[2] / ncols)
page_num = math.ceil(img_data1.shape[2] / ncols / nrows)
# Match brightness of the diffusion weighted volumes
vmin = img_data1[img_data1!=0].min() # vmin and vmax estimation in the last volume
vmax = img_data1.max() # which is likely be non-b0 image
slice_num_s = 0
for page in range(0, page_num): # for each page
fig, axes = plt.subplots(ncols=ncols,
nrows=nrows,
figsize=(11.69, 8.27),
dpi=300)
fig.suptitle('{}\nvs\n{}'.format(img_loc1, img_loc2),
fontsize=14,
fontweight='bold')
for slice_num, ax in enumerate(np.ravel(axes), slice_num_s): # for each axes
try:
img1 = ax.imshow(img_data1[:,:,slice_num], cmap='gray', vmin=vmin, vmax=vmax)#, aspect=img_data[0]/img_data[1])
img2 = ax.imshow(img_data2[:,:,slice_num], cmap='hot', alpha=0.5, vmin=vmin, vmax=vmax)#, aspect=img_data[0]/img_data[1])
ax.text(0.5, 0.1,
slice_num+1,
verticalalignment='bottom', horizontalalignment='center',
#rotation=90,
transform=ax.transAxes,
fontsize=10, color='white')
ax.set_axis_off()
except:
#pass
img = ax.imshow(np.zeros_like(img_data1)[:,:,0], cmap='gray')#, vmin=vmin, vmax=vmax)
ax.set_axis_off()
plt.subplots_adjust(wspace=0, hspace=0)
pdf.savefig(fig) # saves the current figure into a pdf page
plt.close()
slice_num_s = slice_num+1
pdf.close()
print('PDF saved at {}'.format(outname))
def plot_4d_dwi(img_data:np.array):
'''
Plot 4d data with the widgets
- vmin / vmax percentile
- slice number
- volume number
'''
# Match brightness of the diffusion weighted volumes
vmin = img_data[:,:,:,-1].min() # vmin and vmax estimation in the last volume
vmax = img_data[:,:,:,-1].max() # which is likely be non-b0 image
# initialise fig and ax
fig, ax = plt.subplots(ncols=1, figsize=(5,5))
img = ax.imshow(img_data[:,:,0,0], vmin=vmin, vmax=vmax)
axcolor = 'lightgoldenrodyellow'
ax_z_slice = plt.axes([0.25, 0.05, 0.65, 0.03], facecolor=axcolor)
ax_t_slice = plt.axes([0.25, 0.00, 0.65, 0.03], facecolor=axcolor)
z_slice = Slider(ax_z_slice, 'Z-slice', 0, img_data.shape[2]-1, valinit=0, valstep=1, valfmt='%1.0f')
t_slice = Slider(ax_t_slice, 'T-slice', 0, img_data.shape[3]-1, valinit=0, valstep=1, valfmt='%1.0f')
def update(val):
z = int(z_slice.val)
t = int(t_slice.val)
img.set_data(img_data[:,:, z, t])
fig.canvas.draw_idle()
z_slice.on_changed(update)
t_slice.on_changed(update)
plt.show()
def plot_3d_nifti(img_data:np.array):
'''
Plot 3d data with the widgets
- slice number
'''
# initialise fig and ax
fig, ax = plt.subplots(ncols=1)
img = ax.imshow(img_data[:,:,30])
axcolor = 'lightgoldenrodyellow'
ax_z_slice = plt.axes([0.25, 0.05, 0.65, 0.03], facecolor=axcolor)
z_slice = Slider(ax_z_slice, 'Z-slice', 0, img_data.shape[2]-1, valinit=0, valstep=1, valfmt='%1.0f')
def update(val):
z = int(z_slice.val)
img.set_data(img_data[:,:, z])
fig.canvas.draw_idle()
z_slice.on_changed(update)
plt.show()
def plot_bet_out(nodif_img_data:np.array, img_data:np.array):
'''
Plot 3d data with the widgets
- slice number
'''
# initialise fig and ax
fig, ax = plt.subplots(ncols=1)
nodif_img = ax.imshow(nodif_img_data[:,:,30], cmap='hot')
bet_img = np.ma.masked_where(img_data<=0, img_data)
img = ax.imshow(bet_img[:,:,30])
axcolor = 'lightgoldenrodyellow'
ax_z_slice = plt.axes([0.25, 0.05, 0.65, 0.03], facecolor=axcolor)
z_slice = Slider(ax_z_slice, 'Z-slice', 0, img_data.shape[2]-1, valinit=0, valstep=1, valfmt='%1.0f')
def update(val):
z = int(z_slice.val)
nodif_img.set_data(nodif_img_data[:,:,z])
img.set_data(bet_img[:,:, z])
fig.canvas.draw_idle()
z_slice.on_changed(update)
rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, (str(self.bet_f-.05), self.bet_f, str(self.bet_f+0.05)), active=1)
def colorfunc(label, bet_f):
bet_f = float(label)
self.run_bet()
bet_data = nb.load(self.nodif_bet).get_data()
img.set_data(bet_img[:,:, z])
fig.canvas.draw_idle()
radio.on_clicked(colorfunc)
plt.show()
def plot_motion(motion_array:np.array):
'''
motion_array : (n,2) matrix
absolute and relative motion parameters from eddy
'''
fig, ax = plt.subplots(ncols=1)
ax.plot(motion_array)
fig.show()
def check_two_images(img1:str, img2:str):
'''
Plots imshow graph with both img1 and img2
img1, img2 : nifti image location
'''
img1_data = nb.load(img1).get_data()
img2_data = nb.load(img2).get_data()
initial_slice_num = int(img1_data.shape[2] / 2)
fig,ax = plt.subplots(ncols=1)
img_0 = ax.imshow(img2_data[:,:,initial_slice_num])
img_1 = ax.imshow(img1_data[:,:,initial_slice_num], cmap='hot', alpha=0.2)
fig.show()
def update(z=80):
img_0.set_data(img2_data[:,:, z])
img_1.set_data(img1_data[:,:, z])
fig.canvas.draw()
z_slice = widgets.IntSlider(min=0,
max=img1_data.shape[2]-1,
value=initial_slice_num,
description='Z slice')
interact(update, z=z_slice);
def check_roi_overlays(args):
'''
Plots imshow graph with both img1 and img2
img1, img2 : nifti image location
'''
img1_data = nb.load(args[0]).get_data()
roi_data = np.zeros_like(img1_data)
for num, img_loc in enumerate(args[1:],1):
print(img_loc)
single_roi_data = nb.load(img_loc).get_data()
roi_data = np.add(roi_data, num*single_roi_data, casting="unsafe")
roi_data = np.ma.masked_where(roi_data == 0, roi_data)
initial_slice_num = int(img1_data.shape[2] / 2)
fig,ax = plt.subplots(ncols=1)
img_0 = ax.imshow(img1_data[:,:,initial_slice_num])
img_1 = ax.imshow(roi_data[:,:,initial_slice_num], cmap='jet')
fig.show()
def update(z=80):
img_0.set_data(img1_data[:,:, z])
img_1.set_data(roi_data[:,:, z])
fig.canvas.draw()
z_slice = widgets.IntSlider(min=0,
max=img1_data.shape[2]-1,
value=initial_slice_num,
description='Z slice')
interact(update, z=z_slice);
def check_roi_overlays_bilateral(args):
'''
Plots imshow graph with both img1 and img2
img1, img2 : nifti image location
'''
img1_data = nb.load(args[0]).get_data()
roi_data = np.zeros_like(img1_data)
for num, img_loc in enumerate(args[1:],1):
print(img_loc)
single_roi_data = nb.load(img_loc).get_data()
roi_data = np.add(roi_data, single_roi_data, casting="unsafe")
roi_data = np.ma.masked_where(roi_data == 0, roi_data)
initial_slice_num = int(img1_data.shape[2] / 2)
fig,ax = plt.subplots(ncols=1)
img_0 = ax.imshow(img1_data[:,:,initial_slice_num])
img_1 = ax.imshow(roi_data[:,:,initial_slice_num], cmap='jet')
fig.show()
def update(z=80):
img_0.set_data(img1_data[:,:, z])
img_1.set_data(roi_data[:,:, z])
fig.canvas.draw()
z_slice = widgets.IntSlider(min=0,
max=img1_data.shape[2]-1,
value=initial_slice_num,
description='Z slice')
interact(update, z=z_slice);
class mniSettings:
def __init__(self):
# ---
# MNI
# ---
self.mni_fa_1mm = join(os.environ['FSLDIR'],
'data/standard/FMRIB58_FA_1mm.nii.gz')
self.mni_t1_1mm = join(os.environ['FSLDIR'],
'data/standard/MNI152_T1_1mm.nii.gz')
self.mni_t1_1mm_brain = join(os.environ['FSLDIR'],
'data/standard/MNI152_T1_1mm_brain.nii.gz')
self.template_shortname_dict = {'Unclassified':'Outside',
'Middle cerebellar peduncle':'MCP',
'Pontine crossing tract (a part of MCP)':'P-MCP',
'Genu of corpus callosum':'G-CC',
'Body of corpus callosum':'B-CC',
'Splenium of corpus callosum':'S-CC',
'Fornix (column and body of fornix)':'FORNIX',
'Corticospinal tract':'CST',
'Medial lemniscus':'ML',
'Inferior cerebellar peduncle':'ICP',
'Superior cerebellar peduncle':'SCP',
'Cerebral peduncle':'CP',
'Anterior limb of internal capsule':'ALIC',
'Posterior limb of internal capsule':'PLIC',
'Retrolenticular part of internal capsule':'RL-ALIC',
'Anterior corona radiata':'ACR',
'Superior corona radiata':'SCR',
'Posterior corona radiata':'PCR',
'Posterior thalamic radiation (include optic radiation)':'PTR',
'Sagittal stratum (include inferior longitidinal fasciculus and inferior fronto-occipital fasciculus)':'SS',
'External capsule':'EC',
'Cingulum (cingulate gyrus)':'CG',
'Cingulum (hippocampus)':'h-CG',
'Fornix (cres) / Stria terminalis (can not be resolved with current resolution)':'FORNIX/STR',
'Superior longitudinal fasciculus':'SLF',
'Superior fronto-occipital fasciculus (could be a part of anterior internal capsule)':'SFOF',
'Uncinate fasciculus':'UF',
'Tapetum':'Tapetum',
'Anterior thalamic radiation':'ATR',
'Corticospinal tract':'CT',
'Forceps major':'F-major',
'Forceps minor':'F-minor',
'Inferior fronto-occipital fasciculus':'IFOF',
'Inferior longitudinal fasciculus':'ILF',
'Superior longitudinal fasciculus (temporal part)':'SLF-t'}
class psyscanSettings(mniSettings):
def __init__(self, subject_dir):
super().__init__()
# site information
self.site = basename(subject_dir)[4:6]
self.site_dict = {'01':'Melbourne', '02':'Vienna',
'03':'Copenhagen', '04':'Heidelberg (gottingen)',
'05':'Marburg', '06':'Galway',
'07':'Tel Hashomer', '08':'Naples',
'09':'Amsterdam', '10':'Maastricht',
'11':'Utrecht', '12':'Cantabria',
'13':'Madrid', '14':'Zurich',
'15':'Edinburgh', '16':'London',
'17':'Toronto', '18':'Seoul',
'19':'Sao Paulo', '20':'Hong King'}
try:
self.site_name = self.site_dict[self.site]
except:
self.site_name = 'other'
echo_spacing_dict = {'01':0.56,
'02':0.69,
'04':0.53,
'05':0.53,
'08':0.53,
'10':0.5,
'15':0.53,
'16':0.596,
'17':0.596,
'18':0.53}
self.group = basename(subject_dir)[3]
try:
self.echo_spacing = self.echo_spacing_dict[self.site]
except:
self.echo_spacing = 0.5
class fsSettings(psyscanSettings):
def __init__(self, subject_dir):
super().__init__(subject_dir)
self.fs_dir = join(subject_dir, 'FREESURFER')
self.reg_dir = join(subject_dir, 'registration')
self.roi_dir = join(subject_dir, 'ROI')
try:
os.mkdir(self.reg_dir)
except:
pass
try:
os.mkdir(self.roi_dir)
except:
pass
# ----------
# Freesurfer
# ----------
# recon-all has been done in a different server
self.fs_mri_dir = join(self.fs_dir, 'mri')
self.t1_mgz = join(self.fs_mri_dir, 'T1.mgz')
self.t1 = join(self.fs_mri_dir, 'T1.nii.gz')
self.t1_brain_mgz = join(self.fs_mri_dir, 'brain.mgz')
self.t1_brain = join(self.fs_mri_dir, 'brain.nii.gz')
# check data existence
if not all([isfile(x) for x in [self.t1_mgz, self.t1_brain_mgz]]):
print('{} : Problem in the initial data')
if not all([isfile(x) for x in [self.t1, self.t1_brain]]):
self.mgz_to_nii()
self.t1_brain_recip = join(self.fs_mri_dir, 'brain_recip.nii.gz')
# -------------
# FS to MNI
# FLIRT & FNIRT
# -------------
self.t1_to_mni_flirt_mat = join(self.reg_dir, 'fs_to_mni_flirt.mat')
self.t1_to_mni_fnirt = join(self.reg_dir, 'fs_to_mni_warp_coeff.nii.gz')
self.t1_to_mni_fnirt_img = join(self.reg_dir, 'fs_to_mni_warp.nii.gz')
def mgz_to_nii(self):
'''
Convert brain.mgz to brain.nii
in Freesurfer/mri directory
'''
mc = MRIConvert()
mc.inputs.in_file = self.t1_brain_mgz
mc.inputs.out_file = self.t1_brain
mc.inputs.out_type = 'niigz'
mc.run()
mc = MRIConvert()
mc.inputs.in_file = self.t1_mgz
mc.inputs.out_file = self.t1
mc.inputs.out_type = 'niigz'
mc.run()
def t1_to_mni_registration(self):
'''
FS/mri/brain.nii.gz --> MNI
FLIRT, then FNIRT
'''
flt = fsl.FLIRT()#bins=256, cost_func='mutualinfo')
flt.inputs.in_file = self.t1_brain
flt.inputs.reference = self.mni_t1_1mm_brain
flt.inputs.output_type = "NIFTI_GZ"
flt.inputs.out_matrix_file = self.t1_to_mni_flirt_mat
flt.inputs.out_file = re.sub('mat', 'nii.gz', self.t1_to_mni_flirt_mat)
flt.inputs.dof = 12
flt.inputs.interp = 'trilinear'
flt.inputs.searchr_x = [-180, 180]
flt.inputs.searchr_y = [-180, 180]
flt.inputs.searchr_z = [-180, 180]
print(flt.cmdline)
flt.run()
fnt = fsl.FNIRT()#bins=256, cost_func='mutualinfo')
fnt.inputs.in_file = self.t1
fnt.inputs.ref_file = self.mni_t1_1mm
fnt.inputs.affine_file = self.t1_to_mni_flirt_mat
fnt.inputs.fieldcoeff_file = self.t1_to_mni_fnirt
fnt.inputs.warped_file = self.t1_to_mni_fnirt_img
print(fnt.cmdline)
fnt.run()
def invert_t1(self):
'''
1/T1 intensities, for SyN application
'''
inverter = UnaryMaths()
inverter.inputs.in_file = self.t1_brain
inverter.inputs.out_file = self.t1_brain_recip
inverter.inputs.operation = 'recip'
inverter.run()
class dtiSettings(psyscanSettings):
def __init__(self, subject_dir:str):
super().__init__(subject_dir)
self.subject_dir = subject_dir
self.dti_dir = join(subject_dir, 'DTI')
# ---
# DTI
# ---
self.dwi_data = join(self.dti_dir, 'DTI.nii.gz')
self.bvals = join(self.dti_dir, 'bvals')
self.bvecs_initial = join(self.dti_dir, 'bvecs')
# check data existence
if not all([isfile(x) for x in [self.dwi_data, self.bvals, self.bvecs_initial]]):
print('{} : Problem in the initial data'.format(
basename(self.subject_dir)))
# Preproc
self.nodif = join(self.dti_dir, 'nodif.nii.gz')
self.bet_f = 0.2 # bet f value initialise
self.nodif_bet = join(self.dti_dir, 'nodif_brain.nii.gz')
self.nodif_bet_mask = join(self.dti_dir, 'nodif_brain_mask.nii.gz')
self.FA_map_MNI_name = join(self.dti_dir, 'DTI_FA_MNI')
self.FA_mni = join(self.dti_dir, 'DTI_FA_MNI.nii.gz')
if self.check_shapes():
if not isfile(self.nodif):
self.extract_b0()
if not all([isfile (x) for x in [self.nodif_bet, self.nodif_bet_mask]]):
self.run_bet()
# Eddy out
self.dwi_data_eddy_out = join(self.dti_dir, 'eddy_out.nii.gz')
self.bvecs_eddy_out = join(self.dti_dir, 'eddy_out.eddy_rotated_bvecs')
self.motion_rms = join(self.dti_dir, 'eddy_out.eddy_restricted_movement_rms')
# Postproc
self.FA = join(self.dti_dir, 'DTI_FA.nii.gz')
self.FA_unwarpped = join(self.dti_dir, 'DTI_unwarpped_FA.nii.gz')
# --------
# Bedpostx
# --------
self.bedpostx_prep_dir = join(subject_dir, 'DTI_preprocessed')
self.bedpostx_dir = join(subject_dir, 'DTI_preprocessed.bedpostX')
def check_shapes(self):
dwi_img = nb.load(self.dwi_data)
dwi_data = dwi_img.get_data()
to_print = []
to_print.append(basename(self.subject_dir))
to_print.append('-----------')
to_print.append('DWI shape : {}'.format(dwi_data.shape))
bvecs = np.loadtxt(self.bvecs_initial)
to_print.append('Bvector shape : {}'.format(bvecs.shape))
bvals = np.loadtxt(self.bvals)
to_print.append('Bvals shape : {}'.format(bvals.shape))
to_print.append('-----------')
#try:
#if all([len(dwi_data.shape) == 4,
#dwi_data.shape[0] >= 128,
#dwi_data.shape[1] >= 128,
#dwi_data.shape[2] > 50,
#dwi_data.shape[3] > 60,
#bvecs.shape[0] == 3,
#bvecs.shape[1] == dwi_data.shape[3],
#bvals.shape[0] == dwi_data.shape[3]]) == True:
#return True
#else:
#print([len(dwi_data.shape) == 4,
#dwi_data.shape[0] >= 128,
#dwi_data.shape[1] >= 128,
#dwi_data.shape[2] > 50,
#dwi_data.shape[3] > 60,
#bvecs.shape[0] == 3,
#bvecs.shape[1] == dwi_data.shape[3],
#bvals.shape[0] == dwi_data.shape[3]])
#return to_print
#except:
#return to_print
def extract_b0(self):
fslroi = ExtractROI(in_file=self.dwi_data,
roi_file=self.nodif,
t_min=0,
t_size=1)
fslroi.run()
def run_bet(self):
btr = fsl.BET(in_file = self.nodif,
frac = self.bet_f,
out_file = self.nodif_bet,
mask = True)
btr.run()
def check_outputs(self):
self.extracted_roi_check()
def check_raw_dwi(self):
dwi_img = nb.load(self.dwi_data)
dwi_data = dwi_img.get_data()
plot_4d_dwi(dwi_data)
def check_bet(self):
nodif_bet_img = nb.load(self.nodif_bet)
nodif_bet_data = nodif_bet_img.get_data()
nodif_data = nb.load(self.nodif).get_data()
#plot_bet_out(, nodif_bet_data)
#plot_3d_nifti(nodif_bet_data)
# initialise fig and ax
fig, ax = plt.subplots(ncols=1)
nodif_img = ax.imshow(nodif_data[:,:,30], cmap='hot')
self.bet_data = np.ma.masked_where(nodif_bet_data<=0, nodif_bet_data)
img = ax.imshow(self.bet_data[:,:,30])
axcolor = 'lightgoldenrodyellow'
ax_z_slice = plt.axes([0.25, 0.05, 0.65, 0.03], facecolor=axcolor)
z_slice = Slider(ax_z_slice, 'Z-slice', 0, nodif_data.shape[2]-1, valinit=30, valstep=1, valfmt='%1.0f')
def update(val):
z = int(z_slice.val)
nodif_img.set_data(nodif_data[:,:,z])
img.set_data(self.bet_data[:,:, z])
fig.canvas.draw_idle()
z_slice.on_changed(update)
rax = plt.axes([0.025, 0.10, 0.15, 0.8], facecolor=axcolor)
f_vals = [x for x in np.arange(0.0, 0.5, 0.05)]
f_vals = ['{:.2f}'.format(x) for x in f_vals]
#"{:.10f}".format(f)
radio = RadioButtons(rax, f_vals, active=7)
def colorfunc(label):
self.bet_f = float(label)
print(self.bet_f)
self.run_bet()
bet_data = nb.load(self.nodif_bet).get_data()
self.bet_data = np.ma.masked_where(bet_data <= 0, bet_data)
img.set_data(self.bet_data[:,:, int(z_slice.val)])
#rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
#radio = RadioButtons(rax, (str(self.bet_f-.05), self.bet_f, str(self.bet_f+0.05)), active=1)
fig.canvas.draw_idle()
radio.on_clicked(colorfunc)
fig.show()
print("Final bet f value is : {}".format(self.bet_f))
self.final_bet_f = self.bet_f
with open(join(self.dti_dir, 'final_bet_f.txt'), 'w') as f:
f.write(str(self.final_bet_f))
def eddy_settings(self):
# index
data_img = nb.load(self.dwi_data)
self.index_array = np.tile(1, data_img.shape[-1])
self.index_loc = join(self.dti_dir, 'index.txt')
# acqp
self.acqp_num = (128-1) * self.echo_spacing * 0.001
self.acqp_line = '0 -1 0 {}'.format(self.acqp_num)
self.acqp_loc = join(self.dti_dir, 'acqp.txt')
# eddy_command
self.eddy_command = 'eddy_cuda8.0 \
--imain={data} \
--mask={mask} \
--index={index} \
--acqp={acqp} \
--bvecs={bvecs} \
--bvals={bvals} \
--out={out} \
--repol'.format(data=self.dwi_data,
mask=self.nodif_bet_mask,
index=self.index_loc,
acqp=self.acqp_loc,
bvecs=self.bvecs_initial,
bvals=self.bvals,
out=join(self.dti_dir,
'eddy_out'))
self.eddy_command = re.sub('\s+', ' ', self.eddy_command)
def write_index(self):
np.savetxt(self.index_loc, self.index_array,
fmt='%d', newline=' ')
def write_acqp(self):
with open(self.acqp_loc, 'w') as f:
f.write(self.acqp_line)
def run_eddy(self, gpu_num=0):
self.eddy_settings()
self.write_index()
self.write_acqp()
# get most efficient gpu number
if GPUtil.getGPUs()[gpu_num].load == 0:
pass
else:
deviceID = GPUtil.getFirstAvailable(order = 'first', maxLoad=0.1, maxMemory=0.5, attempts=1, interval=1900, verbose=False)
gpu_num = deviceID[0]
self.gpu_command = 'CUDA_VISIBLE_DEVICES={} '.format(gpu_num) + self.eddy_command
print(self.gpu_command)
print(os.popen(self.gpu_command).read())
def check_motion(self):
motion_array = np.loadtxt()
plot_motion(motion_array)
def bedpostx_gpu(self, gpu_num=0):
new_dti_dir = join(dirname(self.dti_dir), 'DTI_preprocessed')
# copy eddy processed files
os.mkdir(new_dti_dir)
for initial_name, new_name in zip(['bvals', 'eddy_out.eddy_rotated_bvecs', 'eddy_out.nii.gz', 'nodif_brain_mask.nii.gz'],
['bvals', 'bvecs', 'data.nii.gz', 'nodif_brain_mask.nii.gz']):
shutil.copy(join(self.dti_dir, initial_name),
join(new_dti_dir, new_name))
if GPUtil.getGPUs()[gpu_num].load == 0:
pass
else:
deviceID = GPUtil.getFirstAvailable(order = 'first', maxLoad=0.1, maxMemory=0.5, attempts=1, interval=1900, verbose=False)
gpu_num = deviceID[0]
command = 'CUDA_VISIBLE_DEVICES={gpu_num} bedpostx_gpu {dtiDir}'.format(
gpu_num = gpu_num, dtiDir = new_dti_dir)
print(command)
os.popen(command).read()
def check_FA_registration(self):
plot_3d_nifti(nb.load(self.FA_mni).get_data())
def extract_bundle_FAs(self):
jhu_label = join(os.environ['FSLDIR'], 'data/atlases/JHU/JHU-ICBM-labels-1mm.nii.gz')
jhu_label_img = nb.load(jhu_label)
jhu_label_data = jhu_label_img.get_data()
FA_mni_img = nb.load(self.FA_mni)
FA_mni_data = FA_mni_img.get_data()
mean_FA_dict = {}
for label_num in np.unique(jhu_label_data):
masked_FA = np.ma.masked_where(jhu_label_data!=label_num, FA_mni_data)
mean_FA_dict[label_num] = masked_FA[masked_FA.nonzero()].mean()
self.jhu_label_mean_FA_dict = mean_FA_dict
# save as csv file
mean_FA_dict.to_csv(join(self.dti_dir, 'JHU_label_mean_FA.txt'))
jhu_tracts = join(os.environ['FSLDIR'], 'data/atlases/JHU/JHU-ICBM-tracts-maxprob-thr25-1mm.nii.gz')
jhu_tracts_img = nb.load(jhu_tracts)
jhu_tracts_data = jhu_tracts_img.get_data()
mean_FA_tracts_dict = {}
for tract_num in np.unique(jhu_tracts_data):
masked_tract_FA = np.ma.masked_where(jhu_tracts_data!=tract_num, FA_mni_data)
mean_FA_tracts_dict[tract_num] = masked_tract_FA[masked_tract_FA.nonzero()].mean()
self.jhu_tracts_mean_FA_dict = mean_FA_tracts_dict
# save as csv file
def make_FA_data_frame(self):
df_jhu_label = pd.DataFrame.from_dict(self.jhu_label_mean_FA_dict, orient='index').reset_index()
df_jhu_label.columns = ['ROI_number', 'FA']
df_jhu_label['Template'] = 'JHU_label'
with open(join(os.environ['FSLDIR'], 'data/atlases/JHU-labels.xml'), 'r') as f:
JHU_label_xml = f.read()
jhu_label_num_label = dict(re.findall("index=\"(\d{1,2})\".+>(.+)</label>", JHU_label_xml))
df_jhu_label['ROI'] = df_jhu_label['ROI_number'].astype('str').map(jhu_label_num_label)
df_jhu_tract = pd.DataFrame.from_dict(self.jhu_tracts_mean_FA_dict, orient='index').reset_index()
df_jhu_tract.columns = ['ROI_number', 'FA']
df_jhu_tract['Template'] = 'JHU_tract'
with open(join(os.environ['FSLDIR'], 'data/atlases/JHU-tracts.xml'), 'r') as f:
JHU_tracts_xml = f.read()
jhu_tract_num_label = dict(re.findall("index=\"(\d{1,2})\".+>(.+)</label>", JHU_tracts_xml))
jhu_tract_num_label_zero_match = {}
jhu_tract_num_label_zero_match[0] = 'Outside'
for key, value in jhu_tract_num_label.items():
jhu_tract_num_label_zero_match[int(key)+1] = value
df_jhu_tract['ROI'] = df_jhu_tract['ROI_number'].map(jhu_tract_num_label_zero_match)
JHU_FA_df = pd.concat([df_jhu_label, df_jhu_tract])
def get_side(roi_name):
try:
if roi_name.endswith('R'):
return 'Right'
elif roi_name.endswith('L'):
return 'Left'
else:
return 'Middle'
except:
return 'Middle'
JHU_FA_df['side'] = JHU_FA_df['ROI'].apply(get_side)
JHU_FA_df.to_csv(join(self.dtidir, 'JHU_FA.txt'))
def side_remove(roi_name):
side_removed_roi_name = re.sub(' R| L', '', roi_name)
return side_removed_roi_name
JHU_FA_df['side_removed'] = JHU_FA_df['ROI'].apply(side_remove)
JHU_FA_df['short_name'] = JHU_FA_df['side_removed'].map(template_shortname_dict)
self.JHU_FA_df = JHU_FA_df
def plot_JHU_FA(self):
fig, axes = plt.subplots(ncols=3, nrows=2,
figsize=(10, 10))
# L M R
# JHU o o o
# JHU o o o
for num, (group, table) in enumerate(self.JHU_FA_df.groupby(['Template', 'side'])):
ax = np.ravel(axes)[num]
sns.barplot(table.short_name,
table.FA,
ax=ax)#.set(axis_bgcolor='w')
ax.set_title(group[1])
ax.set_xlabel('')
ax.set_ylabel('')
#ax.set_xticks(rotation='vertical')
for tick in ax.get_xticklabels():
tick.set_rotation(90)
# tick.set_fontsize(5)
np.ravel(axes)[0].set_ylabel('JHU labels FA')
np.ravel(axes)[3].set_ylabel('JHU tracts FA')
fig.tight_layout()
fig.show()
def check_label_overlay(self):
jhu_label = join(os.environ['FSLDIR'], 'data/atlases/JHU/JHU-ICBM-labels-1mm.nii.gz')
jhu_label_img = nb.load(jhu_label)
jhu_label_data = jhu_label_img.get_data()
jhu_tracts = join(os.environ['FSLDIR'], 'data/atlases/JHU/JHU-ICBM-tracts-maxprob-thr25-1mm.nii.gz')
jhu_tracts_img = nb.load(jhu_tracts)
jhu_tracts_data = jhu_tracts_img.get_data()
FA_mni_img = nb.load(self.FA_mni)
FA_mni_data = FA_mni_img.get_data()
fig,axes = plt.subplots(ncols=2)
img_0=axes[0].imshow(FA_mni_data[:,:,80])
img_1=axes[0].imshow(np.ma.masked_where(jhu_label_data==0, jhu_label_data)[:,:,80])
img_2=axes[1].imshow(FA_mni_data[:,:,80])
img_3=axes[1].imshow(np.ma.masked_where(jhu_tracts_data==0, jhu_tracts_data)[:,:,80])
fig.show()
def update(z=80):
img_0.set_data(FA_mni_data[:,:, z])
img_1.set_data(np.ma.masked_where(jhu_label_data==0, jhu_label_data)[:,:, z])
img_2.set_data(FA_mni_data[:,:, z])
img_3.set_data(np.ma.masked_where(jhu_tracts_data==0, jhu_tracts_data)[:,:, z])
fig.canvas.draw()
z_slice = widgets.IntSlider(min=0,
max=FA_mni_data.shape[2]-1,
value=80,
description='Z slice')
interact(update, z=z_slice);
def plot_single_jhu(self, template, side, roi_name):
gb = self.JHU_FA_df.groupby(['Template', 'side', 'short_name'])
roi_series = gb.get_group(('JHU_'+template, side, roi_name)).iloc[0]
roi_num = roi_series.ROI_number
roi_full_name = roi_series.ROI
jhu_tracts = join(os.environ['FSLDIR'], 'data/atlases/JHU/JHU-ICBM-tracts-maxprob-thr25-1mm.nii.gz')
jhu_tracts_img = nb.load(jhu_tracts)
jhu_tracts_data = jhu_tracts_img.get_data()
FA_mni_img = nb.load(self.FA_mni)
FA_mni_data = FA_mni_img.get_data()
roi_img = nb.Nifti2Image((jhu_tracts_data==roi_num).astype(int),
affine=jhu_tracts_img.affine)
plotting.plot_roi(roi_img, bg_img=FA_mni_img,
title=roi_full_name)
plt.show()
class antsSynSettings(dtiSettings, fsSettings):
'''
f = antsSynSettings(subject_dir)
f.bedpostx_gpu_unwarpped()
f.dtifit_unwarpped()
'''
def __init__(self, subject_dir):
super().__init__(subject_dir)
# --------
# DTI
# Ants SyN
# --------
self.dwi_data_unwarpped = join(self.dti_dir, 'DTI_unwarpped.nii.gz')
self.nodif_bet_mask_unwarpped = join(self.dti_dir, 'nodif_brain_mask_unwarpped.nii.gz')