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

filter: Statementstmt 0.0% 0 / 260 Branchbran 0.0% 0 / 102 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 429 CC 40 SCAR 42.6
CC
40
Cov
0%
open_bigwigset_db
182.0
_lookup_bigwigset_wigs
132.0
collect_bigwig_position_scores
42.0
CRAP 70.6
1 package Bio::ToolBox::db_helper::bigwig;
2  
3 use warnings;
4 use strict;
5 use Carp;
6 use English qw(-no_match_vars);
7 use List::Util qw(min max sum);
8 use Bio::ToolBox::db_helper::constants;
9 use Bio::DB::BigWig qw(binMean binStdev);
10 use Bio::DB::BigWigSet;
11 require Exporter;
12  
13 our $VERSION = '2.02';
14  
15 # Exported names
16 our @ISA = qw(Exporter);
17  
18 ## no critic
19 ## this is never intended to be used directly by end users
20 ## and exporting everything is required
21 our @EXPORT = qw(
22 collect_bigwig_score
23 collect_bigwig_scores
24 collect_bigwig_position_scores
25 collect_bigwigset_score
26 collect_bigwigset_scores
27 collect_bigwigset_position_scores
28 open_bigwig_db
29 open_bigwigset_db
30 );
31 ## use critic
32  
33 # Hash of Bigfile chromosomes
34 our %BIGWIG_CHROMOS;
35  
36 # sometimes user may request a chromosome that's not in the bigfile
37 # that could lead to an exception
38 # we will record the chromosomes list in this hash
39 # $BIGWIG_CHROMOS{bigfile}{chromos}
40 # we also record the chromosome name variant with or without chr prefix
41 # to accommodate different naming conventions
42  
43 # Opened bigWig db objects
44 our %OPENED_BW;
45  
46 # a cache for opened BigWig databases, primarily for collecting scores
47 # caching here is only for local purposes of collecting scores
48 # db_helper also provides caching of db objects but with option to force open in
49 # the case of forking processes - we don't have that here
50  
51 # BigWigSet bigWig IDs
52 our %BIGWIGSET_WIGS;
53  
54 # cache for the bigwigs from a BigWigSet used in a query
55 # we want to use low level bigWig access which isn't normally
56 # available from the high level BigWigSet, so we identify the
57 # bigWigs from the bigWigSet and cache them here
58  
59 # Methods Cache lookup
60 # pre-define the methods code for processing summary objects to avoid
61 # excessive if-elsif tests every data cycle
62 our %ONE_SUMMARY_METHOD = (
63 'mean' => sub { return unless $_[0]; return binMean( $_[0] ) },
64 'sum' => sub { return 0 unless $_[0]; return $_[0]->{sumData} },
65 'min' => sub { return unless $_[0]; return $_[0]->{minVal} },
66 'max' => sub { return unless $_[0]; return $_[0]->{maxVal} },
67 'count' => sub { return 0 unless $_[0]; return $_[0]->{validCount} },
68 'stddev' => sub { return unless $_[0]; return binStdev( $_[0] ) },
69 );
70 our %MULTI_SUMMARY_METHOD = (
71 'mean' => sub {
72 my $summaries = shift;
73 return unless $summaries->[0];
74 my $sum = 0;
75 my $count = 0;
76 foreach my $s ( @{$summaries} ) {
77 $sum += $s->{sumData};
78 $count += $s->{validCount};
79 }
80 return $count ? $sum / $count : '.';
81 },
82 'sum' => sub {
83 my $summaries = shift;
84 return 0 unless $summaries->[0];
85 my $sum = 0;
86 foreach my $s ( @{$summaries} ) {
87 $sum += $s->{sumData};
88 }
89 return $sum;
90 },
91 'min' => sub {
92 my $summaries = shift;
93 return unless $summaries->[0];
94 return min( map { $_->{minVal} } @{$summaries} );
95 },
96 'max' => sub {
97 my $summaries = shift;
98 return unless $summaries->[0];
99 return max( map { $_->{maxVal} } @{$summaries} );
100 },
101 'count' => sub {
102 my $summaries = shift;
103 return 0 unless $summaries->[0];
104 my $count = 0;
105 foreach my $s ( @{$summaries} ) {
106 $count += $s->{validCount};
107 }
108 return $count;
109 },
110 'stddev' => sub {
111 croak
112 'FATAL: cannot calculate stddev value from multiple bigWig Summary objects!';
113 },
114 );
115  
116 ### Modules ###
117  
118 ### Collect single BigWig score
119 sub collect_bigwig_score {
120  
121 # passed parameters as array ref
122 # chromosome, start, stop, strand, strandedness, method, db, dataset
123 my $param = shift;
124  
125 # Collecting summary features
126 # we will collect a summary object for each requested wig feature
127  
128 # Walk through each requested feature
129 # There is likely only one
130 my @summaries;
131 for ( my $d = DATA; $d < scalar @{$param}; $d++ ) {
132 my $bw = _get_bw( $param->[$d] );
133  
134 # first check that the chromosome is present
135 my $chromo = $BIGWIG_CHROMOS{ $param->[$d] }{ $param->[CHR] } or next;
136  
137 # use a low level method to get a single summary hash for 1 bin
138 my $sumArrays = $bw->bf->bigWigSummaryArrayExtended(
139  
140 # chromo, 0-based start, stop, # bins
141 $chromo, $param->[STRT] - 1, $param->[STOP], 1
142 );
143 push @summaries, $sumArrays->[0];
144 }
145  
146 # now process the summary features
147 return _process_summaries( $param->[METH], \@summaries );
148 }
149  
150 ### Collect multiple BigWig scores
151 sub collect_bigwig_scores {
152  
153 # passed parameters as array ref
154 # chromosome, start, stop, strand, strandedness, method, db, dataset
155 my $param = shift;
156  
157 # we don't have support for pcount and ncount, so make sure we change those
158 $param->[METH] = 'count' if $param->[METH] =~ /\wcount/;
159  
160 # Walk through each requested feature
161 # There is likely only one
162 my @scores;
163 for ( my $d = DATA; $d < scalar @{$param}; $d++ ) {
164  
165 # open db object
166 my $bw = _get_bw( $param->[$d] );
167  
168 # first check that the chromosome is present
169 my $chromo = $BIGWIG_CHROMOS{ $param->[$d] }{ $param->[CHR] } or next;
170  
171 # initialize low level stream for this segment
172 my $list =
173 $bw->bf->bigWigIntervalQuery( $chromo, $param->[STRT] - 1, $param->[STOP] );
174 my $f = $list->head;
175 while ($f) {
176  
177 # print $f->start,"..",$f->end,": ",$f->value,"\n";
178 push @scores, $f->value;
179 $f = $f->next;
180 }
181 }
182  
183 # return collected data
184 return wantarray ? @scores : \@scores;
185 }
186  
187 ### Collect positioned BigWig scores
188 sub collect_bigwig_position_scores {
189  
190 # passed parameters as array ref
191 # chromosome, start, stop, strand, strandedness, method, db, dataset
192 my $param = shift;
193  
194 # we don't have support for pcount and ncount, so make sure we change those
195 $param->[METH] = 'count' if $param->[METH] =~ /\wcount/;
196  
197 # initialize
198 my %pos2data; # hash of position => score
199 my %duplicates; # hash of duplicate positions, position => number
200  
201 # Walk through each requested feature
202 # There is likely only one
203 for ( my $d = DATA; $d < scalar @{$param}; $d++ ) {
204  
205 # Open the BigWig file
206 my $bw = _get_bw( $param->[$d] );
207  
208 # first check that the chromosome is present
209 my $chromo = $BIGWIG_CHROMOS{ $param->[$d] }{ $param->[CHR] } or next;
210  
211 # initialize low level stream for this segment
212 my $list =
213 $bw->bf->bigWigIntervalQuery( $chromo, $param->[STRT] - 1, $param->[STOP] );
214 my $f = $list->head;
215 while ($f) {
216  
217 # print $f->start,"..",$f->end,": ",$f->value,"\n";
218 # process the feature
219 for ( my $pos = $f->start + 1; $pos <= $f->end; $pos++ ) {
220  
221 # remember low level features are 0-based
222 # check for duplicate positions
223 # duplicates should not normally exist for a single wig file
224 # but we may be working with multiple wigs that are being combined
225 if ( exists $pos2data{$pos} ) {
226 if ( exists $duplicates{$pos} ) {
227  
228 # append an incrementing number at the end
229 $duplicates{$pos} += 1; # increment first
230 my $new = sprintf( "%d.%d", $pos, $duplicates{$pos} );
231 $pos2data{$new} = $f->value;
232 }
233 else {
234 # first time duplicate
235 my $new = $pos . '.1';
236 $pos2data{$new} = $f->value;
237 $duplicates{$pos} = 1;
238 }
239 }
240 else {
241 $pos2data{$pos} = $f->value;
242 }
243 }
244 $f = $f->next;
245 }
246 }
247  
248 # check for duplicate positions
249 if (%duplicates) {
250 _remove_duplicate_positions( \%pos2data, \%duplicates );
251 }
252  
253 # return collected data
254 return wantarray ? %pos2data : \%pos2data;
255 }
256  
257 sub collect_bigwigset_score {
258  
259 # passed parameters as array ref
260 # chromosome, start, stop, strand, strandedness, method, db, dataset
261 my $param = shift;
262  
263 # lookup the bigWig files based on the parameters
264 my $ids = _lookup_bigwigset_wigs($param);
265 return unless scalar( @{$ids} ) > 0;
266 push @{$param}, @{$ids};
267  
268 # use the low level single bigWig API
269 return collect_bigwig_score($param);
270 }
271  
272 sub collect_bigwigset_scores {
273  
274 # passed parameters as array ref
275 # chromosome, start, stop, strand, strandedness, method, db, dataset
276 my $param = shift;
277  
278 # lookup the bigWig files based on the parameters
279 my $ids = _lookup_bigwigset_wigs($param);
280 return unless scalar( @{$ids} ) > 0;
281 push @{$param}, @{$ids};
282  
283 # use the low level single bigWig API
284 return collect_bigwig_scores($param);
285 }
286  
287 sub collect_bigwigset_position_scores {
288  
289 # passed parameters as array ref
290 # chromosome, start, stop, strand, strandedness, method, db, dataset
291 my $param = shift;
292  
293 # lookup the bigWig files based on the parameters
294 my $ids = _lookup_bigwigset_wigs($param);
295 return unless scalar( @{$ids} ) > 0;
296 push @{$param}, @{$ids};
297  
298 # use the low level single bigWig API
299 return collect_bigwig_position_scores($param);
300 }
301  
302 ### Open a bigWig database connection
303 sub open_bigwig_db {
304  
305 # path
306 my $wigfile = shift;
307 my $path = $wigfile;
308 $path =~ s/^file://; # clean up file prefix if present
309  
310 # open
311 my $bw;
312 eval { $bw = Bio::DB::BigWig->new( -bigwig => $path ); };
313 if ($bw) {
314 return $bw;
315 }
316 elsif ( $EVAL_ERROR or $OS_ERROR ) {
317 carp $EVAL_ERROR;
318 carp $OS_ERROR;
319 return;
320 }
321 else {
322 return;
323 }
324 }
325  
326 ### Open a bigWigSet database connection
327 sub open_bigwigset_db {
328  
329 my $directory = shift;
330  
331 # check for trailing slash
332 # this seems to interfere with generating the list of files, leading
333 # to duplicates: both raw files as well as contents from metadata
334 $directory =~ s/\/$//; # strip trailing slash
335  
336 # open the database connection
337 # we're using the region feature type because that's what the rest of
338 # Bio::ToolBox::db_helper modules expect and work with
339 my $bws;
340 eval {
341 $bws = Bio::DB::BigWigSet->new(
342 -dir => $directory,
343 -feature_type => 'region',
344 );
345 };
346 if ( not $bws and ( $EVAL_ERROR or $OS_ERROR ) ) {
347 carp $EVAL_ERROR;
348 carp $OS_ERROR;
349 return;
350 }
351  
352 # check that we haven't just opened a new empty bigwigset object
353 my @paths = $bws->bigwigs;
354 return unless @paths; # no valid bigWig files, not valid
355  
356 # we have bigwig files, must be a valid bigwigset directory
357  
358 # collect the chromosomes from the first bigwig
359 # we will assume all of the bigwigs have the same chromosomes!
360 _record_seqids( $paths[0], $bws->get_bigwig( $paths[0] ) );
361  
362 # check for potential implied strandedness based on the file name
363 # because the database features are not true SeqFeature objects,
364 # the strand method isn't really supported as expected with SeqFeature
365 # instead it is treated as an attribute, and typical strand convention
366 # of -1, 0, 1 gets messed up with regex matching, so we'll silently
367 # use minus, none, and plus as strand attribute values
368 my $md = $bws->metadata;
369 foreach my $i ( keys %{$md} ) {
370 my $f = $md->{$i}{dbid}; # the file path
371 if ( $f =~ /(?: f | for | forward | top | plus | \+ ) \.bw$/xi ) {
372  
373 # implied forward strand
374 if ( exists $md->{$i}{strand} ) {
375 $md->{$i}{strand} = 'plus' if $md->{$i}{strand} eq '1';
376 }
377 else {
378 $bws->set_bigwig_attributes( $f, { strand => 'plus' } );
379 }
380 }
381 elsif ( $f =~ /(?: r | rev | reverse | bottom | minus | \- ) \.bw$/xi ) {
382  
383 # implied reverse strand
384 if ( exists $md->{$i}{strand} ) {
385 $md->{$i}{strand} = 'minus' if $md->{$i}{strand} eq '-1';
386 }
387 else {
388 $bws->set_bigwig_attributes( $f, { strand => 'minus' } );
389 }
390 }
391 else {
392 # check for strand anyway
393 if ( exists $md->{$i}{strand} ) {
394 $md->{$i}{strand} = 'plus' if $md->{$i}{strand} eq '1';
395 $md->{$i}{strand} = 'minus' if $md->{$i}{strand} eq '-1';
396 $md->{$i}{strand} = 'none' if $md->{$i}{strand} eq '0';
397 }
398 else {
399 # assign a non-strand just in case
400 $md->{$i}{strand} = 'none';
401 }
402 }
403 }
404  
405 return $bws;
406 }
407  
408 ### Internal subroutine for getting the cached bigwig object
409 sub _get_bw {
410 my $bwfile = shift;
411  
412 return $OPENED_BW{$bwfile} if exists $OPENED_BW{$bwfile};
413  
414 # open and cache the bigWig object
415 my $bw = open_bigwig_db($bwfile)
416 or croak "FATAL: Unable to open bigWig file '$bwfile'!";
417 $OPENED_BW{$bwfile} = $bw;
418 _record_seqids( $bwfile, $bw );
419 return $bw;
420 }
421  
422 # record the chromosomes and possible variants
423 sub _record_seqids {
424 my ( $bwfile, $bw ) = @_;
425 $BIGWIG_CHROMOS{$bwfile} = {};
426 foreach my $s ( $bw->seq_ids ) {
427 $BIGWIG_CHROMOS{$bwfile}{$s} = $s;
428 if ( $s =~ /^chr(.+)$/ ) {
429 $BIGWIG_CHROMOS{$bwfile}{$1} = $s;
430 }
431 else {
432 $BIGWIG_CHROMOS{$bwfile}{"chr$s"} = $s;
433 }
434 }
435 }
436  
437 ### Internal subroutine for processing summary features
438 # for personal use only
439 sub _process_summaries {
440 my ( $method, $summaries ) = @_;
441  
442 # calculate a value based on the number of summary features
443 if ( scalar @{$summaries} == 1 ) {
444  
445 # great! only one summary returned
446 return &{ $ONE_SUMMARY_METHOD{$method} }( $summaries->[0] );
447 }
448 elsif ( scalar @{$summaries} > 1 ) {
449  
450 # more than one summary
451 return &{ $MULTI_SUMMARY_METHOD{$method} }($summaries);
452 }
453 else {
454 # no summaries
455 return $method =~ /sum|count/ ? 0 : '.';
456 }
457 }
458  
459 ### Internal subroutine for removing duplicate positions from pos2data hash
460 # for personal use only
461 sub _remove_duplicate_positions {
462  
463 # collect the feature and hashes
464 my ( $pos2data, $duplicates ) = @_;
465  
466 # remove the duplicates
467 # we will combine all of them with a simple mean, what else to do?
468 foreach my $pos ( keys %{$duplicates} ) {
469 my $num = $duplicates->{$pos};
470  
471 # collect all the values
472 my @values;
473 push @values, $pos2data->{$pos}; # initial value
474 for my $i ( 1 .. $num ) {
475 push @values, $pos2data->{"$pos\.$i"};
476 delete $pos2data->{"$pos\.$i"};
477 }
478 $pos2data->{$pos} = sum(@values) / scalar(@values);
479 }
480 }
481  
482 ### Internal subroutine to identify and cache selected bigWigs from a BigWigSet
483 sub _lookup_bigwigset_wigs {
484  
485 # passed parameters as array ref
486 # chromosome, start, stop, strand, strandedness, method, db, dataset
487 my $param = shift;
488  
489 # the datasets, could be either types or names, unfortunately
490 my @types = splice( @{$param}, DATA );
491  
492 # we cache the list of looked up bigwigs to avoid doing this over and over
493 my $lookup =
494 sprintf( "%s_%s_%s", join( '_', @types ), $param->[STND], $param->[STR] );
495 return $BIGWIGSET_WIGS{$lookup} if exists $BIGWIGSET_WIGS{$lookup};
496  
497 # I want to access the bigWigs through the low level API for speed
498 # but first I need to find out which ones to use
499 # use internal methods to filter the bigWigs in the same manner
500 # that get_seq_stream does in BigWigSet
501 my @ids = $param->[DB]->bigwigs;
502  
503 # filter first by type
504 @ids = $param->[DB]->_filter_ids_by_type( \@types, \@ids );
505  
506 # try filtering by name if that doesn't work
507 unless (@ids) {
508 my @bwids = $param->[DB]->bigwigs;
509 foreach my $t (@types) {
510 my @found = $param->[DB]->_filter_ids_by_name( $t, \@bwids );
511 push @ids, @found if (@found);
512 }
513 }
514  
515 # then check for strand
516 if ( $param->[STND] ne 'all' and $param->[STR] != 0 ) {
517  
518 # looks like we are collecting stranded data
519 # try to filter again based on strand attribute
520 # remember to accept 0 strand attributes as well
521 # create an array of acceptable strand values to filter on
522 # remember that strand is an ordinary attribute and does not
523 # behave like the typical SeqFeature strand attribute
524 my @strands;
525 if ( $param->[STND] eq 'sense' ) {
526 @strands =
527 $param->[STR] == -1 ? qw(minus none)
528 : $param->[STR] == 1 ? qw(plus none)
529 : qw(minus plus none);
530 }
531 elsif ( $param->[STND] eq 'antisense' ) {
532 @strands =
533 $param->[STR] == -1 ? qw(plus none)
534 : $param->[STR] == 1 ? qw(minus none)
535 : qw(minus plus none);
536 }
537 else {
538 confess sprintf "FATAL: bad strandedness value: %s", $param->[STND];
539 }
540  
541 # then filter based on attribute
542 @ids = $param->[DB]->_filter_ids_by_attribute( { strand => \@strands }, \@ids );
543 }
544  
545 # cache and return
546 $BIGWIGSET_WIGS{$lookup} = \@ids;
547 return \@ids;
548 }
549  
550 1;
551  
552 __END__