-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha5
executable file
·1545 lines (1390 loc) · 50 KB
/
a5
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 perl
#
# a5 pipeline
# (c) 2011,2012 Andrew Tritt and Aaron Darling
# This is free software licensed under the GPL, v3. Please see the file LICENSE for details.
#
# Usage: a5_pipeline.pl <library file> <output directory or basename>
# Or: a5_pipeline.pl <fastq 1> <fastq 2> <output directory or basename>
#
use strict;
use warnings;
use File::Basename;
use Cwd 'abs_path';
use Getopt::Long;
use Carp;
=pod
=head1 NAME
a5_pipeline.pl -- Assemble isolate genomes from Illumina data with ease
=head1 SYNOPSIS
a5_pipeline.pl takes FastQ format sequence reads directly from the Illumina base-calling software and cleans, filters, and assembles them.
For example the command:
a5_pipeline.pl read1.fastq read2.fastq my_assembly
Will assemble the paired reads in read1.fastq and read2.fastq and store the result in files whose names begin with "my_assembly".
The final scaffolded assembly will be named my_assembly.final.scaffolds.fasta
=head1 DESCRIPTION
The flow of execution is roughly:
1) Clean up the sequence data
- Error correct, trim adapter, quality trim
2) Build contigs on error-corrected reads
3) Scaffold contigs using paired-read and mate-pair information
4) Detect any misassemblies and break contigs/scaffolds
5) Rescaffold the broken contigs/scaffolds
Throughout the pipeline there are various steps used to estimate
alignment parameters
=head1 EXAMPLES
With a single paired-end illumina library:
a5_pipeline.pl <read1.fastq> <read2.fastq> <output directory or basename>
With two or more libraries:
a5_pipeline.pl <library file> <output directory or basename>
=head1 AUTHORS
Andrew Tritt <[email protected]>
Aaron Darling <[email protected]>
=head1 AVAILABILITY
http://ngopt.googlecode.com
=head1 COPYRIGHT
Copyright 2010, 2011
This software is licensed under the terms of the GPLv3
=cut
use constant {
IDBA_MIN_K => 29,
# IDBA_MAX_K => 89,
IDBA_MAX_K => 90,
SGA_Q_TRIM => 10,
SGA_Q_FILTER => 20,
SGA_MIN_READ_LENGTH => 29,
};
my $AVAILMEM = 4000000;
my $def_up_id="upReads";
my @KEYS = ("id","p1","p2","shuf","up","rc","ins","err","nlibs","libfile");
my $pname = basename($0);
my $usage= qq{
Usage: $pname [--begin=1-5] [--end=1-5] [--preprocessed] [--debug] <lib_file> <out_base>
Or: $pname <Read 1 FastQ> <Read 2 FastQ> <out_base>
Or: $pname <Read 1,2 Interleaved FastQ> <out_base>
<out_base> is the base file name for all output files. When assembling from
a single library, the fastq files may be given directly on the command line.
If using more than one library, a library file must be given as <lib_file>.
The library file must contain the filenames of all read files.
If --preprocessed is used, <lib_file> is expected to be the library file
created during step 2 of the pipeline, named <out_base>.preproc.libs. Note
that this flag only applies if beginning pipeline after step 2.
};
die $usage if ! @ARGV;
Getopt::Long::Configure(qw{no_auto_abbrev no_ignore_case_always pass_through});
my $start = 1;
my $end = 5;
my $preproc = 0;
my $debug = 0;
my $nthread = 4;
GetOptions( 'begin=i' => \$start,
'end=i' => \$end,
'preprocessed' => \$preproc,
'debug' => \$debug,
'thread=i' => \$nthread);
die $usage if (@ARGV < 2);
$AVAILMEM = get_availmem();
#
# Check that java is available and in the path
#
my $java = `which java`;
die "Unable to find a java runtime environment. The A5 pipeline requires java 6 or later. Please ensure that java is installed and in the \$PATH" unless length($java)>1;
my $libfile = $ARGV[0];
my $OUTBASE = $ARGV[1];
# check whether command-line input was FastQ files or a library file
if(@ARGV==3){
# assume the user provided two FastQ files instead of a library file
$OUTBASE = $ARGV[2];
open(TMPLIBFILE, ">$OUTBASE.tmplibs");
print TMPLIBFILE "[LIB]\n";
print TMPLIBFILE "p1=$ARGV[0]\n";
print TMPLIBFILE "p2=$ARGV[1]\n";
close TMPLIBFILE;
$libfile = "$OUTBASE.tmplibs";
} else {
$OUTBASE = $ARGV[1];
my $file = $ARGV[0];
my $file_type = `file $file`;
my $first_line = "";
if ($file_type =~ /gzip/){
$first_line = `gunzip -c $file | head -n 1`;
} elsif ($file_type =~ /bzip2/) {
$first_line = `bunzip2 -c $file | head -n 1`;
} else {
$first_line = `head -n 1 $file`;
}
if ($first_line =~ /^@/){ # assume interleaved
open(TMPLIBFILE, ">$OUTBASE.tmplibs");
print TMPLIBFILE "[LIB]\n";
print TMPLIBFILE "shuf=$ARGV[0]\n";
close TMPLIBFILE;
$libfile = "$OUTBASE.tmplibs";
} elsif ($first_line =~ /^\[LIB\]/) {
$libfile = $ARGV[0];
} else {
print STDERR "$file is neither a library file nor a fastq file.\n";
exit;
}
}
my $start_millis = time();
my @start_date = localtime();
$start_date[5] += 1900;
print STDERR "[a5] Begin: $start_date[2]:$start_date[1] on $start_date[4]-$start_date[3]-$start_date[5]\n";
my $DIR = dirname(abs_path($0));
# Format for output of time resource statistics
my $TIME_FMT = "###PROCESS\n".
"%C\n".
"###\n".
"%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata %Mmax)k\n".
"%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps";
my $STAT_FILE = "$OUTBASE.res_stat";
my $TIME = "/usr/bin/time -o $STAT_FILE -a -f $TIME_FMT ";
if ($debug){
open(FILE,">>$STAT_FILE");
print FILE "BEGIN A5 PIPELINE: $start_date[2]:$start_date[1] on $start_date[4]-$start_date[3]-$start_date[5]\n";
close FILE;
}
# An extension to give unzipped files.
my $UNZIP_EXT = "a5unzipped";
my %RAW_LIBS = read_lib_file($libfile);
print STDERR "[a5] Found the following libraries:\n";
print_lib_info(\%RAW_LIBS);
for my $lib (keys %RAW_LIBS){
for my $att (keys %{$RAW_LIBS{$lib}}){
$RAW_LIBS{$lib}{$att} = check_and_unzip($RAW_LIBS{$lib}{$att}) if ($att eq "p1" || $att eq "p2" || $att eq "shuf");
if ($att eq "shuf"){
my ($fq1, $fq2) = split_shuf($RAW_LIBS{$lib}{$att},"$OUTBASE.".$RAW_LIBS{$lib}{"id"});
$RAW_LIBS{$lib}{"p1"} = $fq1;
$RAW_LIBS{$lib}{"p2"} = $fq2;
}
}
}
die "[a5] No libraries found in $libfile\n" unless(keys %RAW_LIBS);
print "[a5] Found ".scalar(keys %RAW_LIBS)." libraries\n";
my $maxrdlen = -1;
my $scafs;
my $ctgs;
my $reads;
my $WD="$OUTBASE";
print "[a5] Starting pipeline at step $start\n";
if ($start <= 1) {
print "[a5] Cleaning reads with SGA\n";
print STDERR "[a5] Cleaning reads with SGA\n";
$WD="$OUTBASE.s1";
mkdir($WD) if ! -d $WD;
$reads = sga_clean($OUTBASE, \%RAW_LIBS);
$reads = tagdust($OUTBASE, $reads);
`mv $reads $OUTBASE.ec.fastq`;
`rm $WD/*.fastq`;
`rm $WD/*.ec.fa`;
}
if ($end == 1){
print STDERR "[a5] Done cleaning reads. Results at $OUTBASE.ec.fastq\n";
exit;
}
if ($start <= 2) {
my $fq_reads = "$OUTBASE.ec.fastq";
if (-f "$fq_reads.gz" && ! -f "$fq_reads") {
`gunzip $fq_reads.gz`;
}
$reads = $fq_reads;
die "[a5_s2] Can't find error corrected reads $reads" unless -f $reads;
print "[a5_s2] Building contigs from $reads with IDBA\n";
print STDERR "[a5_s2] Building contigs from $reads with IDBA\n";
$WD="$OUTBASE.s2";
mkdir($WD) if ! -d $WD;
($reads, $maxrdlen) = fastq_to_fasta($reads,"$WD/$OUTBASE.ec.fasta");
die "[a5] error: max read length = $maxrdlen\n" if $maxrdlen <= 0;
# `gzip -f $fq_reads`;
$ctgs = idba_assemble($OUTBASE, $reads, $maxrdlen);
`rm $reads`;
open (my $filtered, ">", "$OUTBASE.contigs.fasta");
open (IN,"<",$ctgs);
while (my $hdr = <IN>){
my $seq = <IN>;
chomp $seq;
next if (length($seq) < 2*$maxrdlen);
print $filtered $hdr.$seq."\n";
}
close $filtered;
# `rm $ctgs`;
#`mv $ctgs $OUTBASE.contigs.fasta`;
}
if ($end == 2){
print STDERR "[a5] Done building contigs. Results at $OUTBASE.contigs.fasta\n";
exit;
}
$WD="$OUTBASE.s3";
mkdir($WD) if ! -d $WD;
my %PAIR_LIBS;
if (!$preproc || $start <= 2){
print STDERR "[a5] Preprocess libraries for scaffolding with SSPACE\n";
%PAIR_LIBS = preprocess_libs(\%RAW_LIBS,"$OUTBASE.contigs.fasta");
print STDERR "[a5] Processed libraries:\n";
print_lib_info(\%PAIR_LIBS);
# clean up any files we unzipped files if the raw input was compressed
my @unzipped = glob("*.$UNZIP_EXT");
for my $file (@unzipped){
print STDERR "[a5] Removing unzipped file $file\n";
# `rm $file`;
}
} else {
print STDERR "[a5] Libraries already preprocessed\n" if ($preproc);
%PAIR_LIBS = %RAW_LIBS;
delete($PAIR_LIBS{$def_up_id}) if (defined($PAIR_LIBS{$def_up_id}));
}
if ($start <= 3) {
$ctgs = "$OUTBASE.contigs.fasta";
die "[a5_s3] Can't find starting contigs $ctgs.\n" unless -f $ctgs;
print "[a5_s3] Scaffolding contigs from $ctgs with SSPACE\n";
print STDERR "[a5_s3] Scaffolding contigs from $ctgs with SSPACE\n";
$scafs = scaffold_sspace($OUTBASE, \%PAIR_LIBS, $ctgs);
`mv $scafs $OUTBASE.crude.scaffolds.fasta`;
}
if ($end == 3){
print STDERR "[a5] Done building crude scaffolds. Results at $OUTBASE.crude.scaffolds.fasta\n";
exit;
}
my $need_qc = 1;
if ($start <= 4) {
my $prev_scafs = "$OUTBASE.crude.scaffolds.fasta";
$scafs = $prev_scafs;
die "[a5_s4] Can't find starting crude scaffolds $scafs\n" unless -f $scafs;
print "[a5_s4] Detecting and breaking misassemblies in $scafs with A5QC\n";
print STDERR "[a5_s4] Detecting and breaking misassemblies in $scafs with A5QC\n";
$WD="$OUTBASE.s4";
mkdir($WD) if ! -d $WD;
$scafs = break_all_misasms($prev_scafs,\%PAIR_LIBS,"$OUTBASE.qc");
if ($scafs eq $prev_scafs){
$need_qc = 0;
`cp $scafs $OUTBASE.final.scaffolds.fasta`;
print "[a5_s5] No misassemblies found.\n";
} else {
`mv $scafs $OUTBASE.broken.scaffolds.fasta`;
}
}
if ($end == 4){
print STDERR "[a5] Done running QC. ";
if ($need_qc){
print STDERR " Results at $OUTBASE.broken.scaffolds.fasta\n";
} else {
print STDERR " No misassemblies detected.";
}
exit;
}
if ($start <= 5 && $need_qc) {
$scafs = "$OUTBASE.broken.scaffolds.fasta";
die "[a5_s5] Can't find starting broken scaffolds $scafs\n" unless -f $scafs;
print "[a5_s5] Scaffolding broken contigs with SSPACE\n";
print STDERR "[a5_s5] Scaffolding broken contigs with SSPACE\n";
$WD="$OUTBASE.s5";
mkdir($WD) if ! -d $WD;
$scafs = scaffold_sspace("$OUTBASE.rescaf",\%PAIR_LIBS,$scafs,1);
`mv $scafs $OUTBASE.final.scaffolds.fasta`;
}
if ($end == 5){
print "[a5] Final assembly in $OUTBASE.final.scaffolds.fasta\n";
}
my $end_millis = time();
my $diff = $end_millis - $start_millis;
$diff = int($diff/1000);
my $hrs = int($diff/3600);
my $min = int(($diff % 3600)/60);
my $sec = int($diff % 60);
my @end_date = localtime();
$end_date[5] += 1900;
print STDERR "[a5] Finish: $end_date[2]:$end_date[1] $end_date[4]-$end_date[3]-$end_date[5]\n";
print STDERR "[a5] Took $hrs:$min:$sec to complete\n";
if ($debug){
open(FILE,">>$STAT_FILE");
print FILE "END A5 PIPELINE: $end_date[2]:$end_date[1] on $end_date[4]-$end_date[3]-$end_date[5]\n";
print FILE "TOTAL WALL CLOCK RUNTIME: $hrs:$min:$sec\n";
close FILE;
}
#
# Begin subroutines
#
#
=item get_availmem
Reads total installed memory in a platform-dependent way
=cut
sub get_availmem {
my $mem = 4000000;
if ($^O =~ m/darwin/) {
my $inf = `/usr/sbin/system_profiler SPHardwareDataType | grep Memory`;
if ($inf =~ / Memory: (\d+) GB/){
$mem = $1 * 1048576;
}
} else {
my $inf = `cat /proc/meminfo | grep MemTotal`;
if ($inf =~ /MemTotal:\s+(\d+) kB/){
$mem = $1;
}
}
return $mem
}
=item
Read a single entry from an Illumina-platform generated FastQ file, and removed the paired
read id (e.g. "/1") from the end of the read id
=cut
sub readFastqEntry {
my $bufref = shift;
my $infile = shift;
my %buf = %$bufref;
my $name = <$infile>;
my $barename = $name;
chomp($barename);
$barename =~ s/\/\d$//g; # trim off paired read id
$buf{$barename} = $name;
$buf{$barename} .= <$infile>; # seq line
$buf{$barename} .= <$infile>; # qual name line
$buf{$barename} .= <$infile>; # qual seq line
return $barename;
}
=item
3-read sequencing protocols can set the paired read ID to /3 instead of /2
and some softwares don't like this
=cut
sub fix_read_id {
my $fastq = shift;
my $expected_id = shift;
open( FQ, $fastq );
my $line = <FQ>;
chomp $line;
$line =~ /\/(\d+)$/;
my $id = $1;
if(defined($id) && $id != $expected_id){
# swap in the correct read id
print STDERR "[a5] Swapping read identifier from $id to $expected_id\n";
open( NEWFQ, ">$fastq.newid.fastq");
close FQ;
open( FQ, $fastq );
while(my $line = <FQ>){
$line =~ s/^(@.+)\/$id$/$1\/$expected_id/g;
print NEWFQ $line;
}
return "$fastq.newid.fastq";
}
return $fastq;
}
=item qfilter_paired_easy
Preprocess paired reads with SGA by filtering and quality trimming. Discard unpaired reads.
=cut
sub qfilter_paired_easy {
my $r1file = shift;
my $r2file = shift;
my $r1file_in = $r1file;
my $r2file_in = $r2file;
my $r1file_out = "$r1file.pp";
my $r2file_out = "$r2file.pp";
my $cmd = "sga preprocess -q ".SGA_Q_TRIM." -f ".SGA_Q_FILTER." -m ".SGA_MIN_READ_LENGTH." --permute-ambiguous --pe-mode=1 ";
$cmd .= "--phred64 " if (get_phred64($r1file_in));
$cmd .= " $r1file_in $r2file_in";
print STDERR "[a5] $cmd\n";
open(R1OUT, ">$r1file_out");
open(R2OUT, ">$r2file_out");
$cmd = "$DIR/$cmd";
$cmd = $TIME.$cmd if $debug;
open(PPPIPE, "$DIR/$cmd |");
my $lc = -1;
while( my $line = <PPPIPE> ){
$lc++;
print R1OUT $line if( $lc % 8 < 4 );
print R2OUT $line if( $lc % 8 >= 4 );
}
}
=item qfilter_correct_tagdust_paired
Preprocesses paired reads with SGA by filtering low quality reads, quality trimming,
and discarding unpaired reads. After preprocessing reads, error corrects reads and
removes potential contaminants using TagDust.
Takes 4 parameters: $r1file, $r2file, $t, and $lib
where
$r1file = read 1 in paired reads
$r2file = read 2 in paired reads.
$t = the number of threads to use when running SGA
$lib = the library name to use for output generating throughout this subroutine
=cut
sub qfilter_correct_tagdust_paired {
my $r1file = shift;
my $r2file = shift;
my $t = shift;
my $lib = shift;
# quality filter
my $pp_cmd = "sga preprocess -q ".SGA_Q_TRIM." -f ".SGA_Q_FILTER." -m ".SGA_MIN_READ_LENGTH." --permute-ambiguous --pe-mode=1 ";
$pp_cmd .= "--phred64 " if (get_phred64($r1file));
$pp_cmd .= " $r1file $r2file > $r1file.both.pp";
print STDERR "[a5] $pp_cmd\n";
$pp_cmd = "$DIR/$pp_cmd";
$pp_cmd = $TIME.$pp_cmd if $debug;
run($pp_cmd);
# error correct
my $ec_cmd = "sga correct -t $t -p $OUTBASE.pp -o $r1file.both.pp.ec.fastq $r1file.both.pp > $WD/$lib.correct.out";
print STDERR "[a5] $ec_cmd\n";
$ec_cmd = "$DIR/$ec_cmd";
$ec_cmd = $TIME.$ec_cmd if $debug;
run($ec_cmd);
run("rm -rf $r1file.both.pp"); # clear up some disk space
# tagdust and repair
my $td_cmd = "tagdust -s $DIR/../adapter.fasta -o $r1file.both.pp.ec.tagdust.fastq $r1file.both.pp.ec.fastq";
print STDERR "[a5] $td_cmd\n";
$td_cmd = "$DIR/$td_cmd";
$td_cmd = $TIME.$td_cmd if $debug;
run($td_cmd);
run("rm -rf $r1file.both.pp.ec.fastq"); # clear up some disk space
my $lc = -1;
my $prev_read = "";
my $prev_record = "";
open(R1OUT, ">$r1file.pp.ec.fastq");
open(R2OUT, ">$r2file.pp.ec.fastq");
open(TDPIPE, "$r1file.both.pp.ec.tagdust.fastq");
while( my $line = <TDPIPE> ){
$lc++;
if($lc%4 != 0){
$prev_record .= $line;
next;
}
if($prev_read eq ""){
$prev_read = $line;
$prev_record = $line;
next;
}
# we're at a header line and we have a previous FastQ record loaded
chomp $prev_read;
$prev_read =~ s/\/\d$//g;
my $cur_read = $line;
chomp $cur_read;
$cur_read =~ s/\/\d$//g;
# read the rest of the current FastQ entry
my $cur_record = $line;
$cur_record .= <TDPIPE>;
$cur_record .= <TDPIPE>;
$cur_record .= <TDPIPE>;
$lc += 3;
# if records are paired, write them out
# otherwise ignore the previous entry
if($cur_read eq $prev_read){
print R1OUT $prev_record;
print R2OUT $cur_record;
$prev_record = "";
$prev_read = "";
}else{
$prev_record = $cur_record;
$prev_read = $line;
}
}
close R1OUT;
close R2OUT;
run("rm -rf $r1file.both.pp.ec.tagdust.fastq"); # clear up some disk space
}
=item get_phred64
Returns whether or not the given FastQ file has phred64 quality scores
=cut
sub get_phred64 {
my $fastq = shift;
my $phred64 = 0;
my @lines = `head -n 1000 $fastq`;
@lines = @lines[map { $_*4 + 3 } 0 .. int($#lines/4)];
foreach my $qline (@lines) {
chomp $qline;
for my $q (split(//, $qline)) {
if (ord($q) < 64) {
return 0;
} elsif ($q > 'J') {
return 1;
}
}
}
return $phred64;
}
=item sga_clean
Clean reads using SGA. Multi-thread if running in linux environment.
Takes two parameters: an basename for output, $outbase, and a reference to a hash storing library information, $libsref.
First, error correct all reads together to prepare for building contigs using IDBA. To do so, this function passes all
fastq files into the following command:
sga preprocess -q SGA_Q_TRIM -f SGA_Q_FILTER -m SGA_MIN_READ_LENGTH --permute-ambiguous <fastq1> <fastq2> . . . <fastqN>
applying the --phred64 flag to sga if phred-64 quality scores are detected, and writing preprocessed reads to $outbase.pp.fastq.
$outbase.pp.fastq is indexed using the following command:
sga index -d 0.5*AVAL_SYSTEM_MEMORY -t <n_threads> $outbase.pp.fastq
$outbase.pp.fastq is error corrected using the following command:
sga correct -t <n_threads> -o $outbase.pp.ec.fa $outbase.pp.fastq
For the indexing and correcting step, n_threads is to 1 if running in a Macintosh environment, 4 otherwise.
Second, for each paired library in $libsref, error correct reads from each library individually for scaffolding using
the qfilter_correct_tagdust_paired function.
=cut
sub sga_clean {
my $outbase = shift;
my $libsref = shift;
my %libs = %$libsref;
# OS X is missing some required multithreading gadgetry for SGA
my $t = $^O =~ m/darwin/ ? 1 : 4;
$t = $nthread if $nthread;
# figure out which files we need to pass to SGA
my $files = "";
my $tail_file = "";
for my $lib (keys %libs) {
if (defined($libs{$lib}{"p1"})) {
my $fq1 = $libs{$lib}{"p1"};
my $fq2 = $libs{$lib}{"p2"};
$tail_file = $fq1 unless length($tail_file);
$files .= "$fq1 $fq2 ";
}
if (defined($libs{$lib}{"up"})){
my $up = $libs{$lib}{"up"};
$tail_file = $up unless length($tail_file);
$files .= "$up ";
}
}
my $phred64 = get_phred64($tail_file);
# preprocess the reads with SGA -- quality trim and filter
# pipe in the reads so we can count how many passed the filter for each file
my $cmd = "sga preprocess -q ".SGA_Q_TRIM." -f ".SGA_Q_FILTER." -m ".SGA_MIN_READ_LENGTH." --permute-ambiguous ";
$cmd .= "--phred64 " if ($phred64);
$cmd .= " $files >$WD/$outbase.pp.fastq";
$cmd = "$DIR/$cmd";
$cmd = $TIME.$cmd if $debug;
run("$cmd");
die "[a5] Error preprocessing reads with SGA\n" if( $? != 0 );
# build a bwt index for all of the reads
my $sga_ind = "";
my $sga_ind_kb = $AVAILMEM/4;
my $err_file = "$WD/index.err";
do{
$cmd = "sga index -d ".($sga_ind_kb)." -t $t $WD/$outbase.pp.fastq > $WD/index.out 2> $err_file";
print STDERR "[a5] $cmd\n";
$cmd = "$DIR/$cmd";
$cmd = $TIME.$cmd if $debug;
$sga_ind = `$cmd`;
$sga_ind = read_file($err_file);
$sga_ind_kb = int($sga_ind_kb/2);
}while(($sga_ind =~ /bad_alloc/ || $? != 0) && $sga_ind_kb > 500000);
#
# error correct the entire set of reads
my $ec_file = "$WD/$outbase.pp.ec.fa";
run("rm -f core*") if (-f "core*");
die "[a5] Error indexing reads with SGA\n" if( $? != 0 );
$cmd = "sga correct -t $t -o $ec_file $WD/$outbase.pp.fastq > $WD/correct.out";
print STDERR "[a5] $cmd\n";
# `rm $WD/$OUTBASE.pp.*` if (-f "$WD/$OUTBASE.pp.*");
# `rm $OUTBASE.pp.*` if (-f "$OUTBASE.pp.*");
$cmd = "$DIR/$cmd";
$cmd = $TIME.$cmd if $debug;
run("$cmd");
#
# error correct individual paired-end libraries
for my $lib (keys %libs) {
next unless defined($libs{$lib}{"p1"});
my $ec1 = $libs{$lib}{"p1"};
my $ec2 = $libs{$lib}{"p2"};
# bwa and sga require paired reads to have /1 and /2
# make sure our reads have that
$libsref->{$lib}{"p1"} = fix_read_id($ec1,1);
$libsref->{$lib}{"p2"} = fix_read_id($ec2,2);
# clean these reads!
qfilter_correct_tagdust_paired($ec1, $ec2, $t, $lib);
}
die "[a5] Error correcting reads with SGA\n" if( $? != 0 );
return $ec_file;
}
=item check_and_unzip
Check if the given file is zipped up. If it is, unzip and return the file it was unzipped to.
=cut
sub check_and_unzip {
my $file = shift;
my $file_type = `file $file`;
my $ret = $file;
if ($file_type =~ /gzip/){
$ret = "$file.$UNZIP_EXT";
`gunzip -c $file > $ret`;
} elsif ($file_type =~ /bzip2/) {
$ret = "$file.$UNZIP_EXT";
`bunzip2 -c $file > $ret`;
}
return $ret;
}
=item map_all_libs
Maps all librarie back to the final scaffolds generated by the A5 pipeline.
Takes two parameters: $outbase, $libsref
where
$outbase = the basename for output files generated throughout this subroutine
$libsref = a hash storing information on all the libraries passed in.
=cut
sub map_all_libs {
my $outbase = shift;
my $libsref = shift;
my %libs = %$libsref;
my $index_cmd = "bwa index $OUTBASE.final.scaffolds.fasta";
print STDERR "[a5] $index_cmd\n";
$index_cmd = "$DIR/$index_cmd";
$index_cmd = $TIME.$index_cmd if $debug;
run($index_cmd);
for my $lib (keys %libs) {
if (defined($libs{$lib}{"p1"})) {
my $fq1 = $libs{$lib}{"p1"};
my $fq2 = $libs{$lib}{"p2"};
my $aln1_cmd = "bwa aln $OUTBASE.final.scaffolds.fasta $fq1 > $fq1.sai";
my $aln2_cmd = "bwa aln $OUTBASE.final.scaffolds.fasta $fq2 > $fq2.sai";
my $sampe_cmd = "bwa sampe $OUTBASE.final.scaffolds.fasta $fq1.sai $fq2.sai $fq1 $fq2 | $DIR/samtools view -b -S - | $DIR/samtools sort - $lib.pe";
my $bamindex_cmd = "samtools index $lib.pe.bam";
print STDERR "[a5] $aln1_cmd\n";
$aln1_cmd = "$DIR/$aln1_cmd";
$aln1_cmd = $TIME.$aln1_cmd if $debug;
run($aln1_cmd);
print STDERR "[a5] $aln2_cmd\n";
$aln2_cmd = "$DIR/$aln2_cmd";
$aln2_cmd = $TIME.$aln2_cmd if $debug;
run($aln2_cmd);
print STDERR "[a5] $sampe_cmd\n";
$sampe_cmd = "$DIR/$sampe_cmd";
$sampe_cmd = $TIME.$sampe_cmd if $debug;
run($sampe_cmd);
print STDERR "[a5] $bamindex_cmd\n";
$bamindex_cmd = "$DIR/$bamindex_cmd";
$bamindex_cmd = $TIME.$bamindex_cmd if $debug;
run($bamindex_cmd);
# `rm $fq1.sai $fq2.sai`;
}
if (defined($libs{$lib}{"up"})){
my $up = $libs{$lib}{"up"};
my $aln1_cmd = "bwa aln $OUTBASE.final.scaffolds.fasta $up > $up.sai";
my $samse_cmd = "bwa sampe $OUTBASE.final.scaffolds.fasta $up.sai $up | $DIR/samtools view -b -S - | $DIR/samtools sort - $lib.up";
my $bamindex_cmd = "samtools index $lib.up.bam";
print STDERR "[a5] $aln1_cmd\n";
$aln1_cmd = "$DIR/$aln1_cmd";
$aln1_cmd = $TIME.$aln1_cmd if $debug;
run($aln1_cmd);
print STDERR "[a5] $samse_cmd\n";
$samse_cmd = "$DIR/$samse_cmd";
$samse_cmd = $TIME.$samse_cmd if $debug;
run($samse_cmd);
print STDERR "[a5] $bamindex_cmd\n";
$bamindex_cmd = "$DIR/$bamindex_cmd";
$bamindex_cmd = $TIME.$bamindex_cmd if $debug;
run($bamindex_cmd);
# `rm $up.sai`;
}
}
}
=item read_lib_file
Parses the library file, returning the given information stored in a hash.
Takes a singled parameter: $libfile, the path to the library file to be parsed.
Returns a hash of hashes index as such: $hash{$library}{$component}
where $component = 'up' || 'p1' || 'p2' || 'ins' || 'id'
=cut
sub read_lib_file {
my $libfile = shift;
my %libs = ();
open(LIB,"<",$libfile);
my $lib_count = 0;
my $id = "";
my %hash = ();
while(<LIB>){
chomp;
if ($_ =~ m/\[LIB\]/){
if ($lib_count > 0) {
$libs{$id}{"id"} = $id;
for my $key (keys %hash){
$libs{$id}{$key} = $hash{$key};
delete($hash{$key});
}
}
$lib_count++;
$id = "raw$lib_count";
} elsif ($_ =~ m/id=([\w\/\-\.]+)/) {
$id = $1;
} elsif ($_ =~ m/(\w+)=([\w\/\-\.]+)/) {
$hash{$1} = $2;
} else {
die "[a5] Unrecognizable line in library file: >$_<\n";
}
}
$libs{$id}{"id"} = $id;
for my $key (keys %hash){
$libs{$id}{$key} = $hash{$key};
}
return %libs;
}
=item read_file
Read in entire file, returning its contents as a single string.
=cut
sub read_file {
my $file = shift;
local $/=undef;
open(FILE,"<",$file);
my $str = <FILE>;
return $str;
}
=item fastq_to_fasta
Convert a fastq file to fasta.
=cut
sub fastq_to_fasta {
my $fastq = shift;
my $fasta = shift;
my $maxrdlen = 0;
open(FQ,"<$fastq");
open(FA,">$fasta");
while(my $hdr = <FQ>) {
my $seq = <FQ>;
my $qhdr = <FQ>;
my $qseq = <FQ>;
$hdr =~ s/^@/>/g;
print FA $hdr.$seq;
$maxrdlen = length($seq) if length($seq) > $maxrdlen;
}
close FA;
# why are we removing 2 here?
return ($fasta, $maxrdlen - 2); # -1 removes newline char
}
=item split_shuif
Splits a shuffled (a.k.a. interleaved) fastq file into two separate fastq files.
Takes two parameters: $shuf, $outbase
where
$shuf = the shuffled fastq file to split
$outbase = the basename for the two fastq files resulting from splitting $shuf. The two files output
are $outbase_p1.fastq and $outbase_p2.fastq
=cut
sub split_shuf {
my $shuf = shift;
my $outbase = shift;
my $fq1 = "$outbase\_p1.fastq";
my $fq2 = "$outbase\_p2.fastq";
print STDERR "[a5] Splitting shuffled file $shuf into $fq1 and $fq2\n";
open(FQ1,">$fq1");
open(FQ2,">$fq2");
open(IN,"<$shuf");
while(my $hdr = <IN>){
my $seq = <IN>;
my $qhdr = <IN>;
my $qual = <IN>;
print FQ1 "$hdr"."$seq"."$qhdr"."$qual";
$hdr = <IN>;
$seq = <IN>;
$qhdr = <IN>;
$qual = <IN>;
print FQ2 "$hdr"."$seq"."$qhdr"."$qual";
}
close FQ1;
close FQ2;
return ($fq1, $fq2);
}
=item tagdust
Run TagDust to remove any Illumina artifacts. The sequences for the artifact sequences must be stored in $DIR/../adapter.fasta,
where $DIR is the location of this executable.
Takes two parameters: $outbase, $readsfile
where
$outbase = the basename for output generated throughout this subroutine
$readsfile = the path to the file containing the reads for remove artifact from.
=cut
sub tagdust {
my $outbase = shift;
my $readfile = shift;
my $tagdust_cmd = "tagdust -s -o $WD/$outbase.dusted.fq $DIR/../adapter.fasta $readfile";
print STDERR "[a5] $tagdust_cmd\n";
$tagdust_cmd = "$DIR/$tagdust_cmd";
$tagdust_cmd = $TIME.$tagdust_cmd if $debug;
run("$tagdust_cmd");
return "$WD/$outbase.dusted.fq";
}
=item idba_assemble
Assemble reads using IDBA.
Takes 3 parameters: $outbase, $reads, $maxrdlen
where
$outbase = the basename for output generated throughout this subroutine
$reads = the path to the file containing the reads to assemble into contigs
$maxrdlen = the maximum kmer to iterate up to.
=cut
sub idba_assemble {
my $outbase = shift;
my $reads = shift;
my $maxrdlen = shift;
my $idba_choice = ($maxrdlen > 128) ? "idba_ud.256 --num_threads $nthread -r" : 'idba -r';
my $ret_choice = ($maxrdlen > 128) ? "$WD/$outbase/contig.fa" : "$WD/$outbase-contig.fa";
$maxrdlen = IDBA_MAX_K if $maxrdlen > IDBA_MAX_K; # idba seems to break if the max k gets too big
my $idba_cmd = "$idba_choice $reads -o $WD/$outbase --mink ".IDBA_MIN_K." --maxk $maxrdlen";
# my $idba_cmd = "idba -r $reads -o $WD/$outbase --mink ".IDBA_MIN_K." --maxk $maxrdlen";
print STDERR "[a5] $idba_cmd\n";
$idba_cmd = "$DIR/$idba_cmd";
$idba_cmd = $TIME.$idba_cmd if $debug;
`$idba_cmd > $WD/idba.out`;
die "[a5] Error building contigs with IDBA\n" if ($? != 0);
# `rm $WD/$outbase.kmer $WD/$outbase.graph`;
# return "$WD/$outbase-contig.fa";
# return "$WD/$outbase/contig.fa";
return $ret_choice;
}
=item scaffold_sspace
Scaffold contigs using SSPACE.
Takes 3 or 4 parameters: $outbase, $libsref, $curr_ctgs, $rescaffold (optional)
where
$outbase = the basename for output generated throughout this subroutine
$libsref = a hash storing information on all the libraries passed in.
$curr_ctgs = the contigs to scaffold
$rescaffold = a binary value indicating whether or not we are scaffolding our assembly
for the first time (i.e. scaffolding contigs generated from IDBA), indicated
by a 0, or if we are scaffolding for the second time (i.e. scaffolding
scaffolds broken by the A5qc algorithm), indicated by a 1.
Returns the contigs resulting from scaffolding.
=cut
sub scaffold_sspace {
my $outbase = shift;
# build library file
my $libsref = shift;
my %libs = %$libsref;
my $curr_ctgs = shift;
my $rescaffold = shift;
my @library_file = ();
my @lib_files;
my $genome_size = get_genome_size($curr_ctgs);
print STDERR "[a5] Total contig length $genome_size\n";
my $libraryI=1;
my @curr_lib_file = ();
my $curr_ins = -1;
my %run_lib;
$rescaffold=0 unless defined($rescaffold);
# sort library.txt to so that we scaffold with smaller insert libraries first
for my $lib (sort { $libs{$a}{"ins"} <=> $libs{$b}{"ins"} } keys %libs) {
my ($exp_link, $cov) = calc_explinks( $genome_size, $libs{$lib}{"ins"}, $libs{$lib}{"p1"} );
printf STDERR "[a5] %s\: Insert %.0f, coverage %.2f, expected links %.0f\n", $libs{$lib}{"id"}, $libs{$lib}{"ins"}, $cov, $exp_link;
# if (-f "$OUTBASE.unpaired.fastq") { # run sspace with unpaired library if we have one
if (-f "$WD/$OUTBASE.ec.fa") { # run sspace with unpaired library if we have one
$curr_ctgs = run_sspace($genome_size, $libs{$lib}{"ins"}, $exp_link, $outbase.".".$libs{$lib}{"id"},
# $libs{$lib}{"libfile"}, $curr_ctgs, $rescaffold, "$OUTBASE.unpaired.fastq");
$libs{$lib}{"libfile"}, $curr_ctgs, $rescaffold, "$WD/$OUTBASE.ec.fa");
} else {
$curr_ctgs = run_sspace($genome_size, $libs{$lib}{"ins"}, $exp_link, $outbase.".".$libs{$lib}{"id"},
$libs{$lib}{"libfile"}, $curr_ctgs, $rescaffold);
}
}
return $curr_ctgs;
}
=item preprocess_libs
Process a library hash generated with the read_lib_file subroutine. For each library, check to see
if an error corrected version exists, and swap that into the hash if so. Then, do initial insert size
estimates for each library. After estimating insert sizes, merge libraries with similar insert size distributions
using the subroutine aggregate_libs. Insert size distributions are deemed similiar if their calculated ranges overlap.
If two libraries are merged, the insert size of the resulting merged libarary is recalculated. Lastly, for each library,
create a library file for SSPACE>
Takes 2 parameters: $libsref, $ctgs
where
$libsref = a hash storing information on all the libraries passed in.
$ctgs = contigs to use to estimate insert sizes
Returns a new library hash containing insert size calculations and new library information for merged libraries.
=cut
sub preprocess_libs {
my $libsref = shift;
my %libs = %$libsref;
my $ctgs = shift;
if (-f "$OUTBASE.unpaired.fastq"){
print STDERR "[a5] Removing unpaired reads $OUTBASE.unpaired.fastq\n";