Skip to main content

taxutils

Utilities for working with NCBI taxonomic data, accession-to-taxon mappings, taxonomy branches, corrected ranks, and pathogen target taxa.

Install

Conda Formula

conda install bioconda::taxutils

Pip Formula

pip install taxutils

taxutils requires its native Rust extension. Published wheels bundle the extension; there is no slower Python fallback for accession database or FASTA operations. An unsupported platform therefore fails at installation/import instead of silently changing performance or behavior.

from taxutils import backend_info

print(backend_info())
# {'selected': 'rust', 'rust_version': '1.1.1', 'api_version': 6}

Building from a repository checkout or source distribution requires Rust. The extension resolves taxutils 1.1.1 or newer compatible releases directly from crates.io; a sibling taxutils-rs checkout is not required.

Setup

taxutils stores downloaded taxonomy files (names.dmp, nodes.dmp), pathogen target metadata, and accession-to-taxon mappings in a global save directory. Set TAXUTILS_GLOBALS before importing the package if you want to control where these files live:

export TAXUTILS_GLOBALS=/path/to/taxutils/saves

If TAXUTILS_GLOBALS is not set, taxutils defaults to ./taxutils/ in the current working directory. It is the only environment variable taxutils reads, and it is only a default: save_folder= overrides it per call.

tu = taxutils(save_folder="/path/to/taxutils/saves")

Threads

Every parallel stage — gzip decoding, the accession database build and refresh, and the FASTA commands — takes its worker count from a single threads argument. threads=None (the default) uses all logical CPUs.

tu = taxutils(low_memory=False, threads=8)   # cap the database build at 8 workers

The FASTA commands take the same value as --threads:

taxutils filter -i in.fasta -o out.fasta --remove-taxids 9606 --threads 8

Each call builds its own thread pool, so the setting applies to that operation only and never to the host process. RAYON_NUM_THREADS is not consulted.

The first run downloads NCBI taxonomy files. Accession lookups also use the NCBI accession-to-taxon mapping, which is large. By default, taxutils uses low-memory mode and scans the compressed mapping directly. For faster repeated lookups, use low_memory=False to build or reuse a local SQLite database:

from taxutils import taxutils

tu = taxutils(low_memory=False)

Database construction is owned by taxutils-rs. Both NCBI dumps are already sorted by accession, so they are decompressed in parallel and merged into one ascending stream that fills the table in key order. The table is keyed on the accession itself (WITHOUT ROWID), so there is no second copy of every accession to store or sort, and the taxid index is covering for reverse lookups. The result is assembled beside the destination and installed atomically only once every row and index is complete.

Long backend calls are interruptible: Ctrl-C during a build or a lookup raises KeyboardInterrupt promptly, removes the partial database, and leaves any database already installed untouched.

Keeping the database current

Anything missing is downloaded and a missing or unusable database is built automatically, so a first run needs no flags. To pick up new NCBI data, pass refresh=True: it re-fetches the managed taxonomy files and applies only the accessions NCBI added, changed or withdrew, skipping the work entirely when the sources are unchanged.

tu = taxutils(low_memory=False, wgs=True, refresh=True)

This asks NCBI whether each source has changed, and if so applies only the difference. Both the incoming dumps and the stored table are ordered by accession, so a single lockstep pass classifies every row as an insert, an update, or a deletion; accessions withdrawn upstream are removed. When the sources are unchanged, or the server cannot be reached, nothing is downloaded and the database is left alone.

The compressed NCBI mapping is always retained, because low-memory lookups scan it directly. If an installation will only ever use the SQLite database, the .accession2taxid.gz files can simply be deleted to reclaim the space; they are downloaded again only if a later low-memory lookup needs them.

Core usage

Core functions are listed here. See the example notebook for a fuller walkthrough.

# Build object
tu = taxutils(accessions=None, low_memory=True, targets_json=None, wgs=False, save_folder=None, threads=None, refresh=False)  # Build the taxonomy utility object.

# Accession parsing and mapping
tu.parse_accession(header_strings, version=True)          # Extract one accession per string.
tu.load_a2t(accessions, low_memory=None, extend=False, wgs=None)  # Load accession-to-taxon mappings into tu.a2t.
tu.get_t2a(taxa, low_memory=None, wgs=None)                       # Return accessions assigned to taxa.

# Tree queries
tu.get_branch(taxon)                                      # Return the root-to-taxon branch.
tu.get_subtree(taxon)                                     # Return taxon plus all descendants.
tu.get_ancestor(taxon, anchor_rank)                       # Return nearest ancestor at a rank.
tu.is_leaf(taxon_or_taxa)                                 # Test whether taxa have no child nodes.
tu.is_child(taxon_a, taxon_b)                             # Test whether taxon_a is a direct child of taxon_b.
tu.is_descendent(taxon_a, taxon_b)                        # Test whether taxon_a is below taxon_b.
tu.get_lca(taxon_a, taxon_b)                              # Return the lowest common ancestor.
tu.get_distance(taxon_a, taxon_b)                         # Return tree edge distance through the LCA.
tu.sort_taxa(taxa)                                        # Sort taxa in taxonomic order.
tu.format_tree(taxa)                                      # Return an indented tree Series.
tu.topology(taxon, anchor_rank=None)                      # Return subtree topology metrics.
tu.topology(taxon, anchor_rank=None, stat="topology_scale")  # Return one topology statistic.

# Rank utilities
tu.get_rank_order()                                       # Return canonical rank codes.
tu.higher_than_rank(taxa, rank)                           # Test whether taxa are higher than a rank.

In taxutils, accessions=list/of/accessions can be passed to call load_a2t on construction of the taxutils object. A custom targets_json can similarly be passed in lieu of the default json explained below. A missing or unusable database is built from scratch automatically; refresh=True re-fetches the managed taxonomy files and updates an existing database in place, applying only the rows that changed upstream. By default, accession lookups use nucl_gb.accession2taxid.gz; pass wgs=True to also download/use nucl_wgs.accession2taxid.gz for WGS/TSA accessions. SQLite mode always uses nucl.accession2taxid.db; if it was built GB-only, a later wgs=True call upgrades the same DB with WGS mappings. load_a2t overwrites tu.a2t by default; pass extend=True to add missing mappings without discarding existing ones. Method-level low_memory=None and wgs=None use the modes set when tu was built. save_folder and threads are recorded on tu and reused by every later lookup.

parse_accession accepts strings, lists, arrays, and pandas Series. It returns the first accession found from each string using the same container type where possible; missing accessions are returned as "NA".

get_lca(a, b) returns the lowest common ancestor of two taxa. get_distance(a, b) returns the edge distance between two taxa through their lowest common ancestor. Depths are cached lazily as these methods are called.

get_ancestor(taxon, anchor_rank) returns the nearest ancestor at the requested corrected rank. If the input taxon already has that rank, it returns the input taxon; if no ancestor has that rank, it returns the input taxon as a fallback. It accepts a single taxon, list-like input, NumPy arrays, or pandas Series and returns the same container type where possible.

is_leaf(taxon) returns whether a taxon has no child nodes in the taxonomy tree. It accepts a single taxon, list-like input, NumPy arrays, or pandas Series. A single taxon returns a bool; a list-like input returns a list of booleans; a NumPy array returns a boolean array with the original shape; and a pandas Series returns a boolean Series with the original index.

is_child(taxon_a, taxon_b) returns whether taxon_a is a direct child of taxon_b. It uses the parent lookup directly, so each pairwise check is O(1).

is_descendent(taxon_a, taxon_b) returns whether taxon_a is a strict descendant of taxon_b; a taxon is not considered a descendant of itself. The first call builds a cached tree interval index in O(n), and subsequent pairwise checks are O(1).

is_child and is_descendent accept either two scalar taxa or two list-like inputs of the same length. Scalar inputs return a bool; list-like inputs return a list of booleans; NumPy arrays return boolean arrays with the original taxon_a shape; and pandas Series return boolean Series with the original taxon_a index.

topology(taxon, anchor_rank=None, stat=None) returns subtree topology metrics such as taxon count, leaf fraction, depth, branchiness, and topology_scale. Pass anchor_rank="F" to summarize the nearest family-level ancestor. With stat=None, a single taxon returns a Series and a list, array, or Series returns a DataFrame.

Pass stat to return one topology metric. A single taxon returns a scalar; a list, array, or Series returns a Series indexed by taxon.

Topology columns

tu.topology(...) returns these columns:

  • taxon: input taxon.
  • name: input taxon name.
  • rank_code: corrected rank code for the input taxon.
  • anchor_taxon: subtree root used for the topology summary.
  • anchor_name: anchor taxon name.
  • anchor_rank_code: corrected rank code for the anchor.
  • n_taxa: number of taxa in the anchor subtree.
  • n_leaves: number of terminal taxa in the anchor subtree.
  • max_depth: maximum number of edges below the anchor.
  • mean_depth: average number of edges below the anchor.
  • topology_scale: 95th percentile descendant depth, with minimum value 1.
  • max_children: largest number of direct children from any node in the subtree.
  • branching_taxa_fraction: fraction of subtree taxa with at least one child.
  • top_child_fraction: fraction of the anchor subtree contained in its largest immediate child branch.

tu.target_taxa contains the default pathogen-derived target taxa. Use it directly for target filtering or movement checks.

Rust acceleration

The native backend comes from the taxutils Rust crate. It accelerates load_a2t, get_t2a, and the extract, clean, grep, and filter FASTA commands while preserving the Python APIs and return values. Runtime errors are not retried through Python, so a failed native file operation cannot be run twice accidentally. Long native FASTA operations release the GIL and respond to KeyboardInterrupt between bounded batches; atomic-output commands discard their temporary output when cancelled.

Editable installs also compile an optimized Rust extension. After updating the source, rerun python -m pip install -e . to rebuild it; an older debug extension can make large accession scans substantially slower.

pandas/NumPy-returning taxonomy methods remain implemented in Python. This avoids converting already-efficient in-memory containers merely to cross the Python/Rust boundary; additional batch methods will only move behind the native backend after container-specific benchmarks show a benefit.

Run python benchmarks/backend_benchmark.py for native FASTA throughput or python benchmarks/database_build_benchmark.py for native SQLite construction throughput.

Rank correction

taxutils keeps the raw NCBI rank in rank and adds corrected rank columns. Canonical ranks (R, D, K, P, C, O, F, G, S) are used as anchors only when they move deeper than the corrected parent rank. Noncanonical ranks such as no rank, clade, and other unusual labels inherit position from the tree. If a child would be ranked at the same or a higher level than its parent, it is assigned a subrank such as S2, S3, or F2. The canonical name for the corrected rank is stored in new_rank.

Target taxa

In ZarLab, we are working on metagenomics in the clinical setting, with the goal of creating an "agnostic diagnostic". We often want to look at broad array of taxa (tu.target_taxa) that could cause harm to people. In June 2024, CZI did the work of compiling a list of pathogenic taxa. I did the easy work of turning this into a json and uploading it to my website, so that it is available and easily accessed for all time (in case that link ever breaks). taxutils will extend the taxa list to include subtrees of each of those pathogenic taxa. It will additionally include SARS-CoV2, since it was excluded from CZI's list. If you find any other obvious, missing pathogens, please send me a note, so I can update my json. You can also update the target_taxa member variable yourself, or store an entirely different set of targets, if you wanted.

Contact

Author: Will O'Brien
Affiliation: Computer Science Department, UCLA
Email: wob@cs.ucla.edu

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

taxutils-1.1.1.tar.gz (48.2 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

taxutils-1.1.1-cp310-abi3-win_amd64.whl (3.6 MB view details)

Uploaded CPython 3.10+Windows x86-64

taxutils-1.1.1-cp310-abi3-musllinux_1_2_x86_64.whl (4.6 MB view details)

Uploaded CPython 3.10+musllinux: musl 1.2+ x86-64

taxutils-1.1.1-cp310-abi3-musllinux_1_2_aarch64.whl (4.5 MB view details)

Uploaded CPython 3.10+musllinux: musl 1.2+ ARM64

taxutils-1.1.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.3 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ x86-64

taxutils-1.1.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (4.3 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ ARM64

taxutils-1.1.1-cp310-abi3-macosx_11_0_arm64.whl (3.7 MB view details)

Uploaded CPython 3.10+macOS 11.0+ ARM64

taxutils-1.1.1-cp310-abi3-macosx_10_12_x86_64.whl (3.9 MB view details)

Uploaded CPython 3.10+macOS 10.12+ x86-64

File details

Details for the file taxutils-1.1.1.tar.gz.

File metadata

  • Download URL: taxutils-1.1.1.tar.gz
  • Upload date:
  • Size: 48.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.4.1 CPython/3.10.20 Linux/6.17.0-1021-nvidia

File hashes

Hashes for taxutils-1.1.1.tar.gz
Algorithm Hash digest
SHA256 093f5f5d0387c9b5ca55ec09bc7ee1b2973c3d28bc6330bcd341be5d6b459a82
MD5 391a2e3ff3df14ef09c2de55ce951439
BLAKE2b-256 f22bc41499b1c53bdb2f4377c2aa07ca2247c7468110e07b5c23506ab1ea22d7

See more details on using hashes here.

File details

Details for the file taxutils-1.1.1-cp310-abi3-win_amd64.whl.

File metadata

  • Download URL: taxutils-1.1.1-cp310-abi3-win_amd64.whl
  • Upload date:
  • Size: 3.6 MB
  • Tags: CPython 3.10+, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for taxutils-1.1.1-cp310-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 c0001eae8c87ca77654240e1199ef7cb7ee7f3ed9fdfcab097925654022a8b86
MD5 2399d7456b607679ec7cb68237760b9a
BLAKE2b-256 be492db2483188ae48c523c7704af408c063a518e118e31ef2e0185436197a51

See more details on using hashes here.

Provenance

The following attestation bundles were made for taxutils-1.1.1-cp310-abi3-win_amd64.whl:

Publisher: workflow.yml on SwabSeq/taxutils

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file taxutils-1.1.1-cp310-abi3-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for taxutils-1.1.1-cp310-abi3-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 5ca36ffea20b7a084ac59cd81a269b00837c4cb313075185cbe8c4469698a6d2
MD5 7e3261658fbf4da69581e5fc8e4ed6be
BLAKE2b-256 c5940e129a803115ea6a828c9be99a435c62dcd6ab58e108fee33840b81bae90

See more details on using hashes here.

Provenance

The following attestation bundles were made for taxutils-1.1.1-cp310-abi3-musllinux_1_2_x86_64.whl:

Publisher: workflow.yml on SwabSeq/taxutils

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file taxutils-1.1.1-cp310-abi3-musllinux_1_2_aarch64.whl.

File metadata

File hashes

Hashes for taxutils-1.1.1-cp310-abi3-musllinux_1_2_aarch64.whl
Algorithm Hash digest
SHA256 4982fe2da278f2b1abda4bbabc1d02ead899ebaa6a531514220ced0168db5bd7
MD5 4538bd9682f87923f498ed3fc4630029
BLAKE2b-256 57d878cfeafce81b74069af9aebe8a72ce25037ccc0ad0982d7dc0f39c870a57

See more details on using hashes here.

Provenance

The following attestation bundles were made for taxutils-1.1.1-cp310-abi3-musllinux_1_2_aarch64.whl:

Publisher: workflow.yml on SwabSeq/taxutils

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file taxutils-1.1.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for taxutils-1.1.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 06b4fe8100fd924e527522adc6297ff7a47951119c757ae0e4d08a6553288af2
MD5 452ab7c96f9853e5148bd955d174352f
BLAKE2b-256 109f2719da085cb1b054398989aaf022be58ed10413fb63c1def0310e0ff829e

See more details on using hashes here.

Provenance

The following attestation bundles were made for taxutils-1.1.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: workflow.yml on SwabSeq/taxutils

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file taxutils-1.1.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for taxutils-1.1.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 d5a843bce00bc0425d6fe066435a098847958f692f3d793de15712c516d5c870
MD5 1858e90b71e6d94f864236087c4b1a85
BLAKE2b-256 52c9249b21ed8cc642151f15d8d7e216f93552e021b8a5d44131858b089c74db

See more details on using hashes here.

Provenance

The following attestation bundles were made for taxutils-1.1.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: workflow.yml on SwabSeq/taxutils

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file taxutils-1.1.1-cp310-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for taxutils-1.1.1-cp310-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 6a29b3cdcf9b6e2acda9e72fc1640e704a88b24a2a5b543dd05c150b9cfade2f
MD5 7f94419ea832122164c8b83832df26fc
BLAKE2b-256 4acfb676523d37d130c616a25544bec8739ef4640a37c7adedd008c0cbe7d572

See more details on using hashes here.

Provenance

The following attestation bundles were made for taxutils-1.1.1-cp310-abi3-macosx_11_0_arm64.whl:

Publisher: workflow.yml on SwabSeq/taxutils

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file taxutils-1.1.1-cp310-abi3-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for taxutils-1.1.1-cp310-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 e128db21665877ec0eb1b09ad2c52cae8f0bddea3f87d036850c52b28fe2eac0
MD5 0077e067b3e961dd3e46bece6f0aff44
BLAKE2b-256 b4b1bf3fa108498800a555c574bcb23a6ff767e9730133319ca3cb3d7bc8e1aa

See more details on using hashes here.

Provenance

The following attestation bundles were made for taxutils-1.1.1-cp310-abi3-macosx_10_12_x86_64.whl:

Publisher: workflow.yml on SwabSeq/taxutils

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

1.1.1 This release

8 files

1.0.3

2 files

1.0.2

2 files

1.0.1

2 files

1.0.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page