-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHCP_helpers.py
3330 lines (3039 loc) · 147 KB
/
HCP_helpers.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
import os.path as op
from os import mkdir, makedirs, getcwd, remove, listdir, environ
#----------------------------------
# initialize global variable config
#----------------------------------
class config(object):
overwrite = False
scriptlist = list()
joblist = list()
queue = False
tStamp = ''
useFIX = False
useMemMap = False
steps = {}
Flavors = {}
sortedOperations = list()
maskParcelswithGM = False
preWhitening = False
maskParcelswithAll = True
save_voxelwise = False
useNative = False
parcellationName = ''
parcellationFile = ''
outDir = 'rsDenoise'
FCDir = 'FC'
headradius = 50 #50mm as in Powers et al. 2012
interpolation = 'linear'
melodicFolder = op.join('#fMRIrun#_hp2000.ica','filtered_func_data.ica') #the code #fMRIrun# will be replaced
plotSteps = False # produce a grayplot after each processing step
isCifti = False
sourceDir = getcwd()
fcType = 'correlation' # one of {"correlation", "partial correlation", "tangent", "covariance", "precision"}
# these variables are initialized here and used later in the pipeline, do not change
filtering = []
doScrubbing = False
#----------------------------------
# IMPORTS
#----------------------------------
# Force matplotlib to not use any Xwindows backend.
import matplotlib
# core dump with matplotlib 2.0.0; use earlier version, e.g. 1.5.3
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pandas as pd
import sys
import numpy as np
from numpy.polynomial.legendre import Legendre
from scipy import stats, linalg,signal
import scipy.io as sio
from scipy.spatial.distance import pdist, squareform
from scipy.ndimage.morphology import binary_closing, binary_dilation, binary_erosion, binary_opening, generate_binary_structure
from scipy.ndimage.filters import gaussian_filter1d
import nipype.interfaces.fsl as fsl
from subprocess import call, check_output, CalledProcessError, Popen, getoutput
import nibabel as nib
import sklearn.model_selection as cross_validation
from sklearn.linear_model import ElasticNetCV
from sklearn.kernel_ridge import KernelRidge
from sklearn import linear_model,feature_selection,preprocessing
from sklearn.preprocessing import RobustScaler
from nilearn.signal import clean
from nilearn import connectome
#from sklearn.covariance import MinCovDet,GraphicalLassoCV,LedoitWolf
from sklearn.covariance import LedoitWolf
from past.utils import old_div
import operator
import gzip
import string
import random
import xml.etree.cElementTree as ET
from time import localtime, strftime, sleep, time
import fnmatch
import re
import os
import glob
from statsmodels.nonparametric.smoothers_lowess import lowess
import seaborn as sns
import nistats
from nistats import design_matrix
#----------------------------------
# function to build dinamycally path to input fMRI file
#----------------------------------
def buildpath():
return op.join(config.DATADIR, config.subject,'MNINonLinear','Results',config.fmriRun)
#return config.DATADIR
#----------------------------------
# function to build dinamycally output path (BIDS-like)
#----------------------------------
def outpath():
if not op.isdir(config.outDir): mkdir(config.outDir)
outPath = op.join(config.outDir,'denoise_'+config.pipelineName)
if not op.isdir(outPath): mkdir(outPath)
outPath = op.join(outPath,config.subject)
if not op.isdir(outPath): mkdir(outPath)
if hasattr(config, 'session') and config.session:
outPath = op.join(outPath,config.session)
if not op.isdir(outPath): mkdir(outPath)
outPath = op.join(outPath,config.fmriRun)
if not op.isdir(outPath): mkdir(outPath)
return outPath
#----------------------------------
# EVs for task regression
#----------------------------------
# Selected as in Elliot et al. (2018)
def get_EVs(path,task):
EVs = {}
if task == 'GAMBLING' : EVs = {
'win_event' : np.loadtxt(op.join(path,'EVs','win_event.txt'),ndmin=2),
'loss_event' : np.loadtxt(op.join(path,'EVs','loss_event.txt'),ndmin=2),
'neut_event' : np.loadtxt(op.join(path,'EVs','neut_event.txt'),ndmin=2),
}
if task == 'WM' : EVs = {
'0bk_body' : np.loadtxt(op.join(path,'EVs','0bk_body.txt'),ndmin=2),
'0bk_faces' : np.loadtxt(op.join(path,'EVs','0bk_faces.txt'),ndmin=2),
'0bk_places' : np.loadtxt(op.join(path,'EVs','0bk_places.txt'),ndmin=2),
'0bk_tools' : np.loadtxt(op.join(path,'EVs','0bk_tools.txt'),ndmin=2),
'2bk_body' : np.loadtxt(op.join(path,'EVs','2bk_body.txt'),ndmin=2),
'2bk_faces' : np.loadtxt(op.join(path,'EVs','2bk_faces.txt'),ndmin=2),
'2bk_places' : np.loadtxt(op.join(path,'EVs','2bk_places.txt'),ndmin=2),
'2bk_tools' : np.loadtxt(op.join(path,'EVs','2bk_tools.txt'),ndmin=2),
}
if task == 'MOTOR' : EVs = {
'cue' : np.loadtxt(op.join(path,'EVs','cue.txt'),ndmin=2),
'lf' : np.loadtxt(op.join(path,'EVs','lf.txt'),ndmin=2),
'rf' : np.loadtxt(op.join(path,'EVs','rf.txt'),ndmin=2),
'lh' : np.loadtxt(op.join(path,'EVs','lh.txt'),ndmin=2),
'rh' : np.loadtxt(op.join(path,'EVs','rh.txt'),ndmin=2),
't' : np.loadtxt(op.join(path,'EVs','t.txt'),ndmin=2),
}
if task == 'LANGUAGE' : EVs = {
'cue' : np.loadtxt(op.join(path,'EVs','cue.txt'),ndmin=2),
'present_math' : np.loadtxt(op.join(path,'EVs','present_math.txt'),ndmin=2),
'question_math' : np.loadtxt(op.join(path,'EVs','question_math.txt'),ndmin=2),
'response_math' : np.loadtxt(op.join(path,'EVs','response_math.txt'),ndmin=2),
'present_story' : np.loadtxt(op.join(path,'EVs','present_story.txt'),ndmin=2),
'question_story' : np.loadtxt(op.join(path,'EVs','question_story.txt'),ndmin=2),
'response_story' : np.loadtxt(op.join(path,'EVs','response_story.txt'),ndmin=2),
}
if task == 'SOCIAL' : EVs = {
'mental' : np.loadtxt(op.join(path,'EVs','mental.txt'),ndmin=2),
'rnd' : np.loadtxt(op.join(path,'EVs','rnd.txt'),ndmin=2),
}
if task == 'RELATIONAL' : EVs = {
'match' : np.loadtxt(op.join(path,'EVs','match.txt'),ndmin=2),
'relation' : np.loadtxt(op.join(path,'EVs','relation.txt'),ndmin=2),
'error' : np.loadtxt(op.join(path,'EVs','error.txt'),ndmin=2), # might be empty
}
if task == 'EMOTION' : EVs = {
'fear' : np.loadtxt(op.join(path,'EVs','fear.txt'),ndmin=2),
'neut' : np.loadtxt(op.join(path,'EVs','neut.txt'),ndmin=2),
}
return EVs
#----------------------------------
# 3 alternate denoising pipelines
# many more can be implemented
#----------------------------------
config.operationDict = {
'Task': [ #test task regression
['TaskRegression', 1, []]
],
'NSF': [
['VoxelNormalization', 1, ['demean']],
['Detrending', 2, ['poly', 2, 'wholebrain']],
['TissueRegression', 3, ['CompCor', 5, 'WMCSF', 'wholebrain']],
['MotionRegression', 3, ['ICA-AROMA']],
['GlobalSignalRegression', 3, ['GS']],
['TemporalFiltering', 3, ['DCT', 0.008, 0.08]],
['Scrubbing', 5, ['FD-DVARS', 0.25, 50]]
],
'NSF2': [
['VoxelNormalization', 1, ['demean']],
['Detrending', 2, ['poly', 2, 'wholebrain']],
['TissueRegression', 3, ['CompCor', 5, 'WMCSF', 'wholebrain']],
['MotionRegression', 3, ['ICA-AROMA']],
['GlobalSignalRegression', 3, ['GS']],
['TemporalFiltering', 3, ['DCT', 0.008]],
['Scrubbing', 5, ['FDmultiband', 0.25]]
],
'MyConnectome': [
['VoxelNormalization', 1, ['demean']],
['Detrending', 2, ['poly', 1, 'wholebrain']],
['TissueRegression', 3, ['WMCSF', 'wholebrain']],
['MotionRegression', 3, ['R R^2 R-1 R-1^2']],
['GlobalSignalRegression', 3, ['GS']],
['TemporalFiltering', 4, ['Butter', 0.009, 0.08]],
['Scrubbing', 5, ['FD', 0.25]]
],
'A': [ #Finn et al. 2015
['VoxelNormalization', 1, ['zscore']],
['Detrending', 2, ['legendre', 3, 'WMCSF']],
['TissueRegression', 3, ['WMCSF', 'GM']],
['MotionRegression', 4, ['R dR']],
['TemporalFiltering', 5, ['Gaussian', 1]],
['Detrending', 6, ['legendre', 3 ,'GM']],
['GlobalSignalRegression', 7, ['GS']]
],
'A0': [ #Finn et al. 2015 + Task regression
['VoxelNormalization', 1, ['zscore']],
['Detrending', 2, ['legendre', 3, 'WMCSF']],
['TissueRegression', 3, ['WMCSF', 'GM']],
['MotionRegression', 4, ['R dR']],
['TemporalFiltering', 5, ['Gaussian', 1]],
['Detrending', 6, ['legendre', 3 ,'GM']],
['GlobalSignalRegression', 7, ['GS']],
['TaskRegression', 8, []],
],
'B': [ #Satterthwaite et al. 2013 (Ciric7)
['VoxelNormalization', 1, ['demean']],
['Detrending', 2, ['poly', 2, 'wholebrain']],
['TemporalFiltering', 3, ['Butter', 0.01, 0.08]],
['MotionRegression', 4, ['R dR R^2 dR^2']],
['TissueRegression', 4, ['WMCSF+dt+sq', 'wholebrain']],
['GlobalSignalRegression', 4, ['GS+dt+sq']],
['Scrubbing', 4, ['RMS', 0.25]]
],
'C': [ #Siegel et al. 2016 (SiegelB)
['VoxelNormalization', 1, ['demean']],
['Detrending', 2, ['poly', 1, 'wholebrain']],
['TissueRegression', 3, ['CompCor', 5, 'WMCSF', 'wholebrain']],
['TissueRegression', 3, ['GM', 'wholebrain']],
['GlobalSignalRegression', 3, ['GS']],
['MotionRegression', 3, ['censoring']],
['Scrubbing', 3, ['FD+DVARS', 0.25, 5]],
['TemporalFiltering', 4, ['Butter', 0.009, 0.08]]
],
'B0': [ # same as B, with very small change to force recomputation after bug discovered in polynomial filtering 2/12/2018
['VoxelNormalization', 1, ['demean']],
['Detrending', 2, ['poly', 2, 'wholebrain']],
['TemporalFiltering', 3, ['Butter', 0.01, 0.0801]],
['MotionRegression', 4, ['R dR R^2 dR^2']],
['TissueRegression', 4, ['WMCSF+dt+sq', 'wholebrain']],
['GlobalSignalRegression', 4, ['GS+dt+sq']],
['Scrubbing', 4, ['RMS', 0.25]]
],
'C0': [ # same as C, with very small change to force recomputation after bug discovered in polynomial filtering 2/12/2018
['VoxelNormalization', 1, ['demean']],
['Detrending', 2, ['poly', 1, 'wholebrain']],
['TissueRegression', 3, ['CompCor', 5, 'WMCSF', 'wholebrain']],
['TissueRegression', 3, ['GM', 'wholebrain']],
['GlobalSignalRegression', 3, ['GS']],
['MotionRegression', 3, ['censoring']],
['Scrubbing', 3, ['FD+DVARS', 0.25, 5]],
['TemporalFiltering', 4, ['Butter', 0.009, 0.0801]]
]
}
#----------------------------------
#----------------------------------
# HELPER FUNCTIONS
# several of these functions may not be used
# for the specific analyses conducted
# in intelligence.ipynb and personality.ipynb
#----------------------------------
##
# @brief Apply filter to regressors
#
# @param [int] regressors (nTRs,n) array of n regressors to be filtered
# @param [int] filtering filtering method, either 'Butter' or 'Gaussian'
# @param [int] nTRs number of time points
# @param [int] TR repetition time
# @return [np.array] filtered regressors
#
def filter_regressors(regressors, filtering, nTRs, TR):
if len(filtering)==0:
print('Warning! Missing or wrong filtering flavor. Regressors were not filtered.')
else:
if filtering[0] == 'Butter':
regressors = clean(regressors, detrend=False, standardize=False,
t_r=TR, high_pass=filtering[1], low_pass=filtering[2])
elif filtering[0] == 'Gaussian':
regressors = gaussian_filter1d(regressors, filtering[1], axis=0)
return regressors
##
# @brief Apply voxel-wise linear regression to input image
#
# @param [numpy.array] data input image
# @param [int] nTRs number of time points
# @param [float] TR repetition time
# @param [numpy.array] regressors (nTRs,n) array of n regressors
# @param [bool] preWhitening True if preWhitening should be applied
# @return [numpy.array] residuals of regression, same dimensions as data
#
def regress(data, nTRs, TR, regressors, preWhitening=False):
print('Starting regression with {} regressors...'.format(regressors.shape[1]))
if preWhitening:
W = prewhitening(data, nTRs, TR, regressors)
data = np.dot(data,W)
regressors = np.dot(W,regressors)
X = np.concatenate((np.ones([nTRs,1]), regressors), axis=1)
N = data.shape[0]
start_time = time()
fit = np.linalg.lstsq(X, data.T, rcond=None)[0]
fittedvalues = np.dot(X, fit)
resid = data - fittedvalues.T
data = resid
elapsed_time = time() - start_time
print('Regression completed in {:02d}h{:02d}min{:02d}s'.format(int(np.floor(elapsed_time/3600)),int(np.floor((elapsed_time%3600)/60)),int(np.floor(elapsed_time%60))))
return data
##
# @brief Create Legendre polynomial regressor
#
# @param [int] order degree of polynomial
# @param [int] nTRs number of time points
# @return [numpy.array] polynomial regressors
#
def legendre_poly(order, nTRs):
# ** a) create polynomial regressor **
x = np.arange(nTRs)
x = x - x.max()/2
num_pol = range(order+1)
y = np.ones((len(num_pol),len(x)))
coeff = np.eye(order+1)
for i in num_pol:
myleg = Legendre(coeff[i])
y[i,:] = myleg(x)
if i>0:
y[i,:] = y[i,:] - np.mean(y[i,:])
y[i,:] = y[i,:]/np.max(y[i,:])
return y
##
# @brief Load Nifti data
#
# @param [str] volFile filename of volumetric file to be loaded
# @param [numpy.array] maskAll whole brain mask
# @param [bool] unzip True if memmap should be used to load data
# @return [tuple] image data, no. of rows in image, no. if columns in image, no. of slices in image, no. of time points, affine matrix and repetition time
#
def load_img(volFile,maskAll=None,unzip=config.useMemMap):
if unzip:
volFileUnzip = volFile.replace('.gz','')
if not op.isfile(volFileUnzip):
with open(volFile, 'rb') as fFile:
decompressedFile = gzip.GzipFile(fileobj=fFile)
with open(volFileUnzip, 'wb') as outfile:
outfile.write(decompressedFile.read())
img = nib.load(volFileUnzip)
else:
img = nib.load(volFile)
try:
nRows, nCols, nSlices, nTRs = img.header.get_data_shape()
except:
nRows, nCols, nSlices = img.header.get_data_shape()
nTRs = 1
TR = img.header.structarr['pixdim'][4]
if unzip:
data = np.memmap(volFile, dtype=img.header.get_data_dtype(), mode='c', order='F',
offset=img.dataobj.offset,shape=img.header.get_data_shape())
if nTRs==1:
data = data.reshape(nRows*nCols*nSlices, order='F')[maskAll,:]
else:
data = data.reshape((nRows*nCols*nSlices,data.shape[3]), order='F')[maskAll,:]
else:
if nTRs==1:
data = np.asarray(img.dataobj).reshape(nRows*nCols*nSlices, order='F')[maskAll]
else:
data = np.asarray(img.dataobj).reshape((nRows*nCols*nSlices,nTRs), order='F')[maskAll,:]
return data, nRows, nCols, nSlices, nTRs, img.affine, TR, img.header
##
# @brief Create whole brain and tissue masks
#
# @param [bool] overwrite True if existing files should be overwritten
# @return [tuple] whole brain, white matter, cerebrospinal fluid and gray matter masks
#
def makeTissueMasks(overwrite=False,precomputed=False):
if config.isCifti:
prefix = config.session+'_' if hasattr(config,'session') else ''
fmriFile = op.join(buildpath(), prefix+config.fmriRun+'.nii.gz')
else:
fmriFile = config.fmriFile
WMmaskFileout = op.join(outpath(), 'WMmask.nii')
CSFmaskFileout = op.join(outpath(), 'CSFmask.nii')
GMmaskFileout = op.join(outpath(), 'GMmask.nii')
if not op.isfile(GMmaskFileout) or overwrite:
# load ribbon.nii.gz and wmparc.nii.gz
ribbonFilein = op.join(config.DATADIR, config.subject, 'MNINonLinear','ribbon.nii.gz')
wmparcFilein = op.join(config.DATADIR, config.subject, 'MNINonLinear', 'wmparc.nii.gz')
# make sure it is resampled to the same space as the functional run
ribbonFileout = op.join(outpath(), 'ribbon.nii.gz')
wmparcFileout = op.join(outpath(), 'wmparc.nii.gz')
# make identity matrix to feed to flirt for resampling
ribbonMat = op.join(outpath(), 'ribbon_flirt_{}.mat'.format(config.pipelineName))
wmparcMat = op.join(outpath(), 'wmparc_flirt_{}.mat'.format(config.pipelineName))
eyeMat = op.join(outpath(), 'eye_{}.mat'.format(config.pipelineName))
with open(eyeMat,'w') as fid:
fid.write('1 0 0 0\n0 1 0 0\n0 0 1 0\n0 0 0 1')
flirt_ribbon = fsl.FLIRT(in_file=ribbonFilein, out_file=ribbonFileout,
reference=fmriFile, apply_xfm=True,
in_matrix_file=eyeMat, out_matrix_file=ribbonMat, interp='nearestneighbour')
flirt_ribbon.run()
flirt_wmparc = fsl.FLIRT(in_file=wmparcFilein, out_file=wmparcFileout,
reference=fmriFile, apply_xfm=True,
in_matrix_file=eyeMat, out_matrix_file=wmparcMat, interp='nearestneighbour')
flirt_wmparc.run()
# load nii (ribbon & wmparc)
ribbon = np.asarray(nib.load(ribbonFileout).dataobj)
wmparc = np.asarray(nib.load(wmparcFileout).dataobj)
# white & CSF matter mask
# indices are from FreeSurferColorLUT.txt
# Left-Cerebral-White-Matter, Right-Cerebral-White-Matter
ribbonWMstructures = [2, 41]
# Left-Cerebral-Cortex, Right-Cerebral-Cortex
ribbonGMstrucures = [3, 42]
# Cerebellar-White-Matter-Left, Brain-Stem, Cerebellar-White-Matter-Right
wmparcWMstructures = [7, 16, 46]
# Left-Cerebellar-Cortex, Right-Cerebellar-Cortex, Thalamus-Left, Caudate-Left
# Putamen-Left, Pallidum-Left, Hippocampus-Left, Amygdala-Left, Accumbens-Left
# Diencephalon-Ventral-Left, Thalamus-Right, Caudate-Right, Putamen-Right
# Pallidum-Right, Hippocampus-Right, Amygdala-Right, Accumbens-Right
# Diencephalon-Ventral-Right
wmparcGMstructures = [8, 47, 10, 11, 12, 13, 17, 18, 26, 28, 49, 50, 51, 52, 53, 54, 58, 60]
# Fornix, CC-Posterior, CC-Mid-Posterior, CC-Central, CC-Mid-Anterior, CC-Anterior
wmparcCCstructures = [250, 251, 252, 253, 254, 255]
# Left-Lateral-Ventricle, Left-Inf-Lat-Vent, 3rd-Ventricle, 4th-Ventricle, CSF
# Left-Choroid-Plexus, Right-Lateral-Ventricle, Right-Inf-Lat-Vent, Right-Choroid-Plexus
wmparcCSFstructures = [4, 5, 14, 15, 24, 31, 43, 44, 63]
# make masks
WMmask = np.double(np.logical_and(np.logical_and(np.logical_or(np.logical_or(np.in1d(ribbon, ribbonWMstructures),
np.in1d(wmparc, wmparcWMstructures)),
np.in1d(wmparc, wmparcCCstructures)),
np.logical_not(np.in1d(wmparc, wmparcCSFstructures))),
np.logical_not(np.in1d(wmparc, wmparcGMstructures))))
CSFmask = np.double(np.in1d(wmparc, wmparcCSFstructures))
GMmask = np.double(np.logical_or(np.in1d(ribbon,ribbonGMstrucures),np.in1d(wmparc,wmparcGMstructures)))
# write masks
ref = nib.load(wmparcFileout)
img = nib.Nifti1Image(WMmask.reshape(ref.shape).astype('<f4'), ref.affine)
nib.save(img, WMmaskFileout)
img = nib.Nifti1Image(CSFmask.reshape(ref.shape).astype('<f4'), ref.affine)
nib.save(img, CSFmaskFileout)
img = nib.Nifti1Image(GMmask.reshape(ref.shape).astype('<f4'), ref.affine)
nib.save(img, GMmaskFileout)
# delete temporary files
cmd = 'rm {} {} {}'.format(eyeMat, ribbonMat, wmparcMat)
call(cmd,shell=True)
tmpWM = nib.load(WMmaskFileout)
nRows, nCols, nSlices = tmpWM.header.get_data_shape()
maskWM = np.asarray(tmpWM.dataobj).reshape(nRows*nCols*nSlices, order='F') > 0
tmpCSF = nib.load(CSFmaskFileout)
maskCSF = np.asarray(tmpCSF.dataobj).reshape(nRows*nCols*nSlices, order='F') > 0
tmpGM = nib.load(GMmaskFileout)
maskGM = np.asarray(tmpGM.dataobj).reshape(nRows*nCols*nSlices, order='F') > 0
maskAll = np.logical_or(np.logical_or(maskWM, maskCSF), maskGM)
maskWM_ = maskWM[maskAll]
maskCSF_ = maskCSF[maskAll]
maskGM_ = maskGM[maskAll]
return maskAll, maskWM_, maskCSF_, maskGM_
def extract_noise_components(niiImg, WMmask, CSFmask, num_components=5, flavor=None):
"""
Largely based on https://github.com/nipy/nipype/blob/master/examples/
rsfmri_vol_surface_preprocessing_nipy.py#L261
Derive components most reflective of physiological noise according to
aCompCor method (Behzadi 2007)
Parameters
----------
niiImg: raw data
num_components: number of components to use for noise decomposition
extra_regressors: additional regressors to add
Returns
-------
components: n_time_points x regressors
"""
if flavor == 'WMCSF' or flavor == None:
niiImgWMCSF = niiImg[np.logical_or(WMmask,CSFmask),:]
niiImgWMCSF[np.isnan(np.sum(niiImgWMCSF, axis=1)), :] = 0
# remove mean and normalize by variance
# voxel_timecourses.shape == [nvoxels, time]
X = niiImgWMCSF.T
stdX = np.std(X, axis=0)
stdX[stdX == 0] = 1.
stdX[np.isnan(stdX)] = 1.
stdX[np.isinf(stdX)] = 1.
X = (X - np.mean(X, axis=0)) / stdX
u, _, _ = linalg.svd(X, full_matrices=False)
components = u[:, :num_components]
elif flavor == 'WM+CSF':
niiImgWM = niiImg[WMmask,:]
niiImgWM[np.isnan(np.sum(niiImgWM, axis=1)), :] = 0
niiImgCSF = niiImg[CSFmask,:]
niiImgCSF[np.isnan(np.sum(niiImgCSF, axis=1)), :] = 0
# remove mean and normalize by variance
# voxel_timecourses.shape == [nvoxels, time]
X = niiImgWM.T
stdX = np.std(X, axis=0)
stdX[stdX == 0] = 1.
stdX[np.isnan(stdX)] = 1.
stdX[np.isinf(stdX)] = 1.
X = (X - np.mean(X, axis=0)) / stdX
u, _, _ = linalg.svd(X, full_matrices=False)
components = u[:, :num_components]
X = niiImgCSF.T
stdX = np.std(X, axis=0)
stdX[stdX == 0] = 1.
stdX[np.isnan(stdX)] = 1.
stdX[np.isinf(stdX)] = 1.
X = (X - np.mean(X, axis=0)) / stdX
u, _, _ = linalg.svd(X, full_matrices=False)
components = np.hstack((components, u[:, :num_components]))
return components
##
# @brief Create a XML file describing preprocessing steps
#
# @param [str] inFile filename of input image data
# @param [str] dataDir data directory path
# @param [list] operations pipeline operations
# @param [float] startTime start time of preprocessing
# @param [float] endTime end time of preprocessing
# @param [str] fname filename of XML log file
#
def conf2XML(inFile, dataDir, operations, startTime, endTime, fname):
doc = ET.Element("pipeline")
nodeInput = ET.SubElement(doc, "input")
nodeInFile = ET.SubElement(nodeInput, "inFile")
nodeInFile.text = inFile
nodeDataDir = ET.SubElement(nodeInput, "dataDir")
nodeDataDir.text = dataDir
nodeDate = ET.SubElement(doc, "date")
nodeDay = ET.SubElement(nodeDate, "day")
day = strftime("%Y-%m-%d", localtime())
nodeDay.text = day
stime = strftime("%H:%M:%S", startTime)
etime = strftime("%H:%M:%S", endTime)
nodeStart = ET.SubElement(nodeDate, "timeStart")
nodeStart.text = stime
nodeEnd = ET.SubElement(nodeDate, "timeEnd")
nodeEnd.text = etime
nodeSteps = ET.SubElement(doc, "steps")
for op in operations:
if op[1] == 0: continue
nodeOp = ET.SubElement(nodeSteps, "operation", name=op[0])
nodeOrder = ET.SubElement(nodeOp, "order")
nodeOrder.text = str(op[1])
nodeFlavor = ET.SubElement(nodeOp, "flavor")
nodeFlavor.text = str(op[2])
tree = ET.ElementTree(doc)
tree.write(fname)
##
# @brief Create string timestamp
#
# @return [str] timestamp
#
def timestamp():
now = time()
loctime = localtime(now)
milliseconds = '%03d' % int((now - int(now)) * 1000)
return strftime('%Y%m%d%H%M%S', loctime) + milliseconds
def prepareJobArrayFromJobList():
config.tStamp = timestamp()
# make directory
mkdir('tmp{}'.format(config.tStamp))
# write a temporary file with the list of scripts to execute as an array job
with open(op.join('tmp{}'.format(config.tStamp),'scriptlist'),'w') as f:
f.write('\n'.join(config.scriptlist))
# write the .qsub file
with open(op.join('tmp{}'.format(config.tStamp),'qsub'),'w') as f:
f.write('#!/bin/bash\n')
f.write('#$ -S /bin/bash\n')
f.write('#$ -t 1-{} -tc 7\n'.format(len(config.scriptlist)))
f.write('#$ -cwd -V -N tmp{}\n'.format(config.tStamp))
f.write('#$ -e {}\n'.format(op.join('tmp{}'.format(config.tStamp),'err')))
f.write('#$ -o {}\n'.format(op.join('tmp{}'.format(config.tStamp),'out')))
f.write('#$ {}\n'.format(config.sgeopts))
f.write('SCRIPT=$(awk "NR==$SGE_TASK_ID" {})\n'.format(op.join('tmp{}'.format(config.tStamp),'scriptlist')))
f.write('bash $SCRIPT\n')
strCommand = 'qsub {}'.format(op.join('tmp{}'.format(config.tStamp),'qsub'))
# write down the command to a file in the job folder
with open('cmd','w+') as f:
f.write(strCommand+'\n')
config.scriptlist = []
return
##
# @brief Submit jobs with sge qsub
#
def fnSubmitToCluster(strScript, strJobFolder, strJobUID, resources='-l mem_free=25G -pe openmp 6', specifyqueue='long.q'):
# clean up .o and .e
tmpfname = op.join(strJobFolder,strJobUID)
try:
remove(tmpfname+'.e')
except OSError:
pass
try:
remove(tmpfname+'.o')
except OSError:
pass
strCommand = 'qsub {} -cwd -V {} -N {} -e {} -o {} {}'.format(specifyqueue,resources,strJobUID,
op.join(strJobFolder,strJobUID+'.e'), op.join(strJobFolder,strJobUID+'.o'), strScript)
# write down the command to a file in the job folder
with open(op.join(strJobFolder,strJobUID+'.cmd'),'w+') as hFileID:
hFileID.write(strCommand+'\n')
# execute the command
cmdOut = check_output(strCommand, shell=True)
return cmdOut.split()[2]
##
# @brief Submit array of jobs with sge qsub (needs to be customized)
#
def fnSubmitJobArrayFromJobList():
config.tStamp = timestamp()
# make directory
mkdir('tmp{}'.format(config.tStamp))
# write a temporary file with the list of scripts to execute as an array job
with open(op.join('tmp{}'.format(config.tStamp),'scriptlist'),'w') as f:
f.write('\n'.join(config.scriptlist))
# write the .qsub file
with open(op.join('tmp{}'.format(config.tStamp),'qsub'),'w') as f:
f.write('#!/bin/bash\n')
f.write('#$ -S /bin/bash\n')
f.write('#$ -t 1-{} -tc 8\n'.format(len(config.scriptlist)))
f.write('#$ -cwd -V -N tmp{}\n'.format(config.tStamp))
f.write('#$ -e {}\n'.format(op.join('tmp{}'.format(config.tStamp),'err')))
f.write('#$ -o {}\n'.format(op.join('tmp{}'.format(config.tStamp),'out')))
f.write('#$ {}\n'.format(config.sgeopts))
f.write('SCRIPT=$(awk "NR==$SGE_TASK_ID" {})\n'.format(op.join('tmp{}'.format(config.tStamp),'scriptlist')))
f.write('bash $SCRIPT\n')
strCommand = 'qsub {}'.format(op.join('tmp{}'.format(config.tStamp),'qsub'))
#strCommand = 'ssh csclprd3s1 "cd {};qsub {}"'.format(getcwd(),op.join('tmp{}'.format(config.tStamp),'qsub'))
# write down the command to a file in the job folder
with open(op.join('tmp{}'.format(config.tStamp),'cmd'),'w+') as f:
f.write(strCommand+'\n')
# execute the command
cmdOut = check_output(strCommand, shell=True)
config.scriptlist = []
return cmdOut.split()[2]
##
# @brief Submit jobs with sge qsub
#
def fnSubmitToCluster(strScript, strJobFolder, strJobUID, resources='-l mem_free=25G -pe openmp 6', specifyqueue='long.q'):
# clean up .o and .e
tmpfname = op.join(strJobFolder,strJobUID)
try:
remove(tmpfname+'.e')
except OSError:
pass
try:
remove(tmpfname+'.o')
except OSError:
pass
strCommand = 'qsub {} -cwd -V {} -N {} -e {} -o {} {}'.format(specifyqueue,resources,strJobUID,
op.join(strJobFolder,strJobUID+'.e'), op.join(strJobFolder,strJobUID+'.o'), strScript)
# write down the command to a file in the job folder
with open(op.join(strJobFolder,strJobUID+'.cmd'),'w+') as hFileID:
hFileID.write(strCommand+'\n')
# execute the command
cmdOut = check_output(strCommand, shell=True)
return cmdOut.split()[2]
##
# @brief Return list of files ordered by edit time
#
# @param [str] path directory of files to be listed
# @param [bool] reverseOrder True if files should be sorted by most recent
# @return [list] file list ordered by edit time
#
def sorted_ls(path, reverseOrder):
mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
return list(sorted(os.listdir(path), key=mtime, reverse=reverseOrder))
##
# @brief Check if preprocessing has already been performed
#
# @param [str] inFile input image data file
# @param [list] operations pipeline operations
# @param [list] params pipeline operation params
# @param [str] resDir directory path where results are stored
# @param [bool] useMostRecent True if most recent files should be checked first
# @return [str] preprocessed image file name if exists, None otherwise
#
def checkXML(inFile, operations, params, resDir, isCifti=False, useMostRecent=True):
fileList = sorted_ls(resDir, useMostRecent)
for xfile in fileList:
if fnmatch.fnmatch(op.join(resDir,xfile), op.join(resDir,'????????.xml')):
tree = ET.parse(op.join(resDir,xfile))
root = tree.getroot()
tvalue = op.basename(root[0][0].text) == op.basename(inFile)
if not tvalue:
continue
if len(root[2]) != np.sum([len(ops) for ops in operations.values()]):
continue
try:
if max([int(el[0].text) for el in root[2]]) != len(operations):
continue
except:
continue
for el in root[2]:
try:
tvalue = tvalue and (el.attrib['name'] in operations[int(el[0].text)])
tvalue = tvalue and (el[1].text in [repr(param) for param in params[int(el[0].text)]])
except:
tvalue = False
if not tvalue:
continue
else:
rcode = xfile.replace('.xml','')
return op.join(resDir,config.fmriRun+'_prepro_'+rcode+config.ext)
return None
##
# @brief Extract random identifier from preprocessed image filename
#
# @param [str] mystring preprocessed image filename
# @return [str] string identifier
#
def get_rcode(mystring):
if not config.isCifti:
return re.search('.*_(........)\.nii.gz', mystring).group(1)
else:
return re.search('.*_(........)\.dtseries.nii', mystring).group(1)
def _make_gen(reader):
b = reader(1024 * 1024)
while b:
yield b
b = reader(1024*1024)
def rawgencount(filename):
f = open(filename, 'rb')
f_gen = _make_gen(f.read)
return sum( buf.count(b'\n') for buf in f_gen )
"""
The following functions implement the ICA-AROMA algorithm (Pruim et al. 2015)
and are adapted from https://github.com/rhr-pruim/ICA-AROMA
"""
def feature_time_series(melmix, mc):
""" This function extracts the maximum RP correlation feature scores.
It determines the maximum robust correlation of each component time-series
with a model of 72 realigment parameters.
Parameters
---------------------------------------------------------------------------------
melmix: Full path of the melodic_mix text file
mc: Full path of the text file containing the realignment parameters
Returns
---------------------------------------------------------------------------------
maxRPcorr: Array of the maximum RP correlation feature scores for the components of the melodic_mix file"""
# Read melodic mix file (IC time-series), subsequently define a set of squared time-series
mix = np.loadtxt(melmix)
mixsq = np.power(mix,2)
# Read motion parameter file
RP6 = np.loadtxt(mc)[:,:6]
# Determine the derivatives of the RPs (add zeros at time-point zero)
RP6_der = np.array(RP6[list(range(1,RP6.shape[0])),:] - RP6[list(range(0,RP6.shape[0]-1)),:])
RP6_der = np.concatenate((np.zeros((1,6)),RP6_der),axis=0)
# Create an RP-model including the RPs and its derivatives
RP12 = np.concatenate((RP6,RP6_der),axis=1)
# Add the squared RP-terms to the model
RP24 = np.concatenate((RP12,np.power(RP12,2)),axis=1)
# Derive shifted versions of the RP_model (1 frame for and backwards)
RP24_1fw = np.concatenate((np.zeros((1,24)),np.array(RP24[list(range(0,RP24.shape[0]-1)),:])),axis=0)
RP24_1bw = np.concatenate((np.array(RP24[list(range(1,RP24.shape[0])),:]),np.zeros((1,24))),axis=0)
# Combine the original and shifted mot_pars into a single model
RP_model = np.concatenate((RP24,RP24_1fw,RP24_1bw),axis=1)
# Define the column indices of respectively the squared or non-squared terms
idx_nonsq = np.array(np.concatenate((list(range(0,12)), list(range(24,36)), list(range(48,60))),axis=0))
idx_sq = np.array(np.concatenate((list(range(12,24)), list(range(36,48)), list(range(60,72))),axis=0))
# Determine the maximum correlation between RPs and IC time-series
nSplits=int(1000)
maxTC = np.zeros((nSplits,mix.shape[1]))
for i in range(0,nSplits):
# Get a random set of 90% of the dataset and get associated RP model and IC time-series matrices
idx = np.array(random.sample(list(range(0,mix.shape[0])),int(round(0.9*mix.shape[0]))))
RP_model_temp = RP_model[idx,:]
mix_temp = mix[idx,:]
mixsq_temp = mixsq[idx,:]
# Calculate correlation between non-squared RP/IC time-series
RP_model_nonsq = RP_model_temp[:,idx_nonsq]
cor_nonsq = np.array(np.zeros((mix_temp.shape[1],RP_model_nonsq.shape[1])))
for j in range(0,mix_temp.shape[1]):
for k in range(0,RP_model_nonsq.shape[1]):
cor_temp = np.corrcoef(mix_temp[:,j],RP_model_nonsq[:,k])
cor_nonsq[j,k] = cor_temp[0,1]
# Calculate correlation between squared RP/IC time-series
RP_model_sq = RP_model_temp[:,idx_sq]
cor_sq = np.array(np.zeros((mix_temp.shape[1],RP_model_sq.shape[1])))
for j in range(0,mixsq_temp.shape[1]):
for k in range(0,RP_model_sq.shape[1]):
cor_temp = np.corrcoef(mixsq_temp[:,j],RP_model_sq[:,k])
cor_sq[j,k] = cor_temp[0,1]
# Combine the squared an non-squared correlation matrices
corMatrix = np.concatenate((cor_sq,cor_nonsq),axis=1)
# Get maximum absolute temporal correlation for every IC
corMatrixAbs = np.abs(corMatrix)
maxTC[i,:] = corMatrixAbs.max(axis=1)
# Get the mean maximum correlation over all random splits
maxRPcorr = maxTC.mean(axis=0)
# Return the feature score
return maxRPcorr
def feature_frequency(melFTmix, TR):
"""
Taken from https://github.com/rhr-pruim/ICA-AROMA
This function extracts the high-frequency content feature scores.
It determines the frequency, as fraction of the Nyquist frequency,
at which the higher and lower frequencies explain half of the total power between 0.01Hz and Nyquist.
Parameters
---------------------------------------------------------------------------------
melFTmix: Full path of the melodic_FTmix text file
TR: TR (in seconds) of the fMRI data (float)
Returns
---------------------------------------------------------------------------------
HFC: Array of the HFC ('High-frequency content') feature scores for the components of the melodic_FTmix file"""
# Determine sample frequency
Fs = old_div(1,TR)
# Determine Nyquist-frequency
Ny = old_div(Fs,2)
# Load melodic_FTmix file
FT=np.loadtxt(melFTmix)
# Determine which frequencies are associated with every row in the melodic_FTmix file (assuming the rows range from 0Hz to Nyquist)
f = Ny*(np.array(list(range(1,FT.shape[0]+1))))/(FT.shape[0])
# Only include frequencies higher than 0.01Hz
fincl = np.squeeze(np.array(np.where( f > 0.01 )))
FT=FT[fincl,:]
f=f[fincl]
# Set frequency range to [0-1]
f_norm = old_div((f-0.01),(Ny-0.01))
# For every IC; get the cumulative sum as a fraction of the total sum
fcumsum_fract = old_div(np.cumsum(FT,axis=0), np.sum(FT,axis=0))
# Determine the index of the frequency with the fractional cumulative sum closest to 0.5
idx_cutoff=np.argmin(np.abs(fcumsum_fract-0.5),axis=0)
# Now get the fractions associated with those indices index, these are the final feature scores
HFC = f_norm[idx_cutoff]
# Return feature score
return HFC
def feature_spatial(fslDir, tempDir, aromaDir, melIC):
"""
Taken from https://github.com/rhr-pruim/ICA-AROMA
This function extracts the spatial feature scores.
For each IC it determines the fraction of the mixture modeled thresholded Z-maps
respecitvely located within the CSF or at the brain edges, using predefined standardized masks.
Parameters
---------------------------------------------------------------------------------
fslDir: Full path of the bin-directory of FSL
tempDir: Full path of a directory where temporary files can be stored (called 'temp_IC.nii.gz')
aromaDir: Full path of the ICA-AROMA directory, containing the mask-files (mask_edge.nii.gz, mask_csf.nii.gz & mask_out.nii.gz)
melIC: Full path of the nii.gz file containing mixture-modeled threholded (p>0.5) Z-maps, registered to the MNI152 2mm template
Returns
---------------------------------------------------------------------------------
edgeFract: Array of the edge fraction feature scores for the components of the melIC file
csfFract: Array of the CSF fraction feature scores for the components of the melIC file"""
EDGEmaskFileout = op.join(outpath(), 'EDGEmask.nii')
if not op.isfile(EDGEmaskFileout):
WMmaskFileout = op.join(outpath(), 'WMmask.nii')
CSFmaskFileout = op.join(outpath(), 'CSFmask.nii')
GMmaskFileout = op.join(outpath(), 'GMmask.nii')
OUTmaskFileout = op.join(outpath(), 'OUTmask.nii')
tmpWM = nib.load(WMmaskFileout)
nRows, nCols, nSlices = tmpWM.header.get_data_shape()
tmpCSF = nib.load(CSFmaskFileout)
tmpGM = nib.load(GMmaskFileout)
maskGM = np.asarray(tmpGM.dataobj).reshape(nRows*nCols*nSlices, order='F') > 0
GMWMmask = np.logical_or(tmpWM.dataobj,tmpGM.dataobj)
ALLmask = np.logical_or(GMWMmask, tmpCSF.dataobj)
ALLclose = binary_closing(ALLmask,structure=generate_binary_structure(3,4))
OUTmask = binary_erosion(np.logical_not(ALLclose),structure=generate_binary_structure(3,2),border_value=1)
OUTmask = binary_opening(OUTmask,structure=generate_binary_structure(3,2))
img = nib.Nifti1Image(OUTmask.astype('<f4'), tmpWM.affine)
nib.save(img, OUTmaskFileout)
OUTdil = binary_dilation(OUTmask, structure=generate_binary_structure(3,5),iterations=2)
GMWMdil = binary_dilation(GMWMmask, structure=generate_binary_structure(3,5))
CSFdil = binary_dilation(tmpCSF.dataobj, structure=generate_binary_structure(3,5),iterations=2)
CSFero = binary_erosion(CSFdil, iterations=4)
EDGEmask = np.logical_or(binary_opening(np.logical_and(CSFdil,GMWMdil)),binary_closing(np.logical_and(GMWMdil,OUTdil)))
EDGEmask = np.logical_and(EDGEmask, binary_opening(np.logical_not(CSFero)))
img = nib.Nifti1Image(EDGEmask.astype('<f4'), tmpWM.affine)
nib.save(img, EDGEmaskFileout)
# Get the number of ICs
numICs = int(getoutput('%sfslinfo %s | grep dim4 | head -n1 | awk \'{print $2}\'' % (fslDir, melIC) ))
# Loop over ICs
edgeFract=np.zeros(numICs)
csfFract=np.zeros(numICs)
for i in range(0,numICs):
# Define temporary IC-file
tempIC = op.join(tempDir,'temp_IC.nii.gz')
# Extract IC from the merged melodic_IC_thr2MNI2mm file
os.system(' '.join([op.join(fslDir,'fslroi'),
melIC,
tempIC,
str(i),
'1']))
# Change to absolute Z-values
os.system(' '.join([op.join(fslDir,'fslmaths'),
tempIC,
'-abs',
tempIC]))
# Get sum of Z-values within the total Z-map (calculate via the mean and number of non-zero voxels)
totVox = int(getoutput(' '.join([op.join(fslDir,'fslstats'),
tempIC,
'-V | awk \'{print $1}\''])))
if not (totVox == 0):
totMean = float(getoutput(' '.join([op.join(fslDir,'fslstats'),
tempIC,
'-M'])))
else:
print(' - The spatial map of component ' + str(i+1) + ' is empty. Please check!')
totMean = 0
totSum = totMean * totVox
# Get sum of Z-values of the voxels located within the CSF (calculate via the mean and number of non-zero voxels)
csfVox = int(getoutput(' '.join([op.join(fslDir,'fslstats'),
tempIC,
'-k {}/CSFmask.nii'.format(aromaDir),
'-V | awk \'{print $1}\''])))
if not (csfVox == 0):
csfMean = float(getoutput(' '.join([op.join(fslDir,'fslstats'),
tempIC,