lib/Bio/MUST/Core/Taxonomy.pm

filter: Statementstmt 17.6% 156 / 886 Branchbran 0.0% 0 / 242 Conditioncond 0.0% 0 / 91 MC/DCmcdc 0.0% 0 / 53 Subroutinesub 37.8% 42 / 111 Podpod 95.6% 22 / 23 totaltotal 15.6% 220 / 1406 CC 173 SCAR 47.8
CC
173
Cov
13%
_setup_gtdb_taxdir
600.0
_make_gca_files
342.0
_setup_ncbi_taxdir
272.0
CRAP 119.7
« lib/Bio/MUST/Core/Taxonomy/Criterion.pm ↑ Summary lib/Bio/MUST/Core/SeqMask/Weights.pm »
1 package Bio::MUST::Core::Taxonomy;
2 # ABSTRACT: NCBI Taxonomy one-stop shop
3 # CONTRIBUTOR: Loic MEUNIER <loic.meunier@doct.uliege.be>
4 # CONTRIBUTOR: Mick VAN VLIERBERGHE <mvanvlierberghe@doct.uliege.be>
5 18 $Bio::MUST::Core::Taxonomy::VERSION = '0.252040';
6 18 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 18 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 18 ▶use autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 18 ▶use feature qw(say);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 18 ▶use Smart::Comments '###';
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 18 ▶use MooseX::Storage;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 18 with Storage('io' => 'StorableFile');
16  
17 18 ▶use Moose::Util::TypeConstraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 18 ▶use Algorithm::NeedlemanWunsch;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 18 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 18 ▶use Const::Fast;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 18 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 18 ▶use File::Find::Rule;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 18 ▶use IPC::System::Simple qw(system);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 18 ▶use List::AllUtils 0.12
Subroutine BEGIN: called CC=1 SCAR=0.0
26 18 qw(first firstidx uniq each_array mesh count_by max_by);
27 18 ▶use LWP::Simple qw(get getstore);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 18 ▶use Path::Class qw(dir file);
Subroutine BEGIN: called CC=1 SCAR=0.0
29 18 ▶use POSIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 18 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
31 18 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 18 ▶use Try::Tiny::Warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 18 ▶use XML::Bare;
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 18 ▶use Bio::LITE::Taxonomy::NCBI::Gi2taxid qw(new_dict);
Subroutine BEGIN: called CC=1 SCAR=0.0
36 18 ▶use Bio::Phylo::IO qw(parse);
Subroutine BEGIN: called CC=1 SCAR=0.0
37  
38 18 ▶use Bio::MUST::Core::Types;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 18 ▶use Bio::MUST::Core::Constants qw(:ncbi :files);
Subroutine BEGIN: called CC=1 SCAR=0.0
40 18 ▶use Bio::MUST::Core::Utils qw(change_suffix);
Subroutine BEGIN: called CC=1 SCAR=0.0
41 18 ▶use aliased 'Bio::MUST::Core::SeqId';
Subroutine BEGIN: called CC=1 SCAR=0.0
42 18 ▶use aliased 'Bio::MUST::Core::IdList';
Subroutine BEGIN: called CC=1 SCAR=0.0
43 18 ▶use aliased 'Bio::MUST::Core::IdMapper';
Subroutine BEGIN: called CC=1 SCAR=0.0
44 18 ▶use aliased 'Bio::MUST::Core::Tree';
Subroutine BEGIN: called CC=1 SCAR=0.0
45 18 ▶use aliased 'Bio::MUST::Core::Taxonomy::MooseNCBI';
Subroutine BEGIN: called CC=1 SCAR=0.0
46 18 ▶use aliased 'Bio::MUST::Core::Taxonomy::Filter';
Subroutine BEGIN: called CC=1 SCAR=0.0
47 18 ▶use aliased 'Bio::MUST::Core::Taxonomy::Criterion';
Subroutine BEGIN: called CC=1 SCAR=0.0
48 18 ▶use aliased 'Bio::MUST::Core::Taxonomy::Category';
Subroutine BEGIN: called CC=1 SCAR=0.0
49 18 ▶use aliased 'Bio::MUST::Core::Taxonomy::Classifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
50 18 ▶use aliased 'Bio::MUST::Core::Taxonomy::Labeler';
Subroutine BEGIN: called CC=1 SCAR=0.0
51 18 ▶use aliased 'Bio::MUST::Core::Taxonomy::ColorScheme';
Subroutine BEGIN: called CC=1 SCAR=0.0
52  
53  
54 # public path to NCBI Taxonomy dump directory
55 18 has 'tax_dir' => (
56 traits => ['DoNotSerialize'],
57 is => 'ro',
58 isa => 'Bio::MUST::Core::Types::Dir',
59 required => 1,
60 coerce => 1,
61 );
62  
63  
64 # Note: init_arg => undef had to be removed to allow proper serialization
65 # this is needed because MooseX::Storage has never accepted my patches
66 # see https://rt.cpan.org/Public/Bug/Display.html?id=65733
67  
68 18 has '_ncbi_tax' => (
69 is => 'ro',
70 isa => 'Bio::MUST::Core::Taxonomy::MooseNCBI',
71 lazy => 1,
72 builder => '_build_ncbi_tax',
73 handles => qr{get_\w+}xms, # expose Bio::LITE::Taxonomy accessor methods
74 );
75  
76 # Note: this is related to (yet different from)
77 18 has '_gi_mapper' => ( # the nearly homonymous 'gi_mapper' method
78 traits => ['DoNotSerialize'],
79 is => 'ro',
80 isa => 'Bio::LITE::Taxonomy::NCBI::Gi2taxid',
81 lazy => 1,
82 builder => '_build_gi_mapper',
83 handles => {
84 get_taxid_from_gi => 'get_taxid',
85 },
86 );
87  
88  
89 18 has '_is_deleted' => (
90 traits => ['Hash'],
91 is => 'ro',
92 isa => 'HashRef[Bool]',
93 lazy => 1,
94 builder => '_build_is_deleted',
95 handles => {
96 'is_deleted' => 'defined',
97 },
98 );
99  
100  
101 has '_' . $_ . '_for' => (
102 traits => ['Hash'],
103 is => 'ro',
104 isa => 'HashRef[Str]',
105 lazy => 1,
106 builder => '_build_' . $_ . '_for',
107 handles => {
108 'is_' . $_ => 'defined',
109 $_ . '_for' => 'get',
110 },
111 18 ) for qw(merged misleading);
112  
113  
114 18 has '_dupes_for' => (
115 traits => ['Hash'],
116 is => 'ro',
117 isa => 'HashRef[HashRef[Str]]',
118 lazy => 1,
119 builder => '_build_dupes_for',
120 handles => {
121 'is_dupe' => 'defined',
122 'dupes_for' => 'get',
123 },
124 );
125  
126 # TODO: change this name? to avoid confusion with othe uses of rank_for
127 18 has '_rank_for' => (
128 traits => ['Hash'],
129 is => 'ro',
130 isa => 'HashRef[Str]',
131 lazy => 1,
132 builder => '_build_rank_for',
133 handles => {
134 'rank_for' => 'get',
135 },
136 );
137  
138  
139 18 has '_strain_taxid_for' => (
140 traits => ['Hash'],
141 is => 'ro',
142 isa => 'HashRef[HashRef[Str]]',
143 lazy => 1,
144 builder => '_build_strain_taxid_for',
145 handles => {
146 'get_strain_taxid_for' => 'get', # TODO: rename?
147 },
148 );
149  
150  
151 18 has '_matcher' => (
152 traits => ['DoNotSerialize'],
153 is => 'ro',
154 isa => 'Algorithm::NeedlemanWunsch',
155 init_arg => undef,
156 lazy => 1,
157 builder => '_build_matcher',
158 handles => {
159 nw_score => 'align',
160 },
161 );
162  
163 ## no critic (ProhibitUnusedPrivateSubroutines)
164  
165 0 ▶sub _build_ncbi_tax {
Subroutine _build_ncbi_tax: not called CC=1 SCAR=6.9
166 0 my $self = shift;
167  
168 #### in _build_ncbi_tax
169  
170 0 local $_ = q{}; # to avoid loosing $_ due to Bio::LITE... constructor
171  
172 # open pipes from (possibly) multiple names.dmp and nodes.dmp
173 0 my $names_txid = file($self->tax_dir, 'names*.dmp' );
174 0 my $names_gca = file($self->tax_dir, 'gca*names.dmp');
175 0 my $nodes_txid = file($self->tax_dir, 'nodes*.dmp' );
176 0 my $nodes_gca = file($self->tax_dir, 'gca*nodes.dmp');
177  
178 # Note: taxid files are loaded last to get precedence in get_taxid_from_name
179 0 my @names_files = ($names_gca, $names_txid);
180 0 my @nodes_files = ($nodes_txid, $nodes_gca);
181  
182 # Note: names.dmp files are reordered on-the-fly so as scientific names
183 # get precedence over other names (e.g., synonyms) in case of duplicates
184 # Note: this should not be useful anymore (due to _dupes_for attribute)
185 0 my $ol = q{'if (index($_, "scientific name") == -1) { print } else { push @sns, $_ } END{ print for @sns }'};
186 0 open my $names_fh, '-|', qq{perl -nle $ol @names_files 2> /dev/null};
187 0 open my $nodes_fh, '-|', qq{cat @nodes_files 2> /dev/null};
188  
189 0 return MooseNCBI->new(
190 names => $names_fh,
191 nodes => $nodes_fh,
192  
193 # allow most NCBI Taxonomy synonyms classes
194 # cut -f4 -d'|' names.dmp | sort | uniq -c
195 # last updated on Jul-23-2025
196 # 2186 acronym
197 # 872668 authority
198 # 229 blast name
199 # 14861 common name
200 # 64495 equivalent name
201 # 30837 genbank common name
202 # 653 in-part
203 # 93973 includes
204 # 2686415 scientific name
205 # 354657 synonym
206 # 322156 type material
207  
208 synonyms => [
209 'acronym', 'synonym',
210 # 'genbank acronym', 'genbank synonym', # now useless
211 # 'anamorph', 'genbank anamorph', 'teleomorph', # now useless
212 'blast name', 'common name', 'genbank common name',
213 'equivalent name', 'includes',
214 # 'authority', 'in-part', 'type material', # unwanted
215 ]
216 );
217 }
218  
219 0 ▶sub _build_gi_mapper {
Subroutine _build_gi_mapper: not called CC=1 SCAR=6.9
220 0 my $self = shift;
221  
222 #### in _build_gi_mapper
223  
224 0 local $_ = q{}; # to avoid loosing $_ due to Bio::LITE... constructor
225  
226 0 return Bio::LITE::Taxonomy::NCBI::Gi2taxid->new(
227 dict => file($self->tax_dir, 'gi_taxid_nucl_prot.bin'),
228 save_mem => 1, # 0 does not work on my MacBook Air
229 );
230 }
231  
232 0 ▶sub _build_is_deleted {
Subroutine _build_is_deleted: not called CC=2 SCAR=17.9
233 0 my $self = shift;
234  
235 #### in _build_is_deleted
236  
237 0 my %is_deleted;
238  
239 0 my $infile = file($self->tax_dir, 'delnodes.dmp');
240 0 open my $in, '<', $infile;
241  
242 0 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
243 0 my ($taxon_id) = $line =~ m/^(\d+)/xms;
244 0 $is_deleted{$taxon_id} = 1;
245 }
246  
247 0 return \%is_deleted;
248 }
249  
250 0 ▶sub _build_merged_for {
Subroutine _build_merged_for: not called CC=2 SCAR=17.9
251 0 my $self = shift;
252  
253 #### in _build_merged_for
254  
255 0 my %merged_for;
256  
257 0 my $infile = file($self->tax_dir, 'merged.dmp');
258 0 open my $in, '<', $infile;
259  
260 0 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
261 0 chomp $line;
262 0 my ($old_taxid, $new_taxid) = split /\s*\|\s*/xms, $line;
263 0 $merged_for{$old_taxid} = $new_taxid;
264 }
265  
266 0 return \%merged_for;
267 }
268  
269 0 ▶sub _build_misleading_for {
Subroutine _build_misleading_for: not called CC=2 SCAR=17.9
270 0 my $self = shift;
271  
272 #### in _build_misleading_for
273  
274 0 my %misleading_for;
275  
276 # TODO: improve warning suppression
277 # cat: .../taxdump/misleading*.dmp: No such file or directory
278 0 my $misleadings = file($self->tax_dir, 'misleading*.dmp');
279 0 open my $in, '-|', "cat $misleadings 2> /dev/null";
280  
281 0 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
282 0 chomp $line;
283 0 my ($taxid, $full_org) = split /\s*\|\s*/xms, $line;
284 0 $misleading_for{$full_org} = $taxid;
285 }
286  
287 0 return \%misleading_for;
288 }
289  
290 0 ▶sub _build_dupes_for {
Subroutine _build_dupes_for: not called CC=6 SCAR=33.1
291 0 my $self = shift;
292  
293 #### in _build_dupes_for
294  
295 0 my %taxids_for;
296  
297 0 my $infile = file($self->tax_dir, 'names.dmp');
298 0 open my $in, '<', $infile;
299  
300 # build hash of NCBI names => taxon_id(s) for all taxa
301  
302 LINE:
303 0 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
304  
305 # focus on scientific names
306 0 ▶ next LINE unless $line =~ m/scientific \s name/xms;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /scientific \s name/msx 0 0 0
307  
308 # Note: old code was tolerant to "minor" duplications:
309 # do not consider as duplicates genus and subgenus that are the same
310 # similarly ignore duplicates involving phylum vs other levels
311 # phyla come after classes and synonyms (and thus should win)
312 # next LINE if $line =~ m/genus>/xms || $line =~ m/<phylum>/xms;
313 # next LINE if $line =~ m/<actinobacteria>/xms; # workaround...
314  
315 # extract taxon and track taxon_id
316 0 chomp $line;
317 0 my ($taxon_id, $taxon) = (split /\s*\|\s*/xms, $line)[0..1];
318 0 push @{ $taxids_for{$taxon} }, $taxon_id;
319 }
320  
321 0 my %dupes_for;
322  
323 # create helper Taxonomy object
324 0 my $tax = $self->new( tax_dir => $self->tax_dir );
325  
326 TAXON:
327 0 ▶ while (my ($taxon, $taxids) = each %taxids_for) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %taxids_for) 0 0 0
328  
329 # only proceed for duplicate taxa
330 0 ▶ next TAXON if @{$taxids} < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @{$taxids;} < 2 0 0 0
331  
332 # build hash of partial lineage => taxon_id only for duplicate taxa
333 18 ▶ no warnings 'uninitialized'; # avoid undef due to 2-4-level lineages
Subroutine BEGIN: called CC=1 SCAR=0.0
334 my %taxid_for = map {
335 0 ( join q{; }, ( $tax->get_taxonomy($_) )[-5..-1] ) => $_
336 0 } @{$taxids};
337 18 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
338  
339 # warn of taxa that end by the same three last taxa
340 # Note: this looks like a NCBI bug a couple of scientific names
341 carp "[BMC] Note: $taxon cannot be disambiguated."
342 0 ▶ . ' This should not be an issue.' if keys %taxid_for < @{$taxids};
Branch: 1 branch
BranchTrueFalseTotal
if keys %taxid_for < @{$taxids;} 0 0 0
343  
344 0 $dupes_for{$taxon} = \%taxid_for;
345 }
346  
347 0 return \%dupes_for;
348 }
349  
350 # Note: taken from nodes.dmp as follows (then manually re-ordered)
351 # cut -f3 -d'|' nodes.dmp | sort | uniq
352 # last updated on Jul-23-2025
353 18 const my @LEVELS => (
354 'skip', # default collapsing level
355 'top', # useful to preserve 'cellular organisms'
356 'cellular root', 'acellular root',
357 'domain', 'realm',
358 'superkingdom', # not in use anymore (kept for compatibility)
359 'kingdom', 'subkingdom',
360 'superphylum', 'phylum', 'subphylum',
361 'superclass', 'class', 'subclass', 'infraclass',
362 'cohort', 'subcohort',
363 'superorder', 'order', 'suborder', 'infraorder', 'parvorder',
364 'superfamily', 'family', 'subfamily',
365 'tribe', 'subtribe',
366 'genus', 'subgenus',
367 'section', 'subsection',
368 'series',
369 'species group', 'species subgroup', 'species', 'subspecies',
370  
371 'subvariety', 'varietas', # relative order of all these terms is unclear
372 'morph', 'forma', 'forma specialis',
373 'isolate', 'strain',
374 'pathogroup', 'serogroup', 'serotype',
375 'biotype', 'genotype',
376  
377 'clade', 'no rank', # both terms can appear anywhere in a lineage
378 );
379  
380 0 ▶sub _build_rank_for {
Subroutine _build_rank_for: not called CC=1 SCAR=6.9
381 #### in _build_rank_for
382 0 my $i = 1;
383 0 return { map { $_ => $i-- } @LEVELS };
384 }
385  
386 0 ▶sub _build_strain_taxid_for {
Subroutine _build_strain_taxid_for: not called CC=5 SCAR=34.0
387 0 my $self = shift;
388  
389 #### in _build_strain_taxid_for
390  
391 # open pipe from (possibly) multiple names.dmp
392 # TODO: try to avoid code duplication with _build_ncbi_tax
393 0 my $names_txid = file($self->tax_dir, 'names*.dmp' );
394 0 my $names_gca = file($self->tax_dir, 'gca*names.dmp');
395  
396 # Note: taxid files are loaded last to get precedence over gca numbers
397 0 my @names_files = ($names_gca, $names_txid);
398 0 open my $names_fh, '-|', "cat @names_files";
399  
400 0 my %strain_taxid_for;
401  
402 LINE:
403 0 ▶ while (my $line = <$names_fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $names_fh)) 0 0 0
404 0 chomp $line;
405  
406 # fetch taxid and organism name
407 0 my ($taxid, $org) = split /\s*\|\s*/xms, $line;
408  
409 # extract components from organism name
410 0 my ($genus, $species, $strain) = SeqId->parse_ncbi_name($org);
411  
412 # skip entries without strain
413 0 ▶ next LINE unless $strain;
Branch: 1 branch
BranchTrueFalseTotal
unless $strain 0 0 0
414  
415 # store tax_id for org and strain combo
416 0 my $org_key = _make_hashkey($genus, $species);
417 0 my $strain_key = _clean_strain($strain);
418 0 ▶ $strain_taxid_for{$org_key}{$strain_key} = $taxid # avoid bug with
Branch: 1 branch
BranchTrueFalseTotal
if defined $strain_key and length $strain_key 0 0 0
Condition0%0/3
defined $strain_key and length $strain_key
!ll&&!rl&&r
000
MC/DC0%0/2
defined $strain_key and length $strain_key
defined $strain_key length $strain_key
Truth table0%0/3
A and B
A= defined $strain_keyB= length $strain_key
ABresult
0X0
100
111
419 if defined $strain_key and length $strain_key; # NW aligner
420 }
421  
422 0 return \%strain_taxid_for;
423 }
424  
425 0 ▶sub _clean_strain {
Subroutine _clean_strain: not called CC=1 SCAR=6.9
426 0 my $strain = shift;
427  
428 # remove unwanted prefices and characters (if any)
429 0 $strain =~ s{\b substr \b}{}xmsgi;
430 0 $strain =~ s{\b strain \b}{}xmsgi;
431 0 $strain =~ s{\b subsp \b}{}xmsgi;
432 0 $strain =~ s{\b str \b}{}xmsgi;
433 0 $strain =~ tr/A-Za-z0-9//cd; # delete non-alphanumeric chars
434  
435 0 return lc $strain;
436 }
437  
438 0 ▶sub _make_hashkey {
Subroutine _make_hashkey: not called CC=1 SCAR=6.9
439 0 my $genus = shift;
440 0 my $species = shift;
441  
442 0 $species =~ tr/-//d; # clean hyphens in species
443 0 my $org = lc( $genus . q{ } . $species );
444  
445 0 return $org;
446 }
447  
448  
449 18 const my $MATCHYOU => 3; # cannot use $MATCH as it is reserved
450 18 const my $MISMATCH => -1;
451 18 const my $GAP_OPEN => -2;
452 18 const my $GAP_EXTEND => 0;
453  
454 0 ▶sub _build_matcher {
Subroutine _build_matcher: not called CC=1 SCAR=6.9
455 0 my $self = shift;
456  
457 #### in _build_matcher
458  
459 0 local $_ = q{}; # to avoid loosing $_ due to Algorithm::... constructor
460  
461 # setup Algorithm::NeedlemanWunsch object
462 0 my $matcher = Algorithm::NeedlemanWunsch->new( \&_matcher_matrix );
463 0 $matcher->gap_open_penalty( $GAP_OPEN );
464 0 $matcher->gap_extend_penalty($GAP_EXTEND);
465  
466 0 return $matcher;
467 }
468  
469 18 const my $GAP_CODE => '*';
470 18 const my $MATCH_CODE => '.';
471 18 const my $MISMATCH_CODE => ':';
472  
473 18 const my %SCORE_FOR => (
474 $GAP_CODE => $GAP_OPEN,
475 $MATCH_CODE => $MATCHYOU,
476 $MISMATCH_CODE => $MISMATCH,
477 );
478  
479 0 ▶sub _matcher_matrix { ## no critic (RequireArgUnpacking)
Subroutine _matcher_matrix: not called CC=1 SCAR=6.9
480 0 return $SCORE_FOR{ _match_code(@_) };
481 }
482  
483 0 ▶sub _match_code { ## no critic (RequireArgUnpacking)
Subroutine _match_code: not called CC=9 SCAR=45.0
484 0 ▶ return $GAP_CODE unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 0 0
485  
486 # if one is not \w+ and the other is \w+ you want it to be a gap, not a
487 # mismatch --> higher penalty
488 0 ▶ if ( $_[0] =~ m/ [^A-Za-z0-9] /xms && $_[1] =~ m/ [A-Za-z0-9] /xms
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0] =~ / [^A-Za-z0-9] /msx and $_[1] =~ / [A-Za-z0-9] /msx or $_[0] =~ / [A-Za-z0-9] /msx and $_[1] =~ / [^A-Za-z0-9] /msx) 0 0 0
Condition0%0/9
$_[0] =~ / [^A-Za-z0-9] /msx and $_[1] =~ / [A-Za-z0-9] /msx or $_[0] =~ / [A-Za-z0-9] /msx and $_[1] =~ / [^A-Za-z0-9] /msx
l!l&&r!l&&!r
000
$_[0] =~ / [^A-Za-z0-9] /msx and $_[1] =~ / [A-Za-z0-9] /msx
!ll&&!rl&&r
000
$_[0] =~ / [A-Za-z0-9] /msx and $_[1] =~ / [^A-Za-z0-9] /msx
!ll&&!rl&&r
000
MC/DC0%0/4
$_[0] =~ / [^A-Za-z0-9] /msx and $_[1] =~ / [A-Za-z0-9] /msx or $_[0] =~ / [A-Za-z0-9] /msx and $_[1] =~ / [^A-Za-z0-9] /msx
$_[0] =~ / [^A-Za-z0-9] /msx $_[1] =~ / [A-Za-z0-9] /msx $_[0] =~ / [A-Za-z0-9] /msx $_[1] =~ / [^A-Za-z0-9] /msx
Truth table0%0/7
A and B or C and D
A= $_[0] =~ / [^A-Za-z0-9] /msxB= $_[1] =~ / [A-Za-z0-9] /msxC= $_[0] =~ / [A-Za-z0-9] /msxD= $_[1] =~ / [^A-Za-z0-9] /msx
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
489 or $_[0] =~ m/ [A-Za-z0-9] /xms && $_[1] =~ m/ [^A-Za-z0-9] /xms ) {
490 0 return $GAP_CODE;
491 }
492  
493 0 ▶ if ( $_[0] =~ m/ [A-Za-z0-9] /xms || $_[1] =~ m/ [A-Za-z0-9] /xms ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0] =~ / [A-Za-z0-9] /msx or $_[1] =~ / [A-Za-z0-9] /msx) 0 0 0
Condition0%0/3
$_[0] =~ / [A-Za-z0-9] /msx or $_[1] =~ / [A-Za-z0-9] /msx
l!l&&r!l&&!r
000
MC/DC0%0/2
$_[0] =~ / [A-Za-z0-9] /msx or $_[1] =~ / [A-Za-z0-9] /msx
$_[0] =~ / [A-Za-z0-9] /msx $_[1] =~ / [A-Za-z0-9] /msx
Truth table0%0/3
A or B
A= $_[0] =~ / [A-Za-z0-9] /msxB= $_[1] =~ / [A-Za-z0-9] /msx
ABresult
1X1
011
000
494 0 ▶ return ( lc $_[0] eq lc $_[1] ) ? $MATCH_CODE : $MISMATCH_CODE;
Branch: 1 branch
BranchTrueFalseTotal
lc $_[0] eq lc $_[1] ? : 0 0 0
495 }
496  
497 0 return $MATCH_CODE;
498 }
499  
500 ## use critic
501  
502  
503 # additional accessor methods (w.r.t. Bio::LITE::Taxonomy)
504 # Since Bio::LITE::Taxonomy methods return arrays (and not ArrayRefs), these
505 # methods also use arrays as in/out data structures (for consistency).
506 # Not quite... We use wantarray when needed now.
507  
508 0 ▶around qr{ _from_seq_id \z | _from_legacy_seq_id \z }xms => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
509 0 my $method = shift;
510 0 my $self = shift;
511 0 my $seq_id = shift;
512  
513 # coerce plain strings to SeqId...
514 # ... but do not touch (stringified) lineages (and SeqIds)
515 match_on_type $seq_id => (
516 0 ▶ 'Bio::MUST::Core::Types::Lineage' => sub { },
Subroutine __ANON__: not called CC=1 SCAR=0.0
517 0 ▶ 'Str' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
518 0 $seq_id = SeqId->new( full_id => $seq_id )
519 },
520 0 ▶ => sub { },
Subroutine __ANON__: not called CC=1 SCAR=0.0
521 0 );
522  
523 0 return $self->$method($seq_id, @_);
524 18 };
525  
526 0 ▶around qr{ _from_name \z }xms => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
527 0 my $method = shift;
528 0 my $self = shift;
529 0 my $name = shift;
530  
531 # avoid issue with undefined names
532 0 ▶ return undef unless $name; ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
unless $name 0 0 0
533  
534 0 ▶ if ( $self->is_dupe($name) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_dupe($name)) 0 0 0
535 0 carp "[BMC] Warning: $name is taxonomically ambiguous;"
536 . ' returning undef!';
537 0 return undef; ## no critic (ProhibitExplicitReturnUndef)
538 }
539  
540 0 return $self->$method($name);
541 18 };
542  
543 # keep track of noted taxon mergers to avoid repeated Note messages
544 18 my %was_noted;
545  
546 0 ▶around qw( get_taxonomy get_taxonomy_with_levels get_term_at_level ) => sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
547 0 my $method = shift;
548 0 my $self = shift;
549 0 my $taxon_id = shift;
550  
551 # update taxon_id if merged in current version of NCBI Taxonomy
552 # in contrast, we don't do anything if taxon_id has been deleted
553 0 ▶ if ( defined $taxon_id && $self->is_merged($taxon_id) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $taxon_id and $self->is_merged($taxon_id)) 0 0 0
Condition0%0/3
defined $taxon_id and $self->is_merged($taxon_id)
!ll&&!rl&&r
000
MC/DC0%0/2
defined $taxon_id and $self->is_merged($taxon_id)
defined $taxon_id $self->is_merged($taxon_id)
Truth table0%0/3
A and B
A= defined $taxon_idB= $self->is_merged($taxon_id)
ABresult
0X0
100
111
554 0 my $noted = $was_noted{$taxon_id}; # noted?
555 0 ▶ $was_noted{$taxon_id} //= 1; # noted!
Condition0%0/2
$was_noted{$taxon_id} //= 1
l!l
00
MC/DC0%0/1
$was_noted{$taxon_id} //= 1
$was_noted{$taxon_id}
Truth table0%0/2
A
A= $was_noted{$taxon_id}
Aresult
11
00
556 0 my $msg = "[BMC] Note: merged taxid for $taxon_id;";
557 0 $taxon_id = $self->merged_for($taxon_id);
558 0 ▶ carp "$msg using $taxon_id instead!" unless $noted;
Branch: 1 branch
BranchTrueFalseTotal
unless $noted 0 0 0
559 }
560  
561 # enforce use of GCA accessions even with GCF accessions
562 0 ▶ $taxon_id =~ tr/F/A/ if defined $taxon_id && $taxon_id =~ $GCAONLY;
Branch: 1 branch
BranchTrueFalseTotal
if defined $taxon_id and $taxon_id =~ /$Bio::MUST::Core::Taxonomy::GCAONLY/ 0 0 0
Condition0%0/3
defined $taxon_id and $taxon_id =~ /$Bio::MUST::Core::Taxonomy::GCAONLY/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $taxon_id and $taxon_id =~ /$Bio::MUST::Core::Taxonomy::GCAONLY/
defined $taxon_id $taxon_id =~ /$Bio::MUST::Core::Taxonomy::GCAONLY/
Truth table0%0/3
A and B
A= defined $taxon_idB= $taxon_id =~ /$Bio::MUST::Core::Taxonomy::GCAONLY/
ABresult
0X0
100
111
563  
564 0 return $self->$method($taxon_id, @_);
565 18 };
566  
567  
568 0 ▶sub get_taxid_from_seq_id {
Subroutine get_taxid_from_seq_id: not called CC=11 SCAR=48.8
569 0 my $self = shift;
570 0 my $seq_id = shift;
571  
572 # 0. return undef in case of tagged contaminant sequences
573 # TODO: return taxonomy of contaminant 'tail' if any?
574 return undef ## no critic (ProhibitExplicitReturnUndef)
575 0 ▶ if $seq_id->is_doubtful;
Branch: 1 branch
BranchTrueFalseTotal
if $seq_id->is_doubtful 0 0 0
576  
577 # 1. first handles valid MUST strain names that look like taxon_ids
578 # Note1: 'valid' ids are the opposite to 'foreign_ids'
579 # Note2: such cases are keyed by their full_org names
580 0 ▶ unless ( $seq_id->is_foreign ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seq_id->is_foreign) 0 0 0
581 0 my $taxon_id = $self->misleading_for( $seq_id->full_org );
582 0 ▶ return $taxon_id if $taxon_id;
Branch: 1 branch
BranchTrueFalseTotal
if $taxon_id 0 0 0
583 }
584  
585 # 2. default path is to use already parsed taxon_id
586 # this applies to modern MUST SeqIds and taxonomy-aware abbr_ids
587 0 ▶ return $seq_id->taxon_id
Branch: 1 branch
BranchTrueFalseTotal
if $seq_id->taxon_id 0 0 0
588 if $seq_id->taxon_id;
589  
590 # 3. handles foreign_ids:
591 # ... if a GI number is available then use the GI-to-taxid mapper
592 # ... otherwise use full_id as a literal NCBI Taxonomy name
593 0 ▶ if ( $seq_id->is_foreign ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seq_id->is_foreign) 0 0 0
594 0 ▶ return $self->get_taxid_from_gi( $seq_id->gi )
Branch: 1 branch
BranchTrueFalseTotal
if $seq_id->gi 0 0 0
595 if $seq_id->gi;
596 0 return $self->get_taxid_from_name( $seq_id->full_id )
597 }
598  
599 # back to valid MUST ids
600 # idea: use as much information as possible but in case of failure...
601 # ... retry after droppping the most specific piece (greedy behavior)
602  
603 # 4. tries to recover MUST legacy strain in NCBI Taxonomy...
604 0 ▶ if ( $seq_id->strain ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seq_id->strain) 0 0 0
605 0 my $taxon_id = $self->get_taxid_from_legacy_seq_id($seq_id);
606 0 ▶ return $taxon_id if $taxon_id;
Branch: 1 branch
BranchTrueFalseTotal
if $taxon_id 0 0 0
607 }
608  
609 # 5. tries to recover organism binomial in NCBI Taxonomy...
610 0 ▶ unless ( $seq_id->is_genus_only ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seq_id->is_genus_only) 0 0 0
611 0 my $taxon_id = $self->get_taxid_from_name( $seq_id->org );
612 0 ▶ return $taxon_id if $taxon_id;
Branch: 1 branch
BranchTrueFalseTotal
if $taxon_id 0 0 0
613 }
614  
615 # 6. tries to recover organism genus in NCBI Taxonomy
616 # this may fail if genus is ambiguous (see around method modifier)
617 0 return $self->get_taxid_from_name( $seq_id->genus );
618 }
619  
620  
621 0 ▶sub get_taxid_from_legacy_seq_id {
Subroutine get_taxid_from_legacy_seq_id: not called CC=5 SCAR=34.0
622 0 my $self = shift;
623 0 my $seq_id = shift;
624  
625 # fetch organism name
626 0 my $org_key = _make_hashkey( $seq_id->genus, $seq_id->species );
627  
628 # fetch and clean organism (query) strain
629 0 my $query_strain = $seq_id->strain;
630 return undef ## no critic (ProhibitExplicitReturnUndef)
631 0 ▶ unless $query_strain;
Branch: 1 branch
BranchTrueFalseTotal
unless $query_strain 0 0 0
632 0 $query_strain = lc SeqId->clean_strain($query_strain);
633  
634 # fetch hash containing 'strain => taxid' pairs
635 # original clean code using native delegation:
636 # my $taxid_for = $self->get_strain_taxid_for($org_key);
637 # new hackish code for performance only:
638 0 my $taxid_for = $self->_strain_taxid_for->{$org_key};
639 return undef ## no critic (ProhibitExplicitReturnUndef)
640 0 ▶ unless $taxid_for;
Branch: 1 branch
BranchTrueFalseTotal
unless $taxid_for 0 0 0
641  
642 # check if strain exist 'as is'
643 0 my $taxid = $taxid_for->{$query_strain};
644 0 ▶ return $taxid
Branch: 1 branch
BranchTrueFalseTotal
if $taxid 0 0 0
645 if $taxid;
646  
647 # fetch subject strains from hash in lexical order
648 0 my @sbjct_strains = sort { $a cmp $b } keys %{$taxid_for};
649  
650 # split query and subject strains
651 0 my @split_query_strain = split //xms, $query_strain;
652 0 my @split_sbjct_strains = map { [ split //xms ] } @sbjct_strains;
653  
654 # get score for each alignment through _matcher attribute
655 my @scores = map {
656 0 $self->nw_score( \@split_query_strain, $_ )
657 } @split_sbjct_strains;
658  
659 # get strain with max_score
660 0 my $max_score = List::AllUtils::max @scores;
661 0 ▶ my $max_index = firstidx { $_ == $max_score } @scores;
Subroutine __ANON__: not called CC=1 SCAR=6.9
662 0 my $max_strain = $sbjct_strains[$max_index];
663  
664 # set heuristic threshold score based on shortest string len
665 0 my $threshold = List::AllUtils::min(
666 length $query_strain, length $max_strain
667 ) * $MATCHYOU + $GAP_OPEN;
668  
669 # return strain taxid if above threshold
670 return undef ## no critic (ProhibitExplicitReturnUndef)
671 0 ▶ if $max_score < $threshold;
Branch: 1 branch
BranchTrueFalseTotal
if $max_score < $threshold 0 0 0
672 0 return $taxid_for->{$max_strain};
673 }
674  
675  
676 0 ▶sub get_taxonomy_from_seq_id {
Subroutine get_taxonomy_from_seq_id: not called CC=1 SCAR=6.9
677 0 my $self = shift;
678 0 my $seq_id = shift;
679  
680 return match_on_type $seq_id => (
681  
682 # regular case: $seq_id is a Bio::MUST::Core::SeqId
683 0 ▶ 'Bio::MUST::Core::SeqId' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
684 0 $self->_taxonomy_from_seq_id_(0, $seq_id);
685 },
686  
687 # optimizations for 'seq_ids' already being lineages (e.g., LCAs)
688 # examine context for returning plain array or ArrayRef
689  
690 # case 1: stringified lineage that must be split on semicolons
691 0 ▶ 'Bio::MUST::Core::Types::Lineage' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
692 0 my @taxonomy = split qr{;\ *}xms, $seq_id; # q{;} or q{; }
693 0 ▶ wantarray ? @taxonomy : \@taxonomy;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
694 },
695  
696 # case 2: ArrayRef that just must be dereferenced
697 0 ▶ ArrayRef => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
698 0 ▶ wantarray ? @{$seq_id} : $seq_id
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
699 },
700 0 );
701 }
702  
703  
704 0 ▶sub fetch_lineage { ## no critic (RequireArgUnpacking)
Subroutine fetch_lineage: not called CC=1 SCAR=6.9
Pod documented
705 0 return shift->get_taxonomy_from_seq_id(@_);
706 }
707  
708  
709 0 ▶sub get_taxid_from_taxonomy { ## no critic (RequireArgUnpacking)
Subroutine get_taxid_from_taxonomy: not called CC=5 SCAR=28.4
Pod documented
710 0 my $self = shift;
711  
712 # fetch taxonomy from args using match_on_type strategy (see above)
713 # Note: this could also work from a seq_id but (this would be inefficient)
714 0 my @taxonomy = $self->get_taxonomy_from_seq_id(@_);
715  
716 0 ▶ while (@taxonomy) {
Branch: 1 branch
BranchTrueFalseTotal
if (@taxonomy) 0 0 0
717  
718 # first try to get taxon_id from last taxon
719 0 my $taxon = $taxonomy[-1];
720 0 my $taxon_id = $self->get_taxid_from_name($taxon);
721 0 ▶ return $taxon_id if $taxon_id;
Branch: 1 branch
BranchTrueFalseTotal
if $taxon_id 0 0 0
722  
723 # then try to disambiguate duplicate taxa
724 0 my $dupes_for = $self->dupes_for($taxon);
725 18 ▶ no warnings 'uninitialized'; # avoid undef due to 2-4-level lineages
Subroutine BEGIN: called CC=1 SCAR=0.0
726 0 $taxon_id = $dupes_for->{ join q{; }, @taxonomy[-5..-1] };
727 18 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
728 0 ▶ if ($taxon_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($taxon_id) 0 0 0
729 0 carp "[BMC] Note: managed to disambiguate $taxon based on lineage!";
730 0 return $taxon_id;
731 }
732  
733 # finally retry with previous (= higher) taxon
734 # Note: this should never be used for NCBI lineages
735 # but for, e.g., SILVA lineages where (triplet) taxa may be different
736 0 pop @taxonomy;
737 0 ▶ carp "[BMC] Note: trying to identify $taxon by following lineage..."
Branch: 1 branch
BranchTrueFalseTotal
if @taxonomy 0 0 0
738 if @taxonomy;
739 }
740  
741 0 return undef; ## no critic (ProhibitExplicitReturnUndef)
742 }
743  
744  
745 0 ▶sub get_taxonomy_with_levels_from_seq_id { ## no critic (RequireArgUnpacking)
Subroutine get_taxonomy_with_levels_from_seq_id: not called CC=1 SCAR=6.9
746 0 return shift->_taxonomy_from_seq_id_(1, @_);
747 }
748  
749  
750 0 ▶sub _taxonomy_from_seq_id_ {
Subroutine _taxonomy_from_seq_id_: not called CC=6 SCAR=37.4
751 0 my $self = shift;
752 0 my $levels = shift;
753 0 my $seq_id = shift;
754  
755 # try to fetch taxon_id and corresponding taxonomy
756 0 my $taxon_id = $self->get_taxid_from_seq_id($seq_id);
757 0 ▶ my @taxonomy = $levels ? $self->get_taxonomy_with_levels($taxon_id)
Branch: 1 branch
BranchTrueFalseTotal
$levels ? : 0 0 0
758 : $self->get_taxonomy($taxon_id);
759  
760 # workaround for 'return undef' constructs in Bio::LITE::Taxonomy
761 # ... to ensure that no (undef) list is returned by our additional methods
762 # Note: our policy is thus unlike get_taxonomy and get_taxid_from_name
763 0 ▶ @taxonomy = () unless $taxonomy[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $taxonomy[0] 0 0 0
764 0 ▶ carp '[BMC] Warning: cannot fetch tax for ' . ( $seq_id->full_id || q{''} )
Branch: 1 branch
BranchTrueFalseTotal
unless @taxonomy 0 0 0
Condition0%0/2
$seq_id->full_id || q['']
l!l
00
MC/DC0%0/1
$seq_id->full_id || q['']
$seq_id->full_id
Truth table0%0/2
A
A= $seq_id->full_id
Aresult
11
00
765 . '; ignoring it!' unless @taxonomy;
766  
767 # examine context for returning plain array or ArrayRef
768 0 ▶ return wantarray ? @taxonomy : \@taxonomy;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
769 }
770  
771  
772 0 ▶sub get_taxa_from_taxid { ## no critic (RequireArgUnpacking)
Subroutine get_taxa_from_taxid: not called CC=2 SCAR=17.9
Pod documented
773 0 my $self = shift;
774 0 my $taxon_id = shift;
775  
776 # TODO: consider numbered levels as in fetch-tax.pl?
777 0 my @taxa = map { $self->get_term_at_level($taxon_id, $_) } @_;
778 0 ▶ return wantarray ? @taxa : \@taxa; # specify level through currying
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
779 }
780  
781  
782 # TODO: improve method using the following code snippet
783 # TODO: allows for non-pretty (@) MUST ids in --auto-final-ids
784 # # fetch full taxonomy and lowest taxon
785 # my @taxonomy = $tax->get_taxonomy($taxon_id);
786 # my $org = $taxonomy[-1];
787 #
788 # # proceed only if valid taxon_id
789 # if ($org) {
790 #
791 # # build base MUST id...
792 # $must_id = SeqId->new_with(
793 # org => $org,
794 # taxon_id => $taxon_id,
795 # keep_strain => $ARGV_keep_strain,
796 # )->full_id;
797 #
798  
799 0 ▶sub get_nexus_label_from_seq_id {
Subroutine get_nexus_label_from_seq_id: not called CC=8 SCAR=42.8
800 0 my $self = shift;
801 0 my $seq_id = shift;
802 0 ▶ my $args = shift // {}; # HashRef (should not be empty...)
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
803  
804 # try to fetch organism and accession (or GI number as a fallback)
805 # TODO: allow for choosing between acc/gi when both are available
806 0 my @lineage = $self->get_taxonomy_from_seq_id($seq_id);
807 0 ▶ my $org = pop @lineage
Condition0%0/3
pop @lineage // $seq_id->full_org(" ")
l!l&&r!l&&!r
000
MC/DC0%0/2
pop @lineage // $seq_id->full_org(" ")
pop @lineage $seq_id->full_org(" ")
Truth table0%0/3
A // B
A= pop @lineageB= $seq_id->full_org(" ")
ABresult
1X1
011
000
808 // $seq_id->full_org( q{ } ); # use space before strain
809 0 ▶ my $acc = $args->{append_acc} ? $seq_id->accession // $seq_id->gi : undef;
Branch: 1 branch
BranchTrueFalseTotal
$args->{'append_acc'} ? : 0 0 0
Condition0%0/3
$seq_id->accession // $seq_id->gi
l!l&&r!l&&!r
000
MC/DC0%0/2
$seq_id->accession // $seq_id->gi
$seq_id->accession $seq_id->gi
Truth table0%0/3
A // B
A= $seq_id->accessionB= $seq_id->gi
ABresult
1X1
011
000
810  
811 # build label according to available pieces
812 # Note: fallback to full_id for foreign ids (undefined org)
813 0 ▶ my $label = defined $org && defined $acc ? "$org [$acc]"
Branch: 2 branches
BranchTrueFalseTotal
defined $org && defined $acc ? : 0 0 0
defined $org ? : 0 0 0
Condition0%0/3
defined $org and defined $acc
!ll&&!rl&&r
000
MC/DC0%0/2
defined $org and defined $acc
defined $org defined $acc
Truth table0%0/3
A and B
A= defined $orgB= defined $acc
ABresult
0X0
100
111
814 : defined $org ? $org
815 : $seq_id->full_id
816 ;
817  
818 0 return SeqId->new(full_id => $label)->nexus_id;
819 }
820  
821  
822 # clade analysis methods
823  
824  
825 0 ▶sub get_common_taxonomy_from_seq_ids { ## no critic (RequireArgUnpacking)
Subroutine get_common_taxonomy_from_seq_ids: not called CC=2 SCAR=17.9
Pod documented
826 0 my $self = shift;
827 0 my @seq_ids = @_;
828  
829 # setup optional threshold (if any) to first argument
830 # Note: this approach is used to preserved backwards compatibility
831 # Note: even if SeqId->full_id is a number the test works as expected
832 0 ▶ my $threshold = looks_like_number $seq_ids[0] ? shift @seq_ids : 1.0;
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($seq_ids[0]) ? : 0 0 0
833  
834 # fetch lineages for all seq ids
835 my @lineages = map {
836 0 scalar $self->get_taxonomy_from_seq_id($_) # note the scalar context
837 } @seq_ids;
838  
839 # compute common lineage
840 0 return $self->_common_taxonomy($threshold, @lineages);
841 }
842  
843  
844 0 ▶sub compute_lca { ## no critic (RequireArgUnpacking)
Subroutine compute_lca: not called CC=1 SCAR=6.9
Pod documented
845 0 return shift->get_common_taxonomy_from_seq_ids(@_);
846 }
847  
848 0 ▶sub _common_taxonomy { ## no critic (RequireArgUnpacking)
Subroutine _common_taxonomy: not called CC=7 SCAR=40.3
849 0 my $self = shift;
850 0 my $threshold = shift;
851 0 my @lineages = @_;
852  
853 # ignore missing lineages
854 # TODO: decide whether missing lineages should be taken into account
855 0 ▶ @lineages = grep { @{$_} ? $_ : () } @lineages;
Branch: 1 branch
BranchTrueFalseTotal
@{$_;} ? : 0 0 0
856  
857 0 my @common_lineage;
858  
859 # original version: strict consensus
860 # Note the use of a dynamically-sized multiple ArrayRef iterator
861 # to walk down all lineages in parallel
862 # my $ea = each_arrayref(@lineages);
863 #
864 # TAXON:
865 # while ( my @taxa = $ea->() ) {
866 # no warnings 'uninitialized'; # avoid undef due to longer lineages
867 # last TAXON if uniq(@taxa) > 1;
868 # push @common_lineage, shift @taxa;
869 # }
870  
871 # current version: threshold-based majority-rule consensus
872 # algorithm: at each taxonomic rank count all seen taxa
873 # if the most popular taxon is seen > threshold (w.r.t. all lineages)
874 # then continue with the lineages featuring it
875 # otherwise stop at previous taxon
876 0 my $n = @lineages;
877  
878 TAXON:
879 0 ▶ for (my $i = 0; $n; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n) 0 0 0
880 0 ▶ my %count_for = count_by { $_->[$i] // q{} } @lineages;
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/2
$_->[$i] // ""
l!l
00
MC/DC0%0/1
$_->[$i] // ""
$_->[$i]
Truth table0%0/2
A
A= $_->[$i]
Aresult
11
00
881 0 ▶ my $taxon = max_by { $count_for{$_} } keys %count_for;
Subroutine __ANON__: not called CC=1 SCAR=6.9
882 0 ▶ last TAXON unless $taxon;
Branch: 1 branch
BranchTrueFalseTotal
unless $taxon 0 0 0
883 0 my $taxon_n = $count_for{$taxon};
884 0 ▶ last TAXON if $taxon_n / $n < $threshold;
Branch: 1 branch
BranchTrueFalseTotal
if $taxon_n / $n < $threshold 0 0 0
885 0 push @common_lineage, $taxon;
886 0 ▶ @lineages = grep { ( $_->[$i] // q{} ) eq $taxon } @lineages;
Condition0%0/2
$_->[$i] // ""
l!l
00
MC/DC0%0/1
$_->[$i] // ""
$_->[$i]
Truth table0%0/2
A
A= $_->[$i]
Aresult
11
00
887 }
888  
889 # examine context for returning plain array or ArrayRef
890 0 ▶ return wantarray ? @common_lineage : \@common_lineage;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
891 }
892  
893 # tree annotation methods
894  
895  
896 0 ▶sub attach_taxonomies_to_terminals {
Subroutine attach_taxonomies_to_terminals: not called CC=3 SCAR=24.8
Pod documented
897 0 my $self = shift;
898 0 my $tree = shift;
899  
900 #### ATTACHING TAXONOMIES TO TERMINALS...
901  
902 # transparently fetch Bio::Phylo component object
903 0 ▶ $tree = $tree->tree if $tree->isa('Bio::MUST::Core::Tree');
Branch: 1 branch
BranchTrueFalseTotal
if $tree->isa("Bio::MUST::Core::Tree") 0 0 0
904  
905 # store tip taxonomies in Bio::Phylo::Forest::Node generic attributes
906 0 for my $tip ( @{ $tree->get_terminals } ) {
907  
908 # fetch taxonomy (and level list) from tip's seq id
909 0 my @tax = $self->get_taxonomy_with_levels_from_seq_id($tip->get_name);
910  
911 # attach them as distinct ArrayRefs
912 0 $tip->set_generic('taxonomy' => [ map { $_->[0] } @tax ] );
913 0 $tip->set_generic('levels' => [ map { $_->[1] } @tax ] );
914  
915 # Note: levels are needed for robust clade naming and collapsing.
916 # Indeed, get_level_from_name() can return incorrect level when a name
917 # exists at more than one taxonomic level in NCBI Taxonomy (e.g.,
918 # Bacteria, which is also an insect genus).
919 }
920  
921 0 return;
922 }
923  
924  
925  
926 0 ▶sub attach_taxonomies_to_internals {
Subroutine attach_taxonomies_to_internals: not called CC=1 SCAR=6.9
Pod documented
927 0 my $self = shift;
928 0 my $tree = shift;
929  
930 # post-order tree traversal
931 $tree->tree->visit_depth_first(
932  
933 # infer common taxonomy from direct children of each node
934 0 ▶ -post => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
935 0 my $node = shift;
936 0 ▶ return if $node->is_terminal;
Branch: 1 branch
BranchTrueFalseTotal
if $node->is_terminal 0 0 0
937  
938 # collect children lineages
939 # ... and track the longest (better to be safe...) level list
940 0 my @lineages;
941 my @max_levels;
942 0 ▶ for (my $i = 0; my $child = $node->get_child($i); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $child = $node->get_child($i)) 0 0 0
943 0 push @lineages, $child->get_generic('taxonomy');
944 0 my @levels = @{ $child->get_generic('levels') };
945 0 ▶ @max_levels = @levels if @levels > @max_levels;
Branch: 1 branch
BranchTrueFalseTotal
if @levels > @max_levels 0 0 0
946 }
947  
948 # store into current node their common lineage
949 # ... and cut down level list to match this common lineage
950 0 my @common_lineage = $self->_common_taxonomy(1.0, @lineages);
951 0 $node->set_generic('taxonomy' => \@common_lineage);
952 0 $node->set_generic(
953 'levels' => [ @max_levels[0..$#common_lineage] ]
954 );
955  
956 0 return;
957 },
958 0 );
959  
960 0 return;
961 }
962  
963  
964  
965 0 ▶sub attach_taxa_to_entities {
Subroutine attach_taxa_to_entities: not called CC=8 SCAR=42.8
Pod documented
966 0 my $self = shift;
967 0 my $tree = shift;
968 0 ▶ my $args = shift // {}; # HashRef (should not be empty...)
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
969  
970 # setup minimal taxonomic level(s) to reach
971 # Note 1: only named levels can be selected (see list above)
972 # Note 2: thus, 'no rank' results in the lowest possible taxon
973 # Note 3: default values are provided
974 0 my %arg_levels = ( name => 'no rank', collapse => 'skip', %{$args} );
975 my %target_for = map {
976 0 $_ => $self->rank_for( $arg_levels{$_} )
977 } keys %arg_levels;
978  
979 # ensure meaningful subtree collapsing WRT naming
980 0 ▶ if ($target_for{collapse} < $target_for{name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($target_for{"collapse"} < $target_for{"name"}) 0 0 0
981 0 carp '[BMC] Warning: collapsing level must include naming level;'
982 . ' upgrading!';
983 0 $target_for{collapse} = $target_for{name};
984 }
985  
986 # update both terminal and internal nodes
987 # attach lowest taxon with level higher or equal to target level(s)
988  
989 NODE:
990 0 for my $node ( @{ $tree->tree->get_entities } ) {
991  
992 # reset taxon for robustness
993 0 my $is_named;
994 0 $node->set_generic('taxon' => undef);
995 0 $node->set_generic('taxon_collapse' => undef);
996  
997 # walk up node lineage
998 0 my @lineage = @{ $node->get_generic('taxonomy') };
999 0 my @levels = @{ $node->get_generic('levels') };
1000 0 ▶ while (my $taxon = pop @lineage) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $taxon = pop @lineage) 0 0 0
1001  
1002 # OLD VERSION DERIVING LEVEL FROM TAXON NAME
1003 # ... if taxon was the highest in the lineage then rank it at top
1004 # Note: this is needed to preserve 'cellular organisms'
1005 # my $rank = @lineage == 0 ? 0 # 0 means 'top rank'
1006 # : $self->rank_for( $self->get_level_from_name($taxon) );
1007  
1008 # get rank for taxon
1009 0 my $rank = $self->rank_for( pop @levels );
1010  
1011 # name subtree at target level or above
1012 0 ▶ if (!$is_named && $rank >= $target_for{name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_named and $rank >= $target_for{"name"}) 0 0 0
Condition0%0/3
not $is_named and $rank >= $target_for{"name"}
!ll&&!rl&&r
000
MC/DC0%0/2
not $is_named and $rank >= $target_for{"name"}
not $is_named $rank >= $target_for{"name"}
Truth table0%0/3
not(A) and B
A= not $is_namedB= $rank >= $target_for{"name"}
ABresult
0X0
100
111
1013 0 $node->set_generic('taxon' => $taxon);
1014 0 $is_named = 1; # to get the lowest possible taxon
1015 } # ... while keeping walking up to collapse at a higher level
1016  
1017 # collapse subtree only at target level
1018 0 ▶ if ($rank == $target_for{collapse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rank == $target_for{"collapse"}) 0 0 0
1019 0 $node->set_generic('taxon_collapse' => $taxon);
1020 0 next NODE; # can stop walking up now!
1021 }
1022 }
1023 }
1024  
1025 0 return;
1026 }
1027  
1028 # Listable IdList and IdMapper factory methods
1029  
1030 # TODO: decide on whether this kind of check is needed and where...
1031  
1032 # around qr{ \A taxonomic_ }xms => sub {
1033 # my $method = shift;
1034 # my $self = shift;
1035 # my $listable = shift;
1036 #
1037 # # ensure the object is listable (we could also test for the role)
1038 # unless ( $listable->can('all_seq_ids') ) {
1039 # carp 'Cannot build list/mapper from ' . ref($listable) . '; aborting!';
1040 # return;
1041 # }
1042 #
1043 # return $self->$method($listable, @_);
1044 # };
1045  
1046 # TODO: remove support for GI numbers
1047  
1048  
1049 0 ▶sub gi_mapper {
Subroutine gi_mapper: not called CC=1 SCAR=6.9
Pod documented
1050 0 my $self = shift;
1051 0 my $listable = shift;
1052  
1053 return IdMapper->new(
1054 long_ids => [ $self->_taxids_from_gis($listable) ],
1055 0 abbr_ids => [ map { $_->full_id } $listable->all_seq_ids ],
1056 );
1057 }
1058  
1059 18 const my $BATCH_SIZE => 252;
1060 18 const my $GOLDEN_RATIO => 1.618;
1061 18 const my $MAX_ATTEMPT => 3;
1062  
1063 0 ▶sub _taxids_from_gis {
Subroutine _taxids_from_gis: not called CC=10 SCAR=47.0
1064 0 my $self = shift;
1065 0 my $listable = shift;
1066  
1067 # get full_ids and GI numbers
1068 0 my @seq_ids = $listable->all_seq_ids;
1069 0 my @full_ids = map { $_->full_id } @seq_ids;
1070 0 my @gis = map { $_->gi } @seq_ids;
1071 0 ### GIs to process: scalar @gis
1072 0 my @uniq_gis = uniq @gis;
1073 0 ### Unique GIs to process: scalar @uniq_gis
1074  
1075 # try to associate taxon_ids to GIs using binary GI-to-taxid mapper
1076 0 my %taxid_for;
1077 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1078 0 %taxid_for = map { $_ => $self->get_taxid_from_gi($_) } @uniq_gis;
1079 }
1080 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1081 0 ### Note: 'Cannot load binary GI-to-taxid mapper'
1082 0 };
1083  
1084 # collect missing taxon_ids
1085 0 my @miss_gis = grep { not $taxid_for{$_} } @uniq_gis;
1086  
1087 0 ▶ if (@miss_gis) {
Branch: 1 branch
BranchTrueFalseTotal
if (@miss_gis) 0 0 0
1088 0 ### Unique GIs missing from binary GI-to-taxid mapper: scalar @miss_gis
1089 0 ### Fetching corresponding taxon_ids online instead...
1090 }
1091  
1092 0 my %miss_taxid_for;
1093 0 my $batch_size = $BATCH_SIZE;
1094 0 my $attempt = 1;
1095  
1096 0 ESUMMARY:
1097 0 ▶ while (@miss_gis) { ### Iterating on missing GIs |===[%] |
Branch: 1 branch
BranchTrueFalseTotal
if (@miss_gis) 0 0 0
1098 0 my $total = @miss_gis;
1099 0 $batch_size = List::AllUtils::min($batch_size, $total);
1100 #### $total
1101 #### $batch_size
1102 #### $attempt
1103  
1104 BATCH:
1105 0 ▶ for (my $i = 0; $i < $total; $i += $batch_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $total) 0 0 0
1106 0 my $end = List::AllUtils::min($i + $batch_size, $#miss_gis);
1107 #### $i
1108 #### $end
1109  
1110 # fetch eSummaries for current batch of GI numbers
1111 0 my $report = get(
1112 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?'
1113 . 'db=protein&id=' . join ',', @miss_gis[$i..$end]
1114 );
1115  
1116 # stop using current batch size if no answer from NCBI servers
1117 0 ▶ last BATCH unless $report;
Branch: 1 branch
BranchTrueFalseTotal
unless $report 0 0 0
1118  
1119 # parse XML report into hash tree
1120 0 my $ob = XML::Bare->new( text => $report );
1121 0 my $root = $ob->parse();
1122  
1123 # capture GI number/taxon_id pairs for each eSummary of the report
1124 0 for my $docsum ( @{ $root->{eSummaryResult}{DocSum} } ) {
1125 0 my @fields = @{ $docsum->{Item} };
1126 0 ▶ my $gi = first { $_->{Name}->{value} eq 'Gi' } @fields;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1127 0 ▶ my $taxid = first { $_->{Name}->{value} eq 'TaxId' } @fields;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1128 0 $miss_taxid_for{ $gi->{value} } = $taxid->{value};
1129 }
1130 }
1131  
1132 # update hash with retrieved taxon_ids
1133 0 %taxid_for = (%taxid_for, %miss_taxid_for);
1134  
1135 # collect anew missing taxon_ids
1136 0 @miss_gis = grep { not $taxid_for{$_} } @uniq_gis;
1137  
1138 # if some taxon_ids are still missing...
1139 0 ▶ if (@miss_gis) {
Branch: 1 branch
BranchTrueFalseTotal
if (@miss_gis) 0 0 0
1140  
1141 # reduce batch_size after MAX_ATTEMPT attempts
1142 0 ▶ if (++$attempt > $MAX_ATTEMPT) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$attempt > $MAX_ATTEMPT) 0 0 0
1143 0 $batch_size = floor($batch_size / $GOLDEN_RATIO);
1144 0 $attempt = 1;
1145 }
1146  
1147 # stop trying if batch_size falls to zero
1148 0 ▶ unless ($batch_size) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($batch_size) 0 0 0
1149 0 carp '[BMC] Warning: no answer from NCBI E-utilities;'
1150 . ' dropping GIs!';
1151 0 last ESUMMARY;
1152 }
1153 }
1154 }
1155  
1156 0 ### Unique GIs retrieved online: scalar keys %miss_taxid_for
1157 0 ### Unique GIs still missing: scalar @miss_gis
1158  
1159 # build new ids by prepending taxon_ids to full_ids
1160 0 my @taxids_gis;
1161 0 my $ea = each_array(@full_ids, @gis);
1162 0 ▶ while ( my ($full_id, $gi) = $ea->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$ea()) 0 0 0
1163 0 push @taxids_gis, $taxid_for{$gi} . '|' . $full_id;
1164 }
1165  
1166 0 return @taxids_gis;
1167 }
1168  
1169  
1170  
1171 0 ▶sub tab_mapper {
Subroutine tab_mapper: not called CC=12 SCAR=50.5
Pod documented
1172 0 my $self = shift;
1173 0 my $infile = shift;
1174 0 ▶ my $args = shift // {};
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1175  
1176 0 ▶ my $col = $args->{column} // 1;
Condition0%0/2
$args->{"column"} // 1
l!l
00
MC/DC0%0/1
$args->{"column"} // 1
$args->{"column"}
Truth table0%0/2
A
A= $args->{"column"}
Aresult
11
00
1177 0 ▶ my $sep = $args->{separator} // qr{\t}xms;
Condition0%0/2
$args->{"separator"} // qr/\t/msx
l!l
00
MC/DC0%0/1
$args->{"separator"} // qr/\t/msx
$args->{"separator"}
Truth table0%0/2
A
A= $args->{"separator"}
Aresult
11
00
1178 0 my $idm = $args->{gi2taxid};
1179  
1180 0 open my $in, '<', $infile;
1181  
1182 0 tie my %family_for, 'Tie::IxHash';
1183  
1184 LINE:
1185 0 ▶ while ( my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
1186 0 chomp $line;
1187  
1188 # skip empty lines and comment lines
1189 0 ▶ next LINE if $line =~ $EMPTY_LINE
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ or $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/ 0 0 0
Condition0%0/3
$line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ or $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
l!l&&r!l&&!r
000
MC/DC0%0/2
$line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ or $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
$line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
Truth table0%0/3
A or B
A= $line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/B= $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
ABresult
1X1
011
000
1190 || $line =~ $COMMENT_LINE;
1191  
1192 0 my @fields = split $sep, $line;
1193 0 $family_for{ $fields[0] } = $fields[$col];
1194 }
1195  
1196 0 my @abbr_ids = keys %family_for;
1197 0 my @must_ids = @abbr_ids;
1198  
1199 0 ▶ if ($idm) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idm) 0 0 0
1200  
1201 # build gi2taxid 'mapper'
1202 0 my $gi_mapper = IdMapper->load($idm);
1203 0 my @gis = map { $_->gi } $gi_mapper->all_abbr_seq_ids;
1204 0 my @taxon_ids = map { $_->taxon_id } $gi_mapper->all_long_seq_ids;
1205 0 my %taxid_for = mesh @gis, @taxon_ids;
1206  
1207 # build modern seq_ids from GIs using 'mapper'
1208 0 for my $id (@must_ids) {
1209 0 my $taxon_id = $taxid_for{ SeqId->new( full_id => $id )->gi };
1210 0 my @taxonomy = $self->get_taxonomy($taxon_id);
1211 0 my $org = $taxonomy[-1];
1212 0 $id = SeqId->new_with(
1213 org => $org,
1214 taxon_id => $taxon_id,
1215 gi => $id, # actually not a 'pure' GI here
1216 )->full_id;
1217 }
1218 }
1219  
1220 0 my @long_ids;
1221  
1222 0 my $ea = each_array @must_ids, @abbr_ids;
1223 0 ▶ while ( my ($must_id, $abbr_id) = $ea->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$ea()) 0 0 0
1224 0 ▶ ( my $family = $family_for{$abbr_id} // q{} ) =~ tr/- @_/./;
Condition0%0/2
$family_for{$abbr_id} // ""
l!l
00
MC/DC0%0/1
$family_for{$abbr_id} // ""
$family_for{$abbr_id}
Truth table0%0/2
A
A= $family_for{$abbr_id}
Aresult
11
00
1225 0 ▶ $family .= '-' if $family;
Branch: 1 branch
BranchTrueFalseTotal
if $family 0 0 0
1226 0 push @long_ids, $family . $must_id;
1227 }
1228  
1229 0 return IdMapper->new(
1230 long_ids => \@long_ids,
1231 abbr_ids => \@abbr_ids,
1232 );
1233 }
1234  
1235  
1236  
1237 0 ▶sub tax_mapper { ## no critic (RequireArgUnpacking)
Subroutine tax_mapper: not called CC=1 SCAR=6.9
Pod documented
1238 0 my $self = shift;
1239 0 my $listable = shift;
1240  
1241 return IdMapper->new(
1242 long_ids => [ map {
1243 0 $self->get_nexus_label_from_seq_id($_, @_)
1244 } $listable->all_seq_ids ],
1245 0 abbr_ids => [ map { $_->full_id } $listable->all_seq_ids ],
1246 );
1247 }
1248  
1249  
1250  
1251 0 ▶sub tax_filter {
Subroutine tax_filter: not called CC=1 SCAR=6.9
Pod documented
1252 0 my $self = shift;
1253 0 my $list = shift;
1254  
1255 0 return Filter->new( tax => $self, _specs => $list );
1256 }
1257  
1258  
1259  
1260 0 ▶sub tax_criterion {
Subroutine tax_criterion: not called CC=1 SCAR=6.9
Pod documented
1261 0 my $self = shift;
1262 0 my $args = shift;
1263  
1264 0 $args->{tax_filter} = $self->tax_filter( $args->{tax_filter} );
1265  
1266 0 return Criterion->new($args);
1267 }
1268  
1269  
1270  
1271 0 ▶sub tax_category {
Subroutine tax_category: not called CC=1 SCAR=6.9
Pod documented
1272 0 my $self = shift;
1273 0 my $args = shift;
1274  
1275 $args->{criteria} = [
1276 0 map { $self->tax_criterion($_) } @{ $args->{criteria} }
1277 ];
1278  
1279 0 return Category->new($args);
1280 }
1281  
1282  
1283 # Classifier/Labeler/ColorScheme factory methods
1284  
1285  
1286 0 ▶sub tax_classifier {
Subroutine tax_classifier: not called CC=1 SCAR=6.9
Pod documented
1287 0 my $self = shift;
1288 0 my $args = shift;
1289  
1290 $args->{categories} = [
1291 0 map { $self->tax_category($_) } @{ $args->{categories} }
1292 ];
1293  
1294 0 return Classifier->new($args);
1295 }
1296  
1297 # example of input HashRef for tax_classifier
1298 # 'min', 'max' and 'description' keys are both optional
1299 # categories => [
1300 # {
1301 # criteria => [
1302 # {
1303 # max => undef,
1304 # min => 1,
1305 # tax_filter => [
1306 # '+Latimeria'
1307 # ]
1308 # },
1309 # {
1310 # tax_filter => [
1311 # '+Protopterus'
1312 # ]
1313 # },
1314 # {
1315 # tax_filter => [
1316 # '+Danio',
1317 # '+Oreochromis'
1318 # ]
1319 # },
1320 # {
1321 # tax_filter => [
1322 # '+Xenopus'
1323 # ]
1324 # },
1325 # {
1326 # tax_filter => [
1327 # '+Anolis',
1328 # '+Gallus',
1329 # '+Meleagris',
1330 # '+Taeniopygia'
1331 # ]
1332 # },
1333 # {
1334 # tax_filter => [
1335 # '+Mammalia'
1336 # ]
1337 # }
1338 # ],
1339 # description => 'strict species sampling',
1340 # label => 'strict'
1341 # },
1342 # {
1343 # criteria => [
1344 # {
1345 # tax_filter => [
1346 # '+Latimeria'
1347 # ]
1348 # },
1349 # {
1350 # tax_filter => [
1351 # '+Protopterus'
1352 # ]
1353 # },
1354 # {
1355 # tax_filter => [
1356 # '+Danio',
1357 # '+Oreochromis'
1358 # ]
1359 # },
1360 # {
1361 # tax_filter => [
1362 # '+Amphibia',
1363 # '+Amniota'
1364 # ]
1365 # }
1366 # ],
1367 # description => 'loose species sampling',
1368 # label => 'loose'
1369 # }
1370 # ]
1371  
1372  
1373  
1374 0 ▶sub tax_labeler_from_systematic_frame {
Subroutine tax_labeler_from_systematic_frame: not called CC=1 SCAR=6.9
Pod documented
1375 0 my $self = shift;
1376 0 my $infile = shift;
1377  
1378 # Thursday 26 November 2015 at 15 hours 21
1379 # ((((((Crenarchaeota:371:88:-1,Korarchaeota:371:72:-1)a:15:80:-1,...)Tree of Life:3:16:-1;
1380  
1381 # ensure that we get a parseable tree from the .fra file
1382 # by considering only line 2 and turning all funny 'branch lengths' to 1
1383 0 my @lines = file($infile)->slurp;
1384 0 (my $newick_str = pop @lines) =~ s/(?: :-?(\d+) ){3}/:1/xmsg;
1385  
1386 # parse tree using Bio::Phylo
1387 # Note: keep whitespace because tip labels are not between quotes
1388 0 my $tree = parse(
1389 -format => 'newick',
1390 -string => $newick_str,
1391 -keep_whitespace => 1,
1392 )->first;
1393  
1394 # extract tip labels
1395 0 my @labels = map { $_->get_name } @{ $tree->get_terminals };
1396  
1397 # build classifier from labels
1398 0 return $self->tax_labeler_from_list( \@labels );
1399 }
1400  
1401  
1402  
1403 0 ▶sub tax_labeler_from_list {
Subroutine tax_labeler_from_list: not called CC=1 SCAR=6.9
Pod documented
1404 0 my $self = shift;
1405 0 my $list = shift;
1406  
1407 0 return Labeler->new( tax => $self, labels => $list );
1408 }
1409  
1410  
1411  
1412 0 ▶sub load_color_scheme { ## no critic (RequireArgUnpacking)
Subroutine load_color_scheme: not called CC=1 SCAR=6.9
Pod documented
1413 0 my $self = shift;
1414 0 my $scheme = ColorScheme->new( tax => $self );
1415 0 return $scheme->load(@_);
1416 }
1417  
1418  
1419  
1420 0 ▶sub eq_tax { ## no critic (RequireArgUnpacking)
Subroutine eq_tax: not called CC=4 SCAR=30.0
Pod documented
1421 0 my $self = shift;
1422 0 my $got = shift;
1423 0 my $expect = shift;
1424 0 my $classifier = shift;
1425  
1426 # classify got and expect orgs
1427 0 my $got_taxon = $classifier->classify($got, @_);
1428 0 my $exp_taxon = $classifier->classify($expect, @_);
1429  
1430 # use context to decide what to return
1431 # list context: return taxon labels
1432 0 ▶ return ($got_taxon, $exp_taxon)
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 0 0 0
1433 if wantarray;
1434  
1435 # scalar context: compare taxon labels if both are defined
1436 return undef ## no critic (ProhibitExplicitReturnUndef)
1437 0 ▶ unless $got_taxon && $exp_taxon;
Branch: 1 branch
BranchTrueFalseTotal
unless $got_taxon and $exp_taxon 0 0 0
Condition0%0/3
$got_taxon and $exp_taxon
!ll&&!rl&&r
000
MC/DC0%0/2
$got_taxon and $exp_taxon
$got_taxon $exp_taxon
Truth table0%0/3
A and B
A= $got_taxonB= $exp_taxon
ABresult
0X0
100
111
1438  
1439 0 return $got_taxon eq $exp_taxon;
1440 }
1441  
1442  
1443 # I/O METHODS
1444  
1445 18 const my $CACHEDB => 'cachedb.bin';
1446  
1447  
1448 0 ▶sub new_from_cache { ## no critic (RequireArgUnpacking)
Subroutine new_from_cache: not called CC=1 SCAR=6.9
Pod documented
1449 0 my $class = shift;
1450 0 my %args = @_; # TODO: handle HashRef?
1451  
1452 0 ### Loading NCBI (or GTDB) Taxonomy from binary cache file...
1453 0 my $tax_dir = dir( glob $args{tax_dir} );
1454 0 my $cachefile = file($tax_dir, $CACHEDB);
1455 0 my $tax = $class->load($cachefile, inject => { tax_dir => $tax_dir } );
1456  
1457 0 ### Done!
1458 0 return $tax;
1459 }
1460  
1461  
1462 0 ▶sub update_cache {
Subroutine update_cache: not called CC=1 SCAR=6.9
Pod documented
1463 0 my $self = shift;
1464  
1465 0 my $cachefile = file($self->tax_dir, $CACHEDB);
1466 0 ### Updating binary cache file: $cachefile->stringify
1467 0 $self->store($cachefile);
1468  
1469 0 ### Done!
1470 0 return 1;
1471 }
1472  
1473  
1474 # class method to setup local taxonomy database
1475  
1476  
1477 0 ▶sub setup_taxdir {
Subroutine setup_taxdir: not called CC=4 SCAR=30.0
Pod documented
1478 0 my $class = shift;
1479 0 my $tax_dir = shift;
1480 0 ▶ my $args = shift // {}; # HashRef (should not be empty...)
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1481  
1482 0 my $source = $args->{source};
1483  
1484 0 ▶ $class->_setup_ncbi_taxdir($tax_dir, $args)
Branch: 1 branch
BranchTrueFalseTotal
if $source eq "ncbi" 0 0 0
1485 if $source eq 'ncbi';
1486  
1487 0 ▶ $class->_setup_gtdb_taxdir($tax_dir)
Branch: 1 branch
BranchTrueFalseTotal
if $source eq "gtdb" 0 0 0
1488 if $source eq 'gtdb';
1489  
1490 0 return;
1491 }
1492  
1493  
1494 0 ▶sub _setup_ncbi_taxdir {
Subroutine _setup_ncbi_taxdir: not called CC=16 SCAR=56.1
1495 0 my $class = shift;
1496 0 my $tax_dir = shift;
1497 0 ▶ my $args = shift // {}; # HashRef (should not be empty...)
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1498  
1499 0 ▶ my $gi_mapper = $args->{gi_mapper} // 0;
Condition0%0/2
$args->{"gi_mapper"} // 0
l!l
00
MC/DC0%0/1
$args->{"gi_mapper"} // 0
$args->{"gi_mapper"}
Truth table0%0/2
A
A= $args->{"gi_mapper"}
Aresult
11
00
1500  
1501 # setup local directory
1502 0 $tax_dir = dir( glob $tax_dir );
1503 0 $tax_dir->mkpath();
1504  
1505 0 ### Installing NCBI Taxonomy database to: $tax_dir->stringify
1506 0 ### Please be patient...
1507  
1508 # setup remote archive access
1509 0 my $base = 'https://ftp.ncbi.nih.gov/pub/taxonomy';
1510 0 ▶ my @targets = (
Branch: 1 branch
BranchTrueFalseTotal
$gi_mapper ? : 0 0 0
1511 'taxdump.tar.gz',
1512 $gi_mapper ? qw(gi_taxid_nucl.dmp.gz gi_taxid_prot.dmp.gz) : ()
1513 );
1514  
1515 # download and install file(s)...
1516 # ... first, the taxon_id version...
1517 0 my @dmpfiles;
1518 0 for my $target (@targets) {
1519 0 my $url = "$base/$target";
1520  
1521 0 ### Downloading: $url
1522 0 my $zipfile = file($tax_dir, $target)->stringify;
1523 # Note: stringify is required by getstore
1524 0 my $ret_code = getstore($url, $zipfile);
1525 0 ▶ croak "[BMC] Error: cannot download $url: error $ret_code; aborting!"
Branch: 1 branch
BranchTrueFalseTotal
unless $ret_code == 200 0 0 0
1526 unless $ret_code == 200;
1527  
1528 # TODO: use modules for unarchiving (not that easy)
1529  
1530 0 ### Unarchiving: $zipfile
1531 0 ▶ if ($target =~ m/\A gi_taxid/xms) { # GI mappers
Branch: 1 branch
BranchTrueFalseTotal
if ($target =~ /\A gi_taxid/msx) { } 0 0 0
1532 0 system("gzip -d $zipfile");
1533 0 push @dmpfiles, change_suffix( $zipfile, q{} );
1534 }
1535 else { # main tax archive
1536 0 system("tar -xzf $zipfile -C $tax_dir");
1537 0 file($zipfile)->remove;
1538 }
1539 }
1540  
1541 # delete gca files if any
1542 0 my $gcanamefile = file($tax_dir, 'gca0-names.dmp');
1543 0 my $gcanodefile = file($tax_dir, 'gca0-nodes.dmp');
1544 0 ▶ $gcanamefile->remove if -e $gcanamefile;
Branch: 1 branch
BranchTrueFalseTotal
if -e $gcanamefile 0 0 0
1545 0 ▶ $gcanodefile->remove if -e $gcanodefile;
Branch: 1 branch
BranchTrueFalseTotal
if -e $gcanodefile 0 0 0
1546  
1547 #... second, the accession_id version
1548 0 $class->_make_gca_files($tax_dir);
1549  
1550 # return true on success (only check main files)
1551 0 ▶ if ( -r $gcanamefile && -r $gcanodefile ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $gcanamefile and -r $gcanodefile) 0 0 0
Condition0%0/3
-r $gcanamefile and -r $gcanodefile
!ll&&!rl&&r
000
MC/DC0%0/2
-r $gcanamefile and -r $gcanodefile
-r $gcanamefile -r $gcanodefile
Truth table0%0/3
A and B
A= -r $gcanamefileB= -r $gcanodefile
ABresult
0X0
100
111
1552 0 ### Successfully wrote GCA-based files!
1553 }
1554  
1555 # delete cache if any
1556 0 my $cachefile = file($tax_dir, $CACHEDB);
1557 0 ▶ $cachefile->remove if -e $cachefile;
Branch: 1 branch
BranchTrueFalseTotal
if -e $cachefile 0 0 0
1558  
1559 # optionally build binary GI mapper from GI-to-taxid flat files
1560 0 ▶ if ($gi_mapper) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gi_mapper) 0 0 0
1561 0 my $mrgfile = file($tax_dir, 'gi_taxid_nucl_prot.dmp')->stringify;
1562 0 ### Merging GI-to-taxid flat files to: $mrgfile
1563 0 system("sort -nm @dmpfiles > $mrgfile");
1564 0 my $binfile = change_suffix($mrgfile, '.bin');
1565 0 ### Building binary GI-to-taxid mapper: $binfile
1566 0 new_dict( in => $mrgfile, out => $binfile );
1567 0 file($_)->remove for @dmpfiles, $mrgfile;
1568 }
1569  
1570 # return true on success (only check main files)
1571 0 ▶ if ( -r file($tax_dir, 'names.dmp') && -r file($tax_dir, 'nodes.dmp') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r file($tax_dir, "names.dmp") and -r file($tax_dir, "nodes.dmp")) 0 0 0
Condition0%0/3
-r file($tax_dir, "names.dmp") and -r file($tax_dir, "nodes.dmp")
!ll&&!rl&&r
000
MC/DC0%0/2
-r file($tax_dir, "names.dmp") and -r file($tax_dir, "nodes.dmp")
-r file($tax_dir, "names.dmp") -r file($tax_dir, "nodes.dmp")
Truth table0%0/3
A and B
A= -r file($tax_dir, "names.dmp")B= -r file($tax_dir, "nodes.dmp")
ABresult
0X0
100
111
1572 0 ### Successfully wrote taxid files!
1573 0 return 1;
1574 }
1575  
1576 0 ### Failed installation!
1577 0 return 0;
1578 }
1579  
1580 # December 2024
1581 # $ cd ~/taxdump
1582 # $ wc -l assembly_summary_*txt
1583 # 2698890 assembly_summary_genbank.txt
1584 # 75493 assembly_summary_genbank_historical.txt
1585 # 414559 assembly_summary_refseq.txt
1586 # 93051 assembly_summary_refseq_historical.txt
1587 # 3281993 total
1588 #
1589 # $ cut -f1 *genbank_historical.txt | cut -c5- | sort | uniq > gca_hist
1590 # $ cut -f1 *genbank.txt | cut -c5- | sort | uniq > gca
1591 # $ cut -f1 *refseq_historical.txt | cut -c5- | sort | uniq > gcf_hist
1592 # $ cut -f1 *refseq.txt | cut -c5- | sort | uniq > gcf
1593 #
1594 # $ cat gca gca_hist | sort | uniq -d
1595 # 2 # header
1596 # $ cat gcf gcf_hist | sort | uniq -d
1597 # 2 # header
1598 # $ cat gca gcf | sort | uniq -d | wc -l
1599 # 411120 # incl. header
1600 # $ cat gca gcf_hist | sort | uniq -d | wc -l
1601 # 79371 # incl. header
1602 #
1603 # $ sort gca_hist gca > gca_all
1604 # $ sort gcf_hist gcf > gcf_all
1605 #
1606 # $ join gcf_all gca_all > redund_gcf
1607 # $ wc -l redund_gcf
1608 # 507183 redund_gcf
1609 # $ diff redund_gcf gcf_all | grep \> | cut -c3- > uniq_gcf
1610 # $ wc -l uniq_gcf
1611 # 433 uniq_gcf # these RefSeq's GCFs are not found in GenBank's GCAs
1612 #
1613 # # check output of BMC's (smart) skipping of redundant GCFs
1614 # $ grep GCF gca0-names.dmp | cut -f1 | cut -c5- | sort > uniq_gcf_bmc
1615 # $ wc -l uniq_gcf_bmc
1616 # 431 uniq_gcf_bmc # identical (only missing header)
1617 #
1618 # # now these are turned to GCAs in cachedb.bin
1619  
1620 0 ▶sub _make_gca_files {
Subroutine _make_gca_files: not called CC=18 SCAR=58.3
1621 0 my $class = shift;
1622 0 my $tax_dir = shift;
1623  
1624 0 const my $FS => qq{\t|\t};
1625 0 const my $FS_REGEX => qr{\t \| \t}xms;
1626  
1627 0 my %rank_for;
1628 my %parent_taxid_for;
1629  
1630 # open nodes.dmp file
1631 0 my $nodes = file($tax_dir, 'nodes.dmp');
1632 0 open my $in, '<', $nodes;
1633  
1634 # get taxon_id and parent_taxon_id from nodes.dmp file
1635 0 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
1636 0 chomp $line;
1637 0 my ($taxon_id, $parent_taxon_id, $rank) = $line
1638 =~ m/^ (\d+) $FS_REGEX (\d+) $FS_REGEX ([^\t]+) $FS_REGEX/xmsg;
1639 0 $rank_for{$taxon_id} = $rank;
1640 0 $parent_taxid_for{$taxon_id} = $parent_taxon_id;
1641 }
1642  
1643 # create helper Taxonomy object
1644 0 my $tax = $class->new( tax_dir => $tax_dir );
1645  
1646 # define remote assembly reports filenames
1647 # Note: the order is significant (last files dominate over first files)
1648 0 my @targets_acc = qw(
1649 assembly_summary_genbank_historical.txt
1650 assembly_summary_genbank.txt
1651 assembly_summary_refseq_historical.txt
1652 assembly_summary_refseq.txt
1653 );
1654  
1655 0 my %name_for;
1656 my %node_for;
1657 0 my %fix_for;
1658  
1659 0 my $base_acc = 'https://ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS';
1660  
1661 0 for my $target (@targets_acc) {
1662 #### $target
1663  
1664 0 my $url = "$base_acc/$target";
1665 0 my $file = file($tax_dir, $target)->stringify;
1666 #### $file
1667  
1668 0 ### Downloading: $url
1669 0 my $ret_code = getstore($url, $file);
1670 0 ▶ croak "[BMC] Error: cannot download $url: error $ret_code; aborting!"
Branch: 1 branch
BranchTrueFalseTotal
unless $ret_code == 200 0 0 0
1671 unless $ret_code == 200;
1672  
1673 # parse file for accession numbers and related taxon_ids
1674 0 open my $fh, '<', $file;
1675  
1676 LINE:
1677 0 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 0 0 0
1678 0 chomp $line;
1679  
1680 # skip empty lines and comment lines
1681 0 ▶ next LINE if $line =~ $EMPTY_LINE
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ or $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/ 0 0 0
Condition0%0/3
$line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ or $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
l!l&&r!l&&!r
000
MC/DC0%0/2
$line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ or $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
$line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/ $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
Truth table0%0/3
A or B
A= $line =~ /$Bio::MUST::Core::Taxonomy::EMPTY_LINE/B= $line =~ /$Bio::MUST::Core::Taxonomy::COMMENT_LINE/
ABresult
1X1
011
000
1682 || $line =~ $COMMENT_LINE;
1683  
1684 0 my ($accession, $taxon_id, $species_taxon_id)
1685 = (split /\t/xms, $line)[0,5,6];
1686  
1687 # update merged taxon_id (mostly from historical assembly files)
1688 0 ▶ $taxon_id = $tax->merged_for($taxon_id)
Branch: 1 branch
BranchTrueFalseTotal
if $tax->is_merged($taxon_id) 0 0 0
1689 if $tax->is_merged($taxon_id);
1690 0 ▶ $species_taxon_id = $tax->merged_for($species_taxon_id)
Branch: 1 branch
BranchTrueFalseTotal
if $tax->is_merged($species_taxon_id) 0 0 0
1691 if $tax->is_merged($species_taxon_id);
1692  
1693 # skip deleted nodes (again mostly from historical assembly files)
1694 0 ▶ next LINE if $tax->is_deleted($taxon_id);
Branch: 1 branch
BranchTrueFalseTotal
if $tax->is_deleted($taxon_id) 0 0 0
1695  
1696 # skip GCF entries with corresponding GCA already available...
1697 # ... and transform remaining GCF entries into GCA entries
1698 # Note: versions are considered relevant; only prefix is ignored
1699  
1700 0 ▶ if ($accession =~ $GCAONLY) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accession =~ /$Bio::MUST::Core::Taxonomy::GCAONLY/) 0 0 0
1701 0 $accession =~ tr/F/A/;
1702 0 ▶ next LINE if defined $name_for{$accession};
Branch: 1 branch
BranchTrueFalseTotal
if defined $name_for{$accession} 0 0 0
1703 }
1704  
1705 # fetch taxonomy and org using taxon_id
1706 0 my @taxonomy = $tax->get_taxonomy($taxon_id);
1707 0 my $org = $taxonomy[-1];
1708  
1709 # use parent taxon_id if no taxon_id for strain
1710 0 ▶ if ($species_taxon_id == $taxon_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($species_taxon_id == $taxon_id) 0 0 0
1711 0 $species_taxon_id = $parent_taxid_for{$taxon_id};
1712 0 $fix_for{$taxon_id}{name_for} = $org;
1713 0 $fix_for{$taxon_id}{node_for} = $species_taxon_id;
1714 }
1715  
1716 0 $name_for{$accession} = $org;
1717 0 $node_for{$accession} = $species_taxon_id;
1718 }
1719  
1720 0 close $fh;
1721 }
1722  
1723 # write names.dmp
1724 0 my $names_gca_file = file($tax_dir, 'gca0-names.dmp');
1725 0 open my $names_out, '>', $names_gca_file;
1726  
1727 0 for my $accession ( keys %name_for ) {
1728 0 say {$names_out} join $FS,
1729 0 $accession, $name_for{$accession}, q{}, 'scientific name';
1730 }
1731 0 for my $taxon_id ( keys %fix_for ) {
1732 0 say {$names_out} join $FS,
1733 0 $taxon_id, $fix_for{$taxon_id}{name_for}, q{}, 'scientific name';
1734 0 $rank_for{$fix_for{$taxon_id}{name_for}} = $rank_for{$taxon_id};
1735 }
1736  
1737 0 close $names_out;
1738  
1739 # write nodes.dmp
1740 0 my $nodes_gca_file = file($tax_dir, 'gca0-nodes.dmp');
1741 0 open my $nodes_out, '>', $nodes_gca_file;
1742  
1743 0 for my $accession ( keys %node_for ) {
1744 0 ▶ say {$nodes_out} join $FS, $accession, $node_for{$accession},
Condition0%0/2
$rank_for{$name_for{$accession}} // "no rank"
l!l
00
MC/DC0%0/1
$rank_for{$name_for{$accession}} // "no rank"
$rank_for{$name_for{$accession}}
Truth table0%0/2
A
A= $rank_for{$name_for{$accession}}
Aresult
11
00
1745 0 $rank_for{$name_for{$accession}} // 'no rank';
1746 }
1747 0 for my $taxon_id ( keys %fix_for ) {
1748 0 say {$nodes_out} join $FS, $taxon_id, $fix_for{$taxon_id}{node_for},
1749 0 $rank_for{$taxon_id};
1750 }
1751  
1752 0 close $nodes_out;
1753  
1754 0 return;
1755 }
1756  
1757  
1758 # http://www.ncbi.nlm.nih.gov/news/11-21-2013-strain-id-changes/
1759 #
1760 # Planned change in bacterial strain-level information management
1761 #
1762 # Please be aware that there is an upcoming change (January 2014) in how NCBI
1763 # manages organism strain information. Due to significant increases in the
1764 # volume of strain-specific sequencing, we are changing our management of
1765 # strain information.
1766 #
1767 # Next generation sequencing has already changed the way microbial genomes are
1768 # being used. The scope of microbial sequencing projects has shifted from a
1769 # single isolate representing an organism to multi-isolate and multi-species
1770 # projects representing microbial communities. Consequently, in the first nine
1771 # months of 2013 the sequences of more than 6000 prokaryotic genomes were
1772 # released by INSDC (DDBJ/ENA/GenBank).
1773 #
1774 # NCBI is introducing several changes in prokaryotic genomes and related
1775 # resources such as Assembly, BioProject, BioSample, and Taxonomy that will
1776 # affect your submissions, data downloads, analysis tools, and parsers.
1777 #
1778 # Taxonomy
1779 #
1780 # Assigning strain-level TaxID will be discontinued in January 2014 because
1781 # curation of strain-level TaxIDs will not remain possible under such growth.
1782 # However, the thousands of existing strain-level TaxIDs will remain, and we
1783 # will continue to add informal strain-specific names for genomes from
1784 # specimens that have not yet been identified to the species level, e.g.
1785 # “Rhizobium sp. CCGE 510” and “Micromonas sp. RCC299”. The strain information
1786 # will continue to be collected and displayed.
1787 #
1788 # BioSample
1789 #
1790 # Submitters of genome sequences will be required to register sample meta-data
1791 # in the BioSample database for each organism that they are sequencing. The
1792 # BioSample submission will include the strain information and other metadata,
1793 # such as culture collection and isolation information, as appropriate. The
1794 # BioSample accession will be a link on the GenBank records, and the GenBank
1795 # records themselves will display the strain in the source information.
1796 #
1797 # BioProject
1798 #
1799 # Submitters of genome sequences are already required to register meta-data
1800 # about the research project in the BioProject database. We no longer require
1801 # a one-to-one relationship between a BioProject accession and a genome.
1802 # Instead, a research effort examining multiple strains of a species or
1803 # multiple species of drug-resistant bacteria, for example, could be
1804 # registered as a single BioProject.
1805 #
1806 # Assembly
1807 #
1808 # Each genome assembly is loaded to the Assembly database and assigned an
1809 # Assembly accession. The Assembly accession is specific for a particular
1810 # genome submission.
1811 #
1812 # What defines a genome?
1813 #
1814 # A BioProject ID or accession cannot be used to define a single genome, since
1815 # many may belong to a multi-isolate or multi-species project. Furthermore, a
1816 # TaxID can no longer reliably define an individual genome since unique TaxIDs
1817 # will not be assigned for individual strains and isolates. The collection of
1818 # DNA sequences of an individual sample (isolate) will be represented by a
1819 # BioSample accession and if raw sequence reads are assembled and submitted to
1820 # GenBank they will get a unique Assembly accession. The Assembly accession is
1821 # specific for a particular genome submission. For example, sequence data
1822 # generated from a single sample (with a BioSample accession) could be
1823 # assembled with two different algorithms and so have two sets of GenBank
1824 # accessions, each with its own Assembly accession.
1825 # BioSample accession and each assembled genome has its own Assembly
1826 # accession. This BioProject includes an isolate of Listeria monocytogenes
1827 # (TaxID 1639, strain R2-502) which was registered as BioSample SAMN02203126,
1828 # and its genome is represented in GenBank records CP006595-CP006596, which
1829 # are tracked as a group in the Assembly database under accession
1830 # GCA_000438585.
1831 #
1832 # FTP files
1833 #
1834 # Genome text reports on the FTP site have been modified to include the
1835 # BioSample and Assembly accessions. These two columns were added at the end
1836 # of the tables to minimize problems for existing parsers. Initially, not all
1837 # assemblies will have a BioSample accession because we are still in the
1838 # process of back-filling BioSamples for genomes.
1839 #
1840 # These changes will occur in January 2014. We will be releasing more
1841 # information as the date approaches.
1842  
1843 0 ▶sub _setup_gtdb_taxdir {
Subroutine _setup_gtdb_taxdir: not called CC=24 SCAR=64.0
1844 0 my $class = shift;
1845 0 my $tax_dir = shift;
1846  
1847 # setup local directory
1848 0 $tax_dir = dir( glob $tax_dir );
1849 0 $tax_dir->mkpath();
1850  
1851 0 ### Installing GTDB Taxonomy database to: $tax_dir->stringify
1852 0 ### Please be patient...
1853  
1854 # setup remote archive access
1855 0 my $base = 'https://data.ace.uq.edu.au/public/gtdb/data/releases/latest/';
1856  
1857 # get directory listing of latest GTDB release
1858 0 ▶ my $listing = get($base)
Branch: 1 branch
BranchTrueFalseTotal
my $listing = &get($base) or croak("[BMC] Error: cannot download ${base}: error $!; aborting!") 0 0 0
1859 or croak "[BMC] Error: cannot download $base: error $!; aborting!";
1860  
1861 0 ▶ croak "[BMC] Error: cannot determine path to GTDB files; aborting!"
Branch: 1 branch
BranchTrueFalseTotal
unless $listing 0 0 0
1862 unless $listing;
1863  
1864 # determine filenames from directory listing
1865 my @targets = (
1866 0 grep { m/metadata.*\.gz/xms } $listing =~ m/href="([^"]+?)"/xmsg,
1867 # Note: did try with Regexp::Common (delimiters) but less handy
1868 'FILE_DESCRIPTIONS', 'METHODS', 'RELEASE_NOTES', 'VERSION'
1869 );
1870 #### @targets
1871  
1872 0 for my $target (@targets) {
1873 0 my $url = "$base/$target";
1874  
1875 0 ### Downloading: $url
1876 0 my $zipfile = file($tax_dir, $target)->stringify;
1877 0 my $ret_code = getstore($url, $zipfile);
1878 0 ▶ croak "[BMC] Error: cannot download $url: error $ret_code; aborting!"
Branch: 1 branch
BranchTrueFalseTotal
unless $ret_code == 200 0 0 0
1879 unless $ret_code == 200;
1880  
1881 0 ▶ if ($target =~ m/metadata/xms) {
Branch: 1 branch
BranchTrueFalseTotal
if ($target =~ /metadata/msx) 0 0 0
1882 0 ### Unarchiving: $zipfile
1883 0 system("gunzip $zipfile");
1884 # file($zipfile)->remove;
1885 }
1886 }
1887  
1888 # change file names to avoid GTDB version in basenames
1889 0 my $new_arcfile = file($tax_dir, 'archaea_metadata.tsv');
1890 0 my $new_bacfile = file($tax_dir, 'bacteria_metadata.tsv');
1891 0 ▶ $new_arcfile->remove if -e $new_arcfile;
Branch: 1 branch
BranchTrueFalseTotal
if -e $new_arcfile 0 0 0
1892 0 ▶ $new_bacfile->remove if -e $new_bacfile;
Branch: 1 branch
BranchTrueFalseTotal
if -e $new_bacfile 0 0 0
1893  
1894 0 my ($arcbase) = fileparse($targets[0], qr{\.[^.]*}xms);
1895 0 my ($bacbase) = fileparse($targets[1], qr{\.[^.]*}xms);
1896 0 my $old_arcfile = file($tax_dir, $arcbase);
1897 0 my $old_bacfile = file($tax_dir, $bacbase);
1898  
1899 0 $old_arcfile->move_to($new_arcfile);
1900 0 $old_bacfile->move_to($new_bacfile);
1901  
1902 # return true on success (only check main files)
1903 0 ▶ if ( -r $new_arcfile && -r $new_bacfile ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $new_arcfile and -r $new_bacfile) { } 0 0 0
Condition0%0/3
-r $new_arcfile and -r $new_bacfile
!ll&&!rl&&r
000
MC/DC0%0/2
-r $new_arcfile and -r $new_bacfile
-r $new_arcfile -r $new_bacfile
Truth table0%0/3
A and B
A= -r $new_arcfileB= -r $new_bacfile
ABresult
0X0
100
111
1904 0 ### Successfully downloaded metadata files!
1905 }
1906  
1907 else {
1908 0 ### Failed installation!
1909 0 return 0;
1910 }
1911  
1912 # concatenate metadata TSV files
1913 0 my $prok_file = file($tax_dir, 'prok_metadata.tsv');
1914 0 ▶ $prok_file->remove if -e $prok_file;
Branch: 1 branch
BranchTrueFalseTotal
if -e $prok_file 0 0 0
1915 0 system("cat $new_arcfile $new_bacfile > $prok_file");
1916  
1917 # create hash from metadata file
1918 0 my $table_for = _read_gtdb_metadata($prok_file);
1919  
1920 # hash for rank code
1921 my %rank_for = map {
1922 0 substr($_, 0, 1) . '__' => $_
1923 } qw (domain phylum class order family genus species);
1924  
1925 # setup taxonomic tree
1926 0 my %tree = (
1927 1 => {
1928 rank => 'no rank',
1929 name => 'root',
1930 uniq_name => q{},
1931 children => {
1932 2 => {
1933 rank => 'no rank',
1934 name => 'cellular organisms',
1935 children => {},
1936 },
1937 },
1938 }
1939 );
1940  
1941 # fill up taxonomic tree
1942 0 my %seen;
1943  
1944 LINE:
1945 0 for my $gca (keys %{$table_for}) {
1946  
1947 # get GTDB taxonomy
1948 0 my $lineage = $table_for->{$gca}{'gtdb_taxonomy'};
1949 0 my @taxonomy = split q{;}, $lineage;
1950  
1951 0 my $tree_ref = $tree{1}{children}{2}{children};
1952  
1953 # count duplicate taxon in lineage
1954 0 ▶ my %count_for = count_by { substr( $_, 3, length()-1 ) } @taxonomy;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1955  
1956 0 ▶ while (my $gtdb_taxon = shift @taxonomy) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $gtdb_taxon = shift @taxonomy) 0 0 0
1957  
1958 # get taxon rank
1959 0 my ($rank_code, $taxon) = ($gtdb_taxon) =~ m/^([a-z]__)(.*)/xms;
1960 0 my $rank = $rank_for{$rank_code};
1961  
1962 # create taxid for taxon
1963 0 my $taxon_id = $rank_code . lc($taxon =~ tr/A-Za-z0-9//cdr);
1964  
1965 # create taxid entry (if not yet existing)
1966 0 ▶ unless ( $tree_ref->{$taxon_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tree_ref->{$taxon_id}) 0 0 0
1967 0 $tree_ref->{$taxon_id}{name} = $taxon;
1968 0 $tree_ref->{$taxon_id}{rank} = $rank;
1969 }
1970  
1971 # set a unique name (if duplicate taxon)
1972 0 ▶ my $uniq_name = $count_for{$taxon} > 1
Branch: 1 branch
BranchTrueFalseTotal
$count_for{$taxon} > 1 ? : 0 0 0
1973 ? $taxon . ' <' . lc $rank . '>' : q{};
1974 # ... and add it in hash
1975 0 ▶ $tree_ref->{$taxon_id}{uniq_name} = $uniq_name
Branch: 1 branch
BranchTrueFalseTotal
if $uniq_name 0 0 0
1976 if $uniq_name;
1977  
1978 # skip GCF entries with corresponding GCA already available...
1979 # ... and transform remaining GCF entries into GCA entries
1980 # Note: input order is actually irrelevant (no need to sort keys)
1981 # Note: versions are considered relevant; only prefix is ignored
1982 0 ▶ if ($rank eq 'species') {
Branch: 1 branch
BranchTrueFalseTotal
if ($rank eq "species") 0 0 0
1983 0 $gca =~ tr/F/A/;
1984 0 ▶ next LINE if $seen{$gca};
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$gca} 0 0 0
1985 0 push @{ $tree_ref->{$taxon_id}{gca} }, $gca;
1986 0 $seen{$gca} = 1;
1987 }
1988  
1989 # setup children entry if lineage not yet exhausted
1990 0 ▶ if (@taxonomy) {
Branch: 1 branch
BranchTrueFalseTotal
if (@taxonomy) 0 0 0
1991 0 ▶ $tree_ref->{$taxon_id}{children} //= {};
Condition0%0/2
$tree_ref->{$taxon_id}{"children"} //= {}
l!l
00
MC/DC0%0/1
$tree_ref->{$taxon_id}{"children"} //= {}
$tree_ref->{$taxon_id}{"children"}
Truth table0%0/2
A
A= $tree_ref->{$taxon_id}{"children"}
Aresult
11
00
1992 $tree_ref = $tree_ref->{$taxon_id}{children}
1993 0 }
1994 }
1995 }
1996  
1997 # taxid files
1998 0 my $name_file = file($tax_dir, 'names.dmp');
1999 0 my $node_file = file($tax_dir, 'nodes.dmp');
2000 0 open my $name_out, '>', $name_file;
2001 0 open my $node_out, '>', $node_file;
2002  
2003 # gca files
2004 0 my $gcanamefile = file($tax_dir, 'gca0-names.dmp');
2005 0 my $gcanodefile = file($tax_dir, 'gca0-nodes.dmp');
2006 0 open my $gcaname_out, '>', $gcanamefile;
2007 0 open my $gcanode_out, '>', $gcanodefile;
2008  
2009 # create empty additional dmp files
2010 0 file($tax_dir, 'delnodes.dmp')->spew;
2011 0 file($tax_dir, 'merged.dmp' )->spew;
2012  
2013 # write regular dmp files (first recursive call)
2014 _write_dmp_files( $name_out, $node_out, $gcaname_out, $gcanode_out,
2015 0 1, 1, $tree{1} );
2016  
2017 # TODO: make this part more similar with NCBI (error and cache handling)
2018  
2019 0 ▶ if ( -r $name_file && -r $node_file ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $name_file and -r $node_file) 0 0 0
Condition0%0/3
-r $name_file and -r $node_file
!ll&&!rl&&r
000
MC/DC0%0/2
-r $name_file and -r $node_file
-r $name_file -r $node_file
Truth table0%0/3
A and B
A= -r $name_fileB= -r $node_file
ABresult
0X0
100
111
2020 0 ### Successfully wrote taxid files!
2021 }
2022  
2023 0 ▶ if ( -r $gcanamefile && -r $gcanodefile ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $gcanamefile and -r $gcanodefile) 0 0 0
Condition0%0/3
-r $gcanamefile and -r $gcanodefile
!ll&&!rl&&r
000
MC/DC0%0/2
-r $gcanamefile and -r $gcanodefile
-r $gcanamefile -r $gcanodefile
Truth table0%0/3
A and B
A= -r $gcanamefileB= -r $gcanodefile
ABresult
0X0
100
111
2024 0 ### Successfully wrote GCA-based files!
2025 }
2026  
2027 0 close $name_out;
2028 0 close $node_out;
2029 0 close $gcaname_out;
2030 0 close $gcanode_out;
2031  
2032 0 return;
2033 }
2034  
2035 0 ▶sub _read_gtdb_metadata {
Subroutine _read_gtdb_metadata: not called CC=3 SCAR=24.8
2036 0 my $infile = shift;
2037  
2038 0 open my $in, '<', $infile;
2039  
2040 0 my %table_for;
2041 my @keys;
2042  
2043 LINE:
2044 0 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
2045 0 chomp $line;
2046  
2047 0 ▶ if ($line =~ m/^accession/xms) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^accession/msx) 0 0 0
2048 0 (undef, @keys) = split /\t/xms, $line;
2049 0 next LINE;
2050 }
2051  
2052 0 my ($gca, @values) = split /\t/xms, $line;
2053 0 $gca =~ s/GB_|RS_//xms;
2054 0 $table_for{$gca} = { mesh @keys, @values };
2055 }
2056  
2057 0 return \%table_for;
2058 }
2059  
2060 0 ▶sub _write_dmp_files { ## no critic (ProhibitManyArgs)
Subroutine _write_dmp_files: not called CC=7 SCAR=40.3
2061 0 my ($name_out, $node_out, $gcaname_out, $gcanode_out,
2062 $taxon_id, $parent, $tree_ref) = @_;
2063  
2064 0 my $name = $tree_ref->{name };
2065 0 my $rank = $tree_ref->{rank };
2066 0 ▶ my $uniq_name = $tree_ref->{uniq_name} // q{};
Condition0%0/2
$tree_ref->{"uniq_name"} // ""
l!l
00
MC/DC0%0/1
$tree_ref->{"uniq_name"} // ""
$tree_ref->{"uniq_name"}
Truth table0%0/2
A
A= $tree_ref->{"uniq_name"}
Aresult
11
00
2067 0 ▶ my $gcas = $tree_ref->{gca } // [];
Condition0%0/2
$tree_ref->{"gca"} // []
l!l
00
MC/DC0%0/1
$tree_ref->{"gca"} // []
$tree_ref->{"gca"}
Truth table0%0/2
A
A= $tree_ref->{"gca"}
Aresult
11
00
2068  
2069 # write gca files
2070 0 ▶ if ($gcas) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gcas) 0 0 0
2071 _append2dmp($gcaname_out, $gcanode_out,
2072 $_, $parent, $name, $rank, $uniq_name)
2073 0 for sort @{$gcas};
2074 }
2075  
2076 # write taxid files
2077 0 _append2dmp($name_out, $node_out,
2078 $taxon_id, $parent, $name, $rank, $uniq_name);
2079  
2080 0 my $children_for = $tree_ref->{children};
2081 0 ▶ return unless $children_for;
Branch: 1 branch
BranchTrueFalseTotal
unless $children_for 0 0 0
2082  
2083 0 $parent = $taxon_id;
2084  
2085 _write_dmp_files( $name_out, $node_out, $gcaname_out, $gcanode_out,
2086 $_, $parent, $children_for->{$_} )
2087 0 for sort keys %{$children_for};
2088  
2089 0 return;
2090 }
2091  
2092 0 ▶sub _append2dmp { ## no critic (ProhibitManyArgs)
Subroutine _append2dmp: not called CC=1 SCAR=6.9
2093 0 my ($name_out, $node_out,
2094 $taxon_id, $parent, $name, $rank, $uniq_name) = @_;
2095  
2096 # write names file
2097 0 say {$name_out} join "\t",
2098 $taxon_id , '|',
2099 $name , '|',
2100 $uniq_name, '|',
2101 'scientific name'
2102 ;
2103  
2104 # write nodes file
2105 0 say {$node_out} join "\t",
2106 $taxon_id, '|', $parent, '|', $rank,
2107 ( join "\t", '|', q{} ) x 10;
2108  
2109 0 return;
2110 }
2111  
2112 0 ▶sub no_warnings {
Subroutine no_warnings: not called CC=1 SCAR=6.9
Pod undocumented
2113 0 my $class = shift;
2114  
2115 0 ▶ return sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
2116 0 my $msg = shift;
2117 0 ▶ return if $msg =~ m/is\ taxonomically\ ambiguous/xms;
Branch: 1 branch
BranchTrueFalseTotal
if $msg =~ /is\ taxonomically\ ambiguous/msx 0 0 0
2118 0 ▶ return if $msg =~ m/cannot\ fetch\ tax/xms;
Branch: 1 branch
BranchTrueFalseTotal
if $msg =~ /cannot\ fetch\ tax/msx 0 0 0
2119 0 warn $msg; ## no critic (ErrorHandling::RequireCarping)
2120 0 };
2121 }
2122  
2123 18 ▶no Moose::Util::TypeConstraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
2124  
2125 18 __PACKAGE__->meta->make_immutable;
2126 18 1;
2127  
2128 __END__
« lib/Bio/MUST/Core/Taxonomy/Criterion.pm ↑ Summary lib/Bio/MUST/Core/SeqMask/Weights.pm »