-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathantsMultivariateTemplateConstruction.sh
executable file
·1585 lines (1401 loc) · 61.7 KB
/
antsMultivariateTemplateConstruction.sh
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
VERSION="0.0.0"
# trap keyboard interrupt (control-c)
trap control_c SIGINT
function setPath {
cat <<SETPATH
--------------------------------------------------------------------------------------
Error locating ANTS
--------------------------------------------------------------------------------------
It seems that the ANTSPATH environment variable is not set. Please add the ANTSPATH
variable. This can be achieved by editing the .bash_profile in the home directory.
Add:
ANTSPATH=/home/yourname/bin/ants/
Or the correct location of the ANTS binaries.
Alternatively, edit this script ( `basename $0` ) to set up this parameter correctly.
SETPATH
exit 1
}
# Uncomment the line below in case you have not set the ANTSPATH variable in your environment.
# export ANTSPATH=${ANTSPATH:="$HOME/bin/ants/"} # EDIT THIS
if [[ ${#ANTSPATH} -le 3 ]];
then
setPath >&2
fi
# Test availability of helper scripts.
# No need to test this more than once. Can reside outside of the main loop.
ANTS=${ANTSPATH}/ANTS
WARP=${ANTSPATH}/WarpImageMultiTransform
N4=${ANTSPATH}/N4BiasFieldCorrection
PEXEC=${ANTSPATH}/ANTSpexec.sh
SGE=${ANTSPATH}/waitForSGEQJobs.pl
PBS=${ANTSPATH}/waitForPBSQJobs.pl
XGRID=${ANTSPATH}/waitForXGridJobs.pl
SLURM=${ANTSPATH}/waitForSlurmJobs.pl
fle_error=0
for FLE in $ANTS $WARP $N4 $PEXEC $SGE $XGRID $PBS $SLURM
do
if [[ ! -x $FLE ]];
then
echo
echo "--------------------------------------------------------------------------------------"
echo " FILE $FLE DOES NOT EXIST -- OR -- IS NOT EXECUTABLE !!! $0 will terminate."
echo "--------------------------------------------------------------------------------------"
echo " if the file is not executable, please change its permissions. "
fle_error=1
fi
done
if [[ $fle_error = 1 ]];
then
echo "missing helper script"
exit 1
fi
function Usage {
cat <<USAGE
Usage:
`basename $0` -d ImageDimension -o OUTPREFIX <other options> <images>
Compulsory arguments (minimal command line requires SGE cluster, otherwise use -c & -j options):
-d: ImageDimension: 2 or 3 (for 2 or 3 dimensional registration of single volume)
ImageDimension: 4 (for template generation of time-series data)
-o: OUTPREFIX; A prefix that is prepended to all output files.
<images> List of images in the current directory, eg *_t1.nii.gz. Should be at the end
of the command. Optionally, one can specify a .csv or .txt file where each
line is the location of the input image. One can also specify more than
one file for each image for multi-modal template construction (e.g. t1 and t2).
For the multi-modal case, the templates will be consecutively numbered (e.g.
${OUTPUTPREFIX}template0.nii.gz, ${OUTPUTPREFIX}template1.nii.gz, ...).
NB: All images to be added to the template should be in the same directory, and this script
should be invoked from that directory.
Optional arguments:
-a image statistic used to summarize images (default 1)
0 = mean
1 = mean of normalized intensities
2 = median
Normalization here means dividing each image by its mean intensity.
-A sharpening applied to template at each iteration (default 1)
0 = none
1 = Laplacian
2 = Unsharp mask
-c: Control for parallel computation (default 1) -- 0 == run serially, 1 == SGE qsub,
2 == use PEXEC (localhost), 3 == Apple XGrid, 4 == PBS qsub, 5 == SLURM
-g: Gradient step size (default 0.25) -- smaller in magnitude results in
more cautious steps. Use smaller steps to refine template details.
0.25 is an upper (aggressive) limit for this parameter.
-i: Iteration limit (default 4) -- iterations of the template construction (Iteration limit)*NumImages registrations.
-j: Number of cpu cores to use (default 2; -- requires "-c 2")
-k: Number of modalities used to construct the template (default 1)
-w: Modality weights used in the similarity metric (default = 1) --- specified as e.g. 1x0.5x0.75
-m: Max-iterations in each registration
-n: N4BiasFieldCorrection of moving image (default 1) -- 0 == off, 1 == on
-p: Commands to prepend to job scripts (e.g., change into appropriate directory, set paths, etc)
-r: Do rigid-body registration of inputs to the initial template, before doing the main
pairwise registration. 0 == off 1 == on (default 0). If you are trying to refine or update
an existing template, you would use '-r 0'.
Rigid initialization is useful when you do not have an initial template, or you want to use
a single image as a reference for rigid alignment only. For example,
"-z tpl-MNI152NLin2009cAsym_res-01_T1w.nii.gz -y 0 -r 1"
will rigidly align the inputs to the MNI template, and then use their average to begin the
template building process.
-s: Type of similarity metric used for nonlinear registration (affine is always MI). Default = CC.
Options are case sensitive.
CC : Cross-correlation
MI : Mutual information
MSQ : Mean squared differences
PR : CC after subtraction of local mean from the image (deprecated)
-t: Type of transformation model used for nonlinear registration. Options are case sensitive.
GR : Greedy SyN (default for scalar data)
GR_Constrained : Greedy SyN with regularization on the total deformation (default for time series)
EL : Elastic
EX : Exponential
DD : Greedy exponential, diffemorphic-demons-style optimization
SY : LDDMM-style SyN with symmetric time-dependent gradient estimation
LDDMM : Like SY, but with asymmetric time-dependent gradient estimation
S2 : Like SY, but with no time-dependent gradient estimation
-x: XGrid arguments (e.g., -x "-p password -h controlhost")
-y: Update the template with the full affine transform (default 1). If 0, the rigid
component of the affine transform will not be used to update the template. If your
template drifts in translation or orientation try -y 0.
-z: Use this this volume as the target of all inputs. When not used, the script will create an unbiased
starting point by averaging all inputs, then aligning the center of mass of all inputs to that of
the initial average. If you do not use -z, it is recommended to use "-r 1". Use the full path.
For multiple modalities, specify -z modality1.nii.gz -z modality2.nii.gz ...
in the same modality order as the input images.
-b: Boolean for saving full iteration output to directories (default = 0). If 1, images and warps
are saved for each pairwise registration at each iteration. Otherwise, only templates and the shape
update warps are saved.
Example:
`basename $0` -d 3 -m 30x50x20 -t GR -s CC -c 1 -o MY -z InitialTemplate.nii.gz *RF*T1x.nii.gz
- In this example 30x50x20 iterations per registration are used for template creation (that is the default)
- Greedy-SyN and CC are the metrics to guide the mapping.
- Output is prepended with MY and the initial template is InitialTemplate.nii.gz (optional).
- The -c option is set to 1, which will result in using the Sun Grid Engine (SGE) to distribute the computation.
- if you do not have SGE, read the help for multi-core computation on the local machine, or Apple X-grid options.
Output:
{OutputPrefix}template{m}.nii.gz
final template for each modality m.
{OutputPrefix}template{m}{inputFile}{n}WarpedToTemplate.nii.gz
{OutputPrefix}template{m}{inputFile}{n}0GenericAffine.mat
{OutputPrefix}template{m}{inputFile}{n}1Warp.nii.gz
{OutputPrefix}template{m}{inputFile}{n}1InverseWarp.nii.gz
each of n input images warped to the penultimate template m, with transforms. If the template has converged,
these should be well aligned to {OutputPrefix}template{m}.nii.gz.
intermediateTemplates/
initial_{OutputPrefix}template{m}.nii.gz :
initial template
initialRigid_{OutputPrefix}template{m}.nii.gz :
initial rigid template if requested with "-r 1"
{transform}_iteration{i}_{OutputPrefix}template{m}.nii.gz
Template computed with {transform} (-t) for each iteration (-i) and modality.
{transform}_iteration{i}_shapeUpdateWarp.nii.gz
Shape update warp applied to the template at iteration i. As the template converges,
the magnitude of the update warp will converge to a minimal value.
--------------------------------------------------------------------------------------
ANTS was created by:
--------------------------------------------------------------------------------------
Brian B. Avants, Nick Tustison and Gang Song
Penn Image Computing And Science Laboratory
University of Pennsylvania
Please reference http://www.ncbi.nlm.nih.gov/pubmed/20851191 when employing this script
in your studies. A reproducible evaluation of ANTs similarity metric performance in
brain image registration:
* Avants BB, Tustison NJ, Song G, Cook PA, Klein A, Gee JC. Neuroimage, 2011.
Also see http://www.ncbi.nlm.nih.gov/pubmed/19818860 for more details.
The script has been updated and improved since this publication.
--------------------------------------------------------------------------------------
script adapted by N.M. van Strien, http://www.mri-tutorial.com | NTNU MR-Center
multivariate template adaption by Nick Tustison
--------------------------------------------------------------------------------------
Apple XGrid support by Craig Stark
--------------------------------------------------------------------------------------
USAGE
exit 1
}
function reportMappingParameters {
cat <<REPORTMAPPINGPARAMETERS
--------------------------------------------------------------------------------------
Mapping parameters
--------------------------------------------------------------------------------------
ANTSPATH is $ANTSPATH
Dimensionality: $DIM
N4BiasFieldCorrection: $N4CORRECT
Similarity Metric: $METRICTYPE
Transformation: $TRANSFORMATIONTYPE
Regularization: $REGULARIZATION
MaxIterations: $MAXITERATIONS
Number Of MultiResolution Levels: $NUMLEVELS
OutputName prefix: $OUTPUTNAME
Template: $TEMPLATENAME
Template Update Steps: $ITERATIONLIMIT
Template population: $IMAGESETVARIABLE
Number of Modalities: $NUMBEROFMODALITIES
Modality weights: $MODALITYWEIGHTSTRING
Image statistic: $STATSMETHOD
Sharpening method: $SHARPENMETHOD
Shape update full affine: $AFFINE_UPDATE_FULL
--------------------------------------------------------------------------------------
REPORTMAPPINGPARAMETERS
}
function summarizeimageset() {
local dim=$1
shift
local output=$1
shift
local summarizemethod=$1
shift
local sharpenmethod=$1
shift
local images=( "${@}" )
if [[ ${#images[@]} -ne ${IMAGESPERMODALITY} ]]
then
echo "ERROR summarizeimageset - imagelist length is ${#images[@]}, expected ${IMAGESPERMODALITY}"
exit 1
fi
rm -f "$output"
case $summarizemethod in
0) #mean
${ANTSPATH}/AverageImages $dim $output 0 ${images[@]}
;;
1) #mean of normalized images
${ANTSPATH}/AverageImages $dim $output 2 ${images[@]}
;;
2) #median
local image
for image in "${images[@]}";
do
echo $image >> ${output}_list.txt
done
${ANTSPATH}/ImageSetStatistics $dim ${output}_list.txt ${output} 0
rm ${output}_list.txt
;;
esac
if [[ ! -f "$output" ]];
then
echo "summarizeimageset: ERROR - output file $output could not be created"
exit 1
fi
case $sharpenmethod in
0)
echo "Sharpening method none"
;;
1)
echo "Laplacian sharpening"
${ANTSPATH}/ImageMath $dim $output Sharpen $output
;;
2)
echo "Unsharp mask sharpening"
${ANTSPATH}/ImageMath $dim $output UnsharpMask $output 0.5 1 0 0
;;
esac
local sharpenExit=$?
if [[ $? -ne 0 ]]
then
echo "summarizeimageset: ERROR - template sharpening failed with status $?"
exit 1
fi
}
function shapeupdatetotemplate() {
echo "shapeupdatetotemplate()"
# local declaration of values
dim=$1
template=$2
templatename=$3
outputname=$4
gradientstep=-$5
summarizemethod=$6
sharpenmethod=$7
whichtemplate=$8
# debug only
# echo $dim
# echo ${template}
# echo ${templatename}
# echo ${outputname}
# echo ${outputname}*WarpedToTemplate.nii*
# echo ${gradientstep}
# We find the average warp to the template and apply its inverse to the template image
# This keeps the template shape stable over multiple iterations of template building
echo
echo "--------------------------------------------------------------------------------------"
echo " shapeupdatetotemplate---voxel-wise averaging of the warped images to the current template"
echo "--------------------------------------------------------------------------------------"
imagelist=(`ls ${outputname}template${whichtemplate}*WarpedToTemplate.nii.gz`)
if [[ ${#imagelist[@]} -ne ${IMAGESPERMODALITY} ]]
then
echo "ERROR shapeupdatedtotemplate - imagelist length is ${#imagelist[@]}, expected ${IMAGESPERMODALITY}"
exit 1
fi
summarizeimageset ${dim} ${template} ${summarizemethod} ${sharpenmethod} ${imagelist[@]}
if [[ $whichtemplate -eq 0 ]] ;
then
echo
echo "--------------------------------------------------------------------------------------"
echo " shapeupdatetotemplate---voxel-wise averaging of the inverse warp fields (from subject to template)"
echo " ${ANTSPATH}/AverageImages $dim ${templatename}${whichtemplate}warp.nii.gz 0 `ls ${outputname}*Warp.nii.gz | grep -v "InverseWarp"`"
echo "--------------------------------------------------------------------------------------"
${ANTSPATH}/AverageImages $dim ${templatename}${whichtemplate}warp.nii.gz 0 `ls ${outputname}*Warp.nii.gz | grep -v "InverseWarp"`
echo
echo "--------------------------------------------------------------------------------------"
echo " shapeupdatetotemplate---scale the averaged inverse warp field by the gradient step"
echo " ${ANTSPATH}/MultiplyImages $dim ${templatename}${whichtemplate}warp.nii.gz ${gradientstep} ${templatename}${whichtemplate}warp.nii.gz"
echo "--------------------------------------------------------------------------------------"
${ANTSPATH}/MultiplyImages $dim ${templatename}${whichtemplate}warp.nii.gz ${gradientstep} ${templatename}${whichtemplate}warp.nii.gz
echo
echo "--------------------------------------------------------------------------------------"
echo " shapeupdatetotemplate---average the affine transforms (template <-> subject)"
echo " ---transform the inverse field by the resulting average affine transform"
echo " ${ANTSPATH}/${AVERAGE_AFFINE_PROGRAM} ${dim} ${templatename}0Affine.txt ${outputname}*Affine.txt"
echo " ${ANTSPATH}/WarpImageMultiTransform ${dim} ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz -i ${templatename}0Affine.txt -R ${template}"
echo "--------------------------------------------------------------------------------------"
${ANTSPATH}/${AVERAGE_AFFINE_PROGRAM} ${dim} ${templatename}0Affine.txt ${outputname}*Affine.txt
${ANTSPATH}/WarpImageMultiTransform ${dim} ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz -i ${templatename}0Affine.txt -R ${template}
${ANTSPATH}/MeasureMinMaxMean ${dim} ${templatename}0warp.nii.gz ${templatename}warplog.txt 1
fi
echo "--------------------------------------------------------------------------------------"
echo " shapeupdatetotemplate---warp each template by the resulting transforms"
echo " ${ANTSPATH}/WarpImageMultiTransform ${dim} ${template} ${template} -i ${templatename}0Affine.txt ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz -R ${template}"
echo "--------------------------------------------------------------------------------------"
${ANTSPATH}/WarpImageMultiTransform ${dim} ${template} ${template} -i ${templatename}0Affine.txt ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz ${templatename}0warp.nii.gz -R ${template}
}
function jobfnamepadding {
outdir=`dirname ${TEMPLATES[0]}`
if [[ ${#outdir} -eq 0 ]]
then
outdir=`pwd`
fi
files=`ls ${outdir}/job*.sh`
BASENAME1=`echo $files[1] | cut -d 'b' -f 1`
for file in ${files}
do
if [[ "${#file}" -eq "9" ]];
then
BASENAME2=`echo $file | cut -d 'b' -f 2 `
mv "$file" "${BASENAME1}b_000${BASENAME2}"
elif [[ "${#file}" -eq "10" ]];
then
BASENAME2=`echo $file | cut -d 'b' -f 2 `
mv "$file" "${BASENAME1}b_00${BASENAME2}"
elif [[ "${#file}" -eq "11" ]];
then
BASENAME2=`echo $file | cut -d 'b' -f 2 `
mv "$file" "${BASENAME1}b_0${BASENAME2}"
fi
done
}
function setCurrentImageSet() {
WHICHMODALITY=$1
CURRENTIMAGESET=()
COUNT=0
for (( g = $WHICHMODALITY; g < ${#IMAGESETARRAY[@]}; g+=$NUMBEROFMODALITIES ))
do
CURRENTIMAGESET[$COUNT]=${IMAGESETARRAY[$g]}
(( COUNT++ ))
done
}
cleanup()
{
echo "\n*** Performing cleanup, please wait ***\n"
runningANTSpids=$( ps --ppid $$ -o pid= )
for thePID in $runningANTSpids
do
echo "killing: ${thePID}"
kill ${thePID}
done
return $?
}
control_c()
# run if user hits control-c
{
echo -en "\n*** User pressed CTRL + C ***\n"
cleanup
exit $?
echo -en "\n*** Script cancelled by user ***\n"
}
#initializing variables with global scope
time_start=`date +%s`
currentdir=`pwd`
nargs=$#
MAXITERATIONS=30x90x20
LABELIMAGE=0 # initialize optional parameter
METRICTYPE=()
TRANSFORMATIONTYPE="GR" # initialize optional parameter
if [[ $dim == 4 ]]; then
# we use a more constrained regularization for 4D mapping b/c we expect deformations to be relatively small and local
TRANSFORMATIONTYPE="GR_Constrained"
fi
NUMBEROFMODALITIES=1
MODALITYWEIGHTSTRING=""
N4CORRECT=1 # initialize optional parameter
DOQSUB=1 # By default, antsMultivariateTemplateConstruction tries to do things in parallel
GRADIENTSTEP=0.25 # Gradient step size, smaller in magnitude means more smaller (more cautious) steps
ITERATIONLIMIT=4
CORES=2
TDIM=0
RIGID=0
RIGIDTYPE="" # set to an empty string to use affine initialization
range=0
REGTEMPLATES=()
TEMPLATES=()
CURRENTIMAGESET=()
XGRIDOPTS=""
SCRIPTPREPEND=""
# System specific queue options, eg "-q name" to submit to a specific queue
# It can be set to an empty string if you do not need any special cluster options
QSUBOPTS="" # EDIT THIS
OUTPUTNAME=antsBTP
BACKUP_EACH_ITERATION=0
AFFINE_UPDATE_FULL=1
# Methods for averaging warped images and sharpening next template
STATSMETHOD=1
SHARPENMETHOD=1
##Getting system info from linux can be done with these variables.
# RAM=`cat /proc/meminfo | sed -n -e '/MemTotal/p' | awk '{ printf "%s %s\n", $2, $3 ; }' | cut -d " " -f 1`
# RAMfree=`cat /proc/meminfo | sed -n -e '/MemFree/p' | awk '{ printf "%s %s\n", $2, $3 ; }' | cut -d " " -f 1`
# cpu_free_ram=$((${RAMfree}/${cpu_count}))
if [[ ${OSTYPE:0:6} == 'darwin' ]];
then
cpu_count=`sysctl -n hw.physicalcpu`
else
cpu_count=`cat /proc/cpuinfo | grep processor | wc -l`
fi
# Provide output for Help
if [[ "$1" == "-h" ]];
then
Usage >&2
fi
# reading command line arguments
while getopts "A:a:b:c:d:g:h:i:j:k:m:n:o:p:s:r:t:w:x:y:z:" OPT
do
case $OPT in
h) #help
echo "$USAGE"
exit 0
;;
A) # Sharpening method
SHARPENMETHOD=$OPTARG
;;
a) # summarizing statistic
STATSMETHOD=$OPTARG
;;
b) #backup each iteration (default = 0)
BACKUP_EACH_ITERATION=$OPTARG
;;
c) #use SGE cluster
DOQSUB=$OPTARG
if [[ ${#DOQSUB} -gt 2 ]]; then
echo " DOQSUB must be an integer value (0=serial, 1=SGE qsub, 2=try pexec, 3=XGrid, 4=PBS qsub, 5=SLURM) you passed -c $DOQSUB "
exit 1
fi
;;
d) #dimensions
DIM=$OPTARG
if [[ ${DIM} -eq 4 ]]; then
DIM=3
TDIM=4
fi
;;
g) #gradient stepsize (default = 0.25)
GRADIENTSTEP=$OPTARG
;;
i) #iteration limit (default = 3)
ITERATIONLIMIT=$OPTARG
;;
j) #number of cpu cores to use (default = 2)
CORES=$OPTARG
;;
k) #number of modalities used to construct the template (default = 1)
NUMBEROFMODALITIES=$OPTARG
;;
w) #modality weights (default = 1)
MODALITYWEIGHTSTRING=$OPTARG
;;
m) #max iterations other than default
MAXITERATIONS=$OPTARG
;;
n) #apply bias field correction
N4CORRECT=$OPTARG
;;
o) #output name prefix
OUTPUTNAME=$OPTARG
TEMPLATENAME=${OUTPUTNAME}template
;;
p) #Script prepend
SCRIPTPREPEND=$OPTARG
;;
s) #similarity model
METRICTYPE[${#METRICTYPE[@]}]=$OPTARG
;;
r) #start with rigid-body registration
RIGID=$OPTARG
;;
t) #transformation model
TRANSFORMATIONTYPE=$OPTARG
;;
x) #initialization template
XGRIDOPTS=$XGRIDOPTS
;;
y) # update with full affine, 0 for no rigid (default = 1)
AFFINE_UPDATE_FULL=$OPTARG
;;
z) #initialization template
REGTEMPLATES[${#REGTEMPLATES[@]}]=$OPTARG
;;
\?) # getopts issues an error message
echo "$USAGE" >&2
exit 1
;;
esac
done
# Provide different output for Usage and Help
if [[ ${TDIM} -eq 4 && $nargs -lt 5 ]];
then
Usage >&2
elif [[ ${TDIM} -eq 4 && $nargs -eq 5 ]];
then
echo ""
# This option is required to run 4D template creation on SGE with a minimal command line
elif [[ $nargs -lt 6 ]]
then
Usage >&2
fi
OUTPUT_DIR=${OUTPUTNAME%\/*}
if [[ ! -d $OUTPUT_DIR ]];
then
echo "The output directory \"$OUTPUT_DIR\" does not exist. Making it."
mkdir -p $OUTPUT_DIR
fi
# Intermediate template output. Keep the template for each iteration and also the average warp if defined.
# Useful for debugging and monitoring convergence
intermediateTemplateDir=${OUTPUT_DIR}/intermediateTemplates
mkdir -p $intermediateTemplateDir
if [[ $DOQSUB -eq 1 || $DOQSUB -eq 4 ]];
then
qq=`which qsub`
if [[ ${#qq} -lt 1 ]];
then
echo "do you have qsub? if not, then choose another c option ... if so, then check where the qsub alias points ..."
exit
fi
fi
if [[ $DOQSUB -eq 5 ]];
then
qq=`which sbatch`
if [[ ${#qq} -lt 1 ]];
then
echo "do you have sbatch? if not, then choose another c option ... if so, then check where the sbatch alias points ..."
exit
fi
fi
for (( i = 0; i < $NUMBEROFMODALITIES; i++ ))
do
TEMPLATES[$i]=${TEMPLATENAME}${i}.nii.gz
done
if [[ ${#METRICTYPE[@]} -eq 0 ]];
then
METRICTYPE[0]=CC
fi
if [[ ${#METRICTYPE[@]} -eq 1 ]];
then
for (( i = 1; i < $NUMBEROFMODALITIES; i++ ))
do
METRICTYPE[${#METRICTYPE[@]}]=${METRICTYPE[0]}
done
fi
if [[ ${#METRICTYPE[@]} -ne $NUMBEROFMODALITIES ]];
then
echo "The number of similarity metrics does not match the number of specified modalities (see -s option)"
exit
fi
if [[ ! -n "$MODALITYWEIGHTSTRING" ]];
then
for (( i = 0; i < $NUMBEROFMODALITIES; i++ ))
do
MODALITYWEIGHTS[$i]=1
done
else
MODALITYWEIGHTS=(`echo $MODALITYWEIGHTSTRING | tr 'x' "\n"`)
if [[ ${#MODALITYWEIGHTS[@]} -ne $NUMBEROFMODALITIES ]];
then
echo "The number of weights (specified e.g. -w 1x1x1) does not match the number of specified modalities (see -k option)";
exit
fi
fi
# Creating the file list of images to make a template from.
# Shiftsize is calculated because a variable amount of arguments can be used on the command line.
# The shiftsize variable will give the correct number of arguments to skip. Issuing shift $shiftsize will
# result in skipping that number of arguments on the command line, so that only the input images remain.
shiftsize=$(($OPTIND - 1))
shift $shiftsize
# The invocation of $* will now read all remaining arguments into the variable IMAGESETVARIABLE
IMAGESETVARIABLE=$*
NINFILES=$(($nargs - $shiftsize))
IMAGESETARRAY=()
if [[ $STATSMETHOD -lt 0 ]] || [[ $STATSMETHOD -gt 2 ]];
then
echo "Invalid stats type: using normalized mean (1)"
STATSMETHOD=1
fi
if [[ $SHARPENMETHOD -lt 0 ]] || [[ $SHARPENMETHOD -gt 2 ]];
then
echo "Invalid sharpening method: using Laplacian (1)"
SHARPENMETHOD=1
fi
AVERAGE_AFFINE_PROGRAM="AverageAffineTransform"
if [[ $AFFINE_UPDATE_FULL -eq 0 ]];
then
AVERAGE_AFFINE_PROGRAM="AverageAffineTransformNoRigid"
fi
# FSL not needed anymore, all dependent on ImageMath
# #test if FSL is available in case of 4D, exit if not
# if [[ ${TDIM} -eq 4 && ${#FSLDIR} -le 0 ]];
# then
# setFSLPath >&2
# fi
if [[ ${NINFILES} -eq 0 ]];
then
echo "Please provide at least 2 filenames for the template."
echo "Use `basename $0` -h for help"
exit 1
elif [[ ${NINFILES} -eq 1 ]];
then
extension=`echo ${IMAGESETVARIABLE#*.}`
if [[ $extension = 'csv' || $extension = 'txt' ]];
then
IMAGESFILE=$IMAGESETVARIABLE
IMAGECOUNT=0
while read line
do
files=(`echo $line | tr ',' ' '`)
if [[ ${#files[@]} -ne $NUMBEROFMODALITIES ]];
then
echo "The number of files in the csv file does not match the specified number of modalities."
echo "See the -k option."
exit 1
fi
for (( i = 0; i < ${#files[@]}; i++ ));
do
IMAGESETARRAY[$IMAGECOUNT]=${files[$i]}
((IMAGECOUNT++))
done
done < $IMAGESFILE
else
range=`${ANTSPATH}/ImageMath $TDIM abs nvols ${IMAGESETVARIABLE} | tail -1 | cut -d "," -f 4 | cut -d " " -f 2 | cut -d " ]" -f 1 `
if [[ ${range} -eq 1 && ${TDIM} -ne 4 ]];
then
echo "Please provide at least 2 filenames for the template."
echo "Use `basename $0` -h for help"
exit 1
elif [[ ${range} -gt 1 && ${TDIM} -ne 4 ]]
then
echo "This is a multivolume file. Use -d 4"
echo "Use `basename $0` -h for help"
exit 1
elif [[ ${range} -gt 1 && ${TDIM} -eq 4 ]];
then
echo
echo "--------------------------------------------------------------------------------------"
echo " Creating template of 4D input. "
echo "--------------------------------------------------------------------------------------"
#splitting volume
#setting up working dirs
tmpdir=${currentdir}/tmp_${RANDOM}_${RANDOM}_${RANDOM}_$$
(umask 077 && mkdir ${tmpdir}) || {
echo "Could not create temporary directory! Exiting." 1>&2
exit 1
}
mkdir ${tmpdir}/selection
#split the 4D file into 3D elements
cp ${IMAGESETVARIABLE} ${tmpdir}/
cd ${tmpdir}/
# ${ANTSPATH}/ImageMath $TDIM vol0.nii.gz TimeSeriesSubset ${IMAGESETVARIABLE} ${range}
# rm -f ${IMAGESETVARIABLE}
# selecting 16 volumes randomly from the timeseries for averaging, placing them in tmp/selection folder.
# the script will automatically divide timeseries into $total_volumes/16 bins from wich to take the random volumes;
# if there are more than 32 volumes in the time-series (in case they are smaller
nfmribins=16
if [[ ${range} -gt 31 ]];
then
BINSIZE=$((${range} / ${nfmribins}))
j=1 # initialize counter j
for ((i = 0; i < ${nfmribins}; i++))
do
FLOOR=$((${i} * ${BINSIZE}))
BINrange=$((${j} * ${BINSIZE}))
# Retrieve random number between two limits.
number=0 #initialize
while [[ "$number" -le $FLOOR ]];
do
number=$RANDOM
if [[ $i -lt 15 ]];
then
let "number %= $BINrange" # Scales $number down within $range.
elif [[ $i -eq 15 ]];
then
let "number %= $range" # Scales $number down within $range.
fi
done
#debug only
echo
echo "Random number between $FLOOR and $BINrange --- $number"
# echo "Random number between $FLOOR and $range --- $number"
if [[ ${number} -lt 10 ]];
then
${ANTSPATH}/ImageMath $TDIM selection/vol000${number}.nii.gz ExtractSlice ${IMAGESETVARIABLE} ${number}
# cp vol000${number}.nii.gz selection/
elif [[ ${number} -ge 10 && ${number} -lt 100 ]];
then
${ANTSPATH}/ImageMath $TDIM selection/vol00${number}.nii.gz ExtractSlice ${IMAGESETVARIABLE} ${number}
# cp vol00${number}.nii.gz selection/
elif [[ ${number} -ge 100 && ${number} -lt 1000 ]];
then
${ANTSPATH}/ImageMath $TDIM selection/vol0${number}.nii.gz ExtractSlice ${IMAGESETVARIABLE} ${number}
# cp vol0${number}.nii.gz selection/
fi
let j++
done
fi
elif [[ ${range} -gt ${nfmribins} && ${range} -lt 32 ]];
then
for ((i = 0; i < ${nfmribins} ; i++))
do
number=$RANDOM
let "number %= $range"
if [[ ${number} -lt 10 ]];
then
${ANTSPATH}/ImageMath $TDIM selection/vol0.nii.gz ExtractSlice ${IMAGESETVARIABLE} ${number}
# cp vol000${number}.nii.gz selection/
elif [[ ${number} -ge 10 && ${number} -lt 100 ]];
then
${ANTSPATH}/ImageMath $TDIM selection/vol0.nii.gz ExtractSlice ${IMAGESETVARIABLE} ${number}
# cp vol00${number}.nii.gz selection/
fi
done
elif [[ ${range} -le ${nfmribins} ]];
then
${ANTSPATH}/ImageMath selection/$TDIM vol0.nii.gz TimeSeriesSubset ${IMAGESETVARIABLE} ${range}
# cp *.nii.gz selection/
fi
# set filelist variable
rm -f ${IMAGESETVARIABLE}
cd selection/
IMAGESETVARIABLE=`ls *.nii.gz`
IMAGESETARRAY=()
for IMG in $IMAGESETVARIABLE
do
IMAGESETARRAY[${#IMAGESETARRAY[@]}]=$IMG
done
fi
else
IMAGESETARRAY=()
for IMG in $IMAGESETVARIABLE
do
IMAGESETARRAY[${#IMAGESETARRAY[@]}]=$IMG
done
fi
if [[ $NUMBEROFMODALITIES -gt 1 ]];
then
echo "--------------------------------------------------------------------------------------"
echo " Multivariate template construction using the following ${NUMBEROFMODALITIES}-tuples: "
echo "--------------------------------------------------------------------------------------"
for (( i = 0; i < ${#IMAGESETARRAY[@]}; i+=$NUMBEROFMODALITIES ))
do
IMAGEMETRICSET=""
for (( j = 0; j < $NUMBEROFMODALITIES; j++ ))
do
k=0
let k=$i+$j
IMAGEMETRICSET="$IMAGEMETRICSET ${IMAGESETARRAY[$k]}"
done
echo $IMAGEMETRICSET
done
echo "--------------------------------------------------------------------------------------"
fi
# Useful to check the right number of images exist for various ops
IMAGESPERMODALITY=$(( ${#IMAGESETARRAY[@]} / ${NUMBEROFMODALITIES} ))
# check for initial template images
for (( i = 0; i < $NUMBEROFMODALITIES; i++ ))
do
setCurrentImageSet $i
if [[ -n "${REGTEMPLATES[$i]}" ]];
then
if [[ ! -r "${REGTEMPLATES[$i]}" ]];
then
echo "Initial template {REGTEMPLATES[$i]} cannot be read"
exit 1
fi
echo
echo "--------------------------------------------------------------------------------------"
echo " Initial template $i found. This will be used for guiding the registration. use : ${REGTEMPLATES[$i]} and ${TEMPLATES[$i]} "
echo "--------------------------------------------------------------------------------------"
# now move the initial registration template to OUTPUTNAME, otherwise this input gets overwritten.
cp ${REGTEMPLATES[$i]} ${TEMPLATES[$i]}
else
echo
echo "--------------------------------------------------------------------------------------"
echo " Creating template ${TEMPLATES[$i]} from a population average image from the inputs."
echo " ${CURRENTIMAGESET[@]}"
echo "--------------------------------------------------------------------------------------"
# Normalized mean, no sharpening
# This forces a call to AverageImages, which resizes images to match the largest input
summarizeimageset $DIM ${TEMPLATES[$i]} 1 0 ${CURRENTIMAGESET[@]}
# Quickly align COM of input images to average, and then recompute average
IMAGECOMSET=()
for (( j = 0; j < ${#CURRENTIMAGESET[@]}; j+=1 ))
do
IMGbase=`basename ${CURRENTIMAGESET[$j]}`
BASENAME=` echo ${IMGbase} | cut -d '.' -f 1 `
COM="${OUTPUT_DIR}/initialCOM${i}_${j}_${IMGbase}"
COMTRANSFORM="${OUTPUT_DIR}/initialCOM${i}_${j}_${BASENAME}.mat"
antsAI -d 3 --convergence 0 --verbose 1 -m Mattes[${TEMPLATES[$i]},${CURRENTIMAGESET[$j]},32,None] -o ${COMTRANSFORM} -t AlignCentersOfMass
antsApplyTransforms -d 3 -r ${TEMPLATES[$i]} -i ${CURRENTIMAGESET[$j]} -t ${COMTRANSFORM} -o ${COM} --verbose
rm -f $COMTRANSFORM
IMAGECOMSET[${#IMAGECOMSET[@]}]=$COM
done
# Now safe to let user control stat method
summarizeimageset $DIM ${TEMPLATES[$i]} ${STATSMETHOD} 0 ${IMAGECOMSET[@]}
# Clean up
rm -f ${IMAGECOMSET[@]}
fi
if [[ ! -s ${TEMPLATES[$i]} ]];
then
echo "Your template : $TEMPLATES[$i] was not created. This indicates trouble! You may want to check correctness of your input parameters. exiting."
exit
fi
# Back up template
intermediateTemplateBase=`basename ${TEMPLATES[$i]}`
cp ${TEMPLATES[$i]} ${intermediateTemplateDir}/initial_${intermediateTemplateBase}
done
# remove old job bash scripts
outdir=`dirname ${TEMPLATES[0]}`
if [[ ${#outdir} -eq 0 ]];
then
outdir=`pwd`
fi
rm -f ${outdir}/job*.sh
##########################################################################
#
# perform rigid body registration if requested
#
##########################################################################
if [[ "$RIGID" -eq 1 ]];
then
count=0
jobIDs=""
for (( i = 0; i < ${#IMAGESETARRAY[@]}; i+=$NUMBEROFMODALITIES ))
do
IMAGEMETRICSET=""
for (( j = 0; j < $NUMBEROFMODALITIES; j++ ))
do
k=0
let k=$i+$j
IMAGEMETRICSET="$IMAGEMETRICSET -m MI[ ${TEMPLATES[$j]},${IMAGESETARRAY[$k]},${MODALITYWEIGHTS[$j]},32 ]"
done
qscript="${outdir}/job_${count}_qsub.sh"
rm -f $qscript
if [[ $DOQSUB -eq 5 ]];