script/bam2wig.pl untested

filter: Statementstmt 0.0% 0 / 1745 Branchbran 0.0% 0 / 892 Conditioncond 0.0% 0 / 585 MC/DCmcdc 0.0% 0 / 312 Subroutinesub 0.0% 0 / 78 Podpod 0.0% 0 / 59 totaltotal 0.0% 0 / 3671 CC 425 SCAR 87.6
CC
425
Cov
0%
check_defaults
21462.0
process_alignments
702.0
parallel_process_alignments
702.0
CRAP 6376.4
1 #!/usr/local/bin/perl
2  
3 # documentation at end of file
4  
5 use warnings;
6 no warnings qw(uninitialized);
7  
8 # This script results in a ton of uninitialized warnings when packing chromosomal
9 # coverage arrays into binary strings due to vast stretches of chromosomes without
10 # alignments (think megabases of Ns in the human genome).
11 # Taking time to convert into proper zeroes unnecessarily slows down run time.
12 # Since we pack frequently throughout the app, it's easiest to simply turn off
13 # uninitialized warnings globally.
14 use strict;
15 use Getopt::Long qw(:config no_ignore_case bundling);
16 use Pod::Usage;
17 use File::Spec;
18 use File::Temp;
19 use List::Util qw(sum0);
20 use List::MoreUtils qw(any natatime);
21 use English qw(-no_match_vars);
22 use Bio::ToolBox;
23 use Bio::ToolBox::db_helper qw(
24 open_db_connection
25 low_level_bam_coverage
26 low_level_bam_fetch
27 $BAM_ADAPTER
28 );
29 use Bio::ToolBox::utility qw(format_with_commas);
30 use Bio::ToolBox::big_helper qw(
31 check_wigToBigWig_version
32 get_wig_to_bigwig_app
33 generate_chromosome_file
34 open_wig_to_bigwig_fh
35 wig_to_bigwig_conversion
36 );
37 my $parallel;
38 eval {
39 # check for parallel support
40 require Parallel::ForkManager;
41 $parallel = 1;
42 };
43  
44 our $VERSION = '2.03';
45  
46 print "\n This program will convert bam alignments to wig data\n";
47  
48 ### Quick help
49 unless (@ARGV) {
50  
51 # when no command line options are present
52 # print SYNOPSIS
53 pod2usage(
54 {
55 '-verbose' => 0,
56 '-exitval' => 1,
57 }
58 );
59 }
60  
61 ### Get command line options and initialize values
62 my (
63 $outfile, $position, $splice, $paired,
64 $fastpaired, $shift, $chr_number, $correlation_min,
65 $zmin, $zmax, $model, $do_strand,
66 $flip, $min_mapq, $nosecondary, $noduplicate,
67 $nosupplementary, $max_isize, $min_isize, $first_read,
68 $second_read, $multi_hit_scale, $splice_scale, $rpm,
69 $do_mean, $chrnorm, $chrapply, $chr_exclude,
70 $exclude_file, $bin_size, $dec_precison, $bigwig,
71 $no_zero, $bwapp, $cpu, $max_intron,
72 $window, $verbose, $gz, $tempdir,
73 $help, $print_version,
74 );
75 my $use_start = 0; # these need to be explicitly set to zero because I sum them
76 my $use_mid = 0; # to verify user input
77 my $use_span = 0;
78 my $use_cspan = 0;
79 my $use_extend = 0;
80 my $use_smartpe = 0;
81 my $use_ends = 0;
82 my $use_coverage = 0;
83 my $do_fixstep = 0;
84 my $do_varstep = 0;
85 my $do_bedgraph = 0;
86 my $extend_value = 0;
87 my $shift_value = 0;
88 my @bamfiles;
89 my @scale_values;
90  
91 # Command line options
92 GetOptions(
93 'i|in=s' => \@bamfiles, # one or more bam files
94 'o|out=s' => \$outfile, # name of output file
95 's|start!' => \$use_start, # record start point
96 'd|mid!' => \$use_mid, # record mid point
97 'a|span!' => \$use_span, # record span
98 'cspan!' => \$use_cspan, # record center span
99 'e|extend!' => \$use_extend, # extend read
100 'smartcov!' => \$use_smartpe, # smart paired coverage
101 'ends!' => \$use_ends, # record paired-end endpoints
102 'coverage!' => \$use_coverage, # calculate coverage
103 'position=s' => \$position, # legacy option
104 'l|splice|split!' => \$splice, # split splices
105 'p|pe!' => \$paired, # paired-end alignments
106 'P|fastpe!' => \$fastpaired, # fast paired-end alignments
107 'I|shift!' => \$shift, # shift coordinates 3'
108 'H|shiftval=i' => \$shift_value, # value to shift coordinates
109 'x|extval=i' => \$extend_value, # value to extend reads
110 'chrom=i' => \$chr_number, # number of chromosomes to sample
111 'minr=f' => \$correlation_min, # R minimum value for shift
112 'zmin=f' => \$zmin, # minimum z-score interval for calculating shift
113 'zmax=f' => \$zmax, # maximum z-score interval for calculating shift
114 'M|model!' => \$model, # write the strand shift model data
115 't|strand!' => \$do_strand, # separate strands
116 'flip!' => \$flip, # flip the strands
117 'q|qual=i' => \$min_mapq, # minimum mapping quality
118 'S|nosecondary' => \$nosecondary, # skip secondary alignments
119 'D|noduplicate' => \$noduplicate, # skip duplicate alignments
120 'U|nosupplementary' => \$nosupplementary, # skip supplementary alignments
121 'maxsize=i' => \$max_isize, # maximum paired insert size to accept
122 'minsize=i' => \$min_isize, # minimum paired insert size to accept
123 'first!' => \$first_read, # only take first read
124 'second!' => \$second_read, # only take second read
125 'fraction!' => \$multi_hit_scale, # scale by number of hits
126 'splfrac!' => \$splice_scale, # divide counts by number of spliced segments
127 'r|rpm!' => \$rpm, # calculate reads per million
128 'm|separate|mean!' => \$do_mean, # rpm scale separately
129 'scale=s' => \@scale_values, # user specified scale value
130 'chrnorm=f' => \$chrnorm, # chromosome-specific normalization
131 'chrapply=s' => \$chrapply, # chromosome-specific normalization regex
132 'K|chrskip=s' => \$chr_exclude, # regex for skipping chromosomes
133 'exclude|blacklist=s' => \$exclude_file, # file for skipping regions
134 'bin=i' => \$bin_size, # size for binning the data
135 'format=i' => \$dec_precison, # format to number of decimal positions
136 'b|bw!' => \$bigwig, # generate bigwig file
137 'bwapp=s' => \$bwapp, # utility to generate a bigwig file
138 'bdg!' => \$do_bedgraph, # write a bedgraph output
139 'fix!' => \$do_fixstep, # write a fixedStep output
140 'var!' => \$do_varstep, # write a varStep output
141 'nozero!' => \$no_zero, # do not write zero coverage
142 'z|gz!' => \$gz, # compress text output
143 'c|cpu=i' => \$cpu, # number of cpu cores to use
144 'intron=i' => \$max_intron, # maximum intron size to allow
145 'window=i' => \$window, # window size to control memory usage
146 'V|verbose!' => \$verbose, # print sample correlations
147 'temp=s' => \$tempdir, # directory to write temp files
148 'adapter=s' => \$BAM_ADAPTER, # explicitly set the adapter version
149 'h|help' => \$help, # request help
150 'v|version' => \$print_version, # print the version
151 ) or die " unrecognized option(s)!! please refer to the help documentation\n\n";
152  
153 # Print help
154 if ($help) {
155  
156 # print entire POD
157 pod2usage(
158 {
159 '-verbose' => 2,
160 '-exitval' => 1,
161 }
162 );
163 }
164  
165 # Print version
166 if ($print_version) {
167 print " Biotoolbox script bam2wig.pl, version $VERSION\n";
168 my $v = Bio::ToolBox->VERSION;
169 print " Biotoolbox package version $v\n";
170 exit;
171 }
172  
173 ### Check for requirements and set defaults
174 # more global variables
175 my (
176 $unwanted_flags, $main_callback, $callback, $wig_writer,
177 $outbase, $chromo_file, $binpack, $buflength,
178 $coverage_dump, $coverage_sub, $post_bw_convert
179 );
180 check_defaults();
181 print " Writing temp files to $tempdir\n" if $verbose;
182 my $items = $paired ? 'fragments' : 'alignments';
183  
184 # record start time
185 my $start_time = time;
186  
187 ### Open files
188 my @sams;
189 printf " Processing files %s...\n", join( ", ", @bamfiles );
190 foreach (@bamfiles) {
191  
192 # this will open each bam file using the high level API
193 # with the appropriate installed adapter
194 my $sam = open_db_connection($_) or die " unable to open bam file '$_'!\n";
195 $sam->split_splices(1) if $splice;
196 push @sams, $sam;
197 }
198  
199 # generate the chromosome name list
200 # we generate this from the first bam file only, on the assumption that they
201 # all have the same sequences
202 # record the chromosome name, rather than internal tid, just in the off chance
203 # that they are not in the same order (!!!???)
204 my @seq_list;
205 my %seq_name2length;
206 for my $tid ( 0 .. $sams[0]->n_targets - 1 ) {
207 my $chr = $sams[0]->target_name($tid);
208 if ( $chr_exclude and $chr =~ /$chr_exclude/xi ) {
209 print " skipping sequence $chr\n" if $verbose;
210 next;
211 }
212 push @seq_list, $chr;
213 $seq_name2length{$chr} = $sams[0]->target_len($tid);
214 }
215  
216 # set the wrapper reference
217 # this depends on which adapter was opened
218 my $wrapper_ref;
219 if ( $splice or $use_smartpe ) {
220 $wrapper_ref =
221 ref( $sams[0] ) eq 'Bio::DB::Sam' ? 'Bio::DB::Bam::AlignWrapper'
222 : ref( $sams[0] ) eq 'Bio::DB::HTS' ? 'Bio::DB::HTS::AlignWrapper'
223 : 'none';
224 eval { require $wrapper_ref; 1 };
225 }
226 printf " Using the %s Bam adapter and align wrapper $wrapper_ref\n", ref( $sams[0] )
227 if $verbose;
228  
229 ### Process user provided exclusion lists
230 my $exclude_hash = process_exclusion_list();
231  
232 ### Calculate shift value
233 if ( $shift or $use_extend ) {
234 unless ( ( $shift and $shift_value ) or ( $use_extend and $extend_value ) ) {
235 print " Calculating 3' shift value...\n";
236 $shift_value = determine_shift_value();
237 }
238  
239 # quietly exit here after determining shift value if no wig is to be generated
240 exit
241 unless ( $use_start
242 or $use_extend
243 or $use_span
244 or $use_mid
245 or $use_cspan
246 or $use_coverage );
247  
248 # precalculate double shift when recording extended position
249 if ($use_extend) {
250 unless ($extend_value) {
251 $extend_value = $shift_value * 2;
252 }
253 print " Alignments will be extended by $extend_value bp\n";
254 }
255 else {
256 print " Alignments will be shifted by $shift_value bp\n";
257 }
258 }
259  
260 # set center extension global value
261 my $half_extend = int( $extend_value / 2 );
262 if ($use_cspan) {
263 print " $items will be center extended by $half_extend bp both directions\n";
264 }
265  
266 ### Process bam file
267 # process according to type of data collected and alignment type
268 if ( $cpu > 1 ) {
269  
270 # multiple cpu core execution
271 if ($use_coverage) {
272  
273 # special, speedy, low-level, single-bp coverage
274 parallel_process_bam_coverage();
275 }
276 else {
277 # process alignments individually
278 parallel_process_alignments();
279 }
280  
281 }
282 else {
283 # single-thread execution
284 print " Install Parallel::ForkManager to significantly increase performance\n"
285 if not $cpu;
286 if ($use_coverage) {
287  
288 # special, speedy, low-level, single-bp coverage
289 process_bam_coverage();
290 }
291 else {
292 # process alignments individually
293 process_alignments();
294 }
295 }
296  
297 ### Finish
298 printf " Finished in %.3f min\n", ( time - $start_time ) / 60;
299  
300 ######################## Subroutines ###################################
301  
302 ### check required command line options and assign default values
303 sub check_defaults {
304  
305 # checking default and required values from the command line options
306 # moved here to make it cleaner
307  
308 # check input file
309 unless (@bamfiles) {
310 if (@ARGV) {
311 @bamfiles = @ARGV;
312 }
313 else {
314 print STDERR " FATAL: no input files! use --help for more information\n";
315 exit 1;
316 }
317 }
318 if ( $bamfiles[0] =~ /,/ ) {
319 @bamfiles = split /,/, shift @bamfiles;
320 }
321  
322 # check scale values
323 if (@scale_values) {
324 if ( $scale_values[0] =~ /,/ ) {
325 @scale_values = split /,/, shift @scale_values;
326 }
327 if ( scalar(@bamfiles) != scalar(@scale_values) ) {
328 if ( scalar(@scale_values) == 1 ) {
329  
330 # only one, that's ok, use it for all
331 my $v = shift @scale_values;
332 foreach (@bamfiles) {
333 push @scale_values, $v;
334 }
335 }
336 else {
337 print STDERR
338 " FATAL: number of scale values does not equal number of bam files!\n";
339 exit 1;
340 }
341 }
342 }
343  
344 # check parallel support
345 if ($parallel) {
346  
347 # conservatively enable 2 cores
348 $cpu ||= 4;
349 }
350 else {
351 # disable cores
352 print " WARNING: disabling parallel CPU execution, no support present\n" if $cpu;
353 $cpu = 0;
354 }
355  
356 # set missing options if the value was set
357 if ( $shift_value and not $shift ) {
358 $shift = 1;
359 }
360 if ( $extend_value and not $use_extend ) {
361 $use_extend = 1 unless ( $use_cspan or $position );
362 }
363  
364 # check position
365 if ($position) {
366 if ( $position eq 'start' ) {
367 $use_start = 1;
368 }
369 elsif ( $position eq 'mid' ) {
370 $use_mid = 1;
371 }
372 elsif ( $position eq 'span' ) {
373 $use_span = 1;
374 }
375 elsif ( $position eq 'cspan' ) {
376 $use_cspan = 1;
377 }
378 elsif ( $position eq 'extend' ) {
379 $use_extend = 1;
380 }
381 elsif ( $position eq 'coverage' ) {
382  
383 # for backwards compatibility
384 $use_coverage = 1;
385 }
386 elsif ( $position eq 'smartcov' ) {
387  
388 # for backwards compatibility
389 $use_smartpe = 1;
390 $paired = 1;
391 $splice = 1;
392 }
393 elsif ( $position eq 'ends' ) {
394 $use_ends = 1;
395 $paired = 1;
396 }
397 else {
398 print STDERR " FATAL: unrecognized position value '$position'! see help\n";
399 exit 1;
400 }
401 }
402 my $position_check =
403 $use_start +
404 $use_mid +
405 $use_span +
406 $use_cspan +
407 $use_extend +
408 $use_coverage +
409 $use_smartpe +
410 $use_ends;
411 if ( $position_check > 1 ) {
412 print STDERR " FATAL: Modes are mutually exclusive! Please select only one of\n"
413 . " --start, --mid, --span, --cpsan, --extend, --smartcov, --ends, or --coverage\n";
414 exit 1;
415 }
416 elsif ( not $position_check ) {
417  
418 # we allow no position if user has selected shift so that we can calculate
419 # the shift value without running through entire wig conversion
420 unless ($shift) {
421 print STDERR " FATAL: Please select one of the following modes:\n"
422 . " --start, --mid, --span, --cspan, --extend, --smartcov, --ends, or --coverage\n";
423 exit 1;
424 }
425 }
426  
427 # check splices
428 unless ( defined $splice ) {
429 $splice = 0;
430 }
431 if ( $paired and $splice ) {
432 if ($use_span) {
433 print
434 " switching mode to smart paired coverage with paired and splice enabled\n";
435 $use_span = 0;
436 $use_smartpe = 1;
437 }
438 elsif ($use_smartpe) {
439  
440 # perfect
441 }
442 else {
443 print STDERR
444 " FATAL: incompatible mode with paired and splices enabled! Try --smartcov\n";
445 exit 1;
446 }
447 }
448 $max_intron ||= 0;
449  
450 # check paired-end requirements
451 $paired = 1 if $fastpaired; # for purposes here, fastpair is paired
452 if ( ( $paired or $use_smartpe ) and ( $first_read or $second_read ) ) {
453 $paired = 0; # not necessary
454 $use_smartpe = 0;
455 }
456 if ($use_smartpe) {
457 $paired = 1;
458 $splice = 1;
459  
460 # warnings
461 if ($fastpaired) {
462 print " WARNING: disabling fast-paired mode with smart-paired coverage\n";
463 $fastpaired = 0;
464 }
465 if ($splice_scale) {
466 print " WARNING: disabling splice scaling with smart-paired coverage\n";
467 $splice_scale = 0;
468 }
469  
470 # required modules
471 my $fast = 0;
472 eval {
473 # required for conveniently assembling overlapping and spliced coverage
474 require Set::IntSpan::Fast;
475 $fast = 1;
476 };
477 unless ($fast) {
478 print STDERR
479 " FATAL: Module Set::IntSpan::Fast is required for smart-paired coverage\n";
480 exit 1;
481 }
482 }
483 if ($use_ends) {
484 $paired = 1;
485 }
486  
487 # incompatible options
488 if ( $splice and ( $use_extend or $extend_value ) ) {
489 print " WARNING: disabling splices when extend is defined\n";
490 $splice = 0;
491 }
492 if ( $shift and $splice ) {
493 print
494 " WARNING: enabling both shift and splices is currently not allowed. Pick one.\n";
495 exit 1;
496 }
497 if ( $shift and $paired ) {
498 print " WARNING: disabling shift with paired reads\n";
499 undef $shift;
500 }
501 if ( $use_ends and $shift ) {
502 print " WARNING: disabling shift when recording paired endpoints\n";
503 undef $shift;
504 }
505 if ( $use_ends and $splice ) {
506 print " WARNING: disabling splices when recording paired endpoints\n";
507 undef $splice;
508 }
509  
510 # check to shift position or not
511 if ( $shift or $use_extend ) {
512  
513 # set parameters for calculating shift value
514 unless ( $shift_value or $extend_value ) {
515  
516 # not provided by user, empirical calculation required
517 my $stat = 0;
518 eval {
519 # required for calculating shift
520 require Statistics::Descriptive;
521 $stat = 1;
522 };
523 unless ($stat) {
524 print STDERR
525 " FATAL: Provide a shift value or install the Perl module Statistics::Descriptive\n"
526 . " to empirically determine the shift value.\n";
527 exit 1;
528 }
529 }
530  
531 if ( defined $correlation_min ) {
532 if ( $correlation_min <= 0 or $correlation_min >= 1 ) {
533 print STDERR
534 " FATAL: cannot use minimum correlation value of $correlation_min!\n use --help for more information\n";
535 exit 1;
536 }
537 }
538 else {
539 $correlation_min = 0.5;
540 }
541 $chr_number ||= 4;
542 $zmin ||= 3;
543 $zmax ||= 10;
544 }
545  
546 # center span should have extend value
547 if ( $use_cspan and not $extend_value ) {
548 print STDERR
549 " FATAL: please use the --extval option to define an extend value when using center span\n";
550 exit 1;
551 }
552  
553 # check mapping quality
554 if ( defined $min_mapq ) {
555 if ( $min_mapq > 255 or $min_mapq < 0 ) {
556 print STDERR " FATAL: quality score must be 0-255!\n";
557 exit 1;
558 }
559 }
560 else {
561 $min_mapq = 0;
562 }
563  
564 # check paired-end insert size
565 unless ( defined $max_isize ) {
566 if ($use_smartpe) {
567  
568 # Smart paired-end coverage doesn't care at all about the size of
569 # the insertion, but it is nevertheless tested in the pe_callback to
570 # accomodate other functions. So set this to a reasonably really high number.
571 $max_isize = 100000; # 100 kb should be sufficiently high
572 }
573 else {
574 # vast majority of paired-end fragments are less than 600 bp
575 # really, really big fragments are most likely mapping errors
576 $max_isize = 600;
577 }
578 }
579 unless ( defined $min_isize ) {
580 $min_isize = 30;
581 }
582  
583 # chromosome-specific normalization
584 if ( $chrnorm or $chrapply ) {
585  
586 # must have both of these parameters
587 unless ($chrnorm) {
588 print STDERR
589 " FATAL: missing --chrnorm value a for specific-chromosome normalization!\n";
590 exit 1;
591 }
592 unless ($chrapply) {
593 print STDERR
594 "FATAL: missing --chrapply regex for specific-chromosome normalization!\n";
595 exit 1;
596 }
597 }
598  
599 # check flag parameters
600 if ($verbose) {
601 printf " %s secondary 0x100 reads\n", $nosecondary ? 'Skipping' : 'Including';
602 printf " %s duplicate 0x400 reads\n", $noduplicate ? 'Skipping' : 'Including';
603 printf " %s supplementary 0x800 reads\n",
604 $nosupplementary ? 'Skipping' : 'Including';
605 }
606  
607 # set bin size
608 if ($bin_size) {
609 if ( $bin_size < 0 ) {
610 print STDERR " FATAL: bin size cannot be negative!\n";
611 exit 1;
612 }
613 }
614 else {
615 # set default to 10 bp for any span or coverage, or 1 bp for point data
616 $bin_size = ( $use_start or $use_mid or $use_ends ) ? 1 : 10;
617 }
618  
619 # determine binary file packing and length
620 if ( $multi_hit_scale
621 or $splice_scale
622 or $chrnorm
623 or ( $use_coverage and $bin_size > 1 ) )
624 {
625 # pack as floating point values, this is 32 bit
626 $binpack = 'f';
627 }
628 else {
629 # dealing only with integers here
630 # yes we do occasionally have depth greater than 65,536
631 # originally short (16 bits), now long (32 bits)
632 $binpack = 'L';
633 }
634 $buflength = length( pack( $binpack, 1 ) );
635  
636 # set coverage dump size and subroutine code global values
637 # this is for processing the coverage dump array
638 if ($use_coverage) {
639 print " ignoring duplicate read filters with coverage\n" if $noduplicate;
640 print " ignoring supplementary read filters with coverage\n" if $nosupplementary;
641 print " ignoring secondary read filters with coverage\n" if $nosecondary;
642 print " ignoring map quality filter with coverage\n" if $min_mapq;
643 print " ignoring paired-end option with coverage\n" if $paired;
644 print " ignoring RPM option with coverage\n" if $rpm;
645 print " ignoring custom scale option with coverage\n" if @scale_values;
646 print " ignoring multi-hit fractional counting with coverage\n"
647 if $multi_hit_scale;
648 print " ignoring splice segment fractional counting with coverage\n"
649 if $splice_scale;
650 print " ignoring chromosome-specific normalization with coverage\n" if $chrnorm;
651  
652 if ( $bin_size > 1 ) {
653 $coverage_dump = int( 1000 / $bin_size ) * $bin_size;
654 $coverage_dump = $bin_size if $coverage_dump == 0;
655 $coverage_sub = sub {
656 my ( $coverage, $chrom_data ) = @_;
657 my @binned_scores;
658 my $iterator = natatime $bin_size, @{$coverage};
659 while ( my @values = $iterator->() ) {
660 push @binned_scores, mean(@values);
661 }
662 ${$chrom_data} .= pack( "$binpack*", @binned_scores );
663 };
664 }
665 else {
666 $coverage_dump = 1000;
667 $coverage_sub = sub {
668 my ( $coverage, $chrom_data ) = @_;
669 ${$chrom_data} .= pack( "$binpack*", @{$coverage} );
670 };
671 }
672 }
673  
674 # set window length for processing through packed binary chromosome strings
675 $window ||= 10000;
676  
677 # empirical tests show a window of 1000 to 10000 is best, bigger or smaller
678 # result in longer execution times
679  
680 # set decimal formatting
681 unless ( defined $dec_precison ) {
682 $dec_precison = 4 if ( $rpm or $multi_hit_scale or @scale_values );
683 $dec_precison = 1 if ( $use_coverage and $bin_size > 1 );
684 }
685  
686 # check output file
687 unless ($outfile) {
688 if ( scalar @bamfiles == 1 ) {
689 $outfile = $bamfiles[0];
690 $outfile =~ s/\.(?:b|cr)am$//xi;
691 }
692 else {
693 print STDERR
694 " FATAL: Define an output filename when providing multiple bam files!\n";
695 exit 1;
696 }
697 }
698 ( undef, my $outdir, $outbase ) = File::Spec->splitpath($outfile);
699 $outbase =~ s/\.(?: wig | bdg | bedgraph | bw | bigwig ) (?:\.gz)? $//xi;
700 $outfile =~ s/\.(?: wig | bdg | bedgraph | bw | bigwig ) (?:\.gz)? $//xi;
701  
702 # set output temporary directory
703 if ($tempdir) {
704 unless ( -x $tempdir and -d _ and -w _ ) {
705 print STDERR
706 " FATAL: Specified temp directory '$tempdir' either does not exist or is not writeable!\n";
707 exit 1;
708 }
709 $tempdir =
710 File::Temp->newdir( "bam2wigTEMP_XXXX", DIR => $tempdir, CLEANUP => 1 );
711 }
712 else {
713 # use the base path of the output wig file identified above
714 unless ($outdir) {
715 $outdir = File::Spec->curdir;
716 }
717 $tempdir = File::Temp->newdir( "bam2wigTEMP_XXXX", DIR => $outdir, CLEANUP => 1 );
718 }
719  
720 # reassemble outbase file
721 $outbase = File::Spec->catfile( $tempdir, $outbase );
722  
723 # determine output format
724 unless ( $do_bedgraph or $do_varstep or $do_fixstep ) {
725  
726 # pick an appropriate format for the user
727 if ( $use_span or $use_extend or $use_cspan or $use_coverage or $use_smartpe ) {
728 if ( $bin_size > 1 ) {
729 $do_fixstep = 1;
730 }
731 else {
732 $do_bedgraph = 1;
733 }
734 }
735 elsif ( $use_start or $use_mid or $use_ends ) {
736 if ( $bin_size > 1 ) {
737 $do_fixstep = 1;
738 }
739 else {
740 $do_varstep = 1;
741 }
742 }
743 }
744 if ( ( $do_bedgraph + $do_varstep + $do_fixstep ) > 1 ) {
745 print STDERR " FATAL: Select only one of --bedgraph, --fixstep, or --varstep\n";
746 exit 1;
747 }
748 if ( $do_varstep and $bin_size > 1 ) {
749 print
750 " WARNING: Writing variableStep wig files with bin size of $bin_size bp is not supported!"
751 . "\n Writing fixedStep wig file instead\n";
752 $do_varstep = 0;
753 $do_fixstep = 1;
754 }
755  
756 # set wig writer method
757 if ($do_bedgraph) {
758 $wig_writer = \&write_bedgraph;
759 }
760 elsif ($do_fixstep) {
761 $wig_writer = \&write_fixstep;
762 }
763 elsif ($do_varstep) {
764 $wig_writer = \&write_varstep;
765 }
766  
767 # check bigWig utility
768 if ($bigwig) {
769 unless ($bwapp) {
770 $bwapp = get_wig_to_bigwig_app();
771 }
772 if ($bwapp) {
773 if ( check_wigToBigWig_version($bwapp) ) {
774  
775 # we can write directly to utility
776 if ($verbose) {
777 print " $bwapp supports stdin, can write directly\n";
778 }
779 $post_bw_convert = 0;
780 }
781 else {
782 # we cannot write directly to utility
783 if ($verbose) {
784 print " $bwapp does not support stdin, will write temp wig file\n";
785 }
786 $post_bw_convert = 1;
787 $gz = 0;
788 }
789 }
790 else {
791 print " No external bigWig utility available, writing wig\n";
792 $bigwig = 0;
793 }
794 }
795  
796 # calculate flags for filtering out unwanted alignments
797 $unwanted_flags = 0x200; # always skip QCFAIL
798 $unwanted_flags += 0x100 if $nosecondary;
799 $unwanted_flags += 0x400 if $noduplicate;
800 $unwanted_flags += 0x800 if $nosupplementary;
801 $unwanted_flags += 0x8 if ( $paired or $fastpaired ); # skip if mate unmapped
802 $unwanted_flags += 0x80 if $first_read; # skip second read
803 $unwanted_flags += 0x40 if $second_read; # skip first read
804  
805 if ($verbose) {
806 printf " skipping alignments with calculated flag %s\n", $unwanted_flags;
807 }
808  
809 # set the initial main callback for processing alignments
810 $main_callback =
811 $fastpaired ? \&fast_pe_callback
812 : $paired ? \&pe_callback
813 : \&se_callback;
814  
815 ### Determine the alignment recording callback method
816 # coverage
817 if ($use_coverage) {
818  
819 # does not use a callback subroutine
820 undef $callback;
821 print " Recording raw alignment coverage\n";
822 }
823  
824 # start
825 elsif ( not $paired and not $do_strand and not $shift and $use_start ) {
826 $callback = \&se_start;
827 print " Recording single-end alignment starts\n";
828 }
829 elsif ( not $paired and not $do_strand and $shift and $use_start ) {
830 $callback = \&se_shift_start;
831 print " Recording single-end shifted alignment starts\n";
832 }
833 elsif ( not $paired and $do_strand and not $shift and $use_start ) {
834 $callback = \&se_strand_start;
835 print " Recording single-end stranded alignment starts\n";
836 }
837 elsif ( not $paired and $do_strand and $shift and $use_start ) {
838 $callback = \&se_shift_strand_start;
839 print " Recording single-end shifted, stranded alignment starts\n";
840 }
841  
842 # midpoint
843 elsif ( not $paired and not $do_strand and not $shift and $use_mid ) {
844 $callback = \&se_mid;
845 print " Recording single-end alignment midpoints\n";
846 }
847 elsif ( not $paired and not $do_strand and $shift and $use_mid ) {
848 $callback = \&se_shift_mid;
849 print " Recording single-end shifted alignment midpoints\n";
850 }
851 elsif ( not $paired and $do_strand and not $shift and $use_mid ) {
852 $callback = \&se_strand_mid;
853 print " Recording single-end stranded alignment midpoints\n";
854 }
855 elsif ( not $paired and $do_strand and $shift and $use_mid ) {
856 $callback = \&se_shift_strand_mid;
857 print " Recording single-end shifted, stranded alignment midpoints\n";
858 }
859  
860 # span
861 elsif ( not $paired and not $do_strand and not $shift and $use_span ) {
862 $callback = \&se_span;
863 print " Recording single-end alignment span\n";
864 }
865 elsif ( not $paired and not $do_strand and $shift and $use_span ) {
866 $callback = \&se_shift_span;
867 print " Recording single-end shifted alignment span\n";
868 }
869 elsif ( not $paired and $do_strand and not $shift and $use_span ) {
870 $callback = \&se_strand_span;
871 print " Recording single-end stranded alignment span\n";
872 }
873 elsif ( not $paired and $do_strand and $shift and $use_span ) {
874 $callback = \&se_shift_strand_span;
875 print " Recording single-end shifted, stranded alignment span\n";
876 }
877  
878 # center span
879 elsif ( not $paired and not $do_strand and not $shift and $use_cspan ) {
880 $callback = \&se_center_span;
881 print " Recording single-end alignment center-span\n";
882 }
883 elsif ( not $paired and not $do_strand and $shift and $use_cspan ) {
884 $callback = \&se_shift_center_span;
885 print " Recording single-end shifted alignment center-span\n";
886 }
887 elsif ( not $paired and $do_strand and not $shift and $use_cspan ) {
888 $callback = \&se_strand_center_span;
889 print " Recording single-end stranded alignment center-span\n";
890 }
891 elsif ( not $paired and $do_strand and $shift and $use_cspan ) {
892 $callback = \&se_shift_strand_center_span;
893 print " Recording single-end shifted, stranded alignment center-span\n";
894 }
895  
896 # extend
897 elsif ( not $paired and not $do_strand and not $shift and $use_extend ) {
898 $callback = \&se_extend;
899 print " Recording single-end extended alignment span\n";
900 }
901 elsif ( not $paired and not $do_strand and $shift and $use_extend ) {
902 $callback = \&se_shift_extend;
903 print " Recording single-end shifted, extended alignment span\n";
904 }
905 elsif ( not $paired and $do_strand and not $shift and $use_extend ) {
906 $callback = \&se_strand_extend;
907 print " Recording single-end stranded, extended alignment span\n";
908 }
909 elsif ( not $paired and $do_strand and $shift and $use_extend ) {
910 $callback = \&se_shift_strand_extend;
911 print " Recording single-end shifted, stranded, extended alignment span\n";
912 }
913  
914 # paired-end start
915 elsif ( $paired and not $do_strand and $use_start ) {
916 $callback = \&pe_start;
917 print " Recording paired-end fragment start\n";
918 }
919 elsif ( $paired and $do_strand and $use_start ) {
920 $callback = \&pe_strand_start;
921 print " Recording paired-end stranded fragment start\n";
922 }
923  
924 # paired-end midpoint
925 elsif ( $paired and not $do_strand and $use_mid ) {
926 $callback = \&pe_mid;
927 print " Recording paired-end fragment midpoint\n";
928 }
929 elsif ( $paired and $do_strand and $use_mid ) {
930 $callback = \&pe_strand_mid;
931 print " Recording paired-end stranded fragment midpoint\n";
932 }
933  
934 # paired-end span
935 elsif ( $paired and not $do_strand and $use_span ) {
936 $callback = \&pe_span;
937 print " Recording paired-end fragment span\n";
938 }
939 elsif ( $paired and $do_strand and $use_span ) {
940 $callback = \&pe_strand_span;
941 print " Recording paired-end stranded, fragment span\n";
942 }
943  
944 # paired-end center span
945 elsif ( $paired and not $do_strand and $use_cspan ) {
946 $callback = \&pe_center_span;
947 print " Recording paired-end fragment center-span\n";
948 }
949 elsif ( $paired and $do_strand and $use_cspan ) {
950 $callback = \&pe_strand_center_span;
951 print " Recording paired-end stranded, fragment center-span\n";
952 }
953  
954 # paired-end smart coverage
955 elsif ( $paired and not $do_strand and $use_smartpe ) {
956 $callback = \&smart_pe;
957 print " Recording smart paired-end coverage\n";
958 }
959 elsif ( $paired and $do_strand and $use_smartpe ) {
960 $callback = \&smart_stranded_pe;
961 print " Recording stranded, smart paired-end coverage\n";
962 }
963 elsif ( $paired and not $do_strand and $use_ends ) {
964 $callback = \&pe_ends;
965 print " Recording paired-end fragment endpoints\n";
966 }
967 elsif ( $paired and $do_strand and $use_ends ) {
968 $callback = \&pe_strand_ends;
969 print " Recording stranded, paired-end fragment endpoints\n";
970 }
971 else {
972 die "programmer error!\n" unless $shift; # special exception
973 }
974  
975 # summary of wig file being written
976 if ($do_bedgraph) {
977 print " Writing bedGraph format in $bin_size bp increments\n";
978 }
979 elsif ($do_varstep) {
980 printf " Writing variableStep format in $bin_size bp bins\n";
981 }
982 elsif ($do_fixstep) {
983 printf " Writing fixedStep format in $bin_size bp bins\n";
984 }
985 }
986  
987 sub process_exclusion_list {
988 if ( $exclude_file and -e $exclude_file ) {
989 my $i = 0;
990 eval { require Set::IntervalTree; $i = 1; };
991 unless ($i) {
992 print " WARNING! Please install Set::IntervalTree to use exclusion lists\n";
993 undef $exclude_file;
994 return;
995 }
996 my %list_hash = map { $_ => [] } @seq_list;
997 my $Data = Bio::ToolBox->load_file($exclude_file)
998 or die "unable to read exclusion list file '$exclude_file'\n";
999 unless ( $Data->feature_type eq 'coordinate' ) {
1000 printf
1001 " WARNING! Exclusion list file '%s' does not have coordinates! Ignoring.\n",
1002 $exclude_file;
1003 return \%list_hash;
1004 }
1005 $Data->iterate(
1006 sub {
1007 my $row = shift;
1008 push @{ $list_hash{ $row->seq_id } }, [ $row->start - 1, $row->end ]
1009 if exists $list_hash{ $row->seq_id };
1010 }
1011 );
1012 printf " Loaded %s exclusion list regions\n",
1013 format_with_commas( $Data->number_rows );
1014 return \%list_hash;
1015 }
1016 return;
1017 }
1018  
1019 ### Determine the shift value
1020 sub determine_shift_value {
1021  
1022 # identify top regions to score
1023 # we will walk through the largest chromosome(s) looking for the top
1024 # 500 bp regions containing the highest unstranded coverage to use
1025 print " sampling the top coverage regions "
1026 . "on the largest $chr_number chromosomes...\n";
1027  
1028 # first sort the chromosomes by size
1029 # this is assuming all the chromosomes have different sizes ;-)
1030 # use a Schwartzian transform
1031 my $sam = $sams[0];
1032 my @chromosomes =
1033 map { $_->[0] }
1034 sort { $b->[1] <=> $a->[1] }
1035 map { [ $_, $sam->target_len($_) ] } ( 0 .. $sam->n_targets - 1 );
1036 @chromosomes = splice( @chromosomes, 0, $chr_number );
1037  
1038 # result arrays
1039 my @shift_values;
1040 my @f_profile;
1041 my @r_profile;
1042 my @shifted_profile;
1043 my @r_values;
1044 my @all_r_values;
1045 my @regions;
1046  
1047 # look for high coverage regions to sample
1048 # do this in multi-threaded fashion if possible
1049  
1050 if ( $cpu > 1 ) {
1051  
1052 # do each chromosome in parallel
1053 print " Forking into children for parallel scanning\n";
1054 printf " Scanning %s\n",
1055 join( ", ", map { $sam->target_name($_) } @chromosomes );
1056 print "SeqID\t#Intervals\tMean\tMax\tStdDev\tMinCutoff\tMaxCutoff\t#Collected\n"
1057 if $verbose;
1058  
1059 # set up
1060 my $pm = Parallel::ForkManager->new($cpu);
1061 $pm->run_on_finish(
1062 sub {
1063 my ( $pid, $exit_code, $ident, $exit_signal, $core_dump, $result ) =
1064 @_;
1065  
1066 # record the chromosome results
1067 push @shift_values, @{ $result->[0] }; # push the actual values
1068 push @f_profile, @{ $result->[1] };
1069 push @r_profile, @{ $result->[2] };
1070 push @shifted_profile, @{ $result->[3] };
1071 push @all_r_values, @{ $result->[4] };
1072 push @regions, @{ $result->[5] };
1073 push @r_values, @{ $result->[6] };
1074 }
1075 );
1076  
1077 # scan the chromosomes in parallel
1078 for my $tid (@chromosomes) {
1079 $pm->start and next;
1080  
1081 ### In child
1082 $sam->clone; # to make it fork safe
1083  
1084 # calculate the correlation
1085 my $result = calculate_strand_correlation( $sam, $tid );
1086  
1087 $pm->finish( 0, $result );
1088 }
1089 $pm->wait_all_children;
1090 }
1091 else {
1092 # one chromosome at a time
1093 printf " Scanning %s\n",
1094 join( ", ", map { $sam->target_name($_) } @chromosomes );
1095 print "SeqID\t#Intervals\tMean\tMax\tStdDev\tMinCutoff\tMaxCutoff\t#Collected\n"
1096 if $verbose;
1097 for my $tid (@chromosomes) {
1098  
1099 # calculate the correlation
1100 my $result = calculate_strand_correlation( $sam, $tid );
1101  
1102 # record the results for this chromosome
1103 push @shift_values, @{ $result->[0] }; # push the actual values
1104 push @f_profile, @{ $result->[1] };
1105 push @r_profile, @{ $result->[2] };
1106 push @shifted_profile, @{ $result->[3] };
1107 push @all_r_values, @{ $result->[4] };
1108 push @regions, @{ $result->[5] };
1109 push @r_values, @{ $result->[6] };
1110 }
1111 }
1112 printf " %s regions found with a correlative shift in %.1f minutes\n",
1113 format_with_commas( scalar @shift_values ), ( time - $start_time ) / 60;
1114  
1115 # determine the optimal shift value
1116 # we will be using a trimmed mean value to avoid outliers
1117 my $stat = Statistics::Descriptive::Sparse->new;
1118 $stat->add_data(@shift_values);
1119 printf " The collected mean shift value is %.0f +/- %.0f bp\n",
1120 $stat->mean, $stat->standard_deviation;
1121 my $raw_min = $stat->mean - ( 1.5 * $stat->standard_deviation );
1122 $raw_min = 0 if $raw_min < 0;
1123 my $raw_max = $stat->mean + ( 1.5 * $stat->standard_deviation );
1124 my @trimmed_shift_values;
1125 my @trimmed_f_profile;
1126 my @trimmed_r_profile;
1127 my @trimmed_shifted_profile;
1128 my @trimmed_r_values;
1129 my @trimmed_regions;
1130 my @trimmed_bestr;
1131  
1132 foreach my $i ( 0 .. $#shift_values ) {
1133 if ( $shift_values[$i] >= $raw_min and $shift_values[$i] <= $raw_max ) {
1134 push @trimmed_shift_values, $shift_values[$i];
1135 push @trimmed_f_profile, $f_profile[$i];
1136 push @trimmed_r_profile, $r_profile[$i];
1137 push @trimmed_shifted_profile, $shifted_profile[$i];
1138 push @trimmed_r_values, $all_r_values[$i];
1139 push @trimmed_regions, $regions[$i];
1140 push @trimmed_bestr, $r_values[$i];
1141 }
1142 }
1143 $stat->clear;
1144 $stat->add_data(@trimmed_shift_values);
1145 my $best_value = sprintf( "%.0f", $stat->mean );
1146 printf " The trimmed mean shift value is %s +/- %.0f bp from %s regions\n",
1147 $best_value, $stat->standard_deviation,
1148 format_with_commas( $stat->count );
1149  
1150 # write out the shift model data file
1151 if ($model) {
1152 write_model_file(
1153 $best_value, \@trimmed_f_profile,
1154 \@trimmed_r_profile, \@trimmed_shifted_profile,
1155 \@trimmed_r_values, \@trimmed_regions,
1156 \@trimmed_shift_values, \@trimmed_bestr
1157 );
1158 }
1159  
1160 # done
1161 return $best_value;
1162 }
1163  
1164 sub calculate_strand_correlation {
1165 my ( $sam, $tid ) = @_;
1166  
1167 my ( $collected, $data ) = scan_high_coverage( $sam, $tid );
1168  
1169 my @shift_values;
1170 my @bestr_values;
1171 my @all_r_values;
1172 my @f_profile;
1173 my @r_profile;
1174 my @shifted_profile;
1175 my @regions;
1176  
1177 # determine the optimal shift for each of the test regions
1178 foreach my $pos ( @{$collected} ) {
1179  
1180 # generate region string
1181 my $region = sprintf "%s:%d..%d", $sam->target_name($tid), $pos * 10,
1182 ( $pos + 50 ) * 10;
1183  
1184 # grab the stranded scores from the collected binned point data
1185 my $start = $pos - 50;
1186 $start = 0 if $start < 0;
1187 my $stop = $pos + 99;
1188 $stop = scalar( @{ $data->{f} } ) if $stop > scalar( @{ $data->{f} } );
1189 my @f = map { $data->{f}->[$_] || 0 } ( $start .. $stop );
1190 my @r = map { $data->{r}->[$_] || 0 } ( $start .. $stop );
1191 my @original_f = @f;
1192 my @original_r = @r;
1193 my $best_r = 0;
1194 my $best_shift = 0;
1195 my @best_profile;
1196 my @r_values;
1197  
1198 # calculate correlations
1199 for ( my $i = 0; $i <= 50; $i++ ) {
1200  
1201 # check shift from 0 to 500 bp
1202  
1203 # adjust the arrays, mimicking shifting arrays towards the 3'
1204 if ($i) {
1205 unshift @f, 0;
1206 pop @f;
1207 shift @r;
1208 push @r, 0;
1209 }
1210  
1211 # calculate correlation
1212 my $stat = Statistics::Descriptive::Full->new();
1213 $stat->add_data(@f);
1214 my ( $q, $m, $r, $rms ) = $stat->least_squares_fit(@r);
1215  
1216 # this may produce errors when all values are equal
1217 # as might happen with high duplicate coverage
1218  
1219 # check correlation
1220 push @r_values, $r;
1221 if ( $r >= $correlation_min and $r > $best_r ) {
1222  
1223 # record new values
1224 $best_shift = $i * 10;
1225 $best_r = $r;
1226  
1227 # record the best profile, average of f and r values
1228 if ($model) {
1229  
1230 # this is only required when reporting the model
1231 for my $i ( 0 .. 129 ) {
1232 $best_profile[$i] = ( $f[$i] + $r[$i] ) / 2;
1233 }
1234 }
1235 }
1236 }
1237  
1238 # record result
1239 if ( $best_r > $correlation_min ) {
1240 push @shift_values, $best_shift;
1241 if ($model) {
1242 push @f_profile, \@original_f;
1243 push @r_profile, \@original_r;
1244 push @shifted_profile, \@best_profile;
1245 push @all_r_values, \@r_values;
1246 push @regions, $region;
1247 push @bestr_values, $best_r;
1248 }
1249 }
1250 }
1251  
1252 return [
1253 \@shift_values, \@f_profile, \@r_profile, \@shifted_profile,
1254 \@all_r_values, \@regions, \@bestr_values
1255 ];
1256 }
1257  
1258 sub scan_high_coverage {
1259 my ( $sam, $tid ) = @_;
1260  
1261 # walk entire length of chromosome collecting alignment start data in bins of 10 bp
1262 my $chr_length = $sam->target_len($tid);
1263 my %data = (
1264 f => [],
1265 r => [],
1266 );
1267 low_level_bam_fetch( $sam, $tid, 0, $chr_length, \&shift_value_callback, \%data );
1268  
1269 # score 500 bp intervals for coverage
1270 my %pos2depth;
1271 for ( my $start = 0; $start < int( $chr_length / 10 ); $start += 50 ) {
1272 my $readsum = sum0( map { $data{f}->[$_] || 0 } ( $start .. $start + 49 ) );
1273 $readsum += sum0( map { $data{r}->[$_] || 0 } ( $start .. $start + 49 ) );
1274 next if $readsum == 0;
1275 $pos2depth{$start} = $readsum;
1276 }
1277  
1278 # use Statistics::Descriptive to determine the mean, stddev, and then
1279 # loop through the pos2depth hash and select out those +2 z-scores
1280 # maybe exclude the highest ones? +4 or +5?
1281 my $stat = Statistics::Descriptive::Sparse->new();
1282 $stat->add_data( values %pos2depth );
1283 my $count = $stat->count;
1284 my $mean = $stat->mean;
1285 my $max = $stat->max;
1286 my $sd = $stat->standard_deviation;
1287 my $mincutoff = $mean + ( $zmin * $sd );
1288 my $maxcutoff = $mean + ( $zmax * $sd );
1289  
1290 # filter out the best ones
1291 my @collected;
1292 foreach my $p ( keys %pos2depth ) {
1293 push @collected, $p
1294 if $pos2depth{$p} > $mincutoff and $pos2depth{$p} < $maxcutoff;
1295 }
1296 if ($verbose) {
1297 printf "%s\t%d\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\t%d\n", $sam->target_name($tid),
1298 $count, $mean, $max, $sd, $mincutoff, $maxcutoff, scalar(@collected);
1299 }
1300  
1301 return ( \@collected, \%data );
1302 }
1303  
1304 sub shift_value_callback {
1305 my ( $a, $data ) = @_;
1306  
1307 # check alignment quality and flags
1308 return if ( $min_mapq and $a->qual < $min_mapq ); # mapping quality
1309 my $flag = $a->flag;
1310 return if ( $flag & 0x0100 ); # not primary hit
1311 return if ( $flag & 0x0200 ); # QC failed but still aligned? is this necessary?
1312 return if ( $flag & 0x0400 ); # marked duplicate
1313 return if ( $flag & 0x0800 ); # supplementary hit
1314  
1315 # record stranded start in 10 bp bins
1316 if ( $a->reversed ) {
1317 my $p = int( $a->calend / 10 );
1318 $data->{r}->[$p] += 1;
1319 }
1320 else {
1321 my $p = int( $a->pos / 10 );
1322 $data->{f}->[$p] += 1;
1323 }
1324 }
1325  
1326 ### Write a text data file with the shift model data
1327 sub write_model_file {
1328 my ( $value, $f_profile, $r_profile, $shifted_profile, $r_valuess,
1329 $regions, $region_shifts, $region_bestr )
1330 = @_;
1331  
1332 ### Profile model
1333 # Prepare the centered profiles from the raw profiles
1334 # these will be -450 to +450, with 0 being the shifted profile peak
1335 my @centered_f_profile;
1336 my @centered_r_profile;
1337 my @centered_shifted_profile;
1338 for my $r ( 0 .. $#{$regions} ) {
1339  
1340 # first identify the peak in the shifted profile
1341 my $peak = 0;
1342 my $peak_i;
1343 for my $i ( 0 .. 129 ) {
1344 if ( $shifted_profile->[$r][$i] > $peak ) {
1345 $peak = $shifted_profile->[$r][$i];
1346 $peak_i = $i;
1347 }
1348 }
1349  
1350 # collect the centered profiles
1351 for my $i ( 0 .. 90 ) {
1352 my $current_i = $peak_i - 45 + $i;
1353 if ( $current_i >= 0 and $current_i <= 129 ) {
1354  
1355 # check that the current index is within the raw index range
1356 $centered_f_profile[$r][$i] = $f_profile->[$r][$current_i];
1357 $centered_r_profile[$r][$i] = $r_profile->[$r][$current_i];
1358 $centered_shifted_profile[$r][$i] = $shifted_profile->[$r][$current_i];
1359 }
1360 else {
1361 # otherwise record zeros
1362 $centered_f_profile[$r][$i] = 0;
1363 $centered_r_profile[$r][$i] = 0;
1364 $centered_shifted_profile[$r][$i] = 0;
1365 }
1366 }
1367 }
1368  
1369 # Prepare the data structure
1370 my $Data = Bio::ToolBox->new_data(
1371 'Start',
1372 sprintf( "%s_F", $outfile ),
1373 sprintf( "%s_R", $outfile ),
1374 sprintf( "%s_shift", $outfile )
1375 );
1376 return unless $Data;
1377 $Data->add_comment('Average profile of read start point sums');
1378 $Data->add_comment('Only profiles of trimmed shift value samples included');
1379 $Data->add_comment("Final shift value calculated as $value bp");
1380 $Data->metadata( 4, 'minimum_r', $correlation_min );
1381 $Data->metadata( 4, 'number_of_chromosomes_sampled', $chr_number );
1382 $Data->metadata( 4, 'regions_sampled', scalar( @{$f_profile} ) );
1383  
1384 # Load data table
1385 # first we will put the mean value for all the regions
1386 for my $i ( 0 .. 90 ) {
1387 my $s = ( $i - 45 ) * 10;
1388 my $f = mean( map { $centered_f_profile[$_][$i] } ( 0 .. $#centered_f_profile ) );
1389 my $r = mean( map { $centered_r_profile[$_][$i] } ( 0 .. $#centered_r_profile ) );
1390 my $m = mean( map { $centered_shifted_profile[$_][$i] }
1391 ( 0 .. $#centered_shifted_profile ) );
1392 $Data->add_row( [ $s, $f, $r, $m ] );
1393 }
1394  
1395 # Write the model file
1396 my $profile_file = $Data->write_file(
1397 'filename' => sprintf( "%s_model.txt", $outfile ),
1398 'gz' => 0,
1399 );
1400 print " Wrote shift profile model data file $profile_file\n" if $profile_file;
1401  
1402 ### R squared data
1403 # prepare the data structure
1404 undef $Data;
1405 $Data = Bio::ToolBox->new_data( 'Shift', sprintf( "%s_R", $outfile ) );
1406 $Data->add_comment('Average correlation values for each shift');
1407 $Data->add_comment("Final shift value calculated as $value bp");
1408 $Data->metadata( 1, 'minimum_r', $correlation_min );
1409 $Data->metadata( 1, 'number_of_chromosomes_sampled', $chr_number );
1410 $Data->metadata( 1, 'regions_sampled', scalar( @{$f_profile} ) );
1411  
1412 # load data table
1413 # first we will put the mean value for all the r squared values
1414 for my $i ( 0 .. 50 ) {
1415  
1416 # generate the start position
1417 my $s = $i * 10;
1418  
1419 # generate the mean value for each chromosome
1420 my $m = mean( map { $r_valuess->[$_][$i] } ( 0 .. $#{$regions} ) );
1421 $Data->add_row( [ $s, $m ] );
1422 }
1423  
1424 # write the r squared file
1425 my $success = $Data->write_file(
1426 'filename' => sprintf( "%s_correlations.txt", $outfile ),
1427 'gz' => 0,
1428 );
1429 print " Wrote shift correlation data file $success\n" if $success;
1430  
1431 ### Write regions
1432 undef $Data;
1433 $Data = Bio::ToolBox->new_data( 'Region', 'Shift', 'BestCorrelation' );
1434 $Data->add_comment('All correlated regions identified');
1435 for my $i ( 0 .. $#{$regions} ) {
1436 $Data->add_row( [ $regions->[$i], $region_shifts->[$i], $region_bestr->[$i] ] );
1437 }
1438 $success = $Data->write_file(
1439 'filename' => sprintf( "%s_correlated_regions.txt", $outfile ),
1440 'gz' => 0
1441 );
1442 print " Wrote correlated regions data file $success\n" if $success;
1443 }
1444  
1445 sub mean {
1446 return sum0(@_) / scalar(@_);
1447 }
1448  
1449 sub open_wig_file {
1450 my ( $name, $do_bw ) = @_;
1451  
1452 # open a bigWig file handle if requested
1453 if ( $do_bw and $bigwig and not $post_bw_convert ) {
1454 print " Writing directly to bigWig converter\n";
1455 $name .= '.bw' unless $name =~ /\.bw$/;
1456 my $fh = open_wig_to_bigwig_fh(
1457 file => $name,
1458 chromo => $chromo_file,
1459 bwapppath => $bwapp,
1460 );
1461 if ($fh) {
1462 return ( $name, $fh );
1463 }
1464 else {
1465 # we couldn't open a wigToBigWig filehandle for some reason
1466 # so default to standard wig file
1467 # typically a failure of wigToBigWig will bring the entire process
1468 # down, so this may not be all that necessary
1469 print " unable to open a bigWig file, writing standard wig file\n";
1470 $name =~ s/\.bw$//;
1471 }
1472 }
1473  
1474 # otherwise we open a text wig file
1475 unless ( $name =~ /\. (?: bdg |wig ) (?:\.gz)? $/xi ) {
1476 $name .= $do_bedgraph ? '.bdg' : '.wig';
1477 }
1478 my $do_gz = ( $gz and $do_bw ) ? 1 : 0;
1479  
1480 # using the do_bw value because that tells us if it's a temp file or not
1481 $name .= '.gz' if ( $do_gz and $name !~ /\.gz$/i );
1482 my $fh = Bio::ToolBox->write_file( $name, $do_gz )
1483 or die " unable to open output wig file '$name'!\n";
1484  
1485 # finished
1486 return ( $name, $fh );
1487 }
1488  
1489 ### Collect alignment coverage
1490 sub process_bam_coverage {
1491  
1492 # flag to write temporary binary files or go straight to wig files
1493 my $do_temp_bin = scalar(@sams) > 1 ? 1 : 0;
1494  
1495 # walk through each bam file and chromosome one a time
1496 for my $samid ( 0 .. $#sams ) {
1497 foreach my $seq_id (@seq_list) {
1498 process_bam_coverage_on_chromosome( $samid, $sams[$samid], $seq_id,
1499 $do_temp_bin );
1500 }
1501 }
1502  
1503 # find and merge binary files
1504 if ($do_temp_bin) {
1505 print " Merging temporary files from each bam\n";
1506  
1507 # find the children
1508 my %files;
1509 my @filelist = glob("$outbase.*.temp.bin");
1510 my $expected = scalar(@sams) * scalar(@seq_list) * ( $do_strand ? 2 : 1 );
1511 if ( scalar(@filelist) != $expected ) {
1512 die sprintf(
1513 " unable to find all the temporary binary children files! Only found %d, expected %d\n",
1514 scalar(@filelist), $expected );
1515 }
1516 foreach my $file (@filelist) {
1517  
1518 # each file name is basename.samid.seqid.count.strand.bin.gz
1519 if ( $file =~ /$outbase \.(\d+) \.(.+) \.0 \.f \.temp \.bin \Z/x ) {
1520 my $samid = $1;
1521 my $seqid = $2;
1522 $files{$seqid}{$samid} = $file;
1523 }
1524 }
1525  
1526 # check to see how we combine the multiple source sam file coverages
1527 my @norms;
1528 if ($do_mean) {
1529  
1530 # just need to take an average
1531 foreach (@sams) { push @norms, ( 1 / scalar(@sams) ) }
1532 }
1533  
1534 # otherwise we just add the samples
1535  
1536 # merge the samples
1537 foreach my $seq_id (@seq_list) {
1538 merge_bin_files( $seq_id, 'f', 0, $files{$seq_id}, \@norms );
1539 }
1540 }
1541  
1542 # write final wig file
1543 return write_final_wig_file();
1544 }
1545  
1546 ### Parallel process coverage
1547 sub parallel_process_bam_coverage {
1548  
1549 # flag to write temporary binary files or go straight to wig files
1550 my $do_temp_bin = scalar(@sams) > 1 ? 1 : 0;
1551  
1552 # generate pool of to do items
1553 my @pool;
1554 for my $s ( 0 .. $#sams ) {
1555 foreach my $seq_id (@seq_list) {
1556 push @pool, [ $s, $sams[$s], $seq_id ];
1557 }
1558 }
1559  
1560 # prepare ForkManager for working on all chromosomes and bam files in parallel
1561 print " Forking into $cpu children for parallel conversion\n";
1562 my $pm = Parallel::ForkManager->new($cpu);
1563 foreach my $stuff (@pool) {
1564 $pm->start and next;
1565 my ( $samid, $sam, $seq_id ) = @{$stuff};
1566  
1567 # clone the sam object for safe forking
1568 $sam->clone;
1569 process_bam_coverage_on_chromosome( $samid, $sam, $seq_id, $do_temp_bin );
1570 $pm->finish;
1571 }
1572 $pm->wait_all_children;
1573  
1574 # find and merge binary files
1575 # we can do this in parallel too!
1576 if ($do_temp_bin) {
1577 print " Merging temporary files from each bam\n";
1578  
1579 # find the children
1580 my %files;
1581 my @filelist = glob("$outbase.*.temp.bin");
1582 my $expected = scalar(@sams) * scalar(@seq_list) * ( $do_strand ? 2 : 1 );
1583 if ( scalar(@filelist) != $expected ) {
1584 die sprintf(
1585 " unable to find all the temporary binary children files! Only found %d, expected %d\n",
1586 scalar(@filelist), $expected );
1587 }
1588 foreach my $file (@filelist) {
1589  
1590 # each file name is basename.samid.seqid.count.strand.bin.gz
1591 if ( $file =~ /$outbase \.(\d+) \.(.+) \.0 \.f \.temp \.bin \Z/x ) {
1592 my $samid = $1;
1593 my $seqid = $2;
1594 $files{$seqid}{$samid} = $file;
1595 }
1596 }
1597  
1598 # check to see how we combine the multiple source sam file coverages
1599 my @norms;
1600 if ($do_mean) {
1601  
1602 # just need to take an average
1603 foreach (@sams) { push @norms, ( 1 / scalar(@sams) ) }
1604 }
1605  
1606 # otherwise we just add the samples
1607  
1608 # merge the samples
1609 foreach my $seq_id (@seq_list) {
1610 $pm->start and next;
1611 merge_bin_files( $seq_id, 'f', 0, $files{$seq_id}, \@norms );
1612 $pm->finish;
1613 }
1614 $pm->wait_all_children;
1615 }
1616  
1617 # merge and write final wig file
1618 return write_final_wig_file();
1619 }
1620  
1621 sub process_bam_coverage_on_chromosome {
1622 my ( $samid, $sam, $seq_id, $do_temp_bin ) = @_;
1623 my $chr_start_time = time;
1624  
1625 # identify chromosome target id
1626 my ( $tid, undef, undef ) = $sam->header->parse_region($seq_id);
1627 unless ( defined $tid ) {
1628 printf " WARNING: unable to parse target id for '%s' from bam file %s!\n",
1629 $seq_id, $bamfiles[$samid];
1630  
1631 # we continue but this will silently fail the low level fetch below
1632 # but at least an empty temp file will be written allowing program to finish
1633 }
1634 my $seq_length = $seq_name2length{$seq_id};
1635  
1636 # walk through the chromosome in 1 kb increments
1637 my $chrom_data;
1638 for ( my $start = 0; $start < $seq_length; $start += $coverage_dump ) {
1639  
1640 # set endpoint
1641 my $end = $start + $coverage_dump;
1642 $end = $seq_length if $end > $seq_length;
1643  
1644 # using the low level interface for a little more performance
1645 my $coverage = low_level_bam_coverage( $sam, $tid, $start, $end );
1646  
1647 # record the coverage
1648 &{$coverage_sub}( $coverage, \$chrom_data );
1649 }
1650  
1651 # write out chromosome binary file, set count to arbitrary 0
1652 if ($do_temp_bin) {
1653 write_bin_file( \$chrom_data,
1654 join( '.', $outbase, $samid, $seq_id, 0, 'f', 'temp.bin' ) );
1655 }
1656 else {
1657 &{$wig_writer}(
1658 \$chrom_data, $binpack, $seq_id, $seq_length,
1659 join( '.', $outbase, $samid, $seq_id, 0, 'f', 'temp.wig' )
1660 );
1661 }
1662  
1663 # verbose status line
1664 if ($verbose) {
1665 printf " Generated read coverage on $seq_id in %d seconds\n",
1666 time - $chr_start_time;
1667 }
1668 }
1669  
1670 sub process_alignments {
1671  
1672 # flag to write temporary binary files or go straight to wig files
1673 my $do_temp_bin = scalar(@sams) > 1 ? 1 : $rpm ? 1 : @scale_values ? 1 : 0;
1674  
1675 # walk through each bam file and chromosome one a time
1676 for my $samid ( 0 .. $#sams ) {
1677 foreach my $seq_id (@seq_list) {
1678 process_alignments_on_chromosome( $samid, $sams[$samid], $seq_id,
1679 $do_temp_bin );
1680 }
1681 }
1682  
1683 if ($verbose) {
1684 printf " Finished converting $items in %.3f minutes\n",
1685 ( time - $start_time ) / 60;
1686 }
1687  
1688 # find and merge binary files
1689 # we can do this in parallel too!
1690 if ($do_temp_bin) {
1691  
1692 # find the children
1693 my @totals;
1694 my %seq_totals;
1695 my %files;
1696 my @filelist = glob("$outbase.*.temp.bin");
1697 my $expected = scalar(@sams) * scalar(@seq_list) * ( $do_strand ? 2 : 1 );
1698 if ( scalar(@filelist) != $expected ) {
1699 die sprintf(
1700 " unable to find all the temporary binary children files! Only found %d, expected %d\n",
1701 scalar(@filelist), $expected );
1702 }
1703 foreach my $file (@filelist) {
1704  
1705 # each file name is basename.samid.seqid.count.strand.bin.gz
1706 if ( $file =~ /$outbase \.(\d+) \.(.+) \.(\d+) \.([fr]) \.temp \.bin \Z/x ) {
1707 my $samid = $1;
1708 my $seq_id = $2;
1709 my $count = $3;
1710 my $strand = $4;
1711 $totals[$samid] += $count;
1712 $seq_totals{$seq_id}{$strand} += $count;
1713 $files{$seq_id}{$strand}{$samid} = $file;
1714 }
1715 }
1716  
1717 # sanity check of totals to avoid division by 0
1718 if ( any { $_ == 0 } @totals ) {
1719 die sprintf(
1720 " One or more bam files generated zero alignment counts!\n Counts: %s\n",
1721 join( ',', @totals ) );
1722 }
1723  
1724 # merging multiple files
1725 if ( scalar(@sams) > 1 ) {
1726 print " Merging temporary files from each bam\n" if ( scalar(@sams) > 1 );
1727 if ($rpm) {
1728 print " Normalizing depth\n" if $rpm;
1729 for my $i ( 0 .. $#totals ) {
1730 printf " %s had %s total counted $items\n", $bamfiles[$i],
1731 format_with_commas( $totals[$i] );
1732 }
1733 }
1734  
1735 # check to see how we combine the multiple source sam file coverages
1736 my @norms;
1737 if ( $rpm and $do_mean ) {
1738  
1739 # we need to scale each sam source individually and take an average
1740 # calculate normalization factor for each sam file
1741 @norms = map { 1_000_000 / ( $_ * scalar(@sams) ) } @totals;
1742 }
1743 elsif ( $rpm and not $do_mean ) {
1744  
1745 # scale them all the same
1746 my $factor = 1_000_000 / ( sum0(@totals) * scalar(@sams) );
1747 foreach (@sams) {
1748 push @norms, $factor;
1749 }
1750 }
1751 elsif ( not $rpm and $do_mean ) {
1752  
1753 # just need to take an average
1754 foreach (@sams) { push @norms, ( 1 / scalar(@sams) ) }
1755 }
1756  
1757 # otherwise we just add the samples
1758  
1759 # add scale values on top as necessary
1760 if (@scale_values) {
1761 print " Scaling depth with user-supplied factor\n";
1762 if (@norms) {
1763 for my $i ( 0 .. $#norms ) {
1764 $norms[$i] *= $scale_values[$i];
1765 }
1766 }
1767 else {
1768 @norms = @scale_values;
1769 }
1770 }
1771 printf " Normalization factors: %s\n", join( q( ), @norms ) if $verbose;
1772  
1773 # merge the samples
1774 foreach my $seq_id (@seq_list) {
1775 foreach my $strand (qw(f r)) {
1776 next unless defined $files{$seq_id}{$strand};
1777 merge_bin_files(
1778 $seq_id, $strand,
1779 $seq_totals{$seq_id}{$strand},
1780 $files{$seq_id}{$strand}, \@norms
1781 );
1782 }
1783 }
1784  
1785 if ($verbose) {
1786 printf " Finished merging%s in %.3f minutes\n",
1787 defined $norms[0] ? ' and normalizing' : q(),
1788 ( time - $start_time ) / 60;
1789 }
1790 }
1791  
1792 # otherwise we just normalize
1793 else {
1794 # determine scaling factor
1795 my $scale_factor = 1;
1796 if ($rpm) {
1797 printf " Normalizing depth based on %s total counted $items\n",
1798 format_with_commas( $totals[0] );
1799 $scale_factor = 1_000_000 / $totals[0];
1800 }
1801 if ( scalar @scale_values ) {
1802  
1803 # user supplied scaling factor
1804 print " Scaling depth with user-supplied factor\n";
1805 $scale_factor *= $scale_values[0];
1806 }
1807  
1808 # normalize the wig files
1809 foreach my $seq_id (@seq_list) {
1810 foreach my $strand (qw(f r)) {
1811 next unless defined $files{$seq_id}{$strand};
1812 normalize_bin_file( $files{$seq_id}{$strand}{0},
1813 $scale_factor, $seq_id );
1814 }
1815 }
1816 }
1817 }
1818  
1819 # write final wig file
1820 print " Merging temporary files\n";
1821 return write_final_wig_file();
1822 }
1823  
1824 sub parallel_process_alignments {
1825  
1826 # generate pool of to do items
1827 my @pool;
1828 for my $s ( 0 .. $#sams ) {
1829 foreach my $seq_id (@seq_list) {
1830 push @pool, [ $s, $sams[$s], $seq_id ];
1831 }
1832 }
1833  
1834 # flag to write temporary binary files or go straight to wig files
1835 my $do_temp_bin = scalar(@sams) > 1 ? 1 : $rpm ? 1 : @scale_values ? 1 : 0;
1836  
1837 # prepare ForkManager for working on all chromosomes and bam files in parallel
1838 print " Forking into $cpu children for parallel conversion\n";
1839 my $pm = Parallel::ForkManager->new($cpu)
1840 or die "unable to initialize ForkManager object!\n";
1841 foreach my $stuff (@pool) {
1842 $pm->start and next;
1843 my ( $samid, $sam, $seq_id ) = @{$stuff};
1844  
1845 # clone the sam object for safe forking
1846 $sam->clone;
1847 process_alignments_on_chromosome( $samid, $sam, $seq_id, $do_temp_bin );
1848 $pm->finish;
1849 }
1850 $pm->wait_all_children;
1851  
1852 if ($verbose) {
1853 printf " Finished converting $items in %.3f minutes\n",
1854 ( time - $start_time ) / 60;
1855 }
1856  
1857 # find and merge binary files
1858 # we can do this in parallel too!
1859 if ($do_temp_bin) {
1860  
1861 # find the children
1862 my @totals;
1863 my %seq_totals;
1864 my %files;
1865 my @filelist = glob("$outbase.*.temp.bin");
1866 my $expected = scalar(@sams) * scalar(@seq_list) * ( $do_strand ? 2 : 1 );
1867 if ( scalar(@filelist) != $expected ) {
1868 die sprintf(
1869 " unable to find all the temporary binary children files! Only found %d, expected %d\n",
1870 scalar(@filelist), $expected );
1871 }
1872 foreach my $file (@filelist) {
1873  
1874 # each file name is basename.samid.seqid.count.strand.bin.gz
1875 if ( $file =~ /$outbase \.(\d+) \.(.+) \.(\d+) \.([fr]) \.temp \.bin \Z/x ) {
1876 my $samid = $1;
1877 my $seq_id = $2;
1878 my $count = $3;
1879 my $strand = $4;
1880 $totals[$samid] += $count;
1881 $seq_totals{$seq_id}{$strand} += $count;
1882 $files{$seq_id}{$strand}{$samid} = $file;
1883 }
1884 }
1885  
1886 # sanity check of totals to avoid division by 0
1887 if ( any { $_ == 0 } @totals ) {
1888 die sprintf(
1889 " One or more bam files generated zero alignment counts!\n Counts: %s\n",
1890 join( ',', @totals ) );
1891 }
1892  
1893 # merging multiple files
1894 if ( scalar(@sams) > 1 ) {
1895  
1896 # print processing statements
1897 print " Merging temporary files from each bam\n" if ( scalar(@sams) > 1 );
1898 if ($rpm) {
1899 print " Normalizing depth\n" if $rpm;
1900 for my $i ( 0 .. $#totals ) {
1901 printf " %s had %s total counted $items\n", $bamfiles[$i],
1902 format_with_commas( $totals[$i] );
1903 }
1904 }
1905  
1906 # check to see how we combine the multiple source sam file coverages
1907 my @norms;
1908 if ( $rpm and $do_mean ) {
1909  
1910 # we need to scale each sam source individually and take an average
1911 # calculate normalization factor for each sam file
1912 @norms = map { 1_000_000 / ( $_ * scalar(@sams) ) } @totals;
1913  
1914 }
1915 elsif ( $rpm and not $do_mean ) {
1916  
1917 # scale them all the same
1918 my $factor = 1_000_000 / ( sum0(@totals) * scalar(@sams) );
1919 foreach (@sams) {
1920 push @norms, $factor;
1921 }
1922 }
1923 elsif ( not $rpm and $do_mean ) {
1924  
1925 # just need to take an average
1926 foreach (@sams) { push @norms, ( 1 / scalar(@sams) ) }
1927 }
1928  
1929 # otherwise we just add the samples
1930  
1931 # add scale values on top as necessary
1932 if (@scale_values) {
1933 print " Scaling depth with user-supplied factor\n";
1934 if (@norms) {
1935 for my $i ( 0 .. $#norms ) {
1936 $norms[$i] *= $scale_values[$i];
1937 }
1938 }
1939 else {
1940 @norms = @scale_values;
1941 }
1942 }
1943 printf " Normalization factors: %s\n", join( q( ), @norms ) if $verbose;
1944  
1945 # merge the samples
1946 foreach my $seq_id (@seq_list) {
1947 foreach my $strand (qw(f r)) {
1948 next unless defined $files{$seq_id}{$strand};
1949 $pm->start and next;
1950 merge_bin_files(
1951 $seq_id, $strand,
1952 $seq_totals{$seq_id}{$strand},
1953 $files{$seq_id}{$strand}, \@norms
1954 );
1955 $pm->finish;
1956 }
1957 }
1958 $pm->wait_all_children;
1959  
1960 if ($verbose) {
1961 printf " Finished merging%s in %.3f minutes\n",
1962 defined $norms[0] ? ' and normalizing' : q(),
1963 ( time - $start_time ) / 60;
1964 }
1965 }
1966  
1967 # otherwise we just normalize
1968 else {
1969 # determine scaling factor
1970 my $scale_factor = 1;
1971 if ($rpm) {
1972 printf " Normalizing depth based on %s total counted $items\n",
1973 format_with_commas( $totals[0] );
1974 $scale_factor = 1_000_000 / $totals[0];
1975 }
1976 if ( scalar @scale_values ) {
1977  
1978 # user supplied scaling factor
1979 print " Scaling depth with user-supplied factor\n";
1980 $scale_factor *= $scale_values[0];
1981 }
1982  
1983 # normalize the wig files
1984 foreach my $seq_id (@seq_list) {
1985 foreach my $strand (qw(f r)) {
1986 next unless defined $files{$seq_id}{$strand};
1987 $pm->start and next;
1988 normalize_bin_file( $files{$seq_id}{$strand}{0},
1989 $scale_factor, $seq_id );
1990 $pm->finish;
1991 }
1992 }
1993 $pm->wait_all_children;
1994 }
1995 }
1996  
1997 # write final wig file
1998 print " Merging temporary files\n";
1999 return write_final_wig_file();
2000 }
2001  
2002 sub process_alignments_on_chromosome {
2003 my ( $samid, $sam, $seq_id, $do_temp_bin ) = @_;
2004 my $chr_start_time = time;
2005  
2006 # identify chromosome target id
2007 my ( $tid, undef, undef ) = $sam->header->parse_region($seq_id);
2008 unless ( defined $tid ) {
2009 printf " WARNING: unable to parse target id for '%s' from bam file %s!\n",
2010 $seq_id, $bamfiles[$samid];
2011  
2012 # we continue but this will silently fail the low level fetch below
2013 # but at least an empty temp file will be written allowing program to finish
2014 }
2015 my $seq_length = $seq_name2length{$seq_id};
2016  
2017 # generate data structure for callback
2018 my $data = {
2019 f => [],
2020 r => [],
2021 fpack => q(),
2022 rpack => q(),
2023 f_offset => 0,
2024 r_offset => 0,
2025 pair => {},
2026 exclusion => undef,
2027 f_count => 0,
2028 r_count => 0,
2029 sam => $sam,
2030 score => 1,
2031 };
2032  
2033 # chromosome specific normalization
2034 if ( $chrapply and $seq_id =~ /$chrapply/i ) {
2035 $data->{score} = $chrnorm;
2036 }
2037  
2038 # process exclusion lists for this chromosome
2039 # since we're using external interval tree module that is not fork-safe, must
2040 # recreate interval tree each time
2041 if ( $exclude_hash and scalar @{ $exclude_hash->{$seq_id} } ) {
2042 my $tree = Set::IntervalTree->new;
2043 foreach ( @{ $exclude_hash->{$seq_id} } ) {
2044  
2045 # don't need to insert any particular value, just want the interval
2046 $tree->insert( 1, $_->[0], $_->[1] );
2047 }
2048 $data->{exclusion} = $tree;
2049 }
2050  
2051 # Process alignments on this chromosome
2052 low_level_bam_fetch( $sam, $tid, 0, $seq_length, $main_callback, $data );
2053  
2054 # pack remaining data
2055 my $fdiff = int( $seq_length / $bin_size ) - $data->{f_offset};
2056 $data->{fpack} .= pack( "$binpack$fdiff", @{ $data->{f} } );
2057 if ($do_strand) {
2058 my $rdiff = int( $seq_length / $bin_size ) - $data->{r_offset};
2059 $data->{rpack} .= pack( "$binpack$rdiff", @{ $data->{r} } );
2060 }
2061  
2062 # round the final count to a solid integer as necessary
2063 if ($multi_hit_scale) {
2064 $data->{f_count} = sprintf( "%.0f", $data->{f_count} );
2065 $data->{r_count} = sprintf( "%.0f", $data->{r_count} ) if $do_strand;
2066 }
2067  
2068 # write out file
2069 # we always write the forward strand, and reverse strand if stranded data
2070 if ($do_temp_bin) {
2071  
2072 # write a temporary binary file for merging later
2073 write_bin_file( \$data->{fpack},
2074 join( '.', $outbase, $samid, $seq_id, $data->{f_count}, 'f', 'temp.bin' )
2075 );
2076 write_bin_file( \$data->{rpack},
2077 join( '.', $outbase, $samid, $seq_id, $data->{r_count}, 'r', 'temp.bin' )
2078 ) if $do_strand;
2079 }
2080 else {
2081 # write a chromosome specific wig file
2082 &{$wig_writer}(
2083 \$data->{fpack}, $binpack, $seq_id, $seq_length,
2084 join( '.', $outbase, $samid, $seq_id, $data->{f_count}, 'f', 'temp.wig' )
2085 );
2086 &{$wig_writer}(
2087 \$data->{rpack}, $binpack, $seq_id, $seq_length,
2088 join( '.', $outbase, $samid, $seq_id, $data->{r_count}, 'r', 'temp.wig' )
2089 ) if $do_strand;
2090 }
2091  
2092 # verbose status line
2093 if ($verbose) {
2094 printf " Converted %s $items on $seq_id in %d seconds\n",
2095 format_with_commas( $data->{f_count} + $data->{r_count} ),
2096 time - $chr_start_time;
2097 if ( $chrapply and $seq_id =~ /$chrapply/i ) {
2098 printf " Scaled counts by $chrnorm\n";
2099 }
2100 if ( $paired and keys %{ $data->{pair} } ) {
2101 printf " %d orphan paired alignments were left behind and not counted!\n",
2102 scalar keys %{ $data->{pair} };
2103 }
2104 }
2105 }
2106  
2107 sub write_bin_file {
2108 my ( $data, $filename ) = @_;
2109  
2110 # note that $data is a reference
2111 my $fh = Bio::ToolBox->write_file($filename)
2112 or die " unable to write temporary file '$filename'!\n";
2113 $fh->binmode;
2114 $fh->print( ${$data} );
2115 $fh->close;
2116 }
2117  
2118 sub merge_bin_files {
2119 my ( $seq_id, $strand, $total, $files, $norm_factors ) = @_;
2120 my $merge_start_time = time;
2121 my $long_window = 100 * $window;
2122 my $seq_bin_length = int( $seq_name2length{$seq_id} / $bin_size );
2123  
2124 # open filehandles to each binary file
2125 my %fhs;
2126 foreach my $samid ( keys %{$files} ) {
2127 my $fh = Bio::ToolBox->read_file( $files->{$samid} )
2128 or die sprintf " unable to read temporary file %s!\n", $files->{$samid};
2129 $fh->binmode;
2130 $fhs{$samid} = $fh;
2131 }
2132 my $first_norm = $norm_factors->[0] || undef;
2133  
2134 # march along chromosome in defined windows to keep memory usage down
2135 # apply normalization as data is loaded into the combined chrom_data array
2136 my $chrom_data;
2137 for ( my $pos = 0; $pos < $seq_bin_length; $pos += $long_window ) {
2138  
2139 # check length
2140 my $len =
2141 ( $pos + $window ) > $seq_bin_length
2142 ? ( $seq_bin_length - $pos )
2143 : $long_window;
2144 my $binary_len = $len * $buflength;
2145  
2146 # collect the data from the first file handle
2147 my @win_data;
2148 if ( defined $first_norm ) {
2149 $fhs{0}->read( my $string, $binary_len );
2150 @win_data = map { $_ * $first_norm } unpack( "$binpack*", $string );
2151 }
2152 else {
2153 $fhs{0}->read( my $string, $binary_len );
2154 @win_data = unpack( "$binpack*", $string );
2155 }
2156  
2157 # add to the current window the remaining filehandle data
2158 foreach my $samid ( 1 .. $#sams ) {
2159 my $norm = $norm_factors->[$samid] || undef;
2160  
2161 # read and unpack current section from binary file
2162 $fhs{$samid}->read( my $string, $binary_len );
2163 if ( defined $norm ) {
2164 my @data = unpack( "$binpack*", $string );
2165 for my $i ( 0 .. $#data ) {
2166 $win_data[$i] += ( $data[$i] * $norm ) if $data[$i];
2167 }
2168 }
2169 else {
2170 my @data = unpack( "$binpack*", $string );
2171 for my $i ( 0 .. $#data ) {
2172 $win_data[$i] += $data[$i] if $data[$i];
2173 }
2174 }
2175 }
2176  
2177 # final pack
2178 $chrom_data .= pack( "f$len", @win_data );
2179 }
2180  
2181 # clean up
2182 foreach my $samid ( keys %fhs ) {
2183 $fhs{$samid}->close;
2184 unlink $files->{$samid};
2185 }
2186  
2187 # now rewrite the merged bin file
2188 &$wig_writer(
2189 \$chrom_data, 'f', $seq_id,
2190 $seq_name2length{$seq_id},
2191 join( '.', $outbase, '0', $seq_id, $total, $strand, 'temp.wig' )
2192 );
2193 if ($verbose) {
2194 printf " Merged%s $seq_id temp files in %d seconds\n",
2195 defined $norm_factors->[0] ? ' and normalized' : q(),
2196 time - $merge_start_time;
2197 }
2198 }
2199  
2200 sub normalize_bin_file {
2201 my ( $file, $scale_factor, $seq_id ) = @_;
2202 my $norm_start_time = time;
2203 my $seq_bin_length = int( $seq_name2length{$seq_id} / $bin_size );
2204 my $long_window = 10 * $window;
2205  
2206 # open file
2207 my $fh = Bio::ToolBox->read_file($file)
2208 or die " unable to read temporary $file!\n";
2209 $fh->binmode;
2210  
2211 # march along chromosome in defined windows to keep memory usage down
2212 # apply normalization as data is loaded into the combined chrom_data array
2213 my $chrom_data;
2214 for ( my $pos = 0; $pos < $seq_bin_length; $pos += $long_window ) {
2215  
2216 # check length
2217 my $len =
2218 ( $pos + $long_window ) > $seq_bin_length
2219 ? ( $seq_bin_length - $pos )
2220 : $long_window;
2221  
2222 # read, unpack, normalize, and re-pack current window from binary file
2223 my $string;
2224 $fh->read( $string, $len * $buflength );
2225 $chrom_data .=
2226 pack( "f*", map { $_ * $scale_factor } unpack( "$binpack*", $string ) );
2227 }
2228  
2229 # finish
2230 $fh->close;
2231 unlink $file;
2232  
2233 # now write the wig file
2234 $file =~ s/\.bin$/.wig/;
2235 &{$wig_writer}( \$chrom_data, 'f', $seq_id, $seq_name2length{$seq_id}, $file );
2236 if ($verbose) {
2237 printf " Scaled $seq_id temp file in %d seconds\n", time - $norm_start_time;
2238 }
2239 }
2240  
2241 sub write_final_wig_file {
2242  
2243 # find children files
2244 my @filelist = glob("$outbase.*.temp.wig");
2245 my $expected = scalar(@seq_list) * ( $do_strand ? 2 : 1 );
2246 if ( scalar(@filelist) != $expected ) {
2247 die sprintf(
2248 " unable to find all the children wig files! Only found %d, expected %d\n",
2249 scalar(@filelist), $expected );
2250 }
2251  
2252 # assemble into a hash
2253 my %files;
2254 my $f_total = 0;
2255 my $r_total = 0;
2256 foreach my $file (@filelist) {
2257  
2258 # each file name is basename.samid.seqid.count.strand.temp.wig
2259 if ( $file =~ /$outbase \.\d+ \.(.+) \.(\d+) \.([fr]) \.temp \.wig \Z/x ) {
2260 my $seq_id = $1;
2261 my $total = $2;
2262 my $strand = $3;
2263 $files{$seq_id}{$strand} = $file;
2264 $f_total += $total if $strand eq 'f';
2265 $r_total += $total if $strand eq 'r';
2266 }
2267 }
2268  
2269 # put into sorted or original order
2270 my ( @f_filelist, @r_filelist );
2271 if ($bigwig) {
2272  
2273 # UCSC utilities can be very particular about chromosome sort order
2274 @f_filelist = map { $files{$_}{f} } sort { $a cmp $b } @seq_list;
2275 @r_filelist = map { $files{$_}{r} } sort { $a cmp $b } @seq_list;
2276 }
2277 else {
2278 @f_filelist = map { $files{$_}{f} } @seq_list;
2279 @r_filelist = map { $files{$_}{r} } @seq_list;
2280 }
2281  
2282 # print total alignment summaries
2283 if ( $r_total and $flip ) {
2284 printf " %s total forward $items\n", format_with_commas($r_total);
2285 printf " %s total reverse $items\n", format_with_commas($f_total);
2286 }
2287 elsif ($r_total) {
2288 printf " %s total forward $items\n", format_with_commas($f_total);
2289 printf " %s total reverse $items\n", format_with_commas($r_total);
2290 }
2291 else {
2292 printf " %s total $items\n", format_with_commas($f_total);
2293 }
2294  
2295 if ( $bigwig and not $chromo_file ) {
2296 $chromo_file = generate_chromosome_file( $sams[0], $chr_exclude );
2297 }
2298  
2299 # write wig files with the appropriate wig writer
2300 if ( $do_strand and not $flip ) {
2301  
2302 if ( $cpu > 1 ) {
2303  
2304 # we can fork this!!!!
2305 my $pm = Parallel::ForkManager->new(2);
2306 for my $i ( 1 .. 2 ) {
2307 $pm->start and next;
2308 merge_wig_files( "$outfile\_f", @f_filelist ) if $i == 1;
2309 merge_wig_files( "$outfile\_r", @r_filelist ) if $i == 2;
2310 $pm->finish;
2311 }
2312 $pm->wait_all_children;
2313 }
2314 else {
2315 merge_wig_files( "$outfile\_f", @f_filelist );
2316 merge_wig_files( "$outfile\_r", @r_filelist );
2317 }
2318 }
2319 elsif ( $do_strand and $flip ) {
2320 if ( $cpu > 1 ) {
2321  
2322 # we can fork this!!!!
2323 my $pm = Parallel::ForkManager->new(2);
2324 for my $i ( 1 .. 2 ) {
2325 $pm->start and next;
2326 merge_wig_files( "$outfile\_r", @f_filelist ) if $i == 1;
2327 merge_wig_files( "$outfile\_f", @r_filelist ) if $i == 2;
2328 $pm->finish;
2329 }
2330 $pm->wait_all_children;
2331 }
2332 else {
2333 merge_wig_files( "$outfile\_r", @f_filelist );
2334 merge_wig_files( "$outfile\_f", @r_filelist );
2335 }
2336 }
2337 else {
2338 merge_wig_files( $outfile, @f_filelist );
2339 }
2340  
2341 # clean up
2342 unlink $chromo_file if $chromo_file;
2343 }
2344  
2345 sub write_bedgraph {
2346 my ( $data, $packer, $seq_id, $seq_length, $filename ) = @_;
2347  
2348 # note that $data is a reference
2349  
2350 # set the printf formatter for decimal or integer
2351 my $formatter =
2352 length($dec_precison)
2353 ? "$seq_id\t%d\t%d\t%." . $dec_precison . "f\n"
2354 : "$seq_id\t%d\t%d\t%s\n";
2355  
2356 # work though chromosome
2357 my $seq_bin_length = int( $seq_length / $bin_size );
2358 my $out_string;
2359 my $cpos = 0; # current position
2360 my $lpos = 0; # last position
2361 my $cval = 0; # current value
2362 for ( my $pos = 0; $pos < $seq_bin_length; $pos += $window ) {
2363  
2364 # check length
2365 my $len =
2366 ( $pos + $window ) > $seq_bin_length ? ( $seq_bin_length - $pos ) : $window;
2367  
2368 # unpack current window from the passed binary string
2369 my @win_data =
2370 unpack( "$packer*",
2371 substr( ${$data}, $pos * $buflength, $len * $buflength ) );
2372  
2373 # work through current window
2374 foreach my $value (@win_data) {
2375 if ( $value == $cval ) {
2376 $cpos++;
2377 }
2378 else {
2379 my $end = $cpos * $bin_size;
2380 $end = $seq_length if $end > $seq_length;
2381 if ( $no_zero and $cval == 0 ) {
2382  
2383 # we will skip the nonzero intervals
2384 # do nothing here
2385 }
2386 else {
2387 $out_string .= sprintf( $formatter, $lpos * $bin_size, $end, $cval )
2388 if $end; # this avoids writing nonexistent start 0 end 0 lines
2389 }
2390 $lpos = $cpos;
2391 $cval = $value;
2392 $cpos++;
2393 }
2394 }
2395 }
2396  
2397 # final write
2398 if ( $cpos > $lpos ) {
2399 my $end = $cpos * $bin_size;
2400 $end = $seq_length if $end != $seq_length;
2401 $out_string .= sprintf( $formatter, $lpos * $bin_size, $end, $cval );
2402 }
2403  
2404 # write wig file
2405 my $outfh;
2406 ( $filename, $outfh ) = open_wig_file( $filename, 0 );
2407 $outfh->print($out_string);
2408 $outfh->close;
2409 }
2410  
2411 sub write_fixstep {
2412 my ( $data, $packer, $seq_id, $seq_length, $filename ) = @_;
2413  
2414 # note that $data is a reference
2415  
2416 # set the printf formatter for decimal or integer
2417 my $formatter = length($dec_precison) ? "%." . $dec_precison . "f\n" : "%s\n";
2418  
2419 # write fixStep header
2420 my $out_string = "fixedStep chrom=$seq_id start=1 step=$bin_size span=$bin_size\n";
2421  
2422 # work though chromosome
2423 my $seq_bin_length = int( $seq_length / $bin_size );
2424 for ( my $pos = 0; $pos < $seq_bin_length; $pos += $window ) {
2425  
2426 # check length
2427 my $len =
2428 ( $pos + $window ) > $seq_bin_length ? ( $seq_bin_length - $pos ) : $window;
2429  
2430 # unpack current window from the passed binary string
2431 my @win_data =
2432 unpack( "$packer*",
2433 substr( ${$data}, $pos * $buflength, $len * $buflength ) );
2434  
2435 # work through current window
2436 foreach my $value (@win_data) {
2437 $out_string .= sprintf( $formatter, $value );
2438 }
2439 }
2440  
2441 # write wig file
2442 my $outfh;
2443 ( $filename, $outfh ) = open_wig_file( $filename, 0 );
2444 $outfh->print($out_string);
2445 $outfh->close;
2446 }
2447  
2448 sub write_varstep {
2449 my ( $data, $packer, $seq_id, $seq_length, $filename ) = @_;
2450  
2451 # note that $data is a reference
2452  
2453 # set the printf formatter for decimal or integer
2454 my $formatter = length($dec_precison) ? "%d\t%." . $dec_precison . "f\n" : "%d\t%s\n";
2455  
2456 # write fixStep header
2457 # we are only supporting bin_size of 1 bp for varStep
2458 my $out_string = "variableStep chrom=$seq_id\n";
2459  
2460 # work though chromosome
2461 for ( my $pos = 0; $pos < $seq_length; $pos += $window ) {
2462  
2463 # check length
2464 my $len = ( $pos + $window ) > $seq_length ? ( $seq_length - $pos ) : $window;
2465  
2466 # unpack current window from the passed binary string
2467 my @win_data =
2468 unpack( "$packer*",
2469 substr( ${$data}, $pos * $buflength, $len * $buflength ) );
2470  
2471 # work through current window
2472 for ( my $i = 0; $i <= $#win_data; $i++ ) {
2473 next unless $win_data[$i]; # should be a non-zero value
2474 $out_string .= sprintf( $formatter, $i + $pos + 1, $win_data[$i] );
2475 }
2476 }
2477  
2478 # write wig file
2479 my $outfh;
2480 ( $filename, $outfh ) = open_wig_file( $filename, 0 );
2481 $outfh->print($out_string);
2482 $outfh->close;
2483 }
2484  
2485 sub merge_wig_files {
2486 my ( $ofile, @files ) = @_;
2487  
2488 my ( $filename1, $fh ) = open_wig_file( $ofile, 1 );
2489 while (@files) {
2490 my $file = shift @files;
2491 my $in = Bio::ToolBox->read_file($file);
2492 unless ($in) {
2493 warn
2494 "one or more sub-process forks failed! Check your parameters and input file.\nAttempting to clean up\n";
2495 foreach (@files) { unlink; }
2496 unlink $chromo_file if $chromo_file;
2497 exit 1;
2498 }
2499 while ( my $l = $in->getline ) {
2500 $fh->print($l);
2501 }
2502 $in->close;
2503 unlink $file;
2504 }
2505 $fh->close;
2506  
2507 # convert using external utility if necessary
2508 if ( $bigwig and $post_bw_convert ) {
2509  
2510 my $final_bw = wig_to_bigwig_conversion(
2511 wig => $filename1,
2512 chromo => $chromo_file,
2513 bwapppath => $bwapp,
2514 );
2515 if ($final_bw) {
2516 print " Wrote file $final_bw\n";
2517 unlink $filename1;
2518 }
2519  
2520 # error message already printed if conversion had failed
2521 }
2522 else {
2523 print " Wrote file $filename1\n";
2524 }
2525 }
2526  
2527 sub se_callback {
2528 my ( $a, $data ) = @_;
2529  
2530 # check alignment flags and quality
2531 my $flag = $a->flag;
2532 return if ( $flag & $unwanted_flags );
2533 return if ( $min_mapq and $a->qual < $min_mapq );
2534  
2535 # filter excluded regions
2536 if ( defined $data->{exclusion} ) {
2537 my $results = $data->{exclusion}->fetch( $a->pos, $a->calend );
2538 return if scalar @{$results};
2539 }
2540  
2541 # scale by number of hits
2542 my $score = $data->{score}; # probably 1, but may be chromosome scaled
2543 if ($multi_hit_scale) {
2544 my $nh = $a->aux_get('NH') || 1;
2545 if ( $nh > 1 ) {
2546 $score /= $nh;
2547 }
2548 }
2549  
2550 # always record one alignment regardless of multiple hit status
2551 if ( $do_strand and $a->reversed ) {
2552 $data->{r_count} += 1;
2553 }
2554 else {
2555 $data->{f_count} += 1;
2556 }
2557  
2558 # pass on to appropriate callback
2559 if ( $splice and $a->cigar_str =~ /N/ ) {
2560  
2561 # check for splices
2562 se_spliced_callback( $a, $data, $score );
2563 }
2564 else {
2565 &{$callback}( $a, $data, $score );
2566 }
2567  
2568 # check data size
2569 if ( scalar( @{ $data->{f} } ) > 1_000_000 ) {
2570 $data->{fpack} .= pack( "$binpack*", splice( @{ $data->{f} }, 0, 500_000 ) );
2571 $data->{f_offset} += 500_000;
2572 }
2573 if ( scalar( @{ $data->{r} } ) > 1_000_000 ) {
2574 $data->{rpack} .= pack( "$binpack*", splice( @{ $data->{r} }, 0, 500_000 ) );
2575 $data->{r_offset} += 500_000;
2576 }
2577 }
2578  
2579 sub fast_pe_callback {
2580 my ( $a, $data ) = @_;
2581  
2582 # check alignment flags and quality
2583 my $flag = $a->flag;
2584 return if ( $flag & $unwanted_flags );
2585 return if ( $min_mapq and $a->qual < $min_mapq );
2586  
2587 # check paired status
2588 return unless $a->proper_pair; # both alignments are mapped
2589 return if $a->reversed; # only look at forward alignments, that's why it's fast
2590 return if $a->tid != $a->mtid; # same chromosome
2591  
2592 # check insertion size
2593 my $isize = abs( $a->isize );
2594 return if $isize > $max_isize;
2595 return if $isize < $min_isize;
2596  
2597 # filter excluded regions
2598 if ( $data->{exclusion} ) {
2599 my $results = $data->{exclusion}->fetch( $a->pos, $a->pos + $isize );
2600 return if scalar @{$results};
2601 }
2602  
2603 # scale by number of hits
2604 my $score = $data->{score}; # probably 1, but may be chromosome scaled
2605 if ($multi_hit_scale) {
2606 my $nh = $a->aux_get('NH') || 1;
2607 if ( $nh > 1 ) {
2608 $score /= $nh;
2609 }
2610 }
2611  
2612 # always record one alignment regardless of multiple hit status
2613 if ( $do_strand and $flag & 0x80 ) {
2614  
2615 # this alignment is forward and second mate, so must be reverse strand
2616 $data->{r_count} += 1;
2617 }
2618 else {
2619 # otherwise this forward alignment must be first mate
2620 # or unstranded analysis defaults to forward strand
2621 $data->{f_count} += 1;
2622 }
2623  
2624 # record based on the forward read
2625 &{$callback}( $a, $data, $score );
2626  
2627 # check data size
2628 if ( scalar( @{ $data->{f} } ) > 1_000_000 ) {
2629 $data->{fpack} .= pack( "$binpack*", splice( @{ $data->{f} }, 0, 500_000 ) );
2630 $data->{f_offset} += 500_000;
2631 }
2632 if ( scalar( @{ $data->{r} } ) > 1_000_000 ) {
2633 $data->{rpack} .= pack( "$binpack*", splice( @{ $data->{r} }, 0, 500_000 ) );
2634 $data->{r_offset} += 500_000;
2635 }
2636 }
2637  
2638 sub pe_callback {
2639 my ( $a, $data ) = @_;
2640  
2641 # check alignment flags and quality
2642 my $flag = $a->flag;
2643 return if ( $flag & $unwanted_flags );
2644 return if ( $min_mapq and $a->qual < $min_mapq );
2645  
2646 # check paired status
2647 return unless $a->proper_pair; # both alignments are mapped
2648 return if $a->tid != $a->mtid; # same chromosome
2649  
2650 # check insertion size
2651 my $isize = $a->isize;
2652 if ( $a->reversed ) {
2653  
2654 # in proper FR pairs reverse alignments are negative
2655 return if $isize > 0; # pair is RF orientation
2656 $isize = abs($isize);
2657 }
2658 return if $isize > $max_isize;
2659 return if $isize < $min_isize;
2660  
2661 # filter excluded regions
2662 if ( $data->{exclusion} ) {
2663 my $results;
2664 if ( $a->reversed ) {
2665 $results = $data->{exclusion}->fetch( $a->calend - $isize, $a->calend );
2666 }
2667 else {
2668 $results = $data->{exclusion}->fetch( $a->pos, $a->pos + $isize );
2669 }
2670 return if scalar @{$results};
2671 }
2672  
2673 # look for pair
2674 if ( $a->reversed ) {
2675  
2676 # since we look for FR pairs, the F read should already be found
2677 my $f = $data->{pair}->{ $a->qname } or return;
2678 delete $data->{pair}->{ $a->qname };
2679  
2680 # scale by number of hits
2681 my $score = $data->{score}; # probably 1, but may be chromosome scaled
2682 if ($multi_hit_scale) {
2683 my $r_nh = $a->aux_get('NH') || 1;
2684 my $f_nh = $f->aux_get('NH') || 1;
2685  
2686 # use the lowest number of hits reported for either alignment
2687 if ( $f_nh <= $r_nh ) {
2688 $score /= $f_nh if $f_nh > 1;
2689 }
2690 else {
2691 $score /= $r_nh if $r_nh > 1;
2692 }
2693 }
2694  
2695 # always record one alignment regardless of multiple hit status
2696 if ( $do_strand and $flag & 0x40 ) {
2697  
2698 # this alignment is reverse and first mate, so must be reverse strand
2699 $data->{r_count} += 1;
2700 }
2701 else {
2702 # otherwise this reverse alignment is second mate
2703 # or unstranded analysis defaults to forward strand
2704 $data->{f_count} += 1;
2705 }
2706  
2707 # record based primarily on the forward read, but pass reverse read at end
2708 # for use in smart pairing
2709 &{$callback}( $f, $data, $score, $a );
2710 }
2711 else {
2712 # store until we find it's mate
2713 $data->{pair}->{ $a->qname } = $a;
2714 }
2715  
2716 # check data size
2717 if ( scalar( @{ $data->{f} } ) > 1_000_000 ) {
2718 $data->{fpack} .= pack( "$binpack*", splice( @{ $data->{f} }, 0, 500_000 ) );
2719 $data->{f_offset} += 500_000;
2720 }
2721 if ( scalar( @{ $data->{r} } ) > 1_000_000 ) {
2722 $data->{rpack} .= pack( "$binpack*", splice( @{ $data->{r} }, 0, 500_000 ) );
2723 $data->{r_offset} += 500_000;
2724 }
2725 }
2726  
2727 sub se_spliced_callback {
2728 my ( $a, $data, $score ) = @_;
2729 my $aw = $wrapper_ref->new( $a, $data->{sam} );
2730  
2731 # check intron size from the cigar string
2732 if ($max_intron) {
2733 my $size = 1;
2734 my $cigars = $aw->cigar_array;
2735 foreach my $c ( @{$cigars} ) {
2736  
2737 # each element is [operation, size]
2738 $size = $c->[1] if ( $c->[0] eq 'N' and $c->[1] > $size );
2739 }
2740 return if $size > $max_intron; # exceed maximum intron size
2741 }
2742  
2743 # get exon segments
2744 my @segments = $aw->get_SeqFeatures;
2745  
2746 # adjust score
2747 if ($splice_scale) {
2748 $score /= scalar(@segments);
2749 }
2750  
2751 # record
2752 if ($use_start) {
2753 foreach my $segment (@segments) {
2754 if ( $do_strand and $a->reversed ) {
2755  
2756 # reverse strand
2757 my $pos = int( $segment->end / $bin_size );
2758 $data->{r}->[ $pos - $data->{r_offset} ] += $score;
2759 }
2760 else {
2761 # otherwise forward strand
2762 my $pos = int( ( $segment->start - 1 ) / $bin_size );
2763 $data->{f}->[ $pos - $data->{f_offset} ] += $score;
2764 }
2765 }
2766 }
2767 elsif ($use_span) {
2768 foreach my $segment (@segments) {
2769 my $start = int( ( $segment->start - 1 ) / $bin_size );
2770 my $end = int( ( $segment->end - 1 ) / $bin_size );
2771 if ( $do_strand and $a->reversed ) {
2772  
2773 # reverse strand
2774 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
2775 $data->{r}->[$_] += $score;
2776 }
2777 }
2778 else {
2779 # otherwise forward strand
2780 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
2781 $data->{f}->[$_] += $score;
2782 }
2783 }
2784 }
2785 }
2786 }
2787  
2788 sub se_start {
2789 my ( $a, $data, $score ) = @_;
2790 if ( $a->reversed ) {
2791 $data->{f}->[ int( ( $a->calend - 1 ) / $bin_size ) - $data->{f_offset} ] +=
2792 $score;
2793 }
2794 else {
2795 $data->{f}->[ int( $a->pos / $bin_size ) - $data->{f_offset} ] += $score;
2796 }
2797 }
2798  
2799 sub se_shift_start {
2800 my ( $a, $data, $score ) = @_;
2801 if ( $a->reversed ) {
2802 my $pos = int( ( $a->calend - 1 - $shift_value ) / $bin_size );
2803 $data->{f}->[ $pos - $data->{f_offset} ] += $score if $pos >= 0;
2804 }
2805 else {
2806 my $pos = int( ( $a->pos + $shift_value ) / $bin_size );
2807 $data->{f}->[ $pos - $data->{f_offset} ] += $score if $pos >= 0;
2808 }
2809 }
2810  
2811 sub se_strand_start {
2812 my ( $a, $data, $score ) = @_;
2813 if ( $a->reversed ) {
2814 my $pos = int( ( $a->calend - 1 ) / $bin_size );
2815 $data->{r}->[ $pos - $data->{r_offset} ] += $score;
2816 }
2817 else {
2818 my $pos = int( $a->pos / $bin_size );
2819 $data->{f}->[ $a->pos - $data->{f_offset} ] += $score;
2820 }
2821 }
2822  
2823 sub se_shift_strand_start {
2824 my ( $a, $data, $score ) = @_;
2825 if ( $a->reversed ) {
2826 my $pos = int( ( $a->calend - 1 - $shift_value ) / $bin_size );
2827 $data->{r}->[ $pos - $data->{r_offset} ] += $score if $pos >= 0;
2828 }
2829 else {
2830 my $pos = int( ( $a->pos + $shift_value ) / $bin_size );
2831 $data->{f}->[ $pos - $data->{f_offset} ] += $score if $pos >= 0;
2832 }
2833 }
2834  
2835 sub se_mid {
2836 my ( $a, $data, $score ) = @_;
2837 my $pos = int( int( ( $a->pos + $a->calend - 1 ) / 2 ) / $bin_size );
2838 $data->{f}->[ $pos - $data->{f_offset} ] += $score;
2839 }
2840  
2841 sub se_shift_mid {
2842 my ( $a, $data, $score ) = @_;
2843 my $mid = int( ( $a->pos + $a->calend - 1 ) / 2 );
2844 if ( $a->reversed ) {
2845 my $pos = int( ( $mid - $shift_value ) / $bin_size );
2846 $data->{f}->[ $pos - $data->{f_offset} ] += $score if $pos >= 0;
2847 }
2848 else {
2849 my $pos = int( ( $mid + $shift_value ) / $bin_size );
2850 $data->{f}->[ $pos - $data->{f_offset} ] += $score if $pos >= 0;
2851 }
2852 }
2853  
2854 sub se_strand_mid {
2855 my ( $a, $data, $score ) = @_;
2856 my $pos = int( int( ( $a->pos + $a->calend - 1 ) / 2 ) / $bin_size );
2857 if ( $a->reversed ) {
2858 $data->{r}->[ $pos - $data->{r_offset} ] += $score;
2859 }
2860 else {
2861 $data->{f}->[ $pos - $data->{f_offset} ] += $score;
2862 }
2863 }
2864  
2865 sub se_shift_strand_mid {
2866 my ( $a, $data, $score ) = @_;
2867 my $mid = int( ( $a->pos + $a->calend - 1 ) / 2 );
2868 if ( $a->reversed ) {
2869 my $pos = int( ( $mid - $shift_value ) / $bin_size );
2870 $data->{r}->[ $pos - $data->{r_offset} ] += $score if $pos >= 0;
2871 }
2872 else {
2873 my $pos = int( ( $mid + $shift_value ) / $bin_size );
2874 $data->{f}->[ $pos - $data->{f_offset} ] += $score if $pos >= 0;
2875 }
2876 }
2877  
2878 sub se_span {
2879 my ( $a, $data, $score ) = @_;
2880 my $s = int( $a->pos / $bin_size ) - $data->{f_offset};
2881 my $e = int( ( $a->calend - 1 ) / $bin_size ) - $data->{f_offset};
2882 foreach ( $s .. $e ) {
2883 $data->{f}->[$_] += $score;
2884 }
2885 }
2886  
2887 sub se_strand_span {
2888 my ( $a, $data, $score ) = @_;
2889 my $s = int( $a->pos / $bin_size );
2890 my $e = int( ( $a->calend - 1 ) / $bin_size );
2891 if ( $a->reversed ) {
2892 foreach ( $s - $data->{r_offset} .. $e - $data->{r_offset} ) {
2893 $data->{r}->[$_] += $score;
2894 }
2895 }
2896 else {
2897 foreach ( $s - $data->{f_offset} .. $e - $data->{f_offset} ) {
2898 $data->{f}->[$_] += $score;
2899 }
2900 }
2901 }
2902  
2903 sub se_shift_span {
2904 my ( $a, $data, $score ) = @_;
2905 if ( $a->reversed ) {
2906 my $start = int( ( $a->pos - $shift_value ) / $bin_size );
2907 my $end = int( ( $a->calend - 1 - $shift_value ) / $bin_size );
2908 $start = 0 if $start < 0;
2909 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
2910 $data->{f}->[$_] += $score if $_ >= 0;
2911 }
2912 }
2913 else {
2914 my $start = int( ( $a->pos + $shift_value ) / $bin_size );
2915 my $end = int( ( $a->calend - 1 + $shift_value ) / $bin_size );
2916 $start = 0 if $start < 0;
2917 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
2918 $data->{f}->[$_] += $score;
2919 }
2920 }
2921 }
2922  
2923 sub se_shift_strand_span {
2924 my ( $a, $data, $score ) = @_;
2925 if ( $a->reversed ) {
2926 my $start = int( ( $a->pos - $shift_value ) / $bin_size );
2927 $start = 0 if $start < 0;
2928 my $end = int( ( $a->calend - 1 - $shift_value ) / $bin_size );
2929 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
2930 $data->{r}->[$_] += $score if $_ >= 0;
2931 }
2932 }
2933 else {
2934 my $start = int( ( $a->pos + $shift_value ) / $bin_size );
2935 my $end = int( ( $a->calend - 1 + $shift_value ) / $bin_size );
2936 $start = 0 if $start < 0;
2937 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
2938 $data->{f}->[$_] += $score;
2939 }
2940 }
2941 }
2942  
2943 sub se_center_span {
2944 my ( $a, $data, $score ) = @_;
2945 my $mid = int( ( $a->pos + $a->calend - 1 ) / 2 );
2946 my $start = $mid - $half_extend + 1;
2947 $start = 0 if $start < 0;
2948 $start = int( $start / $bin_size );
2949 my $end = int( ( $mid + $half_extend ) / $bin_size );
2950 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
2951 $data->{f}->[$_] += $score;
2952 }
2953 }
2954  
2955 sub se_strand_center_span {
2956 my ( $a, $data, $score ) = @_;
2957 my $mid = int( ( $a->pos + $a->calend - 1 ) / 2 );
2958 my $start = $mid - $half_extend + 1;
2959 $start = 0 if $start < 0;
2960 $start = int( $start / $bin_size );
2961 my $end = int( ( $mid + $half_extend ) / $bin_size );
2962 if ( $a->reversed ) {
2963 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
2964 $data->{r}->[$_] += $score;
2965 }
2966 }
2967 else {
2968 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
2969 $data->{f}->[$_] += $score;
2970 }
2971 }
2972 }
2973  
2974 sub se_shift_center_span {
2975 my ( $a, $data, $score ) = @_;
2976 my $mid = int( ( $a->pos + $a->calend - 1 ) / 2 );
2977 if ( $a->reversed ) {
2978 $mid -= $shift_value;
2979 }
2980 else {
2981 $mid += $shift_value;
2982 }
2983 my $start = $mid - $half_extend + 1;
2984 $start = 0 if $start < 0;
2985 $start = int( $start / $bin_size );
2986 my $end = int( ( $mid + $half_extend ) / $bin_size );
2987 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
2988 $data->{f}->[$_] += $score;
2989 }
2990 }
2991  
2992 sub se_shift_strand_center_span {
2993 my ( $a, $data, $score ) = @_;
2994 my $mid = int( ( $a->pos + $a->calend - 1 ) / 2 );
2995 if ( $a->reversed ) {
2996 $mid -= $shift_value;
2997 }
2998 else {
2999 $mid += $shift_value;
3000 }
3001 my $start = $mid - $half_extend + 1;
3002 $start = 0 if $start < 0;
3003 $start = int( $start / $bin_size );
3004 my $end = int( ( $mid + $half_extend ) / $bin_size );
3005 if ( $a->reversed ) {
3006 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
3007 $data->{r}->[$_] += $score;
3008 }
3009 }
3010 else {
3011 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3012 $data->{f}->[$_] += $score;
3013 }
3014 }
3015 }
3016  
3017 sub se_extend {
3018 my ( $a, $data, $score ) = @_;
3019 if ( $a->reversed ) {
3020 my $start = $a->calend - $extend_value;
3021 $start = 0 if $start < 0;
3022 $start = int( $start / $bin_size );
3023 my $end = int( ( $a->calend - 1 ) / $bin_size );
3024 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3025 $data->{f}->[$_] += $score;
3026 }
3027 }
3028 else {
3029 my $start = int( $a->pos / $bin_size );
3030 my $end = int( ( $a->pos + $extend_value - 1 ) / $bin_size );
3031 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3032 $data->{f}->[$_] += $score;
3033 }
3034 }
3035 }
3036  
3037 sub se_strand_extend {
3038 my ( $a, $data, $score ) = @_;
3039 if ( $a->reversed ) {
3040 my $start = $a->calend - $extend_value;
3041 $start = 0 if $start < 0;
3042 $start = int( $start / $bin_size );
3043 my $end = int( ( $a->calend - 1 ) / $bin_size );
3044 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
3045 $data->{r}->[$_] += $score;
3046 }
3047 }
3048 else {
3049 my $start = int( $a->pos / $bin_size );
3050 $start = 0 if $start < 0;
3051 my $end = int( ( $a->pos + $extend_value - 1 ) / $bin_size );
3052 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3053 $data->{f}->[$_] += $score;
3054 }
3055 }
3056 }
3057  
3058 sub se_shift_extend {
3059 my ( $a, $data, $score ) = @_;
3060 if ( $a->reversed ) {
3061 my $start = $a->calend - $shift_value - $extend_value;
3062 $start = 0 if $start < 0;
3063 $start = int( $start / $bin_size );
3064 my $end = int( ( $a->calend - 1 - $shift_value ) / $bin_size );
3065 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3066 $data->{f}->[$_] += $score;
3067 }
3068 }
3069 else {
3070 my $start = int( ( $a->pos + $shift_value ) / $bin_size );
3071 $start = 0 if $start < 0;
3072 my $end = int( ( $a->pos + $shift_value + $extend_value - 1 ) / $bin_size );
3073 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3074 $data->{f}->[$_] += $score;
3075 }
3076 }
3077 }
3078  
3079 sub se_shift_strand_extend {
3080 my ( $a, $data, $score ) = @_;
3081 if ( $a->reversed ) {
3082 my $start = $a->calend - $shift_value - $extend_value;
3083 $start = 0 if $start < 0;
3084 $start = int( $start / $bin_size );
3085 my $end = int( ( $a->calend - 1 - $shift_value ) / $bin_size );
3086 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
3087 $data->{r}->[$_] += $score;
3088 }
3089 }
3090 else {
3091 my $start = int( ( $a->pos + $shift_value ) / $bin_size );
3092 $start = 0 if $start < 0;
3093 my $end = int( ( $a->pos + $shift_value + $extend_value - 1 ) / $bin_size );
3094 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3095 $data->{f}->[$_] += $score;
3096 }
3097 }
3098 }
3099  
3100 sub pe_start {
3101 my ( $a, $data, $score ) = @_;
3102 my $flag = $a->flag;
3103  
3104 # we always receive the forward read, never reverse, from pe_callback
3105 # therefore the first and second read flag indicates orientation
3106 if ( $flag & 0x0040 ) {
3107  
3108 # first read implies forward orientation
3109 $data->{f}->[ int( $a->pos / $bin_size ) - $data->{f_offset} ] += $score;
3110 }
3111 elsif ( $flag & 0x0080 ) {
3112  
3113 # second read implies reverse orientation
3114 my $pos = int( ( $a->pos + $a->isize ) / $bin_size );
3115 $data->{f}->[ $pos - $data->{f_offset} ] += $score;
3116 }
3117 else {
3118 die sprintf(
3119 " Paired-end flags are set incorrectly; neither 0x040 or 0x080 are set for paired-end read %s.",
3120 $a->query->name );
3121 }
3122 }
3123  
3124 sub pe_strand_start {
3125 my ( $a, $data, $score ) = @_;
3126 my $flag = $a->flag;
3127  
3128 # we always receive the forward read, never reverse, from pe_callback
3129 # therefore the first and second read flag indicates orientation
3130 if ( $flag & 0x0040 ) {
3131  
3132 # first read implies forward orientation
3133 $data->{f}->[ int( $a->pos / $bin_size ) - $data->{f_offset} ] += $score;
3134 }
3135 elsif ( $flag & 0x0080 ) {
3136  
3137 # second read implies reverse orientation
3138 my $pos = int( ( $a->pos + $a->isize ) / $bin_size );
3139 $data->{r}->[ $pos - $data->{r_offset} ] += $score;
3140 }
3141 else {
3142 die sprintf(
3143 " Paired-end flags are set incorrectly; neither 0x040 or 0x080 are set for paired-end read %s.",
3144 $a->query->name );
3145 }
3146 }
3147  
3148 sub pe_mid {
3149 my ( $a, $data, $score ) = @_;
3150 my $mid = int( ( $a->pos + int( $a->isize / 2 ) ) / $bin_size );
3151 $data->{f}->[ $mid - $data->{f_offset} ] += $score;
3152 }
3153  
3154 sub pe_strand_mid {
3155 my ( $a, $data, $score ) = @_;
3156 my $mid = int( ( $a->pos + int( $a->isize / 2 ) ) / $bin_size );
3157 my $flag = $a->flag;
3158  
3159 # we always receive the forward read, never reverse, from pe_callback
3160 # therefore the first and second read flag indicates orientation
3161 if ( $flag & 0x0040 ) {
3162  
3163 # first read, forward
3164 $data->{f}->[ $mid - $data->{f_offset} ] += $score;
3165 }
3166 elsif ( $flag & 0x0080 ) {
3167  
3168 # second read, reverse
3169 $data->{r}->[ $mid - $data->{r_offset} ] += $score;
3170 }
3171 else {
3172 die sprintf(
3173 " Paired-end flags are set incorrectly; neither 0x040 or 0x080 are set for paired-end read %s.",
3174 $a->query->name );
3175 }
3176 }
3177  
3178 sub pe_span {
3179 my ( $a, $data, $score ) = @_;
3180 my $start = int( $a->pos / $bin_size );
3181 my $end = int( ( $a->pos + $a->isize ) / $bin_size );
3182 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3183 $data->{f}->[$_] += $score;
3184 }
3185 }
3186  
3187 sub pe_strand_span {
3188 my ( $a, $data, $score ) = @_;
3189 my $start = int( $a->pos / $bin_size );
3190 my $end = int( ( $a->pos + $a->isize ) / $bin_size );
3191 my $flag = $a->flag;
3192  
3193 # we always receive the forward read, never reverse, from pe_callback
3194 # therefore the first and second read flag indicates orientation
3195 if ( $flag & 0x0040 ) {
3196  
3197 # first read, forward
3198 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3199 $data->{f}->[$_] += $score;
3200 }
3201 }
3202 elsif ( $flag & 0x0080 ) {
3203  
3204 # second read, reverse
3205 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
3206 $data->{r}->[$_] += $score;
3207 }
3208 }
3209 else {
3210 die sprintf(
3211 " Paired-end flags are set incorrectly; neither 0x040 or 0x080 are set for paired-end read %s.",
3212 $a->query->name );
3213 }
3214 }
3215  
3216 sub pe_center_span {
3217 my ( $a, $data, $score ) = @_;
3218 my $center = $a->pos + int( $a->isize / 2 );
3219 my $start = int( ( $center - $half_extend ) / $bin_size );
3220 $start = 0 if $start < 0;
3221 my $end = int( ( $center + $half_extend ) / $bin_size );
3222 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3223 $data->{f}->[$_] += $score;
3224 }
3225 }
3226  
3227 sub pe_strand_center_span {
3228 my ( $a, $data, $score ) = @_;
3229 my $center = $a->pos + int( $a->isize / 2 );
3230 my $start = int( ( $center - $half_extend ) / $bin_size );
3231 $start = 0 if $start < 0;
3232 my $end = int( ( $center + $half_extend ) / $bin_size );
3233 my $flag = $a->flag;
3234  
3235 # we always receive the forward read, never reverse, from pe_callback
3236 # therefore the first and second read flag indicates orientation
3237 if ( $flag & 0x0040 ) {
3238  
3239 # first read, forward
3240 foreach ( $start - $data->{f_offset} .. $end - $data->{f_offset} ) {
3241 $data->{f}->[$_] += $score;
3242 }
3243 }
3244 elsif ( $flag & 0x0080 ) {
3245  
3246 # second read, reverse
3247 foreach ( $start - $data->{r_offset} .. $end - $data->{r_offset} ) {
3248 $data->{r}->[$_] += $score;
3249 }
3250 }
3251 else {
3252 die sprintf(
3253 " Paired-end flags are set incorrectly; neither 0x040 or 0x080 are set for paired-end read %s.",
3254 $a->query->name );
3255 }
3256 }
3257  
3258 sub smart_pe {
3259 my ( $f, $data, $score, $r ) = @_;
3260 my $set = Set::IntSpan::Fast->new;
3261  
3262 # process both reads, adding to the integer set
3263 foreach my $a ( $f, $r ) {
3264 if ( $a->cigar_str =~ /N/ ) {
3265 my $aw = $wrapper_ref->new( $a, $data->{sam} );
3266  
3267 # check intron size from the cigar string
3268 if ($max_intron) {
3269 my $size = 1;
3270 my $cigars = $aw->cigar_array;
3271 foreach my $c ( @{$cigars} ) {
3272  
3273 # each element is [operation, size]
3274 $size = $c->[1] if ( $c->[0] eq 'N' and $c->[1] > $size );
3275 }
3276 return if $size > $max_intron; # exceed maximum intron size
3277 }
3278  
3279 # record
3280 foreach my $segment ( $aw->get_SeqFeatures ) {
3281 $set->add_range(
3282 int( ( $segment->start - 1 ) / $bin_size ),
3283 int( ( $segment->end - 1 ) / $bin_size )
3284 );
3285 }
3286 }
3287 else {
3288 $set->add_range( int( $a->pos / $bin_size ),
3289 int( ( $a->calend - 1 ) / $bin_size ) );
3290 }
3291 }
3292  
3293 # record
3294 foreach my $pos ( $set->as_array ) {
3295 $data->{f}->[ $pos - $data->{f_offset} ] += $score;
3296 }
3297 }
3298  
3299 sub smart_stranded_pe {
3300 my ( $f, $data, $score, $r ) = @_;
3301 my $set = Set::IntSpan::Fast->new;
3302  
3303 # determine strand based on the forward alignment
3304 my ( $strand, $offset );
3305 my $flag = $f->flag;
3306 if ( $flag & 0x0040 ) {
3307  
3308 # it's the first read, therefore fragment is forward
3309 $strand = 'f';
3310 $offset = 'f_offset';
3311 }
3312 elsif ( $flag & 0x0080 ) {
3313  
3314 # it's the second read, therefore fragment is reverse
3315 $strand = 'r';
3316 $offset = 'r_offset';
3317 }
3318  
3319 # process both reads, adding to the integer set
3320 foreach my $a ( $f, $r ) {
3321 if ( $a->cigar_str =~ /N/ ) {
3322 my $aw = $wrapper_ref->new( $a, $data->{sam} );
3323  
3324 # check intron size from the cigar string
3325 if ($max_intron) {
3326 my $size = 1;
3327 my $cigars = $aw->cigar_array;
3328 foreach my $c ( @{$cigars} ) {
3329  
3330 # each element is [operation, size]
3331 $size = $c->[1] if ( $c->[0] eq 'N' and $c->[1] > $size );
3332 }
3333 return if $size > $max_intron; # exceed maximum intron size
3334 }
3335  
3336 # record
3337 foreach my $segment ( $aw->get_SeqFeatures ) {
3338 $set->add_range(
3339 int( ( $segment->start - 1 ) / $bin_size ),
3340 int( ( $segment->end - 1 ) / $bin_size )
3341 );
3342 }
3343 }
3344 else {
3345 $set->add_range( int( $a->pos / $bin_size ),
3346 int( ( $a->calend - 1 ) / $bin_size ) );
3347 }
3348 }
3349  
3350 # record
3351 foreach my $pos ( $set->as_array ) {
3352 $data->{$strand}->[ $pos - $data->{$offset} ] += $score;
3353 }
3354 }
3355  
3356 sub pe_ends {
3357 my ( $a, $data, $score ) = @_;
3358  
3359 # we always receive the forward read, never reverse, from pe_callback
3360  
3361 # first position
3362 $data->{f}->[ int( $a->pos / $bin_size ) - $data->{f_offset} ] += $score;
3363  
3364 # second position
3365 my $pos = int( ( $a->pos + $a->isize ) / $bin_size );
3366 $data->{f}->[ $pos - $data->{f_offset} ] += $score;
3367 }
3368  
3369 sub pe_strand_ends {
3370 my ( $a, $data, $score ) = @_;
3371  
3372 # we always receive the forward read, never reverse, from pe_callback
3373 # therefore the first and second read flag indicates orientation
3374  
3375 # calculate both positions
3376 my $flag = $a->flag;
3377 if ( $flag & 0x0040 ) {
3378  
3379 # first read implies forward orientation
3380 # first position is forward
3381 $data->{f}->[ int( $a->pos / $bin_size ) - $data->{f_offset} ] += $score;
3382  
3383 # second position is reverse
3384 my $pos = int( ( $a->pos + $a->isize ) / $bin_size );
3385 $data->{r}->[ $pos - $data->{r_offset} ] += $score;
3386 }
3387 elsif ( $flag & 0x0080 ) {
3388  
3389 # second read implies reverse orientation
3390 # first position is reverse
3391 $data->{r}->[ int( $a->pos / $bin_size ) - $data->{r_offset} ] += $score;
3392  
3393 # second position is forward
3394 my $pos = int( ( $a->pos + $a->isize ) / $bin_size );
3395 $data->{f}->[ $pos - $data->{f_offset} ] += $score;
3396 }
3397 else {
3398 die sprintf(
3399 " Paired-end flags are set incorrectly; neither 0x040 or 0x080 are set for paired-end read %s.",
3400 $a->query->name );
3401 }
3402 }
3403  
3404 __END__