script/data2wig.pl untested

filter: Statementstmt 0.0% 0 / 410 Branchbran 0.0% 0 / 262 Conditioncond 0.0% 0 / 136 MC/DCmcdc 0.0% 0 / 80 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 927 CC 102 SCAR 48.1
CC
102
Cov
0%
check_indices
342.0
check_step
240.0
set_score_sub
132.0
CRAP 123.0
1 #!/usr/local/bin/perl
2  
3 # documentation at end of file
4  
5 use warnings;
6 use strict;
7 use Getopt::Long qw(:config no_ignore_case bundling);
8 use Pod::Usage;
9 use List::Util qw(sum0 max);
10 use Scalar::Util qw(looks_like_number);
11 use Statistics::Lite qw(median);
12 use Bio::ToolBox::Data::Stream;
13 use Bio::ToolBox::utility qw(parse_list ask_user_for_index);
14 use Bio::ToolBox::big_helper qw(
15 get_wig_to_bigwig_app
16 check_wigToBigWig_version
17 open_wig_to_bigwig_fh
18 generate_chromosome_file
19 wig_to_bigwig_conversion
20 );
21  
22 our $VERSION = '2.02';
23  
24 print "\n This script will export a data file to a wig file\n\n";
25  
26 ### Quick help
27 unless (@ARGV) {
28  
29 # when no command line options are present
30 # print SYNOPSIS
31 pod2usage(
32 {
33 '-verbose' => 0,
34 '-exitval' => 1,
35 }
36 );
37 }
38  
39 ### Get command line options and initialize values
40 my (
41 $infile, $outfile, $fast, $step,
42 $bedgraph, $step_size, $span, $ask,
43 $chr_index, $start_index, $stop_index, $score_index,
44 @score_indices, $no_header, $attribute_name, $track_name,
45 $use_track, $midpoint, $interbase, $format,
46 $method, $bigwig, $bw_app_path, $database,
47 $chromo_file, $gz, $help, $print_version,
48 );
49  
50 # Command line options
51 GetOptions(
52 'i|in=s' => \$infile, # name of input file
53 'o|out=s' => \$outfile, # name of output gff file
54 'f|fast!' => \$fast, # fast mode without checks and stuff
55 'p|step=s' => \$step, # wig step method
56 'bed|bdg!' => \$bedgraph, # write a bedgraph file
57 'size=i' => \$step_size, # wig step size
58 'span=i' => \$span, # the wig span size
59 'a|ask' => \$ask, # request help in assigning indices
60 'c|chr=i' => \$chr_index, # index for the chromosome column
61 'b|begin|start|pos=i' => \$start_index, # index for the start column
62 'e|stop|end=i' => \$stop_index, # index for the stop column
63 's|index|score=s' => \$score_index, # index for the score column
64 'H|noheader' => \$no_header, # source has no header line
65 'attrib=s' => \$attribute_name, # gff or vcf attribute name to use
66 'name=s' => \$track_name, # name string for the track
67 'track!' => \$use_track, # boolean to include a track line
68 'mid!' => \$midpoint, # boolean to use the midpoint
69 '0|zero|inter!' => \$interbase, # shift from interbase
70 'format=i' => \$format, # format output to indicated number of places
71 'm|method=s' => \$method, # method for combining duplicate values
72 'B|bigwig|bw' => \$bigwig, # generate a binary bigwig file
73 'd|db=s' => \$database, # database for bigwig file generation
74 'chromof=s' => \$chromo_file, # name of a chromosome file
75 'bwapp=s' => \$bw_app_path, # path to wigToBigWig utility
76 'z|gz!' => \$gz, # boolean to compress output file
77 'h|help' => \$help, # request help
78 'v|version' => \$print_version, # print the version
79 ) or die " unrecognized option(s)!! please refer to the help documentation\n\n";
80  
81 # Print help
82 if ($help) {
83  
84 # print entire POD
85 pod2usage(
86 {
87 '-verbose' => 2,
88 '-exitval' => 1,
89 }
90 );
91 }
92  
93 # Print version
94 if ($print_version) {
95 print " Biotoolbox script data2wig.pl, version $VERSION\n\n";
96 eval {
97 require Bio::ToolBox;
98 my $v = Bio::ToolBox->VERSION;
99 print " Biotoolbox package version $v\n";
100 };
101 exit;
102 }
103  
104 ### Check for required or default values
105 unless ($infile) {
106 if (@ARGV) {
107 $infile = shift @ARGV;
108 }
109 else {
110 print " FATAL: No source data file specified! \n use data2wig.pl --help\n";
111 exit 1;
112 }
113 }
114 unless ( defined $use_track ) {
115  
116 # default is to write a track
117 $use_track = $bigwig ? 0 : 1;
118 }
119 $method ||= 'mean';
120  
121 ### Load input file
122 my $Input = Bio::ToolBox::Data::Stream->new( file => $infile, noheader => $no_header )
123 or die "Unable to open file '$infile'!\n";
124  
125 ### Check and/or ask for specific options
126  
127 check_indices();
128  
129 check_track_name();
130  
131 check_step();
132  
133 my $post_bw_convert;
134 if ($bigwig) {
135 set_bigwig_options();
136 }
137  
138 my $method_sub = set_method_sub();
139  
140 my $score_sub = set_score_sub();
141  
142 my $printer = set_print_string();
143  
144 if ($fast) {
145 if ($midpoint) {
146 print
147 " WARNING: cannot use midpoint position in fast mode!\nrunning in slow mode...\n";
148 $fast = 0;
149 }
150 if ($attribute_name) {
151 print
152 " WARNING: cannot use GFF or VCF attribute score in fast mode!\nrunning in slow mode...\n";
153 $fast = 0;
154 }
155 }
156  
157 my $start_time = time;
158  
159 ### Open output file
160 unless ($outfile) {
161  
162 # automatically generate output file name based on track name
163 $outfile = $track_name;
164 $outfile =~ s/\(\) /_/g; # strip parentheses and spaces from column name
165 }
166 my $out_fh;
167 if ( $bigwig and not $post_bw_convert ) {
168  
169 # we will write directly to a bigWig file
170 unless ($chromo_file) {
171 $chromo_file = generate_chromosome_file($database)
172 or die "unable to generate chromosome file needed for bigWig conversion!\n";
173 }
174 $outfile .= '.bw' unless $outfile =~ /\.bw$/;
175 $out_fh = open_wig_to_bigwig_fh(
176 file => $outfile,
177 chromo => $chromo_file,
178 bwapppath => $bw_app_path
179 ) or die "unable to open a wigToBigWig file handle!\n";
180 }
181 else {
182 # we will write to a wig file
183 unless ( $outfile =~ /\.(?: wig | bdg | bedgraph ) (?:\.gz)? $/xi ) {
184 $outfile .= $bedgraph ? '.bdg' : '.wig';
185 }
186 $out_fh = Bio::ToolBox::Data::Stream->open_to_write_fh( $outfile, $gz )
187 or die " unable to open output file '$outfile' for writing!\n";
188  
189 # write track line
190 if ($use_track) {
191 print {$out_fh} "track type=wiggle_0 name=$track_name\n";
192 }
193 }
194  
195 ### Start the conversion
196 printf " converting '%s' as %s wig file...\n",
197 scalar(@score_indices)
198 ? join( ", ", map { $Input->name($_) } @score_indices )
199 : $Input->name($score_index),
200 $bedgraph ? 'bedGraph' : $step . 'Step';
201  
202 if ( $fast and $bedgraph ) {
203 fast_convert_to_bedgraph();
204 }
205 elsif ( $fast and $step eq 'fixed' ) {
206 fast_convert_to_fixedStep();
207 }
208 elsif ( $fast and $step eq 'variable' ) {
209 fast_convert_to_variableStep();
210 }
211 elsif ($bedgraph) {
212 convert_to_bedgraph();
213 }
214 elsif ( $step eq 'fixed' ) {
215 convert_to_fixedStep();
216 }
217 elsif ( $step eq 'variable' ) {
218 convert_to_variableStep();
219 }
220  
221 # close
222 $out_fh->close;
223  
224 # convert as necessary
225 if ( $bigwig and $post_bw_convert ) {
226  
227 unless ($chromo_file) {
228 $chromo_file = generate_chromosome_file($database)
229 or die "unable to generate chromosome file needed for bigWig conversion!\n";
230 }
231 my $final_bw = wig_to_bigwig_conversion(
232 wig => $outfile,
233 chromo => $chromo_file,
234 bwapppath => $bw_app_path,
235 );
236 if ($final_bw) {
237 print " Wrote file $final_bw\n";
238 unlink $outfile;
239 }
240  
241 # error message already printed if conversion had failed
242 }
243 else {
244 printf " Wrote file %s\n", $outfile;
245 }
246  
247 # clean up chromosome file
248 if ( $bigwig and $database and $chromo_file =~ /^chr_sizes_\w{5}$/x ) {
249 unlink $chromo_file;
250 }
251  
252 # finished
253 printf " Finished in %.0f seconds\n", ( time - $start_time );
254  
255 ############ Subroutines ###############
256  
257 sub check_indices {
258  
259 # check coordinates
260 if ( not $chr_index ) {
261 $chr_index = $Input->chromo_column;
262 }
263 if ( $ask or not defined $chr_index ) {
264 $chr_index =
265 ask_user_for_index( $Input, " Enter the index for the chromosome column " );
266 unless ( defined $chr_index ) {
267 print " FATAL: No identifiable chromosome column index!\n";
268 exit 1;
269 }
270 }
271 if ( not $start_index ) {
272 $start_index = $Input->start_column;
273 }
274 if ( $ask or not $start_index ) {
275 $start_index = ask_user_for_index( $Input,
276 " Enter the index for the start or position column " );
277 unless ($start_index) {
278 print " FATAL: No identifiable start column index!\n";
279 exit 1;
280 }
281 }
282 if ( substr( $Input->name($start_index), -1 ) eq '0' ) {
283  
284 # name suggests it is 0-based indexed
285 $interbase = 1;
286 }
287  
288 # stop column is optional
289  
290 # score
291 if ( not $score_index ) {
292 $score_index = $Input->gff ? 6 : $Input->bed >= 5 ? 5 : undef;
293 }
294 if ( $ask or not $score_index ) {
295  
296 # first look for a generic score index
297 $score_index =
298 ask_user_for_index( $Input, " Enter the index for the score column " );
299 unless ($score_index) {
300 print " FATAL: No identifiable score column index!\n";
301 exit 1;
302 }
303 }
304 if ( $score_index =~ /[,\-]/ ) {
305 @score_indices = parse_list($score_index);
306 }
307 elsif ( ref($score_index) eq 'ARRAY' ) {
308  
309 # in case returned from interactive
310 @score_indices = @{$score_index};
311 }
312 if (@score_indices) {
313 foreach my $i (@score_indices) {
314 unless ( $Input->name($i) ) {
315 print " FATAL: Score column $i does not exist!\n";
316 exit 1;
317 }
318 }
319 }
320 else {
321 unless ( $Input->name($score_index) ) {
322 print " FATAL: Score column $score_index does not exist!\n";
323 exit 1;
324 }
325 }
326 }
327  
328 sub check_track_name {
329  
330 # determine what the track name will be
331 return if $track_name;
332 if (@score_indices) {
333 $track_name = join( '_', map { $Input->name($_) } @score_indices );
334 }
335 elsif ($score_index) {
336  
337 $track_name = $Input->name($score_index);
338 if ( $track_name =~ /^score$/i ) {
339  
340 # some sort of bed or gff file standard score column
341 $track_name = $Input->basename;
342 }
343 }
344 }
345  
346 sub check_step {
347  
348 # In my biotoolbox scripts that generate genomic bins or windows
349 # the win(dow) and step values are recorded as metadata under
350 # the start column
351 # Therefore, we will check for this metadata to confirm and/or
352 # determine the step and span parameters
353  
354 # check step
355 if ($bedgraph) {
356  
357 # write a bedgraph file
358 $step = 'bed';
359 $use_track = 0; # no track data
360 return;
361 }
362 elsif ( $step and $step eq 'bed' ) {
363  
364 # write a bedgraph file
365 $bedgraph = 1;
366 $use_track = 0; # no track data
367 return;
368 }
369 elsif ( $step and $step eq 'variable' ) {
370  
371 # this is ok, we can work with it
372 }
373 elsif ( $step and $step eq 'fixed' ) {
374  
375 # double check that the data file supports this
376 # assign the step size as necessary
377 if ( defined $Input->metadata( $start_index, 'step' ) ) {
378 if ($step_size) {
379 if ( $step_size != $Input->metadata( $start_index, 'step' ) ) {
380 print
381 " FATAL: Requested step size $step_size does not match metadata step size!!!\n";
382 exit 1;
383 }
384 }
385 else {
386 # define it from the metadata
387 $step_size = $Input->metadata( $start_index, 'step' );
388 }
389 }
390 elsif ( not $step_size ) {
391 print
392 " WARNING: Fixed step size not defined by user or metadata! Using 'variableStep'\n";
393 $step = 'variable';
394 }
395 }
396 else {
397 # attempt to determine automatically
398 if ( defined $Input->metadata( $start_index, 'step' ) ) {
399  
400 # set step size
401 $step = 'fixed';
402 $step_size = $Input->metadata( $start_index, 'step' );
403 print
404 " Automatically generating 'fixedStep' wig with step of $step_size bp\n";
405 }
406 else {
407 print " Automatically generating 'variableStep' wig\n";
408 $step = 'variable';
409 }
410 }
411  
412 # check span
413 if ($span) {
414  
415 # user set it, confirm with metadata if possible
416 if ( defined $Input->metadata( $start_index, 'win' )
417 and $Input->metadata( $start_index, 'win' ) != $span )
418 {
419 # the requested span and metadata window size do not match
420 print
421 " FATAL: Requested span size $span does not match metadata window size!!!\n";
422 exit 1;
423 }
424 }
425 else {
426 # attempt to determine automatically
427 if ( defined $Input->metadata( $start_index, 'win' ) and not $midpoint ) {
428  
429 # set the span equal to the window size
430 $span = $Input->metadata( $start_index, 'win' );
431 print " Automatically setting span to $span bp\n";
432 }
433 else {
434 # default span is 1 bp
435 $span = 1;
436 }
437 }
438  
439 # confirm span
440 if ( $midpoint and $span > 1 ) {
441  
442 # cannot use span parameter if the midpoint is requested
443 $span = 1;
444 print " Reverting span to 1 bp when midpoint is requested\n";
445 }
446 if ( $step eq 'fixed' and $span and $span > $step_size ) {
447  
448 # span greater than the step will confuse wig parsers,
449 # including conversion to bigWig files
450 # the wig format definition cannot have > 1 value per position
451 print " Span of $span bp is greater than step of $step_size bp!\n"
452 . " Wig cannot have overlapping positions. Switching to midpoint\n";
453 $span = 1;
454 $midpoint = 1;
455 }
456 }
457  
458 sub set_bigwig_options {
459  
460 # find external utility
461 unless ($bw_app_path) {
462 $bw_app_path = get_wig_to_bigwig_app();
463 }
464  
465 # check the utility and options
466 if ($bw_app_path) {
467 if ( check_wigToBigWig_version($bw_app_path) ) {
468  
469 # we can write directly to utility
470 # print " $bw_app_path supports stdin, can write directly\n";
471 $post_bw_convert = 0;
472 }
473 else {
474 # we cannot write directly to utility
475 # print " $bw_app_path does not support stdin, will write temp wig file\n";
476 $post_bw_convert = 1;
477 $gz = 0;
478 }
479  
480 # if we're generating bigwig file, no track is needed
481 $use_track = 0;
482  
483 # check that we have a source for chromosome info
484 unless ( $database or $chromo_file ) {
485 $database = $Input->database
486 or die
487 " No database name or chromosome file provided for generating bigwig file!\n";
488 }
489 }
490 else {
491 print " No external bigWig utility available, writing wig format\n";
492 $bigwig = 0;
493 }
494 }
495  
496 sub set_method_sub {
497  
498 # for combining values from duplicate positions we need a method
499 if ( $method eq 'mean' ) {
500 return sub { return sum0(@_) / ( scalar(@_) || 1 ); };
501 }
502 elsif ( $method eq 'median' ) {
503 return \&median;
504 }
505 elsif ( $method eq 'sum' ) {
506 return \&sum0;
507 }
508 elsif ( $method eq 'max' ) {
509 return \&max;
510 }
511 else {
512 print STDERR " FATAL: unrecognized method 'method'!\n";
513 exit 1;
514 }
515 }
516  
517 sub set_score_sub {
518 if ( $attribute_name and $Input->gff ) {
519  
520 # a GFF attribute
521 return sub {
522 my $row = shift;
523 my $attribs = $row->gff_attributes;
524 my $score = $attribs->{$attribute_name} || 0;
525 return if $score eq '.';
526  
527 # format as necessary
528 $score =~ s/\%$//; # remove stupid percents if present
529 return $score;
530 };
531 }
532 elsif ( $attribute_name and $Input->vcf and defined $score_index ) {
533  
534 # a VCF attribute from one sample
535 return sub {
536 my $row = shift;
537 my $attribs = $row->vcf_attributes;
538 my $score = $attribs->{$score_index}{$attribute_name} || 0;
539 return 0 if $score eq '.';
540  
541 # format as necessary
542 $score =~ s/\%$//; # remove stupid percents if present
543 return $score;
544 };
545 }
546 elsif ( $attribute_name and $Input->vcf and @score_indices ) {
547  
548 # a VCF attribute from many samples
549 return sub {
550 my $row = shift;
551 my $attribs = $row->vcf_attributes;
552 my @scores;
553 foreach (@score_indices) {
554 my $s = $attribs->{$_}{$attribute_name} || 0;
555 $s =~ s/\%$//; # remove stupid percents if present
556 if ( looks_like_number($s) ) {
557 push @scores, $s;
558 }
559 }
560 return &{$method_sub}(@scores);
561 };
562 }
563 elsif ( @score_indices and $fast ) {
564  
565 # collect over multiple score columns from array reference
566 return sub {
567 my $data = shift;
568 my @v = grep { looks_like_number($_) } map { $data->[$_] } @score_indices;
569 return &{$method_sub}(@v);
570 };
571 }
572 elsif ( @score_indices and not $fast ) {
573  
574 # collect over multiple score columns from Feature row object
575 return sub {
576 my $row = shift;
577 my @v =
578 grep { looks_like_number($_) } map { $row->value($_) } @score_indices;
579 return &{$method_sub}(@v);
580 };
581 }
582 elsif ( defined $score_index and $fast ) {
583  
584 # collect from a single score column
585 return sub {
586 return shift->[$score_index] || 0;
587 };
588 }
589 elsif ( defined $score_index and not $fast ) {
590  
591 # collect from a single score column
592 return sub {
593 my $row = shift;
594 return $row->value($score_index) || 0;
595 };
596 }
597 else {
598 die "programmer error! how did we get here?\n";
599 }
600 }
601  
602 sub set_print_string {
603  
604 # set the printf format string depending on type of wig file
605 if ( $step eq 'fixed' ) {
606 return defined $format ? '%.' . $format . "f\n" : "%s\n";
607 }
608 elsif ( $step eq 'variable' ) {
609 return defined $format ? '%d %.' . $format . "f\n" : "%s %s\n";
610 }
611 elsif ( $step eq 'bed' ) {
612 return defined $format ? "%s\t%d\t%d\t%." . $format . "f\n" : "%s\t%d\t%d\t%s\n";
613 }
614 }
615  
616 sub convert_to_fixedStep {
617  
618 # keep track of current chromosome name and length
619 my $current_chr = q(); # current chromosome
620 my $previous_pos = 0;
621  
622 # walk through the data file
623 while ( my $row = $Input->next_row ) {
624  
625 # coordinates
626 my $chromosome = defined $chr_index ? $row->value($chr_index) : $row->seq_id;
627 my $start = calculate_position($row);
628  
629 # check coordinate
630 next if $start <= 0; # skip negative or zero coordinates
631  
632 # write definition line if necessary
633 if ( $chromosome ne $current_chr ) {
634  
635 # new chromosome, new definition line
636 $out_fh->printf( "fixedStep chrom=%s start=%d step=%d span=%d\n",
637 $chromosome, $start, $step_size, $span );
638  
639 # reset the current chromosome
640 $current_chr = $chromosome;
641 $previous_pos = $start; # temporary artificial
642 }
643 elsif ( $start > ( $previous_pos + $span ) ) {
644  
645 # skipped a chunk here
646 $out_fh->printf( "fixedStep chrom=%s start=%d step=%d span=%d\n",
647 $chromosome, $start, $step_size, $span );
648 }
649 elsif ( $start < $previous_pos ) {
650 printf STDERR
651 " FATAL: input file is not genomically sorted! %d comes after %d at line %d\n",
652 $start, $previous_pos, $row->line_number;
653 exit 1;
654 }
655 $previous_pos = $start;
656  
657 # print the score
658 $out_fh->printf( $printer, &{$score_sub}($row) );
659 }
660 }
661  
662 sub fast_convert_to_fixedStep {
663 my $current_chr = q(); # current chromosome
664 unless ($chr_index) {
665 $chr_index = $Input->chromo_column;
666 }
667 unless ( $chr_index and $start_index ) {
668 print STDERR " FATAL: coordinate columns not defined!\n";
669 exit 1;
670 }
671 unless ($score_index) {
672 print STDERR " FATAL: no score column defined!\n";
673 exit 1;
674 }
675  
676 # use direct file handle and skip the Stream and row objects
677 my $fh = $Input->fh;
678 while ( my $line = $fh->getline ) {
679 chomp $line;
680 my @data = split( /\t/, $line );
681  
682 # working with raw array, need to shift values to compensate
683 # for 1-base indexing of column indexes
684 unshift @data, 0;
685  
686 my $chromosome = $data[$chr_index];
687 my $start = $data[$start_index];
688 $start++ if $interbase;
689  
690 # write definition line if necessary
691 if ( $chromosome ne $current_chr ) {
692 $out_fh->printf( "fixedStep chrom=%s start=%d step=%d span=%d\n",
693 $chromosome, $start, $step_size, $span );
694 $current_chr = $chromosome;
695 }
696  
697 # print the score
698 $out_fh->printf( $printer, &{$score_sub}( \@data ) );
699 }
700 }
701  
702 sub convert_to_variableStep {
703 my $current_chr = q(); # current chromosome
704 my $previous_pos = 0; # previous position to avoid duplicates in wig file
705 my @scores; # reusable array for putting multiple data points in
706 while ( my $row = $Input->next_row ) {
707  
708 # coordinates
709 my $chromosome = $chr_index ? $row->value($chr_index) : $row->seq_id;
710 my $start = calculate_position($row);
711 next if $start <= 0; # skip negative or zero coordinates
712  
713 # write definition line if necessary
714 if ( $chromosome ne $current_chr ) {
715  
716 # first check and write orphan scores
717 # this might happen if there was only one score on the entire chr
718 if (@scores) {
719 if ( scalar @scores == 1 ) {
720  
721 # print the one score
722 $out_fh->printf( $printer, $previous_pos, $scores[0] );
723 }
724 else {
725 # more than one score, combine them
726 my $score = &{$method_sub}(@scores);
727 $out_fh->printf( $printer, $previous_pos, $score );
728 }
729 @scores = ();
730 }
731  
732 # print new definition line and reset for next
733 $out_fh->print("variableStep chrom=$chromosome span=$span\n");
734 $current_chr = $chromosome;
735 $previous_pos = $start;
736 }
737  
738 # collect the score
739 my $score = &{$score_sub}($row);
740 next unless defined $score;
741  
742 # check for duplicate positions and write appropriately
743 if ( $start < $previous_pos ) {
744 printf STDERR
745 " FATAL: input file is not genomically sorted! %d comes after %d at line %d\n",
746 $start, $previous_pos, $row->line_number;
747 exit 1;
748 }
749 elsif ( $start == $previous_pos ) {
750  
751 # same position, add to the score list
752 push @scores, $score;
753 }
754 else {
755 # we have moved on to the next position
756 # now print the previous scores
757 if ( scalar @scores == 1 ) {
758  
759 # print the one score
760 $out_fh->printf( $printer, $previous_pos, $scores[0] );
761 }
762 elsif ( scalar @scores > 1 ) {
763  
764 # more than one score
765 my $multi_score = &{$method_sub}(@scores);
766 $out_fh->printf( $printer, $previous_pos, $multi_score );
767 }
768  
769 # reset for next
770 $previous_pos = $start;
771 @scores = ($score);
772 }
773 }
774 }
775  
776 sub fast_convert_to_variableStep {
777 my $current_chr = q(); # current chromosome
778 unless ($chr_index) {
779 $chr_index = $Input->chromo_column;
780 }
781 unless ( $chr_index and $start_index ) {
782 print STDERR " FATAL: coordinate columns not defined!\n";
783 exit 1;
784 }
785 unless ($score_index) {
786 print STDERR " FATAL: no score column defined!\n";
787 exit 1;
788 }
789  
790 # use direct file handle and skip the Stream and row objects
791 my $fh = $Input->fh;
792 while ( my $line = $fh->getline ) {
793 chomp $line;
794 my @data = split( /\t/, $line );
795  
796 # working with raw array, need to shift values to compensate
797 # for 1-base indexing of column indexes
798 unshift @data, 0;
799  
800 my $chromosome = $data[$chr_index];
801 my $start = $data[$start_index];
802 $start++ if $interbase;
803  
804 # write definition line if necessary
805 if ( $chromosome ne $current_chr ) {
806 $out_fh->print("variableStep chrom=$chromosome span=$span\n");
807 $current_chr = $chromosome;
808 }
809  
810 # collect the score
811 $out_fh->printf( $printer, $start, &{$score_sub}( \@data ) );
812 }
813 }
814  
815 sub convert_to_bedgraph {
816  
817 # variables to check for overlap
818 my $current_chr = q(); # current chromosome
819 my $previous_pos = 0; # previous position to avoid overlap
820 while ( my $row = $Input->next_row ) {
821  
822 # coordinates
823 my $chromosome = $chr_index ? $row->value($chr_index) : $row->seq_id;
824 my $start = $row->value($start_index);
825 my $stop =
826 defined $stop_index
827 ? $row->value($stop_index)
828 : $row->stop || $row->start || $start;
829  
830 # adjust start position
831 $start-- unless ($interbase);
832  
833 # check coordinates
834 if ( defined $previous_pos and defined $current_chr ) {
835  
836 # check if on the same chromosome
837 if ( $current_chr eq $chromosome ) {
838  
839 # check for overlap
840 if ( $start < $previous_pos ) {
841 print
842 " WARNING: There are overlapping intervals or the file is not sorted by"
843 . " coordinates!\n Compare $chromosome:$start"
844 . " with previous stop position $previous_pos\n";
845  
846 # die if bigwig
847 if ($bigwig) {
848 print STDERR
849 " FATAL: bigWig conversion will fail with overlapping coordinates!\n Fix your file!\n";
850 exit 1;
851 }
852 }
853  
854 # otherwise it is ok
855 $previous_pos = $stop;
856 }
857 else {
858 # new chromosome
859 $current_chr = $chromosome;
860 $previous_pos = $stop;
861 }
862 }
863 else {
864 $current_chr = $chromosome;
865 $previous_pos = $stop;
866 }
867  
868 # collect the score
869 my $score = &{$score_sub}($row);
870 next unless defined $score;
871  
872 # write the feature line
873 $out_fh->printf( $printer, $chromosome, $start, $stop, $score );
874 }
875 }
876  
877 sub fast_convert_to_bedgraph {
878  
879 unless ($chr_index) {
880 $chr_index = $Input->chromo_column;
881 }
882 unless ($stop_index) {
883 $stop_index = $Input->end_column;
884 }
885 unless ( $chr_index and $start_index and $stop_index ) {
886 print " WARNING: coordinate columns not defined!\n";
887 exit 1;
888 }
889 unless ($score_index) {
890 print "WARNING: no score column defined!\n";
891 exit 1;
892 }
893  
894 # use direct file handle and skip the Stream and row objects
895 my $fh = $Input->fh;
896 while ( my $line = $fh->getline ) {
897 chomp $line;
898 my @data = split( /\t/, $line );
899  
900 # working with raw array, need to shift values to compensate
901 # for 1-base indexing of column indexes
902 unshift @data, 0;
903  
904 # adjust start position
905 $data[$start_index]-- unless ($interbase);
906  
907 # write the feature line
908 $out_fh->printf( $printer, $data[$chr_index], $data[$start_index],
909 $data[$stop_index], &{$score_sub}( \@data ) );
910 }
911 }
912  
913 sub calculate_position {
914 my $row = shift;
915 my $start = $row->value($start_index);
916 $start += 1 if $interbase;
917 if ($midpoint) {
918  
919 # calculate midpoint and return
920 my $end = $stop_index ? $row->value($stop_index) : $row->end;
921 $end ||= $start; # in case no end was defined
922 return $start == $end ? $start : int( ( ( $start + $end ) / 2 ) + 0.5 );
923 }
924 else {
925 return $start;
926 }
927 }
928  
929 __END__