-
Notifications
You must be signed in to change notification settings - Fork 8
/
estimate_pangenome_phylogenies.sh
executable file
·1359 lines (1112 loc) · 51.4 KB
/
estimate_pangenome_phylogenies.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
#!/usr/bin/env bash
#-------------------------------------------------------------------------------------------------------
#: PROGRAM: estimate_pangenome_phylogenies.sh
#: AUTHOR: Pablo Vinuesa, Center for Genomic Sciences, UNAM, Mexico
#: http://www.ccg.unam.mx/~vinuesa/
#
#: PROJECT START: October 28th, 2017
#
#: AIM: run PHYLIP's seqboot and pars methods in parallel for a bootstrap analysis
# of a pangenome matrix generated by the comparte_clusters.pl script
# of the get_homologues suite.
#: OUTPUT: a pars phylogeny with bootstrap values mapped on it
#: COPYRIGHT (c) 2017, Pablo Vinuesa. Released under the GNU-license.
# http://www.gnu.org/copyleft/gpl.html
#### DEPENDENCIES
# Assumes that the following binaries and scripts are all in $PATH, checked by check_dependencies()
#
# 1) Binaries from the PHYLIP package:
# seqboot pars consense
# 2) Modified PHYLIP binaries:
# consense # <<< NOT STRICTLY REQUIRED!
# REF:
# Shimada MK, Nishida T. A modification of the PHYLIP program: A solution for
# the redundant cluster problem, and an implementation of an automatic
# bootstrapping on trees inferred from original data. Mol Phylogenet Evol. 2017
# Apr;109:409-414. doi: 10.1016/j.ympev.2017.02.012. PubMed PMID:28232198.
# https://github.com/ShimadaMK/PHYLIP_enhance/
# 3) uses nw_reroot and nw_support from the newick_utils package
# to remap the bootstrap proportions on the orignal tree
# REF:
# Thomas Junier and Evgeny M. Zdobnov (2010). Bioinformatics 26:1669-1670
# http://bioinformatics.oxfordjournals.org/content/26/13/1669.full
# doi:10.1093/bioinformatics/btq243
# http://cegg.unige.ch/newick_utils
#: TODO
#-------------------------------------------------------------------------------------------------------
# Set Bash strict mode
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
#set -euo pipefail
#set -e # NOTE: fails in first call to "run_parallel_cmmds.pl faaed 'add_nos2fasta_header.pl $file"; L973
set -u
set -o pipefail
progname=${0##*/}
VERSION='v1.2.5_2022-12-14' # pass USER as 1st argument to get_script_PID, and progname as 2cnd arg
# localize user and prog in get_script_PID to avoid unbound variable USER/user in function call
# v1.2.4_2022-11-20 added check_bash_version >= 4.3
# v1.2.4_18Nov22 mostly shellcheck compliant; enabled bash strict mode; major syntax revision and update to modern Bash;
# added IQT_threads=4 && updated iqtree2 calls with -T $IQT_threads instead of -T AUTO, which slows down searches
# v1.2.2_15Nov22 updated iqtree calls to match current IQTreee2 syntax
#'v1.2.1_04Oct21' #v1.2.1_04Oct21; preppended missing "${bindir}" to first pars call
# v1.2_16Sep21 added function check_libnw() for lib /usr/local/lib/libnw.so.0.0.0; -R 3 only warns if could not write full_pars_tree_rooted_withBoot.ph
# v.1.2_10Jan20; added option -S <abayes|UFBoot|both> default: $IQT_support
#'1.0.5_28Mar18' # check_scripts_in_path() checks wether USER is regular or root
#'1.0.4_17Feb18' # prepended $bindir/ to a nw_reroot call that was missing it
# 1.0.3_8Feb18 added -v; check_scripts_in_path(); check_dependencies with verbosity; activated set_pipeline_environment; Thanks Felipe Lira!
# fix in set_pipeline_environment: changed to readlink -n when "$OSTYPE" == "darwin"
# v1.0_23Jan18 added code to run IQ-TREE on PGM, including alrt/UFBoot and model selection
# v0.2_2Nov17; added runmodes and code to run parallel pars searches with different
# random seeds; Selects best tree; improved/fixed basic documentation
#'0.1_27Oct17'; first fully working version
# GLOBALS
#DATEFORMAT_SHORT="%d%b%y" # 16Oct13
#TIMESTAMP_SHORT=$(date +${DATEFORMAT_SHORT})
date_F=$(date +%F |sed 's/-/_/g')- # 2013_10_20
date_T=$(date +%T |sed 's/:/./g') # 23.28.22 (hr.min.secs)
start_time="$date_F$date_T"
sleeptime=1
topdir=$(pwd)
declare -A pids
min_bash_vers=4.3 # required for:
# 1. printf '%(%F)T' '-1' in print_start_time; and
# 2. passing an array or hash by name reference to a bash function (since version 4.3+),
# by setting the -n attribute
# see https://stackoverflow.com/questions/16461656/how-to-pass-array-as-an-argument-to-a-function-in-bash
# initialize variables
runmode=''
criterion=ML
discrete_model=BIN
input_fasta=''
num_IQT_runs=1
IQT_support=both #<abayes|UFBoot|both>
IQT_threads=2
input_phylip=''
n_cores=50
boot=2
n_jumbles=20
t_jumbles=1
DEBUG=0
sequential=1
rnd_no=33
outgroup=1
phylo=''
pars_tree=''
check_version=0
#---------------------------------------------------------------------------------#
#>>>>>>>>>>>>>>>>>>>>>>>>>>>> FUNCTION DEFINITIONS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<#
#---------------------------------------------------------------------------------#
function check_bash_version()
{
bash_vers=$(bash --version | head -1 | awk '{print $4}' | sed 's/(.*//' | cut -d. -f1,2)
awk -v bv="$bash_vers" -v mb="$min_bash_vers" 'BEGIN { if (bv < mb) print "FATAL: you are running acient bash v"bv, "and version >=", mb, "is required"; exit 1}'
}
#-----------------------------------------------------------------------------------------
function msg()
{
#[ "$DEBUG" -eq 1 ] && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
msg=$1
mtype=$2
col=$3
NC='\033[0m'
case $col in
RED) col='\033[0;31m';;
LRED) col='\033[1;31m';;
GREEN) col='\033[0;32m';;
YELLOW) col='\033[1;33m';;
BLUE) col='\033[0;34m';;
LBLUE) col='\033[1;34m';;
CYAN) col='\033[0;36m';;
NC) col='\033[0m';;
esac
case $mtype in
HELP) printf "\n${col}%s${NC}\n\n" "$msg" >&2;;
ERROR) printf "\n${col}%s${NC}\n\n" "$msg" >&2;;
WARNING) printf "${col}%s${NC}\n" "$msg" ;;
PROGR) printf "${col}%s${NC}\n" "$msg" ;;
DEBUG) printf "${col}%s${NC}\n" "$msg" ;;
VERBOSE) printf "${col}%s${NC}\n" "$msg" ;;
esac
#[ "$DEBUG" -eq 1 ] && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#-----------------------------------------------------------------------------------------
function set_bindirs()
{
[ "$DEBUG" -eq 1 ] && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
# receives: $bindir $homebinpathflag
bindir=$1
# prepend $bindir to $PATH in any case, to ensure that the script runs with the distributed binaries in $bindir
export PATH="${bindir}:${PATH}"
#echo $setbindir_flag
[ "$DEBUG" -eq 1 ] && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#-----------------------------------------------------------------------------------------
function set_pipeline_environment()
{
local scriptdir distrodir bindir OS no_cores
if [[ "$OSTYPE" == "linux-gnu" ]]
then
scriptdir=$(readlink -f "${BASH_SOURCE[0]}")
distrodir=$(dirname "$scriptdir") #echo "scriptdir: $scriptdir|basedir:$distrodir|OSTYPE:$OSTYPE"
bindir="$distrodir/bin/linux"
OS='linux'
no_cores=$(awk '/^processor/{n+=1}END{print n}' /proc/cpuinfo)
elif [[ "$OSTYPE" == "darwin"* ]]
then
distrodir=$(cd "$scriptdir" || { msg "ERROR: cannot cd into $scriptdir" ERROR RED && exit 1 ; })
bindir="$distrodir/bin/macosx-intel"
OS='darwin'
no_cores=$(sysctl -n hw.ncpu)
fi
echo "$distrodir $bindir $OS $no_cores"
}
#----------------------------------------------------------------------------------------------#
function get_script_PID()
{
local prog proc_ID user
#(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
# returns the PID of the script, run by USER
user=$1
prog=${2%.*} # remove the script's .extension_name
#proc_ID=$(ps -eaf|grep "$prog"|grep -v grep|grep '-'|grep $USER|awk '{print $2}')
#proc_ID=$(ps aux|grep "$prog"|grep -v grep|grep '-'|grep "$USER" |awk '{print $2}')
proc_ID=$(pgrep -u "$user" "$prog")
echo "$proc_ID"
(( DEBUG > 0 )) && msg "$progname PID is: $proc_ID" DEBUG NC
#(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#-----------------------------------------------------------------------------------------
function print_start_time()
{
#echo -n "[$(date +%T)] "
printf '%(%T )T' '-1' # requires Bash >= 4.3
}
#----------------------------------------------------------------------------------
function wait_for_PIDs_to_finish
{
# This function receives a hash as argument
# https://www.linuxquestions.org/questions/programming-9/bash-passing-associative-arrays-as-arguments-4175474655/
# https://stackoverflow.com/questions/17557434/passing-associative-array-as-argument-with-bash
# https://www.gnu.org/software/bash/manual/bash.html#index-declare
# receives an associative array as argument, using the following call:
# wait_for_PIDs_to_finish "$(declare -p pids)"
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
local flag PID
eval "declare -A ref"=${1#*=}
flag=0
while [ "$flag" -eq 0 ]
do
for PID in "${!ref[@]}"
do
#echo "PID is $PID"
flag=1
if ps -ef | grep "${ref[$PID]}" | grep -v 'grep' &> /dev/null
then
flag=0
sleep "$sleeptime"
fi
done
done
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#--------------------------------------------- #
function check_scripts_in_path()
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
local perl_scripts prog distrodir not_in_path prog bin user
distrodir=$1
user=$2
not_in_path=0
homebinflag=0
homebinpathflag=0
(( DEBUG > 0 )) && msg "check_scripts_in_path() distrodir:$distrodir" DEBUG NC
perl_scripts=( run_parallel_cmmds.pl rename.pl add_labels2tree.pl )
# check if scripts are in path; if not, set flag
for prog in "${perl_scripts[@]}"
do
bin=$(type -P "$prog")
if [ -z "$bin" ]; then
echo
if [ "$user" == "root" ]
then
msg "# WARNING: script $prog is not in \$PATH!" WARNING LRED
msg " >>> Will generate a symlink from /usr/local/bin or add it to \$PATH" WARNING CYAN
not_in_path=1
else
msg "# WARNING: script $prog is not in \$PATH!" WARNING LRED
msg " >>> Will generate a symlink from $HOME/bin or add it to \$PATH" WARNING CYAN
not_in_path=1
fi
fi
done
# if flag $not_in_path -eq 1, then either generate symlinks into $HOME/bin (if in $PATH) or export $distrodir to PATH
if (( not_in_path == 1 ))
then
if [ "$user" == "root" ]
then
if [ ! -d /usr/local/bin ]
then
msg "Could not find a /usr/local/bin directory for $user ..." WARNING CYAN
msg " ... will update PATH=$distrodir:$PATH" WARNING CYAN
export PATH="${distrodir}:${PATH}" # prepend $ditrodir to $PATH
else
homebinflag=1
fi
# check if $HOME/bin is in $PATH
if echo "$PATH" | sed 's/:/\n/g' | grep "/usr/local/bin$" &> /dev/null
#if [ $? -eq 0 ]
then
homebinpathflag=1
msg "Found dir /usr/local/bin for $user in \$PATH ..." WARNING CYAN
msg " ... will generate symlinks in /usr/local/bin to all scripts in $distrodir ..." WARNING CYAN
ln -s "$distrodir"/*.sh /usr/local/bin &> /dev/null
ln -s "$distrodir"/*.R /usr/local/bin &> /dev/null
ln -s "$distrodir"/*.pl /usr/local/bin &> /dev/null
else
msg " Found dir /usr/local/bin for $user, but it is NOT in \$PATH ..." WARNING CYAN
msg " ... updating PATH=$PATH:$distrodir" WARNING CYAN
export PATH="${distrodir}:${PATH}" # prepend $distrodir to $PATH
fi
else
if [ ! -d "$HOME"/bin ]
then
msg "Could not find a $HOME/bin directory for $user ..." WARNING CYAN
msg " ... will update PATH=$distrodir:$PATH" WARNING CYAN
export PATH="${distrodir}:${PATH}" # prepend $ditrodir to $PATH
else
homebinflag=1
fi
# check if $HOME/bin is in $PATH
if echo "$PATH" | sed 's/:/\n/g'| grep "$HOME/bin$" &> /dev/null
#if [ $? -eq 0 ]
then
homebinpathflag=1
msg "Found dir $HOME/bin for $user in \$PATH ..." WARNING CYAN
msg " ... will generate symlinks in $HOME/bin to all scripts in $distrodir ..." WARNING CYAN
ln -s "$distrodir"/*.sh "$HOME"/bin &> /dev/null
ln -s "$distrodir"/*.R "$HOME"/bin &> /dev/null
ln -s "$distrodir"/*.pl "$HOME"/bin &> /dev/null
#ln -s $distrodir/rename.pl $HOME/bin &> /dev/null
else
msg " Found dir $HOME/bin for $user, but it is NOT in \$PATH ..." WARNING CYAN
msg " ... updating PATH=$PATH:$distrodir" WARNING CYAN
export PATH="${distrodir}:${PATH}" # prepend $distrodir to $PATH
fi
fi
fi
(( DEBUG > 0 )) && echo "$homebinflag $homebinpathflag"
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#-----------------------------------------------------------------------------------------
function check_libnw()
{
if [ ! -s /usr/local/lib/libnw.so ]
then
cat <<NWUTIL
WARNING: lib libnw.so was not found in /usr/local/lib!
If you you want to use the parsimony module, then you will need to do the following:
1. cp /path/to/get_phylomarkers/lib/libnw.so /usr/local/lib
2. add the following line to your .bashrc or .bash_profile file in your home
export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:/usr/local/lib
3. open a new terminal or source the edited .bashrc or .bash_profile
source ~/.bashrc or source ~/.bash_profile
4. Reconfigure libs:
sudo ldconfig
NWUTIL
fi
}
#-----------------------------------------------------------------------------------------
function check_dependencies
{
# check if scripts are in path; if not, set flag
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
local programname bin
#local VERBOSITY=$1
#local GREEN='\033[0;32m'
local NC='\033[0m'
# check that the following PHYLIP binaries and nw_* tools are in $PATH; die if not
for programname in iqtree seqboot pars consense nw_reroot nw_support add_labels2tree.pl
do
bin=$(type -P "$programname")
if [ -z "$bin" ]; then
echo
echo "# ERROR: $programname not in place!"
echo "# ... you will need to install \"$programname\" first or include it in \$PATH"
echo "# ... exiting"
exit 1
#else
# [ "$VERBOSITY" -eq 1 ] && printf "${GREEN}%s${NC}\n" "# $programname OK!"
fi
done
echo
echo '# Run check_dependencies() ... looks good;) all required binaries and scripts are in place.'
echo
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#---------------------------------------------------------------------------------#
function check_output()
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
local outfile pPID
outfile=$1
pPID=$2
if [ -s "$outfile" ]
then
msg " >>> wrote file $outfile ..." PROGR GREEN
return 0
else
echo
msg " >>> ERROR! The expected output file $outfile was not produced, will exit now!" ERROR RED
echo
exit 9
[ "$DEBUG" -eq 1 ] && msg "check_output running: kill -9 $pPID" DEBUG NC
kill -9 "$pPID"
fi
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#----------------------------------------------------------------------------------
function run_IQT_discrete
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
local input_fasta discrete_model nrep_IQT_searches IQT_support wkdir lmsg
input_fasta=$1
discrete_model=$2
nrep_IQT_searches=$3
IQT_support=$4
wkdir=''
lmsg=''
if [ "$nrep_IQT_searches" -eq 1 ]; then
wkdir=$(pwd)
(( DEBUG > 0 )) && msg "working in $wkdir" DEBUG NC
if [ "$IQT_support" == "both" ]
then
lmsg=" # running iqtree -s $input_fasta -st $discrete_model -m MFP -T $IQT_threads -abayes -B 1000 &> /dev/null"
print_start_time && msg "$lmsg" PROGR BLUE
"${bindir}"/iqtree -s "$input_fasta" -st "$discrete_model" -m MFP -T "$IQT_threads" -abayes -B 1000 &> /dev/null
best_model=$(grep '^Best-fit model' "${input_fasta}".log | cut -d' ' -f 3)
msg " >>> Best-fit model: ${best_model} ..." PROGR GREEN
treefile=PGM_IQT_${best_model}_${IQT_support}.treefile
mv pangenome_matrix_t0.fastaed.treefile "$treefile"
check_output "$treefile" "$pPID"
msg " ... found in $wkdir" PROGR GREEN
msg " ... done!" PROGR GREEN
# cleanup
rm ./*.ckp.gz
elif [ "$IQT_support" == "abayes" ]
then
lmsg=" # running iqtree -s $input_fasta -st $discrete_model -m MFP -T $IQT_threads -abayes &> /dev/null"
print_start_time && msg "$lmsg" PROGR BLUE
"${bindir}"/iqtree -s "$input_fasta" -st "$discrete_model" -m MFP -T "$IQT_threads" -abayes &> /dev/null
best_model=$(grep '^Best-fit model' "${input_fasta}".log | cut -d' ' -f 3)
msg " >>> Best-fit model: ${best_model} ..." PROGR GREEN
treefile=PGM_IQT_${best_model}_${IQT_support}.treefile
mv pangenome_matrix_t0.fastaed.treefile "$treefile"
check_output "$treefile" "$pPID"
msg " ... found in $wkdir" PROGR GREEN
msg " ... done!" PROGR GREEN
# cleanup
rm ./*.ckp.gz
else
lmsg=" # running iqtree -s $input_fasta -st $discrete_model -m MFP -T $IQT_threads -B 1000 &> /dev/null"
print_start_time && msg "$lmsg" PROGR BLUE
"${bindir}"/iqtree -s "$input_fasta" -st "$discrete_model" -m MFP -T "$IQT_threads" -B 1000 &> /dev/null
best_model=$(grep '^Best-fit model' "${input_fasta}".log | cut -d' ' -f 3)
msg " >>> Best-fit model: ${best_model} ..." PROGR GREEN
treefile=PGM_IQT_${best_model}_${IQT_support}.treefile
mv pangenome_matrix_t0.fastaed.treefile "$treefile"
check_output "$treefile" "$pPID"
msg " ... found in $wkdir" PROGR GREEN
msg " ... done!" PROGR GREEN
# cleanup
rm ./*.ckp.gz
fi
else
wkdir=$(pwd)
[ "$DEBUG" -eq 1 ] && msg "working in $wkdir" DEBUG NC
# 1. first run without testing branch supports, to find the best-fitting model
print_start_time && msg " >>> running iqtree -s $input_fasta -st $discrete_model to find best model" PROGR GREEN
"${bindir}"/iqtree -s "$input_fasta" -st "$discrete_model" -m MF -T $IQT_threads &> /dev/null
best_model=$(grep '^Best-fit model' "${input_fasta}".log | cut -d' ' -f 3)
msg " >>> Best-fit model: ${best_model} ..." PROGR GREEN
# 2. generate multirun_dir and launch searches from within
multirun_dir="iqtree_${nrep_IQT_searches}_runs"
mkdir "$multirun_dir" && cd "$multirun_dir" && ln -s ../"$input_fasta" .
msg " ... created and moved into dir $multirun_dir" PROGR LBLUE
wkdir=$(pwd)
if [ "$IQT_support" == "both" ]
then
lmsg="# Will sequentially launch $num_IQT_runs IQ-TREE searches on the supermatrix with best model ${best_model} -abayes -bb 1000!.
This will take a while ..."
print_start_time && msg "$lmsg" PROGR BLUE
# run nrep_IQT_searches IQ-TREE searches under the best-fit model found
for ((rep=1;rep<=nrep_IQT_searches;rep++))
do
lmsg="> iqtree -s $input_fasta -st $discrete_model -m $best_model -abayes -B 1000 -T $IQT_threads -pre abayes_UFBboot_run${rep} &> /dev/null"
print_start_time && msg "$lmsg" PROGR LBLUE
iqtree -s "$input_fasta" -st "$discrete_model" -m "$best_model" -abayes -B 1000 -T "$IQT_threads" -pre "abayes_UFBboot_run${rep}" &> /dev/null
done
grep '^BEST SCORE' ./*log | sed 's#./##' | sort -nrk5 > sorted_lnL_scores_IQ-TREE_searches.out
check_output sorted_lnL_scores_IQ-TREE_searches.out "$pPID"
best_search=$(head -1 sorted_lnL_scores_IQ-TREE_searches.out)
best_search_base_name=$(head -1 sorted_lnL_scores_IQ-TREE_searches.out | cut -d\. -f 1)
msg " >>> Best IQ-TREE run was: $best_search ..." PROGR GREEN
best_tree_file=best_PGM_IQT_${best_search_base_name}_${best_model}.treefile
mv "${best_search_base_name}".treefile "$best_tree_file"
check_output "$best_tree_file" "$pPID"
msg " ... found in $wkdir" PROGR GREEN
msg " ... done!" PROGR GREEN
# cleanup
rm ./*.ckp.gz
elif [ "$IQT_support" == "abayes" ]
then
lmsg="# Will sequentially launch $num_IQT_runs IQ-TREE searches on the supermatrix with best model ${best_model} -abayes!.
This will take a while ..."
print_start_time && msg "$lmsg" PROGR BLUE
# run nrep_IQT_searches IQ-TREE searches under the best-fit model found
for ((rep=1;rep<=nrep_IQT_searches;rep++))
do
lmsg="> iqtree -s $input_fasta -st $discrete_model -m $best_model -abayes -T $IQT_threads -pre abayes_run${rep} &> /dev/null"
print_start_time && msg "$lmsg" PROGR LBLUE
iqtree -s "$input_fasta" -st "$discrete_model" -m "$best_model" -abayes -T "$IQT_threads" -pre "abayes_run${rep}" &> /dev/null
done
grep '^BEST SCORE' ./*log | sed 's#./##' | sort -nrk5 > sorted_lnL_scores_IQ-TREE_searches.out
check_output sorted_lnL_scores_IQ-TREE_searches.out "$pPID"
best_search=$(head -1 sorted_lnL_scores_IQ-TREE_searches.out)
best_search_base_name=$(head -1 sorted_lnL_scores_IQ-TREE_searches.out | cut -d\. -f 1)
msg " >>> Best IQ-TREE run was: $best_search ..." PROGR GREEN
best_tree_file=best_PGM_IQT_${best_search_base_name}_${best_model}.treefile
mv "${best_search_base_name}".treefile "$best_tree_file"
check_output "$best_tree_file" "$pPID"
msg " ... found in $wkdir" PROGR GREEN
msg " ... done!" PROGR GREEN
# cleanup
rm ./*.ckp.gz
else
lmsg="# Will sequentially launch $num_IQT_runs IQ-TREE searches on the supermatrix with best model ${best_model} -UFBoot!.
This will take a while ..."
print_start_time && msg "$lmsg" PROGR BLUE
# run nrep_IQT_searches IQ-TREE searches under the best-fit model found
for ((rep=1;rep<=nrep_IQT_searches;rep++))
do
lmsg="> iqtree -s $input_fasta -st $discrete_model -m $best_model -B 1000 -T $IQT_threads -pre UFBoot_run${rep} &> /dev/null"
print_start_time && msg "$lmsg" PROGR LBLUE
iqtree -s "$input_fasta" -st "$discrete_model" -m "$best_model" -B 1000 -T "$IQT_threads" -pre "UFBoot_run${rep}" &> /dev/null
done
grep '^BEST SCORE' ./*log | sed 's#./##' | sort -nrk5 > sorted_lnL_scores_IQ-TREE_searches.out
check_output sorted_lnL_scores_IQ-TREE_searches.out "$pPID"
best_search=$(head -1 sorted_lnL_scores_IQ-TREE_searches.out)
best_search_base_name=$(head -1 sorted_lnL_scores_IQ-TREE_searches.out | cut -d\. -f 1)
msg " >>> Best IQ-TREE run was: $best_search ..." PROGR GREEN
best_tree_file=best_PGM_IQT_${best_search_base_name}_${best_model}.treefile
mv "${best_search_base_name}".treefile "$best_tree_file"
check_output "$best_tree_file" "$pPID"
msg " ... found in $wkdir" PROGR GREEN
msg " ... done!" PROGR GREEN
# cleanup
rm ./*.ckp.gz
fi
fi
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#------------------------------------------------------------------------------------#
# >>> Functions to write the command files to pass parameters to PHYLIP programs <<< #
#------------------------------------------------------------------------------------#
function write_pars_full_search_cmd
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
local n_jumbles sequential i rseed
n_jumbles=$1
sequential=$2
i=$3
if [ -z "$i" ]
then
rseed=$rnd_no
else
# compute a new rdm number for each new iteration of the loop
# to maximize randomness in bootstrapping.
rseed=$((8*i+1))
fi
# need to remove previous param file, since we are concatenating to it
[ -s pars.params ] && rm pars.params
touch pars.params
[ "$sequential" -eq 0 ] && echo -ne "J\n$rseed\n$n_jumbles\nY\n" > pars.params
[ "$sequential" -gt 0 ] && echo -ne "J\n$rseed\n$n_jumbles\nI\nY\n" > pars.params
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#----------------------------------------------------------------------------------
function write_boot_pars_params
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
#get the input runmodes, models, bootstrap no. ...
local boot sequential n_jumbles i rdm
boot=$1
sequential=$2
n_jumbles=$3
i=$4
# compute a new rdm number for each new iteration of the loop
# to maximize randomness in bootstrapping.
rdm=$((4*i+1))
# need to remove previous param file, since we are concatenating to it
[ -s pars.params ] && rm pars.params
touch pars.params
[ "$sequential" -eq 0 ] && echo -ne "M\nD\n$boot\n$rdm\n$t_jumbles\nY\n" > pars.params
[ "$sequential" -gt 0 ] && echo -ne "M\nD\n$boot\n$rdm\n$t_jumbles\nI\nY\n" > pars.params
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#----------------------------------------------------------------------------------
function write_seqboot_params
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
#get the input runmodes, models and bootstrap no.
local boot i rdm
boot=$1
i=$2
# compute a new rdm number for each new iteration of the loop
# to maximize randomness in bootstrapping.
rdm=$((4*i+1))
# need to remove previous param file, since we are concatenating to it
[ -s seqboot.params ] && rm seqboot.params
touch seqboot.params
# Write Seqboot params
(( boot > 0 )) && echo -ne "D\nR\n$boot\nY\n$rdm\n" > seqboot.params
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#----------------------------------------------------------------------------------
function write_consense_params
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
# very difficult ;)
[ -s consense.params ] && rm consense.params
local outgroup
outgroup=$1
(( outgroup > 1 )) && echo -ne "O\n$outgroup\n" >> consense.params
echo -ne "Y\n" >> consense.params
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#----------------------------------------------------------------------------------
function print_warning
{
local msg
msg=$1
echo "WARNING: $msg"
}
#----------------------------------------------------------------------------------
# don't leave litter behind ... remove intermediate input/output files
function cleanup_dir
{
(( DEBUG > 0 )) && msg " => working in ${FUNCNAME[0]} ..." DEBUG NC
[ -s infile ] && rm infile
[ -s outfile ] && rm outfile
for file in ./*.params
do
[ -s "$file" ] && rm "$file"
done
(( DEBUG > 0 )) && msg " <= exiting ${FUNCNAME[0]} ..." DEBUG NC
}
#----------------------------------------------------------------------------------
# <<<<<<<<<<< END PHYLIP FUNCTIONS >>>>>>>>>>> #
#----------------------------------------------#
function print_help
{
cat<<EOF
$progname v.$VERSION [OPTIONS]
-h prints this help message
REQUIRED
-f <input_fasta_pangenome_matrix> [for IQ-TREE]
-i <input_phylip_pangenome_matrix> [for pars]
[NOTE: script should be called from with the folder containing the required input matrix]
REQUIRED only if -c PARS
-R <int>
1 launch single pars run [ not particularly useful ]
2 launch n pars runs on n cores [ multiple independen searches, no bootstrapping ]
3 automatic single pars run + bootstrap analysis [ recommended ]
4 map bootstrap props on selected -T tree_num found in -R 2 runs
-T <string> pars tree to map the boot-props on (req. for -R 4)
OPTIONAL
-c <string> optimalit criterion: [ML|PARS] [default: $criterion]
OPTIONAL to control IQ-TREE ML searches (-c ML) [default: $discrete_model]
-m <BIN|MORPH> discrete model category
-r <integer> number of independent iqtree runs [default: $num_IQT_runs]
in the range 1:100
-I <integer> number of threads for iqtree2 run [default: $IQT_threads]
-S <string> [<abayes|UFBoot|both>] [default: $IQT_support]
OPTIONAL to control parsimony searches when -c PARS:
-n <number of compute cores to use to launch independent
pars runs, each with a different seed [default: $n_cores]
-b <integer> No. of pars runs or
bootstrap pseudoreplicates [default: $boot]
per compute node
-j <integer> number of tax jumbles [default: $n_jumbles]
for full pars search
-t <integer> number of tax jumbles [default: $t_jumbles]
for pars search on boot replicates
-s <flag> sequential matrix [default: $sequential]
OTHER optional
-D <flag> print debugging messages
EXAMPLES:
1) Search for the best maximum likelihood tree using 10 independent IQ-TREE runs
$progname -f pangenome_matrix_t0.fasta -r 10 -S UFBoot -I 4
2) PARSIMONY searches with pars; NOTE: VERY SLOW!
nohup $progname -c PARS -R 1 -i pangenome_matrix_t0.phylip -j 50 &> /dev/null &
nohup $progname -c PARS -R 2 -i pangenome_matrix_t0.phylip -n 50 -j 100 &> /dev/null &
nohup $progname -c PARS -R 3 -i pangenome_matrix_t0.phylip -n 64 -b 64 -j 50 -t 1 &> /dev/null &
$progname -c PARS -R 4 -T best_pars_tree_name (execute within boot_pars/ after -R 2 and -R 3 runs
have finished answering n to: should dir boot_pars be removed y|n? n)
AIM: Estimate pan-genome phylogenies from the pangenome_matrix files computed by compare_clusters.pl
of the GET_HOMOLOGUES suite. By default the script will estimate a ML phylogeny using the best-fit
binary model. This is large the recommended use of the script, as it is MUCH FASTER.
If desired the optimality criterion can be changed to parsimony (-c PARS) and the script will
run PHYLIPs seqboot and pars programs in parallel on the pangenome_matrix_t0.phylip file to:
1. search for the best pars tree using multiple seed trees (-R 2) or from a single one (-R 1, -R 3)
2. bootstap the pan-genome phylogeny and map the boot-props to the pars phylogeny
[automatically -R 3 or on a user-specified best phylogeny -R 4 -T (best)_tree_file]
NOTES ON PARS PARALLELIZATION:
1. The script runs as many subshells as n_cores indicated by the user
to parallelize the process, running n_boot replicates from each of the processes/subshells.
Therefore, to run 500 bootstrap replicates on 50 nodes, use -n 50 -b 10
2. To make a thorough tree search (-R 2), define -n cores, which will launch -n processes/subshells,
each with a different random seed number, each searching from -j jumbled seed trees.
To add boostrap support values to the best tree found in the search, you need first
to launch a -R 3 run. Then, from within the boot_pars dir, call -R 4 as shown above
$progname is part of the GET_PHYLOMARKERS package
released under the GNU General Public License http://www.gnu.org/copyleft/gpl.html
and available at https://github.com/vinuesa/get_phylomarkers
EOF
exit 1
}
#-------------------------------------------------------------------------------------------------#
#---------------------------------------- GET OPTIONS --------------------------------------------#
#-------------------------------------------------------------------------------------------------#
# GETOPTS
while getopts ':b:c:j:m:n:f:i:I:r:R:S:t:T:hsDv' OPTIONS; do
case $OPTIONS in
f) input_fasta=$OPTARG
;;
i) input_phylip=$OPTARG
;;
I) IQT_threads=$OPTARG
;;
b) boot=$OPTARG
;;
c) criterion=$OPTARG
;;
m) discrete_model=$OPTARG
;;
n) n_cores=$OPTARG
;;
h) print_help
;;
j) n_jumbles=$OPTARG
;;
r) num_IQT_runs=$OPTARG
;;
s) sequential=1
;;
S) IQT_support=$OPTARG
;;
t) t_jumbles=$OPTARG
;;
v) echo "$progname v$VERSION" && check_version=1 && check_dependencies 1 && exit 0
;;
D) DEBUG=1
;;
T) pars_tree=$OPTARG
;;
R) runmode=$OPTARG
;;
:) printf "argument missing from -%s option\n" "$OPTARG"
print_help
exit 2
;;
\?) echo "need the following args: "
print_help
exit 3
;;
esac >&2
done
shift $((OPTIND - 1))
#-------------------------------------------------------#
# >>>BLOCK 0.1 SET THE ENVIRONMENT FOR THE PIPELINE <<< #
#-------------------------------------------------------#
# 0. Set the distribution base directory and OS-specific (linux|darwin) bindirs
env_vars=$(set_pipeline_environment) # returns: $distrodir $bindir $OS $no_proc
[ "$DEBUG" -eq 1 ] && echo "env_vars:$env_vars"
distrodir=$(echo "$env_vars" | awk '{print $1}')
bindir=$(echo "$env_vars" | awk '{print $2}')
OS=$(echo "$env_vars" | awk '{print $3}')
no_proc=$(echo "$env_vars" | awk '{print $4}')
pPID=$(get_script_PID "$USER" "$progname")
#-----------------------------------------------------------------------------------------
# 0.1 Determine if pipeline scripts are in $PATH;
# if not, add symlinks from ~/bin, if available
check_scripts_in_path "$distrodir" "$USER"
# 0.2 Determine the bindir and add prepend it to PATH and export
set_bindirs "$bindir"
# 0.3 append the $distrodir/lib/R to R_LIBS and export
export R_LIBS="${distrodir}/lib/R"
# 0.4 append the $distrodir/lib/perl to PERL5LIB and export
export PERL5LIB="${distrodir}/lib/perl:${distrodir}/lib/perl/bioperl-1.5.2_102"
[ "$DEBUG" -eq 1 ] && echo "distrodir:$distrodir|bindir:$bindir|OS:$OS|no_proc:$no_proc"
# make sure we're runnig a recently modern bash version >= min_bash_version
check_bash_version
#--------------------------------------#
# >>> BLOCK 0.2 CHECK USER OPTIONS <<< #
#--------------------------------------#
[ "$check_version" -eq 1 ] && exit 0
if [ "$criterion" == "ML" ]; then
[ -z "$input_fasta" ] && msg "# ERROR: no input fasta file defined!" ERROR RED && print_help && exit 1
[ "$discrete_model" != "BIN" ] && [ "$discrete_model" != "MORPH" ] && msg "# ERROR: discrete model has to be 'BIN|MORPH'" ERROR RED && print_help && exit 1
[ "$num_IQT_runs" -lt 1 ] || [ "$num_IQT_runs" -gt 100 ] && msg "# ERROR: the number of IQT runs should be in the 1:100 range" ERROR RED && print_help && exit 1
if [ "$IQT_support" != 'abayes' ] && [ "$IQT_support" != 'UFBoot' ] && [ "$IQT_support" != 'both' ]
then
msg "# ERROR: provide one of the following branch support value types for IQ-tree searches: abayes|UFBoot|both" ERROR RED && print_help && exit 1
fi
fi
if [ "$criterion" == "PARS" ]; then
if [ -z "$input_phylip" ] && [ "$runmode" -ne 4 ] # runmode 4 does not require the input phylip file
then
echo
msg "# ERROR: no input phylip file defined!" ERROR RED
print_help
fi
if [ -z "$runmode" ]
then
echo
msg "# ERROR: no runmode defined for parsimony-based analyses!" ERROR RED
print_help
fi
# First check that bootstrap value is an integer
re='^[0-9]+$'
if ! [[ "$boot" =~ $re ]]
then
echo
msg "# ERROR: $boot is not an integer; provide a value between 100 and 1000" ERROR RED
echo
print_help
fi
echo
msg "### $progname v.$VERSION run on $start_time with the following parameters:" PROGR YELLOW
msg "# topdir = $topdir | criterion:$criterion" PROGR YELLOW
fi
if [ "$criterion" == "ML" ]; then
msg "input_fasta: $input_fasta" PROGR YELLOW
msg "discrete_model: $discrete_model" PROGR YELLOW
msg "branch support type: $IQT_support" PROGR YELLOW
fi
if [ "$criterion" == "PARS" ]; then
msg "# runmode = $runmode | input_phylip = $input_phylip | input_phylo = $phylo" PROGR YELLOW
msg "# n_cores = $n_cores | bootstrap no. = $boot | n_jumbles_pars = $n_jumbles | t_jumbles_boot_pars = $t_jumbles" PROGR YELLOW
msg "# DEBUG=$DEBUG" PROGR YELLOW
echo
fi
#-------------------------------------------------------------------------------------------------#
#------------------------------------------ MAIN CODE --------------------------------------------#
#-------------------------------------------------------------------------------------------------#
wkdir=$(pwd)
top_dir=$(pwd)
# 1. Run maximum-likelihood tree searches on the pan-genome matrix with IQ-TREE, including model selection
if [ "$criterion" == "ML" ]; then
msg " " PROGR NC
msg " >>>>>>>>>>>>>>> ModelFinder + IQ-TREE run on pan-genome matrix <<<<<<<<<<<<<<< " PROGR YELLOW
msg " " PROGR NC
iqt_dir="iqtree_PGM_${num_IQT_runs}_runs"
[ -d "$iqt_dir" ] && msg "# WARNING: $iqt_dir exists in $topdir!. Need to remove or rename it." WARNING LRED && exit 1
mkdir "$iqt_dir" && cd "$iqt_dir" && ln -s ../"$input_fasta" .
[ -d "$iqt_dir" ] && msg "...created and moved into subdir $iqt_dir" PROGR LBLUE
sed 's#\.gb[fk]##g' "$input_fasta" > "${input_fasta}ed"
[ "$DEBUG" -eq 1 ] && check_output "${input_fasta}ed" "$pPID"
[ "$DEBUG" -eq 1 ] && msg "calling: run_IQT_discrete ${input_fasta}ed $discrete_model $num_IQT_runs $IQT_support in dir: $wkdir" DEBUG NC
run_IQT_discrete "${input_fasta}ed" "$discrete_model" "$num_IQT_runs" "$IQT_support"
fi
# NOTE: THE PARS TREE SEARCHES ARE VERY SLOW!
# TODO: 1. improve/expand documentation, perhaps adding option -H
# 2. improve/expand error checking + progress messages
# 3. think of adding option -d to define wkdir and improve warning messages/handling
# if -d dir exists, as a function of -R
# 4. Think of adding more runmodes ...