-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsurfergems
executable file
·4006 lines (3965 loc) · 263 KB
/
surfergems
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
#!/usr/bin/env bash
#
## The Magical Surfer Gem Box
##
## TODO add filtering by status (take intersection of matched subject lists based on user input)
## TODO update git publishing for web reports + freesurfer data
## TODO make sure non-defaced files are not published (i.e. added to a gitignore)
## TODO make popup window come to front (grab attention/focus)
## TODO MAKE THIS PROGRAM RUN FASTER
## TODO Average DEFECT size
## TODO Job/Data Management would be so much better with JSON databasing (maybe with mongodb?)
## -- create regularly updating JSON file with job information upon SGE submission
## -- build JSON file with subject recon information (edited? if so where? which commands run? CNR? etc)
## -- build JSON file with subject demographic information
## TODO Long Term Goal :: remove dependency on FreeSurfer binaries (they're not open source, nipype is)
##
VERSION='1.0'
####################################################################################################################
### DEFINE FUNCTION
####################################################################################################################
# TODO make main menu using zenity + terminal
function surfergems_main(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_main $@ (${SECONDS}s elapsed)"
echo 'main menu'
# read user input
}
export -f surfergems_main
####################################################################################################################
### DEFINE FUNCTION
# figure out where function is being called from (follow symlinks)
####################################################################################################################
function surfergems_whereami(){
# >&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_whereami $@"
while [ -h "${SOURCE}" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "${SOURCE}" )" && pwd )"
SOURCE="$(readlink "${SOURCE}")"
[[ ${SOURCE} != /* ]] && SOURCE="${DIR}/${SOURCE}" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
export DIR="$( cd -P "$( dirname "${SOURCE}" )" && pwd )"
# get where this script lives
SOURCEPATH="`dirname \"$0\"`" # relative
export SOURCEPATH="`( cd \"${SOURCEPATH}\" && pwd )`"
}
export -f surfergems_whereami
####################################################################################################################
### DEFINE FUNCTION
## preallocate arrays and default values
####################################################################################################################
function surfergems_defaults(){
# Default Options
export OPTS="--no-colors --plain -nc --status -v --verbose --convert -f --files --web-report --web-report-dir -wrd --detail --kill-jobs -h --help --usage -sd --subjects-dir -s --subjects"
[ ! "${DEBUG}" ] && export DEBUG=''
[ ! "${VERBOSE}" ] && export VERBOSE=''
export AVERAGENAME='average'
export OVERWRITE=''
export EDITSUMMARY=''
# KILL PATTERN
[ ! "${KILLPATTERN}" ] && export KILLPATTERN='recon-all -s'
## Arrays
[ ! "${STATUS}" ] && declare -g STATUS=() # init STATUS if it doesn't exist
[ ! "${RECONSTATS}" ] && declare -g RECONSTATS=() # array of status outputs across subjects
[ ! "${MEASURES}" ] && declare -g MEASURES=() # measures for statistics
[ ! "${ATLAS}" ] && declare -g ATLAS=()
declare -g FINISHEDSUBJECTS=() && declare -g FINISHTIMES=() && declare -g STARTTIMES=() # array of subjects, completion times and start times of finished jobs
declare -g RUNNINGSUBJECTS=() && declare -g RUNNINGSTATUS=() && declare -g RUNNINGTIME=() # array of subjects, statuses and last reported run time of active jobs
declare -g FAILEDSUBJECTS=() && declare -g FAILTIMES=() && declare -g FAILPOINT=() # array of subjects, exit times and last reported step of failed jobs
declare -g RUNNINGHOSTS=() && declare -g FAILEDHOSTS=() && declare -g FINISHEDHOSTS=()
declare -g RUNNINGID=()
## stats arrays for table detail
declare -g hname=() && declare -g talqa=() && declare -g bcnr=() && declare -g acnr=()
declare -g ndef=() && declare -g leno=() && declare -g reno=() && declare -g bmedits=() && declare -g runtime=()
declare -g wmerased=() && declare -g wmfilled=()
## manifest check list
declare -g MISSING=() && declare -g EXISTS=() && declare -g RERUNSUB=() && declare -g COMPLETESUB=() # array for subjects with missing/existing/complete data or those needing rerun
export MANIFEST='' && export NUMFILES=''
## Pretty Colors
[ ! "${PRETTY}" ] && export PRETTY='paintitpretty'
# make things pretty by default unless user asks
if [ "${PRETTY}" = 'paintitpretty' ]; then
export RED='\033[0;31m'
export BRED='\033[1;31m'
export YELLOW='\033[1;33m'
export GREEN='\033[1;32m'
export BLUE='\033[1;34m'
export GREY='\033[1;37m'
export NC='\033[0m'
export BBLUE='\033[1;40m'
export NBC='\033[49m'
export GGREY='\033[1;30m'
export YBC='\033[47m'
export LRED='\033[1;31m'
else
export RED='' && export BRED='' && export YELLOW=''
export GREEN='' && export BLUE='' && export GREY=''
export NC='' && export BBLUE='' && export NBC=''
export GGREY='' && export YBC='' && export LRED=''
fi
## Table Preallocation
export TAB=$'\t' && declare -g TABLE=("SubjectID${TAB}Machine${TAB}JobStatus${TAB}TotalRunTime${TAB}ReconStage${TAB}NumBrainMaskEdits${TAB}NumWhiteMaskDel${TAB}NumWhiteMaskFill${TAB}TalCorr${TAB}OrigCNR${TAB}BrainMaskCNR${TAB}NumDefects${TAB}LEulerNo${TAB}REulerNo\n")
# HTML Web Report
export GITUSERNAME=$(git config -l | ggrep -oP '(?<=user.name=)[a-z]*.?')
export REPORTREPO_TEMPLATE="https://github.com/${GITUSERNAME}/Surfer-webgems.git"
export REPORTREPO=''
## Files for Webreports
export IEXT='mgz' && export OEXT='nii.gz'
declare -g SURFs=("lh.pial" "lh.white" "lh.inflated" "rh.pial" "rh.white" "rh.inflated")
declare -g MGZs=("T1" "brainmask" "wm" "aseg" "aparc+aseg" "aparc.DKTatlas+aseg" "aparc.a2009s+aseg" "wmparc")
[ ! "${DEFACEFILES}" ] && declare -g DEFACEFILES=("orig" "T1" "001")
[ ! "${CONVERTSURFFILES}" ] && declare -g CONVERTSURFFILES=("")
[ ! "${CONVERTVOLFILES}" ] && declare -g CONVERTVOLFILES=("")
# pre-allocate variables here to fill later
#>>${debugerr} echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_defaults $@"
}
export -f surfergems_defaults
####################################################################################################################
#
# DATASET & JOB MANAGEMENT
#
####################################################################################################################
### DEFINE FUNCTION
# check all files are present for subject
####################################################################################################################
## TODO custom check for average manifest (47 files?)
## TODO figure out longitudinal manifest...
## TODO distinguish between autorecon1, 2 and 3 completion (maybe use # of files present) - 20 for ar1
## TODO parallelize surfergems_files ::
### write sub-function surfergems_files_subject
### call surfergems_files.subject with gnu parallel & capture vars
### check status ---> running, successful jobs, failed jobs
function surfergems_files(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_files $@ (${SECONDS}s elapsed)"
local status=''
MANIFEST=$(cat ${SOURCEPATH}/fs-files-manifest.txt) && NUMFILES=$(echo "${MANIFEST}" | wc -l)
# build list of active/success/failed jobs (all inclusive)
if [ -z "${RUNNINGSUBJECTS[*]}" ] && [ -z "${FINISHEDSUBJECTS[*]}" ] && [ -z "${FAILEDSUBJECTS[*]}" ];
then
surfergems_status
return 0
fi
# printf '%d Subjects Found in ${SUBJECTS_DIR}\n' ${#SUBJECTS[@]}
counter=0
# iterate and check subjects for status and against manifest
for SUBJECT in "${SUBJECTS[@]}"; do
((counter++))
[ "$(echo "${RUNNINGSUBJECTS[@]}" | grep "${SUBJECT}")" ] && status=$(echo "🏃♂️ ${BLUE}${SUBJECT}${GREY} (running)")
[ "$(echo "${FAILEDSUBJECTS[@]}" | grep "${SUBJECT}")" ] && status=$(echo "🚧 ${BLUE}${SUBJECT}${YELLOW} (failed)")
[ "$(echo "${FINISHEDSUBJECTS[@]}" | grep "${SUBJECT}")" ] && status=$(echo "🏁 ${BLUE}${SUBJECT}${GREEN} (success)")
for FILE in ${MANIFEST}; do
if [ "$(find "${SUBJECTS_DIR}/${SUBJECT}" \( ! -regex '.*/\..*' \) -name "${FILE}" )" ]; then
printf "\r %s \r${GREY}🔎 (%d/%d) ${BLUE}${SUBJECT} :: ${FILE} ${GREY}(ok)${NC}\r" "$(tput el)" ${counter} ${#SUBJECTS[@]}
declare -g EXISTS+=("${SUBJECT} ${FILE}")
else
printf "\r %s \r${LRED}⨯ ${BLUE}${SUBJECT} :: ${FILE} ${YELLOW}(missing)${NC}\r" "$(tput el)"
declare -g MISSING+=("${SUBJECT} ${FILE}")
fi
done
NUMSUBFILES=$(printf '%s %s\n' ${EXISTS[@]} | grep ${SUBJECT} | sed "s|${SUBJECT}||g" | wc -w)
# NUMFOUND=${#EXISTS} && NUMMISSING=${#MISSING} && PERCENTFOUND=$(echo "scale=2; ${NUMFOUND} / ${NUMFILES} * 100" | bc)
if echo ${SUBJECT} | grep -qE '.?average'; then
if [ "${NUMSUBFILES}" -lt "48" ]; then
declare -g RERUNSUB+=("${SUBJECT}")
echo -e "\r${status} - ${YELLOW}${NUMSUBFILES} / 48 manifest files found${LRED} (incomplete)${NC}"
else
echo -e "\r${status} ${GREEN}✔ 48 files for average ${GREY}(ok)${NC}"
declare -g COMPLETESUB+=("${SUBJECT}")
fi
else
if [ "${NUMSUBFILES}" != "${NUMFILES}" ]; then
declare -g RERUNSUB+=("${SUBJECT}")
echo -e "\r${status} - ${YELLOW}${NUMSUBFILES} / ${NUMFILES} manifest files found${LRED} (incomplete)${NC}"
else
echo -e "\r${status} ${GREEN}✔ all files ${GREY}(ok)${NC}"
declare -g COMPLETESUB+=("${SUBJECT}")
fi
fi
## TODO - more elegant solution rather than brute text stream editing
if [ ${VERBOSE} ]; then
## missing volumes
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.mgz'))" ] && echo -e "${RED}x ${YELLOW}$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.mgz' | sed "s|${SUBJECT} ||g") | wc -w) volumes missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.mgz' | sed "s|${SUBJECT} ||g"))"
## missing talairach
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE 'tal.*'))" ] && echo -e "${RED}x ${YELLOW}$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE 'tal.*' | sed "s|${SUBJECT} ||g") | wc -w) talairach files missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE 'tal.*' | sed "s|${SUBJECT} ||g"))"
## missing nu
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE 'nu.*'))" ] && echo -e "${RED}x ${YELLOW}$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE 'nu.*' | sed "s|${SUBJECT} ||g") | wc -w) non-uniform intensity correction files missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE 'nu.*' | sed "s|${SUBJECT} ||g"))"
## missing lh surfs
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'lh.*'))" ] && echo -e "${RED}x ${YELLOW}$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'lh.*') | wc -w) lh surfaces missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'lh.*'))"
## missing rh surfs
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'rh.*'))" ] && echo -e "${RED}x ${YELLOW}$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'rh.*') | wc -w) rh surfaces missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'rh.*'))"
## missing stats
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.stats'))" ] && echo -e "${RED}x ${YELLOW} $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.stats' | wc -w) stats files missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.stats' | sed "s|${SUBJECT}||g")))"
## missing annot
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.annot'))" ] && echo -e "${RED}x ${YELLOW} $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.annot' | wc -w) annotations missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.annot' | sed "s|${SUBJECT}||g")))"
## missing ctab
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.ctab'))" ] && echo -e "${RED}x ${YELLOW} $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.ctab' | wc -w) color lookup tables missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.ctab' | sed "s|${SUBJECT}||g")))"
## missing labels
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.label'))" ] && echo -e "${RED}x ${YELLOW} $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.label' | wc -w) labels missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.label' | sed "s|${SUBJECT}||g")))"
## missing text files
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.txt'))" ] && echo -e "${RED}x ${BRED} $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.txt' | wc -w) txt files missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.txt' | sed "s|${SUBJECT}||g")))"
## missing logs
[ "$(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep -oE '.*.log'))" ] && echo -e "${RED}x ${BRED} $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.log' | wc -w) log files missing ${NC}:: $(echo $(printf '%s %s\n' "${MISSING[@]}" | grep "${SUBJECT}" | grep '.*.log' | sed "s|${SUBJECT}||g")))"
## present volumes
[ "$(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | grep -oE '.*.mgz'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | grep -oE '.*.mgz' | sed "s|${SUBJECT} ||g") | wc -w) volumes ok ${NC}:: $(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | grep -oE '.*.mgz' | sed "s|${SUBJECT} ||g"))"
## present lh surfs
[ "$(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'lh.*'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'lh.*') | wc -w) lh surfaces ok ${NC}:: $(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'lh.*'))"
## present rh surfs
[ "$(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'rh.*'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'rh.*') | wc -w) rh surfaces ok ${NC}:: $(echo $(printf '%s %s\n' "${EXISTS[@]}" | grep "${SUBJECT}" | sed 's|.*.label||g' | sed 's|.*.txt||g' | sed 's|.*.stats||g' | sed 's|.*.mgz||g' | sed 's|.*.dat||g' | sed 's|.*annot||g' | sed 's|.*mgh||g' | grep -oE 'rh.*'))"
## present talairach
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE 'tal.*'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE 'tal.*' | sed "s|${SUBJECT} ||g") | wc -w) talairach files ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE 'tal.*' | sed "s|${SUBJECT} ||g"))"
## present nu
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE 'nu.*'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE 'nu.*' | sed "s|${SUBJECT} ||g") | wc -w) talairach files ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE 'nu.*' | sed "s|${SUBJECT} ||g"))"
## present stats
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE '.*.stats'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.stats' | wc -w) stats files ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.stats' | sed "s|${SUBJECT}||g")))"
## present annot
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE '.*.annot'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.annot' | wc -w) annotations ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.annot' | sed "s|${SUBJECT}||g")))"
## present ctab
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE '.*.ctab'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.ctab' | wc -w) color lookup tables ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.ctab' | sed "s|${SUBJECT}||g")))"
## present labels
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE '.*.label'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.label' | wc -w) labels ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.label' | sed "s|${SUBJECT}||g")))"
## present text files
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE '.*.txt'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.txt' | wc -w) txt files ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.txt' | sed "s|${SUBJECT}||g")))"
## present log
# [ "$(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep -oE '.*.log'))" ] && echo -e "${GREEN}✔ $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.log' | wc -w) log files ok ${NC}:: $(echo $(printf '%s %s\n' ${EXISTS[@]} | grep "${SUBJECT}" | grep '.*.log' | sed "s|${SUBJECT}||g")))"
fi
done
#echo -e "\n${GREEN}EXISTING FILE MANIFEST:${NC} $(printf '%s ' ${EXISTS[@]})" >&2
echo -e "\n${YELLOW}MISSING FILE MANIFEST:\n${NC} $(printf '%s %s\n' ${MISSING[@]})" >&2
declare -g FILECHECK='done'
return 0
}
export -f surfergems_files
####################################################################################################################
### DEFINE FUNCTION
# Get Arrays of Subjects, Runtimes and Status for Active, Completed and Failed Recons
####################################################################################################################
## TODO this can be parallelized with a major rewrite (subfunctions with serial input and concat output)
## TODO sometimes subjects aren't running but have isrunning
## TODO need to distinguish between local and remote running jobs
function surfergems_status(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_status $@ (${SECONDS}s elapsed)"
# declare vars for status check & printing
[ ! "${STATUS}" ] && declare -g STATUS=("${GREY} active ${NC}" "${BLUE} success ${NC}" "${YELLOW} failed ${NC}" "${GREEN} done ${NC}" "${RED} incomplete ${NC}")
echo -e "\n\n ${NC} 🔦 Searching Dataset\n ⤷ ${GGREY}${YBC}${SUBJECTS_DIR}${NC}\n"
# Find all subjects with IsRunning file, get current status, time and host
if [ "$(echo "${STATUS[*]}" | grep -w 'active')" ] || [ "$(echo "${STATUS[*]}" | grep -w 'complete')" ] || [ "$(echo "${STATUS[*]}" | grep -w 'incomplete')" ]; then
for SUBJECT in "${SUBJECTS[@]}"; do
declare -g RUNNINGSUBJECTS+=($(find "${SUBJECTS_DIR}/${SUBJECT}" \( ! -regex '.*/\..*' \) -name 'IsRunning*' 2> /dev/null | sed "s|${SUBJECTS_DIR}||g" | sed "s|scripts/IsRunning.*||g" | sed "s|/||g"))
done
for SUBJECT in "${RUNNINGSUBJECTS[@]}"; do
declare -g RUNNINGSTATUS+=("$(tail -n 1 ${SUBJECTS_DIR}/${SUBJECT}/scripts/recon-all-status.log | sed "s|#@#|⦿|g" | awk '{i = 6; for (--i; i>=0; i--){$(NF-i)=""}print}'| awk '{{$NF=""}print}')")
declare -g RUNNINGTIME+=("$(grep -oE '[A-Z][a-z]{1,2}.[A-Z][a-z]{1,2}.{1,2}[1-9]{1,2}.{1,2}[0-2][0-9]:[0-9][0-9]:[0-9][0-9].[A-Z]{1,3}.[0-9]{2,4}' ${SUBJECTS_DIR}/${SUBJECT}/scripts/recon-all-status.log | tail -n 1)")
declare -g RUNNINGID+=("${SUBJECT} $(grep "PROCESSID" ${SUBJECTS_DIR}/${SUBJECT}/scripts/IsRunning* | awk '{print $NF}')")
declare -g RUNNINGHOSTS+=("$(grep "HOST" ${SUBJECTS_DIR}/${SUBJECT}/scripts/IsRunning* | awk '{print $NF}' | sed 's/.local//')")
done
fi
# Find all subjects with recon-all.log file and list those with finished message at end of log
if [ "$(echo ${STATUS[*]} | grep -w 'success')" ] || [ "$(echo "${STATUS[*]}" | grep -w 'complete')" ] || [ "$(echo "${STATUS[*]}" | grep -w 'incomplete')" ]; then
RECONS=""
for SUBJECT in "${SUBJECTS[@]}"; do
RECONS+="$(find ${SUBJECTS_DIR}/${SUBJECT}/scripts \( ! -regex '.*/\..*' \) -name 'recon-all.log' -not -iwholename '*fsaverage*' 2> /dev/null) "
done
counter=0
for RECON in ${RECONS}; do
if [ "$(tail -n 5 ${RECON} | grep -B 0 "finished without error")" ]; then
# declare -g FINISHEDSUBJECTS+=("$(tail -n 5 ${RECON} | grep -B 0 "finished without error" | awk '{print $3}')")
declare -g FINISHEDSUBJECTS+=(${SUBJECTS[$counter]})
# FINISHTIMES+=("$(tail -n 5 ${RECON} | grep -B 0 "finished without error" | sed 's|\\n| |g' | awk '{i = 6; for (--i; i >= 0; i--){ printf "%s ",$(NF-i)} print ""}';)")
declare -g FINISHTIMES+=("$(tail -n 5 ${RECON} | grep -B 0 "finished without error" | sed 's|\\n| |g' | egrep -o '[A-Z][a-z]{1,2}.[A-Z][a-z]{1,2}.{1,2}[1-9]{1,2}.{1,2}[0-2][0-9]:[0-9][0-9]:[0-9][0-9].[A-Z]{1,3}.[0-9]{2,4}' | tail -n 1)")
declare -g FINISHEDHOSTS+=("$(grep "hostname" ${RECON} | tail -n 1 | awk '{print $NF}' | sed 's/.local//')")
declare -g STARTTIMES+=("$(tail -n 5 ${RECON} | grep -B 0 "Started at" | head -n 1 | sed 's/Started at //g')")
fi
((counter++))
done
fi
if [ "$(echo ${STATUS[*]} | grep -w 'failed')" ] || [ "$(echo "${STATUS[*]}" | grep -w 'complete')" ] || [ "$(echo "${STATUS[*]}" | grep -w 'incomplete')" ]; then
RECONS=""
for SUBJECT in "${SUBJECTS[@]}"; do
RECONS+="$(find ${SUBJECTS_DIR}/${SUBJECT}/scripts \( ! -regex '.*/\..*' \) -name 'recon-all.log' -not -iwholename '*fsaverage*' 2> /dev/null) "
done
for RECON in ${RECONS}; do
SUBJECT=$(echo ${RECON} | sed "s|${SUBJECTS_DIR}/||g" | sed 's|/scripts/recon-all.log||g' | sed 's|/||g')
if [ "$(tail -n 10 ${RECON} | grep -B 0 "exited with ERRORS at")" ]; then
# declare -g FAILEDSUBJECTS+=("$(tail -n 5 ${RECON} | grep -B 0 "exited with ERRORS at" | awk '{print $3}')")
FAILEDSUBJECTS+=(${SUBJECT})
declare -g FAILPOINT+=("$(tail -n 5 "${SUBJECTS_DIR}/${SUBJECT}/scripts/recon-all-status.log" | grep '#@#' | tail -n 1 | sed "s|#@#|⦿|g" | awk '{i = 6; for (--i; i>=0; i--){$(NF-i)=""}print}'| awk '{{$NF=""}print}')")
declare -g FAILTIMES+=("$(tail -n 5 ${RECON} | grep -B 0 "exited with ERRORS at" | egrep -o '[A-Z][a-z]{1,2}.[A-Z][a-z]{1,2}.{1,2}[1-9]{1,2}.{1,2}[0-2][0-9]:[0-9][0-9]:[0-9][0-9].[A-Z]{1,3}.[0-9]{2,4}' | tail -n 1)")
declare -g FAILEDHOSTS+=("$(grep 'hostname' ${RECON} | tail -1 | awk '{print $NF}' | sed 's/.local//')")
fi
# Collect any other subjects that don't show running files, a fail message at end of log OR
if [ ! "$(find ${SUBJECTS_DIR}/${SUBJECT}/scripts \( ! -regex '.*/\..*' \) -name 'IsRunning*' 2> /dev/null)" ] && [ ! "$(tail -n 5 ${RECON} | grep -B 0 "finished without error")" ] && [ ! "$(tail -n 10 ${RECON} | grep -B 0 "exited with ERRORS at")" ]; then
declare -g FAILEDSUBJECTS+=("$(echo ${SUBJECT})")
declare -g FAILPOINT+=("$(tail -n 5 "${SUBJECTS_DIR}/${SUBJECT}/scripts/recon-all-status.log" | grep '#@#' | tail -n 1 | sed "s|#@#|⦿|g" | awk '{i = 6; for (--i; i>=0; i--){$(NF-i)=""}print}'| awk '{{$NF=""}print}')")
declare -g FAILTIMES+=("$(egrep -o '[A-Z][a-z]{1,2}.[A-Z][a-z]{1,2}.{1,2}[1-9]{1,2}.{1,2}[0-2][0-9]:[0-9][0-9]:[0-9][0-9].[A-Z]{1,3}.[0-9]{2,4}' ${SUBJECTS_DIR}/${SUBJECT}/scripts/recon-all-status.log | tail -n 1)")
declare -g FAILEDHOSTS+=("$(grep 'hostname' ${RECON} | tail -1 | awk '{print $NF}' | sed 's/.local//')")
fi
((counter++))
done
fi
# SUBJECT can either be running, finished running or failed running
declare -g SUBJECTS=("${RUNNINGSUBJECTS[@]}" "${FINISHEDSUBJECTS[@]}" "${FAILEDSUBJECTS[@]}")
if [ ! "${SUBJECTS}" ]; then
printf "◀︎|⁃‣ No Subjects found in ${SUBJECTS_DIR} with status %s\n" $(echo -e "${STATUS[@]}")
fi
if [ "$(echo ${STATUS[*]} | grep -w 'incomplete')" ] || [ "$(echo ${STATUS[*]} | grep -w 'complete')" ]; then
surfergems_files
fi
# signal that the status has been checked (prevents this from being run twice when called to populate an empty subjects variable that may be empty anyway bc none satisfy conditions (i.e. failed))
export STATUSCHECK='done'
export SUBJECTS
export RUNNINGSUBJECTS
export FINISHEDSUBJECTS
export FAILEDSUBJECTS
surfergems_printstatus
return 0
}
export -f surfergems_status
####################################################################################################################
### DEFINE FUNCTION
# get individual subject status (inactive, not used anywhere yet)
########################h############################################################################################
## TODO
function surfergems_status_subject(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_status_subject $@ (${SECONDS}s elapsed)"
# get last reported recon status
echo "$(tail -n 5 ${SUBJECTS_DIR}/${1}/scripts/recon-all-status.log | grep "#@#" | tail -n 1 | sed "s|#@#||g" | awk '{i = 6; for (--i; i>=0; i--){$(NF-i)=""}print}' | awk '{{$NF=""}print}')"
}
export -f surfergems_status_subject
####################################################################################################################
### DEFINE FUNCTION
# stop all current recon jobs using either SGE (if available) or KILL command
####################################################################################################################
## TODO can use host information to kill remote jobs
function surfergems_killJobs(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_killJobs $@ (${SECONDS}s elapsed)"
[ -z ${STATUSCHECK} ] && STATUS=('active') && surfergems_status
echo -e "\n 🗑 Hanging Up Active Processes: ${SUBJECTS[@]}\n"
for subject in "${SUBJECTS[@]}"; do
kill -9 $(echo $(printf '%s %s\n' "${RUNNINGID[@]}" | grep "${SUBJECT}") | awk '{print $NF}')
find ${SUBJECTS_DIR}/${subject} \( ! -regex '.*/\..*' \) -name 'IsRunning*' -exec rm -v {} \;
done
## TODO SGE/TBS commands
# [ $(which qdel) ] && echo -e '\n\t Deleting GRID jobs... for ' $(whoami) && qdel -u $(whoami)
# [ ! $(which qdel) ] && echo -e "🖐 ${YELLOW}Hanging up all local processes matching ${GREY}'${KILLPATTERN}'${YELLOW} pattern${NC}" && kill -9 $(echo $(ps aux | grep ${KILLPATTERN} | tail -n +2 | awk '{print $2}')) 2> /dev/null
# [ "$(find ${SUBJECTS_DIR}/ \( ! -regex '.*/\..*' \) -name 'IsRunning*' 2> /dev/null)" ] && parallel -k --link rm -v {} ::: $(find ${SUBJECTS_DIR}/ -name 'IsRunning*' 2> /dev/null)
# [ -z "${STATUS}" ] && exit
}
export -f surfergems_killJobs
####################################################################################################################
### DEFINE FUNCTION
# rerun failed / incomplete
####################################################################################################################
## TODO run with -make all by default, allow user to specify flags
## create SGE script if sge detected
## otherwise run with gnu parallel
function surfergems_rerun(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_rerun $@ (${SECONDS}s elapsed)"
echo 'work in progress'
}
export -f surfergems_rerun
####################################################################################################################
#
# PRINTING TO FILE
#
####################################################################################################################
### DEFINE FUNCTION
# parse output files for stats
####################################################################################################################
function surfergems_check_input_subjects(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_check_input_subjects $@ (${SECONDS}s elapsed)"
local subjects="$@"
if [ ! "${subjects}" ]
then
# get list of subjects with complete data by default
if [ ! "${SUBJECTS}" ]
then
surfergems_status && declare -g SUBJECTS=("${COMPLETESUB[@]}") && local subjects=${SUBJECTS[@]}
else
# otherwise just use existing global variable and run serially
local averages="$(echo "${SUBJECTS[@]}" | grep -oE '(\s.*?_)?average\s?')"
local subjects=${SUBJECTS[@]}
## --> but first filter out any averages (indicated with *_average or just 'average')
if [ "${averages}" ]
then
for avg in ${averages}; do
subjects=$(echo "${subjects}" | sed "s|${avg}||g"| sort -u)
done
fi
fi
fi
printf '%s ' ${subjects}
}
export -f surfergems_check_input_subjects
####################################################################################################################
### DEFINE FUNCTION
# parse output files for stats
####################################################################################################################
function surfergems_stats(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_stats $@ (${SECONDS}s elapsed)"
local subjects="$(surfergems_check_input_subjects "$@")"
# declare vars for status check & printing
[ ! "${STATUS}" ] && declare -g STATUS=("${GREY} active ${NC}" "${BLUE} success ${NC}" "${YELLOW} failed ${NC}" "${GREEN} done ${NC}" "${RED} incomplete ${NC}")
# summarize subject edits
# TODO redirection works here?
if echo "${subjects}" | parallel -k --link --bar '(surfergems_subject_edits {})' 3>&4 4>&2
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} parallel -k --link surfergems_subject_edits {} ::: ${subjects}${NC}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} parallel -k --link surfergems_subject_edits {} ::: ${subjects}${NC} failed\n"
return 1
fi
# generate file manifest
if surfergems_files
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} surfergems_files${NC}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} surfergems_files${NC} failed\n"
return 1
fi
# Calculate stats for all subjects
if surfergems_stats_calc "${subjects}"
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} surfergems_stats_calc ${subjects}${NC}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} surfergems_stats_calc ${subjects}${NC} failed\n"
return 1
fi
# Build table
if surfergems_stats_table "${subjects}"
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} surfergems_stats_table ${subjects} ${NC}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} surfergems_stats_table ${subjects} ${NC} failed\n"
return 1
fi
return 0
}
export -f surfergems_stats
####################################################################################################################
### DEFINE FUNCTION
# parse output files for stats
####################################################################################################################
## TODO make individual functions for each of the stats and make them option accessible
## TODO must update TABLE header based on this
## TODO average defect size
function surfergems_stats_calc(){
>&2 printf " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_stats_calc %s (${SECONDS}s elapsed)" "$@"
local subjects="$(surfergems_check_input_subjects "$@")"
# Start loop across subjects
local counter=0
# support for serial processing
for s in ${subjects}; do
# Calculate time spent on current recon stage for active jobs
if [ "$(echo ${RUNNINGSUBJECTS[*]} | grep -oE ${s})" ]
then
declare -g status+=('running')
declare -g pid+=("${s} $(grep "PROCESSID" ${SUBJECTS_DIR}/${s}/scripts/IsRunning* | awk '{print $NF}')")
declare -g hname+=("$(grep "HOST" ${SUBJECTS_DIR}/${s}/scripts/IsRunning* | sed 's/HOST //g' | sed 's/.local//g')")
tstart="$(tail -n 1 ${SUBJECTS_DIR}/${s}/scripts/recon-all-status.log | sed "s|#@#|⦿|g" | grep -oE '[A-Z][a-z]{1,2}.[A-Z][a-z]{1,2}.{1,2}[1-9]{1,2}.{1,2}[0-2][0-9]:[0-9][0-9]:[0-9][0-9].[A-Z]{1,3}.[0-9]{2,4}' ${SUBJECTS_DIR}/${s}/scripts/recon-all-status.log | tail -n 1)"
if [ "$(echo "${tstart}" | grep -E '\d{1,2}:\d{1,2}:\d{1,2}')" ]; then
tnow=$(date) && tstart=$(date -d "${tstart}" '+%s') && tnow=$(date -d "${tnow}" '+%s') && trun=$((tnow-tstart))
declare -g runtime+=("$(printf '%02d:%02d:%02d\n' $((trun / 3600)) $((trun % 3600 / 60)) $((trun % 60)))")
else
declare -g runtime+=("nan")
fi
fi
# calculate total time spent running
if [ "$(echo ${FINISHEDSUBJECTS[*]} | grep -oE ${s})" ]
then
if [ "$(echo ${RERUNSUB[*]} | grep -oE ${s})" ]
then
status+=('incomplete')
elif [ "$(echo ${COMPLETESUB[*]} | grep -oE ${s})" ]
then
status+=('complete')
else
status+=('success')
fi
declare -g hname+=("$(grep "hostname" ${SUBJECTS_DIR}/${s}/scripts/recon-all.log | tail -1 | awk '{print $NF}' | sed 's/.local//')")
tstart="$(tail -n 5 ${SUBJECTS_DIR}/${s}/scripts/recon-all.log | grep -B 0 "Started at" | head -n 1 | sed 's/Started at //g')"
tdone="$(tail -n 5 ${SUBJECTS_DIR}/${s}/scripts/recon-all.log | grep -B 0 "finished without error" | sed 's|\\n| |g' | grep -oE '[A-Z][a-z]{1,2}.[A-Z][a-z]{1,2}.{1,2}[1-9]{1,2}.{1,2}[0-2][0-9]:[0-9][0-9]:[0-9][0-9].[A-Z]{1,3}.[0-9]{2,4}' ${SUBJECTS_DIR}/${s}/scripts/recon-all-status.log | tail -n 1)"
if [ "$(echo "${tstart}" | grep -E '\d{1,2}:\d{1,2}:\d{1,2}')" ] && [ "$(echo "${tdone}" | grep -E '\d{1,2}:\d{1,2}:\d{1,2}')" ]; then
tstart=$(date -d "${tstart}" '+%s') && tdone=$(date -d "${tdone}" '+%s') && trun=$((tdone-tstart))
declare -g runtime+=("$(printf '%02d:%02d:%02d\n' $((trun / 3600)) $((trun % 3600 / 60)) $((trun % 60)))")
else
declare -g runtime+=("nan")
fi
fi
if [ "$(echo "${FAILEDSUBJECTS[*]}" | grep -oE "${s}")" ]; then
declare -g status+=('failed')
declare -g hname+=("$(grep "hostname" ${SUBJECTS_DIR}/${s}/scripts/recon-all.log | tail -1 | awk '{print $NF}' | sed 's/.local//')")
## TODO - is there any way to figure out how long recon was running before failure? there is no start time anywhere?
declare -g runtime+=("nan")
fi
# get last reported recon status
declare -g reconstatus+=("$(tail -n 5 ${SUBJECTS_DIR}/${s}/scripts/recon-all-status.log | grep "#@#" | tail -n 1 | sed "s|#@#||g" | awk '{i = 6; for (--i; i>=0; i--){$(NF-i)=""}print}' | awk '{{$NF=""}print}')")
# Count up the number of brainmask edits
# printf "\r%s✏️ 📊 %d/%d -- Compiling Edits" "$(tput el)" $counter ${#SUBJECTS[*]} && surfergems_subject_edits ${s}
declare -g bmedits+=("$(awk '{print $1}' < ${SUBJECTS_DIR}/${s}/stats/bm.erase.dat)")
declare -g wmerased+=("$(awk '{print $1}' < ${SUBJECTS_DIR}/${s}/stats/wm.erase.dat)")
declare -g wmfilled+=("$(awk '{print $1}' < ${SUBJECTS_DIR}/${s}/stats/wm.fill.dat)")
# get talairach quality assurance
declare -g talqa+=("$(grep "TalAviQA" ${SUBJECTS_DIR}/"${s}"/scripts/recon-all.log | tail -1 | awk '{print $NF}')")
# count defects
declare -g ndef+=("$(grep "defects" ${SUBJECTS_DIR}/${s}/scripts/recon-all.log | tail -1 | awk '{print $1}')")
declare -g leno+=("$(grep -Eo "lheno =.*[ *$]-[0-9]{1,4}" ${SUBJECTS_DIR}/${s}/scripts/recon-all.log | tail -n 1 | awk '{print $NF}')")
declare -g reno+=("$(grep -Eo "rheno =.*[ *$]-[0-9]{1,4}" ${SUBJECTS_DIR}/${s}/scripts/recon-all.log | tail -n 1 | awk '{print $NF}')")
# Calculate CNR
declare -g bcnr+=("$("${FREESURFER_HOME}"/bin/mri_cnr ${SUBJECTS_DIR}/${s}/surf/ ${SUBJECTS_DIR}/${s}/mri/orig/001.mgz | tail -1 | awk '{print $NF}')")
declare -g acnr+=("$("${FREESURFER_HOME}"/bin/mri_cnr ${SUBJECTS_DIR}/${s}/surf/ ${SUBJECTS_DIR}/${s}/mri/T1.mgz | tail -1 | awk '{print $NF}')")
# set nans for stats with no vals
[ ! "${hname[$counter]}" ] && hname[$counter]=nan
[ ! "${runtime[$counter]}" ] && runtime[$counter]=nan
[ ! "${status[$counter]}" ] && status[$counter]=nan
[ ! "${reconstatus[$counter]}" ] && reconstatus[$counter]=nan
[ ! "${bcnr[$counter]}" ] && bcnr[$counter]=nan
[ ! "${acnr[$counter]}" ] && acnr[$counter]=nan
[ ! "${ndef[$counter]}" ] && ndef[$counter]=nan
[ ! "${leno[$counter]}" ] && leno[$counter]=nan
[ ! "${reno[$counter]}" ] && reno[$counter]=nan
[ ! "${bmedits[$counter]}" ] && bmedits[$counter]=nan
[ ! "${wmerased[$counter]}" ] && wmerased[$counter]=nan
[ ! "${wmfilled[$counter]}" ] && wmfilled[$counter]=nan
#
((counter++))
done
declare -g reconstatus
return 0
}
export -f surfergems_stats_calc
####################################################################################################################
### DEFINE FUNCTION
# create summary statistic files
####################################################################################################################
function surfergems_morph_stats(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_morph_stats $@ (${SECONDS}s elapsed)"
local subjects="$(surfergems_check_input_subjects "$@")"
local averages="$(echo ${SUBJECTS[@]} | grep -oE '(\s.*?_)?average\s?')"
[ ! "${measures}" ] && local measures=${MEASURES[*]}
[ ! "${atlas}" ] && local atlas=${ATLAS[*]}
## filter out any averages (indicated with *_average or just 'average')
if [ "${averages}" ]
then
for avg in ${averages}; do
subjects=$(echo "${subjects}" | sed "s|${avg}||g"| sort -u)
done
fi
## Print surface area statistics
if [ "${subjects}" ]
then
for atla in ${atlas}; do
if [ "${atla}" = 'aseg' ]; then
## Print volume (mm^3) information
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}"/recon-volume-stats.txt ]
then
if "${FREESURFER_HOME}"/bin/asegstats2table --subjects ${subjects} --tablefile "${SUBJECTS_DIR}"/recon-volume-stats.txt -m 'volume' --skip >&4
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/asegstats2table --subjects ${subjects} --tablefile ${SUBJECTS_DIR}/recon-volume-stats.txt -m 'volume' --skip${BLUE}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/asegstats2table --subjects ${subjects} --tablefile ${SUBJECTS_DIR}/recon-volume-stats.txt -m 'volume' --skip${BLUE}\n"
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${SUBJECTS_DIR}/recon-volume-stats.txt${NC}"
fi
if [ "${OVERWRITE}" ] || [ ! -f ${SUBJECTS_DIR}/recon-mean-intensity-stats.txt ]
then
if "${FREESURFER_HOME}"/bin/asegstats2table --subjects ${subjects} --tablefile "${SUBJECTS_DIR}"/recon-mean-intensity-stats.txt -m 'mean' --skip >&4
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/asegstats2table --subjects ${subjects} --tablefile ${SUBJECTS_DIR}/recon-mean-intensity-stats.txt -m 'mean' --skip${BLUE}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/asegstats2table --subjects ${subjects} --tablefile ${SUBJECTS_DIR}/recon-mean-intensity-stats.txt -m 'mean' --skip${BLUE}\n"
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${SUBJECTS_DIR}/recon-mean-intensity-stats.txt${NC}"
fi
if [ "${OVERWRITE}" ] || [ ! -f ${SUBJECTS_DIR}/recon-std-intensity-stats.txt ]
then
if "${FREESURFER_HOME}"/bin/asegstats2table --subjects ${subjects} --tablefile "${SUBJECTS_DIR}"/recon-std-intensity-stats.txt -m 'std' --skip >&4
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/asegstats2table --subjects ${subjects} --tablefile ${SUBJECTS_DIR}/recon-std-intensity-stats.txt -m 'std' --skip${BLUE}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/asegstats2table --subjects ${subjects} --tablefile ${SUBJECTS_DIR}/recon-std-intensity-stats.txt -m 'std' --skip${BLUE}\n"
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${SUBJECTS_DIR}/recon-std-intensity-stats.txt${NC}"
fi
elif [ "${atla}" = 'aparc' ] || [ "${atla}" = 'aparc.a2009s' ]; then
## Print surface (vertex) statistics
for measure in ${measures}; do
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}"/recon-lh-"${measure}"-"${atla}"-stats.txt ]
then
if "${FREESURFER_HOME}"/bin/aparcstats2table --hemi lh -m "${measure}" --subjects ${subjects} -p "${atla}" -t "${SUBJECTS_DIR}"/recon-lh-"${measure}"-"${atla}"-stats.txt --skip >&4
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/aparcstats2table --hemi lh -m ${measure} --subjects ${subjects} -p ${atla} -t ${SUBJECTS_DIR}/recon-lh-${measure}-${atla}-stats.txt --skip${BLUE}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/aparcstats2table --hemi lh -m ${measure} --subjects ${subjects} -p ${atla} -t ${SUBJECTS_DIR}/recon-lh-${measure}-${atla}-stats.txt --skip${BLUE}\n"
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${SUBJECTS_DIR}/recon-lh-${measure}-${atla}-stats.txt${NC}"
fi
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}"/recon-rh-"${measure}"-"${atla}"-stats.txt ]
then
if ${FREESURFER_HOME}/bin/aparcstats2table --hemi rh -m "${measure}" --subjects ${subjects} -p "${atla}" -t "${SUBJECTS_DIR}"/recon-rh-"${measure}"-"${atla}"-stats.txt --skip >&4
then
>&4 printf "${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/aparcstats2table --hemi rh -m ${measure} --subjects ${subjects} -p ${atla} -t ${SUBJECTS_DIR}/recon-lh-${measure}-${atla}-stats.txt --skip${BLUE}\n"
else
>&2 printf "${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/aparcstats2table --hemi rh -m ${measure} --subjects ${subjects} -p ${atla} -t ${SUBJECTS_DIR}/recon-lh-${measure}-${atla}-stats.txt --skip${BLUE}\n"
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${SUBJECTS_DIR}/recon-rh-${measure}-${atla}-stats.txt${NC}"
fi
done
fi
done
else
return 1
fi
}
export -f surfergems_morph_stats
####################################################################################################################
## DEFINE FUNCTION
# print stats to table
# TODO overwrite check?
# TODO view option?
####################################################################################################################
function surfergems_stats_table(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_stats_table $@ (${SECONDS}s elapsed)"
local subjects="$(surfergems_check_input_subjects $@)"
counter=0
# loop across subjects and build table
for subject in ${subjects}; do
declare -g TABLE+=($(echo "${subject}\t${hname[$counter]}\t${status[$counter]}\t${runtime[$counter]}\t${reconstatus[$counter]}\t${bmedits[$counter]}\t${wmfilled[$counter]}\t${wmerased[$counter]}\t${talqa[$counter]}\t${bcnr[$counter]}\t${acnr[$counter]}\t${ndef[$counter]}\t${leno[$counter]}\t${reno[$counter]}\n"))
((counter++))
done
# echo -e "${TABLE[@]}" > ${SUBJECTS_DIR}/check-recons-report-$(date '+%H:%M:%S|%Y-%m-%d').txt && echo -e '\n 💾 Table written to'${SUBJECTS_DIR}'/check-recons-report.txt\n'
echo -e "${TABLE[@]}" > "${SUBJECTS_DIR}/${RECONSTATS}"
echo -e "${NC}💾 Reconstruction Statistics Written to ${GREY}${SUBJECTS_DIR}/${RECONSTATS}${NC}"
# [ ${VERBOSE} ] && cat ${SUBJECTS_DIR}/recon-statistics.txt | column -s $'\t' -t
return 0
}
export -f surfergems_stats_table
####################################################################################################################
### DEFINE FUNCTION
# calculate contrast-to-noise
####################################################################################################################
## TODO write CNR computation
function surfergems_subject_cnr(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_subject_cnr $@ (${SECONDS}s elapsed)"
echo 'work in progress'
}
export -f surfergems_subject_cnr
####################################################################################################################
### DEFINE FUNCTION
# convert files
####################################################################################################################
## TODO option parsing doesn't support multiple subjects
## TODO use flags to indicate when input starts / ends
function surfergems_convert(){
>&4 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_convert $@ (${SECONDS}s elapsed)"
local convert=${1} && shift
local iext=${1} && shift
[ "${iext}" = 'null' ] && local iext=''
local oext=${1} && shift
local subject=${1} && shift
local files=("$@")
local counter=0
# populate with default files if no user specification
[ "${CONVERTVOL}" ] && [ -z "${files}" ] && local files=("T1" "brainmask" "wm" "aseg" "aparc+aseg" "aparc.DKTatlas+aseg" "aparc.a2009s+aseg" "wmparc")
[ "${CONVERTSURF}" ] && [ -z "${files}" ] && local files=("lh.white" "lh.pial" "lh.inflated" "rh.white" "rh.pial" "rh.inflated")
# check for subject input
if [ ! "${subject}" ]; then
if [ ! "${SUBJECTS}" ]
then
# find finished subjects and create global var if not already existing
# -- only convert finished subjects`
surfergems_status && declare -g SUBJECTS=("${COMPLETESUB[@]}") && local subject=${SUBJECTS[@]}
else
# otherwise just use existing global variable
local subject=${SUBJECTS[@]}
fi
fi
# support for serial processing
local filepath=''
for s in ${subject}; do
for f in "${files[@]}"; do
[ ${iext} ] && [ ! "$(echo ${iext} | grep '^\.')" ] && iext=".${iext}"
[ ! "$(echo "${oext}" | grep '^\.')" ] && oext=".${oext}"
filepath=$(find "${SUBJECTS_DIR}"/"${s}" \( ! -regex '.*/\..*' \) -name "${f}${iext}")
if [ "${filepath}" ]; then
if [ "${OVERWRITE}" ] || [ ! $(find "${SUBJECTS_DIR}/${s}" \( ! -regex '.*/\..*' \) -name "${f}${oext}") ]; then
[ "${OVERWRITE}" ] && >&1 printf "${OVERWRITE} %s :: %s%s\n" "${s}" "${f}" "${oext}"
if [ "${convert}" = 'vol' ]; then
if "${FREESURFER_HOME}"/bin/mri_convert \
"${filepath}" \
"$(echo "${filepath}" | sed "s|${iext}|${oext}|")" >&3
then
>&3 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mri_convert ${filepath} $(echo ${filepath} | sed "s|${iext}|${oext}|")${BLUE}\n"
else
>&4 printf "\r${BRED}◀︎|⁃‣ERROR${NC} ${FREESURFER_HOME}/bin/mri_convert ${filepath} $(echo ${filepath} | sed "s|${iext}|${oext}|") FAILED${BLUE}\n"
return 1
fi
elif [ "${convert}" = 'surf' ]; then
if "${FREESURFER_HOME}"/bin/mris_convert \
"${SUBJECTS_DIR}/${s}/surf/${f}${iext}" \
"${SUBJECTS_DIR}/${s}/surf/${f}.${oext}" >&3
then
>&3 printf "\r${GREEN}◀︎|⁃‣SUCCESS${NC} ${FREESURFER_HOME}/bin/mris_convert ${SUBJECTS_DIR}/${s}/surf/${f}${iext} ${SUBJECTS_DIR}/${s}/surf/${f}.${oext}${BLUE}\n"
else
>&4 printf "\r${BRED}◀︎|⁃‣ERROR${NC} ${FREESURFER_HOME}/bin/mris_convert ${SUBJECTS_DIR}/${s}/surf/${f}${iext} ${SUBJECTS_DIR}/${s}/surf/${f}.${oext} FAILED${BLUE}\n"
return 1
fi
else
>&4 echo -e "${BRED}ERROR :: Unknown Conversion (Surf or Vol?)${NC}"
return 1
fi
else
>&1 echo -e "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} $(find "${SUBJECTS_DIR}/${s}" \( ! -regex '.*/\..*' \) -name "${f}${oext}")${NC}"
fi
((counter ++))
else
>&1 echo -e "${YELLOW}◀︎|⁃‣${YELLOW}WARNING${NC} ${f}${iext} not found for ${subject}"
return 0
fi
done
done
return 0
}
export -f surfergems_convert
####################################################################################################################
## DEFINE FUNCTION
# deface files
####################################################################################################################
## TODO (no overwrite check?)
## TODO fix input parsing for subject (allow multiple subs)
function surfergems_deface(){
>&4 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_deface $@ (${SECONDS}s elapsed)"
local subject=${1} && shift
local iext=${1} && shift
local files="$@"
local counter=0
# use global variables for files if not specified
[ ! "${files}" ] && files=${DEFACEFILES[@]}
# check input subject
if [ ! "${subject}" ]; then
if [ ! "${SUBJECTS}" ]; then
# find finished subjects and create global var if not already existing
# -- only convert finished subjects`
surfergems_status && declare -g SUBJECTS=("${COMPLETESUB[@]}") && local subject=${SUBJECTS[@]}
else
# otherwise just use existing global variable
local subject=${SUBJECTS[@]}
fi
fi
for s in ${subject}; do
for f in ${files}; do
local filepath=$(find ${SUBJECTS_DIR}/${s} -name ${f}".${iext}")
if [ -f ${filepath} ]; then
1>&4 2>&4 cp -vn ${filepath} $(echo ${filepath} | sed "s|.${iext}|_orig.${iext}|g")
if echo ${FREESURFER_HOME}/bin/mri_deface \
${filepath} \
${SOURCEPATH}'/bin/talairach_mixed_with_skull.gca' \
${SOURCEPATH}'/bin/face.gca' \
${filepath} >&3
then
>&3 printf "\r${GREEN}◀︎|⁃‣SUCCESS${NC} ${FREESURFER_HOME}/bin/mri_deface ${filepath} ${SOURCEPATH}'/bin/talairach_mixed_with_skull.gca' ${SOURCEPATH}'/bin/face.gca' ${filepath}${BLUE}\n"
else
>&4 printf "\r${BRED}◀︎|⁃‣ERROR${NC} ${FREESURFER_HOME}/bin/mri_deface ${filepath} ${SOURCEPATH}'/bin/talairach_mixed_with_skull.gca' ${SOURCEPATH}'/bin/face.gca' ${filepath} FAILED${BLUE}\n"
return 1
fi
else
>&3 echo -e "${YELLOW}◀︎|⁃‣${YELLOW}WARNING${NC} ${f}.${iext} not found for ${subject}\r"
return 0
fi
done
done
return 0
}
export -f surfergems_deface
####################################################################################################################
### DEFINE FUNCTION
# summarize subject edits
####################################################################################################################
function surfergems_subject_edits(){
>&3 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_subject_edits $@ (${SECONDS}s elapsed)"
local subjects="$(surfergems_check_input_subjects "$@" 2>&4)"
local counter=0
# supports list for serial processing
for s in ${subjects}; do
# map edits to surface
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${s}/qc/bm.erase.mgh" ] || [ ! -f "${SUBJECTS_DIR}/${s}/qc/bm.clone.mgh" ] || [ ! -f "${SUBJECTS_DIR}/${s}/qc/diff.mgh" ]
then
if "${FREESURFER_HOME}"/bin/bmedits2surf --self --tmp "${SUBJECTS_DIR}/${s}/qc" \
--s "${s}" --overwrite >&3 2>&4
then
>&3 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/bmedits2surf --self --tmp ${SUBJECTS_DIR}/${s}/qc --s ${s} --overwrite${BLUE}\n"
else
>&4 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/bmedits2surf --self --tmp ${SUBJECTS_DIR}/${s}/qc --s ${s} --overwrite FAILED${BLUE}\n"
continue
fi
else
>&3 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${s} brainmask edits summary${NC}\n"
fi
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${s}/qc/wm.erase.mgh" ] || [ ! -f "${SUBJECTS_DIR}/${s}/qc/wm.fill.mgh" ]; then
if "${FREESURFER_HOME}"/bin/wmedits2surf --self --tmp "${SUBJECTS_DIR}/${s}/qc" \
--s "${s}" --overwrite >&3 2>&4
then
>&3 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/wmedits2surf --self --tmp ${SUBJECTS_DIR}/${s}/qc --s ${s} --overwrite${BLUE}\n"
else
>&4 printf "\r${BRED}◀︎|⁃‣ERROR${NC} ${FREESURFER_HOME}/bin/wmedits2surf --self --tmp ${SUBJECTS_DIR}/${s}/qc --s ${s} --overwrite FAILED${BLUE}\n"
continue
fi
else
>&3 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${s} white matter mask edits summary${NC}\n"
fi
# convert to atlas annotation for projection on surfaces
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${s}/qc/rh.bmedits.annot" ] ; then
if "${FREESURFER_HOME}"/bin/mris_seg2annot --seg "${SUBJECTS_DIR}/${s}/surf/rh.bmerase.mgh" \
--s "${s}" --ctab-auto --h rh --surf white \
--o "${SUBJECTS_DIR}/${s}/qc/rh.bmedits.annot" >&3 2>&4
then
>&3 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mris_seg2annot --seg ${SUBJECTS_DIR}/${s}/surf/rh.bmerase.mgh --s ${s} --ctab-auto --h rh --surf white --o ${SUBJECTS_DIR}/${s}/qc/rh.bmedits.annot${BLUE}\n"
else
>&4 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/mris_seg2annot --seg ${SUBJECTS_DIR}/${s}/surf/rh.bmerase.mgh --s ${s} --ctab-auto --h rh --surf white --o ${SUBJECTS_DIR}/${s}/qc/rh.bmedits.annot FAILED${BLUE}\n"
continue
fi
else
>&3 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${SUBJECTS_DIR}/${s}/qc/rh.bmedits.annot${NC}\n"
fi
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${s}/qc/lh.bmedits.annot" ] ; then
if "${FREESURFER_HOME}"/bin/mris_seg2annot --seg "${SUBJECTS_DIR}/${s}/surf/lh.bmerase.mgh" \
--s "${s}" --ctab-auto --h lh --surf white \
--o "${SUBJECTS_DIR}/${s}/qc/lh.bmedits.annot" >&3 2>&4
then
>&4 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mris_seg2annot --seg ${SUBJECTS_DIR}/${s}/surf/lh.bmerase.mgh --s ${s} --ctab-auto --h lh --surf white --o ${SUBJECTS_DIR}/${s}/qc/lh.bmedits.annot${BLUE}\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/mris_seg2annot --seg ${SUBJECTS_DIR}/${s}/surf/lh.bmerase.mgh --s ${s} --ctab-auto --h lh --surf white --o ${SUBJECTS_DIR}/${s}/qc/lh.bmedits.annot FAILED${BLUE}\n"
continue
fi
else
>&3 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${GREY} ${SUBJECTS_DIR}/${s}/qc/lh.bmedits.annot${NC}\n"
fi
# print out stats
bmerase=$(awk '{print $1}' < "${SUBJECTS_DIR}/${s}/stats/bm.erase.dat") && wmerase=$(awk '{print $1}' < "${SUBJECTS_DIR}/${s}/stats/wm.erase.dat") && wmfill=$(awk '{print $1}' < "${SUBJECTS_DIR}/${s}/stats/wm.fill.dat")
>&3 printf "\n${GREY}✏️ Edit Summary Stats: %s ${NC}\n\t# Erased voxels in brainmask: %d\n" "${s}" "${bmerase}"
>&3 printf "\t# Erased voxels in white matter mask: %d\n" "${wmerase}"
>&3 printf "\t# Filled voxels in white matter mask: %d\n" "${wmfill}"
((counter++))
done
return 0
}
export -f surfergems_subject_edits
####################################################################################################################
### DEFINE FUNCTION
# project summary of edits to average space
####################################################################################################################
## TODO check for existence of files before trying to run group summary compilation
function surfergems_group_edits_getsubjectedits(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_group_edits_getsubjectedits $@ (${SECONDS}s elapsed)"
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh" ]
then
# apply transform
if "${FREESURFER_HOME}"/bin/mri_vol2vol \
--mov "${SUBJECTS_DIR}/${1}/qc/bm.erase.mgh" \
--o "${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh" \
--reg "${SUBJECTS_DIR}/${1}/mri/transforms/registration-to-${AVERAGENAME}.dat" \
--targ "${SUBJECTS_DIR}/${AVERAGENAME}/mri/brainmask.mgz"
then
>&1 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY}${FREESURFER_HOME}/bin/mri_vol2vol --mov ${SUBJECTS_DIR}/${1}/qc/bm.erase.mgh --o ${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh --reg ${SUBJECTS_DIR}/${1}/mri/transforms/registration-to-${AVERAGENAME}.dat --targ ${SUBJECTS_DIR}/${AVERAGENAME}/mri/brainmask.mgz ${BLUE}\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY}${FREESURFER_HOME}/bin/mri_vol2vol --mov ${SUBJECTS_DIR}/${1}/qc/bm.erase.mgh --o ${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh --reg ${SUBJECTS_DIR}/${1}/mri/transforms/registration-to-${AVERAGENAME}.dat --targ ${SUBJECTS_DIR}/${AVERAGENAME}/mri/brainmask.mgz ${BLUE}\n"
fi
# binarize transformed edits
if "${FREESURFER_HOME}"/bin/mri_binarize \
--min 1 \
--i "${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh" \
--o "${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh"
then
>&1 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY}${FREESURFER_HOME}/bin/mri_binarize --min 1 --i ${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh ${BLUE} --o ${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY}${FREESURFER_HOME}/bin/mri_binarize --min 1 --i ${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh ${BLUE} --o ${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh\n"
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} ${GREY}${SUBJECTS_DIR}/${1}/qc/bm.erase.${AVERAGENAME}-space.mgh${NC}\n"
fi
}
export -f surfergems_group_edits_getsubjectedits
####################################################################################################################
### DEFINE FUNCTION
# project summary of edits to average space
####################################################################################################################
## TODO check for existence of files before trying to run group summary compilation
function surfergems_group_edits(){
>&2 echo -e " 🕷🔨 ${YELLOW}DEBUG${NC} surfergems_group_edits $@ (${SECONDS}s elapsed)"
local subjects='' && subjects="$(surfergems_check_input_subjects "$@")"
# compute average and register subjects to average
surfergems_makeavg >&4
>&4 printf "\r${YELLOW}❍ applying transform on edits made to each subject${NC}\r"
parallel -k --link --bar surfergems_group_edits_getsubjectedits {} \
::: "${subjects}" \
# compute sum across subjects
local files=($(find "${SUBJECTS_DIR}"/ -name "bm.erase.${AVERAGENAME}-space.mgh"))
if [ ! "${files}" ]
then
>&2 echo -e "\r\r${BRED}ERROR: cannot find bm.erase.${AVERAGENAME}-space.mgh in ${SUBJECTS_DIR}${NC}"
return 1
fi
[ ${AVERAGENAME} ] && [ ! -d "${SUBJECTS_DIR}/${AVERAGENAME}/qc" ] && mkdir -vp "${SUBJECTS_DIR}/${AVERAGENAME}/qc" >&4
## TODO - figure out weird bug where summation does not work with a '.sum' in filename instead of '-sum'
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh" ]
then
if "${FREESURFER_HOME}"/bin/mri_concat \
"${files[@]}" \
--sum --o "${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh" >&4
then
>&4 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mri_concat ${files[@]} --sum --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/mri_concat ${files[@]} --sum --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh\n"
return 1
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} ${GREY}${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh${NC}\n"
fi
# create probability map of edits
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh" ]
then
if "${FREESURFER_HOME}"/bin/fscalc "${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh" \
div ${#files[@]} --o "${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh" >&4
then
>&4 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/fscalc ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh div ${#files[@]} --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY}$ {FREESURFER_HOME}/bin/fscalc ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-sum.mgh div ${#files[@]} --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh\n"
return 1
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} ${GREY}${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh${NC}\n"
fi
# convert to rh surface
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh" ]
then
if "${FREESURFER_HOME}"/bin/mri_vol2surf --src "${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh" \
--o "${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh" \
--interp nearest --projfrac-max 0 5 .2 --fwhm 2.5 \
--regheader average --hemi rh >&4
then
>&4 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mri_vol2surf --src ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh --interp nearest --projfrac-max 0 5 .2 --fwhm 2.5 --regheader average --hemi rh\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/mri_vol2surf --src ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh --interp nearest --projfrac-max 0 5 .2 --fwhm 2.5 --regheader average --hemi rh\n"
return 1
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} ${GREY}${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh${NC}\n"
fi
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.gii" ]
then
if "${FREESURFER_HOME}"/bin/mris_convert -c "${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh" \
"${SUBJECTS_DIR}/${AVERAGENAME}/surf/rh.white" \
"${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.gii" >&4
then
>&4 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mris_convert -c ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh ${SUBJECTS_DIR}/${AVERAGENAME}/surf/rh.white ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.gii\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/mris_convert -c ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh ${SUBJECTS_DIR}/${AVERAGENAME}/surf/rh.white ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.gii\n"
return 1
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} ${GREY}${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.gii${NC}\n"
fi
# convert lh to surface
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedits-brainmask.mgh" ]
then
if "${FREESURFER_HOME}"/bin/mri_vol2surf --src "${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh" \
--o "${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.mgh" \
--interp nearest --projfrac-max 0 5 .2 --fwhm 2.5 \
--regheader average --hemi lh >&4
then
>&4 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mri_vol2surf --src ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh --interp nearest --projfrac-max 0 5 .2 --fwhm 2.5 --regheader average --hemi lh\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/mri_vol2surf --src ${SUBJECTS_DIR}/${AVERAGENAME}/qc/bm.erase-prob.mgh --o ${SUBJECTS_DIR}/${AVERAGENAME}/qc/rh.pedit-brainmask.mgh --interp nearest --projfrac-max 0 5 .2 --fwhm 2.5 --regheader average --hemi lh\n"
return 1
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} ${GREY}${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.mgh${NC}\n"
fi
# convert to gifti
if [ "${OVERWRITE}" ] || [ ! -f "${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.gii" ]
then
if ${FREESURFER_HOME}/bin/mris_convert -c "${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.mgh" \
"${SUBJECTS_DIR}/${AVERAGENAME}/surf/lh.white" \
"${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.gii" >&4
then
>&1 printf "\r${GREEN}◀︎|⁃‣SUCCESS${GREY} ${FREESURFER_HOME}/bin/mris_convert -c ${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.mgh ${SUBJECTS_DIR}/${AVERAGENAME}/surf/lh.white ${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.gii\n"
else
>&2 printf "\r${BRED}◀︎|⁃‣ERROR${GREY} ${FREESURFER_HOME}/bin/mris_convert -c ${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.mgh ${SUBJECTS_DIR}/${AVERAGENAME}/surf/lh.white ${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.gii\n"
return 1
fi
else
>&1 printf "${BLUE}◀︎|⁃‣NO OVERWRITE - FILE EXISTS${NC} ${GREY}${SUBJECTS_DIR}/${AVERAGENAME}/qc/lh.pedit-brainmask.gii${NC}\n"
fi
}
export -f surfergems_group_edits
####################################################################################################################
### DEFINE FUNCTION
# register subject to average