/
UmiBam
executable file
·1762 lines (1485 loc) · 73.7 KB
/
UmiBam
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
use strict;
use warnings;
use Getopt::Long;
### This script is supposed to remove alignments to the same position in the genome which can arise by e.g. PCR amplification
### Paired-end alignments are considered a duplicate if both partner reads start and end at the exact same position
### In addition to the mapping position we are using a UMI in the read ID to discriminate alignments from two distinct molecules to the same position
### 15 06 2020
### Adapting to also work with softclipped reads (CIGAR operation S)
### 16 08 2021
### Fixing auto-detection
### 30 09 20201
### Looking to add Hi-C mode, where R1 and R2 map to different locations
my $dedup_version = 'v0.2.0dev';
my $copyright_dates = "2016-21";
my $last_modified = "01 Oct 2021";
my %umi_reporting = (); # only required for Hi-C, and --detailed_UMI_report
my $help;
my $representative;
my $single;
my $paired;
my $global_single;
my $global_paired;
my $vanilla;
my $samtools_path;
my $bam = 1;
my $umi;
my $mm;
my $double_umi;
my $hic;
my $detail;
my $version;
my $command_line = GetOptions ('help' => \$help,
's|single' => \$global_single,
'p|paired' => \$global_paired,
'samtools_path=s' => \$samtools_path,
'bam' => \$bam,
'umi' => \$umi,
'double_umi' => \$double_umi,
'mismatches|mm=i' => \$mm, # mismatches in the UMI sequence tolerated
'version' => \$version,
'hic' => \$hic,
'detailed_UMI_report' => \$detail,
);
die "Please respecify command line options\n\n" unless ($command_line);
if ($help){
print_helpfile();
exit;
}
if ($version){
print << "VERSION";
UMI Deduplication for BAM files
Deduplicator Version: $dedup_version
Copyright $copyright_dates Felix Krueger, Babraham Bioinformatics
https://github.com/FelixKrueger/Umi-Grinder
VERSION
exit;
}
my @filenames = @ARGV;
unless (@filenames){
print "Please provide one or more BAM files for deduplication\n\n";
sleep (2);
print_helpfile();
exit;
}
### OPTIONS
if ($hic){
warn "\n >>> Hi-C mode was selected: Setting global paired-end mode <<<\n\n"; sleep (1);
$global_paired = 1; # for Hi-C mode we set paired, but need to proceed differently at the processing step
$global_single = 0;
}
if ($double_umi){
warn "Setting --umi as well\n";
$umi = 1; # setting $umi as well
}
if ($detail){
unless ($hic){
die "The detailed UMI report is only intended for use with Hi-C data. Please re-specify!\n\n";
}
unless ($umi){
die "The detailed UMI report can only be used when the option --umi is selected. Please re-specify!\n";
}
if ($double_umi){
die "The detailed UMI report can only be used when the option --umi (but not --double_umi!) is selected. Please re-specify!\n";
}
}
unless ($global_single or $global_paired){
if ($vanilla){
die "Please specify either -s (single-end) or -p (paired-end) for deduplication. Reading this information from the \@PG header line only works for SAM/BAM files\n\n";
}
warn "\nNeither -s (single-end) nor -p (paired-end) selected for deduplication. Trying to extract this information for each file separately from the \@PG line of the SAM/BAM file\n";
}
if ($global_paired){
if ($global_single){
die "Please select either -s for single-end files or -p for paired-end files, but not both at the same time!\n\n";
}
if ($vanilla){
if ($umi){
die "Barcode deduplication only works with BAM output\n";
}
warn "Processing paired-end custom Bismark output file(s):\n";
warn join ("\t",@filenames),"\n\n";
}
else{
warn "Processing paired-end Bismark output file(s) (SAM format):\n";
warn join ("\t",@filenames),"\n\n";
}
}
else{
if ($vanilla){
warn "Processing single-end custom Bismark output file(s):\n";
warn join ("\t",@filenames),"\n\n";
}
else{
warn "Processing single-end Bismark output file(s) (SAM format):\n";
warn join ("\t",@filenames),"\n\n";
}
}
### UMI-mismatches: Currently only allowing 1 or 2 mismatches
if (defined $mm){
if ($mm < 1){ # setting to FALSE
$mm = 0;
}
elsif($mm > 6){
die "The current maximum of mismatches in the UMI is 6, please respecify...\n\n";
}
}
### PATH TO SAMTOOLS
if (defined $samtools_path){
# if Samtools was specified as full command
if ($samtools_path =~ /samtools$/){
if (-e $samtools_path){
# Samtools executable found
}
else{
die "Could not find an installation of Samtools at the location $samtools_path. Please respecify\n";
}
}
else{
unless ($samtools_path =~ /\/$/){
$samtools_path =~ s/$/\//;
}
$samtools_path .= 'samtools';
if (-e $samtools_path){
# Samtools executable found
}
else{
die "Could not find an installation of Samtools at the location $samtools_path. Please respecify\n";
}
}
}
# Check whether Samtools is in the PATH if no path was supplied by the user
else{
if (!system "which samtools >/dev/null 2>&1"){ # STDOUT is binned, STDERR is redirected to STDOUT. Returns 0 if Samtools is in the PATH
$samtools_path = `which samtools`;
chomp $samtools_path;
}
}
if ($bam){
if (defined $samtools_path){
$bam = 1;
}
else{
warn "No Samtools found on your system, writing out a gzipped SAM file instead\n";
$bam = 2;
}
}
else{
$bam = 0;
}
if ($representative){
warn "\nIf there are several alignments to a single position in the genome the alignment with the most representative methylation call will be chosen (this might be the most highly amplified PCR product...)\n\n";
sleep (1);
}
elsif($umi){
warn "\nIf the input is a multiplexed sample with several alignments to a single position in the genome, only alignments with a unique UMI will be chosen\n";
if ($mm){
warn "Number of tolerated edit distance to known UMIs for any given position: $mm\n";
}
warn "\n";
sleep (1);
}
else{ # default; random (=first) alignment
warn "\nIf there are several alignments to a single position in the genome the first alignment will be chosen. Since the input files are not in any way sorted this is a near-enough random selection of reads.\n\n";
sleep (1);
}
foreach my $file (@filenames){
if ($global_single){
$paired = 0;
$single = 1;
}
elsif($global_paired){
$paired = 1;
$single = 0;
}
# Testing if the file appears to be truncated, in which case we bail with a big scary warning message
if ($file =~ /(\.bam$)/){
bam_isTruncated($file);
}
%umi_reporting = (); # clearing; Only required when --detailed_UMI_report was specified
unless($global_single or $global_paired){
warn "Trying to determine the type of mapping from the SAM header line\n"; sleep(1);
### if the user did not specify whether the alignment file was single-end or paired-end we are trying to get this information from the @PG header line in the SAM/BAM file
if ($file =~ /\.gz$/){
open (DETERMINE,"gunzip -c $file |") or die "Unable to read from gzipped file $file: $!\n";
}
elsif ($file =~ /\.bam$/){
open (DETERMINE,"$samtools_path view -h $file |") or die "Unable to read from BAM file $file: $!\n";
}
else{
open (DETERMINE,$file) or die "Unable to read from $file: $!\n";
}
while (<DETERMINE>){
last unless (/^\@/);
if ($_ =~ /^\@PG/){
warn "found a \@PG line:\n$_";
# Paired-end test for known aligners
if ($_ =~ /ID:Bismark/ or $_ =~ /ID:hisat2/ or $_ =~ /ID:bowtie2/){
if ($_ =~ /\s+--?1\s+/ and $_ =~ /\s+--?2\s+/){ # allowing -1 and -2 or --1 and --2
warn "Treating file as paired-end data (extracted from \@PG line)\n"; sleep(1);
$paired = 1;
$single = 0;
}
else{
warn "Treating file as single-end data (extracted from \@PG line)\n"; sleep(1);
$paired = 0;
$single = 1;
}
last; # exiting after one attempt
}
}
}
close DETERMINE or warn "$!\n";
unless (defined $paired){
die "\nUnable to detect library type automatically, please specify whether the file is single- or paired-end manually\n\n";
}
}
if ($file =~ /(\.bam$|\.sam$)/){
bam_isEmpty($file);
}
### OPTIONS
unless ($single or $paired){
die "Please specify either -s (single-end) or -p (paired-end) for deduplication, or provide a SAM/BAM file that contains the \@PG header line\n\n";
}
###
if ($paired){
if ($hic){
warn "Testing for positional sorting is not desirable for Hi-C data. Skipping...\n\n";
}
else{
test_positional_sorting($file);
}
}
### writing to a report file
my $report = $file;
$report =~ s/\.gz$//;
$report =~ s/\.sam$//;
$report =~ s/\.bam$//;
$report =~ s/\.txt$//;
my $detail_report = $report;
if ($umi){
if ($mm){
$report =~ s/$/.UMI_${mm}mm_deduplication_report.txt/;
$detail_report =~ s/$/.UMI_${mm}mm_detailed_UMI_report.txt/;
}
else{
$report =~ s/$/.UMI_deduplication_report.txt/;
$detail_report =~ s/$/.UMI_detailed_UMI_report.txt/;
}
}
else{
$report =~ s/$/.deduplication_report.txt/;
}
open (REPORT,'>',$report) or die "Failed to write to report file to $report: $!\n\n";
if($umi){
if ($mm){
deduplicate_barcoded_umi_with_mismatches($file,$mm);
}
else{
deduplicate_barcoded_umi($file);
}
### PRINTING DETAILED UMI REPORT; should only be available for Hi-C data
if ($detail){
detailed_umi_reporting($detail_report);
}
}
### as the default option we simply write out the first read for a position and discard all others. This is the fastest option
else{
my %unique_seqs;
my %positions;
my $upos = 0; # keeping a separate counter for already covered positions
if ($file =~ /\.gz$/){
open (IN,"gunzip -c $file |") or die "Unable to read from gzipped file $file: $!\n";
}
elsif ($file =~ /\.bam$/){
open (IN,"$samtools_path view -h $file |") or die "Unable to read from BAM file $file: $!\n";
}
else{
open (IN,$file) or die "Unable to read from $file: $!\n";
}
my $outfile = $file;
$outfile =~ s/\.gz$//;
$outfile =~ s/\.sam$//;
$outfile =~ s/\.bam$//;
$outfile =~ s/\.txt$//;
if ($bam == 1){
$outfile =~ s/$/.deduplicated.bam/;
}
elsif ($bam == 2){
$outfile =~ s/$/.deduplicated.sam.gz/;
}
else{
$outfile =~ s/$/.deduplicated.sam/;
}
if ($bam == 1){
open (OUT,"| $samtools_path view -bSh 2>/dev/null - > $outfile") or die "Failed to write to $outfile: $!\n";
}
elsif($bam == 2){ ### no Samtools found on system. Using GZIP compression instead
open (OUT,"| gzip -c - > $outfile") or die "Failed to write to $outfile: $!\n";
}
else{
open (OUT,'>',$outfile) or die "Unable to write to $outfile: $!\n";
}
my $count = 0;
my $unique_seqs = 0;
my $removed = 0;
while (<IN>){
if ($count == 0){
if ($_ =~ /^Bismark version:/){
warn "The file appears to be in the custom Bismark and not SAM format. Please see option --vanilla!\n";
sleep (2);
print_helpfile();
exit;
}
}
### if this was a SAM file we ignore header lines
unless ($vanilla){
if (/^\@\w{2}\t/){
print "skipping header line:\t$_";
print OUT "$_"; # Printing the header lines again into the de-duplicated file
next;
}
}
++$count;
my $composite; # storing positional data. For single end data we are only using the start coordinate since the end might have been trimmed to different lengths
my ($strand,$chr,$start,$end,$cigar);
my $line1;
# BAM/SAM format
($strand,$chr,$start,$cigar) = (split (/\t/))[1,2,3,5]; # we are assigning the FLAG value to $strand
### SAM single-end
if ($single){
if ($strand == 0 ){
### read aligned to the forward strand. No action needed
}
elsif ($strand == 16){
### read is on reverse strand
$start -= 1; # only need to adjust this once
# for InDel free matches we can simply use the M number in the CIGAR string
if ($cigar =~ /^(\d+)M$/){ # linear match
$start += $1;
}
else{
# parsing CIGAR string
my @len = split (/\D+/,$cigar); # storing the length per operation
my @ops = split (/\d+/,$cigar); # storing the operation
shift @ops; # remove the empty first element
die "CIGAR string contained a non-matching number of lengths and operations\n" unless (scalar @len == scalar @ops);
# warn "CIGAR string; $cigar\n";
### determining end position of a read
foreach my $index(0..$#len){
if ($ops[$index] eq 'M'){ # standard matching bases
$start += $len[$index];
# warn "Operation is 'M', adding $len[$index] bp\n";
}
elsif($ops[$index] eq 'I'){ # insertions do not affect the end position
# warn "Operation is 'I', next\n";
}
elsif($ops[$index] eq 'D'){ # deletions do affect the end position
# warn "Operation is 'D',adding $len[$index] bp\n";
$start += $len[$index];
}
elsif($ops[$index] eq 'S'){ # soft-clipped bases do not affect the end position
# warn "Operation is 'S', next\n";
}
elsif($ops[$index] eq 'N'){ # skipped regions (e.g. splice junctions) do affect the end position
# warn "Operation is 'N',adding $len[$index] bp\n";
$start += $len[$index];
}
else{
die "SE BAM: Found CIGAR operations other than M, I, S, N or D: '$ops[$index]'. Not allowed at the moment\n";
}
}
}
}
$composite = join (":",$strand,$chr,$start);
}
elsif($paired){
### storing the current line
$line1 = $_;
if($hic){
## Added this section 30 09 2021
# warn "Hi-C mode:\n";
### reading in the next line
my $line2 = <IN>;
chomp $line1;
chomp $line2;
# warn "R1: $line1\n";
# warn "R2: $line2\n~~~~~~~~~~~~~~~~~\n";
# For Hi-C mode it should be enough to work with the chromosome and start positions of both R1 and R2
my ($chr_r1,$start_r1) = (split (/\t/,$line1))[2,3];
my ($chr_r2,$start_r2) = (split (/\t/,$line2))[2,3];
# print "$chr_r1\t$start_r1\n$chr_r2\t$start_r2\n"; sleep(1);
# Hi-C data essentially behaves like 2 separate single-end alignments, so we
# should be fine to just score chr1:start1:chr2:start2:UMI. Since we don't
# know whether R1 and R2 are aligned in a directional fashion, we need to test
# both combinations.
### Here we take only the mapping position into consideration
my $composite1 = join (":",$chr_r1,$start_r1,$chr_r2,$start_r2);
my $composite2 = join (":",$chr_r2,$start_r2,$chr_r1,$start_r1);
# print ("$composite1\n$composite2\n\n :::::\n\n"); sleep(1);
if ( (exists $unique_seqs{$composite1}) or (exists $unique_seqs{$composite2}) ){
++$removed;
# warn "Exactly this read combination was present already!\n"; sleep(1);
# If a read was found at this position already, we record both R1/R2 combinations (and devide this number by 2 for reporting)
unless (exists $positions{$composite1}){
$positions{$composite1}++;
$positions{$composite2}++;
}
}
else{
print OUT "$line1\n"; # printing first line of Hi-C output
print OUT "$line2\n"; # printing second line of Hi-C output
# print "$line1\n$line2\n"; sleep(1);
# If neither read combination was found so far, it should be enough to record a single one, e.g. composite1
$unique_seqs{$composite1}++;
}
}
else{
my $flag = (split /\t/,$line1)[1];
# if the read aligns in forward orientation we can certainly use the start position of read 1, and only need to work out the end position of read 2
if ($flag == 99){ # 99 is paired-end, properly paired, read first in pair, mate on reverse strand
### reading in the next line
$_ = <IN>;
# the only thing we need is the end position
($end,my $cigar_2) = (split (/\t/))[3,5];
$end -= 1; # only need to adjust this once
# for InDel free matches we can simply use the M number in the CIGAR string
if ($cigar_2 =~ /^(\d+)M$/){ # linear match
$end += $1;
}
else{
# parsing CIGAR string
my @len = split (/\D+/,$cigar_2); # storing the length per operation
my @ops = split (/\d+/,$cigar_2); # storing the operation
shift @ops; # remove the empty first element
die "CIGAR string contained a non-matching number of lengths and operations ($cigar_2)\n" unless (scalar @len == scalar @ops);
# warn "CIGAR string; $cigar_2\n";
### determining end position of the read
foreach my $index(0..$#len){
if ($ops[$index] eq 'M'){ # standard matching bases
$end += $len[$index];
# warn "Operation is 'M', adding $len[$index] bp\n";
}
elsif($ops[$index] eq 'I'){ # insertions do not affect the end position
# warn "Operation is 'I', next\n";
}
elsif($ops[$index] eq 'D'){ # deletions do affect the end position
# warn "Operation is 'D',adding $len[$index] bp\n";
$end += $len[$index];
}
elsif($ops[$index] eq 'S'){ # soft-clipped bases do NOT affect the end position
# warn "Operation is 'S'\n";
}
elsif($ops[$index] eq 'N'){ # skipped regions (e.g. splice junctions) do affect the end position
# warn "Operation is 'N',adding $len[$index] bp\n";
$end += $len[$index];
}
else{
die "PE BAM: Found CIGAR operations other than M, I, D, S or N: '$ops[$index]'. Not allowed at the moment\n";
}
}
}
}
elsif($flag == 83){
# Flag 83 is paired-end, properly paired, read reverse strand, first in pair
# else read 1 aligns in reverse orientation and we need to work out the end of the fragment first, and use the start of the next line
$end = $start - 1; # need to adjust this only once
# for InDel free matches we can simply use the M number in the CIGAR string
if ($cigar =~ /^(\d+)M$/){ # linear match
$end += $1;
}
else{
# parsing CIGAR string
my @len = split (/\D+/,$cigar); # storing the length per operation
my @ops = split (/\d+/,$cigar); # storing the operation
shift @ops; # remove the empty first element
die "CIGAR string contained a non-matching number of lengths and operations ($cigar)\n" unless (scalar @len == scalar @ops);
# warn "CIGAR string; $cigar\n";
### determining end position of the read
foreach my $index(0..$#len){
if ($ops[$index] eq 'M'){ # standard matching bases
$end += $len[$index];
# warn "Operation is 'M', adding $len[$index] bp\n";
}
elsif($ops[$index] eq 'I'){ # insertions do not affect the end position
# warn "Operation is 'I', next\n";
}
elsif($ops[$index] eq 'D'){ # deletions do affect the end position
# warn "Operation is 'D',adding $len[$index] bp\n";
$end += $len[$index];
}
elsif($ops[$index] eq 'S'){ # soft-clipped bases do NOT affect the end position
# warn "Operation is 'S'\n";
}
elsif($ops[$index] eq 'N'){ # skipped regions such as splice junctions do affect the end position
# warn "Operation is 'N',adding $len[$index] bp\n";
$end += $len[$index];
}
else{
die "PE BAM: Found CIGAR operations other than M, I, D, S or N: '$ops[$index]'. Not allowed at the moment\n";
}
}
}
### reading in the next line
$_ = <IN>;
# the only thing we need is the start position
($start) = (split (/\t/))[3];
}
else{
die "So far unhandled FLAG value: $flag. Please update UMI-BAM\n\n";
}
$composite = join (":",$strand,$chr,$start,$end);
}
}
else{
die "Input must be single or paired-end\n";
}
unless ($hic){ # this has already been carried out at this step
if (exists $unique_seqs{$composite}){
++$removed;
unless (exists $positions{$composite}){
$positions{$composite}++;
}
}
else{
if ($paired){
print OUT "$line1"; # printing first paired-end line for SAM output
}
print OUT "$_"; # printing single-end SAM alignment or second paired-end line
$unique_seqs{$composite}++;
}
}
}
my $percentage;
my $percentage_leftover;
my $leftover = $count - $removed;
unless ($count == 0){
$percentage = sprintf("%.2f",$removed/$count*100);
$percentage_leftover = sprintf("%.2f",$leftover/$count*100);
}
else{
$percentage = 'N/A';
$percentage_leftover = 'N/A';
}
warn "\nTotal number of alignments analysed in $file:\t$count\n";
warn "Total number duplicated alignments removed:\t$removed ($percentage%)\n";
if ($hic){
warn "Duplicated Hi-C alignments were found at: \t",(scalar keys %positions)/2," different positional combinations\n\n";
}
else{
warn "Duplicated alignments were found at:\t",scalar keys %positions," different position(s)\n\n";
}
warn "Total count of deduplicated leftover sequences: $leftover ($percentage_leftover% of total)\n\n";
print REPORT "\nTotal number of alignments analysed in $file:\t$count\n";
print REPORT "Total number duplicated alignments removed:\t$removed ($percentage%)\n";
if ($hic){
print REPORT "Duplicated Hi-C alignments were found at: \t",(scalar keys %positions)/2," different positional combinations\n\n";
}
else{
print REPORT "Duplicated alignments were found at:\t",scalar keys %positions," different position(s)\n\n";
}
print REPORT "Total count of deduplicated leftover sequences: $leftover ($percentage_leftover% of total)\n\n";
}
close OUT or warn "Failed to close output filehandle: $!\n";
close REPORT or warn "Failed to close report filehandle: $!\n";
}
sub deduplicate_barcoded_umi{
my $file = shift;
warn "Running in >>> UMI-mode <<< (no mismatches in UMI tolerated)\n\n"; sleep(1);
my %unique_seqs;
my %positions;
if ($file =~ /\.gz$/){
open (IN,"gunzip -c $file |") or die "Unable to read from gzipped file $file: $!\n";
}
elsif ($file =~ /\.bam$/){
open (IN,"$samtools_path view -h $file |") or die "Unable to read from BAM file $file: $!\n";
}
else{
open (IN,$file) or die "Unable to read from $file: $!\n";
}
my $outfile = $file;
$outfile =~ s/\.gz$//;
$outfile =~ s/\.sam$//;
$outfile =~ s/\.bam$//;
$outfile =~ s/\.txt$//;
if ($bam == 1){
$outfile =~ s/$/.UMI_deduplicated.bam/;
}
else{
$outfile =~ s/$/.UMI_deduplicated.sam/;
}
if ($bam == 1){
open (OUT,"| $samtools_path view -bSh 2>/dev/null - > $outfile") or die "Failed to write to $outfile: $!\n";
}
else{
open (OUT,'>',$outfile) or die "Unable to write to $outfile: $!\n";
}
my $count = 0;
my $unmapped = 0;
my $unique_seqs = 0;
my $removed = 0;
while (<IN>){
### if this was a SAM file we ignore header lines
if (/^\@\w{2}\t/){
# warn "skipping SAM header line:\t$_";
print OUT; # Printing the header lines again into the de-duplicated file
next;
}
my $composite; # storing positional data. For single end data we are only using the start coordinate since the end might have been trimmed to different lengths
### in this UMI mode we also store the read barcode (UMI) as additional means of assisting the deduplication
### in effect the $composite string looks like this (separated by ':'):
### FLAG:chromosome:start->{barcode}
my $end;
my $line1;
# SAM format
my ($id,$strand,$chr,$start,$cigar) = (split (/\t/))[0,1,2,3,5]; # we are assigning the FLAG value to $strand
if ($single){
if($strand & 0x4){
++$unmapped;
# warn "Sequence unmapped -> skipping\n";
next;
}
}
++$count;
my $umi_seq;
if ($double_umi){
$id =~ /:R1:(\w+):R2:(\w+):.*$/; # adapting for Tom's barcodes, possibly subject to change
my $umi1 = $1;
my $umi2 = $2;
$umi_seq = $umi1.$umi2;
}
else{
$id =~ /.*:(.+)$/;
$umi_seq = $1;
}
if ($paired){
# warn "paired-end mode\n"
}
# warn "$umi_seq\n"; sleep(1);
if ($umi_seq){
if ($umi_seq =~ /[^GATCNgatcn\+]/){
# warn "UMI was: $umi_seq\nLine was: $_\n";
die "Failed to extract a UMI that looks like a DNA sequence: $umi_seq (last element of each read ID needs to be the UMI sequence, e.g. ':CATGAT'\n\n";
}
}
else{
die "Failed to extract a UMI from the read ID (last element of each read ID needs to be the UMI sequence, e.g. ':CATGAT'\n\n";
}
### SAM single-end
if ($single){
if ($strand == 0 ){
### read aligned to the forward strand. No action needed
}
elsif ($strand == 16){
### read is on reverse strand
### ignoring reverse reads for the moment
$start -= 1; # only need to adjust this once
# for InDel free matches we can simply use the M number in the CIGAR string
if ($cigar =~ /^(\d+)M$/){ # linear match
$start += $1;
}
else{
# parsing CIGAR string
my @len = split (/\D+/,$cigar); # storing the length per operation
my @ops = split (/\d+/,$cigar); # storing the operation
shift @ops; # remove the empty first element
die "CIGAR string contained a non-matching number of lengths and operations\n" unless (scalar @len == scalar @ops);
# warn "CIGAR string; $cigar\n";
### determining end position of a read
foreach my $index(0..$#len){
if ($ops[$index] eq 'M'){ # standard matching bases
$start += $len[$index];
# warn "Operation is 'M', adding $len[$index] bp\n";
}
elsif($ops[$index] eq 'I'){ # insertions do not affect the end position
# warn "Operation is 'I', next\n";
}
elsif($ops[$index] eq 'D'){ # deletions do affect the end position
# warn "Operation is 'D', adding $len[$index] bp\n";
$start += $len[$index];
}
elsif($ops[$index] eq 'S'){ # soft-clipped bases do NOT affect the end position
# warn "Operation is 'S' (SE BAM (UMI mode))\n";
}
elsif ($ops[$index] eq 'N'){ # splice junctions are similar to deletions and do count towards the end position
# warn "Operation is 'N', adding $len[$index] bp\n";
$start += $len[$index];
}
else{
die "SE BAM (UMI mode): Found CIGAR operations other than M, I, S, N or D: '$ops[$index]'. Not allowed at the moment\n";
}
}
}
}
### Here we take the barcode sequence into consideration
$composite = join (":",$strand,$chr,$start,$umi_seq);
# warn "$composite\n"; sleep(1);
}
elsif($paired){
### storing the current line
$line1 = $_;
if($hic){
## Added this section 30 09 2021
# warn "Hi-C mode:\n";
### reading in the next line
my $line2 = <IN>;
chomp $line1;
chomp $line2;
# warn "R1: $line1\n";
# warn "R2: $line2\n~~~~~~~~~~~~~~~~~\n";
# For Hi-C mode it should be enough to work with the chromosome and start positions of both R1 and R2
my ($chr_r1,$start_r1) = (split (/\t/,$line1))[2,3];
my ($chr_r2,$start_r2) = (split (/\t/,$line2))[2,3];
# print "$chr_r1\t$start_r1\n$chr_r2\t$start_r2\n"; sleep(1);
# Hi-C data essentially behaves like 2 separate single-end alignments, so we
# should be fine to just score chr1:start1:chr2:start2:UMI. Since we don't
# know whether R1 and R2 are aligned in a directional fashion, we need to test
# both combinations.
### Here we take the barcode sequence into consideration
my $composite1 = join (":",$chr_r1,$start_r1,$chr_r2,$start_r2,$umi_seq);
my $composite2 = join (":",$chr_r2,$start_r2,$chr_r1,$start_r1,$umi_seq);
my $comp_pos1 = join (":",$chr_r1,$start_r1,$chr_r2,$start_r2);
my $comp_pos2 = join (":",$chr_r2,$start_r2,$chr_r1,$start_r1);
# print ("$composite1\n$composite2\n\n :::::\n\n"); sleep(1);
if (exists $unique_seqs{$composite1} ){
++$removed;
# warn "Exactly this read combination was present already\n";
# If a read was found at this position already, we record both R1/R2 combinations (and devide this number by 2 for reporting)
unless (exists $positions{$comp_pos1}){
$positions{$comp_pos1}++;
$positions{$comp_pos2}++;
}
}
elsif(exists $unique_seqs{$composite2}){
++$removed;
# warn "Exactly this read combination was present already\n";
# If a read was found at this position already, we record both R1/R2 combinations (and devide this number by 2 for reporting)
unless (exists $positions{$comp_pos1}){
$positions{$comp_pos1}++;
$positions{$comp_pos2}++;
}
}
else{
print OUT "$line1\n"; # printing first line of Hi-C output
print OUT "$line2\n"; # printing second line of Hi-C output
# print "$line1\n$line2\n"; sleep(1);
# If neither read combination was found so far, it should be enough to record a single one, e.g. composite1
$unique_seqs{$composite1}++;
}
# Optional detailed UMI report
if ($detail){
push @{$umi_reporting{$umi_seq}},"${chr_r1}:${start_r1}:::${chr_r2}:${start_r2}";
}
}
else{
my $flag = (split /\t/,$line1)[1];
# if the read aligns in forward orientation we can certainly use the start position of read 1, and only need to work out the end position of read 2
if ($flag == 99){ # 99 is paired-end, properly paired, read first in pair, mate on reverse strand
### reading in the next line
$_ = <IN>;
# the only thing we need is the end position
($end,my $cigar_2) = (split (/\t/))[3,5];
$end -= 1; # only need to adjust this once
# for InDel free matches we can simply use the M number in the CIGAR string
if ($cigar_2 =~ /^(\d+)M$/){ # linear match
$end += $1;
}
else{
# parsing CIGAR string
my @len = split (/\D+/,$cigar_2); # storing the length per operation
my @ops = split (/\d+/,$cigar_2); # storing the operation
shift @ops; # remove the empty first element
die "CIGAR string contained a non-matching number of lengths and operations ($cigar_2)\n" unless (scalar @len == scalar @ops);
# warn "CIGAR string; $cigar_2\n";
### determining end position of the read
foreach my $index(0..$#len){
if ($ops[$index] eq 'M'){ # standard matching bases
$end += $len[$index];
# warn "Operation is 'M', adding $len[$index] bp\n";
}
elsif($ops[$index] eq 'I'){ # insertions do not affect the end position
# warn "Operation is 'I', next\n";
}
elsif($ops[$index] eq 'D'){ # deletions do affect the end position
# warn "Operation is 'D',adding $len[$index] bp\n";
$end += $len[$index];
}
elsif($ops[$index] eq 'S'){ # soft-clipped bases do NOT affect the end position
# warn "Operation is 'S' (PE BAM (UMI mode))\n";
}
elsif($ops[$index] eq 'N'){ # skipped regions (e.g. splice junctions) do affect the end position
# warn "Operation is 'N',adding $len[$index] bp\n";
$end += $len[$index];
}
else{
die "PE BAM (UMI mode): Found CIGAR operations other than M, I, S, N or D: '$ops[$index]'. Not allowed at the moment\n";
}
}
}
$composite = join (":",$strand,$chr,$start,$end,$umi_seq);
}
elsif($flag == 83){
# Flag 83 is paired-end, properly paired, read reverse strand, first in pair
# else read 1 aligns in reverse orientation and we need to work out the end of the fragment first, and use the start of the next line
$end = $start - 1; # need to adjust this only once
# for InDel free matches we can simply use the M number in the CIGAR string
if ($cigar =~ /^(\d+)M$/){ # linear match
$end += $1;
}
else{
# parsing CIGAR string
my @len = split (/\D+/,$cigar); # storing the length per operation
my @ops = split (/\d+/,$cigar); # storing the operation
shift @ops; # remove the empty first element
die "CIGAR string contained a non-matching number of lengths and operations ($cigar)\n" unless (scalar @len == scalar @ops);
# warn "CIGAR string; $cigar\n";
### determining end position of the read
foreach my $index(0..$#len){
if ($ops[$index] eq 'M'){ # standard matching bases
$end += $len[$index];
# warn "Operation is 'M', adding $len[$index] bp\n";
}
elsif($ops[$index] eq 'I'){ # insertions do not affect the end position
# warn "Operation is 'I', next\n";
}