script/get_intersecting_features.pl untested

filter: Statementstmt 0.0% 0 / 223 Branchbran 0.0% 0 / 106 Conditioncond 0.0% 0 / 52 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 441 CC 40 SCAR 40.5
CC
40
Cov
0%
intersect_named_features
156.0
determine_distance
56.0
summarize_found_features
56.0
CRAP 57.6
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 Bio::ToolBox::Data;
10 use Bio::ToolBox::db_helper qw(
11 open_db_connection
12 verify_or_request_feature_types
13 get_chromosome_list
14 );
15 use Bio::ToolBox::utility qw(format_with_commas);
16  
17 our $VERSION = '2.04';
18  
19 print "\n A script to pull out overlapping features\n\n";
20  
21 ### Quick help
22 unless (@ARGV) {
23  
24 # when no command line options are present
25 # print SYNOPSIS
26 pod2usage(
27 {
28 '-verbose' => 0,
29 '-exitval' => 1,
30 }
31 );
32 }
33  
34 ### Command line options
35 my ( $infile, $database, $start, $stop, $extend, $adjustment_position,
36 $reference_position, $outfile, $gz, $help, $print_version, );
37 my @search_features;
38 GetOptions(
39 'i|in=s' => \$infile, # the input nucleosome data file
40 'd|db=s' => \$database, # the name of the database
41 'f|feature=s' => \@search_features, # the feature(s) to look for
42 'b|begin|start=i' => \$start, # the relative start position
43 'e|end|stop=i' => \$stop, # the relative stop position
44 'p|pos=s' =>
45 \$adjustment_position, # the coordinate to make start and stop adjustments
46 'x|extend=i' => \$extend, # extend lookup-feature by this amount
47 'r|ref=s' => \$reference_position, # relative position when calc distance
48 'o|out=s' => \$outfile, # output file name
49 'z|gz!' => \$gz, # compress file
50 'h|help' => \$help, # request help
51 'v|version' => \$print_version, # print the version
52 ) or die " unrecognized option(s)!! please refer to the help documentation\n\n";
53  
54 # Print help
55 if ($help) {
56  
57 # print entire POD
58 pod2usage(
59 {
60 '-verbose' => 2,
61 '-exitval' => 1,
62 }
63 );
64 }
65  
66 # Print version
67 if ($print_version) {
68 print " Biotoolbox script get_intersecting_features.pl, version $VERSION\n";
69 eval {
70 require Bio::ToolBox;
71 my $v = Bio::ToolBox->VERSION;
72 print " Biotoolbox package version $v\n";
73 };
74 exit;
75 }
76  
77 ### Check for required values and assign defaults
78 unless ($infile) {
79 if (@ARGV) {
80 $infile = shift @ARGV;
81 }
82 else {
83 print STDERR " FATAL: no input file! use --help for more information\n";
84 exit 1;
85 }
86 }
87 unless ($reference_position) {
88 $reference_position = 'start';
89 }
90 unless ($adjustment_position) {
91 $adjustment_position = '5';
92 }
93 unless ( defined $gz ) {
94 $gz = 0;
95 }
96 if ( scalar @search_features == 1 and $search_features[0] =~ /,/ ) {
97  
98 # a comma-delimited list of features
99 @search_features = split /,/, shift @search_features;
100 }
101  
102 ### Load the input file
103 my $Data = Bio::ToolBox::Data->new( file => $infile )
104 or die " Unable to load data file!\n";
105 printf " Loaded %s features from $infile.\n", format_with_commas( $Data->last_row );
106  
107 ### Open database connection
108 if ($database) {
109 if ( $Data->database and $Data->database ne $database ) {
110 print " WARNING: provided database '$database' does not match file metadata!\n"
111 . " overriding metadata and using '$database'\n";
112 }
113 $Data->database($database);
114 }
115 elsif ( not $Data->database ) {
116 die "No database defined! See help\n";
117 }
118 my $db = $Data->open_database;
119  
120 ### Identify the Features to Search
121 @search_features = verify_or_request_feature_types(
122 'db' => $db,
123 'feature' => [@search_features],
124 'prompt' => "Enter the number(s) to the intersecting feature(s) to"
125 . " search.\n Enter as comma delimited list and/or range ",
126 );
127  
128 ### Collect the features
129 # search
130 print " Searching for intersecting " . join( ", ", @search_features ) . " features....\n";
131 find_overlapping_features();
132  
133 ### Write output
134 # write data file
135 unless ($outfile) {
136  
137 # overwrite the input file
138 $outfile = $infile;
139 }
140 my $success = $Data->write_file(
141 'filename' => $outfile,
142 'gz' => $gz,
143 );
144 if ($success) {
145 print " Wrote data file '$success'\n";
146 }
147 else {
148 print " Unable to write data file!\n";
149 }
150  
151 ### The End
152  
153 ############################# Subroutines #####################################
154  
155 ### Main starting point to find overlapping features
156 sub find_overlapping_features {
157  
158 if ( $Data->feature_type eq 'coordinate' ) {
159  
160 # we're working with genomic coordinates here
161 intersect_genome_features();
162 }
163 elsif ( $Data->feature_type eq 'named' ) {
164  
165 # we're working with named features
166 intersect_named_features();
167 }
168 else {
169 # unable to identify
170 print STDERR
171 " FATAL: unable to identify feature information columns in source file "
172 . "'$infile'\n No chromosome, start, stop, name, ID, and/or type columns\n";
173 exit 1;
174 }
175 }
176  
177 ### Working with named features
178 sub intersect_named_features {
179  
180 # Named features
181  
182 # prepare new metadata columns
183 my ( $number_i, $name_i, $type_i, $strand_i, $distance_i, $overlap_i ) =
184 generate_new_metadata();
185  
186 # iterate through table
187 my $stream = $Data->row_stream;
188 while ( my $row = $stream->next_row ) {
189  
190 # identify feature first
191 my $feature = $row->feature;
192 unless ($feature) {
193 process_no_feature( $row, $number_i, $name_i, $type_i, $strand_i,
194 $distance_i, $overlap_i );
195 next;
196 }
197  
198 # Establish the region based on the found feature
199 my $region;
200  
201 # extend the region
202 if ($extend) {
203  
204 # we're adding an extension on either side of the feature
205  
206 # establish region
207 $region = $db->segment(
208 $feature->seq_id,
209 $feature->start - $extend,
210 $feature->end + $extend
211 );
212  
213 # this segment will not have a strand, and I can not set it
214 }
215  
216 # specific relative start, stop from indicated position
217 elsif ( defined $start and defined $stop ) {
218  
219 # we'll adjust the coordinates specifically
220 # this is relative to the indicated position
221  
222 # establish region based on the feature's orientation
223 if ( $adjustment_position eq '5' and $feature->strand >= 0 ) {
224  
225 # Watson strand or unstranded
226 $region = $db->segment(
227 $feature->seq_id,
228 $feature->start + $start,
229 $feature->start + $stop
230 );
231 }
232 elsif ( $adjustment_position eq '5' and $feature->strand < 0 ) {
233  
234 # Crick strand
235 $region = $db->segment(
236 $feature->seq_id,
237 $feature->end - $stop,
238 $feature->end - $start
239 );
240 }
241 if ( $adjustment_position eq '3' and $feature->strand >= 0 ) {
242  
243 # Watson strand or unstranded
244 $region = $db->segment(
245 $feature->seq_id,
246 $feature->end + $start,
247 $feature->end + $stop
248 );
249 }
250 elsif ( $adjustment_position eq '3' and $feature->strand < 0 ) {
251  
252 # Crick strand
253 $region = $db->segment(
254 $feature->seq_id,
255 $feature->start - $stop,
256 $feature->start - $start
257 );
258 }
259 elsif ( $adjustment_position eq 'm' and $feature->strand >= 0 ) {
260  
261 # midpoint
262 my $mid = int( ( $feature->start + $feature->end ) / 2 );
263 $region = $db->segment( $feature->seq_id, $mid + $start, $mid + $stop );
264 }
265 elsif ( $adjustment_position eq 'm' and $feature->strand >= 0 ) {
266  
267 # midpoint
268 my $mid = int( ( $feature->start + $feature->end ) / 2 );
269 $region = $db->segment( $feature->seq_id, $mid - $start, $mid - $stop );
270 }
271 }
272  
273 # default is entire region
274 else {
275 # establish region as is
276 $region = $feature->segment();
277  
278 # this segment will have strand
279 }
280  
281 # check region
282 if ($region) {
283  
284 # succesfully established a region, find features
285 $region->start(1) if $region->start <= 0; # sanity check
286 process_region(
287 $region,
288 $feature->strand, # the region may not support strand
289 # so need to pass this separately
290 $row,
291 $number_i,
292 $name_i,
293 $type_i,
294 $strand_i,
295 $distance_i,
296 $overlap_i
297 );
298 }
299 else {
300 # no region defined
301 printf " WARNING: unable to establish region for %s %s\n",
302 $row->type, $row->name;
303  
304 # fill in table anyway
305 process_no_feature( $row, $number_i, $name_i, $type_i, $strand_i,
306 $distance_i, $overlap_i );
307 }
308  
309 }
310  
311 # summarize the findings
312 summarize_found_features($number_i);
313 }
314  
315 ### Working with genomic features
316 sub intersect_genome_features {
317  
318 # prepare new metadata columns
319 my ( $number_i, $name_i, $type_i, $strand_i, $distance_i, $overlap_i ) =
320 generate_new_metadata();
321  
322 # get chromosome list and their lengths
323 # this is to ensure that regions don't go over length
324 my %chrom2length;
325 foreach ( get_chromosome_list($db) ) {
326  
327 # each element is [name, length]
328 $chrom2length{ $_->[0] } = $_->[1];
329 }
330  
331 # iterate through table
332 my $stream = $Data->row_stream;
333 while ( my $row = $stream->next_row ) {
334  
335 # adjust positions as necessary
336 my ( $new_start, $new_stop );
337 if ($extend) {
338  
339 # we're adding an extension on either side of the region
340 $new_start = $row->start - $extend;
341 $new_stop = $row->end + $extend;
342 }
343 elsif ( defined $start and defined $stop ) {
344  
345 # we'll adjust the coordinates specifically
346 # this is relative to the start position
347 $new_start = $row->start + $start;
348 $new_stop = $row->start + $stop;
349 }
350 else {
351 $new_start = $row->start;
352 $new_stop = $row->end;
353 }
354  
355 # check new positions
356 if ( $new_start < 1 ) {
357  
358 # limit to actual start
359 $new_start = 1;
360 }
361 if ( $chrom2length{ $row->seq_id } and $new_stop > $chrom2length{ $row->seq_id } )
362 {
363 # limit to actual length
364 $new_stop = $chrom2length{ $row->seq_id };
365 }
366  
367 # establish region
368 my $region = $db->segment( $row->seq_id, $new_start, $new_stop );
369  
370 # check region
371 if ($region) {
372  
373 # succesfully established a region, find features
374 process_region(
375 $region,
376 $row->strand, # default is 0 if not defined
377 $row,
378 $number_i,
379 $name_i,
380 $type_i,
381 $strand_i,
382 $distance_i,
383 $overlap_i
384 );
385 }
386 else {
387 # no region defined
388 printf " WARNING: unable to establish region for %s:%s..%s\n",
389 $row->seq_id, $row->start, $row->end;
390  
391 # fill in table anyway
392 process_no_feature( $row, $number_i, $name_i, $type_i, $strand_i,
393 $distance_i, $overlap_i );
394 }
395 }
396  
397 # summarize the findings
398 summarize_found_features($number_i);
399 }
400  
401 ### Prepare new columns
402 sub generate_new_metadata {
403  
404 # count of features column
405 my $number_i = $Data->add_column('Number_features');
406  
407 # Name column
408 my $name_i = $Data->add_column('Target_Name');
409 if ( defined $start and defined $stop ) {
410 $Data->metadata( $name_i, 'Start', $start );
411 $Data->metadata( $name_i, 'Stop', $stop );
412 }
413 if ( defined $extend ) {
414 $Data->metadata( $name_i, 'Extend', $extend );
415 }
416  
417 # Type column
418 my $type_i = $Data->add_column('Target_Type');
419  
420 # Strand column
421 my $strand_i = $Data->add_column('Target_Strand');
422  
423 # Distance column
424 my $distance_i = $Data->add_column('Target_Distance');
425 $Data->metadata( $distance_i, 'reference', $reference_position );
426  
427 # Overlap column
428 my $overlap_i = $Data->add_column('Target_Overlap');
429 $Data->metadata( $overlap_i, 'reference', $reference_position );
430  
431 return ( $number_i, $name_i, $type_i, $strand_i, $distance_i, $overlap_i );
432 }
433  
434 ### Prepare new columns
435 sub process_region {
436  
437 my (
438 $region, $region_strand, $row, $number_i, $name_i,
439 $type_i, $strand_i, $distance_i, $overlap_i
440 ) = @_;
441  
442 # look for the requested features
443 my @features = $region->features( -type => [@search_features], );
444  
445 #print " found ", scalar(@features), "\n";
446  
447 # process depending on the number of features found
448 if ( scalar @features == 0 ) {
449  
450 # no features found
451  
452 # put in null data
453 process_no_feature( $row, $number_i, $name_i, $type_i, $strand_i,
454 $distance_i, $overlap_i );
455 }
456  
457 elsif ( scalar @features == 1 ) {
458  
459 # only one feature found, that's perfect
460 my $f = shift @features;
461  
462 # record information
463 $row->value( $number_i, 1 );
464 $row->value( $name_i, $f->display_name );
465 $row->value( $type_i, $f->type );
466 $row->value( $strand_i, $f->strand );
467 $row->value( $distance_i, determine_distance( $region, $region_strand, $f ) );
468 $row->value( $overlap_i, determine_overlap( $region, $region_strand, $f ) );
469 }
470  
471 elsif ( scalar @features > 1 ) {
472  
473 # more than one feature
474 # need to identify the most appropriate one
475 my $f;
476 if ( scalar @features > 1 ) {
477 my %overlap2f;
478 foreach (@features) {
479 my $overlap = determine_overlap( $region, $region_strand, $_ );
480 $overlap2f{$overlap} = $_;
481  
482 # this may overwrite if two or more features have identical
483 # amounts of overlap, but we'll simply use that as a means
484 # of "randomly" selecting one of them ;)
485 # otherwise how else to select one?
486 }
487  
488 # now take the feature with the greatest overlap
489 my $max = ( sort { $b <=> $a } keys %overlap2f )[0];
490 $f = $overlap2f{$max};
491 }
492 else {
493 # now there is only one, one of them must've been tossed because
494 # it was dubious
495 $f = $features[0];
496 }
497  
498 # record the information
499 $row->value( $number_i, scalar(@features) );
500 $row->value( $name_i, $f->display_name );
501 $row->value( $type_i, $f->type );
502 $row->value( $strand_i, $f->strand );
503 $row->value( $distance_i, determine_distance( $region, $region_strand, $f ) );
504 $row->value( $overlap_i, determine_overlap( $region, $region_strand, $f ) );
505 }
506  
507 return;
508 }
509  
510 ### Fill in data table with null data
511 sub process_no_feature {
512 my ( $row, $number_i, $name_i, $type_i, $strand_i, $distance_i, $overlap_i ) = @_;
513  
514 $row->value( $number_i, 0 );
515 $row->value( $name_i, '.' );
516 $row->value( $type_i, '.' );
517 $row->value( $strand_i, 0 );
518 $row->value( $distance_i, '.' );
519 $row->value( $overlap_i, '.' );
520 }
521  
522 ### Calculate the distance between target and reference features
523 sub determine_distance {
524  
525 my ( $reference, $ref_strand, $target ) = @_;
526  
527 # determine distance
528 my $distance;
529  
530 # Calculating the distance between the 5' ends
531 if ( $reference_position eq 'start' ) {
532  
533 # Calculation dependent on identifying the strand
534 # basically calculating distance from target 5' end to reference 5' end
535 if ( $ref_strand >= 0 and $target->strand >= 0 ) {
536  
537 # Both are Watson strand or unstranded
538 $distance = $target->start - $reference->start;
539 }
540 elsif ( $ref_strand >= 0 and $target->strand < 0 ) {
541  
542 # Reference is Watson, target is Crick
543 $distance = $target->end - $reference->start;
544 }
545 elsif ( $ref_strand < 0 and $target->strand >= 0 ) {
546  
547 # Reference is Crick, target is Watson
548 $distance = $target->start - $reference->end;
549 }
550 elsif ( $ref_strand < 0 and $target->strand < 0 ) {
551  
552 # Both are Crick
553 $distance = $target->end - $reference->end;
554 }
555 }
556  
557 # Calculating the distance between the midpoints
558 # since midpoint is equidistant from 5' and 3' ends, strand doesn't matter
559 elsif ( $reference_position eq 'mid' ) {
560 my $reference_mid = ( $reference->end + $reference->start ) / 2;
561 my $target_mid = ( $target->end + $target->start ) / 2;
562 $distance = int( $target_mid - $reference_mid + 0.5 );
563 }
564  
565 return $distance;
566 }
567  
568 ### Calculate the overlap between target and reference features
569 sub determine_overlap {
570 my ( $reference, $ref_strand, $target ) = @_;
571  
572 # apparently, using Bio::RangeI methods on a region doesn't
573 # work (what!!!!????), intersection and overlap_extent fail to
574 # give proper end values, just returns "-end"
575  
576 # the workaround is to just calculate the intersection ourself
577 my ( $istart, $istop );
578 if ( $reference->start <= $target->start ) {
579 $istart = $reference->start;
580 }
581 else {
582 $istart = $target->start;
583 }
584 if ( $reference->end >= $target->end ) {
585 $istop = $reference->end;
586 }
587 else {
588 $istop = $target->end;
589 }
590 return 0 if $istart > $istop;
591 return ($istop - $istart + 1);
592 }
593  
594 sub summarize_found_features {
595 my $number_i = shift;
596  
597 # intialize counts
598 my $none = 0;
599 my $one = 0;
600 my $multiple = 0;
601  
602 # count up
603 $Data->iterate(
604 sub {
605 my $row = shift;
606 if ( $row->value($number_i) == 0 ) {
607 $none++;
608 }
609 elsif ( $row->value($number_i) == 1 ) {
610 $one++;
611 }
612 elsif ( $row->value($number_i) > 1 ) {
613 $multiple++;
614 }
615 }
616 );
617  
618 # print summary
619 printf " $one (%.1f%%) reference features intersected with unique target features\n",
620 ( ( $one / $Data->{'last_row'} ) * 100 )
621 if $one;
622 printf " $none (%.1f%%) reference features intersected with zero target features\n",
623 ( ( $none / $Data->{'last_row'} ) * 100 )
624 if $none;
625 printf
626 " $multiple (%.1f%%) reference features intersected with multiple target features\n",
627 ( ( $multiple / $Data->{'last_row'} ) * 100 )
628 if $multiple;
629 }
630  
631 __END__