lib/Bio/ToolBox/db_helper/hts.pm untested

filter: Statementstmt 0.0% 0 / 167 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 268 CC 28 SCAR 40.7
CC
28
Cov
0%
sum_total_bam_alignments
132.0
collect_bam_scores
90.0
check_bam_index
30.0
CRAP 58.5
1 package Bio::ToolBox::db_helper::hts;
2  
3 use warnings;
4 use strict;
5 use Carp;
6 use English qw(-no_match_vars);
7 use Bio::ToolBox::db_helper::constants;
8 use Bio::ToolBox::db_helper::alignment_callbacks;
9 use Bio::DB::HTS;
10 require Exporter;
11  
12 my $parallel;
13 eval {
14 # check for parallel support, when counting bam alignments
15 require Parallel::ForkManager;
16 $parallel = 1;
17 };
18  
19 our $VERSION = '2.03';
20  
21 # Exported names
22 our @ISA = qw(Exporter);
23  
24 ## no critic
25 ## this is never intended to be used directly by end users
26 ## and exporting everything is required
27 our @EXPORT = qw(
28 open_bam_db
29 open_indexed_fasta
30 check_bam_index
31 write_new_bam_file
32 collect_bam_scores
33 sum_total_bam_alignments
34 );
35 ## use critic
36  
37 # Hash of Bam chromosomes
38 my %BAM_CHROMOS;
39  
40 # sometimes user may request a chromosome that's not in the bigfile
41 # that could lead to an exception
42 # we will record the chromosomes list in this hash
43 # $BAM_CHROMOS{bamfile}{chromos}
44 # we also record the chromosome name variant with or without chr prefix
45 # to accommodate different naming conventions
46  
47 # Opened Bam db objects
48 my %OPENED_BAM;
49  
50 # a cache for opened Bam files
51 # caching here is only for local purposes of collecting scores
52 # db_helper also provides caching of db objects but with option to force open in
53 # the case of forking processes - we don't have that here
54  
55 ### Open a bam database connection
56 sub open_bam_db {
57 my $bamfile = shift;
58  
59 # check the path
60 my $path = $bamfile;
61 $path =~ s/^file://; # strip the file prefix if present
62  
63 # check for bam index
64 check_bam_index($path);
65  
66 # open the bam database object
67 # we specifically do not cache the bam object or chromosome names here
68 my $sam;
69 eval { $sam = Bio::DB::HTS->new( -bam => $path ); };
70 if ($sam) {
71 return $sam;
72 }
73 elsif ( $EVAL_ERROR or $OS_ERROR ) {
74 carp "ERROR: Unable to open Bam file: $EVAL_ERROR $OS_ERROR";
75 return;
76 }
77 else {
78 return;
79 }
80 }
81  
82 ### Open an indexed fasta file
83 sub open_indexed_fasta {
84 my $fasta = shift;
85 eval { require Bio::DB::HTS::Faidx }; # this should be available
86 my $fai = Bio::DB::HTS::Faidx->new($fasta);
87  
88 # this should automatically build the fai index if possible
89 return $fai if defined $fai;
90 }
91  
92 ### Check for a bam index
93 sub check_bam_index {
94  
95 # HTSlib can accept either .bam.bai or .bai
96 my $bamfile = shift;
97  
98 # check for possible index names
99 return if -e "$bamfile.bai"; # .bam.bai
100 return if -e "$bamfile.crai"; # .cram.crai
101 return if -e "$bamfile.csi"; # .bam.csi
102 my $alt_index = $bamfile;
103 $alt_index =~ s/m$/i/i; # change bam to bai or cram to crai
104 return if -e $alt_index;
105  
106 # existing index can't be found, so make one
107 Bio::DB::HTSfile->reindex($bamfile);
108 }
109  
110 ### Write a new bam file
111 sub write_new_bam_file {
112 my $file = shift;
113 $file .= '.bam' unless $file =~ /\.bam$/i;
114 my $bam = Bio::DB::HTSfile->open( $file, 'wb' );
115 carp "ERROR: unable to open bam file $file!" unless $bam;
116 return $bam;
117 }
118  
119 ### Collect Bam scores
120 sub collect_bam_scores {
121  
122 # passed parameters as array ref
123 # chromosome, start, stop, strand, strandedness, method, db, dataset
124 my $param = shift;
125  
126 # initialize score structures
127 # which one is used depends on the return type variable
128 my %pos2data; # either position => count or position => [scores]
129 my $scores = []; # just scores
130  
131 # look at each bamfile
132 # usually there is only one, but there may be more than one
133 for ( my $b = DATA; $b < scalar @{$param}; $b++ ) {
134  
135 ## Open the Bam File
136 my $bamfile = $param->[$b];
137 my $bam = $OPENED_BAM{$bamfile} || undef;
138 unless ($bam) {
139  
140 # open and cache the bam file
141 $bam = open_bam_db($bamfile)
142 or croak "FATAL: Unable to open bam file '$bamfile'!";
143 $OPENED_BAM{$bamfile} = $bam;
144  
145 # record the chromosomes and possible variants
146 $BAM_CHROMOS{$bamfile} = {};
147 foreach my $s ( $bam->seq_ids ) {
148 $BAM_CHROMOS{$bamfile}{$s} = $s;
149 if ( $s =~ /^chr(.+)$/ ) {
150 $BAM_CHROMOS{$bamfile}{$1} = $s;
151 }
152 else {
153 $BAM_CHROMOS{$bamfile}{"chr$s"} = $s;
154 }
155 }
156 }
157  
158 # first check that the chromosome is present
159 my $chromo = $BAM_CHROMOS{$bamfile}{ $param->[CHR] } or next;
160  
161 # convert coordinates into low level coordinates
162 # consumed by the low level Bam API
163 my ( $tid, $zstart, $end ) = $bam->header->parse_region(
164 sprintf( "%s:%d-%d", $chromo, $param->[STRT], $param->[STOP] ) );
165  
166 ## Collect the data according to the requested value type
167 # we will either use simple coverage or alignments (count)
168 if ( $param->[METH] =~ /count/ ) {
169  
170 # Need to collect and count alignments
171  
172 ## Set the callback and a callback data structure
173 my $callback = assign_callback($param);
174 my %data = (
175 'scores' => $scores,
176 'index' => \%pos2data,
177 'start' => $param->[STRT],
178 'stop' => $param->[STOP],
179 );
180  
181 # get the alignments
182 # we are using the low level API to eke out performance
183 $bam->hts_index->fetch( $bam->hts_file, $tid, $zstart, $end, $callback,
184 \%data );
185 }
186 else {
187 ## Coverage
188 # I am assuming everything else is working with read coverage
189  
190 # generate the coverage, this will ignore strand
191 my $coverage = $bam->hts_index->coverage(
192 $bam->hts_file,
193 $tid,
194 $zstart, # 0-based coordinates
195 $end,
196 );
197  
198 # convert the coverage data
199 # by default, this should return the coverage at 1 bp resolution
200 if ( scalar @{$coverage} ) {
201  
202 # check whether we need to index the scores
203 if ( $param->[RETT] == 2 ) {
204 for ( my $i = $param->[STRT]; $i <= $param->[STOP]; $i++ ) {
205  
206 # move the scores into the position score hash
207 $pos2data{$i} += $coverage->[ $i - $param->[STRT] ];
208 }
209 }
210 else {
211 $scores = $coverage;
212 }
213 }
214 }
215 }
216  
217 ## Return collected data
218 if ( $param->[RETT] == 2 ) {
219 return wantarray ? %pos2data : \%pos2data;
220 }
221 else {
222 return wantarray ? @{$scores} : $scores;
223 }
224 }
225  
226 ### Determine total number of alignments in a bam file
227 sub sum_total_bam_alignments {
228  
229 # Passed arguments;
230 my $sam_file = shift;
231 my $cpu = shift || 2; # number of forks to execute in parallel
232 $cpu = 1 unless ($parallel);
233 unless ($sam_file) {
234 carp 'ERROR: no Bam file or bam db object passed!';
235 return;
236 }
237  
238 # Open Bam file if necessary
239 my $bam;
240 my $bam_ref = ref $sam_file;
241 if ( $bam_ref =~ /Bio::DB::HTS/x ) {
242  
243 # we have an opened sam db object
244 $bam = $sam_file;
245 }
246 else {
247 # we have a name of a sam file
248 $bam = open_bam_db($sam_file);
249 return unless ($bam);
250 }
251  
252 # prepare the alignment iterator callback
253 my $callback = sub {
254 my ( $a, $n ) = @_;
255  
256 # check alignment flags
257 my $flag = $a->flag;
258 return if $flag & 0xf04; # UNMAP,SECONDARY,QCFAIL,DUP,SUPPLEMENTARY
259  
260 # check mapping quality based on global variable
261 return if $a->qual < $MAPQ;
262  
263 # count properly paired alignments only once by skipping reverse alignment
264 if ( $flag & 0x01 and $flag & 0x2 ) {
265 return if ( $flag & 0x10 );
266 }
267  
268 # count this fragment
269 ${$n}++;
270 };
271  
272 # prepare the counting subroutine
273 my $counter = sub {
274 my $tid = shift;
275 my $number = 0;
276 $bam->hts_index->fetch( $bam->hts_file, $tid, 0, $bam->target_len($tid),
277 $callback, \$number );
278 return $number;
279 };
280  
281 # Count the alignments on each chromosome
282 my $total_read_number = 0;
283 if ( $cpu > 1 ) {
284  
285 # count each chromosome in multiple parallel threads to speed things up
286  
287 # generate relatively equal lists of chromosome for each process based on length
288 my @chromosomes = map { $_->[0] }
289 sort { $b->[1] <=> $a->[1] }
290 map { [ $_, $bam->target_len($_) ] } ( 0 .. $bam->n_targets - 1 );
291 my @list; # array of arrays, [process][chromosome id]
292 my $i = 1;
293 while (@chromosomes) {
294 push @{ $list[$i] }, shift @chromosomes;
295 $i++;
296 $i = 1 if $i > $cpu;
297 }
298  
299 # we will use Parallel ForkManager for convenience
300 my $pm = Parallel::ForkManager->new($cpu);
301 $pm->run_on_finish(
302 sub {
303 my ( $pid, $exit_code, $ident, $exit_signal, $core_dump, $count ) =
304 @_;
305 $total_read_number += ${$count};
306 }
307 );
308  
309 # Count the chromosomes in parallel processess
310 foreach my $n ( 1 .. $cpu ) {
311 $pm->start and next;
312  
313 ### In child
314 $bam->clone; # to make it fork safe
315 my $count = 0;
316 foreach ( @{ $list[$n] } ) {
317  
318 # count each chromosome in this process list
319 $count += &{$counter}($_);
320 }
321 $pm->finish( 0, \$count );
322 }
323 $pm->wait_all_children;
324 }
325  
326 else {
327 # loop through all the chromosomes in one execution thread
328 for my $tid ( 0 .. $bam->n_targets - 1 ) {
329  
330 # each chromosome is internally represented in the bam file as
331 # a numeric target identifier
332 $total_read_number += &{$counter}($tid);
333 }
334 }
335  
336 # done
337 return $total_read_number;
338 }
339  
340 1;
341  
342 __END__