FAST/Bio/DB/Taxonomy/flatfile.pm untested

filter: Statementstmt 0.0% 0 / 211 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 90 MC/DCmcdc 0.0% 0 / 55 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 446 CC 34 SCAR 43.0
CC
34
Cov
0%
_build_index
210.0
get_taxon
42.0
get_taxonids
20.0
CRAP 73.8
1 #
2 # BioPerl module for FAST::Bio::DB::Taxonomy::flatfile
3 #
4 # Please direct questions and support issues to <bioperl-l@bioperl.org>
5 #
6 # Cared for by Jason Stajich <jason-at-bioperl-dot-org>
7 #
8 # Copyright Jason Stajich
9 #
10 # You may distribute this module under the same terms as perl itself
11  
12 # POD documentation - main docs before the code
13  
14 =head1 NAME
15  
16 FAST::Bio::DB::Taxonomy::flatfile - An implementation of FAST::Bio::DB::Taxonomy
17 which uses local flat files
18  
19 =head1 SYNOPSIS
20  
21 use FAST::Bio::DB::Taxonomy;
22  
23 my $db = FAST::Bio::DB::Taxonomy->new(-source => 'flatfile',
24 -nodesfile => $nodesfile,
25 -namesfile => $namefile);
26  
27 =head1 DESCRIPTION
28  
29 This is an implementation which uses local flat files and the DB_File
30 module RECNO data structures to manage a local copy of the NCBI
31 Taxonomy database.
32  
33 Required database files can be obtained from
34 ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdump.tar.gz
35  
36 =head1 FEEDBACK
37  
38 =head2 Mailing Lists
39  
40 User feedback is an integral part of the evolution of this and other
41 Bioperl modules. Send your comments and suggestions preferably to
42 the Bioperl mailing list. Your participation is much appreciated.
43  
44 bioperl-l@bioperl.org - General discussion
45 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
46  
47 =head2 Support
48  
49 Please direct usage questions or support issues to the mailing list:
50  
51 I<bioperl-l@bioperl.org>
52  
53 rather than to the module maintainer directly. Many experienced and
54 reponsive experts will be able look at the problem and quickly
55 address it. Please include a thorough description of the problem
56 with code and data examples if at all possible.
57  
58 =head2 Reporting Bugs
59  
60 Report bugs to the Bioperl bug tracking system to help us keep track
61 of the bugs and their resolution. Bug reports can be submitted via
62 the web:
63  
64 https://redmine.open-bio.org/projects/bioperl/
65  
66 =head1 AUTHOR - Jason Stajich
67  
68 Email jason-at-bioperl-dot-org
69  
70 =head1 CONTRIBUTORS
71  
72 Sendu Bala: bix@sendu.me.uk
73  
74 =head1 APPENDIX
75  
76 The rest of the documentation details each of the object methods.
77 Internal methods are usually preceded with a _
78  
79 =cut
80  
81 # Let the code begin...
82  
83 package FAST::Bio::DB::Taxonomy::flatfile;
84 use vars qw($DEFAULT_INDEX_DIR $DEFAULT_NODE_INDEX $DEFAULT_NAME2ID_INDEX $DEFAULT_ID2NAME_INDEX
85 $NCBI_TAXONOMY_HOSTNAME $DEFAULT_PARENT_INDEX
86 $NCBI_TAXONOMY_FILE @DIVISIONS);
87 use strict;
88 use FAST::Bio::Taxon;
89 use DB_File;
90  
91 use constant SEPARATOR => ':';
92  
93 $DEFAULT_INDEX_DIR = '/tmp';
94 $DEFAULT_NODE_INDEX = 'nodes';
95 $DEFAULT_NAME2ID_INDEX = 'names2id';
96 $DEFAULT_ID2NAME_INDEX = 'id2names';
97 $DEFAULT_PARENT_INDEX = 'parents';
98 $NCBI_TAXONOMY_HOSTNAME = 'ftp.ncbi.nih.gov';
99 $NCBI_TAXONOMY_FILE = '/pub/taxonomy/taxdump.tar.gz';
100  
101 $DB_BTREE->{'flags'} = R_DUP; # allow duplicate values in DB_File BTREEs
102  
103 @DIVISIONS = ([qw(BCT Bacteria)],
104 [qw(INV Invertebrates)],
105 [qw(MAM Mammals)],
106 [qw(PHG Phages)],
107 [qw(PLN Plants)], # (and fungi)
108 [qw(PRI Primates)],
109 [qw(ROD Rodents)],
110 [qw(SYN Synthetic)],
111 [qw(UNA Unassigned)],
112 [qw(VRL Viruses)],
113 [qw(VRT Vertebrates)],
114 [qw(ENV 'Environmental samples')]);
115  
116 use base qw(FAST::Bio::DB::Taxonomy);
117  
118 =head2 new
119  
120 Title : new
121 Usage : my $obj = FAST::Bio::DB::Taxonomy::flatfile->new();
122 Function: Builds a new FAST::Bio::DB::Taxonomy::flatfile object
123 Returns : an instance of FAST::Bio::DB::Taxonomy::flatfile
124 Args : -directory => name of directory where index files should be created
125 -nodesfile => name of file containing nodes (nodes.dmp from NCBI)
126 -namesfile => name of the file containing names(names.dmp from NCBI)
127 -force => 1 replace current indexes even if they exist
128  
129 =cut
130  
131 sub new {
132 my($class,@args) = @_;
133  
134 my $self = $class->SUPER::new(@args);
135 my ($dir,$nodesfile,$namesfile,$force) = $self->_rearrange([qw
136 (DIRECTORY NODESFILE NAMESFILE FORCE)], @args);
137
138 $self->index_directory($dir || $DEFAULT_INDEX_DIR);
139 if ( $nodesfile ) {
140 $self->_build_index($nodesfile,$namesfile,$force);
141 }
142  
143 $self->_db_connect;
144 return $self;
145 }
146  
147 =head2 FAST::Bio::DB::Taxonomy Interface implementation
148  
149 =cut
150  
151 =head2 get_taxon
152  
153 Title : get_taxon
154 Usage : my $taxon = $db->get_taxon(-taxonid => $taxonid)
155 Function: Get a FAST::Bio::Taxon object from the database.
156 Returns : FAST::Bio::Taxon object
157 Args : just a single value which is the database id, OR named args:
158 -taxonid => taxonomy id (to query by taxonid)
159 OR
160 -name => string (to query by a taxonomy name: common name,
161 scientific name, etc)
162  
163 =cut
164  
165 sub get_taxon {
166 my ($self) = shift;
167 my ($taxonid, $name);
168
169 if (@_ > 1) {
170 ($taxonid, $name) = $self->_rearrange([qw(TAXONID NAME)],@_);
171 if ($name) {
172 ($taxonid, my @others) = $self->get_taxonids($name);
173 $self->warn("There were multiple ids ($taxonid @others) matching '$name', using '$taxonid'") if @others > 0;
174 }
175 }
176 else {
177 $taxonid = shift;
178 }
179
180 return unless $taxonid;
181
182 $taxonid =~ /^\d+$/ || return;
183 my $node = $self->{'_nodes'}->[$taxonid] || return;
184 length($node) || return;
185 my ($taxid, undef, $rank, $code, $divid, $gen_code, $mito) = split(SEPARATOR,$node);
186 last unless defined $taxid;
187 my ($taxon_names) = $self->{'_id2name'}->[$taxid];
188 my ($sci_name, @common_names) = split(SEPARATOR, $taxon_names);
189
190 my $taxon = FAST::Bio::Taxon->new(
191 -name => $sci_name,
192 -common_names => [@common_names],
193 -ncbi_taxid => $taxid, # since this is a real ncbi taxid, explicitly set it as one
194 -rank => $rank,
195 -division => $DIVISIONS[$divid]->[1],
196 -genetic_code => $gen_code,
197 -mito_genetic_code => $mito );
198 # we can't use -dbh or the db_handle() method ourselves or we'll go
199 # infinite on the merge attempt
200 $taxon->{'db_handle'} = $self;
201
202 $self->_handle_internal_id($taxon);
203
204 return $taxon;
205 }
206  
207 *get_Taxonomy_Node = \&get_taxon;
208  
209 =head2 get_taxonids
210  
211 Title : get_taxonids
212 Usage : my @taxonids = $db->get_taxonids('Homo sapiens');
213 Function: Searches for a taxonid (typically ncbi_taxon_id) based on a query
214 string. Note that multiple taxonids can match to the same supplied
215 name.
216 Returns : array of integer ids in list context, one of these in scalar context
217 Args : string representing taxon's name
218  
219 =cut
220  
221 sub get_taxonids {
222 my ($self, $query) = @_;
223 my $ids = $self->{'_name2id'}->{lc($query)};
224 unless ($ids) {
225 if ($query =~ /_/) {
226 # try again converting underscores to spaces
227 $query =~ s/_/ /g;
228 $ids = $self->{'_name2id'}->{lc($query)};
229 }
230 $ids || return;
231 }
232 my @ids = split(SEPARATOR, $ids);
233 return wantarray() ? @ids : shift @ids;
234 }
235  
236 *get_taxonid = \&get_taxonids;
237  
238 =head2 get_Children_Taxids
239  
240 Title : get_Children_Taxids
241 Usage : my @childrenids = $db->get_Children_Taxids
242 Function: Get the ids of the children of a node in the taxonomy
243 Returns : Array of Ids
244 Args : FAST::Bio::Taxon or a taxon_id
245 Status : deprecated (use each_Descendent())
246  
247 =cut
248  
249 sub get_Children_Taxids {
250 my ($self,$node) = @_;
251 $self->warn("get_Children_Taxids is deprecated, use each_Descendent instead");
252 my $id;
253 if( ref($node) ) {
254 if( $node->can('object_id') ) {
255 $id = $node->object_id;
256 } elsif( $node->can('ncbi_taxid') ) {
257 $id = $node->ncbi_taxid;
258 } else {
259 $self->warn("Don't know how to extract a taxon id from the object of type ".ref($node)."\n");
260 return;
261 }
262 } else { $id = $node }
263 my @vals = $self->{'_parentbtree'}->get_dup($id);
264 return @vals;
265 }
266  
267 =head2 ancestor
268  
269 Title : ancestor
270 Usage : my $ancestor_taxon = $db->ancestor($taxon)
271 Function: Retrieve the full ancestor taxon of a supplied Taxon from the
272 database.
273 Returns : FAST::Bio::Taxon
274 Args : FAST::Bio::Taxon (that was retrieved from this database)
275  
276 =cut
277  
278 sub ancestor {
279 my ($self, $taxon) = @_;
280 $self->throw("Must supply a FAST::Bio::Taxon") unless ref($taxon) && $taxon->isa('FAST::Bio::Taxon');
281 $self->throw("The supplied Taxon must belong to this database") unless $taxon->db_handle && $taxon->db_handle eq $self;
282 my $id = $taxon->id || $self->throw("The supplied Taxon is missing its id!");
283
284 my $node = $self->{'_nodes'}->[$id];
285 if (length($node)) {
286 my (undef, $parent_id) = split(SEPARATOR,$node);
287 $parent_id || return;
288 $parent_id eq $id && return; # one of the roots
289 return $self->get_taxon($parent_id);
290 }
291 return;
292 }
293  
294 =head2 each_Descendent
295  
296 Title : each_Descendent
297 Usage : my @taxa = $db->each_Descendent($taxon);
298 Function: Get all the descendents of the supplied Taxon (but not their
299 descendents, ie. not a recursive fetchall).
300 Returns : Array of FAST::Bio::Taxon objects
301 Args : FAST::Bio::Taxon (that was retrieved from this database)
302  
303 =cut
304  
305 sub each_Descendent {
306 my ($self, $taxon) = @_;
307 $self->throw("Must supply a FAST::Bio::Taxon") unless ref($taxon) && $taxon->isa('FAST::Bio::Taxon');
308 $self->throw("The supplied Taxon must belong to this database") unless $taxon->db_handle && $taxon->db_handle eq $self;
309 my $id = $taxon->id || $self->throw("The supplied Taxon is missing its id!");
310
311 my @desc_ids = $self->{'_parentbtree'}->get_dup($id);
312 my @descs;
313 foreach my $desc_id (@desc_ids) {
314 push(@descs, $self->get_taxon($desc_id) || next);
315 }
316 return @descs;
317 }
318  
319 =head2 Helper methods
320  
321 =cut
322  
323 # internal method which does the indexing
324 sub _build_index {
325 my ($self,$nodesfile,$namesfile,$force) = @_;
326
327 my ($dir) = ($self->index_directory);
328 my $nodeindex = "$dir/$DEFAULT_NODE_INDEX";
329 my $name2idindex = "$dir/$DEFAULT_NAME2ID_INDEX";
330 my $id2nameindex = "$dir/$DEFAULT_ID2NAME_INDEX";
331 my $parent2childindex = "$dir/$DEFAULT_PARENT_INDEX";
332 $self->{'_nodes'} = [];
333 $self->{'_id2name'} = [];
334 $self->{'_name2id'} = {};
335 $self->{'_parent2children'} = {};
336
337 if (! -e $nodeindex || $force) {
338 my (%parent2children,@nodes);
339 open(NODES,$nodesfile) ||
340 $self->throw("Cannot open node file '$nodesfile' for reading");
341
342 unlink $nodeindex;
343 unlink $parent2childindex;
344 my $nh = tie ( @nodes, 'DB_File', $nodeindex, O_RDWR|O_CREAT, 0644, $DB_RECNO) ||
345 $self->throw("Cannot open file '$nodeindex': $!");
346 my $btree = tie( %parent2children, 'DB_File', $parent2childindex, O_RDWR|O_CREAT, 0644, $DB_BTREE) ||
347 $self->throw("Cannot open file '$parent2childindex': $!");
348
349 while (<NODES>) {
350 chomp;
351 my ($taxid,$parent,$rank,$code,$divid,undef,$gen_code,undef,$mito) = split(/\t\|\t/,$_);
352 # don't include the fake root node 'root' with id 1; we essentially have multiple roots here
353 next if $taxid == 1;
354 if ($parent == 1) {
355 $parent = $taxid;
356 }
357
358 # keep this stringified
359 $nodes[$taxid] = join(SEPARATOR, ($taxid,$parent,$rank,$code,$divid,$gen_code,$mito));
360 $btree->put($parent,$taxid);
361 }
362 close(NODES);
363
364 $nh = $btree = undef;
365 untie @nodes ;
366 untie %parent2children;
367 }
368
369 if ((! -e $name2idindex || -z $name2idindex) || (! -e $id2nameindex || -z $id2nameindex) || $force) {
370 open(NAMES,$namesfile) ||
371 $self->throw("Cannot open names file '$namesfile' for reading");
372
373 unlink $name2idindex;
374 unlink $id2nameindex;
375 my (@id2name,%name2id);
376 my $idh = tie (@id2name, 'DB_File', $id2nameindex, O_RDWR|O_CREAT, 0644, $DB_RECNO) ||
377 $self->throw("Cannot open file '$id2nameindex': $!");
378 my $nameh = tie ( %name2id, 'DB_File', $name2idindex, O_RDWR|O_CREAT, 0644, $DB_HASH) ||
379 $self->throw("Cannot open file '$name2idindex': $!");
380
381 while (<NAMES>) {
382 chomp;
383 my ($taxid, $name, $unique_name, $class) = split(/\t\|\t/,$_);
384 # don't include the fake root node 'root' or 'all' with id 1
385 next if $taxid == 1;
386
387 $class =~ s/\s+\|\s*$//;
388 my $lc_name = lc($name);
389 my $orig_name = $name;
390
391 # unique names aren't always in the correct column, sometimes they
392 # are uniqued by adding bracketed rank names to the normal name;
393 # store the uniqued version then fix the name for normal use
394 if ($lc_name =~ /\(class\)$/) { # it seems that only rank of class is ever used in this situation
395 $name2id{$lc_name} = $taxid;
396 $name =~ s/\s+\(class\)$//;
397 $lc_name = lc($name);
398 }
399
400 # handle normal names which aren't necessarily unique
401 my $taxids = $name2id{$lc_name} || '';
402 my %taxids = map { $_ => 1 } split(SEPARATOR, $taxids);
403 unless (exists $taxids{$taxid}) {
404 $taxids{$taxid} = 1;
405 $name2id{$lc_name} = join(SEPARATOR, keys %taxids);
406 }
407
408 # store unique names in name2id
409 if ($unique_name) {
410 $name2id{lc($unique_name)} = $taxid;
411 }
412
413 # store all names in id2name array
414 my $names = $id2name[$taxid] || '';
415 my @names = split(SEPARATOR, $names);
416 if ($class && $class eq 'scientific name') {
417 # the scientific name should be the first name stored
418 unshift(@names, $name);
419 push(@names, $orig_name) if ($orig_name ne $name);
420 push(@names, $unique_name) if $unique_name;
421 }
422 else {
423 # all other ('common' in this simplification) names get added after
424 push(@names, $name);
425 push(@names, $orig_name) if ($orig_name ne $name);
426 push(@names, $unique_name) if $unique_name;
427 }
428 $id2name[$taxid] = join(SEPARATOR, @names);
429 }
430 close(NAMES);
431
432 $idh = $nameh = undef;
433 untie( %name2id);
434 untie( @id2name);
435 }
436 }
437  
438 # connect the internal db handle
439 sub _db_connect {
440 my $self = shift;
441 return if $self->{'_initialized'};
442
443 $self->{'_nodes'} = [];
444 $self->{'_id2name'} = [];
445 $self->{'_name2id'} = {};
446
447 my ($dir) = ($self->index_directory);
448 my $nodeindex = "$dir/$DEFAULT_NODE_INDEX";
449 my $name2idindex = "$dir/$DEFAULT_NAME2ID_INDEX";
450 my $id2nameindex = "$dir/$DEFAULT_ID2NAME_INDEX";
451 my $parent2childindex = "$dir/$DEFAULT_PARENT_INDEX";
452
453 if( ! -e $nodeindex ||
454 ! -e $name2idindex ||
455 ! -e $id2nameindex ) {
456 $self->warn("Index files have not been created");
457 return 0;
458 }
459 tie ( @{$self->{'_nodes'}}, 'DB_File', $nodeindex, O_RDWR,undef, $DB_RECNO)
460 || $self->throw("$! $nodeindex");
461 tie (@{$self->{'_id2name'}}, 'DB_File', $id2nameindex,O_RDWR, undef,
462 $DB_RECNO) || $self->throw("$! $id2nameindex");
463
464 tie ( %{$self->{'_name2id'}}, 'DB_File', $name2idindex, O_RDWR,undef,
465 $DB_HASH) || $self->throw("$! $name2idindex");
466 $self->{'_parentbtree'} = tie( %{$self->{'_parent2children'}},
467 'DB_File', $parent2childindex,
468 O_RDWR, 0644, $DB_BTREE);
469 $self->{'_initialized'} = 1;
470 }
471  
472  
473 =head2 index_directory
474  
475 Title : index_directory
476 Funtion : Get/set the location that index files are stored. (this module
477 will index the supplied database)
478 Usage : $obj->index_directory($newval)
479 Returns : value of index_directory (a scalar)
480 Args : on set, new value (a scalar or undef, optional)
481  
482 =cut
483  
484 sub index_directory {
485 my $self = shift;
486 return $self->{'index_directory'} = shift if @_;
487 return $self->{'index_directory'};
488 }
489  
490 1;