Python API¶
A taxonomy is a Taxonomy whatever its kind (NCBI, GTDB, SILVA, Greengenes2, Open Tree, your own) and wherever it lives: in a SQLite file (a temporary one for load), or on a server. The same code runs on both and gets the same answers.
import omnitax
tax = omnitax.load("gtdb", "232") # parse into a temporary file
tax = omnitax.open("taxonomies.sqlite", "ncbi") # a file
tax = omnitax.connect(url="https://...", taxonomy="ncbi") # a server
tax.save("taxonomies.sqlite") # temporary -> a file of your own
Loading taxonomies¶
ncbi = omnitax.load("ncbi") # NCBI new_taxdump, current; its version is its date: ncbi.version == "2026-11-26"
old = omnitax.load("ncbi", "2024-03-01") # from NCBI's monthly archive (the first of each month, from 2018-12-01)
gtdb = omnitax.load("gtdb", "232") # also 226, 220, 214.1, 207, 202, 95, 89, 86.2, 83, 80
silva = omnitax.load("silva", "ssu_138.2") # or lsu_138.2
gg = omnitax.load("greengenes", "2024.09") # or 2022.10
ott = omnitax.load("ott", "3.7.3") # or 3.6
mine = omnitax.load("custom", files=["tree.tsv"], columns=["id", "parent", "rank", "name"])
omnitax.load("gtdb", "232", files=["bac120_taxonomy_r232.tsv.gz", "ar53_taxonomy_r232.tsv.gz"]) # local files
omnitax.load("ncbi", cache_dir="~/.cache/omnitax") # keep (and reuse) the downloads
omnitax.load("gtdb", "232", urls=["https://..."]) # your own URLs (multitax's `urls`); version is then only a label
Downloads stream through httpx and are discarded after parsing unless cache_dir is given. files take plain, .gz and tar archives, or a directory.
load returns a read-only Taxonomy that lives in a temporary SQLite file: the same layout omnitax build makes, so a loaded taxonomy and an opened one behave alike. The file is in a private directory under the system's temporary directory, or under $OMNITAX_TMPDIR, and goes when you close() the taxonomy (or leave a with block), when it is garbage collected, and when the program ends. Mind where it is: on many Linux systems /tmp is a RAM disk, and the temporary file of NCBI is about 1.2 GB. Point OMNITAX_TMPDIR at a disk if that is not what you want.
Load or build a file? load parses on every start; a file opens in milliseconds. Measured on the full releases:
temporary file (load) |
size | |
|---|---|---|
| GTDB 232 (247 k nodes, 0.9 M genomes) | 7.5 s | 231 MB |
| NCBI (3.0 M nodes, 4.2 M names) | 80 s | 1.18 GB |
For anything you open often, omnitax.load(kind, version, path="taxonomies.sqlite") (or omnitax build) writes the file where you say, with the fuzzy-search index unless you pass fuzzy=False, and omnitax.open opens it. tax.save(path) of a loaded taxonomy copies the temporary file in seconds (NCBI: 6 s, against about 65 s for a rebuild).
Taxa¶
t = ncbi["562"] # KeyError if unknown; ncbi.get("562") gives None; ints work too
t.name, t.rank, t.parent, t.children, t.attrs # attrs: specified_species, genetic_code, division, ...
t.lineage() # root ... t
t.lineage(ranks=omnitax.GTDB_RANKS) # one slot per rank, None where missing
t.lineage(root="2") # from that ancestor down (empty if it is not an ancestor)
t.at("genus") # this node or its ancestor of that rank, or None
t.closest(ranks=["species", "genus"], formal=True) # nearest one; formal skips "Escherichia sp. X"
t.leaves(), t.descendants()
t.names # [(name, class)]: its own name, then synonyms, common names, ...
ncbi.many(["562", "12", "nope"]) # one batch; merged ids give the current node, unknown gives None
ncbi.lookup(["Homo sapiens", "Morus"]) # {name: [Taxon, ...]}: the nodes each name names exactly (Morus: several)
ncbi.of_rank("genus") # every node of a rank, streamed
ncbi.meta["genetic_codes"][str(t.attrs["genetic_code"])] # tables about the taxonomy (NCBI: divisions, genetic codes)
Merged and deleted ids are aliases: ncbi["12"].id == "74109" (12 was merged into another node).
omnitax.GTDB_RANKS is GTDB's seven ranks (domain ... species), which also define the d__...;s__ format of lineage_string(). It is not a universal ladder: it has no kingdom (eukaryotes have one, and so do NCBI's prokaryotes since 2024). Every function that needs ranks takes ranks=, so pass your own ladder. The only places that fall back to GTDB_RANKS are cap=True and lineage_string.
Search¶
ncbi.search("escherichia coli", rank="species", match="fuzzy", limit=5)
ncbi.search("e. coli", within="2") # only below a node (Bacteria): an id or a Taxon
ncbi.search("sapiens", classes=["name", "common name"], details=True) # [Match(taxon, name, name_class)]
search is autocomplete. Each match finds what the one before finds, then more, each node once, best first:
match |
finds |
|---|---|
"exact" |
names equal to the text, of any class |
"prefix" (default) |
then names that start with it, then names with a word that starts with it (sapiens finds Homo sapiens), then abbreviated binomials (e. coli) |
"substring" |
then names that contain it (needs a word of three letters or more and the trigram index; otherwise it behaves as prefix) |
"fuzzy" |
then names that resemble it (typos) |
Case, diacritics and whitespace do not matter, _ - and brackets are blanks, quotes are dropped. Empty text finds nothing, text over 200 characters is an error, and a trailing space ends the last word (homo finds what follows Homo, not the genus itself). Without classes, an exact match looks in all name classes and the others in all but authority (NCBI's 1.2 million "Name Author, 1870" names are noise for autocomplete). rank= and classes= restrict the search; an unknown rank or class is a ValueError (ncbi.ranks and ncbi.name_classes list them). Substring and fuzzy search need the trigram index (fuzzy=True, the default of save and build). Search always runs within one taxonomy. The ordering rules are in the design.
LCA and consensus¶
ncbi.lca(["562", "564"]) # strict LCA
ncbi.consensus({"562": 60, "564": 40}, threshold=0.5) # deepest node holding > 50% of the weight (default 0.9)
ncbi.consensus(ids, threshold=0.7, exclude=ncbi.uninformative) # unclassified/environmental ids do not vote
ncbi.consensus(ids, top=0.95) # multitax's top_perc, then the LCA
ncbi.consensus(ids, ranks=omnitax.GTDB_RANKS, formal=True) # lifted to a standard rank, never an informal species
consensus is plain voting by default: every vote counts for or against every node. threshold (default 0.9, above 0 and at most 1) is the share of the weight a node must strictly exceed; top (above 0, at most 1) is the alternative rule, and giving both is a ValueError. Ties go to the deeper node, then the heavier, then the smaller id (top=: the heavier vote first, then the deeper, then the smaller id). ranks= lifts the answer to the nearest ancestor of one of those ranks and gives None when there is none, which is the signal to try a larger clade. Weights must be finite and not negative; a weight of 0 is no vote, and no weight at all gives None (the same for lca). A threshold, top or min_informative out of range is a ValueError.
min_informative=f (0 to 1) switches on abstention (see Translation): votes above a node say nothing against it. It is off by default here, because it was measured only for GTDB → NCBI, where translate turns it on. top= has no abstention, so top= together with a min_informative other than False is a ValueError. With abstention and ranks=, every vote is lifted to its nearest ancestor of those ranks; a vote with none says nothing.
consensus(..., details=True) and translate(..., details=True) return a Placement: taxon (or None), support (the weight at or below it), total (the weight that counted), share (support / total), votes (every vote as (taxon, weight), heaviest first), abstained (the weight of the votes above the answer, which abstained) and unplaced (the weight of the votes that had no node of ranks). So total + abstained + unplaced is the weight of all votes cast. Unknown ids, nodes under exclude and weights of 0 are not votes.
Translation¶
translate goes through keys that both taxonomies share (links). Today these are genome accessions, so it converts between NCBI and GTDB and between GTDB releases. SILVA, Greengenes2 and Open Tree have no links, so they cannot be translated. The method, the defaults and the benchmark are on the translation page; this is the call:
gtdb = omnitax.open("taxonomies.sqlite", "gtdb:232") # built with: omnitax build -o taxonomies.sqlite gtdb:232 ncbi+gtdb:232
gtdb.translate("g__Escherichia", ncbi) # an NCBI node: for GTDB -> NCBI the bare call is the measured configuration
gtdb.translate("g__Escherichia", ncbi, ranks=(), exclude=(), min_informative=False) # the same, with each default turned off
ncbi.translate("620", gtdb, threshold=0.5) # options are those of consensus
gtdb.translate("g__Pseudomonas", ncbi, weight="genome", cap=True, top=0.95) # multitax's behaviour
p = gtdb.translate("g__Escherichia", ncbi, details=True)
[(t.name, round(w, 2)) for t, w in p.votes[:3]] # the distribution over NCBI: multitax's translate(counts=True)
gtdb.defaults_for(ncbi) # Defaults(threshold=0.9, min_informative=0.2, ranks=GTDB_RANKS, exclude_uninformative=True)
weight="leaf"(default) or"genome": whether every source leaf votes once or every genome does.cap=False(default),True, or a ladder of ranks (("domain", "phylum", "class", "family")): never answer finer than the source node.threshold,top,exclude,ranks,formal,min_informative,detailsas inconsensus. What you leave out is the default of the conversion (omnitax.consensus.DEFAULTS,Taxonomy.defaults_for(other)): for GTDB → NCBI, the one measured pair, threshold 0.9,min_informative=0.2,ranks=GTDB_RANKSandexclude=other.uninformative; for every other pair (omnitax.consensus.FALLBACK) threshold 0.9, plain voting, no ranks, nothing excluded. To turn a default off givemin_informative=False,ranks=()orexclude=(). The measured configuration has no kingdom, so it cannot answer at kingdom (see Translation).gca_gcf=True,via=,sources=,other_sources=choose the keys (below).
Links: genomes, sequences, other taxonomies' ids¶
A link attaches a key to a node of a taxonomy; translate joins two taxonomies through the keys they share. Every link has a kind, which says what its key is and how it is matched (one rule per kind, omnitax.links.match_link):
| kind | key | matching |
|---|---|---|
genome |
an assembly accession, GCF_000005845.2 (any case, RS_/GB_ dropped) |
the same accession; else the same version (gca_gcf: of the other database); else the one stored version of the number. Versions are different genomes, and so are GCA_ and GCF_ unless gca_gcf=True |
seq |
an INSDC sequence accession, with or without a region: AB000278, A16379.1.1485 |
the same key; else the same accession whatever the region |
a taxonomy kind (ncbi, gbif, ...) |
the id in that taxonomy, 562 |
the same key |
One match is a match; several are ambiguous (several versions or regions, sources that disagree). link() says None for those, links() answers the candidates, and translate lets such a key not vote. Today the loaders make genome links only (NCBI's assembly summaries, GTDB's files and metadata, a taxdump's taxid.map, which can also be read as seq links). seq and taxonomy-id links work when you add them yourself or through with_links; no loader fills them from SILVA, Greengenes2 or Open Tree yet.
ncbi.link("GCF_000005845.2") # Linked(key, taxon, name, source, kind, attrs), or None
ncbi.links(["GCF_000005845.2", "GCA_000000001"]) # {key as given: Linked | [candidates]}, one batch; unknown keys are left out
ncbi.link("GCF_000005845.2", gca_gcf=True) # GCA_ and GCF_ of one number are one genome
ncbi.link("12", "ncbi") # a taxonomy's own ids are links too (no rows stored): the node 12 was merged into
ncbi.link_kinds # ("genome", "ncbi"): the kinds of its link sources, then its own
Accessions are accepted raw everywhere (GCF_000005845.2, RS_GCF_000005845.2, any case). Every taxonomy carries an implicit link <its kind>:<id> for each node, resolved through the aliases. A list of links given to with_links is (key, node[, name[, source[, kind[, attrs]]]]); a source has one kind, and a key listed twice by one source is a ValueError.
Link sources¶
The links of a taxonomy can come from several sources, each with a label (ncbi-assemblies, gtdb:232, taxonomy for a loader's own links). They are all kept and may disagree:
ncbi = omnitax.open("taxonomies.sqlite", "ncbi") # built with ncbi+assemblies+gtdb:232
ncbi.link_sources # {"ncbi-assemblies": LinkSource(kind, links, provenance), "gtdb:232": ...}
ncbi.link("GCF_000005845.2") # sources agree: the Linked. They disagree: None
ncbi.link("GCF_000005845.2", sources="gtdb:232") # only that source
ncbi.link("GCF_000005845.2", sources=["ncbi-assemblies", "gtdb:232"]) # the first source that has it wins
gtdb.translate("g__Escherichia", ncbi, other_sources="ncbi-assemblies") # `sources` is for gtdb, `other_sources` for ncbi
translate lets a key vote once, with the node of the first source that has it. omnitax build logs the links per source and warns how many keys the sources put on different nodes.
Link attributes of the assembly summaries¶
A link has attrs, one dict of what else is known (None for nothing). The ncbi-assemblies source fills it from the assembly summaries: refseq_category, assembly_level, version_status, genome_rep, assembly_type, group, release_type, seq_rel_date, relation_to_type_material, excluded_from_refseq, asm_not_live_date and species_taxid (na and empty values are left out). Genome size, GC content and the FTP path are not stored: they differ for every genome and would grow the file by half. A selection of genomes is a filter over the links; choosing sets of genomes and the historical summaries are planned:
# complete, latest, representative or reference genomes of RefSeq bacteria
chosen = [
g.key for g in ncbi.store.rows().links
if g.source == "ncbi-assemblies" and g.key.startswith("GCF_")
and (a := g.attrs) and a.get("assembly_level") == "Complete Genome" and a.get("version_status") == "latest"
and a.get("refseq_category") in ("reference genome", "representative genome") and a.get("group") == "bacteria"
]
Old taxids¶
Assembly summaries and GTDB's metadata name taxids that NCBI has since merged (and a few it deleted). A link of a merged id is moved to the current node when the taxonomy is built or loaded (through a chain of merges, at most 100 steps). A link of a deleted or unknown id, or one in a cycle of merges, is dropped without a message (omnitax.taxonomies(path)[...]["links"] counts the links kept).
GTDB releases through representatives¶
multitax's convert places a clade of one GTDB release into another through the species representatives of the source release:
old = omnitax.load("gtdb", "214.1", representatives=True) # only the representative genomes (also downloads the metadata)
new = omnitax.load("gtdb", "232")
old.translate("g__Lactobacillus", new, details=True) # the distribution of those genomes over 232
multitax's convert returns the set of 232 nodes of the same rank; details=True gives the same set with weights, and translate the single consensus. With omnitax build the spec is gtdb:214.1+representatives.
A nearest-taxon walk¶
With ranks=, translate returns None when the result and its ancestors have none of the ranks. That is the signal to try a larger clade:
def place(gtdb_taxon, ncbi, gtdb):
"""The NCBI taxon, at a standard rank, of the smallest GTDB clade that agrees on one."""
for clade in reversed(gtdb_taxon.lineage()): # species, genus, family, ...
hit = gtdb.translate(clade, ncbi, ranks=omnitax.GTDB_RANKS, formal=True, exclude=ncbi.uninformative)
if hit is not None:
return hit
return None
Lineage strings¶
ncbi["562"].lineage_string() # "d__Bacteria;p__Pseudomonadota;...;g__Escherichia;s__Escherichia coli"
ncbi["562"].lineage_string(ranks=["genus", "species"], sep="|", prefixes=False) # "Escherichia|Escherichia coli"
GTDB's format: one name per rank of ranks (default GTDB_RANKS), root first, a missing rank empty (g__), the prefix the first letter of the rank. The loaders parse such strings, so GTDB lineage strings round-trip. write(path, ["id", "lineage_string"]) writes the column.
Annotating a table¶
omnitax.annotate.annotate(tax, rows, column, by, add) appends columns about taxa to rows (lists of strings), a batch at a time, as omnitax annotate does for a file:
from omnitax.annotate import annotate
rows = [["sample1", "562"], ["sample2", "9606"]]
for row in annotate(ncbi, rows, column=1, by="id", add=("name", "genus", "lineage_string")):
print(row) # ['sample1', '562', 'Escherichia coli', 'Escherichia', 'd__Bacteria;p__Pseudomonadota;...']
by is "id", "name" (exact, as lookup) or "link" (keys of kind=, genome accessions by default, with sources= and gca_gcf=). A value that names nothing, or several taxa (ambiguous="empty", or "first" for the best), gives empty cells, and the count is logged.
Copies and exports¶
Taxonomies are read-only. These return new taxonomies, each built into a temporary file of its own: a copy costs a rebuild (seconds for GTDB, about 90 s for NCBI), so batch your edits in one apply.
small = ncbi.subset(["561"], descendants=True) # nodes, their ancestors, optionally everything below
ncbi.prune(["2157"]) # without Archaea (keep=True: the node stays, as a leaf)
ncbi.apply(nodes=[{"id": "my:a", "parent": "562", "name": "A", "color": "red"}, {"id": "my:b", "parent": "my:a"}],
links=[{"key": "GCA_1.1", "node": "my:b"}], remove=["999"]) # add, change and remove: all edits, one rebuild
ncbi.apply("abrinca/") # the same from overlay files (see "Adding your own taxa")
ncbi.with_links(pairs) # more (key, node) pairs; kind genome unless given
ncbi.stats() # nodes, leaves, ranks, leaf_ranks, aliases, links
small.write("tax.tsv", columns=["id", "rank", "name_lineage"], ranks=omnitax.GTDB_RANKS)
gtdb.write_taxdump("gtdb-r232/") # nodes.dmp, names.dmp, merged.dmp, delnodes.dmp, taxid.map (see Taxdumps)
apply(overlay=(), *, nodes=(), links=(), remove=(), uninformative=()) is the one way to edit: a new id adds a node, an existing id changes it, remove takes nodes out (their children need a new parent in the same call; their links are dropped unless re-linked). It checks everything before it builds (Adding your own taxa).
write columns: id, parent, rank, name, lineage, name_lineage, rank_lineage, leaves, children; .gz paths are compressed. See Adding your own taxa and Taxdumps.
Files¶
omnitax.taxonomies("taxonomies.sqlite") # [{'label': 'ncbi:2026-11-26', 'nodes': ..., 'links': ..., 'built': ...}, ...]
tax = omnitax.open("taxonomies.sqlite", "ncbi") # newest version of a kind
tax = omnitax.open("taxonomies.sqlite", "gtdb:232") # a version; no name needed for a file with just one taxonomy
tax.save("taxonomies.sqlite") # add (or replace) kind:version, all or nothing
tax.save("taxonomies.sqlite", fuzzy=False) # without the trigram index (no fuzzy or substring search)
tax.close() # or: with omnitax.open(...) as tax:
One file holds any number of taxonomies, so translation between them needs just one file. save of a taxonomy that is already in the file replaces it in one transaction; a failed save leaves the file as it was. Reads are thread safe. The database layout is documented.
A file that is not an omnitax file of this layout is refused by open, taxonomies, save and the server with omnitax.LayoutError, a ValueError with .path, .layout and .expected. Rebuild such a file with omnitax build.
Connecting¶
tax = omnitax.connect(db="taxonomies.sqlite") # a file, no server
tax = omnitax.connect(socket="/run/user/1000/omnitax.sock") # a local server
tax = omnitax.connect(url="https://omnitax.example.org", taxonomy="gtdb:232") # a remote one
tax = omnitax.connect() # $OMNITAX_DB, else $OMNITAX_URL, else $OMNITAX_SOCKET, else the default socket
Give at most one of db, url and socket. Without any, the environment decides in that order, then $XDG_RUNTIME_DIR/omnitax.sock (/tmp/omnitax-$UID.sock without it); an empty variable counts as unset. taxonomy (default $OMNITAX_TAXONOMY) names the taxonomy as in open, and can be left out when there is only one.
timeout=andretries=apply to servers.retriesis how often a429or503, which a reverse proxy sends, is retried after itsRetry-After. A server of another API version is refused.prefix="/taxonomy"is the path the server's routes are mounted under, for a server mounted in your own app. On a socket it is the whole path; on a URL it comes after the URL's own path.headers={"Authorization": "Bearer ..."}is sent with every request to a server and replaces a default of the same name. It is for what sits in front of the server (a token, proxy credentials); omnitax keeps the values out of its errors.- A remote taxonomy costs one request per batch, never one per node:
tax.many(ids),tax.consensus(ids)andtax.lca(ids)are a few requests however many ids they take. Walking a tree node by node is slower than on a file; prefer the batched calls, ortax.subset(...)into a local taxonomy. omnitax.client.Clientis the HTTP transport,omnitax.remote.RemoteStorethe store on top of it,omnitax.sqlite.SqliteStorethe file's; all implement theStoreprotocol ofomnitax.store.omnitax.consensushas the voting andomnitax.linksthe key rules.