script/get_feature_info.pl untested

filter: Statementstmt 0.0% 0 / 296 Branchbran 0.0% 0 / 160 Conditioncond 0.0% 0 / 58 MC/DCmcdc 0.0% 0 / 29 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 596 CC 63 SCAR 47.6
CC
63
Cov
0%
get_attribute_method
380.0
get_gene_length
182.0
get_exon_number
72.0
CRAP 116.3
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 IO::Prompt::Tiny qw(prompt);
10 use Bio::ToolBox::db_helper qw(open_db_connection);
11 use Bio::ToolBox::Data;
12 use Bio::ToolBox::utility qw( format_with_commas parse_list );
13  
14 our $VERSION = '2.00';
15  
16 print "\n This script will collect information for a list of features\n\n";
17  
18 ### Quick help
19 unless (@ARGV) { # when no command line options are present
20 # print SYNOPSIS
21 pod2usage(
22 {
23 '-verbose' => 0,
24 '-exitval' => 1,
25 }
26 );
27 }
28  
29 ### Get command line options and initialize values
30  
31 # Initialize values
32 my ( $infile, $outfile, $database, $attrib_request, $use_type, $gz, $help,
33 $print_version, );
34  
35 # Command line options
36 GetOptions(
37 'i|in=s' => \$infile, # input file
38 'a|attrib=s' => \$attrib_request, # attribute
39 'o|out=s' => \$outfile, # output filename
40 'd|db=s' => \$database, # database name
41 't|type=s' => \$use_type, # force a type
42 'z|gz!' => \$gz, # gzip status
43 'h|help' => \$help, # help
44 'v|version' => \$print_version, # print the version
45 ) or die " unrecognized option(s)!! please refer to the help documentation\n\n";
46  
47 # Print help
48 if ($help) {
49  
50 # print entire POD
51 pod2usage(
52 {
53 '-verbose' => 2,
54 '-exitval' => 1,
55 }
56 );
57 }
58  
59 # Print version
60 if ($print_version) {
61 print " Biotoolbox script get_feature_info.pl, version $VERSION\n";
62 eval {
63 require Bio::ToolBox;
64 my $v = Bio::ToolBox->VERSION;
65 print " Biotoolbox package version $v\n";
66 };
67 exit;
68 }
69  
70 # Check for required values
71 unless ($infile) {
72 $infile = shift @ARGV;
73 }
74 unless ( defined $gz ) { $gz = 0 }
75  
76 ### Load the feature list
77  
78 # load file
79 my $Data = Bio::ToolBox::Data->new( file => $infile )
80 or die " Unable to load data file!\n";
81 printf " Loaded %s features from %s.\n", format_with_commas( $Data->last_row ), $infile;
82  
83 if ($use_type) {
84  
85 # set the general feature type, which will be used as a proxy for individual
86 # feature types in the Data method that looks for the database features.
87 my $f = $Data->feature;
88 if ( defined $f ) {
89 print " Resetting feature type '$f' to requested '$use_type'\n";
90 }
91 $Data->feature($use_type);
92 }
93  
94 # check columns
95 {
96 my $name_i = $Data->name_column;
97 my $id_i = $Data->id_column;
98 my $type_i = $Data->type_column;
99 unless ( defined $name_i or defined $id_i ) {
100 print STDERR
101 " FATAL: unable to identify a name or ID column. Database lookup unlikely to work\n";
102 exit 1;
103 }
104 unless ( defined $type_i or $use_type or $Data->feature ) {
105 print
106 " WARNING: No type column present or type specified. Database lookup may have problems\n";
107 }
108 }
109  
110 ### Establish database connection
111 my $db;
112 if ($database) {
113 if ( $Data->database and $Data->database ne $database ) {
114 print
115 " Using provided database '$database' instead of metadata-specified database\n";
116 }
117  
118 # check if we have a real file
119 if ( -e $database ) {
120 if ( $database =~ /(?: db | database | sqlite )$/xi ) {
121  
122 # looks like maybe a SQLite file
123 $Data->database($database);
124 $db = $Data->open_meta_database or die "unable to open database!\n";
125 }
126 elsif ( $Data->taste_file($database) ) {
127  
128 # looks like a parsable annotation file
129 # parse the file and associate with the table
130 $Data->parse_table(
131 {
132 file => $database,
133 feature =>
134 $Data->feature, # may be explicitly set by use_type above
135 simplify => 0,
136 subfeature => 'exon,cds,utr,codon',
137 }
138 ) or die " unable to parse annotation file '$database'!\n";
139  
140 # this may fail if not everything can be loaded
141 }
142 else {
143 print STDERR " FATAL: unrecognized database file!\n";
144 exit 1;
145 }
146 }
147 else {
148 # maybe the name of a database
149 # attempt to open
150 $Data->database($database);
151 $db = $Data->open_meta_database or die "unable to open database!\n";
152 }
153 }
154 elsif ( $Data->database ) {
155  
156 # use metadata-specified database
157 if ( $Data->database =~ /^Parsed: (.+)$/x ) {
158  
159 # there was a parsed annotation file, try and re-parse it
160 $Data->parse_table(
161 {
162 file => $1,
163 feature => $Data->feature, # may be explicitly set by use_type above
164 simplify => 0,
165 subfeature => 'exon,cds,utr,codon',
166 }
167 )
168 or die
169 " unable to parse annotation file '$1' in metadata!\n try specifying a new database or annoation file\n";
170  
171 # this may fail if not everything can be loaded
172 }
173 else {
174 $db = $Data->open_meta_database or die "unable to open database!\n";
175 }
176 }
177 else {
178 print STDERR " FATAL: No database defined! See help\n";
179 exit 1;
180 }
181  
182 ### Determine the attribute to collect
183  
184 # get the attribute list from the user
185 my @attribute_list = get_attribute_list_from_user();
186  
187 # process the requests
188 collect_attributes_for_list(@attribute_list);
189  
190 ### Output the data
191 # assign file name if necessary
192 unless ($outfile) {
193 $outfile = $infile;
194 }
195  
196 # write the file
197 my $file_success = $Data->write_file(
198 'filename' => $outfile,
199 'gz' => $gz,
200 );
201 if ($file_success) {
202  
203 # success
204 print " Wrote file '$file_success'\n";
205 }
206 else {
207 # failure
208 print " Unable to write output file!\n";
209 }
210 print " That's it!\n";
211  
212 ### Subroutines
213  
214 sub get_attribute_list_from_user {
215  
216 # get the list from the user
217 # either as a command line option or interactively
218  
219 my @list;
220  
221 # provided by command line argument
222 if ($attrib_request) {
223 @list = split /,/, $attrib_request;
224 }
225  
226 # request interactively from user
227 else {
228  
229 # get the list of features to check for examples
230 print " Collecting sample features to generate list of attributes....\n";
231  
232 # get the attributes for a sample of features
233 # store the tag keys in an example hash
234 my %tagexamples;
235 my $stream = $Data->row_stream;
236 for ( 1 .. 50 ) {
237 my $row = $stream->next_row;
238 last unless $row;
239 my $f = $row->feature;
240 next unless $f;
241 my %taghash = $f->attributes();
242 foreach ( keys %taghash ) {
243 $tagexamples{$_} += 1;
244 }
245 }
246  
247 # present list to user
248 print " These are the attributes which may be collected:\n";
249 my $i = 1;
250 my %index2att;
251  
252 # standard attributes for any user
253 foreach (
254 qw(Chromosome Start Stop Strand Score Name Alias Note Type Primary_tag Source
255 Length Midpoint Phase RNA_count Exon_count Gene_length Transcript_length
256 Parent Primary_ID
257 )
258 )
259 {
260 print " $i\t$_\n";
261 $index2att{$i} = $_;
262 $i++;
263 }
264  
265 # specific attributes for these features
266 foreach ( sort { $a cmp $b } keys %tagexamples ) {
267  
268 # all other attributes
269 print " $i\t$_\n";
270 $index2att{$i} = $_;
271 $i++;
272 }
273  
274 # collect the user response
275 my $p = ' Enter the attribute number(s) to collect, comma-delimited or range ';
276 my $answer = prompt($p);
277 my @answers = parse_list($answer);
278  
279 # check the answers
280 foreach (@answers) {
281 if ( exists $index2att{$_} ) {
282 push @list, $index2att{$_};
283 }
284 else {
285 print " unknown response '$_'!\n";
286 }
287 }
288 }
289  
290 return @list;
291 }
292  
293 sub get_attribute_method {
294  
295 # a subroutine to get the appropriate subroutine method
296  
297 my $attrib = shift;
298  
299 # set the appropriate attribute collection subroutine
300 my $method;
301 if ( $attrib =~ /^chromo/i ) {
302 $method = \&get_chromo;
303 }
304 elsif ( $attrib =~ /^start$/i ) {
305 $method = \&get_start;
306 }
307 elsif ( $attrib =~ /^stop$/i ) {
308 $method = \&get_stop;
309 }
310 elsif ( $attrib =~ /^midpoint$/i ) {
311 $method = \&get_midpoint;
312 }
313 elsif ( $attrib =~ /^length$/i ) {
314 $method = \&get_length;
315 }
316 elsif ( $attrib =~ /^gene.?length$/xi ) {
317 $method = \&get_gene_length;
318 }
319 elsif ( $attrib =~ /^transcript.?length$/xi ) {
320 $method = \&get_transcript_length;
321 }
322 elsif ( $attrib =~ /^strand$/i ) {
323 $method = \&get_strand;
324 }
325 elsif ( $attrib =~ /^phase$/i ) {
326 $method = \&get_phase;
327 }
328 elsif ( $attrib =~ /^score$/i ) {
329 $method = \&get_score;
330 }
331 elsif ( $attrib =~ /^rna.?count$/xi ) {
332 $method = \&get_rna_number;
333 }
334 elsif ( $attrib =~ /^exon.?count$/xi ) {
335 $method = \&get_exon_number;
336 }
337 elsif ( $attrib =~ /^parent$/i ) {
338 $method = \&get_parent;
339 }
340 elsif ( $attrib =~ /^primary.?id$/xi ) {
341 $method = \&get_primary_id;
342 }
343 elsif ( $attrib =~ /^name$/i ) {
344 $method = \&get_display_name;
345 }
346 elsif ( $attrib =~ /^source$/i ) {
347 $method = \&get_source;
348 }
349 elsif ( $attrib =~ /^type$/i ) {
350 $method = \&get_type;
351 }
352 elsif ( $attrib =~ /^primary.?tag$/xi ) {
353 $method = \&get_primary_tag;
354 }
355 else {
356 # unrecognized, must be tag key
357 $method = \&get_tag_value;
358 }
359  
360 return $method;
361 }
362  
363 sub collect_attributes_for_list {
364  
365 my @list = @_;
366  
367 # get the attribute method(s)
368 my @methods; # the methods are references to appropriate subroutines
369 foreach (@list) {
370 push @methods, get_attribute_method($_);
371 }
372  
373 # prepare columns
374 my @indices;
375 foreach (@list) {
376 my $i = $Data->add_column($_);
377 push @indices, $i;
378 }
379  
380 print " Retrieving ", join( ", ", @list ), "\n";
381 my $stream = $Data->row_stream;
382 while ( my $row = $stream->next_row ) {
383  
384 my $feature = $row->feature(1);
385  
386 # pass a true value to force the seqfeature lookup
387 if ($feature) {
388  
389 # get the attribute(s)
390 for ( my $i = 0; $i < scalar @list; $i++ ) {
391  
392 # for each request in the list, we will collect the attribute
393 # we'll use the method sub defined in the methods
394 # pass both the feature and the name of the attribute
395 # only the tag value actually needs the name of the attribute
396 my $v = &{ $methods[$i] }( $feature, $list[$i] );
397 $row->value( $indices[$i], $v );
398 }
399 }
400 else {
401 # no feature found, cannot collect attributes
402 # record nulls
403 foreach (@indices) { $row->value( $_, '.' ) }
404 }
405 }
406 }
407  
408 sub get_chromo {
409 my $feature = shift;
410 return '.' unless $feature;
411 return $feature->seq_id || '.';
412 }
413  
414 sub get_start {
415 my $feature = shift;
416 return '.' unless $feature;
417 return $feature->start || '.';
418 }
419  
420 sub get_stop {
421 my $feature = shift;
422 return '.' unless $feature;
423 return $feature->end || '.';
424 }
425  
426 sub get_length {
427 my $feature = shift;
428 return 0 unless $feature;
429 return $feature->length || 0;
430 }
431  
432 sub get_gene_length {
433 my $feature = shift;
434 return 0 unless $feature;
435  
436 # collect all exons or CDSs for every transcript
437 my @exons;
438 my @cdss;
439 foreach my $subfeat ( $feature->get_SeqFeatures() ) {
440  
441 # feature may consist of multiple transcripts
442 if ( $subfeat->primary_tag =~ /exon/i ) {
443 push @exons, $subfeat;
444 }
445 elsif ( $subfeat->primary_tag =~ /utr | untranslated/xi ) {
446 push @cdss, $subfeat;
447 }
448 elsif ( $subfeat->primary_tag =~ /cds/i ) {
449 push @cdss, $subfeat;
450 }
451 elsif ( $subfeat->primary_tag =~ /rna | transcript/xi ) {
452  
453 # an RNA subfeature, keep going down another level
454 foreach my $f ( $subfeat->get_SeqFeatures ) {
455 if ( $f->primary_tag =~ /exon/i ) {
456 push @exons, $f;
457 }
458 elsif ( $f->primary_tag =~ /utr | untranslated/xi ) {
459 push @cdss, $f;
460 }
461 elsif ( $f->primary_tag =~ /cds/i ) {
462 push @cdss, $f;
463 }
464 }
465 }
466 }
467  
468 # Determine which subfeatures to collect
469 # we prefer to use exons because they are easier
470 # if exons are not defined then we'll infer them from CDSs and UTRs
471 my @features_to_check;
472 if (@exons) {
473 @features_to_check = @exons;
474 }
475 elsif (@cdss) {
476 @features_to_check = @cdss;
477 }
478 else {
479 # found neither exons, CDSs, or UTRs
480 # possibly because there were no subfeatures
481 # in this case we just take the whole thing
482 push @features_to_check, $feature;
483 }
484  
485 # Order and collapse the subfeatures
486 # we don't want overlapping features
487 my @sorted_features = map { $_->[1] }
488 sort { $a->[0] <=> $b->[0] }
489 map { [ $_->start, $_ ] } @features_to_check;
490 my @merged;
491 my $current = shift @sorted_features;
492 while ($current) {
493 if (@sorted_features) {
494 my $next = shift @sorted_features;
495 if ( $current->overlaps($next) ) {
496  
497 # overlapping features, so reassign the end point to that of the next
498 $current->end( $next->end );
499 }
500 else {
501 # no overlap, keep current, next becomes current
502 push @merged, $current;
503 $current = $next;
504 }
505 }
506 else {
507 # no more features
508 push @merged, $current;
509 undef $current;
510 }
511 }
512  
513 # calculate the length
514 my $gene_length = 0;
515 foreach my $f (@merged) {
516 $gene_length += $f->length;
517 }
518  
519 # return most appropriate number
520 return $gene_length;
521 }
522  
523 sub get_transcript_length {
524 my $feature = shift;
525 return 0 unless $feature;
526 my $exon_total = 0;
527 my $cds_total = 0;
528 foreach my $subf ( $feature->get_SeqFeatures() ) {
529  
530 # feature may consist of multiple subfeature types
531 # we're only interested in the exon subfeatures, or if those don't
532 # exist, then the CDS subfeatures
533 # ignore all other subfeatures
534  
535 # exon subfeature
536 if ( $subf->primary_tag eq 'exon' ) {
537 $exon_total += $subf->length;
538 }
539  
540 # cds subfeature
541 elsif ( $subf->primary_tag eq 'CDS' ) {
542 $cds_total += $subf->length;
543 }
544 }
545  
546 # return most appropriate number
547 return $exon_total > 0 ? $exon_total : $cds_total;
548 }
549  
550 sub get_midpoint {
551 my $feature = shift;
552 return '.' unless $feature;
553 return ( $feature->start + int( $feature->length / 2 ) ) || '.';
554 }
555  
556 sub get_strand {
557 my $feature = shift;
558 return '.' unless $feature;
559 return $feature->strand || 0;
560 }
561  
562 sub get_phase {
563 my $feature = shift;
564 return '.' unless $feature;
565 return $feature->phase || '.';
566 }
567  
568 sub get_score {
569 my $feature = shift;
570 return '.' unless $feature;
571 return $feature->score || '.';
572 }
573  
574 sub get_rna_number {
575 my $feature = shift;
576 return 0 unless $feature;
577 my $rna_count = 0;
578 foreach my $f ( $feature->get_SeqFeatures ) {
579 if ( $f->primary_tag =~ /rna | transcript/xi ) {
580  
581 # an RNA transcript
582 $rna_count++;
583 }
584 }
585 return $rna_count;
586 }
587  
588 sub get_exon_number {
589 my $feature = shift;
590 return 0 unless $feature;
591 my $exon_count = 0;
592 my $cds_count = 0;
593 foreach my $f ( $feature->get_SeqFeatures ) {
594  
595 # count both exons and CDSs
596 if ( $f->primary_tag =~ /exon/i ) {
597 $exon_count++;
598 }
599 elsif ( $f->primary_tag =~ /cds/i ) {
600 $cds_count++;
601 }
602 elsif ( $f->primary_tag =~ /rna | transcript/xi ) {
603  
604 # an RNA transcript, go one more level
605 foreach my $sf ( $f->get_SeqFeatures ) {
606 if ( $sf->primary_tag =~ /exon/i ) {
607 $exon_count++;
608 }
609 elsif ( $sf->primary_tag =~ /cds/i ) {
610 $cds_count++;
611 }
612 }
613 }
614 }
615  
616 # return exon_count if non-zero, else return cds_count, zero or non-zero
617 return $exon_count ? $exon_count : $cds_count;
618 }
619  
620 sub get_parent {
621 my $feature = shift;
622 return '.' unless $feature;
623  
624 # this is tricky, because it's not always recorded in the SeqFeature object itself
625 # and we can't easily recurse in memory an object and what it is linked to
626 #
627 if ( $feature->has_tag('parent_id') ) {
628  
629 # feature has a parent in a database
630 my @parent_ids = $feature->get_tag_values('parent_id');
631 if ($db) {
632  
633 # looks like we have SeqFeature database
634 # unfortunately we have to do a slow lookup through the database
635 # using the attribute load_id
636 # this seems to be the only way to get to the parent name
637 my @parents;
638 foreach my $id (@parent_ids) {
639 foreach my $p ( $db->get_features_by_attribute( 'load_id' => $id ) ) {
640 push @parents, $p->display_name;
641 }
642 }
643 return join( ',', @parents );
644 }
645 }
646 if ( $feature->has_tag('Parent') ) {
647 my @parents = $feature->get_tag_values('Parent');
648 return join( ',', @parents );
649 }
650 return '.';
651 }
652  
653 sub get_primary_id {
654 my $feature = shift;
655 return $feature->primary_id || '.';
656 }
657  
658 sub get_display_name {
659 my $feature = shift;
660 return $feature->display_name || '.';
661 }
662  
663 sub get_type {
664 my $feature = shift;
665 return $feature->type || $feature->primary_tag || '.';
666 }
667  
668 sub get_primary_tag {
669 my $feature = shift;
670 return $feature->primary_tag || $feature->type || '.';
671 }
672  
673 sub get_source {
674 my $feature = shift;
675 return $feature->source_tag || '.';
676 }
677  
678 sub get_tag_value {
679 my $feature = shift;
680 my $attrib = shift;
681 return '.' unless $feature;
682 if ( $feature->has_tag($attrib) ) {
683 return join( ';', ( $feature->get_tag_values($attrib) ) );
684 }
685 else {
686 return '.';
687 }
688 }
689  
690 __END__