-
Notifications
You must be signed in to change notification settings - Fork 41
/
dDocent
executable file
·1384 lines (1171 loc) · 57 KB
/
dDocent
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
export LC_ALL=en_US.UTF-8
export SHELL=bash
##########dDocent##########
VERSION='2.8.13'; export VERSION
#This script serves as an interactive bash wrapper to QC, assemble, map, and call SNPs from double digest RAD (SE or PE), ezRAD (SE or PE) data, or SE RAD data.
#It requires that your raw data are split up by tagged individual and follow the naming convention of:
#Pop_Sample1.F.fq and Pop_Sample1.R.fq
#Prints out title and contact info
echo -e "dDocent" $VERSION "\n"
echo -e "Contact jpuritz@uri.edu with any problems \n\n "
###Code to check for the required software for dDocent
echo "Checking for required software"
DEP=(freebayes mawk bwa samtools vcftools rainbow gnuplot seqtk cd-hit-est bamToBed bedtools parallel vcfcombine pearRM fastp)
NUMDEP=0
for i in "${DEP[@]}"
do
if which $i &> /dev/null; then
foo=0
else
echo "The dependency" $i "is not installed or is not in your" '$PATH'"."
NUMDEP=$((NUMDEP + 1))
fi
done
SAMV1=$(samtools 2>&1 >/dev/null | grep Ver | sed -e 's/Version://' | cut -f2 -d " " | sed -e 's/-.*//' | cut -f1 -d ".")
SAMV2=$(samtools 2>&1 >/dev/null | grep Ver | sed -e 's/Version://' | cut -f2 -d " " | sed -e 's/-.*//' | cut -f2 -d ".")
if [ "$SAMV1" -ge "1" ]; then
if [ "$SAMV2" -lt "3" ]; then
echo "The version of Samtools installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install at least version 1.3.0"
echo -en "\007"
echo -en "\007"
exit 1
fi
else
echo "The version of Samtools installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install at least version 1.3.0"
echo -en "\007"
echo -en "\007"
exit 1
fi
RAINV=(`rainbow | head -1 | cut -f2 -d' ' `)
if [[ "$RAINV" != "2.0.2" && "$RAINV" != "2.0.3" && "$RAINV" != "2.0.4" ]]; then
echo "The version of Rainbow installed in your" '$PATH' "is not optimized for dDocent."
echo -en "\007"
echo -en "\007"
echo -en "\007"
echo "Is the version of rainbow installed newer than 2.0.2? Enter yes or no."
read TEST
if [ "$TEST" != "yes" ]; then
echo "Please install a version newer than 2.0.2"
exit 1
fi
fi
FREEB=(`freebayes | grep -oh 'v[0-9].*' | cut -f1 -d "." | sed -e 's/v//' `)
if [ "$FREEB" != "1" ]; then
echo "The version of FreeBayes installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install at least version 1.0.0"
exit 1
fi
SEQTK=( `seqtk 2>&1 | grep Version | cut -f2 -d ":" | sed -e 's/1.[0-9]-r//g' | sed -e 's/-dirty//g' `)
if [ "$SEQTK" -lt "102" ]; then
echo "The version of seqtk installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install at least version 1.2-r102-dirty"
exit 1
fi
VCFTV=$(vcftools | grep VCF | grep -oh '[0-9]*[a-z]*)$' | sed -e 's/[a-z)]//')
if [ "$VCFTV" -lt "10" ]; then
echo "The version of VCFtools installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install at least version 0.1.11"
exit 1
elif [ "$VCFTV" == "11" ]; then
VCFGTFLAG="--geno"
elif [ "$VCFTV" -ge "12" ]; then
VCFGTFLAG="--max-missing"
fi
BWAV=$(bwa 2>&1 | mawk '/Versi/' | sed -e 's/Version: //g' | sed -e 's/0.7.//g' | sed -e 's/-.*//g' | cut -c 1-2)
if [ "$BWAV" -lt "13" ]; then
echo "The version of bwa installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install at least version 0.7.13"
exit 1
fi
BTC=$( bedtools --version | mawk '{print $2}' | sed -e 's/v//g' | cut -f1,2 -d"." | sed -e 's/2\.//g' )
if [ "$BTC" -ge "26" ]; then
BEDTOOLSFLAG="NEW"
elif [ "$BTC" == "23" ]; then
BEDTOOLSFLAG="OLD"
elif [ "$BTC" != "23" ]; then
echo "The version of bedtools installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install version 2.23.0 or version 2.26.0 and above"
exit 1
fi
FASTP=$(fastp -v 2>&1 | cut -f2 -d " ")
FASTP1=$(echo $FASTP | cut -f1 -d ".")
FASTP2=$(echo $FASTP | cut -f2 -d ".")
FASTP3=$(echo $FASTP | cut -f3 -d ".")
if [ "$FASTP1" -lt "2" ]; then
if [ "$FASTP2" -lt "20" ]; then
if [ "$FASTP2" -lt "5" ]; then
echo "The version of fastp installed in your" '$PATH' "is not optimized for dDocent."
echo "Please install version 0.19.5 or above"
exit 1
fi
fi
fi
if ! sort --version | fgrep GNU &>/dev/null; then
sort=gsort
else
sort=sort
fi
if [ $NUMDEP -gt 0 ]; then
echo -e "\nPlease install all required software before running dDocent again."
exit 1
else
echo -e "\nAll required software is installed!"
fi
#This code checks for individual fastq files follow the correct naming convention and are gziped
TEST=$(ls *.fq 2> /dev/null | wc -l )
if [ "$TEST" -gt 0 ]; then
echo -e "\ndDocent is now configured to work on compressed sequence files. Please run gzip to compress your files."
echo "This is as simple as 'gzip *.fq'"
echo "Please rerun dDocent after compressing files."
exit 1
fi
#Count number of individuals in current directory
NumInd=$(ls *.F.fq.gz 2> /dev/null | wc -l)
NumInd=$(($NumInd - 0))
#Test for file limits for current user and reset if necessary
Flimit=$(ulimit -n)
export Flimit
if [ "$Flimit" != "unlimited" ]; then
Nlimit=$(( $NumInd * 10 ))
if [ "$Flimit" -lt "$Nlimit" ]; then
ulimit -n $Nlimit
fi
fi
#Create list of sample names
ls *.F.fq.gz > namelist 2> /dev/null
sed -i'' -e 's/.F.fq.gz//g' namelist
#Create an array of sample names
NUMNAMES=$(mawk '/_/' namelist | wc -l)
if [ "$NUMNAMES" -eq "$NumInd" ]; then
NAMES=( `cat "namelist" `)
else
echo "Individuals do not follow the dDocent naming convention."
echo "Please rename individuals to: Locality_Individual.F.fq.gz"
echo "For example: LocA_001.F.fq.gz"
exit 1
fi
if [[ "$1" == "help" || "$1" == "-help" || "$1" == "--help" || "$1" == "-h" || "$1" == "--h" ]]; then
echo -e "\nTo run dDocent, simply type '"dDocent"' and press [ENTER]"
echo -e "\nAlternatively, dDocent can be run with a configuration file. Usuage is:"
echo -e "\ndDocent config_file\n\n"
exit 0
fi
#Wrapper for main program functions. This allows the entire file to be read first before execution
main(){
##########User Input Section##########
#This code gets input from the user and assigns variables
######################################
#Sets a start time variable
STARTTIME=$(date)
echo -e "\ndDocent version $VERSION started" $STARTTIME "\n"
#dDocent can now accept a configuration file instead of running interactively
#Checks if a configuration file is being used, if not asks for user input
if [ -n "$1" ]; then
CONFIG=$1
if [ ! -f $CONFIG ]; then
echo -e "\nThe configuration file $CONFIG does not exist."
exit 1
fi
NUMProc=$(grep -A1 Processor $CONFIG 2> /dev/null | tail -1 )
if [[ $NUMProc -lt 999999 && $NUMProc -gt 1 ]]; then
MAXMemory1=$(grep -A1 Memory $CONFIG | sed -e 's/[g,G]//g' | tail -1)
else
echo -e "\nConfiguration file is not properly configured. Please see example on dDocent.com or the dDocent GitHub page."
exit 1
fi
MAXMemory=0
#MAXMemory=$(( $MAXMemory1 / $NUMProc ))G
if [[ "$OSTYPE" == "darwin"* ]]; then
MAXMemory=0
MAXMemory1=0
fi
TRIM=$(grep -A1 Trim $CONFIG | tail -1)
ASSEMBLY=$(grep -A1 '^Assembly' $CONFIG | tail -1)
CUTOFF=$(grep -A1 'Minimum within' $CONFIG 2> /dev/null | tail -1)
if [[ $CUTOFF -lt 9999 && $CUTOFF -gt 0 ]]; then
CUTOFF2=$(grep -A1 'Minimum number' $CONFIG | tail -1)
else
if [ "$ASSEMBLY" == "yes" ]; then
echo -e "\nConfiguration file is not properly configured. Please see example on dDocent.com or the dDocent GitHub page."
exit 1
fi
fi
ATYPE=$(grep -A1 Type $CONFIG | tail -1)
simC=$(grep -A1 Simi $CONFIG | tail -1)
MAP=$(grep -A1 Mapping_R $CONFIG | tail -1)
optA=$(grep -A1 _Match $CONFIG | tail -1)
optB=$(grep -A1 MisMatch $CONFIG | tail -1)
optO=$(grep -A1 Gap $CONFIG | tail -1)
SNP=$(grep -A1 SNP $CONFIG | tail -1)
MAIL=$(grep -A1 Email $CONFIG | tail -1)
if [ "$ASSEMBLY" == "yes" ] && [[ -z $CUTOFF || -z $CUTOFF2 ]]; then
echo "dDocent will require input during the assembly stage. Please wait until prompt says it is safe to move program to the background."
else
#Prints instructions on how to move analysis to background and disown process
echo "At this point, all configuration information has been entered and dDocent may take several hours to run."
echo "It is recommended that you move this script to a background operation and disable terminal input and output."
echo "All data and logfiles will still be recorded."
echo "To do this:"
echo "Press control and Z simultaneously"
echo "Type 'bg' without the quotes and press enter"
echo "Type 'disown -h' again without the quotes and press enter"
echo ""
echo "Now sit back, relax, and wait for your analysis to finish"
fi
else
GetInfo
fi
#Set a variable for samtools threads
if [ "$NUMProc" -gt 4 ]; then
SAMProc=4
else
SAMProc=$NUMProc
fi
export SAMProc
#Creates (or appends to) a dDcoent run file recording variables
echo "Variables used in dDocent (version $VERSION) run at" $STARTTIME >> dDocent.runs
echo "Number of Processors" >> dDocent.runs
echo $NUMProc >> dDocent.runs
echo "Trimming" >> dDocent.runs
echo $TRIM >> dDocent.runs
echo "Assembly?" >> dDocent.runs
echo $ASSEMBLY >> dDocent.runs
echo "Type_of_Assembly" >> dDocent.runs
echo $ATYPE >> dDocent.runs
echo "Clustering_Similarity%" >> dDocent.runs
echo $simC >> dDocent.runs
if [ -n "$CUTOFF" ]; then
echo "Minimum within individaul coverage level to include a read for assembly (K1)" >> dDocent.runs
echo $CUTOFF >> dDocent.runs
else
echo "Minimum within individaul coverage level to include a read for assembly (K1)" >> dDocent.runs
echo "CUTOFF1_NOTSET" >> dDocent.runs
fi
if [ -n "$CUTOFF2" ]; then
echo "Minimum number of individuals a read must be present in to include for assembly (K2)" >> dDocent.runs
echo $CUTOFF2 >> dDocent.runs
else
echo "Minimum number of individuals a read must be present in to include for assembly (K2)" >> dDocent.runs
echo "CUTOFF2_NOTSET" >> dDocent.runs
fi
echo "Mapping_Reads?" >> dDocent.runs
echo $MAP >> dDocent.runs
echo "Mapping_Match_Value" >> dDocent.runs
echo $optA >> dDocent.runs
echo "Mapping_MisMatch_Value" >> dDocent.runs
echo $optB >> dDocent.runs
echo "Mapping_GapOpen_Penalty" >> dDocent.runs
echo $optO >> dDocent.runs
echo "Calling_SNPs?" >> dDocent.runs
echo $SNP >> dDocent.runs
echo "Email" >> dDocent.runs
echo $MAIL >> dDocent.runs
##Section of logic statements that dictates the order and function of processing the pipeline
if [[ "$TRIM" == "yes" && "$ASSEMBLY" == "yes" ]]; then
echo -e "\nTrimming reads and simultaneously assembling reference sequences"
TrimReads & 2> trim.log
Assemble
#setupRainbow 2> rainbow.log
wait
fi
if [[ "$TRIM" == "yes" && "$ASSEMBLY" != "yes" ]]; then
echo -e "\nTrimming reads"
TrimReads 2> trim.log
fi
if [[ "$TRIM" != "yes" && "$ASSEMBLY" == "yes" ]]; then
Assemble
#setupRainbow 2> rainbow.log
fi
#Checks to see if reads will be mapped.
if [ "$MAP" != "no" ]; then
echo -e "\nUsing BWA to map reads"
if [ reference.fasta -nt reference.fasta.fai ]; then
samtools faidx reference.fasta &> index.log
bwa index reference.fasta >> index.log 2>&1
fi
#dDocent now checks for trimmed read files before attempting mapping
if [[ "$MAP" != "no" && ! -f "${NAMES[@]:(-1)}".R1.fq.gz ]]; then
echo "dDocent cannot locate trimmed reads files"
echo "Please rerun dDocent with quality trimming"
exit 1
fi
#This next section of code checks to see if the reference was assembled by dDocent
#and if so, modifies the expected insert length distribution for BWA's metric for proper pairing
if head -1 reference.fasta | grep -e 'dDocent' 1>/dev/null; then
rm lengths.txt &> /dev/null
for i in "${NAMES[@]}";
do
if [ -f "$i.R.fq.gz" ]; then
gunzip -c $i.R.fq.gz | head -2 | tail -1 >> lengths.txt
fi
done
if [ -f "lengths.txt" ]; then
MaxLen=$(mawk '{ print length() | "sort -rn" }' lengths.txt| head -1)
INSERT=$(($MaxLen * 2 ))
INSERTH=$(($INSERT + 100 ))
INSERTL=$(($INSERT - 100 ))
SD=$(($INSERT / 5))
fi
#BWA for mapping for all samples. As of version 2.0 can handle SE or PE reads by checking for PE read files
for i in "${NAMES[@]}"
do
if [ -f "$i.R2.fq.gz" ]; then
bwa mem -L 20,5 -I $INSERT,$SD,$INSERTH,$INSERTL -t $NUMProc -a -M -T 10 -A $optA -B $optB -O $optO -R "@RG\tID:$i\tSM:$i\tPL:Illumina" reference.fasta $i.R1.fq.gz $i.R2.fq.gz 2> bwa.$i.log | mawk '$6 !~/[2-9].[SH]/ && $6 !~ /[1-9][0-9].[SH]/' | samtools view -@$SAMProc -q 1 -SbT reference.fasta - > $i.bam 2>$i.bam.log
else
bwa mem -L 20,5 -t $NUMProc -a -M -T 10 -A $optA -B $optB -O $optO -R "@RG\tID:$i\tSM:$i\tPL:Illumina" reference.fasta $i.R1.fq.gz 2> bwa.$i.log | mawk '$6 !~/[2-9].[SH]/ && $6 !~ /[1-9][0-9].[SH]/' | samtools view -@$SAMProc -q 1 -SbT reference.fasta - > $i.bam 2>$i.bam.log
fi
samtools sort -@$SAMProc $i.bam -o $i.bam 2>>$i.bam.log
mv $i.bam $i-RG.bam
samtools index $i-RG.bam
done
else
for i in "${NAMES[@]}"
do
if [ -f "$i.R2.fq.gz" ]; then
bwa mem -L 20,5 -t $NUMProc -a -M -T 10 -A $optA -B $optB -O $optO -R "@RG\tID:$i\tSM:$i\tPL:Illumina" reference.fasta $i.R1.fq.gz $i.R2.fq.gz 2> bwa.$i.log | mawk '$6 !~/[2-9].[SH]/ && $6 !~ /[1-9][0-9].[SH]/' | samtools view -@$SAMProc -q 1 -SbT reference.fasta - > $i.bam 2>$i.bam.log
else
bwa mem -L 20,5 -t $NUMProc -a -M -T 10 -A $optA -B $optB -O $optO -R "@RG\tID:$i\tSM:$i\tPL:Illumina" reference.fasta $i.R1.fq.gz 2> bwa.$i.log | mawk '$6 !~/[2-9].[SH]/ && $6 !~ /[1-9][0-9].[SH]/' | samtools view -@$SAMProc -q 1 -SbT reference.fasta - > $i.bam 2>$i.bam.log
fi
samtools sort -@$SAMProc $i.bam -o $i.bam 2>>$i.bam.log
mv $i.bam $i-RG.bam
samtools index $i-RG.bam
done
fi
fi
##Creating mapping intervals if needed, CreateIntervals function is defined later in script
#If mapping is being performed, intervals are created automatically
if [ "$MAP" != "no" ]; then
echo -e "\nCreating alignment intervals"
ls *-RG.bam >bamlist.list
CreateIntervals
fi
##SNP Calling Section of code
if [ "$SNP" != "no" ]; then
#Create list of BAM files
ls *-RG.bam >bamlist.list
#If mapping is not being performed, but intervals do not exist they are created
if [[ "$MAP" == "no" && ! -f "cat-RRG.bam" ]]; then
CreateIntervals
fi
#Check for runs from older versions to ensure the recreation of cat-RRG.bam
if [[ "$MAP" == "no" && -f "map.bed" ]]; then
CreateIntervals
fi
#Check to make sure interval files have been created
if [[ "$MAP" == "no" && ! -f "mapped.bed" ]]; then
bedtools merge -i cat-RRG.bam -bed > mapped.bed
fi
#This code estimates the coverage of reference intervals and removes intervals in 0.01% of depth
#This allows genotyping to be more effecient and eliminates extreme copy number loci from the data
if [ "cat-RRG.bam" -nt "cov.stats" ]; then
FB2=$(( $NUMProc / 2 ))
if [ "$BEDTOOLSFLAG" == "OLD" ]; then
cat namelist | parallel -j $FB2 "coverageBed -abam {}-RG.bam -b mapped.bed -counts > {}.cov.stats"
else
mawk -v OFS='\t' {'print $1,$2'} reference.fasta.fai > genome.file
cat namelist | parallel -j $FB2 "bedtools coverage -b {}-RG.bam -a mapped.bed -counts -sorted -g genome.file > {}.cov.stats"
fi
cat *.cov.stats | $sort -k1,1 -k2,2n | bedtools merge -i - -c 4 -o sum > cov.stats
fi
SNPNUMProc=$(( $NUMProc * 2 ))
if head -1 reference.fasta | grep -e 'dDocent' 1>/dev/null; then
DP=$(mawk '{print $4}' cov.stats | $sort -rn | perl -e '$d=.001;@l=<>;print $l[int($d*@l)]')
CC=$( mawk -v x=$DP '$4 < x' cov.stats | mawk '{len=$3-$2;lc=len*$4;tl=tl+lc} END {OFMT = "%.0f";print tl/"'$SNPNUMProc'"}')
else
DP=$(mawk '{print $4}' cov.stats | $sort -rn | perl -e '$d=.00005;@l=<>;print $l[int($d*@l)]')
CC=$( mawk -v x=$DP '$4 < x' cov.stats | mawk '{len=$3-$2;lc=len*$4;tl=tl+lc} END {OFMT = "%.0f";print tl/"'$SNPNUMProc'"}')
fi
#calculate read length
rm lengths.txt &> /dev/null
read_length(){
if [ -f "$1.R.fq.gz" ]; then
gunzip -c $1.R.fq.gz | head -2 | tail -1 >> lengths.txt
else
gunzip -c $1.F.fq.gz | head -2 | tail -1 >> lengths.txt
fi
}
export -f read_length
cat namelist| parallel --env read_length -j $NUMProc --no-notice "read_length {}"
MaxLen=$(mawk '{ print length() | "sort -rn" }' lengths.txt| head -1)
#split cov.stats file into high and low coverage intervals
mawk '$4 > 500000' cov.stats > cov.high.stats
mawk '$4 <= 500000' cov.stats > cov.low.stats
#split high coverage intervals into smaller, 1/2 read-length sized intervals
MaxLen2=$(( $MaxLen / 2 ))
ML1=$(( $MaxLen2 + 1 ))
bedtools makewindows -b cov.high.stats -w $MaxLen2 -s $ML1 > temp1.bed
bedtools intersect -a cov.stats -b temp1.bed > temp.cov.stats
cat temp.cov.stats cov.low.stats > cov.split.stats
rm cov.high.stats cov.low.stats temp1.bed temp.cov.stats
TT=$(( $MaxLen2 * 1000000 ))
mawk -v x=$DP '$4 < x' cov.split.stats |sort -V -k1,1 -k2,2 | mawk -v cutoff=$CC -v tt=$TT 'BEGIN{i=1}
{len=$3-$2;lc=len*$4;cov = cov + lc
if (NR == 1 && lc > tt) {x="mapped."i".bed";print $1"\t"$2"\t"$3 > x; i=i+1; e=1}
else if ( cov < cutoff && lc < tt) {x="mapped."i".bed";print $1"\t"$2"\t"$3 > x; e=0}
else if (lc > tt && e > 0 ) {x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=0;i=i+1; e=1}
else if (lc > tt && e < 1 ) {i=i+1; x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=0;i=i+1;e=1}
else if (cov > cutoff && lc < tt ) {i=i+1; x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=lc;e=0}
}'
FB2=$(( $NUMProc / 8 ))
export FB2
echo -e "\nUsing FreeBayes to call SNPs"
#Creates a population file to use for more accurate genotype calling
cut -f1 -d "_" namelist > p
paste namelist p > popmap
rm p
###New implementation of SNP calling here to save on memory
call_genos(){
#samtools view -@$SAMProc -b -1 -L mapped.$1.bed -o split.$1.bam cat-RRG.bam
#samtools index split.$1.bam
echo "Starting Freebayes instance " $1 >> freebayes.log
freebayes -b cat-RRG.bam -t mapped.$1.bed -v raw.$1.vcf -f reference.fasta -m 5 -q 5 -E 3 --min-repeat-entropy 1 -V --populations popmap -n 10 -F 0.1 &> fb.$1.error.log
if [ $? -eq 0 ]; then
echo "freebayes instance $1 completed successfully." >> freebayes.log
rm fb.$1.error.log
else
echo -e "\n\nERROR: freebayes instance DID NOT COMPLETE\n\nSee below:"
cat fb.$1.error.log
echo -e "$?" "\t" "$1" >> freebayes.error
exit 1
fi
}
export -f call_genos
call_genos2(){
#samtools view -@$SAMProc -b -1 -L mapped.$1.bed -o split.$1.bam split.bam
#samtools index split.$1.bam
echo "Starting Freebayes instance " $1 >> freebayes.log
freebayes -b cat-RRG.bam -t mapped.$1.bed -v raw.$1.vcf -f ../reference.fasta -m 5 -q 5 -E 3 --min-repeat-entropy 1 -V --populations ../popmap -n 10 -F 0.1
if [ $? -eq 0 ]; then
rm mapped.$1.bed
else
echo -e "$?" "\t" "$1" >> freebayes.error
exit 1
fi
}
export -f call_genos2
finish_genos(){
echo "Redoing a failed instance of FreeBayes"
mkdir Finish.$1
cd Finish.$1
cp ../mapped.$1.bed mapped.bed
ln -s ../cat-RRG.bam* .
bedtools intersect -b mapped.bed -a ../cov.stats > cov.stats
CC=$( mawk '{len=$3-$2;lc=len*$4;tl=tl+lc} END {OFMT = "%.0f";print tl/4}' cov.stats)
$sort -V -k1,1 -k2,2 cov.stats | mawk -v cutoff=$CC 'BEGIN{i=1}
{
len=$3-$2;lc=len*$4;cov = cov + lc
if ( cov < cutoff) {x="mapped."i".bed";print $1"\t"$2"\t"$3 > x}
else {i=i+1; x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=0}
}'
ls mapped.*.bed | sed -e 's/mapped.//g' | sed -e 's/.bed//g' | shuf | parallel --bar --halt now,fail=1 --env call_genos2 -j 4 --no-notice "call_genos2 {} "
if [ -f "freebayes.error" ]; then
echo -e "\n\n\nFreeBayes has failed when trying to finish a previously failed instance. Memory and processor settings need to be drastically reconfigured"
ERROR3=1
export ERROR3
else
echo "The failed instance of FreeBayes was successfully rerun"
ERROR3=0
export ERROR3
mv raw.1.vcf raw.01.vcf 2>/dev/null
mv raw.2.vcf raw.02.vcf 2>/dev/null
mv raw.3.vcf raw.03.vcf 2>/dev/null
mv raw.4.vcf raw.04.vcf 2>/dev/null
vcfcombine raw.*.vcf | sed -e 's/ \.\:/ \.\/\.\:/g' > RedoRawSNPs.vcf
mv RedoRawSNPs.vcf ../raw.$1.vcf
fi
cd ..
rm -rf Finish.$1
}
export -f finish_genos
rm freebayes.error freebayes.log &> /dev/null
ls mapped.*.bed | sed -e 's/mapped.//g' | sed -e 's/.bed//g' | shuf | parallel --bar --halt now,fail=10 --env call_genos -j $NUMProc --no-notice --joblog ./par.log "call_genos {} "
if [ -f "freebayes.error" ]; then
FAILS=$( cat freebayes.error | wc -l )
if [ $FAILS -lt 10 ]; then
mv freebayes.error freebayes.redos
for i in `cut -f2 freebayes.redos`
do
finish_genos $i
done
rm freebayes.redos
else
echo -e "\nmultiple instances of freebayes failed. dDocent will now recalibrate run parameters to use less memory.\n"
rm mapped.*.bed
rm freebayes.error
LIM=$(( $SNPNUMProc * 4 ))
if head -1 reference.fasta | grep -e 'dDocent' 1>/dev/null; then
DP=$(mawk '{print $4}' cov.stats | $sort -rn | perl -e '$d=.001;@l=<>;print $l[int($d*@l)]')
CC=$( mawk -v x=$DP '$4 < x' cov.stats | mawk '{len=$3-$2;lc=len*$4;tl=tl+lc} END {OFMT = "%.0f";print tl/"'$LIM'"}')
else
DP=$(mawk '{print $4}' cov.stats | $sort -rn | perl -e '$d=.00005;@l=<>;print $l[int($d*@l)]')
CC=$( mawk -v x=$DP '$4 < x' cov.stats | mawk '{len=$3-$2;lc=len*$4;tl=tl+lc} END {OFMT = "%.0f";print tl/"'$LIM'"}')
fi
TT=$(( $MaxLen2 * 1000000 ))
mawk -v x=$DP '$4 < x' cov.split.stats |sort -V -k1,1 -k2,2 | mawk -v cutoff=$CC -v tt=$TT 'BEGIN{i=1}
{len=$3-$2;lc=len*$4;cov = cov + lc
if (NR == 1 && lc > tt) {x="mapped."i".bed";print $1"\t"$2"\t"$3 > x; i=i+1; e=1}
else if ( cov < cutoff && lc < tt) {x="mapped."i".bed";print $1"\t"$2"\t"$3 > x; e=0}
else if (lc > tt && e > 0 ) {x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=0;i=i+1; e=1}
else if (lc > tt && e < 1 ) {i=i+1; x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=0;i=i+1;e=1}
else if (cov > cutoff && lc < tt ) {i=i+1; x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=lc;e=0}
}'
FB2=$(( $NUMProc / 10 ))
export FB2
echo "Using FreeBayes to call SNPs again"
NumP=$(( $NUMProc / 4 ))
NumP=$(( $NumP * 3 ))
ls mapped.*.bed | sed -e 's/mapped.//g' | sed -e 's/.bed//g' | shuf | parallel --bar --halt now,fail=10 --env call_genos -j $NumP --no-notice --joblog ./par2.log "call_genos {} "
fi
fi
if [ -f "freebayes.error" ]; then
FAILS=$( cat freebayes.error | wc -l )
if [ $FAILS -lt 10 ]; then
mv freebayes.error freebayes.redos
for i in `cut -f2 freebayes.redos`
do
finish_genos $i
done
rm freebayes.redos
else
echo -e "\nA previous freebayes instance failed again. dDocent will now recalibrate run parameters to use even less memory.\n"
rm freebayes.error
LIM=$(( $LIM * 4 ))
if head -1 reference.fasta | grep -e 'dDocent' 1>/dev/null; then
DP=$(mawk '{print $4}' cov.stats | $sort -rn | perl -e '$d=.001;@l=<>;print $l[int($d*@l)]')
CC=$( mawk -v x=$DP '$4 < x' cov.stats | mawk '{len=$3-$2;lc=len*$4;tl=tl+lc} END {OFMT = "%.0f";print tl/"'$LIM'"}')
else
DP=$(mawk '{print $4}' cov.stats | $sort -rn | perl -e '$d=.00005;@l=<>;print $l[int($d*@l)]')
CC=$( mawk -v x=$DP '$4 < x' cov.stats | mawk '{len=$3-$2;lc=len*$4;tl=tl+lc} END {OFMT = "%.0f";print tl/"'$LIM'"}')
fi
TT=$(( $MaxLen2 * 1000000 ))
mawk -v x=$DP '$4 < x' cov.split.stats |sort -V -k1,1 -k2,2 | mawk -v cutoff=$CC -v tt=$TT 'BEGIN{i=1}
{len=$3-$2;lc=len*$4;cov = cov + lc
if (NR == 1 && lc > tt) {x="mapped."i".bed";print $1"\t"$2"\t"$3 > x; i=i+1; e=1}
else if ( cov < cutoff && lc < tt) {x="mapped."i".bed";print $1"\t"$2"\t"$3 > x; e=0}
else if (lc > tt && e > 0 ) {x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=0;i=i+1; e=1}
else if (lc > tt && e < 1 ) {i=i+1; x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=0;i=i+1;e=1}
else if (cov > cutoff && lc < tt ) {i=i+1; x="mapped."i".bed"; print $1"\t"$2"\t"$3 > x; cov=lc;e=0}
}'
NumP=$(( $NumP / 4 ))
NumP=$(( $NumP * 3 ))
echo "Using FreeBayes to call SNPs again"
ls mapped.*.bed | sed -e 's/mapped.//g' | sed -e 's/.bed//g' | shuf | parallel --bar --halt now,fail=10 --env call_genos -j $NumP --joblog ./par3.log --no-notice "call_genos {}"
fi
fi
if [ -f "freebayes.error" ]; then
echo -e "\n\n\nFreeBayes has now failed a third time, likely because of memory issues. More resources must be allocated to finish this analysis."
ERROR3=1
export ERROR3
else
ERROR3=0
export ERROR3
fi
rm mapped.*.bed
mv raw.1.vcf raw.01.vcf 2>/dev/null
mv raw.2.vcf raw.02.vcf 2>/dev/null
mv raw.3.vcf raw.03.vcf 2>/dev/null
mv raw.4.vcf raw.04.vcf 2>/dev/null
mv raw.5.vcf raw.05.vcf 2>/dev/null
mv raw.6.vcf raw.06.vcf 2>/dev/null
mv raw.7.vcf raw.07.vcf 2>/dev/null
mv raw.8.vcf raw.08.vcf 2>/dev/null
mv raw.9.vcf raw.09.vcf 2>/dev/null
vcfcombine raw.*.vcf | sed -e 's/ \.\:/ \.\/\.\:/g' > TotalRawSNPs.vcf
if [ ! -d "raw.vcf" ]; then
mkdir raw.vcf
fi
mv raw.*.vcf ./raw.vcf
echo -e "\nUsing VCFtools to parse TotalRawSNPS.vcf for SNPs that are called in at least 90% of individuals"
vcftools --vcf TotalRawSNPs.vcf $VCFGTFLAG 0.9 --out Final --recode --non-ref-af 0.001 --max-non-ref-af 0.9999 --mac 1 --minQ 30 --recode-INFO-all &>VCFtools.log
fi
##Checking for possible errors
if [ "$MAP" != "no" ]; then
ERROR1=$(mawk '/developer/' bwa* 2>/dev/null | wc -l 2>/dev/null)
fi
ERROR2=$(mawk '/error/' *.bam.log 2>/dev/null | wc -l 2>/dev/null)
if [ "$SNP" == "no" ]; then
ERROR3=0
fi
ERRORS=$(($ERROR1 + $ERROR2 + $ERROR3))
#Move various log files to own directory
if [ ! -d "logfiles" ]; then
mkdir logfiles
fi
mv *.txt *.log log ./trim_reports ./logfiles 2> /dev/null
#Sending a completion email
if [ "$SNP" != "no" ]; then
if [ $ERRORS -gt 0 ]; then
echo -e "dDocent has finished with errors in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\nPlease check log files\n\n"`mawk '/After filtering, kept .* out of a possible/' ./logfiles/VCFtools.log ` "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly." | mailx -s "dDocent has finished with ERRORS!" $MAIL 2>/dev/null
echo -e "\ndDocent has finished with errors in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\nPlease check log files\n\n"`mawk '/After filtering, kept .* out of a possible/' ./logfiles/VCFtools.log ` "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly."
else
echo -e "dDocent has finished with an analysis in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\n"`mawk '/After filtering, kept .* out of a possible/' ./logfiles/VCFtools.log ` "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly." | mailx -s "dDocent has finished" $MAIL 2>/dev/null
echo -e "\ndDocent has finished with an analysis in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\n"`mawk '/After filtering, kept .* out of a possible/' ./logfiles/VCFtools.log ` "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly."
fi
else
if [ $ERRORS -gt 0 ]; then
echo -e "dDocent has finished with errors in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\nPlease check log files" "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly." | mailx -s "dDocent has finished" $MAIL 2>/dev/null
echo -e "\ndDocent has finished with errors in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\nPlease check log files" "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly."
else
echo -e "dDocent has finished with an analysis in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\n" "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly." | mailx -s "dDocent has finished" $MAIL 2>/dev/null
echo -e "\ndDocent has finished with an analysis in" `pwd` "\n\ndDocent started" $STARTTIME "\n\ndDocent finished" `date` "\n\n" "\n\ndDocent" $VERSION "\nThe 'd' is silent, hillbilly."
fi
fi
}
##Function definitions
#Function for trimming reads using fastp
trim_reads(){
if [ -f $1.R.fq.gz ]; then
# paired
fastp --in1 $1.F.fq.gz --in2 $1.R.fq.gz --out1 $1.R1.fq.gz --out2 $1.R2.fq.gz --cut_front --cut_tail --cut_window_size 5 --cut_mean_quality 15 --correction $TW -q 15 -u 50 -j $1.json -h $1.html --detect_adapter_for_pe &> $1.trim.log
else
#single
fastp -i $1.F.fq.gz -o $1.R1.fq.gz --cut_by_quality5 20 --cut_by_quality3 20 --cut_window_size 5 --cut_mean_quality 15 -q 15 -u 50 $TW -j $1.json -h $1.html &> $1.trim.log
fi
mv $1.html ./trim_reports &>/dev/null && mv $1.json ./trim_reports &>/dev/null
}
export -f trim_reads
TrimReads () {
#STACKS adds a strange _1 or _2 character to the end of processed reads, this looks for checks for errant characters and replaces them.
#This functionality is now parallelized and will run if only SE sequences are used.
NAMES=( `cat "namelist" `)
STACKS=$(cat namelist| parallel -j $NUMProc --no-notice "gunzip -c {}.F.fq.gz | head -1" | mawk '$0 !~ /\/1$/ && $0 !~ /\/1[ , ]/ && $0 !~ / 1:.*[A-Z]*/' | wc -l )
FB1=$(( $NUMProc / 2 ))
if [ $STACKS -gt 0 ]; then
echo "Removing the _1 character and replacing with /1 in the name of every sequence"
cat namelist | parallel -j $FB1 --no-notice "gunzip -c {}.F.fq.gz | sed -e 's:_1$:/1:g' > {}.F.fq"
rm -f *.F.fq.gz
cat namelist | parallel -j $FB1 --no-notice "gzip {}.F.fq"
fi
if [ -f "${NAMES[@]:(-1)}".R.fq.gz ]; then
STACKS=$(cat namelist| parallel -j $NUMProc --no-notice "gunzip -c {}.R.fq.gz | head -1" | mawk '$0 !~ /\/2$/ && $0 !~ /\/2[ , ]/ && $0 !~ / 2:.*[A-Z]*/'| wc -l )
if [ $STACKS -gt 0 ]; then
echo "Removing the _2 character and replacing with /2 in the name of every sequence"
cat namelist | parallel -j $FB1 --no-notice "gunzip -c {}.R.fq.gz | sed -e 's:_2$:/2:g' > {}.R.fq"
rm -f *.R.fq.gz
cat namelist | parallel -j $FB1 --no-notice "gzip {}.R.fq"
fi
fi
cat namelist | parallel -j $NUMProc "gunzip -c {}.F.fq.gz | head -2 | tail -1 >> lengths.txt"
MLen=$(mawk '{ print length() | "sort -rn" }' lengths.txt| head -1)
MLen=$(($MLen / 2))
TW="--length_required $MLen"
mkdir trim_reports &>/dev/null
cat namelist | parallel --env trim_reads -j $FB1 trim_reads {}
}
getAssemblyInfo(){
#Have user estimate/enter assembly parameters if unentered
if [ -z "$CUTOFF" ]; then
for i in {2..20};
do
echo $i >> pfile
done
cat pfile | parallel -j $NUMProc --no-notice "echo -n {}xxx && mawk -v x={} '\$1 >= x' uniq.seqs | wc -l" | mawk '{gsub("xxx","\t",$0); print;}'| $sort -g > uniqseq.data
rm pfile
#Plot graph of above data
gnuplot << \EOF
set terminal dumb size 120, 30
set autoscale
set xrange [2:20]
unset label
set title "Number of Unique Sequences with More than X Coverage (Counted within individuals)"
set xlabel "Coverage"
set ylabel "Number of Unique Sequences"
set lmargin 10
plot 'uniqseq.data' with lines notitle
pause -1
EOF
echo -en "\007"
echo -en "\007"
echo -en "\007"
echo -e "Please choose data cutoff. In essence, you are picking a minimum (within individual) coverage level for a read (allele) to be used in the reference assembly"
read CUTOFF
fi
special_uniq(){
mawk -v x=$1 '$1 >= x' $2 |cut -f2 | sed -e 's/NNNNNNNNNN/ /g' | cut -f1 | uniq
}
export -f special_uniq
if [[ "$ATYPE" == "RPE" || "$ATYPE" == "ROL" ]]; then
parallel --no-notice -j $NUMProc --env special_uniq special_uniq $CUTOFF {} ::: *.uniq.seqs | $sort --parallel=$NUMProc -S 2G | uniq -c > uniqCperindv
else
parallel --no-notice -j $NUMProc mawk -v x=$CUTOFF \''$1 >= x'\' ::: *.uniq.seqs | cut -f2 | perl -e 'while (<>) {chomp; $z{$_}++;} while(($k,$v) = each(%z)) {print "$v\t$k\n";}' > uniqCperindv
fi
if [ -z "$CUTOFF2" ]; then
if [ "$NumInd" -gt 10 ]; then
NUM=$(($NumInd / 2))
else
NUM=$NumInd
fi
for ((i = 2; i <= $NUM; i++));
do
echo $i >> ufile
done
cat ufile | parallel -j $NUMProc --no-notice "echo -n {}xxx && mawk -v x={} '\$1 >= x' uniqCperindv | wc -l" | mawk '{gsub("xxx","\t",$0); print;}'| $sort -g > uniqseq.peri.data
rm ufile
#Plot graph of above data
gnuplot << \EOF
set terminal dumb size 120, 30
set autoscale
unset label
set title "Number of Unique Sequences present in more than X Individuals"
set xlabel "Number of Individuals"
set ylabel "Number of Unique Sequences"
set lmargin 10
plot 'uniqseq.peri.data' with lines notitle
pause -1
EOF
echo -en "\007"
echo -en "\007"
echo -en "\007"
echo -e "Please choose data cutoff. Pick point right before the assymptote. A good starting cutoff might be 10% of the total number of individuals"
read CUTOFF2
fi
#Prints instructions on how to move analysis to background and disown process
sed -i 's/CUTOFF1_NOTSET/'$CUTOFF'/g' dDocent.runs
sed -i 's/CUTOFF2_NOTSET/'$CUTOFF2'/g' dDocent.runs
echo "At this point, all configuration information has been entered and dDocent may take several hours to run."
echo "It is recommended that you move this script to a background operation and disable terminal input and output."
echo "All data and logfiles will still be recorded."
echo "To do this:"
echo "Press control and Z simultaneously"
echo "Type 'bg' without the quotes and press enter"
echo "Type 'disown -h' again without the quotes and press enter"
echo ""
echo "Now sit back, relax, and wait for your analysis to finish"
}
#Main function for assembly
Assemble()
{
AWK1='BEGIN{P=1}{if(P==1||P==2){gsub(/^[@]/,">");print}; if(P==4)P=0; P++}'
AWK2='!/>/'
AWK3='!/NNN/'
AWK4='{for(i=0;i<$1;i++)print}'
PERLT='while (<>) {chomp; $z{$_}++;} while(($k,$v) = each(%z)) {print "$v\t$k\n";}'
SED1='s/^[ \t]*//'
SED2='s/\s/\t/g'
FRL=$(gunzip -c ${NAMES[0]}.F.fq.gz | mawk '{ print length() | "sort -rn" }' | head -1)
special_uniq(){
mawk -v x=$1 '$1 >= x' $2 |cut -f2 | sed -e 's/NNNNNNNNNN/ /g' | cut -f1 | uniq
}
export -f special_uniq
if [ ${NAMES[@]:(-1)}.F.fq.gz -nt ${NAMES[@]:(-1)}.uniq.seqs ];then
if [[ "$ATYPE" == "PE" || "$ATYPE" == "RPE" ]]; then
#If PE assembly, creates a concatenated file of every unique for each individual in parallel
cat namelist | parallel --no-notice -j $NUMProc "gunzip -c {}.F.fq.gz | mawk '$AWK1' | mawk '$AWK2' > {}.forward"
cat namelist | parallel --no-notice -j $NUMProc "gunzip -c {}.R.fq.gz | mawk '$AWK1' | mawk '$AWK2' > {}.reverse"
if [ "$ATYPE" = "RPE" ]; then
cat namelist | parallel --no-notice -j $NUMProc "paste {}.forward {}.reverse | $sort -k1 -S 200M > {}.fr"
cat namelist | parallel --no-notice -j $NUMProc "cut -f1 {}.fr | uniq -c > {}.f.uniq && cut -f2 {}.fr > {}.r"
cat namelist | parallel --no-notice -j $NUMProc "mawk '$AWK4' {}.f.uniq > {}.f.uniq.e"
cat namelist | parallel --no-notice -j $NUMProc "paste -d '-' {}.f.uniq.e {}.r | mawk '$AWK3'| sed -e 's/-/NNNNNNNNNN/' | sed -e '$SED1' | sed -e '$SED2'> {}.uniq.seqs"
rm *.f.uniq.e *.f.uniq *.r *.fr
else
cat namelist | parallel --no-notice -j $NUMProc "paste -d '-' {}.forward {}.reverse | mawk '$AWK3'| sed -e 's/-/NNNNNNNNNN/' | perl -e '$PERLT' > {}.uniq.seqs"
fi
rm *.forward
rm *.reverse
fi
if [ "$ATYPE" == "SE" ]; then
#if SE assembly, creates files of every unique read for each individual in parallel
cat namelist | parallel --no-notice -j $NUMProc "gunzip -c {}.F.fq.gz | mawk '$AWK1' | mawk '$AWK2' | perl -e '$PERLT' > {}.uniq.seqs"
fi
if [ "$ATYPE" == "OL" ]; then
#If OL assembly, dDocent assumes that the marjority of PE reads will overlap, so the software PEAR is used to merge paired reads into single reads
for i in "${NAMES[@]}";
do
gunzip -c $i.R.fq.gz | head -2 | tail -1 >> lengths.txt
done
MaxLen=$(mawk '{ print length() | "sort -rn" }' lengths.txt| head -1)
LENGTH=$(( $MaxLen / 3))
for i in "${NAMES[@]}"
do
pearRM -f $i.F.fq.gz -r $i.R.fq.gz -o $i -j $NUMProc -n $LENGTH
done
cat namelist | parallel --no-notice -j $NUMProc "mawk '$AWK1' {}.assembled.fastq | mawk '$AWK2' | perl -e '$PERLT' > {}.uniq.seqs"
fi
if [ "$ATYPE" == "HYB" ]; then
#If HYB assembly, dDocent assumes some PE reads will overlap but that some will not, so the OL method performed and remaining reads are then put through PE method
for i in "${NAMES[@]}";
do
gunzip -c $i.R.fq.gz | head -2 | tail -1 >> lengths.txt
done
MaxLen=$(mawk '{ print length() | "sort -rn" }' lengths.txt| head -1)
LENGTH=$(( $MaxLen / 3))
for i in "${NAMES[@]}"
do
pearRM -f $i.F.fq.gz -r $i.R.fq.gz -o $i -j $NUMProc -n $LENGTH &>kopt.log
done
cat namelist | parallel --no-notice -j $NUMProc "mawk '$AWK1' {}.assembled.fastq | mawk '$AWK2' | perl -e '$PERLT' > {}.uniq.seqs"
cat namelist | parallel --no-notice -j $NUMProc "cat {}.unassembled.forward.fastq | mawk '$AWK1' | mawk '$AWK2' > {}.forward"
cat namelist | parallel --no-notice -j $NUMProc "cat {}.unassembled.reverse.fastq | mawk '$AWK1' | mawk '$AWK2' > {}.reverse"
cat namelist | parallel --no-notice -j $NUMProc "paste -d '-' {}.forward {}.reverse | mawk '$AWK3'| sed -e 's/-/NNNNNNNNNN/' | perl -e '$PERLT' > {}.uniq.ua.seqs"
rm *.forward
rm *.reverse
fi
fi
#Create a data file with the number of unique sequences and the number of occurrences
if [ -f "uniq.seqs.gz" ]; then
if [ uniq.seqs.gz -nt uniq.seqs ]; then
gunzip uniq.seqs.gz 2>/dev/null
fi
fi
if [ ! -f "uniq.seqs" ]; then
cat *.uniq.seqs > uniq.seqs
fi
if [[ -z $CUTOFF || -z $CUTOFF2 ]]; then
getAssemblyInfo
fi
if [[ "$ATYPE" == "RPE" || "$ATYPE" == "ROL" ]]; then
parallel --no-notice -j $NUMProc --env special_uniq special_uniq $CUTOFF {} ::: *.uniq.seqs | $sort --parallel=$NUMProc -S 2G | uniq -c > uniqCperindv
else
parallel --no-notice -j $NUMProc mawk -v x=$CUTOFF \''$1 >= x'\' ::: *.uniq.seqs | cut -f2 | perl -e 'while (<>) {chomp; $z{$_}++;} while(($k,$v) = each(%z)) {print "$v\t$k\n";}' > uniqCperindv
fi
#Now that data cutoffs have been chosen, reduce data set to specified set of unique reads, convert to FASTA format,
#and remove reads with substantial amounts of adapters
if [[ "$ATYPE" == "RPE" || "$ATYPE" == "ROL" ]]; then
parallel --no-notice -j $NUMProc mawk -v x=$CUTOFF \''$1 >= x'\' ::: *.uniq.seqs | cut -f2 | sed -e 's/NNNNNNNNNN/-/' > total.uniqs
cut -f 1 -d "-" total.uniqs > total.u.F
cut -f 2 -d "-" total.uniqs > total.u.R
paste total.u.F total.u.R | $sort -k1 --parallel=$NUMProc -S 2G > total.fr
parallel --no-notice --env special_uniq special_uniq $CUTOFF {} ::: *.uniq.seqs | $sort --parallel=$NUMProc -S 2G | uniq -c > total.f.uniq
join -1 2 -2 1 -o 1.1,1.2,2.2 total.f.uniq total.fr | mawk '{print $1 "\t" $2 "NNNNNNNNNN" $3}' | mawk -v x=$CUTOFF2 '$1 >= x' > uniq.k.$CUTOFF.c.$CUTOFF2.seqs
rm total.uniqs total.u.* total.fr total.f.uniq*
else
parallel --no-notice mawk -v x=$CUTOFF \''$1 >= x'\' ::: *.uniq.seqs | cut -f2 | perl -e 'while (<>) {chomp; $z{$_}++;} while(($k,$v) = each(%z)) {print "$v\t$k\n";}' | mawk -v x=$CUTOFF2 '$1 >= x' > uniq.k.$CUTOFF.c.$CUTOFF2.seqs
fi
#$sort -k1 -r -n uniq.k.$CUTOFF.c.$CUTOFF2.seqs | cut -f 2 > totaluniqseq
$sort -k1 -r -n --parallel=$NUMProc -S 2G uniq.k.$CUTOFF.c.$CUTOFF2.seqs |cut -f2 > totaluniqseq
mawk '{c= c + 1; print ">dDocent_Contig_" c "\n" $1}' totaluniqseq > uniq.full.fasta
LENGTH=$(mawk '!/>/' uniq.full.fasta | mawk '(NR==1||length<shortest){shortest=length} END {print shortest}')
LENGTH=$(($LENGTH * 3 / 4))
seqtk seq -F I uniq.full.fasta > uniq.fq
if [ "$NUMProc" -gt 8 ]; then
NP=8
else
NP=$NUMProc
fi
fastp -i uniq.fq -o uniq.fq1 -w $NP -Q &> assemble.trim.log