Skip to content

Latest commit

 

History

History
230 lines (170 loc) · 18.5 KB

api_reference.md

File metadata and controls

230 lines (170 loc) · 18.5 KB

Public API Reference

This guide documents the names exported by taxdumpy.__all__. Install the package, then build caches from an NCBI taxdump directory before opening a database:

taxdumpy cache -d /path/to/taxdump

The command creates the caches used by the Python readers. The API opens existing caches and does not build them.

from taxdumpy import Taxon, get_rank_taxid, open_database

with open_database("/path/to/taxdump") as db:
    human = Taxon(9606, db)
    print(human.name)  # Homo sapiens
    print(get_rank_taxid(human, "genus"))  # 9605

Database readers

TaxonomyDatabase

TaxonomyDatabase is the abstract interface shared by the readers. It is not instantiated directly. Both concrete readers support with statements and expose the following common API:

Member Result and behavior
get_node(taxid) Returns a Node record containing taxid, parent, rank, name, equal, acronym, and division. Merged IDs resolve to the current node.
get_names(taxid) Returns a mutable dictionary from NCBI name class to sorted, distinct tuples of names. Includes "scientific name"; absent classes are omitted.
search(query, limit=10) Returns up to limit dictionaries with name, taxid, and similarity score (0–100), ordered by score. Each taxid is a separate candidate, including homonyms. A blank query returns [].
fuzzy_search(query, limit=10) Prints the matching names with taxid and rank. Prints a no-results message for an empty result.
all_names Returns a new list of scientific names. Homonyms appear once per taxid.
name2taxids Read-only mapping from scientific names to sorted tuples of all matching taxids.
delnodes Deleted taxids as a frozenset[int].
max_taxid_strlen, max_rank_strlen Maximum taxid and rank string widths, used to align formatted output.
children_index Lazily materialized, read-only mapping from parent taxid to sorted child-taxid tuples. Access scans the full database.
children_for(parents) Returns current child taxids for the supplied parent IDs, preserving parent order and sorting each sibling group.
iter_parent_pairs() Yields (child_taxid, parent_taxid) pairs for current nodes. This abstract method is part of the contract for custom backends.
close() Releases materialized indexes and caches. TaxSQLite also closes its SQLite connection.
len(db) Number of current taxonomy nodes.

get_node and get_names accept positive integer taxids or numeric strings. Invalid inputs raise ValidationError. Unknown or deleted taxids raise TaxidError. Fuzzy-search inputs must be a string and limit must be a positive integer.

TaxDb and TaxSQLite

TaxDb(taxdump_dir: Path | str, fast: bool = False, verbose: bool = False)
TaxSQLite(taxdump_dir: Path | str, verbose: bool = False)

TaxDb loads the pickle cache into memory. Set fast=True to read a filtered cache created for selected taxids. TaxSQLite reads the SQLite cache and is the default backend for open_database. taxdump_dir is the directory containing the relevant cache. Both accept verbose to enable initialization messages.

open_database

open_database(taxdump_dir: Path | str, backend: str = "sqlite", **kwargs) -> TaxonomyDatabase

Opens an existing cache and returns a TaxSQLite or TaxDb. Backend names are case-insensitive: "sqlite" and "sql" select SQLite; "dict", "memory", and "pickle" select TaxDb. Backend-specific keyword arguments are forwarded to the selected reader. An unsupported backend raises ValidationError; missing or stale caches raise TaxdumpFileError.

with open_database("/path/to/taxdump", backend="dict") as db:
    print(db.search("Homo sapiens", limit=5))

Taxon

Taxon(taxid: int | str, taxdb: TaxonomyDatabase)

Represents one taxid and its lineage. Create it with an open reader. Its names property loads lazily from that reader, so first access must happen before closing the reader. A merged input ID is preserved in .taxid; .node and .update_taxid refer to its current, resolved node.

Property Description
taxid Validated input ID, as an integer.
update_taxid Current ID after resolving a merged ID.
node Current Node record.
lineage Tuple of Node records ordered from this taxon toward root.
name, rank, parent, division, acronym Corresponding fields from the current node. acronym may be None.
names Lazy, read-only mapping of all name classes to tuples.
synonyms, common_names, genbank_common_names, equivalent_names, acronyms Tuples for the respective name class, empty when absent.
is_legacy Whether the input taxid was merged into another taxid.
taxid_lineage, rank_lineage, name_lineage Tuples aligned with lineage, each ordered from this taxon to root.
rankcode_lineage Comparable RC codes aligned with the lineage.
rc Rank code for this taxon's own node.
mpa_repr MetaPhlAn-style lineage string, containing available MPA-coded ranks from root to taxon.
has_species_level Whether the lineage contains a species rank.
species_taxid Species ancestor taxid, or None if the lineage has no species rank.

Construction raises ValidationError for malformed IDs and TaxidError for unknown or deleted IDs. Lineage corruption, including cycles or a lineage ending outside root taxid 1, raises TaxDbError.

Rank codes: RC

RC(code: str | int) constructs an integer subclass for comparing rank positions. String codes use a principal rank letter (R, D, K, P, C, O, F, G, or S) with an optional numeric depth from 0 to 255. A zero-depth code is displayed without a suffix. The integer value encodes the same position. Lower values represent higher ranks, so RC("R") < RC("S") and RC("F") < RC("F1"). str(code) returns its display code. Invalid codes and booleans raise ValueError.

Intermediate and unranked nodes can receive a depth suffix based on their position below the nearest principal rank. realm has a canonical rank name but no dedicated principal RC letter.

Rank and lineage functions

Canonical levels, from lowest to highest, are species, genus, family, order, class, phylum, kingdom, superkingdom, and realm. domain aliases superkingdom. Canonical rank lookup helpers also handle the corresponding subrank when their include_subrank(s) option is enabled. These helpers do not infer a rank solely from an unranked node's place in the tree.

Exact lookup and rank inventories

upper_rank_id(tax: Taxon, rank: RankName) -> int
get_rank_taxid(taxon: Taxon, rank: str, include_subrank: bool = True) -> int | None
get_canonical_ranks(taxon: Taxon, include_subranks: bool = True) -> dict[str, int]
get_all_ranks(taxon: Taxon) -> dict[str, int]
  • get_rank_taxid returns the ID at the exact rank, or None if absent. With its default include_subrank=True, it also accepts the matching sub... rank when the exact rank is missing. domain and superkingdom resolve to the same level.
  • get_canonical_ranks returns the canonical-rank-to-taxid mapping for ranks present. By default, a subrank may supply a canonical rank's value. Because domain is an alias, both alias keys can map to the same taxid. Set include_subranks=False to require canonical ranks themselves.
  • get_all_ranks includes canonical and noncanonical lineage ranks, including values such as "clade" and "no rank". If a rank occurs more than once, the nearest occurrence to the queried taxon is kept.
  • upper_rank_id is strict. The source rank and requested rank must be canonical, and the requested rank must be strictly higher than the source. It returns the requested rank's taxid, accepting its subrank when needed. It raises TaxRankError for invalid, equal, lower, or missing ranks.
from taxdumpy import Taxon, get_all_ranks, get_canonical_ranks, get_rank_taxid, open_database, upper_rank_id

with open_database("/path/to/taxdump") as db:
    human = Taxon(9606, db)

    assert upper_rank_id(human, "genus") == 9605
    assert get_rank_taxid(human, "family") == 9604

    canonical = get_canonical_ranks(human)
    assert canonical["species"] == 9606
    assert canonical["domain"] == canonical["superkingdom"] == 2759

    all_ranks = get_all_ranks(human)
    assert all_ranks["species"] == 9606
    assert all_ranks["subfamily"] == 207598

Fallback, preference, and distance

get_closest_rank(
    taxon: Taxon, target_rank: str, include_subranks: bool = True
) -> tuple[int, str] | tuple[None, None]
get_rank_or_closest(taxon: Taxon, rank: str, max_distance: int | None = None) -> int | None
find_rank_in_lineage(taxon: Taxon, rank_list: list[str]) -> tuple[int, str] | tuple[None, None]
get_rank_distance(rank1: str, rank2: str) -> int | None
  • get_closest_rank searches from the requested level upward through canonical levels. It returns (taxid, actual_rank_name) or (None, None). The actual name matters when fallback selects a higher rank or a subrank. Set include_subranks=False to skip subranks. An unrecognized target returns (None, None).
  • get_rank_or_closest searches similarly but returns only the taxid. max_distance bounds the number of canonical levels searched above the requested rank, with zero allowing only that level. None means no bound. An unrecognized rank or no available ancestor returns None. A supplied distance must be a non-negative integer and not a boolean, or ValidationError is raised.
  • find_rank_in_lineage checks exact rank names in the caller's preference order and returns the first (taxid, rank_name) match. It returns (None, None) when none match. It does not canonicalize aliases.
  • get_rank_distance returns the absolute distance between two canonical rank levels. Aliases share a level, so distance between domain and superkingdom is zero. If either name is noncanonical or unknown, it returns None.
from taxdumpy import Taxon, find_rank_in_lineage, get_closest_rank, get_rank_distance, get_rank_or_closest, open_database

with open_database("/path/to/taxdump") as db:
    human = Taxon(9606, db)
    taxon_without_class = Taxon(6072, db)

    assert get_closest_rank(taxon_without_class, "class") == (33208, "kingdom")
    assert get_rank_or_closest(taxon_without_class, "class", max_distance=1) is None
    assert get_rank_or_closest(taxon_without_class, "class", max_distance=2) == 33208

    assert find_rank_in_lineage(human, ["genus", "family"]) == (9605, "genus")
    assert get_rank_distance("species", "family") == 2

Grouping taxids

group_taxids_by_rank(
    taxids: list[int], rank: str, taxdb: TaxonomyDatabase
) -> dict[int, list[int]]

group_taxids_by_rank groups each valid input ID under its exact canonical rank, falling back to the nearest higher canonical ancestor when that rank is absent. Subranks are not used as groups. rank must be canonical or "root", otherwise TaxRankError is raised. Use "root" to group all valid inputs under root taxid 1. Invalid, unknown, and deleted IDs are skipped; database and lineage corruption errors propagate. Group lists preserve input order and repeated IDs.

from taxdumpy import group_taxids_by_rank, open_database

with open_database("/path/to/taxdump") as db:
    by_family = group_taxids_by_rank([9606, 9605], "family", db)
    assert by_family[9604] == [9606, 9605]  # Hominidae

Descendant traversal

build_children_index(taxdb: TaxonomyDatabase) -> Mapping[int, tuple[int, ...]]
descendants(taxdb: TaxonomyDatabase, taxid: int | str, max_depth: int | None = None) -> list[int]
descendant_nodes(taxdb: TaxonomyDatabase, taxid: int | str, max_depth: int | None = None) -> list[Node]
  • build_children_index explicitly materializes and caches a read-only mapping from parent IDs to sorted child-ID tuples. It scans the full database. The cache is released by taxdb.close().
  • descendants returns all descendants of the resolved taxid, excluding the starting node, in breadth-first order with siblings sorted by taxid. max_depth=1 returns direct children; None returns the full subtree. Merged starting IDs resolve to their current node. Deleted and superseded IDs are excluded. SQLite uses indexed child queries, while the dictionary backend reuses a parent/children index.
  • descendant_nodes returns the same descendants as Node records. It performs a node lookup for each result, so use descendants when IDs alone are sufficient.

max_depth must be None or an integer of at least 1; booleans and other values raise ValidationError. Unknown or deleted starting IDs raise TaxidError. A repeated node during traversal raises TaxDbError for a malformed taxonomy tree.

from taxdumpy import build_children_index, descendant_nodes, descendants, open_database

with open_database("/path/to/taxdump") as db:
    children_by_parent = build_children_index(db)
    child_ids = descendants(db, 561, max_depth=1)  # Direct children of Escherichia
    child_nodes = descendant_nodes(db, 561, max_depth=1)

    assert tuple(child_ids) == children_by_parent.get(561, ())
    assert 562 in child_ids  # Escherichia coli
    assert [node.taxid for node in child_nodes] == child_ids

Exceptions

All exported exceptions inherit from TaxdumpyError, so callers can catch that base class for package-level failures.

Exception Use and additional attributes
TaxdumpyError Base exception for package errors.
TaxDbError(message, details=None) General database or lineage failure. Stores message and optional details.
TaxidError(taxid, message=None, suggestion=None) Invalid, unknown, or deleted taxid. Stores taxid and optional suggestion.
TaxRankError(rank, message=None, valid_ranks=None) Rank lookup or validation failure. Stores rank and valid_ranks.
TaxdumpFileError(filename, issue, solution=None) Source or cache file problem. Stores filename, issue, and optional solution.
DatabaseCorruptionError (database_type, corruption_details) Detected cache corruption. Stores database_type and corruption_details.
ValidationError(parameter, value, expected) Invalid argument. Stores parameter, value, and expected.

Catch specific subclasses when handling expected lookup or input errors. Use TaxdumpyError when a caller should handle any library-defined exception uniformly.

Related guides