forked from HBClab/RestingState
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqualityCheck.sh
More file actions
executable file
·1470 lines (1230 loc) · 56.5 KB
/
qualityCheck.sh
File metadata and controls
executable file
·1470 lines (1230 loc) · 56.5 KB
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
#!/bin/bash
##################################################################################################################
# Motion Correction and Other inital processing for Resting State Analysis
# 1. Motion Correction
# 2. SNR Estimation
# 4. Spike Detection
# 5. Registration
# a. T1 to MNI (flirt/fnirt), with/without lesion mask optimization
# b. EPI to T1 (BBR), with/without FieldMap correction
##################################################################################################################
#Commenting out code I want to remove (RM)
#(RM)scriptPath=`perl -e 'use Cwd "abs_path";print abs_path(shift)' $0`
#(RM)scriptDir=`dirname $scriptPath`
#clobber default
clob=false
# Parse Command line arguments
while getopts “hE:A:a:l:fb:v:x:D:d:o:m:c” OPTION
do
case $OPTION in
h)
printCommandLine
;;
E)
epiData=$OPTARG
;;
A)
T1_brain=$OPTARG
;;
a)
T1_head=$OPTARG
;;
m)
T1_mask=$OPTARG
;;
o)
outDir=$OPTARG
;;
l)
#lesionMask=$OPTARG
lesionMaskFlag=1
;;
f)
fieldMapFlag=1
;;
b)
fieldMap=$OPTARG
;;
v)
fieldMapMagHead=$OPTARG
;;
x)
fieldMapMagBrain=$OPTARG
;;
D)
dwellTime=$OPTARG
;;
d)
peDir=$OPTARG
;;
c)
clob=true
;;
?)
echo "ERROR: Invalid option"
printCommandLine
;;
esac
done
############################# HELPER FUNCTIONS #############################
function printCommandLine {
echo "Usage: qualityCheck.sh -E restingStateImage -a T1Image -A T1SkullImage -l lesionMask -f -b fieldMapPrepped -v fieldMapMagSkull -x fieldMapMag -D 0.00056 -d PhaseEncDir -c"
echo ""
echo " where:"
echo " -E Resting State file"
echo " -A T1 file"
echo " -a T1 (with skull) file"
echo " -o subject base(output) directory"
echo " *Both EPI and T1 (with and without skull) should be from output of dataPrep script"
echo " -m T1 brain mask"
echo " -l Binary lesion mask"
echo " -f (fieldMap registration correction)"
echo " -b fieldMapPrepped (B0 correction image from dataPrep/fsl_prepare_fieldmap)"
echo " -v fieldMapMagSkull (FieldMap Magnitude image, with skull (from dataPrep))"
echo " -x fieldMapMag (FieldMap Magnitude image, skull-stripped (from dataPrep))"
echo " -D dwell time (in seconds)"
echo " *dwell time is from the EPI but is only set if FieldMap correction ('-f') is chosen."
echo " *If not set and FieldMap correction is flagged ('-f'), default is 0.00056"
echo " -d Phase Encoding Direction (from dataPrep)"
echo " *Options are x/y/z/-x/-y/-z"
echo " -c clobber/overwrite previous results"
exit 1
}
##################
#function: clobber
##################
#purpose: checks to see if files exist and overwrites them when clob is set to true
##################
#input: any number of filenames that may or may not exist
##################
#output: a 1 (false) or 0 (true)
##################
#dependencies: None
##################
#Used in: (almost) Everything
##################
function clobber()
{
#Tracking Variables
local -i num_existing_files=0
local -i num_args=$#
#Tally all existing outputs
for arg in $@; do
if [ -e "${arg}" ] && [ "${clob}" == true ]; then
rm -rf "${arg}"
elif [ -e "${arg}" ] && [ "${clob}" == false ]; then
num_existing_files=$(( ${num_existing_files} + 1 ))
continue
elif [ ! -e "${arg}" ]; then
continue
else
echo "How did you get here?"
fi
done
#see if the command should be run by seeing if the requisite files exist.
#0=true
#1=false
if [ ${num_existing_files} -lt ${num_args} ]; then
return 0
else
return 1
fi
#example usage
#clobber test.nii.gz &&\
#fslmaths input.nii.gz -mul 10 test.nii.gz
}
##################
#function: RPI_orient
##################
#purpose: Checks to see if input is in R->L,P->A,I->S orientation, and switches the image around if it isn't
##################
#input: a 3d nifti image
##################
#output: a 3d nifti image in RPI orientation
##################
#dependencies: FSL
##################
#Used in: lesionMaskprep
##################
function RPI_orient() {
#JK: probably overkill to check the variable was set without error.
local infile=$1 &&\
#-z tests if a string is null, so what I'm saying here is:
#if the variable ${infile} is not an empty string (return 0) then don't run the following command
#if the variable ${infile} is an empty string (return 1), then do run the next command.
[ ! -z "${infile}" ] ||\
#I used () brackets, but should be {} I believe.
{ printf '%s\n' "${FUNCNAME[0]}, input not defined" && return 1 ;}
#Determine qform-orientation to properly reorient file to RPI (MNI) orientation
xorient=`fslhd ${infile} | grep "^qform_xorient" | awk '{print $2}' | cut -c1`
yorient=`fslhd ${infile} | grep "^qform_yorient" | awk '{print $2}' | cut -c1`
zorient=`fslhd ${infile} | grep "^qform_zorient" | awk '{print $2}' | cut -c1`
native_orient=${xorient}${yorient}${zorient}
echo "native orientation = ${native_orient}"
if [ "${native_orient}" != "RPI" ]; then #setting flip flags if native orientaiton is not already RPI
case ${native_orient} in
#L PA IS
LPI)
flipFlag="-x y z"
;;
LPS)
flipFlag="-x y -z"
;;
LAI)
flipFlag="-x -y z"
;;
LAS)
flipFlag="-x -y -z"
;;
#R PA IS
RPS)
flipFlag="x y -z"
;;
RAI)
flipFlag="x -y z"
;;
RAS)
flipFlag="x -y -z"
;;
#L IS PA
LIP)
flipFlag="-x z y"
;;
LIA)
flipFlag="-x -z y"
;;
LSP)
flipFlag="-x z -y"
;;
LSA)
flipFlag="-x -z -y"
;;
#R IS PA
RIP)
flipFlag="x z y"
;;
RIA)
flipFlag="x -z y"
;;
RSP)
flipFlag="x z -y"
;;
RSA)
flipFlag="x -z -y"
;;
#P IS LR
PIL)
flipFlag="-z x y"
;;
PIR)
flipFlag="z x y"
;;
PSL)
flipFlag="-z x -y"
;;
PSR)
flipFlag="z x -y"
;;
#A IS LR
AIL)
flipFlag="-z -x y"
;;
AIR)
flipFlag="z -x y"
;;
ASL)
flipFlag="-z -x -y"
;;
ASR)
flipFlag="z -x -y"
;;
#P LR IS
PLI)
flipFlag="-y x z"
;;
PLS)
flipFlag="-y x -z"
;;
PRI)
flipFlag="y x z"
;;
PRS)
flipFlag="y x -z"
;;
#A LR IS
ALI)
flipFlag="-y -x z"
;;
ALS)
flipFlag="-y -x -z"
;;
ARI)
flipFlag="y -x z"
;;
ARS)
flipFlag="y -x -z"
;;
#I LR PA
ILP)
flipFlag="-y z x"
;;
ILA)
flipFlag="-y -z x"
;;
IRP)
flipFlag="y z x"
;;
IRA)
flipFlag="y -z x"
;;
#S LR PA
SLP)
flipFlag="-y z -x"
;;
SLA)
flipFlag="-y -z -x"
;;
SRP)
flipFlag="y z -x"
;;
SRA)
flipFlag="y -z -x"
;;
#I PA LR
IPL)
flipFlag="-z y x"
;;
IPR)
flipFlag="z y x"
;;
IAL)
flipFlag="-z -y x"
;;
IAR)
flipFlag="z -y x"
;;
#S PA LR
SPL)
flipFlag="-z y -x"
;;
SPR)
flipFlag="z y -x"
;;
SAL)
flipFlag="-z -y -x"
;;
SAR)
flipFlag="z -y -x"
;;
esac
echo "flipping by ${flipFlag}"
#Reorienting image and checking for warning messages
local warnFlag=`fslswapdim ${infile} ${flipFlag} ${infile%.nii.gz}_RPI.nii.gz`
local warnFlagCut=`echo ${warnFlag} | awk -F":" '{print $1}'`
#Reorienting the file may require swapping out the flag orientation to match the .img block
if [[ $warnFlagCut == "WARNING" ]]; then
fslorient -swaporient ${infile%.nii.gz}_RPI.nii.gz
fi
else
echo "No need to reorient. Dataset already in RPI orientation."
if [ ! -e ${infile%.nii.gz}_RPI.nii.gz ]; then
cp ${infile} ${infile%.nii.gz}_RPI.nii.gz
fi
fi
}
##################
#function: lesionMaskPrep
##################
#purpose: reorients the lesion mask and inverts the mask
##################
#preconditions: Already ran dataPrep.sh
##################
#input (typical): lesionMask (from option -m)
# ${outDir} (from option -o)
##################
#output: ${outDir}/func/T1forWarp
# ${outDir}/func/T1forWarp/T1_lesionmask.nii.gz
# ${outDir}/func/T1forWarp/T1_lesionmask_RPI.nii.gz
# ${outDir}/func/T1forWarp/LesionWeight.nii.gz
##################
#dependencies: FSL, RPI_Orient, clobber
##################
#Used in: T1ToStd
##################
function lesionMaskPrep()
{
local lesionMask=$1
local outDir=$2
printf "%s\n" "...Prepping the Lesion Mask"
mkdir -p ${outDir}/func/T1forWarp ||\
{ printf "%s\n" "creation of directory T1forWarp failed, exiting ${FUNCNAME}" && return 1; }
#Create a temporaray binary lesion mask (in case it's not char, binary format)
clobber ${outDir}/func/T1forWarp/T1_lesionmask.nii.gz &&\
{ fslmaths ${lesionMask} -bin ${outDir}/func/T1forWarp/T1_lesionmask.nii.gz -odt char ||\
{ printf "%s\n" "creation of ${outDir}/func/T1forWarp/T1_mask.nii.gz failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Orient lesion mask to RPI
clobber ${outDir}/func/T1forWarp/T1_lesionmask_RPI.nii.gz &&\
{ RPI_Orient ${outDir}/func/T1forWarp/T1_lesionmask.nii.gz ||\
{ printf "%s\n" "creation of ${outDir}/func/T1forWarp/T1_lesionmask_RPI.nii.gz failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Invert the lesion mask
clobber ${outDir}/func/T1forWarp/LesionWeight.nii.gz &&\
{ fslmaths ${outDir}/func/T1forWarp/T1_lesionmask_RPI.nii.gz -mul -1 -add 1 -thr 0.5 -bin ${outDir}/func/T1forWarp/LesionWeight.nii.gz ||\
{ printf "%s\n" "creation of ${outDir}/func/T1forWarp/LesionWeight.nii.gz failed, exiting ${FUNCNAME}" && return 1 ;} ;}
printf "%s\n" "${FUNCNAME} completed successfully"
}
##################
#function: EPItoT1FieldMap
##################
#purpose: makes the transform from the motion corrected EPI to the T1 (with fieldmap corrections).
##################
#preconditions: dataPrep.sh, motion_correction, tissueSeg
##################
#input (typical): ${outDir}/func/mc/mcImgMean.nii.gz (from motion_correct)
# T1_brain (from option -A)
# T1_head (from option -a)
# T1_mask (from option -m)
# outDir (from option -o)
# #Additional Arguments from Fieldmap data
# fieldmapFlag (0 or 1) (from option -f)
# fieldmap (from option -b)
# fieldmapMagHead (from option -v)
# fieldmapMagBrain (from option -x)
# dwelltime (from option -D or default)
# peDir (from option -d or default)
##################
#output: ${outDir}/func/EPItoT1/EPItoT1_warp.nii.gz
# ${outDir}/func/EPItoT1/T1toEPI.mat
# ${outDir}/func/EPItoT1/T1toEPI_warp.nii.gz
# ${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz
# ${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz
# ${outDir}/func/EPItoT1/EPIstrippedtoT1.nii.gz
# ${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz
# ${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz
# ${outDir}/func/EPItoT1/EPItoMNI.nii.gz
##################
#dependencies: FSL, clobber
##################
#Used in: EPItoT1Master
##################
function EPItoT1FieldMap()
{
#basic args (without fieldmap)
local mcImgMean=$1
local T1_brain=$2
local T1_head=$3
local T1_mask=$4
local outDir=$5
#additional arguments for fieldmap processing
local fieldmap=$6
local fieldmapMagHead=$7
local fieldmapMagBrain=$8
local dwellTime=$9
local peDir=$10
printf "%s\n" "......Registration With FieldMap Correction."
#Warp using FieldMap correction
#Output will be a (warp) .nii.gz file
#epi_reg --epi=${indir}/mcImgMean.nii.gz --t1=${t1SkullData} --t1brain=${t1Data} --wmseg=$epiWarpDir/T1_MNI_brain_wmseg.nii.gz --out=$epiWarpDir/EPItoT1 --fmap=${fieldMap} --fmapmag=${fieldMapMagSkull} --fmapmagbrain=${fieldMapMag} --echospacing=${dwellTime} --pedir=${peDir}
clobber ${outDir}/func/EPItoT1/EPItoT1_warp.nii.gz &&\
{ epi_reg --epi=${mcImgMean} \
--t1=${T1_head} \
--t1brain=${T1_brain} \
--wmseg=${outDir}/func/T1forWarp/T1_MNI_brain_wmseg.nii.gz \
--out=${outDir}/func/EPItoT1/EPItoT1 \
--fmap=${fieldMap} \
--fmapmag=${fieldMapMagHead} \
--fmapmagbrain=${fieldMapMagBrain} \
--echospacing=${dwellTime} \
--pedir=${peDir} --noclean ||\
{ printf "%s\n" "epi_reg failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Invert the affine registration (to get T1toEPI)
clobber ${outDir}/func/EPItoT1/T1toEPI.mat &&\
{ convert_xfm -omat ${outDir}/func/EPItoT1/T1toEPI.mat -inverse ${outDir}/func/EPItoT1/EPItoT1.mat ||\
{ printf "%s\n" "convert_xfm failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Invert the nonlinear warp (to get T1toEPI)
clobber ${outDir}/func/EPItoT1/T1toEPI_warp.nii.gz &&\
{ invwarp -w ${outDir}/func/EPItoT1/EPItoT1_warp.nii.gz -r ${mcImgMean} -o ${outDir}/func/EPItoT1/T1toEPI_warp.nii.gz ||\
{ printf "%s\n" "invwarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Apply the inverted (T1toEPI) warp to the brain mask
clobber ${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz &&\
{ applywarp --ref=${mcImgMean} --in=${T1_mask} --out=${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz --warp=${outDir}/func/EPItoT1/T1toEPI_warp.nii.gz --datatype=char --interp=nn ||\
{ printf "%s\n" "applywarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Create a stripped version of the EPI (mcImg) file, apply the warp
clobber ${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz &&\
{ fslmaths ${mcImgMean} -mas ${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz ${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz ||\
{ printf "%s\n" "fslmaths failed, exiting ${FUNCNAME}" && return 1 ;} ;}
clobber ${outDir}/func/EPItoT1/EPIstrippedtoT1.nii.gz &&\
{ applywarp --ref=${T1_brain} --in=${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz --out=${outDir}/func/EPItoT1/EPIstrippedtoT1.nii.gz --warp=${outDir}/func/EPItoT1/EPItoT1_warp.nii.gz ||\
{ printf "%s\n" "applywarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Sum the nonlinear warp (MNItoT1_warp.nii.gz) with the second nonlinear warp (T1toEPI_warp.nii.gz) to get a warp from MNI to EPI
clobber ${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz &&\
{ convertwarp \
--ref=${mcImgMean} \
--warp1=${outDir}/func/T1forWarp/MNItoT1_warp.nii.gz \
--warp2=${outDir}/func/EPItoT1/T1toEPI_warp.nii.gz \
--out=${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz --relout ||\
{ printf "%s\n" "convertwarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Invert the warp to get EPItoMNI_warp.nii.gz
clobber ${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz &&\
{ invwarp -w ${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz -r $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz -o ${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz ||\
{ printf "%s\n" "invwarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Apply EPItoMNI warp to EPI file
clobber ${outDir}/func/EPItoT1/EPItoMNI.nii.gz &&\
{ applywarp --ref=$FSLDIR/data/standard/MNI152_T1_2mm.nii.gz --in=${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz --out=${outDir}/func/EPItoT1/EPItoMNI.nii.gz --warp=${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz ||\
{ printf "%s\n" "applywarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
printf "%s\n ${FUNCNAME} successful" && return 0
}
##################
#function: EPItoT1
##################
#purpose: makes the transform from the motion corrected EPI to the T1.
##################
#preconditions: dataPrep.sh, motion_correction, tissueSeg
##################
#input (typical): ${outDir}/func/mc/mcImgMean.nii.gz (from motion_correct)
# T1_brain (from option -A)
# T1_head (from option -a)
# T1_mask (from option -m)
# outDir (from option -o)
##################
#output: ${outDir}/func/EPItoT1/EPItoT1.mat
# ${outDir}/func/EPItoT1/T1toEPI.mat
# ${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz
# ${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz
# ${outDir}/func/EPItoT1/EPIstrippedtoT1.nii.gz
# ${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz
# ${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz
# ${outDir}/func/EPItoT1/EPItoMNI.nii.gz
##################
#dependencies: FSL, clobber
##################
#Used in: EPItoT1Master
##################
function EPItoT1()
{
#local variables here
local mcImgMean=$1 #epi is mcImgMean
local T1_brain=$2
local T1_head=$3
local T1_mask=$4
local outDir=$5
printf "%s\n" "......Registration Without FieldMap Correction."
#Warp without FieldMap correction
clobber ${outDir}/func/EPItoT1/EPItoT1.mat &&\
{ epi_reg --epi=${mcImgMean} \
--t1=${T1_head} \
--t1brain=${T1_brain} \
--wmseg=${outDir}/func/T1forWarp/T1_MNI_brain_wmseg.nii.gz \
--out=${outDir}/func/EPItoT1/EPItoT1 --noclean ||\
{ printf "%s\n" "epi_reg failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Invert the affine registration (to get T1toEPI)
clobber ${outDir}/func/EPItoT1/T1toEPI.mat &&\
{ convert_xfm -omat ${outDir}/func/EPItoT1/T1toEPI.mat -inverse ${outDir}/func/EPItoT1/EPItoT1.mat ||\
{ printf "%s\n" "convert_xfm failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Apply the inverted (T1toEPI) mat file to the brain mask
clobber ${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz &&\
{ flirt -in ${T1_mask} -ref ${mcImgMean} -applyxfm -init ${outDir}/func/EPItoT1/T1toEPI.mat -out ${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz -interp nearestneighbour -datatype char ||\
{ printf "%s\n" "flirt failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Create a stripped version of the EPI (mcImg) file, apply the mat file
clobber ${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz &&\
{ fslmaths ${mcImgMean} -mas ${outDir}/func/EPItoT1/mcImgMean_mask.nii.gz ${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz ||\
{ printf "%s\n" "fslmaths failed, exiting ${FUNCNAME}" && return 1 ;} ;}
clobber ${outDir}/func/EPItoT1/EPIstrippedtoT1.nii.gz &&\
{ flirt -in ${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz -ref ${T1_brain} -applyxfm -init ${outDir}/func/EPItoT1/EPItoT1.mat -out ${outDir}/func/EPItoT1/EPIstrippedtoT1.nii.gz ||\
{ printf "%s\n" "flirt failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Sum the nonlinear warp (MNItoT1_warp.nii.gz) with the affine transform (T1toEPI.mat) to get a warp from MNI to EPI
clobber ${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz &&\
{ convertwarp --ref=${mcImgMean} --warp1=${outDir}/func/T1forWarp/MNItoT1_warp.nii.gz --postmat=${outDir}/func/EPItoT1/T1toEPI.mat --out=${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz --relout ||\
{ printf "%s\n" "convertwarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Invert the warp to get EPItoMNI_warp.nii.gz
clobber ${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz &&\
{ invwarp -w ${outDir}/func/EPItoT1/MNItoEPI_warp.nii.gz -r $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz -o ${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz ||\
{ printf "%s\n" "invwarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Apply EPItoMNI warp to EPI file
clobber ${outDir}/func/EPItoT1/EPItoMNI.nii.gz &&\
{ applywarp --ref=$FSLDIR/data/standard/MNI152_T1_2mm.nii.gz --in=${outDir}/func/EPItoT1/mcImgMean_stripped.nii.gz --out=${outDir}/func/EPItoT1/EPItoMNI.nii.gz --warp=${outDir}/func/EPItoT1/EPItoMNI_warp.nii.gz ||\
{ printf "%s\n" "invwarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
printf "%s\n ${FUNCNAME} successful" && return 0
}
##################
#function: makeROI_Noise
##################
#purpose: Creates an ROI centered around user-supplied y-coordinates
##################
#input: ydim, integer
# xydim, integer
# inputImage, nifti file
# outputImage, nifti file name
##################
#output: outputImage (ROI nifti file)
##################
#dependencies: FSL
##################
#Used in: Estimate_SNR
##################
function makeROI_Noise()
{
local ydim=$1
local xydim=$2
#Set input/output images
local inputImage=$3
local outputImage=$4
#ROI is arbitrarily set to %age of xy voxel dimensions ($2)
{ fslmaths $inputImage -mul 0 -add 1 -roi 0 -1 ${ydim} 1 0 -1 0 1 $outputImage -odt float ||\
{ printf "fslmaths failed, exiting ${FUNCNAME}" && return 1 ;} ;}
{ fslmaths $outputImage -kernel sphere ${xydim} -fmean $outputImage -odt float ||\
{ printf "fslmaths failed, exiting ${FUNCNAME}" && return 1 ;} ;}
{ fslmaths $outputImage -bin $outputImage ||\
{ printf "fslmaths failed, exiting ${FUNCNAME}" && return 1 ;} ;}
printf "%s\n ${FUNCNAME} successful" && return 0
}
######################## END HELPER FUNCTIONS #############################
############################# MAIN FUNCTIONS #############################
##################
#function: motion_correction
##################
#purpose: Runs motion correction on the raw resting state image.
##################
#preconditions: you have run dataPrep.sh already.
##################
#input (typical): ${outDir}/func/RestingStateRaw.nii.gz
# ${outDir}
##################
#output: ${outDir}/func/mc/mcImg.nii.gz
# ${outDir}/func/mc/mcImg_raw.par
# ${outDir}/func/mc/mcImgMean.nii.gz
# ${outDir}/func/mc/mcImg_deg.par
# ${outDir}/func/mc/mcImg.par
# ${outDir}/func/mc/mcImg_mm.par
# ${outDir}/func/mc/mcImg_abs.rms
# ${outDir}/func/mc/mcImg_deriv.par
# ${outDir}/func/mc/mcImg_rel.rms
# ${outDir}/func/mc/rot.png
# ${outDir}/func/mc/trans.png
# ${outDir}/func/mc/rot_mm.png
# ${outDir}/func/mc/rot_trans.png
# ${outDir}/func/mc/disp.png
##################
#dependencies: FSL, AFNI, clobber
##################
#Used in: MAIN
##################
function motion_correction()
{
########## Motion Correction ###################
#Going to run with AFNI's 3dvolreg over FSL's mcflirt. Output pics will have same names to be drop-in replacments
echo "...Applying motion correction."
local epi=$1
local outDir=$2
mkdir -p ${outDir}/func/mc ||\
{ printf "%s\n" "mkdir ${outDir}/func/mc, exiting ${FUNCNAME}" && return 1 ;}
#Determine halfway point of dataset to use as a target for registration
local halfPoint=$(fslhd $epi | grep "^dim4" | awk '{print int($2/2)}')
#Run 3dvolreg, save matrices and parameters
#Saving "raw" AFNI output for possible use later (motionscrubbing?)
clobber ${outDir}/func/mc/mcImg.nii.gz &&\
{ 3dvolreg -verbose \
-tshift 0 \
-Fourier \
-zpad 4 \
-prefix ${outDir}/func/mc/mcImg.nii.gz \
-base $halfPoint \
-dfile ${outDir}/func/mc/mcImg_raw.par \
-1Dmatrix_save ${outDir}/func/mc/mcImg.mat \
$epi ||\
{ printf "%s\n" "3dvolreg failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Create a mean volume
clobber ${outDir}/func/mc/mcImgMean.nii.gz &&\
{ fslmaths ${outDir}/func/mc/mcImg.nii.gz -Tmean ${outDir}/func/mc/mcImgMean.nii.gz ||\
{ printf "%s\n" "fslmaths failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Save out mcImg.par (like fsl) with only the translations and rotations
#mcflirt appears to have a different rotation/translation order. Reorder 3dvolreg output to match "RPI" FSL ordering
##AFNI ordering
#roll = rotation about the I-S axis }
#pitch = rotation about the R-L axis } degrees CCW
#yaw = rotation about the A-P axis }
#dS = displacement in the Superior direction }
#dL = displacement in the Left direction } mm
#dP = displacement in the Posterior direction }
awk '{print ($3 " " $4 " " $2 " " $6 " " $7 " " $5)}' ${outDir}/func/mc/mcImg_raw.par > ${outDir}/func/mc/mcImg_deg.par ||\
{ printf "%s\n" "creation of mcImg_deg.par failed, exiting ${FUNCNAME}" && return 1; }
#Need to convert rotational parameters from degrees to radians
#rotRad= (rotDeg*pi)/180
#pi=3.14159
awk -v pi=3.14159 '{print (($1*pi)/180) " " (($2*pi)/180) " " (($3*pi)/180) " " $4 " " $5 " " $6}' ${outDir}/func/mc/mcImg_deg.par > ${outDir}/func/mc/mcImg.par ||\
{ printf "%s\n" "creation of mcImg.par failed, exiting ${FUNCNAME}" && return 1; }
#Need to create a version where ALL (rotations and translations) measurements are in mm. Going by Power 2012 Neuroimage paper, radius of 50mm.
#Convert degrees to mm, leave translations alone.
#rotDeg= ((2r*Pi)/360) * Degrees = Distance (mm)
#d=2r=2*50=100
#pi=3.14159
awk -v pi=3.14159 -v d=100 '{print (((d*pi)/360)*$1) " " (((d*pi)/360)*$2) " " (((d*pi)/360)*$3) " " $4 " " $5 " " $6}' ${outDir}/func/mc/mcImg_deg.par > ${outDir}/func/mc/mcImg_mm.par ||\
{ printf "%s\n" "creation of mcImg_mm.par failed, exiting ${FUNCNAME}" && return 1; }
#Cut motion parameter file into 6 distinct TR parameter files
for i in {1..6}; do
awk -v var=${i} '{print $var}' ${outDir}/func/mc/mcImg.par > ${outDir}/func/mc/mc${i}.par ||\
{ printf "%s\n" "creation of mc{$1}.par failed, exiting ${FUNCNAME}" && return 1; }
done
##Need to create the absolute and relative displacement RMS measurement files
#From the FSL mailing list (https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=FSL;2ce58db1.1202):
#rms = sqrt(0.2*R^2*((cos(theta_x)-1)^2+(sin(theta_x))^2 + (cos(theta_y)-1)^2 + (sin(theta_y))^2 + (cos(theta_z)-1)^2 + (sin(theta_z)^2)) + transx^2+transy^2+transz^2)
#where R=radius of spherical ROI = 80mm used in rmsdiff; theta_x, theta_y, theta_z are the three rotation angles from the .par file; and transx, transy, transz are the three translations from the .par file.
#Absolute Displacement
awk '{print (sqrt(0.2*80^2*((cos($1)-1)^2+(sin($1))^2 + (cos($2)-1)^2 + (sin($2))^2 + (cos($3)-1)^2 + (sin($3)^2)) + $4^2+$5^2+$6^2))}' ${outDir}/func/mc/mcImg.par > ${outDir}/func/mc/mcImg_abs.rms ||\
{ printf "%s\n" "creation of mcImg_abs.rms failed, exiting ${FUNCNAME}" && return 1; }
#Relative Displacement
#Create the relative displacement .par file from the input using AFNI's 1d_tool.py to first calculate the derivatives
1d_tool.py -infile ${outDir}/func/mc/mcImg.par -set_nruns 1 -derivative -write ${outDir}/func/mc/mcImg_deriv.par -overwrite ||\
{ printf "%s\n" "creation of mcImg_deriv.par failed, exiting ${FUNCNAME}" && return 1; }
awk '{print (sqrt(0.2*80^2*((cos($1)-1)^2+(sin($1))^2 + (cos($2)-1)^2 + (sin($2))^2 + (cos($3)-1)^2 + (sin($3)^2)) + $4^2+$5^2+$6^2))}' ${outDir}/func/mc/mcImg_deriv.par > ${outDir}/func/mc/mcImg_rel.rms ||\
{ printf "%s\n" "creation of mcImg_rel.rms failed, exiting ${FUNCNAME}" && return 1; }
#Create images of the motion correction (translation, rotations, displacement), mm and radians
#switched from "MCFLIRT estimated...." title
fsl_tsplot -i ${outDir}/func/mc/mcImg.par -t '3dvolreg estimated rotations (radians)' -u 1 --start=1 --finish=3 -a x,y,z -w 800 -h 300 -o ${outDir}/func/mc/rot.png ||\
{ printf "%s\n" "creation of rot.png failed, exiting ${FUNCNAME}" && return 1; }
fsl_tsplot -i ${outDir}/func/mc/mcImg.par -t '3dvolreg estimated translations (mm)' -u 1 --start=4 --finish=6 -a x,y,z -w 800 -h 300 -o ${outDir}/func/mc/trans.png ||\
{ printf "%s\n" "creation of trans.png failed, exiting ${FUNCNAME}" && return 1; }
fsl_tsplot -i ${outDir}/func/mc/mcImg_mm.par -t '3dvolreg estimated rotations (mm)' -u 1 --start=1 --finish=3 -a x,y,z -w 800 -h 300 -o ${outDir}/func/mc/rot_mm.png ||\
{ printf "%s\n" "creation of rot_mm.png failed, exiting ${FUNCNAME}" && return 1; }
fsl_tsplot -i ${outDir}/func/mc/mcImg_mm.par -t '3dvolreg estimated rotations and translations (mm)' -u 1 --start=1 --finish=6 -a "x(rot),y(rot),z(rot),x(trans),y(trans),z(trans)" -w 800 -h 300 -o ${outDir}/func/mc/rot_trans.png ||\
{ printf "%s\n" "creation of rot_trans.png failed, exiting ${FUNCNAME}" && return 1; }
fsl_tsplot -i ${outDir}/func/mc/mcImg_abs.rms,${outDir}/func/mc/mcImg_rel.rms -t '3dvolreg estimated mean displacement (mm)' -u 1 -w 800 -h 300 -a absolute,relative -o ${outDir}/func/mc/disp.png ||\
{ printf "%s\n" "creation of dip.png failed, exiting ${FUNCNAME}" && return 1; }
printf "%s\n" "${FUNCNAME} completed successfully" && return 0
}
##################
#function: TissueSeg
##################
#purpose: Separates the highres image into CSF, GM, WM
##################
#preconditions: dataPrep.sh
##################
#input (typical): T1_brain (from option -A)
# outDir (from option -o)
##################
#output: ${outDir}/func/T1forWarp/tissueSeg
# ${outDir}/func/T1forWarp/tissueSeg/T1_mixeltype.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_pve_0.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_pve_1.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_pve_2.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_pveseg.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_seg_0.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_seg_1.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_seg_2.nii.gz
# ${outDir}/func/T1forWarp/tissueSeg/T1_seg.nii.gz
##################
#dependencies: FSL, clobber
##################
#Used in: MAIN
##################
function TissueSeg()
{
local T1_brain=$1
local outDir=$2
#Do we need to run fast if epi_reg runs fast?
########## Tissue class segmentation ###########
echo "...Creating Tissue class segmentations."
mkdir -p ${outDir}/func/T1forWarp/tissueSeg
#Tissue segment the skull-stripped T1
echo "......Starting FAST segmentation"
clobber ${outDir}/func/T1forWarp/T1_MNI_brain_wmseg.nii.gz &&\
{ fast -t 1 -n 3 -g -o ${outDir}/func/T1forWarp/tissueSeg/T1 ${T1_brain} &&\
cp ${outDir}/func/T1forWarp/tissueSeg/T1_seg_2.nii.gz ${outDir}/func/T1forWarp/T1_MNI_brain_wmseg.nii.gz ||\
{ printf "%s\n" "fast failed, exiting ${FUNCNAME}" && return 1 ;} ;}
printf "%s\n ${FUNCNAME} successful" && return 0
}
##################
#function: T1ToStd
##################
#purpose: Creates the transforms to move the T1 image to MNI space
##################
#preconditions: Already ran dataPrep.sh
##################
#input (typical): T1_brain (from option -A)
# T1_head (from option -a)
# T1_mask (from option -m)
# ${outDir}
# lesion (0 or 1)
##################
#output: ${outDir}/func/T1forWarp
# lesion=1
# ${outDir}/func/T1forWarp/T1_lesionmask.nii.gz
# ${outDir}/func/T1forWarp/T1_lesionmask_RPI.nii.gz
# ${outDir}/func/T1forWarp/LesionWeight.nii.gz
# ${outDir}/func/T1forWarp/T1_to_MNIaff.nii.gz
# ${outDir}/func/T1forWarp/T1_to_MNIaff.mat
# ${outDir}/func/T1forWarp/coef_T1_to_MNI152.nii.gz
# ${outDir}/func/T1forWarp/T1_to_MNI152.nii.gz
# ${outDir}/func/T1forWarp/jac_T1_to_MNI152.nii.gz
# ${outDir}/func/T1forWarp/T1_brain_to_MNI152.nii.gz
# ${outDir}/func/T1forWarp/"lesion"MasktoMNI.nii.gz
# ${outDir}/func/T1forWarp/MNItoT1_warp.nii.gz
##################
#dependencies: FSL, RPI_Orient, clobber, LestionMaskPrep
##################
#Used in: MAIN
##################
function T1ToStd()
{
local T1_brain=$1
local T1_head=$2
local T1_mask=$3
local outDir=$4
local lesion=$5
printf "%s\n" "...Optimizing T1 (highres) to MNI (standard) registration."
if [ ${lesion} -eq 1 ]; then
lesionMaskPrep ${T1_mask} ${outDir}
local flirt_transform_option="-inweight ${outDir}/func/T1forWarp/LesionWeight.nii.gz"
local fnirt_transform_option="--inmask=$t1WarpDir/LesionWeight.nii.gz"
local maskname="lesion"
fi
mkdir -p ${outDir}/func/T1forWarp ||\
{ printf "%s\n" "creation of directory T1forWarp failed, exiting ${FUNCNAME}" && return 1; }
#T1 to MNI, affine (skull-stripped data)
clobber ${outDir}/func/T1forWarp/T1_to_MNIaff.nii.gz ${outDir}/func/T1forWarp/T1_to_MNIaff.mat &&\
{ flirt -in ${T1_brain} \
-ref $FSLDIR/data/standard/MNI152_T1_2mm_brain.nii.gz \
-out ${outDir}/func/T1forWarp/T1_to_MNIaff.nii.gz \
-omat ${outDir}/func/T1forWarp/T1_to_MNIaff.mat ${flirt_transform_option} ||\
{ printf "%s\n" "flirt failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#T1 to MNI, nonlinear (T1 with skull)
clobber ${outDir}/func/T1forWarp/coef_T1_to_MNI152.nii.gz ${outDir}/func/T1forWarp/T1_to_MNI152.nii.gz ${outDir}/func/T1forWarp/jac_T1_to_MNI152.nii.gz &&\
{ fnirt --in=${T1_head} \
--aff=${outDir}/func/T1forWarp/T1_to_MNIaff.mat \
--config=T1_2_MNI152_2mm.cnf \
--cout=${outDir}/func/T1forWarp/coef_T1_to_MNI152 \
--iout=${outDir}/func/T1forWarp/T1_to_MNI152.nii.gz \
--jout=${outDir}/func/T1forWarp/jac_T1_to_MNI152 \
--jacrange=0.1,10 ${fnirt_transform_option} ||\
{ printf "%s\n" "fnirt failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Apply the warp to the skull-stripped T1
clobber ${outDir}/func/T1forWarp/T1_brain_to_MNI152.nii.gz &&\
{ applywarp \
--ref=$FSLDIR/data/standard/MNI152_T1_2mm_brain.nii.gz \
--in=$T1_brain \
--out=${outDir}/func/T1forWarp/T1_brain_to_MNI152.nii.gz \
--warp=${outDir}/func/T1forWarp/coef_T1_to_MNI152.nii.gz ||\
{ printf "%s\n" "applywarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Apply the warp to the lesion mask or to the T1 mask
clobber ${outDir}/func/T1forWarp/${maskname}MasktoMNI.nii.gz &&\
{ applywarp \
--ref=$FSLDIR/data/standard/MNI152_T1_2mm_brain.nii.gz \
--in=$T1_mask \
--out=${outDir}/func/T1forWarp/${maskname}MasktoMNI.nii.gz \
--warp=${outDir}/func/T1forWarp/coef_T1_to_MNI152.nii.gz \
--interp=nn ||\
{ printf "%s\n" "applywarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
#Invert the warp (to get MNItoT1)
clobber ${outDir}/func/T1forWarp/MNItoT1_warp.nii.gz &&\
{ invwarp \
-w ${outDir}/func/T1forWarp/coef_T1_to_MNI152.nii.gz \
-r $T1_brain \
-o ${outDir}/func/T1forWarp/MNItoT1_warp.nii.gz ||\
{ printf "%s\n" "invwarp failed, exiting ${FUNCNAME}" && return 1 ;} ;}
printf "%s\n" "${FUNCNAME} completed successfully"
}
##################
#function: EPItoT1Master
##################
#purpose: makes the transform from the motion corrected EPI to the T1, and skullstrips the mcImg and RestingStateRaw.
##################
#preconditions: dataPrep.sh, motion_correction, tissueSeg
##################
#input (typical): ${outDir}/func/mc/mcImgMean.nii.gz (from motion_correct)
# T1_brain (from option -A)
# T1_head (from option -a)
# T1_mask (from option -m)
# outDir (from option -o)
# #Additional Arguments from Fieldmap data
# fieldmapFlag (0 or 1) (from option -f)
# fieldmap (from option -b)
# fieldmapMagHead (from option -v)
# fieldmapMagBrain (from option -x)
# dwelltime (from option -D or default)
# peDir (from option -d or default)
##################
#output: ${outDir}/func/mc/mcImg_stripped.nii.gz
# ${outDir}/func/RestingState.nii.gz
##################
#dependencies: FSL, clobber, EPItoT1FieldMap, EPItoT1
##################
#Used in: MAIN
##################
function EPItoT1Master()
{
#basic args (without fieldmap)
local mcImgMean=$1
local T1_brain=$2
local T1_head=$3
local T1_mask=$4
local outDir=$5
#additional arguments for fieldmap processing
local fieldmapFlag=$6
local fieldmap=$7
local fieldmapMagHead=$8
local fieldmapMagBrain=$9
local dwellTime=$10
local peDir=$11
#number of arguments to decide which processing stream.
#local num_args=$#
printf "%s\n" "...Optimizing EPI (func) to T1 (highres) registration."
mkdir -p ${outDir}/func/EPItoT1 ||\
{ printf "%s\n" "creation of ${outDir}/func/EPItoT1 failed, exiting ${FUNCNAME}" && return 1; }
if [ ${fieldMapFlag} -eq 1 ]; then
EPItoT1FieldMap $@
{ printf "%s\n" "EPItoT1FieldMap failed, exiting ${FUNCNAME}" && return 1 ;}
elif [ ${fieldMapFlag} -eq 0 ]; then
EPItoT1 $@ ||\
{ printf "%s\n" "EPItoT1 failed, exiting ${FUNCNAME}" && return 1 ;}
else
printf "%s\n" "fieldmapFlag not set to 1 or 0, exiting EPItoT1Master" && return 1
fi