Boulder/Genbank.pm untested

filter: Statementstmt 0.0% 0 / 414 Branchbran 0.0% 0 / 140 Conditioncond 0.0% 0 / 80 MC/DCmcdc 0.0% 0 / 47 Subroutinesub 0.0% 0 / 53 Podpod 0.0% 0 / 27 totaltotal 0.0% 0 / 761 CC 71 SCAR 42.5
CC
71
Cov
0%
parse
306.0
get_entries
132.0
fetch_next
90.0
CRAP 70.0
1 package Boulder::Genbank;
2  
3 use strict;
4 use Boulder::Stream;
5 use Stone::GB_Sequence;
6 use Carp;
7 use vars qw(@ISA $VERSION);
8 @ISA = qw(Boulder::Stream);
9  
10 $VERSION = 1.10;
11  
12 # Hard-coded defaults - must modify for your site
13 use constant YANK => '/usr/local/bin/yank';
14  
15 #use constant BATCH_URI => '/cgi-bin/Entrez/qserver.cgi/result';
16 #use constant BATCH_URI => '/htbin-post/Entrez/query';
17 use constant HOST => 'www.ncbi.nlm.nih.gov';
18 use constant BATCH_URI => '/IEB/ToolBox/XML/xbatch.cgi';
19  
20 # Genbank entry parsing constants
21 # (may need to adjust!)
22 my $KEYCOL=0;
23 my $VALUECOL=12;
24 my $FEATURECOL=5;
25 my $FEATUREVALCOL=21;
26  
27 =head1 NAME
28  
29 Boulder::Genbank - Fetch Genbank data records as parsed Boulder Stones
30  
31 =head1 SYNOPSIS
32  
33 use Boulder::Genbank
34
35 # network access via Entrez
36 $gb = Boulder::Genbank->newFh( qw(M57939 M28274 L36028) );
37  
38 while ($data = <$gb>) {
39 print $data->Accession;
40  
41 @introns = $data->features->Intron;
42 print "There are ",scalar(@introns)," introns.\n";
43 $dna = $data->Sequence;
44 print "The dna is ",length($dna)," bp long.\n";
45  
46 my @features = $data->features(-type=>[ qw(Exon Source Satellite) ],
47 -pos=>[90,310] );
48 foreach (@features) {
49 print $_->Type,"\n";
50 print $_->Position,"\n";
51 print $_->Gene,"\n";
52 }
53 }
54  
55 # another syntax
56 $gb = new Boulder::Genbank(-accessor=>'Entrez',
57 -fetch => [qw/M57939 M28274 L36028/]);
58  
59 # local access via Yank
60 $gb = new Boulder::Genbank(-accessor=>'Yank',
61 -fetch=>[qw/M57939 M28274 L36028/]);
62 while (my $s = $gb->get) {
63 # etc.
64 }
65  
66 # parse a file of Genbank records
67 $gb = new Boulder::Genbank(-accessor=>'File',
68 -fetch => '/usr/local/db/gbpri3.seq');
69 while (my $s = $gb->get) {
70 # etc.
71 }
72  
73 # parse flatfile records yourself
74 open (GB,"/usr/local/db/gbpri3.seq");
75 local $/ = "//\n";
76 while (<GB>) {
77 my $s = Boulder::Genbank->parse($_);
78 # etc.
79 }
80  
81 =head1 DESCRIPTION
82  
83 Boulder::Genbank provides retrieval and parsing services for NCBI
84 Genbank-format records. It returns Genbank entries in L<Stone>
85 format, allowing easy access to the various fields and values.
86 Boulder::Genbank is a descendent of Boulder::Stream, and provides a
87 stream-like interface to a series of Stone objects.
88  
89 >> IMPORTANT NOTE <<
90  
91 As of January 2002, NCBI has changed their Batch Entrez interface. I
92 have modified Boulder::Genbank so as to use a "demo" interface, which
93 fixes things, but this isn't guaranteed in the long run.
94  
95 I have written to NCBI, and they may fix this -- or they may not.
96  
97 >> IMPORTANT NOTE <<
98  
99 Access to Genbank is provided by three different I<accessors>, which
100 together give access to remote and local Genbank databases. When you
101 create a new Boulder::Genbank stream, you provide one of the three
102 accessors, along with accessor-specific parameters that control what
103 entries to fetch. The three accessors are:
104  
105 =over 4
106  
107 =item Entrez
108  
109 This provides access to NetEntrez, accessing the most recent Genbank
110 information directly from NCBI's Web site. The parameters passed to
111 this accessor are either a series of Genbank accession numbers, or an
112 Entrez query (see http://www.ncbi.nlm.nih.gov/Entrez/linking.html).
113 If you provide a list of accession numbers, the stream will return a
114 series of stones corresponding to the numbers. Otherwise, if you
115 provided an Entrez query, the entries returned will be in the order
116 returned by Entez.
117  
118 =item File
119  
120 This provides access to local Genbank entries by reading from a flat file
121 (typically one of the .seq files downloadable from NCBI's Web site).
122 The stream will return a Stone corresponding to each of the entries in
123 the file, starting from the top of the file and working downward. The
124 parameter in this case is the path to the local file.
125  
126 =item Yank
127  
128 This provides access to local Genbank entries using Will Fitzhugh's
129 Yank program. Yank provides fast indexed access to a Genbank flat
130 file using the accession number as the key. The parameter passed to
131 the Yank accessor is a list of accession numbers. Stones will be
132 returned in the requested order. By default the yank binary lives in
133 /usr/local/bin/yank. To support other locations, you may define the
134 environment variable YANK to contain the full path.
135  
136 =back
137  
138 It is also possible to parse a single Genbank entry from a text string
139 stored in a scalar variable, returning a Stone object.
140  
141 =head2 Boulder::Genbank methods
142  
143 This section lists the public methods that the I<Boulder::Genbank>
144 class makes available.
145  
146 =over 4
147  
148 =item new()
149  
150 # Network fetch via Entrez, with accession numbers
151 $gb=new Boulder::Genbank(-accessor => 'Entrez',
152 -fetch => [qw/M57939 M28274 L36028/]);
153  
154 # Same, but shorter and uses -> operator
155 $gb = Boulder::Genbank->new qw(M57939 M28274 L36028);
156  
157 # Network fetch via Entrez, with a query
158  
159 # Network fetch via Entrez, with a query
160 $query = 'Homo sapiens[Organism] AND EST[Keyword]';
161 $gb=new Boulder::Genbank(-accessor => 'Entrez',
162 -fetch => $query);
163  
164 # Local fetch via Yank, with accession numbers
165 $gb=new Boulder::Genbank(-accessor => 'Yank',
166 -fetch => [qw/M57939 M28274 L36028/]);
167  
168 # Local fetch via File
169 $gb=new Boulder::Genbank(-accessor => 'File',
170 -fetch => '/usr/local/genbank/gbpri3.seq');
171  
172 The new() method creates a new I<Boulder::Genbank> stream on the
173 accessor provided. The three possible accessors are B<Entrez>,
174 B<Yank> and B<File>. If successful, the method returns the stream
175 object. Otherwise it returns undef.
176  
177 new() takes the following arguments:
178  
179 -accessor Name of the accessor to use
180 -fetch Parameters to pass to the accessor
181 -proxy Path to an HTTP proxy, used when using
182 the Entrez accessor over a firewall.
183  
184 Specify the accessor to use with the B<-accessor> argument. If not
185 specified, it defaults to B<Entrez>.
186  
187 B<-fetch> is an accessor-specific argument. The possibilities are:
188  
189 For B<Entrez>, the B<-fetch> argument may point to a scalar, in which
190 case it is interpreted as an Entrez query string. See
191 http://www.ncbi.nlm.nih.gov/Entrez/linking.html for a description of
192 the query syntax. Alternatively, B<-fetch> may point to an array
193 reference, in which case it is interpreted as a list of accession
194 numbers to retrieve. If B<-fetch> points to a hash, it is interpreted
195 as extended information. See L<"Extended Entrez Parameters"> below.
196  
197 For B<Yank>, the B<-fetch> argument must point to an array reference
198 containing the accession numbers to retrieve.
199  
200 For B<File>, the B<-fetch> argument must point to a string-valued
201 scalar, which will be interpreted as the path to the file to read
202 Genbank entries from.
203  
204 For Entrez (and Entrez only) Boulder::Genbank allows you to use a
205 shortcut syntax in which you provde new() with a list of accession
206 numbers:
207  
208 $gb = new Boulder::Genbank('M57939','M28274','L36028');
209  
210 =item newFh()
211  
212 This works like new(), but returns a filehandle. To recover each
213 GenBank record read from the filehandle with the <> operator:
214  
215 $fh = Boulder::GenBank->newFh('M57939','M28274','L36028');
216 while ($record = <$fh>) {
217 print $record->asString;
218 }
219  
220 =item get()
221  
222 The get() method is inherited from I<Boulder::Stream>, and simply
223 returns the next parsed Genbank Stone, or undef if there is nothing
224 more to fetch. It has the same semantics as the parent class,
225 including the ability to restrict access to certain top-level tags.
226  
227 The object returned is a L<Stone::GB_Sequence> object, which is a
228 descendent of L<Stone>.
229  
230 =item put()
231  
232 The put() method is inherited from the parent Boulder::Stream class,
233 and will write the passed Stone to standard output in Boulder format.
234 This means that it is currently not possible to write a
235 Boulder::Genbank object back into Genbank flatfile form.
236  
237 =back
238  
239 =head2 Extended Entrez Parameters
240  
241 The Entrez accessor recognizes extended parameters that allow you the
242 ability to customize the search. Instead of passing a query string
243 scalar or a list of accession numbers as the B<-fetch> argument, pass
244 a hash reference. The hashref should contain one or more of the
245 following keys:
246  
247 =over
248  
249 =item B<-query>
250  
251 The Entrez query to process.
252  
253 =item B<-accession>
254  
255 The list of accession numbers to fetch, as an array ref.
256  
257 =item B<-db>
258  
259 The database to search. This is a single-letter database code
260 selected from the following list:
261  
262 m MEDLINE
263 p Protein
264 n Nucleotide
265 s Popset
266  
267 =item B<-proxy>
268  
269 An HTTP proxy to use. For example:
270  
271 -proxy => http://www.firewall.com:9000
272  
273 If you think you need this, get the correct URL from your system
274 administrator.
275  
276 =back
277  
278 As an example, here's how to search for ESTs from Oryza sativa that
279 have been entered or modified since 1999.
280  
281 my $gb = new Boulder::Genbank( -accessor=>Entrez,
282 -query=>'Oryza sativa[Organism] AND EST[Keyword] AND 1999[MDAT]',
283 -db => 'n'
284 });
285  
286 =head1 METHODS DEFINED BY THE GENBANK STONE OBJECT
287  
288 Each record returned from the Boulder::Genbank stream defines a set of
289 methods that correspond to features and other fields in the Genbank
290 flat file record. L<Stone::GB_Sequence> gives the full details, but
291 they are listed for reference here:
292  
293 =head2 $length = $entry->length
294  
295 Get the length of the sequence.
296  
297 =head2 $start = $entry->start
298  
299 Get the start position of the sequence, currently always "1".
300  
301 =head2 $end = $entry->end
302  
303 Get the end position of the sequence, currently always the same as the
304 length.
305  
306 =head2 @feature_list = $entry->features(-pos=>[50,450],-type=>['CDS','Exon'])
307  
308 features() will search the entry feature list for those features that
309 meet certain criteria. The criteria are specified using the B<-pos>
310 and/or B<-type> argument names, as shown below.
311  
312 =over 4
313  
314 =item -pos
315  
316 Provide a position or range of positions which the feature must
317 B<overlap>. A single position is specified in this way:
318  
319 -pos => 1500; # feature must overlap postion 1500
320  
321 or a range of positions in this way:
322  
323 -pos => [1000,1500]; # 1000 to 1500 inclusive
324  
325 If no criteria are provided, then features() returns all the features,
326 and is equivalent to calling the Features() accessor.
327  
328 =item -type, -types
329  
330 Filter the list of features by type or a set of types. Matches are
331 case-insensitive, so "exon", "Exon" and "EXON" are all equivalent.
332 You may call with a single type as in:
333  
334 -type => 'Exon'
335  
336 or with a list of types, as in
337  
338 -types => ['Exon','CDS']
339  
340 The names "-type" and "-types" can be used interchangeably.
341  
342 =head2 $seqObj = $entry->bioSeq;
343  
344 Returns a L<Bio::Seq> object from the Bioperl project. Dies with an
345 error message unless the Bio::Seq module is installed.
346  
347 =back
348  
349 =head1 OUTPUT TAGS
350  
351 The tags returned by the parsing operation are taken from the NCBI
352 ASN.1 schema. For consistency, they are normalized so that the
353 initial letter is capitalized, and all subsequent letters are
354 lowercase. This section contains an abbreviated list of the most
355 useful/common tags. See "The NCBI Data Model", by James Ostell and
356 Jonathan Kans in "Bioinformatics: A Practical Guide to the Analysis
357 of Genes and Proteins" (Eds. A. Baxevanis and F. Ouellette), pp
358 121-144 for the full listing.
359  
360 =head2 Top-Level Tags
361  
362 These are tags that appear at the top level of the parsed Genbank
363 entry.
364  
365 =over 4
366  
367 =item Accession
368  
369 The accession number of this entry. Because of the vagaries of the
370 Genbank data model, an entry may have multiple accession numbers
371 (e.g. after a merging operation). Accession may therefore be a
372 multi-valued tag.
373  
374 Example:
375
376 my $accessionNo = $s->Accession;
377  
378 =item Authors
379  
380 The list of authors, as they appear on the AUTHORS line of the Genbank
381 record. No attempt is made to parse them into individual authors.
382  
383 =item Basecount
384  
385 The nucleotide basecount for the entry. It is presented as a Boulder
386 Stone with keys "a", "c", "t" and "g". Example:
387  
388 my $A = $s->Basecount->A;
389 my $C = $s->Basecount->C;
390 my $G = $s->Basecount->G;
391 my $T = $s->Basecount->T;
392 print "GC content is ",($G+$C)/($A+$C+$G+$T),"\n";
393  
394 =item Blob
395  
396 The entire flatfile record as an unparsed chunk of text (a "blob").
397 This is a handy way of reassembling the record for human inspection.
398  
399 =item Comment
400  
401 The COMMENT line from the Genbank record.
402  
403 =item Definition
404  
405 The DEFINITION line from the Genbank record, unmodified.
406  
407 =item Features
408  
409 The FEATURES table. This is a complex stone object with multiple
410 subtags. See the L<"The Features Tag"> for details.
411  
412  
413 =item Journal
414  
415 The JOURNAL line from the Genbank record, unmodified.
416  
417 =item Keywords
418  
419 The KEYWORDS line from the Genbank record, unmodified. No attempt is
420 made to parse the keywords into separate values.
421  
422 Example:
423  
424 my $keywords = $s->Keywords
425  
426 =item Locus
427  
428 The LOCUS line from the Genbank record. It is not further parsed.
429  
430 =item Medline, Nid
431  
432 References to other database accession numbers.
433  
434 =item Organism
435  
436 The taxonomic name of the organism from which this entry was
437 derived. This line is taken from the Genbank entry unmodified. See
438 the NCBI data model documentation for an explanation of their
439 taxonomic syntax.
440  
441 =item Reference
442  
443 The REFERENCE line from the Genbank entry. There are often multiple
444 Reference lines. Example:
445  
446 my @references = $s->Reference;
447  
448 =item Sequence
449  
450 The DNA or RNA sequence of the entry. This is presented as a single
451 lower-case string, with all base numbers and formatting characters
452 removed.
453  
454 =item Source
455  
456 The entry's SOURCE field; often giving clues on how the sequencing was
457 performed.
458  
459 =item Title
460  
461 The TITLE field from the paper describing this entry, if any.
462  
463 =back
464  
465 =head2 The Features Tag
466  
467 The Features tag points to a Stone record that contains multiple
468 subtags. Each subtag is the name of a feature which points, in turn,
469 to a Stone that describes the feature's location and other attributes.
470 The full list of feature is beyond this document, but the following
471 are the features that are most often seen:
472  
473 Cds a CDS
474 Intron an intron
475 Exon an exon
476 Gene a gene
477 Mrna an mRNA
478 Polya_site a putative polyadenylation signal
479 Repeat_unit a repetitive region
480 Source More information about the organism and cell
481 type the sequence was derived from
482 Satellite a microsatellite (dinucleotide repeat)
483  
484 Each feature will contain one or more of the following subtags:
485  
486 =over 4
487  
488 =item DB_xref
489  
490 A cross-reference to another database in the form
491 DB_NAME:accession_number. See the NCBI Web site for a description of
492 these cross references.
493  
494 =item Evidence
495  
496 The evidence for this feature, either "experimental" or "predicted".
497  
498 =item Gene
499  
500 If the feature involves a gene, this will be the gene's name (or one
501 of its names). This subtag is often seen in "Gene" and Cds features.
502  
503 Example:
504  
505 foreach ($s->Features->Cds) {
506 my $gene = $_->Gene;
507 my $position = $_->Position;
508 Print "Gene $gene ($position)\n";
509 }
510  
511 =item Map
512  
513 If the feature is mapped, this provides a map position, usually as a
514 cytogenetic band.
515  
516 =item Note
517  
518 A grab-back for various text notes.
519  
520 =item Number
521  
522 When multiple features of this type occur, this field is used to
523 number them. Ordinarily this field is not needed because
524 Boulder::Genbank preserves the order of features.
525  
526 =item Organism
527  
528 If the feature is Source, this provides the source organism.
529  
530 =item Position
531  
532 The position of this feature, usually expresed as a range
533 (1970..1975).
534  
535 =item Product
536  
537 The protein product of the feature, if applicable, as a text string.
538  
539 =item Translation
540  
541 The protein translation of the feature, if applicable.
542  
543 =back
544  
545 =head1 SEE ALSO
546  
547 L<Boulder>, L<Boulder::Blast>
548  
549 =head1 AUTHOR
550  
551 Lincoln Stein <lstein@cshl.org>.
552  
553 Copyright (c) 1997-2000 Lincoln D. Stein
554  
555 This library is free software; you can redistribute it and/or modify
556 it under the same terms as Perl itself. See DISCLAIMER.txt for
557 disclaimers of warranty.
558  
559 =head1 EXAMPLE GENBANK OBJECT
560  
561 The following is an excerpt from a moderately complex Genbank Stone.
562 The Sequence line and several other long lines have been truncated for readability.
563  
564 Authors=Spritz,R.A., Strunk,K., Surowy,C.S.O., Hoch,S., Barton,D.E. and Francke,U.
565 Authors=Spritz,R.A., Strunk,K., Surowy,C.S. and Mohrenweiser,H.W.
566 Locus=HUMRNP7011 2155 bp DNA PRI 03-JUL-1991
567 Accession=M57939
568 Accession=J04772
569 Accession=M57733
570 Keywords=ribonucleoprotein antigen.
571 Sequence=aagcttttccaggcagtgcgagatagaggagcgcttgagaaggcaggttttgcagcagacggcagtgacagcccag...
572 Definition=Human small nuclear ribonucleoprotein (U1-70K) gene, exon 10 and 11.
573 Journal=Nucleic Acids Res. 15, 10373-10391 (1987)
574 Journal=Genomics 8, 371-379 (1990)
575 Nid=g337441
576 Medline=88096573
577 Medline=91065657
578 Features={
579 Polya_site={
580 Evidence=experimental
581 Position=1989
582 Gene=U1-70K
583 }
584 Polya_site={
585 Position=1990
586 Gene=U1-70K
587 }
588 Polya_site={
589 Evidence=experimental
590 Position=1992
591 Gene=U1-70K
592 }
593 Polya_site={
594 Evidence=experimental
595 Position=1998
596 Gene=U1-70K
597 }
598 Source={
599 Organism=Homo sapiens
600 Db_xref=taxon:9606
601 Position=1..2155
602 Map=19q13.3
603 }
604 Cds={
605 Codon_start=1
606 Product=ribonucleoprotein antigen
607 Db_xref=PID:g337445
608 Position=join(M57929:329..475,M57930:183..245,M57930:358..412, ...
609 Gene=U1-70K
610 Translation=MTQFLPPNLLALFAPRDPIPYLPPLEKLPHEKHHNQPYCGIAPYIREFEDPRDAPPPTR...
611 }
612 Cds={
613 Codon_start=1
614 Product=ribonucleoprotein antigen
615 Db_xref=PID:g337444
616 Evidence=experimental
617 Position=join(M57929:329..475,M57930:183..245,M57930:358..412, ...
618 Gene=U1-70K
619 Translation=MTQFLPPNLLALFAPRDPIPYLPPLEKLPHEKHHNQPYCGIAPYIREFEDPR...
620 }
621 Polya_signal={
622 Position=1970..1975
623 Note=putative
624 Gene=U1-70K
625 }
626 Intron={
627 Evidence=experimental
628 Position=1100..1208
629 Gene=U1-70K
630 }
631 Intron={
632 Number=10
633 Evidence=experimental
634 Position=1100..1181
635 Gene=U1-70K
636 }
637 Intron={
638 Number=9
639 Evidence=experimental
640 Position=order(M57937:702..921,1..1011)
641 Note=2.1 kb gap
642 Gene=U1-70K
643 }
644 Intron={
645 Position=order(M57935:272..406,M57936:1..284,M57937:1..599, <1..>1208)
646 Gene=U1-70K
647 }
648 Intron={
649 Evidence=experimental
650 Position=order(M57935:284..406,M57936:1..284,M57937:1..599, <1..>1208)
651 Note=first gap-0.14 kb, second gap-0.62 kb
652 Gene=U1-70K
653 }
654 Intron={
655 Number=8
656 Evidence=experimental
657 Position=order(M57935:272..406,M57936:1..284,M57937:1..599, <1..>1181)
658 Note=first gap-0.14 kb, second gap-0.62 kb
659 Gene=U1-70K
660 }
661 Exon={
662 Number=10
663 Evidence=experimental
664 Position=1012..1099
665 Gene=U1-70K
666 }
667 Exon={
668 Number=11
669 Evidence=experimental
670 Position=1182..(1989.1998)
671 Gene=U1-70K
672 }
673 Exon={
674 Evidence=experimental
675 Position=1209..(1989.1998)
676 Gene=U1-70K
677 }
678 Mrna={
679 Product=ribonucleoprotein antigen
680 Position=join(M57928:358..668,M57929:319..475,M57930:183..245, ...
681 Gene=U1-70K
682 }
683 Mrna={
684 Product=ribonucleoprotein antigen
685 Citation=[2]
686 Evidence=experimental
687 Position=join(M57928:358..668,M57929:319..475,M57930:183..245, ...
688 Gene=U1-70K
689 }
690 Gene={
691 Position=join(M57928:207..719,M57929:1..562,M57930:1..577, ...
692 Gene=U1-70K
693 }
694 }
695 Reference=1 (sites)
696 Reference=2 (bases 1 to 2155)
697 =
698  
699 =cut
700  
701 # new() takes named parameters:
702 # -accessor=> Reference to an object class that will return a series of
703 # Genbank records. Predefined objects include 'Yank', 'Entrez' and 'File'.
704 # (defaults to 'Entrez').
705 # -fetch=> Parameters to pass to the subroutine. Can be a list of accession numbers
706 # or an entrez query.
707 # -out=> Output filehandle. Defaults to STDOUT.
708 #
709 # If you don't use named parameters, then will assume method 'yank' on
710 # a list of accession numbers.
711 # e.g.
712 # $gb = new Boulder::Genbank(-accessor=>'Yank',-fetch=>[qw/M57939 M28274 L36028/]);
713 sub new {
714 my($package,@parameters) = @_;
715 # superclass constructor
716 my($self) = $package->SUPER::new();
717
718 # figure out whether parameters are named. Look for
719 # an initial '-'
720 my %parameters;
721  
722 if ($parameters[0]=~/^-/) {
723 %parameters = @parameters;
724 $self->{accessor} = $parameters{'-accessor'} || 'Entrez';
725 $self->{OUT} = $parameters{'-out'} || \*STDOUT;
726 $self->{format} = $parameters{'-format'};
727 } else {
728 $self->{accessor}='Entrez';
729 $parameters{-fetch} = \@parameters;
730 }
731  
732 $self->{format} ||= 'stone';
733 $parameters{-format} = $self->{format};
734 $self->{accessor} = new {$self->{accessor}}(\%parameters);
735
736 return bless $self,$package;
737 }
738  
739 sub read_record {
740 my($self,@tags) = @_;
741 my($s);
742 my $query = $self->{query};
743  
744 if (wantarray) {
745 my(@result);
746 while (!$self->{EOF}) {
747 $s = $self->read_one_record(@tags);
748 next unless $s;
749 next if $query && !(&$query);
750 push(@result,$s);
751 }
752 return @result;
753 }
754  
755 # we get here if in a scalar context
756 while (!$self->{EOF}) {
757 $s = $self->read_one_record(@tags);
758 next unless $s;
759 return $s unless $query;
760 return $s if &$query;
761 }
762 return undef;
763 }
764  
765 sub parse {
766 my $self = shift;
767 my $record = shift;
768 return unless $record;
769  
770 my $tags = shift;
771 my %ok;
772 %ok = map {$_ => 1} @$tags if ref($tags) eq 'ARRAY';
773
774 my($s,@lines,$line,$accumulated,$key,$keyword,$value,$feature,@features);
775
776 $s = Stone::GB_Sequence->new;
777 @lines = split("\n",$record);
778
779 foreach $line (@lines) {
780
781 if ($line=~/^ACCESSION\s+(.+)/) {
782 foreach ($1=~/(\S+)/g) {
783 $self->_addToStone('Accession',$_,$s,\%ok);
784 }
785 next;
786 }
787  
788 # special case for the VERSION
789 if ($line=~/^VERSION/) {
790 my @vernid = split(/\s+/,$line);
791 my ($junk,$tmp)=split(/:/,$vernid[2]);
792 $vernid[2]='g'.$tmp;
793 $self->_addToStone('Version',$vernid[1],$s,\%ok);
794 $self->_addToStone('Nid',$vernid[2],$s,\%ok);
795 next;
796 }
797
798 # special case for the features table
799 if ($line=~/^FEATURES/..$line=~/^ORIGIN/) {
800 undef $keyword;
801
802 if ($line=~/^FEATURES/) {
803 undef @features;
804 next;
805 }
806  
807 if ($line =~ /^(BASE COUNT|ORIGIN)/) {
808 push(@features,$feature) if $feature;
809 $self->_addFeaturesToStone(\@features,_trim($'),$s,\%ok) if @features;
810 undef @features;
811 undef $feature;
812 next if $line =~ /^BASE COUNT/;
813  
814 # special case for the sequence itself
815 if ($line=~/^ORIGIN/) {
816 # next line added by Luca Toldo
817 $self->_addToStone('Blob',$record,$s,\%ok);
818 $self->_addToStone($key,$accumulated,$s,\%ok) if $key;
819 last;
820 }
821 }
822  
823 my($featurelabel) = _trim(substr($line,$FEATURECOL,$FEATUREVALCOL-$FEATURECOL));
824 my($featurevalue) = _trim(substr($line,$FEATUREVALCOL));
825 if ($featurelabel) {
826 push(@features,$feature) if $feature;
827 $feature = {'label'=>$featurelabel,'value'=>$featurevalue};
828 } else {
829 $feature->{'value'} .= $featurevalue;
830 }
831 next;
832 }
833
834 $keyword = _trim(substr($line,0,$VALUECOL-1));
835 $value = _trim(substr($line,$VALUECOL));
836
837 if ($keyword && $key) {
838 $self->_addToStone($key,_trim($accumulated),$s,\%ok);
839 $accumulated = $value;
840 next;
841 }
842 $accumulated .= " $value";
843 } continue {
844 $key = $keyword if $keyword;
845 }
846
847 my($sequence) = $record=~/\nORIGIN[^\n]*\n(.+)\\?\\?/s;
848  
849 # $sequence=~s/[\s0-9-]+//g; # remove white space and numbers
850 # $sequence =~ s/^\s*\d+\s//mg; # remove leading numbers and whitespace
851 # $sequence =~ s/(\S{1,10}) /$1/g; # remove spacer
852 $sequence =~ s/^.{9,10}//mg; # remove leading numbers and whitespace
853 $sequence =~ s/(.{10}) /$1/g; # remove spacers
854 $sequence =~ s/\n//g;
855 $self->_addToStone('Sequence',$sequence,$s,\%ok);
856 return $s;
857 }
858  
859 sub read_one_record {
860 my($self,@tags) = @_;
861 my(%ok);
862
863 my $accessor = $self->{'accessor'};
864 my $record = $accessor->fetch_next();
865 unless ($record) {
866 $self->{EOF}++;
867 return undef;
868 }
869  
870 return $record unless $self->{format} eq 'stone';
871 return $self->parse($record,\@tags);
872 }
873  
874 sub _trim {
875 my($v) = @_;
876 $v=~s/^\s+//;
877 $v=~s/\s+$//;
878 return $v;
879 }
880  
881 sub _canonicalize {
882 my $h = shift;
883 substr($h,0)=~tr/a-z/A-Z/;
884 substr($h,1,length($h)-1)=~tr/A-Z/a-z/;
885 $h;
886 }
887  
888 sub _addToStone {
889 my($self,$label,$value,$stone,$ok) = @_;
890 return unless !%{$ok} || $ok->{$label};
891 $stone->insert(_canonicalize($label),$value);
892 }
893  
894 sub _addFeaturesToStone {
895 my($self,$features,$basecount,$stone,$ok) = @_;
896  
897 # first add the basecount
898 if (!%{$ok} || $ok->{'BASECOUNT'}) {
899 my(%counts) = $basecount=~/(\d+)\s+([gatcGATC])/g;
900 %counts = map { uc $_ } reverse %counts;
901 $stone->insert('Basecount',new Stone(%counts));
902 }
903
904 if (!%{$ok} || $ok->{'FEATURES'}) {
905 # now add the features
906 my($f) = new Stone;
907 foreach (@$features) {
908 my($p) = new Stone;
909 my($q) = $_->{'value'};
910 my($label) = _canonicalize($_->{'label'});
911 my($position) = $q=~m!^([^/\s]+)!;
912 my @qualifiers = $q=~m@/(\w+)=(.+?)(?=\"|/\w+=|$)@g; # slower but ?better
913 my %qualifiers;
914 while (my($key,$value) = splice(@qualifiers,0,2)) {
915 $value =~ s/^\s*\"//; # trim off extra space and quotes
916 $value =~ s/\"\s*$//;
917 $value =~ s/^\s+//; # trim off extra space and quotes
918 $value =~ s/\s+$//;
919 $value =~ s/\s+//g if uc($key) eq 'TRANSLATION'; # get rid of spaces in protein translation
920 $p->insert(_canonicalize($key)=>$value);
921 }
922 $p->insert('Position'=>$position);
923 $f->insert($label=>$p);
924 undef $p;
925 }
926 $stone->insert('Features',$f);
927 }
928 }
929  
930 # ----------------------------------------------------------------------------------------
931 # -------------------------- DEFINITION OF ACCESSOR OBJECTS ------------------------------
932 package GenbankAccessor;
933 use Carp;
934  
935 sub new {
936 my($class,@parameters) = @_;
937 croak "GenbankAccessor::new: Abstract class\n";
938 }
939  
940 sub fetch_next {
941 my($self) = @_;
942 croak "GenbankAccessor::fetch_next: Abstract class\n";
943 }
944  
945 sub DESTROY {
946 }
947  
948 package Yank;
949 use strict;
950 use Carp;
951 use vars '@ISA';
952  
953 @ISA=qw(GenbankAccessor);
954 my $YANK = $ENV{YANK} || Boulder::Genbank::YANK();
955  
956 sub new {
957 my($package,$param) = @_;
958 croak "Yank::new(): need at least one Genbank acccession number" unless $param;
959 croak "Yank::new(): yank executable not found" unless -x $YANK;
960 $param->{-fetch} ||= $param->{-param}; # for backward compatibility
961 $param->{-fetch} || croak "Provide list of accession numbers to yank";
962 my @accession = @{$param->{-fetch}};
963 my $tmpfile = "/usr/tmp/yank$$";
964 open (TMP,">$tmpfile") || croak "Yank::new(): couldn't open tmpfile $tmpfile for write: $!";
965 print TMP join("\n",@accession),"\n";
966 close TMP;
967 open(YANK,"$YANK -b < $tmpfile |") || croak "Yank::new(): couldn't open pipe from yank: $!";
968 return bless {'tmpfile'=>$tmpfile,'fh'=>\*YANK},$package;
969 }
970  
971 sub fetch_next {
972 my($self) = @_;
973 return undef unless $self->{'fh'};
974 local($/) = "//\n";
975 my($line);
976 my($fh) = $self->{'fh'};
977 chomp($line = <$fh>);
978 return $line;
979 }
980  
981 sub DESTROY {
982 my($self) = shift;
983 close $self->{'fh'} if $self->{'fh'};
984 unlink $self->{'tmpfile'} if $self->{'tmpfile'}
985 }
986  
987 package File;
988 use vars '@ISA';
989 use Symbol;
990 use Carp;
991  
992 @ISA=qw(GenbankAccessor);
993  
994 sub new {
995 my($package,$param) = @_;
996 my $path = $param->{-fetch} || $param->{-path} || $param->{-param};
997 my $fh;
998 if (!$path) {
999 $fh = \*ARGV;
1000 } elsif (ref $path eq 'GLOB') {
1001 $fh = $path;
1002 } else {
1003 $fh = Symbol::gensym;
1004 open ($fh,$path) or croak "File::new(): couldn't open $path: $!";
1005 }
1006 return bless {'fh'=>$fh},$package;
1007 }
1008  
1009 sub fetch_next {
1010 my $self = shift;
1011 return undef unless $self->{'fh'};
1012 local($/)="//\n";
1013 my $line;
1014 my $fh = $self->{'fh'};
1015 $line = <$fh>;
1016 chomp $line if $line;
1017 return $line;
1018 }
1019  
1020 package Entrez;
1021 use Carp;
1022 use vars '@ISA';
1023 use IO::Socket;
1024 use CGI 'escape';
1025  
1026 # used by Entrez accessor, may need to change in the future
1027 use constant ENTREZ_HOST => 'www.ncbi.nlm.nih.gov';
1028 use constant QUERY_URI => '/entrez/utils/pmqty.fcgi';
1029 use constant BATCH_URI => '/entrez/utils/pmfetch.fcgi';
1030 use constant XBATCH_URI => '/IEB/ToolBox/XML/xbatch.cgi';
1031  
1032 use constant PROTO => 'HTTP/1.0';
1033 use constant CRLF => "\r\n";
1034 use constant MAX_ENTRIES => 10_000;
1035  
1036 @ISA=qw(GenbankAccessor);
1037  
1038 sub new {
1039 my($package,$param) = @_;
1040 croak "Entrez::new(): usage [list of accession numbers] or {args => values}"
1041 unless $param;
1042 my $self = bless {},ref($package) || $package;
1043  
1044 $self->{query} = $param->{-query};
1045 $self->{accession} = $param->{-fetch} || $param->{-param};
1046 $self->{db} = $param->{-db} || 'n';
1047 $self->{format} = $param->{-format} || 'stone';
1048 $self->{proxy} = $param->{-proxy};
1049 $self->{limit} = $param->{-limit};
1050  
1051 if ($self->{query}) {
1052 $self->{accession} = $self->get_accessions($self->{query});
1053 } elsif ($self->{accession}) {
1054 my @accessions = ref $self->{accession} ? @{$self->{accession}} : ($self->{accession});
1055 $self->{accession} = \@accessions;
1056 } else {
1057 croak "Must provide a 'query' or 'accession' argument" unless $self->{query} || $self->{accession} ;
1058 }
1059 $self;
1060 }
1061  
1062 sub fetch_next {
1063 my $self = shift;
1064  
1065 # if any additional records are left, then return them
1066 if ($self->{'records'} && @{$self->{'records'}}) {
1067 my $data = shift @{$self->{'records'}};
1068 if ($data=~/\S/) {
1069 $self->_cleanup(\$data);
1070 return $data;
1071 } else {
1072 $self->{'records'} = [];
1073 }
1074 }
1075  
1076 my $format = $self->{format};
1077  
1078 local ($/) = $format eq 'fasta' ? "\n>" : "//\n";
1079 # if we have a socket open, then read a record
1080 if ($self->{'socket'}) {
1081 if (my $data = $self->_getline) {
1082 $self->_cleanup(\$data);
1083 return $data;
1084 } elsif (!$self->{accession} || @{$self->{accession}} == 0) { # nothing more to do
1085 return;
1086 }
1087 }
1088  
1089 die "Must provide either a list of accession numbers or an Entrez query"
1090 unless $self->{accession} || $self->{query};
1091  
1092 return unless $self->get_entries;
1093  
1094 my $data = $self->_getline;
1095 $self->_cleanup(\$data);
1096 return $data;
1097 }
1098  
1099 sub _cleanup {
1100 my ($self,$d) = @_;
1101 $$d =~ s/\A\s+//;
1102 $$d=~s!//\n$!!;
1103 return unless $self->{format} eq 'fasta';
1104 chomp $$d;
1105 substr($$d,0,0)='>' unless $$d =~/^>/;
1106 }
1107  
1108 sub get_accessions {
1109 my $self = shift;
1110 my $query = shift;
1111 my $sock = $self->_build_connection(ENTREZ_HOST) or return;
1112  
1113 # bug here: assume that the server will give us everything when we ask for 1 billion entries
1114 my $request = $self->_build_post(ENTREZ_HOST,
1115 QUERY_URI,
1116 undef,
1117 sprintf("db=%s&dispmax=%d&report=gen&mode=text&tool=boulder&term=%s",$self->db,$self->limit, escape($query)));
1118  
1119 print $sock $request;
1120 my $status = $self->_read_header($sock);
1121 return unless $status == 200;
1122  
1123 local $/ = ' ';
1124 my $line = $sock->getline;
1125 chomp $line;
1126 warn "*** ENTREZ: $line ***" unless $line =~ /^\d+$/;
1127 my @accessions = $line;
1128 while (defined ($line = $sock->getline)) {
1129 chomp $line;
1130 push @accessions,$line;
1131 }
1132 return \@accessions;
1133 }
1134  
1135 sub db {
1136 my $self = shift;
1137 my $db = $self->{db} || 'n';
1138 my $translated = { m => 'medline',
1139 p => 'protein',
1140 n => 'nucleotide',
1141 s => 'popset' }->{$db};
1142 $translated || $db;
1143 }
1144  
1145 # BUG: one billion = infinity
1146 sub limit {
1147 shift->{limit} || 1_000_000_000;
1148 }
1149  
1150 sub _build_connection {
1151 my $self = shift;
1152 my $host = shift;
1153 my ($hostent,$peer,$peerport);
1154  
1155 if (my $proxy = $self->{proxy}) {
1156 $proxy =~ m!^http://([^/]+)/?! or return;
1157 $hostent = $1;
1158 } else {
1159 $hostent = $host;
1160 }
1161
1162 ($peer,$peerport) = split(':',$hostent);
1163 $peerport ||= 'http(80)';
1164  
1165 my $sock = IO::Socket::INET->new(
1166 PeerAddr => $peer,
1167 PeerPort => $peerport,
1168 Proto => 'tcp'
1169 );
1170  
1171 $sock;
1172 }
1173  
1174 sub _build_post {
1175 my $self = shift;
1176 my ($host,$uri,$type,$param) = @_;
1177  
1178 my $path = $self->{proxy} ? "http://$host$uri" : $uri;
1179 $type ||= 'application/x-www-form-urlencoded';
1180 my $length = length($param);
1181 my $request = join (CRLF,
1182 "POST $path ".PROTO,
1183 "User-agent: Mozilla/5.0 [en] (PalmOS)",
1184 "Content-Type: $type",
1185 "Content-Length: $length",
1186 CRLF
1187 );
1188 $request.$param;
1189 }
1190  
1191 sub _read_header {
1192 my $self = shift;
1193 my $sock = shift;
1194 local $/ = CRLF.CRLF;
1195 my $header = $sock->getline;
1196 return 500 unless $header;
1197 return 500 unless $header =~ /^HTTP\/[\d.]+ (\d+)/;
1198 $1;
1199 }
1200  
1201 sub get_entries {
1202 my $self = shift;
1203 my $format = $self->{format};
1204  
1205 my $sock = $self->_build_connection(ENTREZ_HOST) or return;
1206  
1207 # create the multipart form...
1208 my $db = $self->{'db'};
1209 my $boundary = '-' x 30 . int rand(10E14);
1210 my $name = 'Content-Disposition: form-data; name=';
1211 my %canned = ('db' => $db,
1212 'FORMAT' => $format eq 'fasta' ? 1 : 0,
1213 'REQUEST_TYPE' => $self->{accession} ? 'LIST_OF_GIS' : 'ADVANCED_QUERY',
1214 'ORGNAME' => '',
1215 'LIST_ORG' => '(None)',
1216 'QUERY' => "$self->{query}\r\n",
1217 'SAVETO' => 'YES',
1218 'NOHEADER' => 'YES',
1219 );
1220  
1221 my @records = map {qq(Content-Disposition: form-data; name="$_"\r\n\r\n$canned{$_}\r\n)} keys %canned;
1222  
1223 if (my $a = $self->{accession}) {
1224 my @accessions = splice(@$a,0,MAX_ENTRIES);
1225 return unless @accessions;
1226 my $accessions = join "\n",@accessions;
1227 push @records,
1228 qq{Content-Disposition: form-data; name="UID"; filename="accession.txt"\r\nContent-type: text/plain\r\n\r\n$accessions\r\n};
1229 }
1230  
1231 my $content = "$boundary\r\n" . join("$boundary\r\n",@records) . "$boundary--\r\n";
1232  
1233 my $request = $self->_build_post(ENTREZ_HOST,
1234 XBATCH_URI,
1235 "multipart/form-data; boundar=$boundary",
1236 $content);
1237  
1238 print $sock $request;
1239  
1240 local($/) = CRLF . CRLF;
1241  
1242 my $header = $sock->getline;
1243 return unless $header;
1244 return unless $header =~ /^HTTP\/[\d.]+ 200/;
1245  
1246 $/ = "\n";
1247 my $line = $sock->getline;
1248  
1249 # this handles the case of Batch Entrez complaining that we're trying to
1250 # get too many sequences at once!
1251 if ($line =~ /exceed limit/) {
1252 my @accessions;
1253 while ($_ = $sock->getline) {
1254 chomp;
1255 push @accessions,$_;
1256 }
1257 delete $self->{query};
1258 $self->{accession} = \@accessions;
1259 return $self->get_entries; # horrible recursion here!
1260 } else {
1261 while ($line =~ /(\*\*\*\* |WARNING: |ERROR: )(.+)/) {
1262 warn "**** GENBANK $1: $2\n";
1263 $line = $sock->getline;
1264 }
1265 }
1266 $self->{bufferedline} = $line;
1267 if ($format eq 'fasta') {
1268 return unless $line =~ /^>/;
1269 } else {
1270 return unless $line =~ /LOCUS/;
1271 }
1272  
1273 $self->{socket} = $sock;
1274 return 1;
1275 }
1276  
1277 sub _getline {
1278 my $l = $_[0]->{socket}->getline;
1279 if ($_[0]->{bufferedline}) {
1280 $l = "$_[0]->{bufferedline}$l";
1281 delete $_[0]->{bufferedline};
1282 }
1283 return $l;
1284 }
1285  
1286 1;
1287  
1288 __END__