forked from StevenWingett/FastQ-Screen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastq_screen
executable file
·2735 lines (2241 loc) · 106 KB
/
fastq_screen
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/perl
use warnings;
use strict;
use Getopt::Long;
use FindBin qw($RealBin);
use File::Copy;
use File::Spec;
use File::Basename;
use File::Temp qw/ tempfile tempdir /;
use Cwd;
use File::Path;
use Data::Dumper;
our $VERSION = "0.16.0";
###########################################################################
###########################################################################
## ##
## Copyright 2024, Simon Andrews (The Babraham Institute, UK) ##
## Steven Wingett (MRC-LMB, Cambridge, UK) ##
## Felix Krueger (The Babraham Institute, UK) ##
## Mark Fiers (Plant & Food Research, NZ) ##
## Martin Pollard (Wellcome Sanger Institute, UK) ##
## ##
## This program is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## (at your option) any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <http://www.gnu.org/licenses/>. ##
###########################################################################
###########################################################################
unless (@ARGV) { #Display a help message if no arguments specified
print while (<DATA>);
exit(0);
}
## Option variables
my $subset_count;
my $outdir;
my $illumina;
my $quiet;
my $help;
my $version;
my $threads;
my $conf;
my $bowtie_opts;
my $bowtie2_opts;
my $bismark_opts;
my $bwa_opts;
my $minimap2_opts;
my $nohits;
my $zip_data_output = 0;
my $aligner;
my $force;
my $paired;
my $bisulfite;
my $tag;
my $filter;
my $top;
my $skip = 0; #Specified via $top variable
my $pass;
my $inverse = 0;
my $get_genomes;
my $add_genome;
my $config_result = GetOptions(
"subset=i" => \$subset_count,
"outdir=s" => \$outdir,
"illumina1_3" => \$illumina,
"quiet" => \$quiet,
"help" => \$help,
"version" => \$version,
"conf=s" => \$conf,
"bowtie=s" => \$bowtie_opts,
"bowtie2=s" => \$bowtie2_opts,
"bismark=s" => \$bismark_opts,
"bwa=s" => \$bwa_opts,
"minimap2=s" => \$minimap2_opts,
"threads=i" => \$threads,
"nohits" => \$nohits,
"aligner=s" => \$aligner,
"force" => \$force,
"paired" => \$paired,
"bisulfite" => \$bisulfite,
"tag" => \$tag,
"filter=s" => \$filter,
"top=s" => \$top,
"pass=i" => \$pass,
"inverse" => \$inverse,
"get_genomes" => \$get_genomes,
"add_genome=s" => \$add_genome,
);
die "Could not parse options, please adjust configuration.\n" unless ($config_result);
if ($help) {
print while (<DATA>);
exit(0);
}
if ($version) {
print "FastQ Screen v$VERSION\n";
exit(0);
}
if(defined $add_genome){ #Add a genome to the configuration file
my @terms_to_add = split(/,/, $add_genome);
unless(scalar @terms_to_add == 3 ){ #Check three entries passed
warn "Add 3 terms to --add_genome as a comma separated list:\n";
die "'Database name','Genome path and basename','Notes'\n";
}
unless(-e "$RealBin/fastq_screen.conf"){
warn "File 'fastq_screen.conf not found in '$RealBin'\n";
die "Please add this file and try again.\n";
}
unless(-w "$RealBin/fastq_screen.conf"){
warn "File '$RealBin/fastq_screen.conf' is not writable\n";
die "Please change file permissions and try again.\n";
}
#Edit input to conform to fastq_screen.conf file structure
$terms_to_add[0] = "DATABASE\t$terms_to_add[0]";
$terms_to_add[2] = '#' . $terms_to_add[2];
my $string_for_file = "\n$terms_to_add[2]\n$terms_to_add[0]\t$terms_to_add[1]\n";
my $command = "echo '$string_for_file' >> $RealBin/fastq_screen.conf";
!system($command) or die "Could not edit '$RealBin/fastq_screen.conf'\n";
print "Added genome $terms_to_add[0] to '$RealBin/fastq_screen.conf\n'";
exit(0);
}
if ( defined $outdir ) {
unless ( -d $outdir ) {
warn "Output directory '$outdir' does not exist, creating directory\n";
mkdir $outdir or die "Could not create '$outdir'\n";
}
unless ( -w $outdir ) {
die "Output directory '$outdir' is not writable, please adjust configuration.\n";
}
$outdir = File::Spec->rel2abs($outdir); #Get absolute path
} else {
$outdir = getcwd;
}
$outdir .= '/'; #Add trailing forward slash, so don't need to do this again
if(defined $get_genomes){
get_genomes();
exit(0);
}
# Identify input files
my @files = get_paths(@ARGV);
foreach my $file (@files) {
if ( $file =~ /\.gz$/ ) {
$zip_data_output = 1;
last;
}
}
if(defined $filter){
die "Option --filter not in the correct format, see --help for more details.\n" unless($filter =~ /^[012345-]+$/);
die "Option --filter may not contain only hyphens '-'\n" if($filter =~ /^-+$/);
if(!defined $tag){
process_tag_files(@files);
warn "Filtering complete.\n" unless ($quiet);
exit (0);
}
}
if(defined $pass){
die "Option --pass may only be used in conjunction with --filter" unless(defined $filter);
die "Option --pass needs to be at least one." if($pass < 1);
my $non_active_filters = ($filter =~ tr/-//); #Count number of hyphens
my $filters_applied = (length $filter) - $non_active_filters;
if($pass > $filters_applied){
warn "Option --pass requires a read to pass $pass filters, but only $filters_applied active filters by '$filter'\n";
die "Please adjust configuration\n";
}
}
if($inverse != 0){
die "Option --inverse may only be used in conjunction with --filter" unless(defined $filter);
}
if (defined $aligner) {
$aligner = lc $aligner;
if ( ( $aligner ne 'bowtie' ) and ( $aligner ne 'bowtie2' ) and ($aligner ne 'bwa') and ($aligner ne 'minimap2') ) {
die "Valid options for --aligner are 'bowtie', 'bowtie2', 'bwa' or 'minimap2' only.\n";
} elsif ( ( $aligner eq 'bowtie' ) and ( defined $bowtie2_opts ) ) {
die "Bowtie selected as the aligner yet bowtie2 options specified.\n";
} elsif ( ( $aligner eq 'bowtie' ) and ( defined $bwa_opts ) ) {
die "Bowtie selected as the aligner yet BWA options specified.\n";
} elsif ( ( $aligner eq 'bowtie' ) and ( defined $minimap2_opts ) ) {
die "Bowtie selected as the aligner yet minimap2 options specified.\n";
} elsif ( ( $aligner eq 'bowtie2' ) and ( defined $bowtie_opts ) ) {
die "Bowtie 2 selected as the aligner yet bowtie options specified.\n";
} elsif ( ( $aligner eq 'bowtie2' ) and ( defined $bwa_opts ) ) {
die "Bowtie 2 selected as the aligner yet BWA options specified.\n";
} elsif ( ( $aligner eq 'bowtie2' ) and ( defined $minimap2_opts ) ) {
die "Bowtie 2 selected as the aligner yet minimap2 options specified.\n";
} elsif ( ( $aligner eq 'bwa' ) and ( defined $bowtie_opts ) ) {
die "BWA selected as the aligner yet Bowtie options specified.\n";
} elsif ( ( $aligner eq 'bwa' ) and ( defined $bowtie2_opts ) ) {
die "BWA selected as the aligner yet Bowtie 2 options specified.\n";
} elsif ( ( $aligner eq 'bwa' ) and ( defined $minimap2_opts ) ) {
die "BWA selected as the aligner yet minimap2 options specified.\n";
} elsif ( ( $aligner eq 'minimap2' ) and ( defined $bwa_opts ) ) {
die "minimap2 selected as the aligner yet BWA options specified.\n";
} elsif ( ( $aligner eq 'minimap2' ) and ( defined $bowtie_opts ) ) {
die "minimap2 selected as the aligner yet Bowtie options specified.\n";
} elsif ( ( $aligner eq 'minimap2' ) and ( defined $bowtie2_opts ) ) {
die "minimap2 selected as the aligner yet Bowtie 2 options specified.\n";
}
}
if( (defined $bismark_opts) and (!defined $bisulfite) ){
die "Option --bismark may not be specified without --bisulfite\n";
}
$bowtie_opts = '' unless (defined $bowtie_opts); # Get undef warnings otherwise
$bowtie2_opts = '' unless (defined $bowtie2_opts);
$bwa_opts = '' unless (defined $bwa_opts);
$bismark_opts = '' unless (defined $bismark_opts);
$minimap2_opts = '' unless (defined $minimap2_opts);
# Configuration
my $number_of_threads = 1;
my $path_to_bowtie = `which bowtie 2>/dev/null` eq '' ? undef : `which bowtie`;
chomp $path_to_bowtie if(defined $path_to_bowtie);
my $path_to_bowtie2 = `which bowtie2 2>/dev/null` eq '' ? undef : `which bowtie2`;
chomp $path_to_bowtie2 if(defined $path_to_bowtie2);
my $path_to_bismark = `which bismark 2>/dev/null` eq '' ? undef : `which bismark`;
chomp $path_to_bismark if(defined $path_to_bismark);
my $path_to_bwa = `which bwa 2>/dev/null` eq '' ? undef : `which bwa`;
chomp $path_to_bwa if(defined $path_to_bwa);
my $path_to_minimap2 = `which minimap2 2>/dev/null` eq '' ? undef : `which minimap2`;
chomp $path_to_minimap2 if(defined $path_to_minimap2);
my $path_to_samtools = `which samtools 2>/dev/null` eq '' ? undef : `which samtools`;
chomp $path_to_samtools if(defined $path_to_samtools);
my @libraries;
warn "Using fastq_screen v$VERSION\n" unless ($quiet);
if ($paired) {
warn "Attention: option --paired removed in fastq_screen v0.5.0, processing data in single-end mode\n";
}
if(!defined $aligner and $bisulfite){
warn "Defaulting to Bowtie 2 for --bisulfite mode\n" unless ($quiet);
$aligner = 'bowtie2';
}
load_configuration($conf);
# Override the configuration default if they've
# manually specified a number of threads to use
$number_of_threads = $threads if ($threads);
warn "Using $number_of_threads threads for searches\n" unless ($quiet);
unless (@libraries) {
die "No reference genomes were configured, please adjust configuration.\n";
}
if(defined $nohits){
if( (defined $tag) or (defined $filter) ){
die "Option --nohits may not be specified with --filter/--tag.\n";
}
$tag = 1;
$filter = 0 x scalar(@libraries);
warn "Option --nohits specified, setting --tag and --filter $filter\n" unless ($quiet);
}
if(defined $top){
($top, $skip) = split(/,/, $top);
$skip = 0 unless($skip); #Prevent initialisation errors
unless( ($top =~ /^\d+$/) and ($skip =~ /^\d+$/) ){
die "Option --top may only be passed <int> or <int>,<int>.\n";
}
die "Option --top may not be set to 0" if($top == 0);
die "Specify either --subset or --top, but not both.\n" if(defined $subset_count);
$subset_count = $top; #For reporting numbers to standard out
}
if ( defined $tag ) {
unless ( defined $subset_count ) {
$subset_count = 0; #Process all reads
}
}
$subset_count = 100_000 unless ( defined $subset_count ); #Subset needs to be after nohits and tag so that it will be set to 0
if(defined $top){
if($skip){
warn "Skipping first $skip reads then extracting top $top reads from the sequence file(s)\n" unless ($quiet);
} else {
warn "Extracting top $top reads from the sequence file(s)\n" unless ($quiet);
}
} elsif ($subset_count) {
warn "Option --subset set to $subset_count reads\n" unless ($quiet);
} else {
warn "Option --subset set to 0: processing all reads in FASTQ files\n" unless ($quiet);
}
if ( ( ( 1 << 32 ) != 4294967296 ) and ( scalar @libraries > 15 ) ) { #32-bit
die "Maximum number of reference genomes exceeded for 32-bit Perl, please adjust configuration and specify at most 15 libraries.\n";
} elsif ( scalar @libraries > 32 ) { #64-bit
die "Maximum number of reference genomes exceeded, please adjust configuration and specify at most 32 libraries.\n";
}
die "No files to process\n" unless (@files);
my $index = 0;
while ( $index <= $#files ) {
process_file( $files[$index] );
$index++;
}
sub process_file {
my ($file) = @_;
my $initial_filename = $file; #Used later in program
my @index_genomes; # Stores the hits to each genome
my @bisulfite_orientation; #Stores strand in bisulfite mode
#@Genome->@(count of OT, CTOT, CTOB, OB)
for(my $i = 0; $i < scalar(@libraries); $i++){ #Intialise array
$bisulfite_orientation[$i] = [0, 0, 0, 0];
}
warn "Processing " . basename($file) . "\n" unless ($quiet);
# Check that we can actually find the files we're working with
unless ( -e $file ) {
warn "Couldn't locate file $file - skipping\n";
return;
}
# Check the output file names we're going to generate don't already exist
if ( !$force and check_outfilename($file) ) { #check_outfilename returns 1 if there is a problem
warn "\tSkipping " . basename($file) . "\n";
return;
}
# We can try to remove the end specific part of the name
# if they're using standard Illumina naming. It doesn't
# really matter if this fails
my $outfile = basename($file);
$outfile = $outdir . $outfile;
$outfile =~ s/\.gz$//;
$outfile =~ s/\.(txt|seq|fastq|fq)$//i;
$outfile .= "_screen.txt";
open( RESULTS_OUT, '>', $outfile ) or do {
warn "Couldn't write to $outfile: $!";
return;
};
#Print out the Version and other information to the output file
print RESULTS_OUT "#Fastq_screen version: $VERSION\t";
if($bisulfite){
print RESULTS_OUT "#Aligner: Bismark/$aligner\t";
}else{
print RESULTS_OUT "#Aligner: $aligner\t";
}
if ($subset_count) {
if(defined $top){
print RESULTS_OUT "#Processed $top reads from top of file after skipping $skip reads\n";
} else {
print RESULTS_OUT "#Reads in subset: $subset_count\n";
}
} else {
print RESULTS_OUT "#Processing all reads in FASTQ files\n";
}
#Print the headers to the output file
print RESULTS_OUT join( "\t", ( 'Genome', '#Reads_processed', '#Unmapped', '%Unmapped', '#One_hit_one_genome', '%One_hit_one_genome', '#Multiple_hits_one_genome', '%Multiple_hits_one_genome', '#One_hit_multiple_genomes', '%One_hit_multiple_genomes', 'Multiple_hits_multiple_genomes', '%Multiple_hits_multiple_genomes' ) ), "\n";
my $temp_file;
my $read_length = get_read_length($file);
if ( $read_length < 0 ) {
warn 'Failed to calculate read length from ' . basename($file) . "\n";
return;
}
if ( $read_length < 20 ) {
warn "Ignoring reads shorter than 20bp\n";
$read_length = 20;
}
# We don't use a seed of >40 even if the reads are that long
$read_length = 40 if ( $read_length > 40 );
# Count the sequences in the file.
# We need to make a subset of these sequences
# First we need to count how many sequences are in the original file
my $seqcount = 0;
unless($top){
if ($subset_count) {
warn "Counting sequences in " . basename($file) . "\n" unless ($quiet);
}
#Check if the read file is compressed and open accordingly
if ( $file =~ /\.gz$/ ) {
open( IN_COUNT, "gunzip -c \'$file\' |" ) or do {
warn "Can't read $file: $!";
return;
};
} else {
open( IN_COUNT, $file ) or do {
warn "Can't read $file: $!";
return;
};
}
++$seqcount while (<IN_COUNT>);
$seqcount = int( $seqcount / 4 );
close IN_COUNT or die "Cannot close filehandle on '$file' : $!";
}
my $interval;
my $readsprocessed;
$temp_file = basename($file);
$temp_file = $outdir . $temp_file . "_temp_subset.fastq";
if($top){
$interval = 1;
$readsprocessed = subset( $file, $temp_file, $interval );
} elsif ( $subset_count and $seqcount > $subset_count * 2 ) { # We actually need to do the reduction
$interval = sprintf( "%.0f", ( $seqcount / $subset_count ) );
warn "Making reduced sequence file with ratio $interval:1\n" unless ($quiet);
$readsprocessed = subset( $file, $temp_file, $interval );
} else { #Make new indexed file with no reduction
$interval = 1;
if ($subset_count) {
warn "Not making subset of $subset_count since $seqcount actual sequences is too low or close enough\n" unless ($quiet);
$readsprocessed = subset( $file, $temp_file, $interval ); #Interval is 1, so TEMP file has same number of reads as original
} else {
warn "Not making data subset\n" unless ($quiet);
$readsprocessed = subset( $file, $temp_file, $interval ); #Still need to make temp file, since headers adjusted in temp file
}
}
if($readsprocessed == 0){
if(defined $top){
warn "No reads in " . basename($file) . " (perhaps adjusting --top setting would correct this), skipping\n";
} else {
warn "No reads in " . basename($file) . ", skipping\n";
}
return;
}
$file = $temp_file;
my $library_index = -1; # Make lists in the same order as @libraries
foreach my $library (@libraries) {
#Write Bowtie/Bowtie2 Standard Error to a temporary output file
#Generate a random filename and place in $outdir (if specified)
my $error_fh;
my $error_filename;
if ($outdir) {
( $error_fh, $error_filename ) = tempfile( 'aligner_standard_error.XXXXXXXX', SUFFIX => '.txt', DIR => $outdir );
} else {
( $error_fh, $error_filename ) = tempfile( 'aligner_standard_error.XXXXXXXX', SUFFIX => '.txt' );
}
warn "Searching " . basename($file) . " against $library->[0]\n" unless ($quiet);
my $illumina_flag = '';
if($illumina){
$illumina_flag = '--phred64-quals';
}
#Count the index of the library being used
$library_index++;
if ($bisulfite) {
die "The aligners BWA or minimap2 may not be used in --bisulfite mode, please adjust configuration.\n" if(($aligner eq 'bwa') or ($aligner eq 'minimap2'));
bisulfite_mapping( $illumina_flag, $library, $file, $error_filename, $library_index, $error_fh, \@index_genomes, \@bisulfite_orientation );
} else {
conventional_mapping( $illumina_flag, $read_length, $library, $file, $error_filename, \@index_genomes, $library_index, $error_fh );
}
}
# Collate the hit results from the Bowtie searches.
# Result categories are:
# 0 - read not map to library
# 1 - read maps uniquely to this library but maps to no others
# 2 - read multi-maps to this library but maps to no others
# 3 - read maps uniquely to this library and maps to at least one other library
# 4 - read multi-maps to this library and maps to at least one other library
my @one_hit_one_library;
my @one_hit_multiple_libraries;
my @multiple_hits_one_library;
my @multiple_hits_multiple_libraries;
# Initialise those arrays with zero values, making them the same length as @libraries
for my $position ( 0 .. $#libraries ) { #$position is 0-based
$one_hit_one_library[$position] = 0;
$one_hit_multiple_libraries[$position] = 0;
$multiple_hits_one_library[$position] = 0;
$multiple_hits_multiple_libraries[$position] = 0;
}
for my $val (@index_genomes) {
if ( !defined $val ) { #May not be defined, but later elements in array may be defined
$val = 0;
next;
}
for my $position ( 0 .. $#libraries ) {
my $mapping_result = maps_which_library( $val, $position + 1 ); #maps_which_library uses 1-based numbering for libraries
if ( $mapping_result == 0 ) {
next; #Did not map to this genome
} elsif ( $mapping_result == 1 ) {
$one_hit_one_library[$position]++;
} elsif ( $mapping_result == 2 ) {
$multiple_hits_one_library[$position]++;
} elsif ( $mapping_result == 3 ) {
$one_hit_multiple_libraries[$position]++;
} elsif ( $mapping_result == 4 ) {
$multiple_hits_multiple_libraries[$position]++;
}
}
}
# Summarise the counts and write the text report
foreach my $index ( 0 .. $#libraries ) {
my $library = $libraries[$index];
my $percent_one_hit_one_library = calc_perc($one_hit_one_library[$index], $readsprocessed);
my $percent_one_hit_multiple_libraries = calc_perc($one_hit_multiple_libraries[$index], $readsprocessed);
my $percent_multiple_hits_one_library = calc_perc($multiple_hits_one_library[$index], $readsprocessed);
my $percent_multiple_hits_multiple_libraries = calc_perc($multiple_hits_multiple_libraries[$index], $readsprocessed);
my $percent_unmapped;
if($percent_one_hit_one_library eq 'NA'){ #No reads processed
$percent_unmapped = 'NA';
} else {
$percent_unmapped = 100 - $percent_one_hit_one_library - $percent_one_hit_multiple_libraries - $percent_multiple_hits_one_library - $percent_multiple_hits_multiple_libraries;
$percent_unmapped = sprintf( "%.2f", $percent_unmapped );
}
my $reads_unmapped = $readsprocessed - $one_hit_one_library[$index] - $one_hit_multiple_libraries[$index] - $multiple_hits_one_library[$index] - $multiple_hits_multiple_libraries[$index];
print RESULTS_OUT join( "\t", ( $library->[0], $readsprocessed, $reads_unmapped, $percent_unmapped, $one_hit_one_library[$index], $percent_one_hit_one_library, $multiple_hits_one_library[$index], $percent_multiple_hits_one_library, $one_hit_multiple_libraries[$index], $percent_one_hit_multiple_libraries, $multiple_hits_multiple_libraries[$index], $percent_multiple_hits_multiple_libraries ) ), "\n";
}
#Calculate the number of reads that mapped to none of the libraries
my $hit_no_genomes = $readsprocessed; #Number of reads in temp file
foreach my $val (@index_genomes) {
$hit_no_genomes-- if ($val); #This read mapped to at least one genome
}
my $percent_hit_no_libraries = calc_perc($hit_no_genomes, $readsprocessed);
print RESULTS_OUT "\n\%Hit_no_genomes: $percent_hit_no_libraries\n";
if($bisulfite and ($hit_no_genomes != $readsprocessed) ){ #Add additional bisulfite orientation results, providing at least one reads mapped to any genome
print RESULTS_OUT "\n\n";
print RESULTS_OUT "#Bisulfite read orientation results\n";
print RESULTS_OUT "Library\t";
print RESULTS_OUT "#Original_top_strand\t%Original_top_strand\t";
print RESULTS_OUT "#Complementary_to_original_top_strand\t%Complementary_to_original_top_strand\t";
print RESULTS_OUT "#Complementary_to_original_bottom_strand\t%Complementary_to_original_bottom_strand\t";
print RESULTS_OUT "#Original_bottom_strand\t%Original_bottom_strand\n";
foreach my $index ( 0 .. $#libraries ) {
my $library = $libraries[$index];
my $ot = $bisulfite_orientation[$index]->[0];
my $ctot = $bisulfite_orientation[$index]->[1];
my $ctob = $bisulfite_orientation[$index]->[2];
my $ob = $bisulfite_orientation[$index]->[3];
my $total = $ot + $ctot + $ctob + $ob;
next unless($total); #No reads mapped to bisulfite genome
my $pc_ot = sprintf( "%.2f", ($ot / $total * 100) );
my $pc_ctot = sprintf( "%.2f", ($ctot / $total * 100) );
my $pc_ctob = sprintf( "%.2f", ($ctob / $total * 100) );
my $pc_ob = sprintf( "%.2f", ($ob / $total * 100) );
print RESULTS_OUT "$library->[0]\t$ot\t$pc_ot\t$ctot\t$pc_ctot\t$ctob\t$pc_ctob\t$ob\t$pc_ob\n";
}
}
#close IN or die "Cannot close filehandle : $!";
close RESULTS_OUT or die "Cannot close filehandle on '$outfile' : $!";
if(defined $tag){
tag_reads(\@index_genomes, $file, $outfile);
}
if(defined $filter){
my $tagged_filename = $outfile;
$tagged_filename =~ s/_screen.txt$//;
$tagged_filename .= '.tagged.fastq';
$tagged_filename .= '.gz' if ($zip_data_output);
warn "Filtering " . basename($tagged_filename) . "\n" unless($quiet);
process_tag_files($tagged_filename);
}
unlink($temp_file) or warn "Unable to delete temp file '$temp_file'" if ($temp_file);
#Check whether the module GD::Graph is installed
eval {
require GD::Graph::bars;
GD::Graph::pie->import();
};
unless ($@) {
make_graph($outfile);
if($bisulfite){
make_bisulfite_graph($outfile);
}
} else {
warn "Perl module GD::Graph::bars not installed, skipping charts\n";
}
#Make HTML report (this could be performed above, but code neater if kept as a separate subroutine)
make_html($initial_filename);
}
#Tag files are processed and a filter file is produced
#Takes an array of the files to process
sub process_tag_files{
my @files = get_paths(@_);
my $filter_string = $filter;
warn "Filtering files with filter '$filter'\n" unless ($quiet);
foreach my $file (@files){
warn "Filtering " . basename($file) . "\n" unless ($quiet);
my $outfile = basename($file);
$outfile = $outdir . $outfile;
$outfile =~ s/\.gz$//;
$outfile =~ s/\.(txt|seq|fastq|fq)$//i;
$outfile .= "_filter.fastq";
$outfile .= '.gz' if ($zip_data_output);
if(-e $outfile and !$force){ #When only filtering file (i.e. not mapping/tagging) this check will not have been performed already
warn "Output file '" . basename($outfile) . "' already exists\n";
warn "Skipping " . basename($outfile) . "\n";
next;
}
if($file =~ /\.gz$/){
open (IN_PROCESS_TAG, "gunzip -c $file |") or die "Could not read file '$file' : $!";
$zip_data_output = 1; #Output will be zipped
} else{
open (IN_PROCESS_TAG, '<', $file) or die "Could not read file '$file' : $!";
}
if ($zip_data_output) { #Declared outside of subroutine
open( OUT_PROCESS_TAG, "| gzip -c - > $outfile" ) or die "Couldn't write to file '$outfile' : $!";
} else {
open( OUT_PROCESS_TAG, ">$outfile" ) or die "Could not write to '$outfile' : $!";
}
my $filter_description = ''; #Print out the filter description to the first line of the filtered file (may not be first line of tagged file)
my $printed_description_flag = 0;
my $first_read = 1;
while(<IN_PROCESS_TAG>){
my $header = $_;
my $rest_of_read = scalar <IN_PROCESS_TAG>;
$rest_of_read .= scalar <IN_PROCESS_TAG>;
$rest_of_read .= scalar <IN_PROCESS_TAG>;
my $pass_filter_flag = pass_filter_data($header);
$pass_filter_flag = abs($pass_filter_flag - $inverse); #Invert the filter: 0->1, 1->0
if($first_read){
if($pass_filter_flag){ #Print read as is
print OUT_PROCESS_TAG $header . $rest_of_read;
$printed_description_flag = 1;
} else {
$header =~ /#?.+(#.+?):\d+$/;
$filter_description = $1;
}
} else {
if($pass_filter_flag){
if($printed_description_flag){
print OUT_PROCESS_TAG $header . $rest_of_read; #Print as is
} else { #Edit to incorporate tag description
my $modified_header = $header;
$modified_header =~ s/#FQST/$filter_description/;
print OUT_PROCESS_TAG $modified_header . $rest_of_read;
$printed_description_flag = 1;
}
}
}
$first_read = 0;
}
close IN_PROCESS_TAG or die "Could not close filehandle on " . basename($file) . " : $!";
close OUT_PROCESS_TAG or die "Could not close filehandle on " . basename($outfile) . ": $!";
}
}
warn "Processing complete\n" unless ($quiet);
exit (0);
#####################################################################################################
#Subroutines
#####################################################################################################
#Takes an input filename and uses global parameter variables to check
#whether potential outfiles already exist.
#Returns 1 if at least one potential outfile already exists, else returns 0
sub check_outfilename {
my $file = $_[0];
my $outfile = basename($file);
$outfile = $outdir . $outfile;
my $parameters_problem = 0; #Set to 0 if outpufile already exists and force option not selected
if ( -e $outfile . "_temp_subset.fastq") {
warn "Temporary subset file '" . basename($outfile) . "_temp_subset.fastq' already exists\n";
$parameters_problem = 1;
}
$outfile =~ s/\.gz$//;
$outfile =~ s/\.(txt|seq|fastq|fq)$//i;
$outfile .= "_screen.png";
if ( -e $outfile ) {
warn "\tOutput graphics file '" . basename($outfile) . "' already exists\n";
$parameters_problem = 1;
}
$outfile =~ s/_screen\.png$/_screen\.html/;
if ( -e $outfile ) {
warn "\tOutput HTML file '" . basename($outfile) . "' already exists\n";
$parameters_problem = 1;
}
$outfile =~ s/_screen\.html$/_screen\.txt/;
if ( -e $outfile ) {
warn "\tOutput file '" . basename($outfile) . "' already exists\n";
$parameters_problem = 1;
}
if($tag){
$outfile =~ s/_screen\.txt$/\.tagged\.fastq/;
$outfile .= '.gz' if($zip_data_output);
if ( -e $outfile ) {
warn "\tOutput file '" . basename($outfile) . "' already exists\n";
$parameters_problem = 1;
}
if(defined $filter){
$outfile =~ s/\.gz$//;
$outfile =~ s/\.(txt|seq|fastq|fq)$//i;
$outfile .= "_filter.fastq";
$outfile .= '.gz' if ($zip_data_output);
if ( -e $outfile ) {
warn "\tOutput file '" . basename($outfile) . "' already exists\n";
$parameters_problem = 1;
}
}
}
if ($bisulfite) { #Identify temp files made
my $bisulfite_graphfile = basename($file);
$bisulfite_graphfile =~ s/\.gz$//;
$bisulfite_graphfile =~ s/\.(txt|seq|fastq|fq)$//i;
$bisulfite_graphfile = $outdir . '/' . $bisulfite_graphfile;
$bisulfite_graphfile .= "_screen.bisulfite_orientation.png";
if ( -e $bisulfite_graphfile) {
warn "\tOutput bisulfite graphics file '" . basename($bisulfite_graphfile) . "' already exists\n";
$parameters_problem = 1;
}
my $original_file = basename($file);
my $subset_file = basename($file) . '_temp_subset.fastq';
foreach my $myFile ( $original_file, $subset_file ) {
$myFile =~ s/(\.fastq\.gz|\.fq\.gz|\.fastq|\.fq)$//; #attempting to remove fastq.gz etc to make filename a little shorter
foreach my $library (@libraries) {
my $genome_name = $library->[0];
my $bismark_temp_file = "$genome_name.$myFile";
if ( $aligner eq 'bowtie' ) {
$bismark_temp_file .= '_bismark';
} else {
$bismark_temp_file .= '_bismark_bt2';
}
if ( defined $path_to_samtools ) {
$bismark_temp_file .= '.bam';
} else {
$bismark_temp_file .= '.sam';
}
$bismark_temp_file = $outdir . $bismark_temp_file;
my $bismark_temp_report_file = $bismark_temp_file;
$bismark_temp_report_file =~ s/\.sam$|\.bam$/_SE_report.txt/;
if ( -e $bismark_temp_file ) {
warn "\tBismark potential temporary output file '" . basename($bismark_temp_file) . "' already exists\n";
$parameters_problem = 1;
}
if ( -e $bismark_temp_report_file ) {
warn "\tBismark potential temporary report file '" . basename($bismark_temp_report_file) . "' already exists\n";
$parameters_problem = 1;
}
}
}
}
if ($parameters_problem) {
return 1;
} else {
return 0;
}
}
#Takes a FASTQ filename and generates an HTML summary report by reading the
#relevant summary file already produced by FastQ Screen
sub make_html{
my $file = $_[0];
my $summary_file = basename($file);
$summary_file = $outdir . $summary_file;
$summary_file =~ s/\.gz$//;
$summary_file =~ s/\.(txt|seq|fastq|fq)$//i;
$summary_file .= "_screen.txt";
#Read in summary file
open (SUMMARY, '<', $summary_file) or die "Could not open '$summary_file' for creating HTML summary report: $!";
my ($version, $aligner, $subset) = split(/\t/, scalar <SUMMARY>);
$version =~ s/^#Fastq_screen version: //;
$aligner =~ s/^#Aligner: //;
$subset =~ s/^#Reads in subset: //;
scalar <SUMMARY>; #Ignore column headers
my @data;
my @bisulfite_data; #The following variables will only be used in bisulfite mode
while(<SUMMARY>){
my $line = $_;
chomp $line;
next if($line =~ /^\s*$/);
if( ($line eq '#Bisulfite read orientation results') or (scalar (@bisulfite_data)) ){ #In bisulfite region
push(@bisulfite_data, $line);
}else{
push(@data, $line);
}
}
close SUMMARY or die "Could not close filehandle on '$summary_file' when creating HTML summary report: $!";
my $bisulfite_table_string;
my $bisulfite_species_string = '';
my $pc_ot = '';
my $pc_ctot = '';
my $pc_ctob = '';
my $pc_ob = '';
if(scalar @bisulfite_data){ #Contains bisulfite data
@bisulfite_data = splice(@bisulfite_data, 2); #Remove header rows
my $table_string = '';
foreach my $element (@bisulfite_data){
my @sub_elements = split(/\t/, $element);
$bisulfite_table_string .= "\t\t\t<tr>\n";
$bisulfite_table_string .= "\t\t\t\t<td>" . commify($sub_elements[0]) . "</td>\n";
$bisulfite_table_string .= "\t\t\t\t<td>" . commify($sub_elements[1]) . "</td>\n";
$bisulfite_table_string .= "\t\t\t\t<td>" . commify($sub_elements[3]) . "</td>\n";
$bisulfite_table_string .= "\t\t\t\t<td>" . commify($sub_elements[5]) . "</td>\n";
$bisulfite_table_string .= "\t\t\t\t<td>" . commify($sub_elements[7]) . "</td>\n";
$bisulfite_table_string .= "\t\t\t</tr>\n";
$bisulfite_species_string .= "'" . $sub_elements[0] . "', ";
$pc_ot .= $sub_elements[2] . ", ";
$pc_ctot .= $sub_elements[4] . ", ";
$pc_ctob .= $sub_elements[6] . ", ";
$pc_ob .= $sub_elements[8] . ", ";
}
$bisulfite_table_string =~ s/^\t\t\t//; #Remove tabs already in file
$bisulfite_species_string =~ s/, $//; #Remove trailing characters
$pc_ot =~ s/, $//;
$pc_ctot =~ s/, $//;
$pc_ctob =~ s/, $//;
$pc_ob =~ s/, $//;
}
#Make HTML table
my $pc_hit_no_genomes = pop(@data);
$pc_hit_no_genomes =~ s/^%Hit_no_genomes: //;
my $datestamp = datestampGenerator();
my $table_string = '';
my @species;
my @pc_one_hit_one_genome;
my @pc_multiple_hits_one_genome;
my @pc_one_hit_multiple_genomes;
my @pc_multiple_hits_multiple_genomes;
my $graph_height = 100 * ((scalar @data) + 1);
$graph_height = 500 if($graph_height < 500);
foreach my $element (@data){
my @sub_elements = split(/\t/, $element);
$table_string .= "\t\t\t<tr>\n";
$table_string .= "\t\t\t\t<td><b>" . commify($sub_elements[0]) . "</b></td>\n";
$table_string .= "\t\t\t\t<td>" . commify($sub_elements[1]) . "</td>\n";
$table_string .= "\t\t\t\t<td>" . commify($sub_elements[2]) . "</td>\n";
$table_string .= "\t\t\t\t<td>" . commify($sub_elements[4]) . "</td>\n";
$table_string .= "\t\t\t\t<td>" . commify($sub_elements[6]) . "</td>\n";
$table_string .= "\t\t\t\t<td>" . commify($sub_elements[8]) . "</td>\n";
$table_string .= "\t\t\t\t<td>" . commify($sub_elements[10]) . "</td>\n";
$table_string .= "\t\t\t</tr>\n";
push(@species, $sub_elements[0]);
push(@pc_one_hit_one_genome, $sub_elements[5]);
push(@pc_multiple_hits_one_genome, $sub_elements[7]);
push(@pc_one_hit_multiple_genomes, $sub_elements[9]);
push(@pc_multiple_hits_multiple_genomes, $sub_elements[11]);
}
my $pc_one_hit_one_genome_string = join(', ', @pc_one_hit_one_genome) . ', 0';
my $pc_multiple_hits_one_genome_string = join(', ', @pc_multiple_hits_one_genome) . ', 0';
my $pc_one_hit_multiple_genomes_string = join(', ', @pc_one_hit_multiple_genomes) . ', 0';
my $pc_multiple_hits_multiple_genomes_string = join(', ', @pc_multiple_hits_multiple_genomes) . ', 0';
#Hover required for nice editing of graphs
my $hoverinfo_samples = '';
my $hoverinfo_nohits = '';
my $hover_pc_one_hit_one_genome_string = create_hover_string(@pc_one_hit_one_genome);
my $hover_pc_multiple_hits_one_genome_string = create_hover_string(@pc_multiple_hits_one_genome);
my $hover_pc_one_hit_multiple_genomes_string = create_hover_string(@pc_one_hit_multiple_genomes);
my $hover_pc_multiple_hits_multiple_genomes_string = create_hover_string(@pc_multiple_hits_multiple_genomes);
my $species_string = '';
my $nohits_string = $pc_hit_no_genomes;
my $hover_nohits_string = "'" . $nohits_string ."'";
my $hover_info_bisulfite_samples = '';
foreach my $species (@species){
$species_string .= "'" . $species . "', ";
$hoverinfo_samples .= "'text', ";
$hover_info_bisulfite_samples .= "'text', ";
$hoverinfo_nohits .= "'skip', ";
$nohits_string = "0, " . $nohits_string;
$hover_nohits_string = "'0', " . $hover_nohits_string;
}
$species_string .= "'Hit_No_Genomes'";
$hoverinfo_samples .= "'skip'";
$hoverinfo_nohits .= "'text'";
$hover_info_bisulfite_samples = substr( $hover_info_bisulfite_samples, 0, (length($hover_info_bisulfite_samples) - 2) ); #Remove trailing comma and space
#Read in template file
my $html_string = '';
open (TEMPLATE, '<', "$RealBin/fastq_screen_summary_template.html") or die "Could not open HTML summary template : $!";
while(<TEMPLATE>){
$html_string .= $_;
}
close TEMPLATE or die "Could not close filehandle on HTML summary template: $!";