Skip to content

Commit

Permalink
add name2taxids
Browse files Browse the repository at this point in the history
  • Loading branch information
banhbio committed Oct 29, 2022
1 parent 533bb34 commit 22cda38
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 15 deletions.
2 changes: 1 addition & 1 deletion src/Taxonomy.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export current_db, current_db!,
AbstractTaxon, Taxon, UnclassifiedTaxon,
Lineage, isreformatted,
print_tree,
taxid, name, rank, parent, get, children, lca, source,
taxid, name, rank, parent, get, name2taxids, children, lca, source,
reformat, namedtuple, print_lineage, isdescendant, isancestor,
All, Between, Cols,
From, Until,
Expand Down
20 changes: 7 additions & 13 deletions src/taxon.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,18 @@ struct Taxon <: AbstractTaxon
return new(idx, db)
end
end
Taxon(idx::Int) = Taxon(idx, current_db())

"""
Taxon(name::AbstractString, db::Taxonomy.DB)
Taxon(name::AbstractString)
name2taxids(name::AbstractString, db::Taxonomy.DB)
name2taxids(name::AbstractString)
Construct a `Taxon` from its `name`. `name` must match to the scientific name exactly.
Throws an error if there is no match or multiple candidates.
Return a `Vector` of taxid from its `name`. `name` must match to the scientific name exactly.
If multiple hits are found, return a multi-element `Vector`. If not, 1- or 0-element `Vector`.
Omitting `db` automatically calls `current_db()`, which is usually the database that was last created.
"""
function Taxon(name::String, db::DB)
taxid_canditates = findall(isequal(name), db.names)
length(taxid_canditates) == 0 && error("There is no candidate for $name")
length(taxid_canditates) == 1 && return Taxon(only(taxid_canditates), db)
length(taxid_canditates) > 1 && error("There are several candidates for $name. Candidates: $taxid_canditates")
end

Taxon(idx::Int) = Taxon(idx, current_db())
Taxon(name::String) = Taxon(name, current_db())
name2taxids(name::AbstractString, db::DB) = findall(isequal(name), db.names)
name2taxids(name::AbstractString) = name2taxids(name, current_db())

"""
taxid(taxon::Taxon)
Expand Down
2 changes: 1 addition & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ db = Taxonomy.DB("db/nodes.dmp", "db/names.dmp")
@test @inferred(sprint(io -> show(io, human))) == "9606 [species] Homo sapiens"

@test @inferred(Nothing, get(db, 9606, nothing)) == human
@test Taxon("Homo", db) == Taxon(9605, db)
@test @inferred(name2taxids("Homo", db)) == [9605]

@test @inferred(Nothing, AbstractTrees.parent(human)) == Taxon(9605,db)
@test @inferred(Set(children(human))) == Set([Taxon(63221,db), Taxon(741158, db)])
Expand Down

0 comments on commit 22cda38

Please sign in to comment.