script/get_binned_data.pl untested

filter: Statementstmt 0.0% 0 / 371 Branchbran 0.0% 0 / 158 Conditioncond 0.0% 0 / 126 MC/DCmcdc 0.0% 0 / 71 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 755 CC 58 SCAR 49.3
CC
58
Cov
0%
check_defaults
420.0
parallel_execution
90.0
collect_binned_long_data
72.0
CRAP 138.2
1 #!/usr/local/bin/perl
2  
3 # documentation at end of file
4  
5 use warnings;
6 use strict;
7 use English qw(-no_match_vars);
8 use Getopt::Long qw(:config no_ignore_case bundling);
9 use Pod::Usage;
10 use Scalar::Util qw(looks_like_number);
11 use Bio::ToolBox::Data;
12 use Bio::ToolBox::db_helper qw(
13 open_db_connection
14 verify_or_request_feature_types
15 calculate_score
16 use_minimum_mapq
17 $BAM_ADAPTER
18 $BIG_ADAPTER
19 );
20 use Bio::ToolBox::utility qw( format_with_commas simplify_dataset_name );
21 my $parallel;
22 eval {
23 # check for parallel support
24 require Parallel::ForkManager;
25 $parallel = 1;
26 };
27  
28 our $VERSION = '2.04';
29  
30 print "\n This script will collect binned values across features\n\n";
31  
32 ### Quick help
33 unless (@ARGV) { # when no command line options are present
34 # when no command line options are present
35 # print SYNOPSIS
36 pod2usage(
37 {
38 '-verbose' => 0,
39 '-exitval' => 1,
40 }
41 );
42 }
43  
44 ### Get command line options and initialize values
45  
46 ## Initialize values
47 my (
48 $infile, $parse, $outfile, $main_database,
49 $data_database, $feature, $subfeature, $exon_subfeature,
50 $method, $stranded, $bins, $extension,
51 $extension_size, $min_length, $long_data, $smooth,
52 $sum, $format, $groupcol, $gz,
53 $cpu, $help, $print_version, $mapq
54 ); # command line variables
55 my @datasets;
56  
57 ## Command line options
58 GetOptions(
59 'i|in=s' => \$infile, # input file
60 'parse!' => \$parse, # parse input file
61 'o|out=s' => \$outfile, # name of outfile
62 'd|db=s' => \$main_database, # main or annotation database name
63 'D|ddb=s' => \$data_database, # data database
64 'a|data=s' => \@datasets, # dataset name
65 'f|feature=s' => \$feature, # what type of feature to work with
66 'u|subfeature=s' => \$subfeature, # indicate to restrict to subfeatures
67 'exons!' => \$exon_subfeature, # old parameter
68 'm|method=s' => \$method, # method for collecting the data
69 't|strand=s' => \$stranded, # indicate whether stranded data should be taken
70 'b|bins=i' => \$bins, # number of bins
71 'x|ext=i' => \$extension, # number of bins to extend beyond the feature
72 'X|extsize=i' => \$extension_size, # explicit size of extended bins
73 'min=i' => \$min_length, # minimum feature size
74 'long!' => \$long_data, # collecting long data features
75 'smooth!' => \$smooth, # do not interpolate over missing values
76 'U|sum!' => \$sum, # determine a final average for all the features
77 'r|format=i' => \$format, # decimal formatting
78 'mapq=i' => \$mapq, # minimum map quality
79 'g|groups' => \$groupcol, # write group column file
80 'z|gz!' => \$gz, # compress the output file
81 'c|cpu=i' => \$cpu, # number of execution threads
82 'h|help' => \$help, # print the help
83 'v|version' => \$print_version, # print the version
84 'bam=s' => \$BAM_ADAPTER, # explicitly set the bam adapter
85 'big=s' => \$BIG_ADAPTER, # explicitly set the big adapter
86 ) or die " unrecognized option(s)!! please refer to the help documentation\n\n";
87  
88 # Print help
89 if ($help) {
90  
91 # print entire POD
92 pod2usage(
93 {
94 '-verbose' => 2,
95 '-exitval' => 1,
96 }
97 );
98 }
99  
100 # Print version
101 if ($print_version) {
102 print " Biotoolbox script get_binned_data.pl, version $VERSION\n";
103 eval {
104 require Bio::ToolBox;
105 my $v = Bio::ToolBox->VERSION;
106 print " Biotoolbox package version $v\n";
107 };
108 exit;
109 }
110  
111 ### Check for required values
112 my $formatter;
113 check_defaults();
114 my $start_time = time;
115 my $length_i; # global value for the merged transcript length
116  
117 ### Generate or load the dataset
118 my $Data;
119 if ($infile) {
120 $Data = Bio::ToolBox::Data->new(
121 file => $infile,
122 parse => $parse,
123 feature => $feature,
124 subfeature => $subfeature,
125 ) or die " unable to load input file '$infile'\n";
126 if ( $Data->last_row ) {
127 printf " Loaded %s features from $infile.\n",
128 format_with_commas( $Data->last_row );
129 }
130 else {
131 print STDERR " FATAL: No features loaded from file '$infile'!\n";
132 exit 1;
133 }
134  
135 # update main database as necessary
136 if ($main_database) {
137 if ( $main_database ne $Data->database ) {
138  
139 # update with new database
140 printf " updating main database name from '%s' to '%s'\n",
141 $Data->database, $main_database;
142 $Data->database($main_database);
143 }
144 }
145 elsif ( $Data->database ) {
146 $main_database = $Data->database if $Data->database !~ /^Parsed/;
147 }
148  
149 # update feature type as necessary
150 if ( not defined $Data->feature
151 and not defined $Data->type_column
152 and defined $feature )
153 {
154 $Data->feature($feature);
155 }
156  
157 # set headers to true if file was explicitly not parsed
158 # since warnings will occur when we add columns and write to a file
159 if ( $parse == 0 ) {
160 $Data->headers(1);
161 }
162 }
163 else {
164 # generate a new file
165 print " Generating a new feature list from database '$main_database'...\n";
166 $Data = Bio::ToolBox::Data->new(
167 db => $main_database,
168 feature => $feature,
169 ) or die " unable to generate new feature list\n";
170 }
171 $Data->program("$PROGRAM_NAME, v $VERSION");
172  
173 # the number of columns already in the data array
174 my $beginningcolumn = $Data->last_column + 1;
175 my $startcolumn; # this is now calculated separately for each datasets
176  
177 # Check output file name
178 unless ($outfile) {
179 if ( $Data->filename ) {
180  
181 # reuse the input filename and overwrite
182 $outfile = $Data->filename;
183 }
184 elsif ( $Data->basename ) {
185  
186 # no filename but a basename is indicative of a parsed file
187 # so stick a txt extension on it, and write in current directory
188 $outfile = sprintf "%s.txt", $Data->basename;
189 }
190 else {
191 print STDERR " FATAL: No output file provided!\n";
192 exit 1;
193 }
194 }
195  
196 # Open data database
197 my $ddb;
198 if ( defined $data_database ) {
199  
200 # specifically defined a data database
201 $ddb = open_db_connection($data_database)
202 or die "unable to establish data database connection to $data_database!\n";
203 }
204  
205 # Check for the dataset
206 @datasets = verify_or_request_feature_types(
207 'db' => $ddb || $Data->database,
208 'feature' => \@datasets,
209 'prompt' => " Enter the dataset(s) or feature type(s) from which \n"
210 . " to collect data. Comma delimited or range is acceptable\n",
211 );
212 unless (@datasets) {
213 die
214 " No verifiable dataset(s) provided. Check your file path, database, or dataset.\n";
215 }
216  
217 ## Collect the relative data
218 printf " Collecting $method data in %d bins from %s\n",
219 ( $bins + 2 * $extension ), join( ", ", @datasets );
220  
221 # check whether it is worth doing parallel execution
222 if ( $cpu > 1 and ( $Data->number_rows / $cpu ) < 100 ) {
223 while ( $cpu > 1 and ( $Data->number_rows / $cpu ) < 100 ) {
224  
225 # I figure we need at least 100 lines in each fork split to make
226 # it worthwhile to do the split, otherwise, reduce the number of
227 # splits to something more worthwhile
228 $cpu--;
229 }
230 print " Reducing number of process forks to $cpu due to number of input features\n";
231 }
232  
233 if ( $cpu > 1 ) {
234  
235 # parallel execution
236 print " Forking into $cpu children for parallel data collection...\n";
237 parallel_execution();
238 }
239  
240 else {
241 # single process execution
242 single_execution();
243 }
244  
245 ## Generate summed data -
246 # an average across all features at each position suitable for plotting
247 if ($sum) {
248 print " Generating trimmed-mean summary file....\n";
249 my $sumfile = $Data->summary_file(
250 'filename' => $outfile,
251 'dataset' => \@datasets,
252 'method' => 'trimmean'
253 );
254 if ($sumfile) {
255 print " Wrote summary file '$sumfile'\n";
256 }
257 else {
258 print " Unable to write summary file!\n";
259 }
260 }
261  
262 ## Write main output
263 my $written_file = $Data->save(
264 'filename' => $outfile,
265 'gz' => $gz,
266 );
267 if ($written_file) {
268 print " Wrote data file '$written_file'\n";
269 }
270 else {
271 print " unable to write data file!\n";
272 }
273  
274 # write the column group file
275 if ($groupcol) {
276 my $groupfile = $written_file;
277 $groupfile =~ s/\.txt (?:\.gz)? $/.col_groups.txt/x;
278 my $fh = Bio::ToolBox::Data->open_to_write_fh($groupfile);
279 $fh->print("Name\tDataset\n");
280 for my $i ( $beginningcolumn .. $Data->last_column ) {
281 my $name = $Data->name($i);
282 my $dataset = $name;
283 $dataset =~ s/: [\-\d%bp]+ $//x;
284 $fh->print("$name\t$dataset\n");
285 }
286 $fh->close;
287 print " wrote group column file $groupfile\n";
288 }
289  
290 printf " Completed in %.1f minutes\n", ( time - $start_time ) / 60;
291  
292 # done
293  
294 #### Subroutines #######
295  
296 sub check_defaults {
297 unless ( $main_database or $infile ) {
298  
299 # a database must be defined
300 # a tim data file used as an input file would also define one
301 print STDERR " FATAL: You must define a database or input file!\n";
302 exit 1;
303 }
304 $parse = 1 if ( $infile and not defined $parse );
305  
306 unless ( $outfile or $infile ) {
307 print STDERR
308 " FATAL: You must define an output filename !\n Use --help for more information\n";
309 exit 1;
310 }
311  
312 # check datasets
313 if ( not @datasets and @ARGV ) {
314 @datasets = @ARGV;
315 }
316 if ( @datasets and $datasets[0] =~ /,/ ) {
317  
318 # seems to be a comma delimited list, possibly more than one?????
319 my @list;
320 foreach my $d (@datasets) {
321 push @list, ( split /,/, $d );
322 }
323 @datasets = @list;
324 }
325  
326 # strand
327 if ($stranded) {
328 unless ( $stranded eq 'sense'
329 or $stranded eq 'antisense'
330 or $stranded eq 'all' )
331 {
332 print STDERR
333 " FATAL: '$stranded' is not recognized for strand\n Use --help for more information\n";
334 exit 1;
335 }
336 }
337 else {
338 $stranded = 'all'; # default is no strand information
339 }
340  
341 # method
342 if ( defined $method ) {
343 unless ( $method eq 'mean'
344 or $method eq 'median'
345 or $method eq 'sum'
346 or $method eq 'min'
347 or $method eq 'max'
348 or $method eq 'stddev'
349 or $method =~ /^\w?count/ )
350 {
351 print STDERR
352 " FATAL: '$method' is not recognized for method\n Use --help for more information\n";
353 exit 1;
354 }
355  
356 }
357 else {
358 $method = 'mean';
359 }
360  
361 # subfeatures
362 if ( $subfeature and $long_data ) {
363 print STDERR
364 " FATAL: Long data collection is incompatible with subfeatures\n Use --help for more information\n";
365 exit 1;
366 }
367 if ($exon_subfeature) {
368  
369 # legacy option
370 $subfeature = 'exon';
371 }
372 if ( $subfeature and $subfeature !~ /^ (?: exon | cds | 5p_utr | 3p_utr )$/x ) {
373 print STDERR
374 " FATAL: unrecognized subfeature option '$subfeature'! Use exon, cds, 5p_utr or 3p_utr\n";
375 exit 1;
376 }
377  
378 # assign default window bin values
379 unless ( defined $bins ) {
380  
381 # dividing gene into 10 (10%) bins seems reasonable to me
382 $bins = 10;
383 }
384 unless ( defined $extension ) {
385  
386 # default is no extension
387 $extension = 0;
388 }
389 unless ( defined $smooth ) {
390  
391 # default is to not include smoothing
392 $smooth = 0;
393 }
394  
395 # generate formatter
396 if ( defined $format ) {
397 $formatter = '%.' . $format . 'f';
398 }
399  
400 if ($parallel) {
401 $cpu ||= 4;
402 }
403 else {
404 # disable cores
405 print " disabling parallel CPU execution, no support present\n" if $cpu;
406 $cpu = 1;
407 }
408  
409 # set minimum alignment mapping quality
410 if ( $method =~ /count/ and $mapq ) {
411 use_minimum_mapq($mapq);
412 }
413 }
414  
415 ## Parallel execution for efficiency
416 sub parallel_execution {
417 my $pm = Parallel::ForkManager->new($cpu);
418  
419 # generate base name for child processes
420 my $child_base_name = $outfile . ".$PID";
421  
422 # Split the input data into parts and execute in parallel in separate forks
423 for my $i ( 1 .. $cpu ) {
424 $pm->start and next;
425  
426 #### In child ####
427  
428 # splice the data structure
429 $Data->split_data( $i, $cpu );
430  
431 # re-open database objects to make them clone safe
432 # pass second true to avoid cached database objects
433 my $db = $Data->open_database(1);
434 if ($data_database) {
435 $ddb = open_db_connection( $data_database, 1 );
436 }
437  
438 # collapse transcripts if needed
439 if ( $feature
440 and $feature =~ /gene/i
441 and $subfeature
442 and $subfeature =~ m/exon | intron/xi )
443 {
444 $Data->collapse_gene_transcripts;
445 }
446  
447 # calculate length if necessary
448 if ($subfeature) {
449 $length_i = $Data->add_transcript_length($subfeature);
450 }
451  
452 # work through each dataset
453 foreach my $dataset (@datasets) {
454  
455 # new start column for this dataset
456 $startcolumn = $Data->number_columns + 1;
457  
458 # Prepare the metadata and header names
459 my $binsize = ( 100 / $bins );
460 prepare_bins( $binsize, $dataset );
461  
462 # Collect the data
463 if ($long_data) {
464 collect_binned_long_data( $binsize, $dataset );
465 }
466 else {
467 collect_binned_data( $binsize, $dataset );
468 }
469  
470 # Interpolate values
471 if ($smooth) {
472 go_interpolate_values();
473 }
474 }
475  
476 # write out result
477 my $success = $Data->save(
478 'filename' => sprintf( "$child_base_name.%03s", $i ),
479 'gz' => 0, # faster to write without compression
480 );
481 if ($success) {
482 printf " wrote child file $success\n";
483 }
484 else {
485 # failure! the subroutine will have printed error messages
486 die " unable to write file!\n";
487  
488 # no need to continue
489 }
490  
491 # Finished
492 $pm->finish;
493 }
494 $pm->wait_all_children;
495  
496 # reassemble children files into output file
497 my @files = glob "$child_base_name.*";
498 unless (@files) {
499 die "unable to find children files!\n";
500 }
501 unless ( scalar @files == $cpu ) {
502 die "only found " . scalar(@files) . " child files when there should be $cpu!\n";
503 }
504 my $count = $Data->reload_children(@files);
505 printf " reloaded %s features from children\n", format_with_commas($count);
506 }
507  
508 ## Run in single thread
509 sub single_execution {
510  
511 # collapse transcripts if needed
512 if ( $feature
513 and $feature =~ /gene/i
514 and $subfeature
515 and $subfeature =~ m/exon | intron/xi )
516 {
517 $Data->collapse_gene_transcripts;
518 }
519  
520 # calculate length if necessary
521 if ($subfeature) {
522 $length_i = $Data->add_transcript_length($subfeature);
523 }
524  
525 # work through each dataset
526 foreach my $dataset (@datasets) {
527  
528 # new start column for this dataset
529 $startcolumn = $Data->number_columns + 1;
530  
531 # Prepare the metadata and header names
532 my $binsize = ( 100 / $bins );
533 prepare_bins( $binsize, $dataset );
534  
535 # Collect the data
536 if ($long_data) {
537 collect_binned_long_data( $binsize, $dataset );
538 }
539 else {
540 collect_binned_data( $binsize, $dataset );
541 }
542  
543 # Interpolate values
544 if ($smooth) {
545 print " Smoothing data by interpolation....\n";
546 go_interpolate_values();
547 }
548 }
549 }
550  
551 sub collect_binned_data {
552 my ( $binsize, $dataset ) = @_;
553  
554 ## Collect the data
555 my $stream = $Data->row_stream;
556 while ( my $row = $stream->next_row ) {
557  
558 # define the starting and ending points based on gene length
559 my $length = defined $length_i ? $row->value($length_i) : $row->length;
560  
561 # check the length
562 if ( defined $min_length and $length < $min_length ) {
563  
564 # this feature is too short to divided into bins
565 # we will skip this feature
566  
567 # but first, put in null values
568 for my $c ( $startcolumn .. ( $Data->last_column ) ) {
569 $row->value( $c, '.' );
570 }
571 next;
572 }
573  
574 # calculate the actual extension in bp
575 # this is determined from the extension_size or the feature length
576 # and multiplied by the number of extensions requested
577 my $extra;
578 if ($extension) {
579 if ($extension_size) {
580  
581 # extension is specific bp in size
582 $extra = $extension_size * $extension;
583 }
584 else {
585 # extension is dependent on feature length
586 $extra = int( ( $extension * $binsize * 0.01 * $length ) + 0.5 );
587 }
588 }
589  
590 my $regionscores = $row->get_region_position_scores(
591 'ddb' => $ddb,
592 'dataset' => $dataset,
593 'method' => $method,
594 'extend' => $extra,
595 'stranded' => $stranded,
596 'subfeature' => $subfeature,
597 'length' => $length,
598 );
599  
600 # record the scores for each bin
601 record_the_bin_values( $row, $length, $regionscores );
602 }
603 }
604  
605 sub collect_binned_long_data {
606 my ( $binsize, $dataset ) = @_;
607  
608 ## Collect the data
609 my $stream = $Data->row_stream;
610 while ( my $row = $stream->next_row ) {
611  
612 # identify the feature or use the row
613 my $fstart = $row->start;
614 my $fstop = $row->end;
615 my $strand = $row->strand;
616 my $length = $row->length; # subfeatures not allowed here, so use feature length
617  
618 # collect the scores to the bins in the region
619 for my $column ( $startcolumn .. ( $Data->last_column ) ) {
620  
621 # we will step through each data column, representing each window (bin)
622 # across the feature's region
623 # any scores within this window will be collected and the mean
624 # value reported
625  
626 # convert the window start and stop coordinates (as percentages) to
627 # actual bp
628 # this depends on whether the binsize is explicitly defined in bp or
629 # is a fraction of the feature length
630 my ( $start, $stop );
631 if ( $Data->metadata( $column, 'bin_size' ) =~ /bp$/ ) {
632  
633 # the bin size is explicitly defined
634  
635 # the start and stop points are relative to either the feature
636 # start (always 0) or the end (the feature length), depending
637 # upon whether the 5' or 3' end of the feature
638  
639 # determine this by the sign of the start position
640 if ( $Data->metadata( $column, 'start' ) < 0 and $strand >= 0 ) {
641  
642 # the start position is less than 0, implying the 5' end
643 # the reference position will be the feature start on plus strand
644 $start = $fstart + $Data->metadata( $column, 'start' );
645 $stop = $fstart + $Data->metadata( $column, 'stop' );
646 }
647 elsif ( $Data->metadata( $column, 'start' ) < 0 and $strand < 0 ) {
648  
649 # the start position is less than 0, implying the 5' end
650 # the reference position will be the feature end on minus strand
651 $start = $fstop - $Data->metadata( $column, 'start' );
652 $stop = $fstop - $Data->metadata( $column, 'stop' );
653 }
654 elsif ( $Data->metadata( $column, 'start' ) >= 0 and $strand >= 0 ) {
655  
656 # the start position is greather than 0, implying the 3' end
657 # the reference position will be the feature start on plus strand
658 $start = $fstop + $Data->metadata( $column, 'start' );
659 $stop = $fstop + $Data->metadata( $column, 'stop' );
660 }
661 elsif ( $Data->metadata( $column, 'start' ) >= 0 and $strand < 0 ) {
662  
663 # the start position is greather than 0, implying the 3' end
664 # the reference position will be the feature end on minus strand
665 $start = $fstart - $Data->metadata( $column, 'start' );
666 $stop = $fstart - $Data->metadata( $column, 'stop' );
667 }
668 else {
669 warn " unable to unable to identify region orientation: start "
670 . $Data->metadata( $column, 'start' )
671 . ", strand $strand\n";
672 return;
673 }
674 }
675 else {
676 # otherwise the bin size is based on feature length
677 if ( $strand >= 0 ) {
678  
679 # forward plus strand
680 $start =
681 int( $fstart +
682 ( $Data->metadata( $column, 'start' ) * 0.01 * $length ) +
683 0.5 );
684 $stop =
685 int( $fstart +
686 ( $Data->metadata( $column, 'stop' ) * 0.01 * $length ) - 1 +
687 0.5 );
688 }
689 else {
690 # reverse minus strand
691 $start =
692 int( $fstop -
693 ( $Data->metadata( $column, 'start' ) * 0.01 * $length ) +
694 0.5 );
695 $stop =
696 int( $fstop -
697 ( $Data->metadata( $column, 'stop' ) * 0.01 * $length ) + 1 +
698 0.5 );
699 }
700 }
701  
702 # collect the data for this bin
703 my $score = $row->get_score(
704 'ddb' => $ddb,
705 'dataset' => $dataset,
706 'start' => $start,
707 'stop' => $stop,
708 'method' => $method,
709 'stranded' => $stranded,
710 );
711 if ( $formatter and looks_like_number($score) ) {
712 $score = sprintf( $formatter, $score );
713 }
714 $row->value( $column, $score );
715 }
716 }
717 }
718  
719 sub record_the_bin_values {
720  
721 # get the passed values
722 my ( $row, $length, $regionscores ) = @_;
723  
724 # assign the scores to the bins in the region
725 for my $column ( $startcolumn .. ( $Data->last_column ) ) {
726  
727 # we will step through each data column, representing each window (bin)
728 # across the feature's region
729 # any scores within this window will be collected and the mean
730 # value reported
731  
732 # record nulls if no data returned
733 unless ( scalar keys %{$regionscores} ) {
734 $row->value( $column, calculate_score( $method, undef ) );
735 next;
736 }
737  
738 # convert the window start and stop coordinates (as percentages) to
739 # actual bp
740 # this depends on whether the binsize is explicitly defined in bp or
741 # is a fraction of the feature length
742 my ( $start, $stop );
743 if ( $Data->metadata( $column, 'bin_size' ) =~ /bp$/ ) {
744  
745 # the bin size is explicitly defined
746  
747 # the start and stop points are relative to either the feature
748 # start (always 0) or the end (the feature length), depending
749 # upon whether the 5' or 3' end of the feature
750  
751 # determine this by the sign of the start position
752 if ( $Data->metadata( $column, 'start' ) < 0 ) {
753  
754 # the start position is less than 0, implying the 5' end
755 # the reference position will be the feature start, or 0
756 $start = $Data->metadata( $column, 'start' );
757 $stop = $Data->metadata( $column, 'stop' );
758 }
759 else {
760 # the start position is greather than 0, implying the 3' end
761 # the reference position will be the feature end, or length
762 $start = $Data->metadata( $column, 'start' ) + $length;
763 $stop = $Data->metadata( $column, 'stop' ) + $length;
764 }
765 }
766 else {
767 # otherwise the bin size is based on feature length
768 $start = sprintf "%.0f",
769 ( $Data->metadata( $column, 'start' ) * 0.01 * $length ) + 1;
770 $stop = sprintf "%.0f",
771 ( $Data->metadata( $column, 'stop' ) * 0.01 * $length );
772 }
773  
774 # collect the scores for this window
775 my @scores = map { $regionscores->{$_} }
776 grep { $_ >= $start and $_ <= $stop }
777 keys %{$regionscores};
778  
779 # calculate the value
780 my $window_score = calculate_score( $method, \@scores );
781 if ( $formatter and looks_like_number($window_score) ) {
782 $window_score = sprintf( $formatter, $window_score );
783 }
784  
785 # record the value
786 $row->value( $column, $window_score );
787 }
788 }
789  
790 ## Interpolate the '.' values with the mean of the neighbors
791 sub go_interpolate_values {
792  
793 # determine counts
794 my $lastwindow = $Data->last_column;
795  
796 # lastwindow is the index of the last column
797  
798 # walk through each data line and then each window
799 my $stream = $Data->row_stream;
800 while ( my $row = $stream->next_row ) {
801 my $col = $startcolumn + 1;
802 while ( $col < $lastwindow ) {
803  
804 # walk through the windows of a data row
805 # skipping the very first and last windows (columns)
806 # we will look for null values
807 # if one is found, interpolate from neighbors
808 if ( $row->value($col) eq '.' and $row->value( $col - 1 ) ne '.' ) {
809  
810 # we will interpolate the value from the neighbors
811 # first, need to check that the neighbors have values
812  
813 # find the next real value
814 my $next_i;
815 for ( my $i = $col + 1; $col <= $lastwindow; $i++ ) {
816 if ( $row->value($i) ne '.' ) {
817 $next_i = $i;
818 last;
819 }
820 }
821 next unless defined $next_i;
822  
823 # determine fractional value
824 my $initial = $row->value( $col - 1 );
825 my $fraction =
826 ( $row->value($next_i) - $initial ) / ( $next_i - $col + 1 );
827  
828 # apply fractional values
829 for ( my $n = $col; $n < $next_i; $n++ ) {
830 my $score = $initial + ( $fraction * ( $n - $col + 1 ) );
831 if ( $formatter and looks_like_number($score) ) {
832 $score = sprintf( $formatter, $score );
833 }
834 $row->value( $n, $score );
835 }
836  
837 # jump ahead
838 $col = $next_i;
839 }
840 $col++;
841 }
842 }
843 }
844  
845 ### Prepare all of the bin columns and their metadata
846 sub prepare_bins {
847  
848 my ( $binsize, $dataset ) = @_;
849  
850 # the size of the bin in percentage units, default would be 10%
851 # each bin will be titled the starting and ending point for that bin in
852 # percentage units
853 # for example, -20..-10,-10..0,0..10,10..20
854  
855 # if $extension is defined, then it will add the appropriate flanking bins,
856 # otherwise it should skip them
857  
858 # bin(s) on 5' flank
859 if ($extension) {
860  
861 if ($extension_size) {
862  
863 # extended bins should be of specific bp size
864 for ( my $i = $extension; $i > 0; $i-- ) {
865 my $start = 0 - ( $extension_size * $i );
866 my $stop = 0 - ( $extension_size * ( $i - 1 ) );
867 _set_metadata( $start, $stop, $extension_size, 'bp', $dataset );
868 }
869 }
870 else {
871 # extended bin size will be based on feature length
872 for ( my $i = $extension; $i > 0; $i-- ) {
873 my $start = 0 - ( $binsize * $i );
874 my $stop = 0 - ( $binsize * ( $i - 1 ) );
875 _set_metadata( $start, $stop, $binsize, '%', $dataset );
876 }
877 }
878 }
879  
880 # bins over the gene body
881 for ( my $i = 0; $i < $bins; $i++ ) {
882 my $start = ( $i * $binsize );
883 my $stop = ( $i + 1 ) * $binsize;
884 _set_metadata( $start, $stop, $binsize, '%', $dataset );
885 }
886  
887 # bin(s) on 3' flank
888 if ($extension) {
889  
890 if ($extension_size) {
891  
892 # extended bins should be of specific bp size
893 for ( my $i = 0; $i < $extension; $i++ ) {
894 my $start = ( $extension_size * $i );
895 my $stop = ( $extension_size * ( $i + 1 ) );
896 _set_metadata( $start, $stop, $extension_size, 'bp', $dataset );
897 }
898 }
899 else {
900 # extended bin size will be based on feature length
901 for ( my $i = 0; $i < $extension; $i++ ) {
902 my $start = 100 + ( $binsize * $i );
903 my $stop = 100 + ( $binsize * ( $i + 1 ) );
904 _set_metadata( $start, $stop, $binsize, '%', $dataset );
905 }
906 }
907 }
908 }
909  
910 ### Set the metadata for a new data table column (dataset)
911 sub _set_metadata {
912  
913 # the start and stop positions are passed
914 my ( $start, $stop, $binsize, $unit, $dataset ) = @_;
915  
916 # generate a simplified new name
917 my $new_name = simplify_dataset_name($dataset);
918  
919 # set new index
920 my $new_index = $Data->add_column( sprintf( "%s:%d%s", $new_name, $start, $unit ) );
921  
922 # set the metadata using passed and global variables
923 # set the metadata
924 $Data->metadata( $new_index, 'start', $start );
925 $Data->metadata( $new_index, 'stop', $stop );
926 $Data->metadata( $new_index, 'dataset', $dataset );
927 $Data->metadata( $new_index, 'method', $method );
928 $Data->metadata( $new_index, 'bin_size', $binsize . $unit );
929 $Data->metadata( $new_index, 'strand', $stranded );
930 $Data->metadata( $new_index, 'decimal_format', $format ) if defined $format;
931  
932 if ($data_database) {
933 $Data->metadata( $new_index, 'db', $data_database );
934 }
935  
936 if ( $dataset =~ / \. (b|cr) am $/xni and $method =~ /count/ ) {
937 $Data->metadata( $new_index, 'mapq', $mapq );
938 }
939 }
940  
941 __END__