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

filter: Statementstmt 0.0% 0 / 456 Branchbran 0.0% 0 / 226 Conditioncond 0.0% 0 / 123 MC/DCmcdc 0.0% 0 / 67 Subroutinesub 0.0% 0 / 44 Podpod 0.0% 0 / 29 totaltotal 0.0% 0 / 945 CC 114 SCAR 47.0
CC
114
Cov
0%
collect_bigbed_position_scores
342.0
filter_bigwigs_by_strand
240.0
new
182.0
CRAP 110.5
1 package Bio::ToolBox::db_helper::big;
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::Big;
10 require Exporter;
11  
12 our $VERSION = '2.02';
13  
14 # Initialize CURL buffers
15 BEGIN {
16 # not clear if this should be done only once or if it's harmless to re-init
17 # for every new file, so I guess best to just do it here at the very beginning
18 # initialization is only for remote files
19 Bio::DB::Big->init();
20 }
21  
22 # Exported names
23 our @ISA = qw(Exporter);
24  
25 ## no critic
26 ## this is never intended to be used directly by end users
27 ## and exporting everything is required
28 our @EXPORT = qw(
29 open_bigwig_db
30 collect_bigwig_score
31 collect_bigwig_scores
32 collect_bigwig_position_scores
33 open_bigbed_db
34 collect_bigbed_scores
35 collect_bigbed_position_scores
36 open_bigwigset_db
37 collect_bigwigset_score
38 collect_bigwigset_scores
39 collect_bigwigset_position_scores
40 sum_total_bigbed_features
41 );
42 ## use critic
43  
44 # Hash of Bigfile chromosomes
45 my %BIG_CHROMOS;
46  
47 # sometimes user may request a chromosome that's not in the bigfile
48 # that could lead to an exception
49 # we will record the chromosomes list in this hash
50 # $BIG_CHROMOS{bigfile}{altchromo} = chromo
51 # we also record the chromosome name variant with or without chr prefix
52 # to accommodate different naming conventions
53  
54 # Hash of Bigfile chromosome lengths
55 my %BIG_CHROMOLENGTHS;
56  
57 # since libBigWig doesn't internally clip chromosome lengths
58 # we will cache chromosome lengths and check them before it leads to an exception
59 # $BIG_CHROMOLENGTHS{bigfile}{chromo} = length
60  
61 # Opened bigFile db objects
62 my %OPENED_BIG;
63  
64 # a cache for opened Bigfile databases, primarily for collecting scores
65 # caching here is only for local purposes of collecting scores
66 # db_helper also provides caching of db objects but with option to force open in
67 # the case of forking processes - we don't have that here
68  
69 # BigWigSet bigWig IDs
70 my %BIGWIGSET_WIGS;
71  
72 # cache for the bigwigs from a BigWigSet used in a query
73 # we want to use low level bigWig access which isn't normally
74 # available from the high level BigWigSet, so we identify the
75 # bigWigs from the bigWigSet and cache them here
76  
77 #### BigWig Subroutines
78  
79 sub open_bigwig_db {
80 my $path = shift;
81 my $bw = _open_big($path)
82 or croak "FATAL: Unable to open bigWig file '$path'!";
83 unless ( $bw->is_big_wig ) {
84 croak "FATAL: $path is not a bigWig file!";
85 }
86 return $bw; # we do not cache here
87 }
88  
89 sub collect_bigwig_score {
90  
91 # passed parameters as array ref
92 # chromosome, start, stop, strand, strandedness, method, db, dataset(s)
93 my $param = shift;
94  
95 # this will use the built-in summary statistics
96 # the following methods are available: mean, min, max, std, cov
97  
98 # adjust old method name for compatibility
99 $param->[METH] = 'std' if $param->[METH] eq 'stddev';
100  
101 # check how many features we have
102 if ( scalar @{$param} == 9 ) {
103  
104 # only one bw, great!
105 my $bw = _get_bigwig( $param->[DATA] );
106 my $chromo = $BIG_CHROMOS{ $param->[DATA] }{ $param->[CHR] } or return;
107 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
108 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
109 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
110 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
111 my $s = $bw->get_stats( $chromo, $param->[STRT] - 1,
112 $param->[STOP], 1, $param->[METH] );
113 return $s->[0];
114 }
115 else {
116 # we have multiple bigwigs
117 my @scores;
118 for ( my $d = DATA; $d < scalar @{$param}; $d++ ) {
119 my $bw = _get_bigwig( $param->[$d] );
120 my $chromo = $BIG_CHROMOS{ $param->[$d] }{ $param->[CHR] } or next;
121 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
122 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
123 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
124 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
125 my $s = $bw->get_stats( $chromo, $param->[STRT] - 1,
126 $param->[STOP], 1, $param->[METH] );
127 push @scores, $s->[0];
128 }
129 if ( $param->[METH] eq 'min' ) {
130 return min(@scores);
131 }
132 elsif ( $param->[METH] eq 'max' ) {
133 return max(@scores);
134 }
135 else {
136 confess sprintf "FATAL: unable to calculate %s from multiple bigwigs!",
137 $param->[METH];
138 }
139 }
140 }
141  
142 sub collect_bigwig_scores {
143  
144 # passed parameters as array ref
145 # chromosome, start, stop, strand, strandedness, method, db, dataset(s)
146 my $param = shift;
147  
148 # check how many features we have
149 if ( scalar @{$param} == 9 ) {
150  
151 # only one, great!
152 my $bw = _get_bigwig( $param->[DATA] );
153 my $chromo = $BIG_CHROMOS{ $param->[DATA] }{ $param->[CHR] } or return;
154 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
155 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
156 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
157 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
158 my $raw_scores = $bw->get_values( $chromo, $param->[STRT] - 1, $param->[STOP] );
159 my @scores = grep {defined} @{$raw_scores};
160 return wantarray ? @scores : \@scores;
161 }
162 else {
163 # we have multiple bigwigs
164 my @scores;
165 for ( my $d = DATA; $d < scalar @{$param}; $d++ ) {
166 my $bw = _get_bigwig( $param->[$d] );
167 my $chromo = $BIG_CHROMOS{ $param->[$d] }{ $param->[CHR] } or next;
168 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
169 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
170 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
171 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
172 my $raw = $bw->get_values( $chromo, $param->[STRT] - 1, $param->[STOP] );
173 push @scores, grep {defined} @{$raw};
174 }
175 return wantarray ? @scores : \@scores;
176 }
177 }
178  
179 sub collect_bigwig_position_scores {
180  
181 # passed parameters as array ref
182 # chromosome, start, stop, strand, strandedness, method, db, dataset(s)
183 my $param = shift;
184 my %pos2score;
185  
186 # check how many features we have
187 if ( scalar @{$param} == 9 ) {
188  
189 # only one, great!
190 my $bw = _get_bigwig( $param->[DATA] );
191 my $chromo = $BIG_CHROMOS{ $param->[DATA] }{ $param->[CHR] } or return;
192 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
193 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
194 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
195 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
196 my $intervals = $bw->get_intervals( $chromo, $param->[STRT] - 1, $param->[STOP] );
197  
198 # record intervals into hash
199 foreach my $i ( @{$intervals} ) {
200 for ( my $p = $i->{start} + 1; $p <= $i->{end}; $p++ ) {
201 $pos2score{$p} = $i->{value};
202 }
203 }
204 }
205 else {
206 # we have multiple bigwigs
207 my %duplicates; # hash of duplicate positions, position => number
208  
209 # collect from each one
210 for ( my $d = DATA; $d < scalar @{$param}; $d++ ) {
211 my $bw = _get_bigwig( $param->[$d] );
212 my $chromo = $BIG_CHROMOS{ $param->[$d] }{ $param->[CHR] } or next;
213 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
214 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
215 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
216 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
217 my $intervals =
218 $bw->get_intervals( $chromo, $param->[STRT] - 1, $param->[STOP] );
219  
220 # record intervals into hash
221 foreach my $i ( @{$intervals} ) {
222 for ( my $p = $i->{start} + 1; $p <= $i->{end}; $p++ ) {
223  
224 # check every position to see if it's a duplicate
225 if ( exists $pos2score{$p} ) {
226 if ( exists $duplicates{$p} ) {
227  
228 # append an incrementing number at the end
229 $duplicates{$p} += 1; # increment first
230 my $new = sprintf( "%d.%d", $p, $duplicates{$p} );
231 $pos2score{$new} = $i->{value};
232 }
233 else {
234 # first time duplicate
235 my $new = $p . '.1';
236 $pos2score{$new} = $i->{value};
237 $duplicates{$p} = 1;
238 }
239 }
240 else {
241 $pos2score{$p} = $i->{value};
242 }
243 }
244 }
245 }
246  
247 # check for duplicate positions - we may not have any
248 if (%duplicates) {
249 _remove_duplicate_positions( \%pos2score, \%duplicates );
250 }
251 }
252 return wantarray ? %pos2score : \%pos2score;
253 }
254  
255 #### BigBed Subroutines
256  
257 sub open_bigbed_db {
258 my $path = shift;
259 my $bb = _open_big($path)
260 or croak "FATAL: Unable to open bigBed file '$path'!";
261 unless ( $bb->is_big_bed ) {
262 croak "FATAL: $path is not a bigBed file!";
263 }
264 return $bb;
265 }
266  
267 sub collect_bigbed_scores {
268  
269 # passed parameters as array ref
270 # chromosome, start, stop, strand, strandedness, method, db, dataset
271 my $param = shift;
272  
273 # look at each bedfile
274 # usually there is only one, but for stranded data there may be
275 # two bedfiles (+ and -), so we'll check each bed file for strand info
276 my @scores;
277 for ( my $d = DATA; $d < scalar @{$param}; $d++ ) {
278  
279 # open the bedfile
280 my $bb = _get_bigbed( $param->[$d] );
281  
282 # first check chromosome is present
283 my $chromo = $BIG_CHROMOS{ $param->[$d] }{ $param->[CHR] } or next;
284 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
285 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
286 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
287 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
288  
289 # collect the features overlapping the region
290 # we are using the high level API rather than the low-level
291 # since we getting the individual scores from each bed element
292 my $bb_stream =
293 Bio::ToolBox::db_helper::big::BedIteratorWrapper->new( $bb, $chromo,
294 $param->[STRT], $param->[STOP] );
295  
296 # process each feature
297 while ( my $bed = $bb_stream->next_seq ) {
298  
299 # First check whether the strand is acceptable
300 if (
301 $param->[STND] eq 'all' # all data is requested
302 or $bed->strand == 0 # unstranded data
303 or (
304 # sense data
305 $param->[STR] == $bed->strand and $param->[STND] eq 'sense'
306 )
307 or (
308 # antisense data
309 $param->[STR] != $bed->strand and $param->[STND] eq 'antisense'
310 )
311 )
312 {
313 # we have acceptable data to collect
314  
315 # store the appropriate datapoint
316 if ( $param->[METH] eq 'count' ) {
317 push @scores, 1;
318 }
319 elsif ( $param->[METH] eq 'pcount' ) {
320 push @scores, 1
321 if ( $bed->start >= $param->[STRT]
322 and $bed->end <= $param->[STOP] );
323 }
324 elsif ( $param->[METH] eq 'ncount' ) {
325 push @scores, $bed->display_name || $bed->primary_id;
326 }
327 else {
328 push @scores, $bed->score;
329 }
330 }
331 }
332 }
333  
334 # return collected data
335 return wantarray ? @scores : \@scores;
336 }
337  
338 sub collect_bigbed_position_scores {
339  
340 # passed parameters as array ref
341 # chromosome, start, stop, strand, strandedness, method, db, dataset
342 my $param = shift;
343  
344 # look at each bedfile
345 # usually there is only one, but there may be more
346 my %pos2data;
347 for ( my $i = DATA; $i < scalar @{$param}; $i++ ) {
348  
349 # open the bedfile
350 my $bb = _get_bigbed( $param->[$i] );
351  
352 # first check that the chromosome is present
353 my $chromo = $BIG_CHROMOS{ $param->[$i] }{ $param->[CHR] } or next;
354 $param->[STRT] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
355 if $param->[STRT] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
356 $param->[STOP] = $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo}
357 if $param->[STOP] > $BIG_CHROMOLENGTHS{ $param->[DATA] }{$chromo};
358  
359 # collect the features overlapping the region
360 my $bb_stream =
361 Bio::ToolBox::db_helper::big::BedIteratorWrapper->new( $bb, $chromo,
362 $param->[STRT], $param->[STOP] );
363  
364 # process each feature
365 while ( my $bed = $bb_stream->next_seq ) {
366  
367 # First check whether the strand is acceptable
368 if (
369 $param->[STND] eq 'all' # all data is requested
370 or $bed->strand == 0 # unstranded data
371 or (
372 # sense data
373 $param->[STR] == $bed->strand and $param->[STND] eq 'sense'
374 )
375 or (
376 # antisense data
377 $param->[STR] != $bed->strand and $param->[STND] eq 'antisense'
378 )
379 )
380 {
381 # we have acceptable data to collect
382  
383 # determine position to record
384 my $position;
385 if ( $bed->start == $bed->end ) {
386  
387 # just one position recorded
388 $position = $bed->start;
389 }
390 else {
391 # calculate the midpoint
392 $position = int( ( ( $bed->start + $bed->end ) / 2 ) + 0.5 );
393 }
394  
395 # check the position
396 next
397 unless (
398 # want to avoid those whose midpoint are not technically
399 # within the region of interest
400 $position >= $param->[STRT] and $position <= $param->[STOP]
401 );
402  
403 # store the appropriate datapoint
404 # for score and length, we're putting these into an array
405 if ( $param->[METH] eq 'count' ) {
406 $pos2data{$position} += 1;
407 }
408 elsif ( $param->[METH] eq 'pcount' ) {
409 $pos2data{$position} += 1
410 if ( $bed->start <= $param->[STRT]
411 and $bed->end <= $param->[STOP] );
412 }
413 elsif ( $param->[METH] eq 'ncount' ) {
414 $pos2data{$position} ||= [];
415 push @{ $pos2data{$position} }, $bed->display_name
416 || $bed->primary_id;
417 }
418 else {
419 # everything else we just take the score
420 push @{ $pos2data{$position} }, $bed->score + 0;
421 }
422 }
423 }
424 }
425  
426 # combine multiple datapoints at the same position
427 if ( $param->[METH] eq 'ncount' ) {
428 foreach my $position ( keys %pos2data ) {
429 my %name2count;
430 foreach ( @{ $pos2data{$position} } ) { $name2count{$_} += 1 }
431 $pos2data{$position} = scalar( keys %name2count );
432 }
433 }
434 elsif ( $param->[METH] eq 'count' or $param->[METH] eq 'pcount' ) {
435  
436 # do nothing, these aren't arrays
437 }
438 elsif ( $param->[METH] eq 'mean' ) {
439 foreach my $position ( keys %pos2data ) {
440 $pos2data{$position} =
441 sum( @{ $pos2data{$position} } ) / scalar( @{ $pos2data{$position} } );
442 }
443 }
444 elsif ( $param->[METH] eq 'median' ) {
445 foreach my $position ( keys %pos2data ) {
446 $pos2data{$position} = median( @{ $pos2data{$position} } );
447 }
448 }
449 elsif ( $param->[METH] eq 'min' ) {
450 foreach my $position ( keys %pos2data ) {
451 $pos2data{$position} = min( @{ $pos2data{$position} } );
452 }
453 }
454 elsif ( $param->[METH] eq 'max' ) {
455 foreach my $position ( keys %pos2data ) {
456 $pos2data{$position} = max( @{ $pos2data{$position} } );
457 }
458 }
459 elsif ( $param->[METH] eq 'sum' ) {
460 foreach my $position ( keys %pos2data ) {
461 $pos2data{$position} = sum( @{ $pos2data{$position} } );
462 }
463 }
464 else {
465 # just take the mean for everything else
466 foreach my $position ( keys %pos2data ) {
467 $pos2data{$position} =
468 sum( @{ $pos2data{$position} } ) / scalar( @{ $pos2data{$position} } );
469 }
470 }
471  
472 # return collected data
473 return wantarray ? %pos2data : \%pos2data;
474 }
475  
476 sub sum_total_bigbed_features {
477  
478 # there is no easy way to do this with this adapter, except to literally
479 # walk through the entire file.
480 # well, we do this with bam files, I guess we could do the same here
481 # honestly, who uses this????? it's legacy. skip for now until someone complains
482 return undef;
483 }
484  
485 #### BigWigSet Subroutines
486  
487 sub open_bigwigset_db {
488 my $path = shift;
489 return Bio::ToolBox::db_helper::big::BigWigSet->new($path);
490 }
491  
492 sub collect_bigwigset_score {
493  
494 # passed parameters as array ref
495 # chromosome, start, stop, strand, strandedness, method, db, dataset
496 my $param = shift;
497  
498 # lookup the bigWig files based on the parameters
499 my $ids = _lookup_bigwigset_wigs($param);
500 return unless scalar( @{$ids} ) > 0;
501 croak(
502 'FATAL: multiple selected bigWig files from a BigWigSet is not supported with single score method'
503 ) if scalar( @{$ids} ) > 1;
504 push @{$param}, @{$ids};
505  
506 # use the low level single bigWig API
507 return collect_bigwig_score($param);
508 }
509  
510 sub collect_bigwigset_scores {
511  
512 # passed parameters as array ref
513 # chromosome, start, stop, strand, strandedness, method, db, dataset
514 my $param = shift;
515  
516 # lookup the bigWig files based on the parameters
517 my $ids = _lookup_bigwigset_wigs($param);
518 return unless scalar( @{$ids} ) > 0;
519 push @{$param}, @{$ids};
520  
521 # use the low level single bigWig API
522 return collect_bigwig_scores($param);
523 }
524  
525 sub collect_bigwigset_position_scores {
526  
527 # passed parameters as array ref
528 # chromosome, start, stop, strand, strandedness, method, db, dataset
529 my $param = shift;
530  
531 # lookup the bigWig files based on the parameters
532 my $ids = _lookup_bigwigset_wigs($param);
533 return unless scalar( @{$ids} ) > 0;
534 push @{$param}, @{$ids};
535  
536 # use the low level single bigWig API
537 return collect_bigwig_position_scores($param);
538 }
539  
540 #### Internal
541  
542 sub _open_big {
543 my $path = shift;
544 $path =~ s/^file://; # clean up file prefix if present
545 my $big;
546 eval { $big = Bio::DB::Big->open($path); };
547 if ($big) {
548 return $big;
549 }
550 elsif ( $EVAL_ERROR or $OS_ERROR ) {
551 carp $EVAL_ERROR;
552 carp $OS_ERROR;
553 return;
554 }
555 else {
556 return;
557 }
558 }
559  
560 sub _get_bigwig {
561 my $file = shift;
562 return $OPENED_BIG{$file} if exists $OPENED_BIG{$file};
563  
564 # open and cache the bigFile object
565 my $bw = _open_big($file)
566 or croak "FATAL: Unable to open big file '$file'!";
567 unless ( $bw->is_big_wig ) {
568 croak "FATAL: $file is not a bigWig file!";
569 }
570 $OPENED_BIG{$file} = $bw;
571 _record_seqids( $file, $bw );
572 return $bw;
573 }
574  
575 sub _get_bigbed {
576 my $file = shift;
577 return $OPENED_BIG{$file} if exists $OPENED_BIG{$file};
578  
579 # open and cache the bigFile object
580 my $bb = _open_big($file)
581 or croak "FATAL: Unable to open big file '$file'!";
582 unless ( $bb->is_big_bed ) {
583 croak "FATAL: $file is not a bigBed file!";
584 }
585 $OPENED_BIG{$file} = $bb;
586 _record_seqids( $file, $bb );
587 return $bb;
588 }
589  
590 sub _record_seqids {
591 my ( $file, $big ) = @_;
592 $BIG_CHROMOS{$file} = {};
593 my $chroms = $big->chroms(); # returns hash seq_id => length
594 foreach my $c ( keys %{$chroms} ) {
595 my $chr = $chroms->{$c}{name};
596 my $len = $chroms->{$c}{length};
597  
598 # store length
599 $BIG_CHROMOLENGTHS{$file}{$chr} = $len;
600 $BIG_CHROMOS{$file}{$chr} = $chr; # itself
601 # now store alternate names, with or without chr prefix
602 if ( $chr =~ /^chr(.+)$/i ) {
603 $BIG_CHROMOS{$file}{$1} = $chr;
604 }
605 else {
606 $BIG_CHROMOS{$file}{"chr$chr"} = $chr;
607 }
608 }
609 }
610  
611 sub _remove_duplicate_positions {
612  
613 # collect the feature and hashes
614 my ( $pos2data, $duplicates ) = @_;
615  
616 # remove the duplicates
617 # we will combine all of them with a simple mean, what else to do?
618 foreach my $pos ( keys %{$duplicates} ) {
619 my $num = $duplicates->{$pos};
620  
621 # collect all the values
622 my @values;
623 push @values, $pos2data->{$pos}; # initial value
624 for my $i ( 1 .. $num ) {
625 push @values, $pos2data->{"$pos\.$i"};
626 delete $pos2data->{"$pos\.$i"};
627 }
628 $pos2data->{$pos} = sum(@values) / scalar(@values);
629 }
630 }
631  
632 sub _lookup_bigwigset_wigs {
633  
634 # passed parameters as array ref
635 # chromosome, start, stop, strand, strandedness, method, db, dataset
636 my $param = shift;
637  
638 # the datasets, could be either types or names, unfortunately
639 my @types = splice( @{$param}, DATA );
640  
641 # we cache the list of looked up bigwigs to avoid doing this over and over
642 my $lookup =
643 sprintf( "%s_%s_%s", join( '_', @types ), $param->[STND], $param->[STR] );
644 return $BIGWIGSET_WIGS{$lookup} if exists $BIGWIGSET_WIGS{$lookup};
645  
646 # filter first by the name or type
647 my @ids = $param->[DB]->filter_bigwigs(@types);
648  
649 # then check for strand if necessary
650 if ( $param->[STND] ne 'all' and $param->[STR] != 0 ) {
651  
652 # looks like we are collecting stranded data
653 # try to filter again based on strand attribute
654 my $strand_to_keep;
655 if ( $param->[STND] eq 'sense' ) {
656 $strand_to_keep = $param->[STR];
657 }
658 elsif ( $param->[STND] eq 'antisense' ) {
659 $strand_to_keep =
660 $param->[STR] == -1 ? 1
661 : $param->[STR] == 1 ? -1
662 : 0;
663 }
664 else {
665 confess sprintf "FATAL: bad strandedness value: %s", $param->[STND];
666 }
667 @ids = $param->[DB]->filter_bigwigs_by_strand( $strand_to_keep, @ids );
668 }
669  
670 # map the names back to full bigwig paths
671 my @paths = map { $param->[DB]->get_bigwig_path($_) } @ids;
672  
673 # cache and return
674 $BIGWIGSET_WIGS{$lookup} = \@paths;
675 return \@paths;
676 }
677  
678 1;
679  
680 package Bio::ToolBox::db_helper::big::BigWigSet;
681  
682 # this package borrows concepts from Bio::DB::BigWigSet by Lincoln Stein
683 # in order to make it compatible with Bio::DB::Big
684 # it is NOT a drop-in replacement or equivalent
685 # if you need more functionality, install Bio::DB::BigWigSet
686 use Carp;
687 use IO::Dir;
688 use IO::File;
689 use English qw(-no_match_vars);
690 use File::Spec;
691  
692 sub new {
693 my ( $class, $dir ) = @_;
694 croak 'FATAL: must call method new with a directory path!' unless $dir;
695 croak "FATAL: BigWigSet '$dir' is not a directory path!" unless -d $dir;
696 my $self = {
697 dir => $dir,
698 bwfiles => {},
699 metadata => {}
700 };
701  
702 # read directory
703 my $D = IO::Dir->new($dir) or croak "FATAL: unable to open $dir! $OS_ERROR";
704 while ( my $f = $D->read ) {
705 my $f_path = File::Spec->catfile( $dir, $f );
706 next unless -f $f_path;
707 if ( $f =~ /\.(?: bw | bigwig)$/xi ) {
708  
709 # bigwig file
710 $self->{bwfiles}{$f} = $f_path;
711 }
712 elsif ( $f =~ /^meta.*\.txt$/xi ) {
713  
714 # a genuine metadata file - excellent!
715 # let's open it and parse the contents
716 my $fh = IO::File->new($f_path)
717 or croak "FATAL: unable to read metadata file '$f_path'! $OS_ERROR";
718 my $current_bw; # the current bigwig file we're describing
719 while ( my $line = $fh->getline ) {
720 next if $line =~ /^#/;
721 next if $line !~ /\w+/;
722 chomp $line;
723 if ( $line =~ /\[(.+ \. (?: bw | bigwig))\]/xi ) {
724  
725 # start of a new metadata block for the current bw file
726 $current_bw = $1;
727 next;
728 }
729 elsif ( $line =~ /^( [\w\-\.]+ ) \s* = \s* ( [\w\-\.]+ )/x ) {
730  
731 # a metadata line
732 croak
733 'FATAL: malformed metadata file! no bw file stanza header before metadata line!'
734 unless defined $current_bw;
735 $self->{metadata}{$current_bw}{$1} = $2;
736 }
737  
738 # ignore everything else
739 }
740 $fh->close;
741 }
742  
743 # ignore all other files
744 }
745 undef $D;
746  
747 # fill out the metadata
748 foreach my $f ( keys %{ $self->{bwfiles} } ) {
749  
750 # a genuine metadata file isn't absolutely required
751 # therefore we will always put in our own metadata gleaned from file name
752 # do a regex to pull out basename and possibly strand information from filename
753 my $name = $f;
754 $name =~ s/\. (?: bw | bigwig)$//xi; # remove extension for the name
755 my ( $type, $strand );
756 if ( $name =~ /^(.+) [\._] (?: f | for | forward | plus | \+ )$/xi ) {
757 $type = $1;
758 $strand = 1;
759 }
760 elsif ( $name =~ /^(.+) [\._] (?: r | rev | reverse | minus | \- )$/xi ) {
761 $type = $1;
762 $strand = -1;
763 }
764 else {
765 $type = $name;
766 $strand = 0;
767 }
768  
769 # be careful and do not overwrite pre_existing key value
770 $self->{metadata}{$f}{name} ||= $name;
771 $self->{metadata}{$f}{type} ||= $type;
772 $self->{metadata}{$f}{strand} ||= $strand;
773 }
774  
775 bless $self, $class;
776 return $self;
777 }
778  
779 sub bigwig_names {
780 my $self = shift;
781 my @b = keys %{ $self->{bwfiles} };
782 return wantarray ? @b : \@b;
783 }
784  
785 sub bigwigs {
786  
787 # to maintain compatiblity with the old BigWigSet, we will return the full path
788 # of all the bigwig files
789 my $self = shift;
790 my @b = values %{ $self->{bwfiles} };
791 return wantarray ? @b : \@b;
792 }
793  
794 sub get_bigwig {
795 my ( $self, $bwfile ) = @_;
796 return unless $bwfile;
797 my $path = $self->get_bigwig_path($bwfile);
798 if ($path) {
799 return Bio::ToolBox::db_helper::big::open_bigwig_db($path);
800 }
801 else {
802 carp "ERROR: unrecognized bigWig file name '$bwfile'!";
803 return;
804 }
805 }
806  
807 sub get_bigwig_path {
808 my ( $self, $bwfile ) = @_;
809 return unless $bwfile;
810 return $self->{bwfiles}{$bwfile} || undef;
811 }
812  
813 sub metadata {
814 my $self = shift;
815 return $self->{metadata};
816 }
817  
818 sub filter_bigwigs {
819 my ( $self, @names ) = @_;
820  
821 # we start with all of the bigwigs available, then filter out
822 my $start_list = $self->bigwig_names;
823 my $md = $self->metadata;
824 my @filtered;
825  
826 foreach my $name (@names) {
827  
828 # there may be more than one name of a dataset passed
829 # in all likelihood, probably not, but just in case....
830  
831 # we are filtering on basically any value that matches and are not really
832 # restricting on a specific attribute key
833 # so type, name, display_name, or primary_tag are all checked in that order
834 # let's hope this is adequate and won't create too many problems
835 # I'm betting on the fact that bigwigset databases are so obscure that
836 # most users won't even bother with a genuine metadata file
837 # in fact, why am I even bothering with this at all?
838 # because they are a cool concept and I occasionally use them. huh.
839 foreach my $b ( @{$start_list} ) {
840 if ( exists $md->{$b}{type} ) {
841 push @filtered, $b if $name eq $md->{$b}{type};
842 }
843 elsif ( exists $md->{$b}{name} ) {
844 push @filtered, $b if $name eq $md->{$b}{name};
845 }
846 elsif ( exists $md->{$b}{display_name} ) {
847 push @filtered, $b if $name eq $md->{$b}{display_name};
848 }
849 elsif ( exists $md->{$b}{primary_tag} ) {
850 push @filtered, $b if $name eq $md->{$b}{primary_tag};
851 }
852 }
853 }
854 return wantarray ? @filtered : \@filtered;
855 }
856  
857 sub filter_bigwigs_by_strand {
858 my $self = shift;
859 my $strand = shift;
860  
861 # check what files were passed
862 my @files;
863 if ( scalar(@_) == 1 and ref( $_[0] ) eq 'ARRAY' ) {
864 @files = @{ $_[0] };
865 }
866 elsif ( scalar(@_) == 0 ) {
867 @files = $self->bigwig_names;
868 }
869 else {
870 @files = @_;
871 }
872  
873 # filter the bigWigs based on strand
874 # we keep anything that matches the given strand
875 # because the old BigWigSet adapter didn't really handle strand properly,
876 # and certainly not standard BioPerl 1,0,-1 values, I had adopted plus, none, minus
877 # now I'm doomed as I have to support this too. ugh.
878 my @keepers;
879 my $md = $self->metadata;
880 if ( $strand >= 0 ) {
881 foreach my $f (@files) {
882 my $str = $md->{$f}{strand} || 0;
883 if ( $str =~ /[a-z]/ ) {
884  
885 # ugh old school
886 $str =
887 $str eq 'plus' ? 1
888 : $str eq 'minus' ? -1
889 : $str eq 'none' ? 0
890 : 0;
891 }
892 push @keepers, $f if $str >= 0;
893 }
894 }
895 elsif ( $strand < 0 ) {
896 foreach my $f (@files) {
897 my $str = $md->{$f}{strand} || 0;
898 if ( $str =~ /[a-z]/ ) {
899  
900 # ugh old school
901 $str =
902 $str eq 'plus' ? 1
903 : $str eq 'minus' ? -1
904 : $str eq 'none' ? 0
905 : 0;
906 }
907 push @keepers, $f if $str < 0;
908 }
909 }
910 return @keepers;
911 }
912  
913 1;
914  
915 package Bio::ToolBox::db_helper::big::BedIteratorWrapper;
916 use Carp;
917 use Bio::ToolBox::SeqFeature;
918  
919 sub new {
920 my $class = shift;
921  
922 # check the bigBed object
923 my $bb = shift;
924 unless ( ref($bb) eq 'Bio::DB::Big::File' and $bb->is_big_bed ) {
925 confess 'FATAL: passed big object is not a bigBed file!';
926 }
927  
928 # get coordinates
929 my ( $seqid, $start, $end ) = @_;
930 confess 'FATAL: no coordinates provided!'
931 unless ( defined $seqid and defined $start and defined $end );
932 $start -= 1; # compensate for 0-based coordinates
933  
934 # create an iterator
935 # include all string entries and just one per iteration
936 # return 10 at a time, not too many, not too little
937 my $iterator = $bb->get_entries_iterator( $seqid, $start, $end, 1, 10 );
938  
939 # return object wrapper
940 my $self = {
941 bb => $bb,
942 iter => $iterator,
943 seqid => $seqid,
944 start => $start,
945 end => $end,
946 entries => [],
947 };
948 return bless $self, $class;
949 }
950  
951 sub next_seq {
952 my $self = shift;
953 my $entry = shift @{ $self->{entries} } || undef;
954 unless ($entry) {
955 $self->{entries} = $self->{iter}->next || undef;
956 return unless $self->{entries};
957 $entry = shift @{ $self->{entries} } || undef;
958 }
959 return unless $entry;
960 my @bits = split /\t/, $entry->{string};
961 return Bio::ToolBox::SeqFeature->new(
962 -seq_id => $self->{seqid},
963 -start => $entry->{start} + 1, # compensate for 0-based coordinates
964 -end => $entry->{end},
965 -display_name => $bits[0] || undef,
966 -score => $bits[1] || 1,
967 -strand => $bits[2] || 0,
968 );
969 }
970  
971 1;
972  
973 __END__