lib/Bio/ViennaNGS/Bam.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« lib/Bio/ViennaNGS/MinimalFeature.pm ↑ Summary lib/Bio/ViennaNGS.pm »
1 # -*-CPerl-*-
2 # Last changed Time-stamp: <2017-06-10 18:20:31 michl>
3  
4 package Bio::ViennaNGS::Bam;
5  
6 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Bio::ViennaNGS;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 0 ▶use Bio::DB::Sam 1.37;
Subroutine BEGIN: called CC=1 SCAR=2.6
11 use Data::Dumper;
12 use File::Basename qw(fileparse);
13 use File::Temp qw(tempfile);
14 use Path::Class;
15 use Carp;
16 use version; our $VERSION = version->declare("$Bio::ViennaNGS::VERSION");
17  
18 our @ISA = qw(Exporter);
19 our @EXPORT = ();
20  
21 our @EXPORT_OK = qw ( split_bam uniquify_bam uniquify_bam2 );
22  
23 #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^#
24 #^^^^^^^^^^^ Subroutines ^^^^^^^^^^#
25 #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^#
26  
27 sub split_bam {
28 my %data = ();
29 my @NHval = ();
30 my @processed_files = ();
31 my ($verbose,$nh_warning_issued) = (0)x2;
32 my ($bamfile,$reverse,$want_uniq,$want_bed,$dest_dir,$log) = @_;
33 my ($bam,$sam,$bn,$path,$ext,$header,$flag,$NH,$eff_strand,$tmp);
34 my ($bam_pos,$bam_neg,$tmp_bam_pos,$tmp_bam_neg,$bamname_pos,$bamname_neg);
35 my ($bed_pos,$bed_neg,$bedname_pos,$bedname_neg);
36 my ($seq_id,$start,$stop,$strand,$target_names,$id,$score);
37 my $this_function = (caller(0))[3];
38 my %count_entries = (
39 total => 0,
40 uniq => 0,
41 pos => 0,
42 neg => 0,
43 skip => 0,
44 cur => 0,
45 mult => 0,
46 se_alis => 0,
47 pe_alis => 0,
48 flag => 0,
49 unmapped => 0,
50 );
51 $data{count} = \%count_entries;
52 $data{flag} = ();
53 $data{nh_issues} = 0; # will be set to 1 if NH attribute is missing
54 $nh_warning_issued = 0;
55  
56 croak "ERROR [$this_function] $bamfile does not exist\n"
57 unless (-e $bamfile);
58 croak "ERROR [$this_function] $dest_dir does not exist\n"
59 unless (-d $dest_dir);
60  
61 (undef,$tmp_bam_pos) = tempfile('BAM_POS_XXXXXXX',UNLINK=>0);
62 (undef,$tmp_bam_neg) = tempfile('BAM_NEG_XXXXXXX',UNLINK=>0);
63  
64 $bam = Bio::DB::Bam->open($bamfile, "r");
65 $header = $bam->header;
66 $target_names = $header->target_name;
67  
68 ($bn,$path,$ext) = fileparse($bamfile, qr /\..*/);
69 unless ($dest_dir =~ /\/$/){$dest_dir .= "/";}
70 $bamname_pos = $dest_dir.$bn.".pos".$ext;
71 $bamname_neg = $dest_dir.$bn.".neg".$ext;
72 $bam_pos = Bio::DB::Bam->open($tmp_bam_pos,'w')
73 or croak "ERROR [$this_function] Could not open bam_pos file for writing: $!";
74 $bam_neg = Bio::DB::Bam->open($tmp_bam_neg,'w')
75 or croak "ERROR [$this_function] Could not open bam_neg file for writing: $!";
76  
77 if ($want_bed == 1){
78 $bedname_pos = $dest_dir.$bn.".pos.bed";
79 $bedname_neg = $dest_dir.$bn.".neg.bed";
80 open($bed_pos, ">", $bedname_pos); open($bed_neg, ">", $bedname_neg);
81 }
82  
83 $bam_pos->header_write($header);$bam_neg->header_write($header);
84 if($reverse == 1) { # switch +/- strand mapping
85 $tmp = $bam_pos;$bam_pos = $bam_neg;$bam_neg = $tmp;
86 $tmp = $bed_pos;$bed_pos = $bed_neg;$bed_neg = $tmp;
87 }
88  
89 while (my $read= $bam->read1() ) {
90 @NHval = ();
91 $data{count}{total}++;
92  
93 # collect statistics of SAM flags
94 $flag = $read->flag;
95 unless (exists $data{flag}{$flag}){
96 $data{flag}{$flag} = 0;
97 }
98 $data{flag}{$flag}++;
99  
100 # skip unmapped reads
101 if ( $read->get_tag_values('UNMAPPED') ){
102 $data{count}{unmapped}++;
103 next;
104 }
105  
106 # check if NH (the SAM tag used to indicate multiple mappings) is set
107 if ($read->has_tag("NH")) {
108 @NHval = $read->get_tag_values("NH");
109 $NH = $NHval[0];
110 if ($NH == 1) {$data{count}{uniq}++;}
111 else {
112 $data{count}{mult}++;
113 if ($want_uniq == 1) { # skip processing this read if it is a mutli-mapper
114 $data{count}{skip}++;
115 next;
116 }
117 }
118 }
119 else{ # no NH tag found
120 $data{nh_issues} = 1; # set this once and for all
121 unless ($nh_warning_issued == 1){
122 carp "WARN [$this_function] Read ".$read->query->name." does not have NH attribute\n";
123 $nh_warning_issued = 1;
124 }
125 }
126  
127 # print Dumper ($read->query);
128 $strand = $read->strand;
129 $seq_id = $target_names->[$read->tid];
130 $start = $read->start;
131 $stop = $read->end;
132 $id = "x"; # $read->qname;
133 $score = 100;
134  
135 if ( $read->get_tag_values('PAIRED') ) { # paired-end
136 if($verbose == 1) {print STDERR "pe\t";}
137 $data{count}{pe_alis}++;
138 if ( $read->get_tag_values('FIRST_MATE') ){ # 1st mate; take its strand as granted
139 if($verbose == 1) {print STDERR "FIRST_MATE\t".$strand." ";}
140 if ( $strand eq "1" ){
141 $bam_pos->write1($read);
142 if ($want_bed){printf $bed_pos "%s\t%d\t%d\t%s\t%d\t",$seq_id,eval($start-1),$stop,$id,$score;}
143 if ($reverse == 0){
144 $data{count}{pos}++; $eff_strand=$strand;
145 if ($want_bed){printf $bed_pos "%s\n", "+";}
146 }
147 else {
148 $data{count}{neg}++; $eff_strand=-1*$strand;
149 if ($want_bed){printf $bed_pos "%s\n", "-";}
150 }
151 }
152 elsif ($strand eq "-1") {
153 $bam_neg->write1($read);
154 if ($want_bed){printf $bed_neg "%s\t%d\t%d\t%s\t%d\t",$seq_id,eval($start-1),$stop,$id,$score;}
155 if ($reverse == 0){
156 $data{count}{neg}++; $eff_strand=$strand;
157 if ($want_bed){printf $bed_neg "%s\n", "-";}
158 }
159 else {
160 $data{count}{pos}++;$eff_strand=-1*$strand;
161 if ($want_bed){printf $bed_neg "%s\n", "+";}
162 }
163 }
164 else {croak "Strand neither + nor - ...exiting!\n";}
165 }
166 else{ # 2nd mate; reverse strand since the fragment it belongs to is ALWAYS located
167 # on the other strand
168 if($verbose == 1) {print STDERR "SECOND_MATE\t".$strand." ";}
169 if ( $strand eq "1" ) {
170 $bam_neg->write1($read);
171 if ($want_bed){printf $bed_neg "%s\t%d\t%d\t%s\t%d\t",$seq_id,eval($start-1),$stop,$id,$score;}
172 if ($reverse == 0){
173 $data{count}{neg}++;$eff_strand=$strand;
174 if ($want_bed){printf $bed_neg "%s\n", "-";}
175 }
176 else {
177 $data{count}{pos}++; $eff_strand=-1*$strand;
178 if ($want_bed){printf $bed_neg "%s\n", "+";}
179 }
180 }
181 elsif ( $strand eq "-1" ) {
182 $bam_pos->write1($read);
183 if ($want_bed){printf $bed_pos "%s\t%d\t%d\t%s\t%d\t",$seq_id,eval($start-1),$stop,$id,$score;}
184 if ($reverse == 0){
185 $data{count}{pos}++;$eff_strand=$strand;
186 if ($want_bed){printf $bed_pos "%s\n", "+";}
187 }
188 else {
189 $data{count}{neg}++;$eff_strand=-1*$strand;
190 if ($want_bed){printf $bed_pos "%s\n", "-";}
191 }
192 }
193 else {croak "Strand neither + nor - ...exiting!\n";}
194 }
195 }
196 else { # single-end
197 if($verbose == 1) {print STDERR "se\t";}
198 $data{count}{se_alis}++;
199 if ( $read->strand eq "1" ){
200 $bam_pos->write1($read);
201 if ($want_bed){printf $bed_pos "%s\t%d\t%d\t%s\t%d\t",$seq_id,eval($start-1),$stop,$id,$score;}
202 if ($reverse == 0){
203 $data{count}{pos}++;$eff_strand=$strand;
204 if ($want_bed){printf $bed_pos "%s\n", "+";}
205 }
206 else {
207 $data{count}{neg}++;$eff_strand=-1*$strand;
208 if ($want_bed){printf $bed_pos "%s\n", "-";}
209 }
210 }
211 elsif ($read->strand eq "-1") {
212 $bam_neg->write1($read);
213 if ($want_bed){printf $bed_neg "%s\t%d\t%d\t%s\t%d\t",$seq_id,eval($start-1),$stop,$id,$score;}
214 if ($reverse == 0){
215 $data{count}{neg}++;$eff_strand=$strand;
216 if ($want_bed){printf $bed_neg "%s\n", "-";}
217 }
218 else {
219 $data{count}{pos}++;$eff_strand=-1*$strand;
220 if ($want_bed){printf $bed_neg "%s\n", "+";}
221 }
222 }
223 else {croak "Strand neither + nor - ...exiting!\n";}
224 }
225 if($verbose == 1) {print STDERR "--> ".$eff_strand."\t";}
226  
227 # count considered reads
228 $data{count}{cur}++;
229  
230 } # end while
231  
232 rename ($tmp_bam_pos, $bamname_pos);
233 rename ($tmp_bam_neg, $bamname_neg);
234 push (@processed_files, ($bamname_pos,$bamname_neg));
235 push (@processed_files, ($data{count}{pos},$data{count}{neg}));
236 if ($want_bed){
237 push (@processed_files, ($bedname_pos,$bedname_neg))
238 }
239  
240 # error checks
241 unless ($data{count}{pe_alis} + $data{count}{se_alis} == $data{count}{cur}) {
242 printf "ERROR: paired-end + single-end != total alignments\n";
243 print Dumper(\%data);
244 croak $!;
245 }
246 unless ($data{count}{pos} + $data{count}{neg} == $data{count}{cur}) {
247 printf STDERR "%20d fragments on [+] strand\n",$data{count}{pos};
248 printf STDERR "%20d fragments on [-] strand\n",$data{count}{neg};
249 printf STDERR "%20d sum\n",eval($data{count}{pos}+$data{count}{neg});
250 printf STDERR "%20d unmapped reads\n",$data{count}{unmapped};
251 printf STDERR "%20d total alignment/read count\n",$data{count}{cur};
252 printf STDERR "ERROR: pos alignments + neg alignments != total alignments\n";
253 print Dumper(\%data);
254 croak $!;
255 }
256 foreach (keys %{$data{flag}}){
257 $data{count}{flag} += $data{flag}{$_};
258 }
259 unless ($data{count}{flag} == $data{count}{cur} + $data{count}{unmapped}){
260 printf STDERR "%20d alignments considered\n",$data{count}{cur};
261 printf STDERR "%20d unmapped reads\n",$data{count}{unmapped};
262 printf STDERR "%20d alignments found in flag statistics\n",$data{count}{flag};
263 printf STDERR "ERROR: alignments considered + unmapped reads != alignments from flag stat\n";
264 print Dumper(\%data);
265 croak $!;
266 }
267  
268 # logging output
269 open(LOG, ">", $log) or croak $!;
270 printf LOG "# bam_split.pl log for file \'$bamfile\'\n";
271 printf LOG "#-----------------------------------------------------------------\n";
272 printf LOG "%20d total alignments (unique/multi/unmapped)\n",$data{count}{total};
273 printf LOG "%20d unique-mappers (%7.2f%% of total) ",
274 $data{count}{uniq},eval(100*$data{count}{uniq}/$data{count}{total});
275 if ($data{nh_issues}){printf LOG " *** NH attribute issues ***";}
276 printf LOG "\n";
277 printf LOG "%20d multi-mappers (%7.2f%% of total) ",
278 $data{count}{mult},eval(100*$data{count}{mult}/$data{count}{total});
279 if ($data{nh_issues}){printf LOG " *** NH attribute issues ***";}
280 printf LOG "\n";
281 printf LOG "%20d skipped\n", $data{count}{skip};
282 printf LOG "%20d alignments considered\n", $data{count}{cur};
283 printf LOG "%20d paired-end\n", $data{count}{pe_alis};
284 printf LOG "%20s single-end\n", $data{count}{se_alis};
285 if($data{count}{cur}>0){
286 printf LOG "%20d fragments on [+] strand (%7.2f%% of considered)\n",
287 $data{count}{pos},eval(100*$data{count}{pos}/$data{count}{cur});
288 printf LOG "%20d fragments on [-] strand (%7.2f%% of considered)\n",
289 $data{count}{neg},eval(100*$data{count}{neg}/$data{count}{cur});
290 }
291 else{
292 printf LOG "%20d fragments on [+] strand\n",$data{count}{pos};
293 printf LOG "%20d fragments on [-] strand\n",$data{count}{neg};
294 }
295 printf LOG "%20d unmapped\n", $data{count}{unmapped};
296 printf LOG "#-----------------------------------------------------------------\n";
297 printf LOG "Dumper output:\n". Dumper(\%data);
298 close(LOG);
299 return @processed_files;
300 }
301  
302 sub uniquify_bam {
303 my %data = ();
304 my ($bamfile,$dest,$log) = @_;
305 my ($bam, $bn,$path,$ext,$read,$header);
306 my ($tmp_uniq,$tmp_mult,$fn_uniq,$fn_mult,$bam_uniq,$bam_mult,$NH);
307 my ($count_all,$count_uniq,$count_mult,$unmapped,$nh_warning_issued) = (0)x5;
308 my @processed_files = ();
309 my @NHval = ();
310 my $this_function = (caller(0))[3];
311 my %count_entries = (
312 total => 0,
313 uniq => 0,
314 mult => 0,
315 unmapped => 0,
316 nonhtag => 0,
317 );
318 $data{count} = \%count_entries;
319 $data{nh_issues} = 0; # will be set to 1 if NH attribute is missing
320  
321 croak "ERROR [$this_function] Cannot find $bamfile\n"
322 unless (-e $bamfile);
323 croak "ERROR [$this_function] $dest does not exist\n"
324 unless (-d $dest);
325  
326 ($bn,$path,$ext) = fileparse($bamfile, qr /\..*/);
327  
328 (undef,$tmp_uniq) = tempfile('BAM_UNIQ_XXXXXXX',UNLINK=>0);
329 (undef,$tmp_mult) = tempfile('BAM_MULT_XXXXXXX',UNLINK=>0);
330  
331 $bam = Bio::DB::Bam->open($bamfile, "r");
332 $fn_uniq = file($dest,$bn.".uniq".$ext);
333 $fn_mult = file($dest,$bn.".mult".$ext);
334 $header = $bam->header; # TODO: modify header, leave traces ...
335  
336 $bam_uniq = Bio::DB::Bam->open($tmp_uniq,'w')
337 or croak "ERROR [$this_function] Cannot open temp file for writing: $!";
338 $bam_mult = Bio::DB::Bam->open($tmp_mult,'w')
339 or croak "ERROR [$this_function] Cannot open temp file for writing: $!";
340 $bam_uniq->header_write($header);
341 $bam_mult->header_write($header);
342  
343 while ($read = $bam->read1() ) {
344 $data{count}{total}++;
345  
346 # skip unmapped reads
347 if ( $read->get_tag_values('UNMAPPED') ){
348 $data{count}{unmapped}++;
349 next;
350 }
351  
352 # check if NH (the SAM tag used to indicate multiple mappings) is set
353 if ($read->has_tag("NH")) {
354 @NHval = $read->get_tag_values("NH");
355 $NH = $NHval[0];
356 if ($NH == 1) {
357 $bam_uniq->write1($read);
358 $data{count}{uniq}++;
359 }
360 else {
361 $bam_mult->write1($read);
362 $data{count}{mult}++;
363 }
364 }
365 else{ # no NH tag found
366 $data{nh_issues} = 1; # set this once and for all
367 unless ($nh_warning_issued == 1){
368 $data{count}{nonhtag}++;
369 carp "ERROR [$this_function] Read ".$read->query->name.
370 " does not have NH attribute\nCannot continue ...";
371 $nh_warning_issued = 1;
372 }
373 }
374 }
375  
376 unless ($data{count}{uniq} + $data{count}{mult} ==
377 $data{count}{total} - $data{count}{unmapped} - $data{count}{nonhtag}){
378 printf STDERR "%20d unique alignments\n",$data{count}{uniq};
379 printf STDERR "%20d multiple alignments\n",$data{count}{mult};
380 printf STDERR "%20d total alignments\n",$data{count}{total};
381 printf STDERR "%20d unmapped reads\n",$data{count}{unmapped};
382 croak "ERROR [$this_function] Read counts don't match\n";
383 }
384  
385 rename ($tmp_uniq, $fn_uniq);
386 rename ($tmp_mult, $fn_mult);
387 push (@processed_files, ($fn_uniq,$fn_mult));
388  
389 if (defined $log){
390 my $lf = file($dest,$log);
391 open(LOG, ">", $lf) or croak $!;
392 printf LOG "%15d reads total\n%15d unique alignments\n%15d multiple alignments\n%15d unmapped\n",
393 $data{count}{total},$data{count}{uniq},$data{count}{mult},$data{count}{unmapped};
394 close(LOG);
395 }
396 }
397  
398 sub uniquify_bam2 {
399 my %data = ();
400 my ($bamfile,$dest,$log) = @_;
401 my ($bam, $bn,$path,$ext,$read,$header,$ali);
402 my ($tmp_uniq,$tmp_mult,$fn_uniq,$fn_mult,$bam_uniq,$bam_mult,$NH);
403 my ($count_all,$count_uniq,$count_mult,$unmapped,$nh_warning_issued) = (0)x5;
404 my $pushme = 0;
405 my $allgomulti = 0;
406 my @processed_files = ();
407 my @NHval = ();
408 my $lastqname = undef;
409 my @band = ();
410 my $this_function = (caller(0))[3];
411 my %count_entries = (
412 total => 0,
413 uniq => 0,
414 mult => 0,
415 unmapped => 0,
416 nonhtag => 0,
417 );
418 $data{count} = \%count_entries;
419 $data{nh_issues} = 0; # will be set to 1 if NH attribute is missing
420  
421 croak "ERROR [$this_function] Cannot find $bamfile\n"
422 unless (-e $bamfile);
423 croak "ERROR [$this_function] $dest does not exist\n"
424 unless (-d $dest);
425  
426 ($bn,$path,$ext) = fileparse($bamfile, qr /\..*/);
427  
428 (undef,$tmp_uniq) = tempfile('BAM_UNIQ_XXXXXXX',UNLINK=>0);
429 (undef,$tmp_mult) = tempfile('BAM_MULT_XXXXXXX',UNLINK=>0);
430  
431 $bam = Bio::DB::Bam->open($bamfile, "r");
432 $fn_uniq = file($dest,$bn.".uniq.band.".$ext);
433 $fn_mult = file($dest,$bn.".mult.band.".$ext);
434 $header = $bam->header; # TODO: modify header, leave traces ...
435  
436 $bam_uniq = Bio::DB::Bam->open($tmp_uniq,'w')
437 or croak "ERROR [$this_function] Cannot open temp file for writing: $!";
438 $bam_mult = Bio::DB::Bam->open($tmp_mult,'w')
439 or croak "ERROR [$this_function] Cannot open temp file for writing: $!";
440 $bam_uniq->header_write($header);
441 $bam_mult->header_write($header);
442  
443 while ($read = $bam->read1() ) {
444 $data{count}{total}++;
445  
446 # skip unmapped reads
447 if ( $read->get_tag_values('UNMAPPED') ){
448 $data{count}{unmapped}++;
449 next;
450 }
451  
452 my $qname = $read->qname;
453 $qname =~ s/\/[12]$//;
454  
455 if (!defined($lastqname) || $qname eq $lastqname ){
456 #print "$qname\n";
457 push @band, $read;
458 }
459 else {
460 # band is now completely read, processing it ...
461 foreach $ali (@band){
462 # check if NH (the SAM attribute used to indicate multiple mappings) is set
463 if ($ali->has_tag("NH")) {
464 @NHval = $ali->get_tag_values("NH");
465 $NH = $NHval[0];
466 if ($NH > 1) {
467 $allgomulti = 1;
468 $data{count}{mult}++;
469 }
470 else {
471 $data{count}{uniq}++;
472 }
473 }
474 else{ # no NH tag found
475 $data{nh_issues} = 1; # set this once and for all
476 unless ($nh_warning_issued == 1){
477 $data{count}{nonhtag}++;
478 carp "ERROR [$this_function] Read ".$read->qname.
479 " does not have NH attribute\nCannot continue ...";
480 $nh_warning_issued = 1;
481 }
482 }
483 } # end foreach
484  
485 if ($allgomulti == 1){ # write entire band to multi mapper file
486 foreach $ali (@band){$bam_mult->write1($ali)}
487 #print " -> mult\n";
488 }
489 else{ # write entire band to uniq mapper file
490 foreach $ali (@band){$bam_uniq->write1($ali)}
491 #print " -> uniq\n";
492 }
493  
494 #print "-----\n";
495 @band = ();
496 $pushme = 1;
497 $allgomulti = 0;
498 } # end else
499  
500 if ($pushme == 1){
501 #print "$qname\n";
502 push @band, $read;
503 $pushme = 0;
504 }
505  
506 $lastqname = $qname;
507 }
508  
509 unless ($data{count}{uniq} + $data{count}{mult} ==
510 $data{count}{total} - $data{count}{unmapped} - $data{count}{nonhtag}){
511 printf STDERR "%20d unique alignments\n",$data{count}{uniq};
512 printf STDERR "%20d multiple alignments\n",$data{count}{mult};
513 printf STDERR "%20d total alignments\n",$data{count}{total};
514 printf STDERR "%20d unmapped reads\n",$data{count}{unmapped};
515 croak "ERROR [$this_function] Read counts don't match\n";
516 }
517  
518 rename ($tmp_uniq, $fn_uniq);
519 rename ($tmp_mult, $fn_mult);
520 push (@processed_files, ($fn_uniq,$fn_mult));
521  
522 if (defined $log){
523 my $lf = file($dest,$log);
524 open(LOG, ">", $lf) or croak $!;
525 printf LOG "%15d reads total\n%15d unique alignments\n%15d multiple alignments\n%15d unmapped\n",
526 $data{count}{total},$data{count}{uniq},$data{count}{mult},$data{count}{unmapped};
527 close(LOG);
528 }
529 }
530  
531  
532 1;
533 __END__
« lib/Bio/ViennaNGS/MinimalFeature.pm ↑ Summary lib/Bio/ViennaNGS.pm »