blib/lib/Bio/DB/SoapEUtilities/FetchAdaptor/seq.pm untested

filter: Statementstmt 0.0% 0 / 292 Branchbran 0.0% 0 / 102 Conditioncond 0.0% 0 / 47 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 476 CC 52 SCAR 51.8
CC
52
Cov
0%
next_obj
380.0
_read_db_source
272.0
_read_species
110.0
CRAP 177.6
1 # $Id$
2 #
3 # BioPerl module for Bio::DB::SoapEUtilities::FetchAdaptor::seq
4 #
5 # Please direct questions and support issues to <bioperl-l@bioperl.org>
6 #
7 # Cared for by Mark A. Jensen <maj -at- fortinbras -dot- us>
8 #
9 # Copyright Mark A. Jensen
10 #
11 # You may distribute this module under the same terms as perl itself
12  
13 # POD documentation - main docs before the code
14  
15 =head1 NAME
16  
17 Bio::DB::SoapEUtilities::FetchAdaptor::seq - Fetch adaptor for 'seq'
18 efetch SOAP messages
19  
20 =head1 SYNOPSIS
21  
22 Imported by L<Bio::DB::SoapEUtilities::FetchAdaptor> as required.
23  
24 =head1 DESCRIPTION
25  
26 Returns an iterator over L<Bio::Seq> or L<Bio::Seq::RichSeq> objects,
27 depending on the the return type of the C<efetch>. A standard
28 C<efetch> to a sequence database will return a GenBank SOAP result;
29 this will be parsed into rich sequence objects:
30  
31 my $fac = Bio::DB::SoapEUtilities->new;
32 my $seqio = $fac->efetch(-db => 'protein', -id => 730439)->run(-auto_adapt=>1);
33 my $seq = $seqio->next_seq;
34 $seq->species->binomial; # returns 'Bacillus caldolyticus'
35  
36 An C<efetch> with C<-rettype => 'fasta'> will be parsed into
37 L<Bio::Seq> objects (VERY much faster):
38  
39 $seqio = $fac->efetch( -rettype => 'fasta' )->run(-auto_adapt=>1);
40 $seq = $seqio->next_seq;
41 $seq->species; # undef
42 $seq->desc; # kitchen sink
43  
44 To find out the object type returned:
45
46 $class = $seqio->obj_class;
47  
48 as for all L<Bio::DB::SoapEUtilities::FetchAdaptor> objects.
49  
50 =head1 SEE ALSO
51  
52 L<Bio::DB::SoapEUtilities>, L<Bio::DB::SoapEUtilities::FetchAdaptor>
53  
54 =head1 FEEDBACK
55  
56 =head2 Mailing Lists
57  
58 User feedback is an integral part of the evolution of this and other
59 Bioperl modules. Send your comments and suggestions preferably to
60 the Bioperl mailing list. Your participation is much appreciated.
61  
62 bioperl-l@bioperl.org - General discussion
63 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
64  
65 =head2 Support
66  
67 Please direct usage questions or support issues to the mailing list:
68  
69 L<bioperl-l@bioperl.org>
70  
71 rather than to the module maintainer directly. Many experienced and
72 reponsive experts will be able look at the problem and quickly
73 address it. Please include a thorough description of the problem
74 with code and data examples if at all possible.
75  
76 =head2 Reporting Bugs
77  
78 Report bugs to the Bioperl bug tracking system to help us keep track
79 of the bugs and their resolution. Bug reports can be submitted via
80 the web:
81  
82 http://redmine.open-bio.org/projects/bioperl/
83  
84 =head1 AUTHOR - Mark A. Jensen
85  
86 Email maj -at- fortinbras -dot- us
87  
88 =head1 CONTRIBUTORS
89  
90 Much inspiration from L<Bio::SeqIO> and family.
91  
92 =head1 APPENDIX
93  
94 The rest of the documentation details each of the object methods.
95 Internal methods are usually preceded with a _
96  
97 =cut
98  
99 # Let the code begin...
100  
101 package Bio::DB::SoapEUtilities::FetchAdaptor::seq;
102 use strict;
103  
104 use Bio::Root::Root;
105 use Bio::Annotation::Collection;
106 use Bio::Annotation::Comment;
107 use Bio::Annotation::DBLink;
108 use Bio::Annotation::Reference;
109 use Bio::Annotation::SimpleValue;
110 use Bio::Factory::FTLocationFactory;
111 use Bio::SeqFeature::Generic;
112 use Bio::Seq::SeqBuilder;
113 use Bio::Seq::SeqFactory;
114 use Bio::Species;
115  
116 use base qw(Bio::DB::SoapEUtilities::FetchAdaptor Bio::Root::Root);
117  
118 our %VALID_ALPHABET = (
119 'AA' => 'protein',
120 'DNA' => 'dna',
121 'RNA' => 'rna'
122 );
123  
124 our %TYPE_XLT = (
125 'Bio::Seq' => ['TSeqSet','TSeq'],
126 'Bio::Seq::RichSeq' => ['GBSet', 'GBSeq']
127 );
128  
129 sub _initialize {
130 my ($self, @args) = @_;
131 $self->SUPER::_initialize(@args);
132 my ($builder, $seqfac ) = $self->_rearrange( [qw(SEQBUILDER
133 SEQFACTORY)], @args );
134 # choose rich or simple seq based on result
135  
136 my ($t) = keys %{$self->result->som->method};
137 for ($t) {
138 /^GB/ && do {
139 $t = 'GB'; # genbank info
140 $self->{'_obj_class'} = ($seqfac ? $seqfac->type : 'Bio::Seq::RichSeq');
141 last;
142 };
143 /^T/ && do {
144 $t = 'T'; # fasta info
145 $self->{'_obj_class'} = ($seqfac ? $seqfac->type : 'Bio::Seq');
146 last;
147 };
148 $self->throw("FetchAdaptor::seq : unrecognized result elt type '$t', can't parse");
149 }
150
151 $self->{'_builder'} = $builder || Bio::Seq::SeqBuilder->new();
152 $self->{'_builder'}->sequence_factory(
153 $seqfac || Bio::Seq::SeqFactory->new( -type => $self->{'_obj_class'} )
154 );
155 $self->{'_locfac'} = Bio::Factory::FTLocationFactory->new();
156 $self->{'_idx'} = 1;
157 1;
158 }
159  
160 sub rewind { shift->{'_idx'} = 1 }
161  
162 sub obj_class { shift->{'_obj_class'} }
163  
164 sub builder { shift->{'_builder'} };
165  
166 sub locfac { shift->{'_locfac'} };
167  
168 sub next_obj {
169 my $self = shift;
170 my $t = $TYPE_XLT{$$self{_obj_class}};
171
172 my $stem = "//$$t[0]/[".$self->{'_idx'}."]";
173 my $som = $self->result->som;
174 my $seqid;
175 return unless defined $som->valueof("$stem");
176  
177 my $get = sub { $som->valueof("$stem/$$t[1]_".shift) };
178 # speed up (?) by caching top-level data hash
179 my $toplev = $som->valueof("$stem");
180 my $get_tl = sub { $toplev->{"$$t[1]_".shift} };
181  
182 my %params = (-verbose => $self->verbose);
183  
184 if ($t->[0] =~ /^T/) {
185 $params{'-display_id'} = $get_tl->('accver');
186 $params{'-primary_id'} = $get_tl->('gi');
187 $params{'-length'} = $get_tl->('length');
188 $params{'-desc'} = $get_tl->('defline');
189 $params{'-seq'} = $get_tl->('sequence');
190 $params{'-alphabet'} = $get_tl->('seqtype') || undef;
191 $self->builder->add_slot_value(%params);
192 ($self->{_idx})++;
193 if ( !$self->builder->want_object ) { # skip
194 $self->builder->make_object;
195 goto &next_obj;
196 }
197 else {
198 return $self->builder->make_object;
199 }
200 }
201 elsif ($t->[0] =~ /^GB/) {
202 # source, id, alphabet
203 $params{'-display_id'} = $get_tl->('locus');
204 $params{'-length'} = $get_tl->('length');
205 $get_tl->('moltype') =~ /(AA|[DR]NA)/;
206 $params{'-alphabet'} = $VALID_ALPHABET{$1} || '';
207
208 # molecule, division, dates
209 $params{'-molecule'} = $get_tl->('moltype');
210 $params{'-is_circular'} = ($get_tl->('topology') eq 'circular');
211 $params{'-division'} = $get->('division');
212 $params{'-dates'} = [$get_tl->('create-date'), $get_tl->('update-date')];
213  
214 $self->builder->add_slot_value(%params);
215 %params = ();
216
217 if ( !$self->builder->want_object ) { # skip this
218 $self->builder->make_object;
219 ($self->{_idx})++;
220 goto &next_obj;
221 }
222
223 # accessions, version, pid, description
224 $get_tl->('accession-version') =~ /.*\.([0-9]+)$/;
225 $params{'-version'} = $params{'-seq_version'} = $1;
226 my @secondary_ids;
227 my @ids = $get->('other-seqids/GBSeqid');
228 foreach (@ids) {
229 /^gi\|([0-9]+)/ && do {
230 $seqid = $params{'-primary_id'} = $1;
231 $params{'-accession_number'} = $_; # correct?
232 next;
233 };
234 do { # else
235 push @secondary_ids, $_;
236 next;
237 };
238 }
239 $params{'-secondary_accessions'} = \@secondary_ids;
240
241 $params{'-desc'} = $get->('definition');
242
243 # sequence
244 if ( $self->builder->want_slot('seq')) {
245 $params{'-seq'} = $get->('sequence');
246 }
247
248 # keywords
249 if ($get->('keywords')) {
250 my @kw;
251 foreach my $kw ($som->valueof("$stem/GBSeq_keywords/*")) {
252 push @kw, $kw;
253 }
254 $params{'-keywords'} = join(' ',@kw);
255 }
256
257 $self->builder->add_slot_value(%params);
258 %params = ();
259
260 my $ann;
261 # annotations
262 if ($self->builder->want_slot('annotation')) {
263 $ann = Bio::Annotation::Collection->new();
264 # references
265 if ($get->('references')) {
266 $ann->add_Annotation('reference', $_)
267 for _read_references($stem,$som);
268 }
269
270 # comment
271 if ($get_tl->('comment')) {
272 $ann->add_Annotation('comment',
273 Bio::Annotation::Comment->new(
274 -tagname => 'comment',
275 -text => $get_tl->('comment')
276 )
277 );
278 }
279 # project
280 if ( $get_tl->('project') ) {
281 $ann->add_Annotation('project',
282 Bio::Annotation::SimpleValue->new(
283 -value => $get_tl->('project')
284 )
285 );
286 }
287 # contig
288 if ($get_tl->('contig')) {
289 $ann->add_Annotation('contig',
290 Bio::Annotation::SimpleValue->new(
291 -value => $get_tl->('contig')
292 )
293 );
294 }
295
296 # dblink
297 if ($get_tl->('source-db')) {
298 _read_db_source($ann, $get);
299 }
300
301 $self->builder->add_slot_value(-annotation => $ann);
302 }
303  
304 # features
305 my $feats;
306 if ($self->builder->want_slot('features')) {
307 $feats = _read_features($stem,$som,$self->locfac,$get);
308 $self->builder->add_slot_value(
309 -features => $feats
310 );
311 }
312
313 # organism data
314 if ( $self->builder->want_slot('species') && $get_tl->('source') ) {
315 my $sp = _read_species($get);
316 if ($sp && !$sp->ncbi_taxid) {
317 my ($src) = grep { $_->primary_tag eq 'source' } @$feats;
318 if ($src) {
319 foreach my $val ($src->get_tag_values('db_xref')) {
320 $sp->ncbi_taxid(substr($val,6)) if index($val,"taxon:") == 0;
321 }
322 }
323 }
324 $self->builder->add_slot_value( -species => $sp );
325 }
326 }
327 else {
328 $self->throw("FetchAdaptor::seq : unrecognized result elt type '$t', can't parse");
329 }
330
331 ($self->{_idx})++;
332 return $self->builder->make_object;
333 }
334  
335 # mostly ripped from Bio::SeqIO::genbank...
336  
337 sub _read_species {
338 my ($get) = @_;
339
340 my @unkn_names = ('other', 'unknown organism', 'not specified', 'not shown',
341 'Unspecified', 'Unknown', 'None', 'unclassified',
342 'unidentified organism', 'not supplied');
343 # dictionary of synonyms for taxid 32644
344 my @unkn_genus = ('unknown','unclassified','uncultured','unidentified');
345 # all above can be part of valid species name
346  
347 my( $sub_species, $species, $genus, $sci_name, $common,
348 $abbr_name, $organelle);
349  
350 $sci_name = $get->('organism') || return;
351  
352 # parse out organelle, common name, abbreviated name if present;
353 # this should catch everything, but falls back to
354 # entire GBSeq_taxonomy element just in case
355 if ($get->('source') =~ m{^
356 (mitochondrion|chloroplast|plastid)?
357 \s*(.*?)
358 \s*(?: \( (.*?) \) )?\.?
359 $}xms ) {
360 ($organelle, $abbr_name, $common) = ($1, $2, $3); # optional
361 } else {
362 $abbr_name = $get->('source'); # nothing caught; this is a backup!
363 }
364  
365 # Convert data in classification lines into classification array.
366 my @class = split(/; /, $get->('taxonomy'));
367  
368 # do we have a genus?
369 my $possible_genus = quotemeta($class[-1])
370 . ($class[-2] ? "|" . quotemeta($class[-2]) : '');
371 if ($sci_name =~ /^($possible_genus)/) {
372 $genus = $1;
373 ($species) = $sci_name =~ /^$genus\s+(.+)/;
374 }
375 else {
376 $species = $sci_name;
377 }
378  
379 # is this organism of rank species or is it lower?
380 # (we don't catch everything lower than species, but it doesn't matter -
381 # this is just so we abide by previous behaviour whilst not calling a
382 # species a subspecies)
383 if ($species && $species =~ /subsp\.|var\./) {
384 ($species, $sub_species) = $species =~ /(.+)\s+((?:subsp\.|var\.).+)/;
385 }
386  
387 # Don't make a species object if it's empty or "Unknown" or "None"
388 # return unless $genus and $genus !~ /^(Unknown|None)$/oi;
389 # Don't make a species object if it belongs to taxid 32644
390 my $src = $get->('source');
391 return unless ($species || $genus) and
392 !grep { $_ eq $src } @unkn_names;
393  
394 # Bio::Species array needs array in Species -> Kingdom direction
395 push(@class, $sci_name);
396 @class = reverse @class;
397  
398 my $make = Bio::Species->new();
399 $make->scientific_name($sci_name);
400 $make->classification(@class) if @class > 0;
401 $make->common_name( $common ) if $common;
402 $make->name('abbreviated', $abbr_name) if $abbr_name;
403 $make->organelle($organelle) if $organelle;
404  
405 return $make;
406 }
407  
408 sub next_seq { shift->next_obj }
409  
410 sub _read_references {
411 my ($stem, $som) = @_;
412 my @ret;
413 for ( my $i = 1; $som->valueof($stem."/GBSeq_references/[$i]"); $i++ ) {
414 my $get = sub {
415 $som->valueof($stem."/GBSeq_references/[$i]/GBReference_".shift )
416 };
417 my %params;
418 $params{'-title'} = $get->('title');
419 $params{'-pubmed'} = $get->('pubmed');
420 $params{'-medline'} = $get->('pubmed');
421 $params{'-journal'} = $get->('journal');
422 $params{'-comment'} = $get->('remark');
423 $params{'-consortium'} = $get->('consortium');
424  
425 my $pos = $get->('position');
426 $pos and $pos =~ /^([0-9]+)[.]+([0-9]+)$/;
427 $params{'-start'} = $1;
428 $params{'-end'} = $2;
429 $params{'-gb_reference'} = $get->('reference');
430 $params{'-authors'} = '';
431 foreach my $author ( $get->('authors/*') ) {
432 $params{'-authors'} .= " $author";
433 }
434 push @ret, Bio::Annotation::Reference->new(
435 -tagname => 'reference',
436 %params);
437 }
438 return @ret;
439 }
440  
441 sub _read_features {
442 my ($stem, $som, $locfac, $get_pri) = @_;
443 my @ret;
444 my $seqid = $get_pri->('primary-accession');
445  
446 for ( my $i = 1; $get_pri->("feature-table/[$i]"); $i++ ) {
447 my $get = sub {
448 $som->valueof($stem."/GBSeq_feature-table/[$i]/GBFeature_".shift )
449 };
450 my $loc;
451 my $sf = Bio::SeqFeature::Generic->direct_new();
452 if ($get->('location')) {
453 # may have to parse GBIntervals instead here...
454 $loc = $locfac->from_string( $get->('location') );
455 if ($seqid && !($loc->is_remote)) {
456 $loc->seq_id($seqid);
457 }
458 }
459 $sf->location($loc);
460 $sf->seq_id($seqid);
461 $sf->primary_tag($get->('key'));
462 $sf->source_tag('EMBL/GenBank/SwissProt');
463 # fill other fields using $sf->add_tag_value...
464
465 # qualifiers are name => value pairs. add as tags
466 # to this feature
467 if ($get->('quals')) {
468 foreach ($get->('quals/*')) {
469 $sf->add_tag_value( $_->{'GBQualifier_name'},
470 $_->{'GBQualifier_value'} );
471 }
472 }
473 if ($get->('partial5')) {
474 $sf->add_tag_value( 'is_partial5',
475 $get->('partial5') eq 'true' ? 1 : 0)
476 }
477 if ($get->('partial3')) {
478 $sf->add_tag_value( 'is_partial3',
479 $get->('partial3') eq 'true' ? 1 : 0)
480 }
481 push @ret, $sf;
482 }
483 return \@ret;
484 }
485  
486 sub _read_db_source {
487 my ($ann, $get) = @_;
488 my $dbsource = $get->('source-db');
489 # ripped mainly from Bio::SeqIO::genbank...
490 # deal with UniProKB dbsources
491 if( $dbsource =~
492 s/(UniProt(?:KB)?|swissprot):\s+locus\s+(\S+)\,[^.]+\.\s*// ) {
493 $ann->add_Annotation
494 ('dblink',
495 Bio::Annotation::DBLink->new
496 (-primary_id => $2,
497 -database => $1,
498 -tagname => 'dblink'));
499 if( $dbsource =~ s/created:\s+([^.]+)\.\s*// ) {
500 $ann->add_Annotation
501 ('swissprot_dates',
502 Bio::Annotation::SimpleValue->new
503 (-tagname => 'date_created',
504 -value => $1));
505 }
506 while( $dbsource =~
507 s/\s+(sequence|annotation)\s+
508 updated:\s+([^.]+)\.\s*//xg ) {
509 $ann->add_Annotation
510 ('swissprot_dates',
511 Bio::Annotation::SimpleValue->new
512 (-tagname => 'date_updated',
513 -value => $2));
514 }
515 $dbsource =~ s/\n/ /g;
516 if ( $dbsource =~ s/xrefs:\s+
517 ((?:\S+,\s+)+\S+)\s+xrefs/xrefs/x ) {
518 # will use $i to determine even or odd
519 # for swissprot the accessions are paired
520 my $i = 0;
521 for my $dbsrc ( split(/,\s+/,$1) ) {
522 if( $dbsrc =~ /(\S+)\.(\d+)/ ||
523 $dbsrc =~ /(\S+)/ ) {
524 my ($id,$version) = ($1,$2);
525 $version ='' unless defined $version;
526 my $db;
527 if( $id =~ /^\d\S{3}/) {
528 $db = 'PDB';
529 } else {
530 $db = ($i++ % 2 ) ? 'GenPept' : 'GenBank';
531 }
532 $ann->add_Annotation
533 ('dblink',
534 Bio::Annotation::DBLink->new
535 (-primary_id => $id,
536 -version => $version,
537 -database => $db,
538 -tagname => 'dblink'));
539 }
540 }
541 }
542 elsif ( $dbsource =~ s/xrefs:\s+(.+)\s+xrefs/xrefs/i ) {
543 # download screwed up and ncbi didn't put
544 # acc in for gi numbers
545 my $i = 0;
546 for my $id ( split(/\,\s+/,$1) ) {
547 my ($acc,$db);
548 if( $id =~ /gi:\s+(\d+)/ ) {
549 $acc= $1;
550 $db = ($i++ % 2 ) ? 'GenPept' : 'GenBank';
551 } elsif( $id =~ /pdb\s+accession\s+(\S+)/ ) {
552 $acc= $1;
553 $db = 'PDB';
554 } else {
555 $acc= $id;
556 $db = '';
557 }
558 $ann->add_Annotation
559 ('dblink',
560 Bio::Annotation::DBLink->new
561 (-primary_id => $acc,
562 -database => $db,
563 -tagname => 'dblink'));
564 }
565 } else {
566 warn "Cannot match $dbsource";
567 }
568 if( $dbsource =~ s/xrefs\s+\(non\-sequence\s+databases\):\s+
569 ((?:\S+,\s+)+\S+)//x ) {
570 for my $id ( split(/\,\s+/,$1) ) {
571 my $db;
572 # quote from Bio::SeqIO::genbank:
573 # this is because GenBank dropped the spaces!!!
574 # I'm sure we're not going to get this right
575 $db = substr($id,0,index($id,':'));
576 $id = substr($id,index($id,':')+1);
577 $ann->add_Annotation
578 ('dblink',
579 Bio::Annotation::DBLink->new
580 (-primary_id => $id,
581 -database => $db,
582 -tagname => 'dblink'));
583 }
584 }
585 }
586 else {
587 if( $dbsource =~ /^(\S*?):?\s*accession\s+(\S+)\.(\d+)/ ) {
588 my ($db,$id,$version) = ($1,$2,$3);
589 $ann->add_Annotation
590 ('dblink',
591 Bio::Annotation::DBLink->new
592 (-primary_id => $id,
593 -version => $version,
594 -database => $db || 'GenBank',
595 -tagname => 'dblink'));
596 } elsif ( $dbsource =~ /(\S+)([\.:])(\d+)/ ) {
597 my ($id, $db, $version);
598 if ($2 eq ':') {
599 ($db, $id) = ($1, $3);
600 } else {
601 ($db, $id, $version) = ('GenBank', $1, $3);
602 }
603 $ann->add_Annotation('dblink',
604 Bio::Annotation::DBLink->new(
605 -primary_id => $id,
606 -version => $version,
607 -database => $db,
608 -tagname => 'dblink')
609 );
610 }
611 else {
612 warn "Unrecognized DBSOURCE data: $dbsource";
613 }
614 }
615 return 1;
616 }
617 1;
618  
619 __END__