forked from hugp-ri/hicup-plus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
hicup_mapper
executable file
·1315 lines (1086 loc) · 54.8 KB
/
hicup_mapper
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 strict;
use warnings;
use Time::HiRes;
use Getopt::Long;
use POSIX ":sys_wait_h"; #for nonblocking read
use POSIX;
use IPC::Open2;
use IPC::Open3;
use IO::Select;
use FindBin '$Bin';
use lib $Bin;
use File::Basename;
use Sys::Hostname;
use hicup_module;
use hicup_module qw(hashVal checkAligner checkAlignerIndices
determineAlignerFormat quality_checker);
use Data::Dumper;
###################################################################################
###################################################################################
##This file is Copyright (C) 2023, Steven Wingett ##
## ##
## ##
##This file is part of HiCUP. ##
## ##
##HiCUP 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. ##
## ##
##HiCUP 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 HiCUP. If not, see <http://www.gnu.org/licenses/>. ##
###################################################################################
###################################################################################
###################################################################################
###################################################################################
## ##
## This file has been modified to support the following aligners ##
## Dragen, HiSAT2, STAR ##
## ##
## HiCUP+ (HiCUP-Plus) ##
## Maintained by S. Thomas Kelly (simonthomas.kelly [at] hugp [dot] com) ##
## ##
## Changes: additional input parameters for additional aligners ##
## verbose log output for debugging ##
## add aligner calls for HiSAT2 and Dragen ##
## skip counting reads too short to map for Dragen ##
## report results for HiSaT2 using same parameters as Bowtie2 ##
## skip logs from stdout with Dragen ##
## run Dragen with a system call and print logs to files ##
## parse Dragen mapping statistics from log files ##
## initialise values and correct whitespace to allow debugging ##
## initialise reverse read and match by header strings ##
## ##
###################################################################################
###################################################################################
#Option variables
my %config = (
bowtie => '',
bowtie2 => '',
dragen => '',
hisat2 => '',
star => '',
config => '',
datestamp => '',
example => '',
format => '',
index => '',
ligation => '',
help => '',
outdir => '',
quiet => '',
samtools => '',
threads => '',
version => '',
r => '',
zip => ''
);
my $config_result = GetOptions(
"bowtie=s" => \$config{bowtie},
"bowtie2=s" => \$config{bowtie2},
"dragen=s" => \$config{dragen},
"hisat2=s" => \$config{hisat2},
"star=s" => \$config{star},
"config=s" => \$config{config},
"datestamp=s" => \$config{datestamp},
"example" => \$config{example},
"format=s" => \$config{format},
"index=s" => \$config{index},
"ligation=s" => \$config{ligation}, #Hidden flag to pass ligation details from HiCUP so hicup_truncater header can be included in the SAM file
"outdir=s" => \$config{outdir},
"help" => \$config{help},
"quiet" => \$config{quiet},
"threads=i" => \$config{threads},
"version" => \$config{version},
"r=s" => \$config{r},
"samtools=s" => \$config{samtools},
"zip" => \$config{zip}
);
die "Could not parse options.\n" unless ($config_result);
$config{help} = 1 unless ( hashVal(%config) ); #Print help and exit if no command line parameters
if ( $config{help} ) {
print while (<DATA>);
exit(0);
}
#Print version and exit
if ( $config{version} ) {
print "HiCUP+ Mapper v$hicup_module::VERSION\n";
exit(0);
}
if ( $config{example} ) {
print_example_config_file('mapper_example.conf');
exit(0);
}
if ( $config{datestamp} eq '' ) {
$config{datestamp} = datestampGenerator();
}
my @filenames;
if ( hasval( $config{config} ) ) {
@filenames = process_config( $config{config}, \%config ); #Modifies %config and returns an array of the filenames
if ( scalar @filenames % 2 ) {
die "There needs to be an even number of files in the configuration file, see hicup --help for more details.\n";
}
}
if (@ARGV) {
if ( scalar @ARGV % 2 ) {
die "There needs to be an even number of files specified in the command line, see hicup_mapper --help for more details.\n";
}
push( @filenames, @ARGV ); #Add filenames specified in the command line to those in the configuration file
}
unless ( check_files_exist( \@filenames, 'EXISTS' ) ) {
die "Please adjust configuration.\n";
}
my %files = @filenames; #%files : hash of paired forward and reverse files
##########################################################
#Check user-supplied parameters are ok
unless ( check_parameters() ) {
die "Please change configuration file and/or command-line parameters and/or installation accordingly.\n";
}
#Check the hicup mapper outputfiles don't already exist
my @hicup_Mapper_Outfiles = fileNamer( \@filenames, \%config, 'mapper', 1, 1, 1, 1, 1 );
foreach my $file (@hicup_Mapper_Outfiles) { #Add filename extension
$file = $config{outdir} . $file;
}
unless ( check_files_exist( \@hicup_Mapper_Outfiles, 'NOT_EXISTS' ) ) {
die "HiCUP+ mapper will not run until files have been removed.\n";
}
#Determine number of threads the Bowtie2 aligner may use
#Remember that each file is already processed using a separate core
my $bowtie2_threads = floor( $config{threads} / scalar(@filenames) );
$bowtie2_threads = 1 if ($bowtie2_threads < 1);
#Datestamp the summary file
my ($summaryfile) = fileNamer( \@filenames, \%config, 'mapper', 0, 1, 0, 0, 0 );
$summaryfile = $config{outdir} . $summaryfile;
my $summaryfileTemp = ( fileNamer( \@filenames, \%config, 'mapper', 0, 0, 0, 1, 0 ) )[-1]; #Temp summary file will be the last item returned
$summaryfileTemp = $config{outdir} . $summaryfileTemp;
open( SUMMARYTEMP, ">$summaryfileTemp" ) or die "Could not write to '$summaryfileTemp' : $!";
print "Mapping with HiCUP+ Mapper v$hicup_module::VERSION\n" unless $config{quiet};
print "Using aligner '$config{aligner}'\n" unless $config{quiet};
my $terminate = 0; #Instruct script to die if error detected in child process
my %children; #Hash of child processes
foreach my $inputfile (@filenames) {
my $pid = fork();
die "cannot fork" unless defined $pid;
if ( $pid == 0 ) {
map_file($inputfile);
exit(0);
} else {
$children{$pid} = 1;
while ( keys(%children) == $config{threads} ) {
sleep(1);
reaper();
}
}
}
#Make sure all child processes have terminated before exiting
do {
sleep(1);
reaper();
} until ( keys(%children) == 0 );
print "Mapping complete\n" unless $config{quiet};
close SUMMARYTEMP or die "Could not close filehandle on '$summaryfileTemp' : $!";
#Write the results from the mapping into a hash
my %summary_results = extract_mapping_results("$summaryfileTemp"); #Stores the results to write to the summary file
#Now pair the files
print "Pairing files with HiCUP+ Mapper v$hicup_module::VERSION\n" unless $config{quiet};
open( SUMMARY, ">$summaryfile" ) or die "Could not write to $summaryfile : $!";
print SUMMARY "File\tTotal_reads_processed\tReads_too_short_to_map\t%Reads_too_short_to_map\tUnique_alignments\t%Unique_alignments\tMultiple_alignments\t%Multiple_alignments\tFailed_to_align\t%failed_to_align\tPaired\t%Paired\n";
#Process the jobs as separate child processes (in accordance with $config{threads})
%children = ();
foreach my $fileforward ( keys %files ) {
my $filereverse = $files{$fileforward};
print "File forward: $fileforward\n" unless $config{quiet};
print "File reverse: $filereverse\n" unless $config{quiet};
my $pid = fork();
die "cannot fork" unless defined $pid;
if ( $pid == 0 ) {
pair( $fileforward, $filereverse );
exit(0);
} else {
$children{$pid} = 1;
while ( keys(%children) == $config{threads} ) {
sleep(1);
reaper();
}
}
}
#Make sure all child processes have terminated before exiting
do {
sleep(1);
reaper();
} until ( keys(%children) == 0 );
print "Pairing complete\n" unless $config{quiet};
#Remove intermediate *.map* files
my @map_files = fileNamer(\@filenames, \%config, 'mapper', 0, 0, 0, 1, 0);
foreach my $mapFile (@map_files) {
unlink $config{outdir}.$mapFile or warn "Could not delete '$config{outdir}.$mapFile'\n";
}
close SUMMARY or die "Could not close filehandle on '$summaryfile' : $!";
#Produce summary graph
unless ( $config{r} eq '0' ) { #R not installed/found
my $command = $config{r} . 'script ' . "$Bin/r_scripts/hicup_mapper_summary.r $config{outdir} $summaryfile";
!system("$command") or warn "Could not produce hicup_mapper summary bar chart: $command: $!";
}
exit(0);
#######################################################################################
#Subroutines #
#######################################################################################
############################
#Subroutine "check_parameters":
#Check the user supplied parameters are ok
#Uses global variables
sub check_parameters {
my $parameters_ok = 1;
#Check aligners ok
$parameters_ok = 0 unless ( checkAligner( \%config ) );
$parameters_ok = 0 unless ( checkAlignerIndices( \%config ) );
if ( hasval( $config{format} ) ) { #Check specified FASTQ format is valid
$parameters_ok = 0 unless ( determineAlignerFormat( $config{format} ) );
} else { #If FASTQ quality format not specified, determine this automatically
my @sequence_files = %files;
warn "FASTQ quality format not specified, analysing file '$sequence_files[0]' to predict file format used\n";
$config{format} = quality_checker( $sequence_files[0] );
if ( $config{format} eq 0 ) {
die "Unable to determine FASTQ quality format, please specify this and re-run HiCUP.\n";
} else {
warn "FASTQ quality set to $config{format}\n";
}
}
#Convert the FASTQ format into an aligner-specific format
$config{format} = determineAlignerFormat( $config{format}, $config{aligner} ) if ($parameters_ok); #Only run if parameters ok to prevent duplicate warning messages
#Check the output directory exists and allows write access
if ( $config{outdir} ) {
unless ( -d $config{outdir} ) {
warn "Output directory '$config{outdir}' does not exist or is not writable\n";
$parameters_ok = 0;
}
unless ( $config{outdir} =~ /\/$/ ) {
$config{outdir} .= '/'; #Make sure that $config{outdir} ends with the forward slash character
}
} else {
$config{outdir} = './'; #Make current directory if none specified
}
$config{threads} = 1 unless ( hasval( $config{threads} ) );
#Check whether SAMtools is installed
unless ( hasval( $config{samtools} ) ) {
if ( !system "which samtools >/dev/null 2>&1" ) {
$config{samtools} = `which samtools`;
chomp $config{samtools};
}
}
checkR( \%config ); #Check R installed
return $parameters_ok;
}
#######################
#Subroutine "map_file":
#launches Bowtie to align FASTQ reads against a specified reference genome
sub map_file {
# start timing step
print STDOUT "\nstarting HiCUP aligner call\n";
my $start_aligner = [Time::HiRes::gettimeofday()];
my $inputfile = $_[0];
my ($outputfile) = fileNamer( $inputfile, \%config, 'mapper', 0, 0, 0, 1, 0 ); #The first temp file returned (These files are deleted after pairing, a mapper_summary temp file is also returned)
$outputfile = $config{outdir} . $outputfile;
my $line_counter = 1;
if ( $inputfile =~ /.*\.gz$/ ) {
open( INPUT, "gunzip -c $inputfile |" ) or die $!;
} else {
open( INPUT, $inputfile ) or die $!;
}
my $index_directory = dirname( $config{index} );
print "index: $index_directory \n" unless $config{quiet};
print "index: $config{index} \n" unless $config{quiet};
my $output_directory = dirname ( $outputfile );
print "output: $output_directory \n" unless $config{quiet};
my $output_prefix = basename( $outputfile, ".sam");
print "filename $output_prefix \n" unless $config{quiet};
if ( $config{dragen} ne '' ) {
print(system("pwd")) unless $config{quiet};
print "\n" unless $config{quiet};
print "Mapping $inputfile\n" unless $config{quiet};
system ("ls $inputfile") unless $config{quiet};
print "\n" unless $config{quiet};
}
local ( *READER, *WRITER, *ERROR );
my $oid;
print( "$inputfile \n" );
my $inputprefix = substr($inputfile, 0, -15);
if ( $config{bowtie} ne '' ) {
print "\n running bowtie...\n" unless $config{quiet};
print( "\n $config{bowtie} -m 1 -n 1 --best --$config{format} -p 1 --chunkmbs 512 $config{index} --sam - $outputfile \n" ) unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "$config{bowtie} -m 1 -n 1 --best --$config{format} -p 1 --chunkmbs 512 $config{index} --sam - $outputfile" );
} elsif ( $config{bowtie2} ne '' ) {
print "\n running bowtie2...\n" unless $config{quiet};
#TODO
if ( $config{zip} and $config{samtools} ) {
print( "\n $config{bowtie2} --very-sensitive -x $config{index} --$config{format} --no-unal --threads $bowtie2_threads --reorder - -S $outputfile \n" ) unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "$config{bowtie2} --very-sensitive -x $config{index} --$config{format} --no-unal --threads $bowtie2_threads --reorder - -S $outputfile" );
# "| samtools view -bSh 2>/dev/null - > $paired_filename"
} elsif ( $config{zip} ) {
print( "\n $config{bowtie2} --very-sensitive -x $config{index} --$config{format} --no-unal --threads $bowtie2_threads --reorder - -S $outputfile \n" ) unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "$config{bowtie2} --very-sensitive -x $config{index} --$config{format} --no-unal --threads $bowtie2_threads --reorder - -S $outputfile" );
# "| gzip -c - > $paired_filename"
} else {
print( "\n $config{bowtie2} --very-sensitive -x $config{index} --$config{format} --no-unal --threads $bowtie2_threads --reorder - -S $outputfile \n" ) unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "$config{bowtie2} --very-sensitive -x $config{index} --$config{format} --no-unal --threads $bowtie2_threads --reorder - -S $outputfile" );
}
} elsif ( $config{dragen} ne '' ) {
print "\n running dragen...\n" unless $config{quiet};
#check hostname has partial match to dragen
my $host;
$host = hostname;
print "\n" unless $config{quiet};
printf ${host} unless $config{quiet};
print "\n" unless $config{quiet};
if ($host =~ /[Dd]ragen/ ) {
print "\n run installed dragen via bash call..." unless $config{quiet};
print "\n$config{dragen} -r $index_directory -1 $inputfile --output-format SAM --enable-sort false --Aligner.supp-aligns 0 --Aligner.sec-aligns 0 --Aligner.hard-clips 0 --soft-read-trimmers none --read-trimmers none --Aligner.global 1 --enable-map-align true --preserve-map-align-order true --ref-sequence-filter false --Mapper.min-intron-bases 255 --fastq-offset $config{format} --enable-map-align-output true --num-threads $bowtie2_threads --RGID $output_prefix --RGSM $output_prefix --output-file-prefix $output_prefix --output-directory $output_directory > $output_directory/dragen.out 2> $output_directory/dragen.err \n" unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "$config{dragen} -1 $inputfile -r $index_directory --output-format SAM --enable-sort false --Aligner.supp-aligns 0 --Aligner.sec-aligns 0 --Aligner.hard-clips 0 --soft-read-trimmers none --read-trimmers none --Aligner.global 1 --enable-map-align true --preserve-map-align-order true --ref-sequence-filter false --Mapper.min-intron-bases 255 --fastq-offset $config{format} --enable-map-align-output true --num-threads $bowtie2_threads --RGID $output_prefix --RGSM $output_prefix --output-file-prefix $output_prefix --output-directory $output_directory > $output_directory/dragen.out 2> $output_directory/dragen.err" );
} else {
print "run via SSH required to call dragen" unless $config{quiet};
my $username;
$username = $ENV{LOGNAME} || $ENV{USER} || getpwuid($<);
print "\n" unless $config{quiet};
printf ${username} unless $config{quiet};
print "\n" unless $config{quiet};
my $dragenhost;
$dragenhost = "dragen";
print "attempting to login to node " unless $config{quiet};
printf ${dragenhost} unless $config{quiet};
print " as " unless $config{quiet};
printf ${username} unless $config{quiet};
print "\n" unless $config{quiet};
my $remotelogin = ${username} . "@" . ${dragenhost};
print $remotelogin;
print "\nssh -q -t $remotelogin $config{dragen} -r $index_directory -1 $inputfile --output-format SAM --enable-sort false --Aligner.supp-aligns 0 --Aligner.sec-aligns 0 --Aligner.hard-clips 0 --soft-read-trimmers none --read-trimmers none --Aligner.global 1 --enable-map-align true --preserve-map-align-order true --ref-sequence-filter false --Mapper.min-intron-bases 255 --fastq-offset $config{format} --enable-map-align-output true --num-threads $bowtie2_threads --RGID $output_prefix --RGSM $output_prefix --output-file-prefix $output_prefix --output-directory $output_directory > $output_directory/dragen.out 2> $output_directory/dragen.err \n" unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "ssh -q -t $remotelogin $config{dragen} -1 $inputfile -r $index_directory --output-format SAM --enable-sort false --Aligner.supp-aligns 0 --Aligner.sec-aligns 0 --Aligner.hard-clips 0 --soft-read-trimmers none --read-trimmers none --Aligner.global 1 --enable-map-align true --preserve-map-align-order true --ref-sequence-filter false --Mapper.min-intron-bases 255 --fastq-offset $config{format} --enable-map-align-output true --num-threads $bowtie2_threads --RGID $output_prefix --RGSM $output_prefix --output-file-prefix $output_prefix --output-directory $output_directory > $output_directory/dragen.out 2> $output_directory/dragen.err" );
};
} elsif ( $config{hisat2} ne '' ) {
print "\n running hisat2...\n" unless $config{quiet};
print ( "\n $config{hisat2} -x $config{index} --$config{format} --no-unal --threads $bowtie2_threads --reorder - -S $outputfile \n" ) unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "$config{hisat2} -x $config{index} --$config{format} -k 1 --no-unal --no-spliced-alignment --no-softclip --threads $bowtie2_threads --reorder - -S $outputfile" );
} elsif ( $config{star} ne '' ) {
print "\n running STAR...\n" unless $config{quiet};
print ( "\n $config{star} --runMode alignReads --genomeDir $config{index} --outQSconversionAdd $config{format} --readFilesIn /dev/stdin --runThreadN $bowtie2_threads --outSAMtype SAM --chimMainSegmentMultNmax 1 --chimSegmentMin 0 --outFilterIntronMotifs RemoveNoncanonical --outFilterMismatchNmax 1 --outFilterMultimapNmax 1 --bamRemoveDuplicatesType UniqueIdentical --outSAMmultNmax 1 --alignSoftClipAtReferenceEnds No --alignEndsType EndToEnd --alignIntronMax 0 --alignIntronMin 999999999999 --outSAMunmapped None --outReadsUnmapped None --readFilesCommand cat --outFileNamePrefix $inputprefix --outStd SAM > $outputfile && \n" ) unless $config{quiet};
$oid = open3( \*WRITER, \*READER, \*ERROR, "$config{star} --runMode alignReads --genomeDir $config{index} --outQSconversionAdd $config{format} --readFilesIn /dev/stdin --runThreadN $bowtie2_threads --outSAMtype SAM --chimMainSegmentMultNmax 1 --chimSegmentMin 0 --outFilterIntronMotifs RemoveNoncanonical --outFilterMismatchNmax 1 --outFilterMultimapNmax 1 --bamRemoveDuplicatesType UniqueIdentical --outSAMmultNmax 1 --alignSoftClipAtReferenceEnds No --alignEndsType EndToEnd --alignIntronMax 0 --alignIntronMin 999999999999 --outSAMunmapped None --outReadsUnmapped None --readFilesCommand cat --outFileNamePrefix $inputprefix --outStd SAM > $outputfile && cat ${inputprefix}Log.final.out | tr '\t' ' ' 1>&2" );
} else {
print("Must path for specify at least one aligner: bowtie, bowtie2, dragen, hisat2, or star in configuration");
exit(1);
}
print ( "call \n" );
print ( $oid );
unless ($oid) {
die "Failed to launch aligner";
}
print "\nMapping $inputfile\n" unless $config{quiet};
my $read_count = 1;
my $too_short_to_map = 0;
my $unique_map = 0;
my $mapped = 0;
my $unmapped = 0;
my $multi_mapped = 0;
my $reads_processed = 0;
my $bowtie2_custom_multimap = 0; #Number of reads
my $select = IO::Select->new();
$select->add( \*ERROR );
while (<INPUT>) {
my $read = $_;
if (/^@\d+_[ATCG]+_/) { #Checks if lines already numbered by the no longer supported script hicup_sorter?
my $line2 = scalar <INPUT>;
$read .= $line2;
my $read_length = length $line2;
$read .= scalar <INPUT>;
$read .= scalar <INPUT>;
if ( $read_length < 20 ) { #Don't pass very short reads to Bowtie
$too_short_to_map++ unless $config{dragen};
next;
}
} elsif (/^@/) {
$read =~ s/^@/\@$read_count\_/;
my $line2 = scalar <INPUT>;
$read .= $line2;
my $read_length = length $line2;
$read .= scalar <INPUT>;
$read .= scalar <INPUT>;
$read_count++;
if ( $read_length < 20 ) { #Don't pass very short reads to Bowtie
$too_short_to_map++;
next;
}
}
if ( $config{dragen} ) {
print "";
} else {
print WRITER $read; ## <- dragen fails on this line
#Check for error messages from Bowtie
if ( $select->can_read(0.00000001) ) {
while ( $select->can_read(0.0001) ) {
$_ = <ERROR>;
warn "$inputfile Aligner error: $_" unless(/Unable to change buffer size from default of 8192/); #Suppress confusing message from Bowtie2
}
}
}
}
if ( $config{dragen} ) {
print WRITER "";
} elsif ( $config{star} ) {
print ERROR "";
} else {
while ( $select->can_read(0.01) ) {
$_ = <ERROR>;
warn "$inputfile Aligner error: $_";
}
}
close WRITER or die "Could not close 'WRITER' filehandle : $!";
while (<ERROR>) {
if ( $config{bowtie} ne '' ) {
# Don't show expected messages from bowtie but
# warn about anything else
unless ( /^\#/ or /^Reported/ or /^No alignments/ ) {
warn $_;
}
if (/\# reads processed: (\d+)/) { #Bowtie output
$reads_processed = $1;
}
if (/\# reads with at least one reported alignment: (\d+)/) { #Bowtie output
$unique_map = $1;
}
if (/\# reads that failed to align: (\d+)/) { #Bowtie output
$unmapped = $1;
}
if (/\# reads with alignments suppressed due to -m: (\d+)/) { #Bowtie output
$multi_mapped = $1;
}
} elsif ( $config{bowtie2} or $config{hisat2} ) {
# Don't show expected messages from bowtie2, but
# warn about anything else
unless ( /\d* reads; of these:/ or /were unpaired; of these:/ or /aligned.+time/ or /overall alignment rate/ ) {
warn $_;
}
if (/(\d+) reads; of these:/) { #Bowtie2 or HiSAT2 output
$reads_processed = $1;
}
if (/(\d+) \(.+\) aligned exactly 1 time/) { #Bowtie2 or HiSAT2 output
$unique_map = $1; #Will be overwritten later owing to new definition of multi-mapping
}
if (/(\d+) \(.+\) aligned 0 times/) { #Bowtie2 or HiSAT2 output
$unmapped = $1;
}
if (/(\d+) \(.+\) aligned >1 times/) { #Bowtie2 or HiSAT2 output
$multi_mapped = $1; #Will be overwritten later owing to new definition of multi-mapping
}
} elsif ( $config{star} ) {
# Don't show expected messages from bowtie2, but
# warn about anything else
#unless ( /\d* reads; of these:/ or /were unpaired; of these:/ or /aligned.+time/ or /overall alignment rate/ ) {
# warn $_;
#}
if (/Number of input reads \| (\d+)/) { #STAR output
$reads_processed = $1;
}
if (/Uniquely mapped reads number \| (\d+) \(.+\)/) { #STAR output
$unique_map = $1; #Will be overwritten later owing to new definition of multi-mapping
}
if (/Number of reads unmapped\: too many mismatches \| (\d+)/) { #STAR output
$unmapped = $1;
}
if (/Number of reads unmapped: too short \| (\d+)/) { #STAR output
$too_short_to_map = $1 + $too_short_to_map;
}
if (/Number of reads unmapped: other \| (\d+)/) { #STAR output
$unmapped = $1 +$unmapped;
}
if (/Number of reads mapped to multiple loci \| (\d+)/) { #STAR output
$multi_mapped = $1; #Will be overwritten later owing to new definition of multi-mapping
}
if (/Number of reads mapped to too many loci \| (\d+)/) { #STAR output
$multi_mapped = $1 + $multi_mapped; #Will be overwritten later owing to new definition of multi-mapping
}
} elsif ( $config{dragen} ) {
# show all warnings
warn $_;
}
}
# complete aligner call
close READER or die "Could not close 'READER' filehandle : $!";
close ERROR or die "Could not close 'ERROR' filehandle : $!";
waitpid( $oid, 0 );
#report timing results
my $end = Time::HiRes::tv_interval($start_aligner);
print STDOUT "\ncompleted HiCUP aligner call\n";
print STDOUT "\n\naligner run time: $end\n";
if ( $config{dragen} ) {
# import results from Dragen logs
my $dragen_file = "$output_directory/dragen.out" ;
my %dragen_results = %{ &dragen2hash($dragen_file) };
$reads_processed = $dragen_results{TOTAL};
print "total reads: " unless $config{quiet};
print($reads_processed) unless $config{quiet};
print "\n" unless $config{quiet};
$mapped = $dragen_results{MAPPED};
print "mapped: " unless $config{quiet};
print($mapped) unless $config{quiet};
print "\n" unless $config{quiet};
$multi_mapped = $dragen_results{MULTI};
print "multimappers: " unless $config{quiet};
print($multi_mapped) unless $config{quiet};
print "\n" unless $config{quiet};
$unmapped = $dragen_results{UNMAPPED};
print "unmapped: " unless $config{quiet};
print($unmapped) unless $config{quiet};
print "\n" unless $config{quiet};
# defines mapping quality >10 as uniquely mapped
$unique_map = $mapped - $multi_mapped;
print "unique mappers: " unless $config{quiet};
print($unique_map) unless $config{quiet};
print "\n" unless $config{quiet};
}
#Add the results to the results summary hash
#Note, these values will be re-calculated if Bowtie2 is used as the aligner
my $percent_too_short_to_map;
my $percent_unique;
my $percent_unmapped;
my $percent_multi;
if ( $config{dragen}) {
#Reads processed is those reported by Dragen including those too short (unmapped)
$too_short_to_map = 0;
}
else {
#Reads processed is the number of reads processed by Bowtie + those too short to send to Bowtie
$reads_processed += $too_short_to_map unless $config{dragen};
}
if ($reads_processed) {
$percent_too_short_to_map = sprintf( "%.1f", ( $too_short_to_map / $reads_processed * 100 ) );
$percent_unique = sprintf( "%.1f", ( $unique_map / $reads_processed * 100 ) );
$percent_unmapped = sprintf( "%.1f", ( $unmapped / $reads_processed * 100 ) );
$percent_multi = sprintf( "%.1f", ( $multi_mapped / $reads_processed * 100 ) );
} else {
$percent_too_short_to_map = 'N/A';
$percent_unique = 'N/A';
$percent_unmapped = 'N/A';
$percent_multi = 'N/A';
}
# reporting timing results
my $end2 = Time::HiRes::tv_interval($start_aligner);
print STDOUT "\ncompleted HiCUP aligner summary\n";
print STDOUT "\n\naligner total time: $end2\n";
print SUMMARYTEMP "$inputfile\t$reads_processed\t$too_short_to_map\t$percent_too_short_to_map\t$unique_map\t$percent_unique\t$multi_mapped\t$percent_multi\t$unmapped\t$percent_unmapped\t\n";
}
#################################
#Subroutine "bowtie2MultiMapRead"
#Takes a read and uses the Bowtie2 flag
#to report whether it is a multi-mapping read
#Returns 1 if multi-mapping and 0 if uniquely mapping
#Slightly adjusted from the main hicup subroutine
sub bowtie2MultiMapRead {
my @tags = split( /\t/, $_[0]);
my $mapq = $tags[4];
@tags = splice( @tags, 11 ); #Only evaluate SAM tags
my $as;
my $xs;
foreach my $tag (@tags) {
my ($tag_id, $score) = split(/:i:/, $tag);
if($tag_id eq 'AS'){
$as = $score;
} elsif($tag_id eq 'XS') {
$xs = $score;
}
}
if(defined $xs and defined $as){ #Potential multi-map, check quality scores to determine whether multi-maps
if( ($mapq >= 30) and ( abs($xs - $as) >= 10 ) ){
return 0; #Unique map
} else {
return 1;
}
} elsif(defined $as){ #Unique map
return 0;
} else {
die "AS not defined in @tags\n";
}
}
###################
#Subroutine "pair":
#pairs the .map files
sub pair {
my $sequencefileF = $_[0]; #Keep original filename for writing results
my $sequencefileR = $_[1]; #Keep original filename for writing results
my ($fileForward) =
fileNamer( $sequencefileF, \%config, 'mapper', 0, 0, 0, 1, 0 ); #The first temp file returned (These files are deleted after pairing, a mapper_summary temp file is also returned)
$fileForward = $config{outdir} . $fileForward;
my ($fileReverse) =
fileNamer( $sequencefileR, \%config, 'mapper', 0, 0, 0, 1, 0 ); #The first temp file returned (These files are deleted after pairing, a mapper_summary temp file is also returned)
$fileReverse = $config{outdir} . $fileReverse;
my @forwardAndReverse = ( $sequencefileF, $sequencefileR );
my ($paired_filename) = fileNamer( \@forwardAndReverse, \%config, 'mapper', 1, 0, 0, 0, 0 );
$paired_filename = $config{outdir} . $paired_filename;
print 'Pairing ' . basename($fileForward) . ' and ' . basename($fileReverse) . "\n" unless $config{quiet};
if ( $config{zip} and $config{samtools} ) {
open( PAIRED, "| samtools view -bSh 2>/dev/null - > $paired_filename" ) or die "Couldn't write to file '$paired_filename' : $!";
} elsif ( $config{zip} ) {
open( PAIRED, "| gzip -c - > $paired_filename" ) or die "Couldn't write to file '$paired_filename' : $!";
} else {
open( PAIRED, ">$paired_filename" ) or die "Couldn't write to file '$paired_filename' : $!";
}
#Check whether the input file is zipped and then open accordingly
if ( $fileForward =~ /\.gz$/ ) {
open( FORWARD, "gunzip -c $fileForward |" ) or die "Couldn't read file '$fileForward : $!";
} else {
open( FORWARD, $fileForward ) or die "Can't read \'$fileForward\' : $!";
}
if ( $fileReverse =~ /\.gz$/ ) {
open( REVERSE, "gunzip -c $fileReverse |" ) or die "Couldn't read file '$fileReverse' : $!";
} else {
open( REVERSE, $fileReverse ) or die "Can't read \'$fileReverse\' : $!";
}
my $f_read = <FORWARD>;
my $r_read = <REVERSE>; # initialise with first line for Dragen
my $f_read_id = 0;
my $r_read_id = 0;
my $paired_reads_counter = 0;
my $f_reads_counter = 0;
my $r_reads_counter = 0;
my $f_read_bowtie2_multimap = 0; #Bowtie2 multi-mapping
my $r_read_bowtie2_multimap = 0;
my $in_header = 1; #Flag indicating if in the header region
while (<FORWARD>) {
$f_read = $_;
# while (<REVERSE>){ ##
# $r_read = $_; ##
# print STDERR "input";
# print STDERR "\n";
# print STDERR $f_read;
# print STDERR "\n";
# print STDERR $r_read;
# print STDERR "\n";
if (/^\s*$/) {
next;
} elsif (/^@/) { #Print SAM header lines so conversion to BAM is possible
print PAIRED $_;
next;
} else {
if ($in_header) { #Print the additional SAM header line
my $sam_header_line = "\@PG\tID:HiCUP+ Mapper\tVN:" . "$hicup_module::VERSION\n";
print PAIRED $sam_header_line;
if ( $config{ligation} ) {
print PAIRED $config{ligation} . "\n";
}
$in_header = 0;
}
if ( $config{dragen} ) { ##
my @f_read_split = split("\t", $f_read);
my $f_read_str_id = $f_read_split[0];
my @r_read_split = split("\t", $r_read);
my $r_read_str_id = $r_read_split[0];
# print STDERR "string ID";
# print STDERR "\n";
# print STDERR $f_read_str_id;
# print STDERR "\n";
# print STDERR $r_read_str_id;
# print STDERR "\n";
if ( $f_read_id == 0){
$f_read_id = 1;
}
# convert to numeric comparison
if ($r_read_str_id eq $f_read_str_id){
$r_read_id = $f_read_id;
} else {
# if ( $f_read_id == 0 ){
$r_read_id = $f_read_id - 1;
# } else {
$r_read_id = $f_read_id - 1;
# }
}
# print STDERR $f_read_id;
# print STDERR "\n";
# print STDERR $r_read_id;
# print STDERR "\n";
# test for header rows and skip
my $firstchar = substr $f_read_str_id, 0, 1;
if ( $firstchar eq "@"){
$r_read_id = $f_read_id - 1;
}
my $firstchar2 = substr $r_read_str_id, 0, 1;
if ( $firstchar2 eq "@"){
$r_read_id = $f_read_id - 1;
}
# print STDERR "read ID";
# print STDERR "\n";
# print STDERR $f_read_id;
# print STDERR "\n";
# print STDERR $r_read_id;
# print STDERR "\n";
} else {
/^(\d+)_/;
$f_read_id = $1;
}
# print STDERR "read ID";
# print STDERR "\n";
# print STDERR $f_read_id;
# print STDERR "\n";
# print STDERR $r_read_id;
# print STDERR "\n";
if( $config{bowtie2} or $config{hisat2} ){
if ( bowtie2MultiMapRead($f_read) ){ #Don't included multi-mapping reads
$f_read_bowtie2_multimap++;
next;
}
}
# if($r_read_id == $f_read_id){
if($r_read_id eq $f_read_id){ #Special case in which current Forward ID is same as previous reverse ID
# print STDERR "read ID match";
# print STDERR "\n";
# print STDERR $f_read_id;
# print STDERR "\n";
# print STDERR $r_read_id;
# print STDERR "\n";
if($config{bowtie2} or $config{hisat2}){
if ( bowtie2MultiMapRead($r_read) ){ #Don't included multi-mapping reads
$r_read_bowtie2_multimap++;
next;
}
}
if ( $config{dragen} ){ ##
# $f_read =~ s/^(.*?)\t/1_$1\t/; # add \1 to add R1s
# $r_read =~ s/^(.*?)\t/2_$1\t/; # add \2 to add R2s
print STDERR $f_read;
print STDERR $r_read;
} else {
# if ( ! $config{dragen} ){
$f_read =~ s/^(\d+)_//; #Remove numbering labels
$r_read =~ s/^(\d+)_//; #Remove numbering labels ##
}
# print STDERR "\n";
# print STDERR "read to format input";
# print STDERR "\n";
# print STDERR $f_read;
# print STDERR "\n";
# print STDERR $r_read;
# print STDERR "\n";
( $f_read, $r_read ) = sam_formatter( $f_read, $r_read );
if ($f_read) { #Do not print empty values
print PAIRED $f_read;
print PAIRED $r_read;
$paired_reads_counter++;
next;
}
}
# while ( $r_read_id lt $f_read_id ) {
while ( $r_read_id < $f_read_id ) { ##
$r_read = scalar <REVERSE> or last;
# print STDERR "reverse input";
# print STDERR "\n";
# print STDERR $f_read;
# print STDERR "\n";
# print STDERR $r_read;
# print STDERR "\n";
if ( $r_read =~ /^\s*$/ ) {
next;
} elsif ( $r_read =~ /^@/ ) { #Ignore SAM format header lines
next;
} else {
if ( $config{dragen} ) { ##
$r_read =~ //;
my @f_read_split = split("\t", $f_read);
my $f_read_str_id = $f_read_split[0];
my @r_read_split = split("\t", $r_read);
my $r_read_str_id = $r_read_split[0];
# convert to numeric comparison
if ($r_read_str_id cmp $f_read_str_id){
$r_read_id = $f_read_id;
} else {
# if ( $f_read_id == 0 ){
$r_read_id = $f_read_id - 1;
# } else {
$r_read_id = $f_read_id - 1;
# }
}
# test for header rows and skip
my $firstchar = substr $f_read_str_id, 0, 1;
if ( $firstchar eq "@"){
$r_read_id = $f_read_id - 1;
}
} else {
$r_read =~ /^(\d+)_/;
$r_read_id = $1;
}
}
# print STDERR "final read ID input";
# print STDERR "\n";
# print STDERR $f_read_id;
# print STDERR "\n";
# print STDERR $r_read_id;
# print STDERR "\n";
if( $config{bowtie2} or $config{hisat2} ){
if ( bowtie2MultiMapRead($r_read) ){ #Don't included multi-mapping reads
$r_read_bowtie2_multimap++;
next;
}
}
# print STDERR "preview read to format";
# print STDERR "\n";
# print STDERR $f_read;
# print STDERR "\n";
# print STDERR $r_read;
# print STDERR "\n";
# if ( $f_read_id == $r_read_id ) {
if ( $f_read_id eq $r_read_id ) { ##
#if ( $config{dragen} ){ ##
# $f_read =~ s/^(.*?) /$1\\1 /; # add \1 to add R1s