omnitax 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- omnitax/__init__.py +26 -0
- omnitax/__main__.py +5 -0
- omnitax/_download.py +163 -0
- omnitax/_serve.py +110 -0
- omnitax/annotate.py +100 -0
- omnitax/api.py +72 -0
- omnitax/cli.py +415 -0
- omnitax/client.py +188 -0
- omnitax/consensus.py +193 -0
- omnitax/core.py +792 -0
- omnitax/dbwrite.py +479 -0
- omnitax/links.py +109 -0
- omnitax/loaders.py +718 -0
- omnitax/names.py +31 -0
- omnitax/overlay.py +353 -0
- omnitax/paths.py +51 -0
- omnitax/py.typed +0 -0
- omnitax/remote.py +87 -0
- omnitax/schema.py +109 -0
- omnitax/server.py +346 -0
- omnitax/sqlite.py +786 -0
- omnitax/store.py +169 -0
- omnitax/taxdump.py +345 -0
- omnitax-0.1.0.dist-info/METADATA +97 -0
- omnitax-0.1.0.dist-info/RECORD +28 -0
- omnitax-0.1.0.dist-info/WHEEL +4 -0
- omnitax-0.1.0.dist-info/entry_points.txt +2 -0
- omnitax-0.1.0.dist-info/licenses/LICENSE +21 -0
omnitax/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""omnitax: biological taxonomies (NCBI, GTDB, SILVA, Greengenes, Open Tree, custom) as Python
|
|
2
|
+
objects, parsed into a SQLite file, read from one or from a server.
|
|
3
|
+
|
|
4
|
+
::
|
|
5
|
+
|
|
6
|
+
import omnitax
|
|
7
|
+
|
|
8
|
+
tax = omnitax.load("gtdb", "232") # parse into a temporary SQLite file
|
|
9
|
+
tax = omnitax.open("taxonomy.sqlite", "ncbi") # a file (see `omnitax build`)
|
|
10
|
+
tax = omnitax.connect(url="https://...", taxonomy="ncbi") # a server
|
|
11
|
+
tax["562"].lineage()
|
|
12
|
+
tax.consensus({"562": 6, "564": 4})
|
|
13
|
+
|
|
14
|
+
Importing this package needs only the standard library; ``httpx`` is imported when something is
|
|
15
|
+
downloaded or a server is used, ``starlette`` only by :mod:`omnitax.server`.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0" # first: modules imported below read it
|
|
19
|
+
|
|
20
|
+
from . import loaders
|
|
21
|
+
from .api import connect, open, taxonomies
|
|
22
|
+
from .core import GTDB_RANKS, Taxon, Taxonomy
|
|
23
|
+
from .loaders import load
|
|
24
|
+
from .sqlite import LayoutError
|
|
25
|
+
|
|
26
|
+
__all__ = ["GTDB_RANKS", "LayoutError", "Taxon", "Taxonomy", "__version__", "connect", "load", "loaders", "open", "taxonomies"]
|
omnitax/__main__.py
ADDED
omnitax/_download.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Downloading a source file: a resumable ``httpx`` transfer.
|
|
2
|
+
|
|
3
|
+
Only what ``omnitax build`` needs. The transfer goes to ``<destination>.part``, resumes with
|
|
4
|
+
HTTP ``Range`` and ``If-Range`` (the ``ETag`` or ``Last-Modified`` is kept in ``<destination>.part.validator``), is tried again a few times
|
|
5
|
+
after connection errors and ``5xx``, and is renamed once the size matches the ``Content-Length`` of the server.
|
|
6
|
+
``httpx`` is imported here, so a machine that only reads a taxonomy file never loads it.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, NamedTuple
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
#: Chunk size for streaming transfers.
|
|
21
|
+
CHUNK_SIZE = 1024 * 1024
|
|
22
|
+
#: Tries after the first one for a connection error or a 5xx answer, and the wait before the first (it doubles).
|
|
23
|
+
RETRIES = 3
|
|
24
|
+
RETRY_DELAY = 1.0
|
|
25
|
+
|
|
26
|
+
ProgressCallback = Callable[[str, int, int | None], None]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DownloadError(RuntimeError):
|
|
30
|
+
"""A transfer failed or produced the wrong file size."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _range_start(response: httpx.Response) -> int | None:
|
|
34
|
+
"""Where a ``206`` response starts: ``Content-Range: bytes 100-999/1000`` is 100."""
|
|
35
|
+
try:
|
|
36
|
+
return int(response.headers["Content-Range"].split(None, 1)[1].split("-", 1)[0])
|
|
37
|
+
except (KeyError, IndexError, ValueError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Download(NamedTuple):
|
|
42
|
+
"""A file downloaded: where it is, its ``size`` and its checksums, computed as it arrived."""
|
|
43
|
+
|
|
44
|
+
path: Path
|
|
45
|
+
size: int
|
|
46
|
+
sha256: str
|
|
47
|
+
md5: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _hashed(path: Path | None = None) -> tuple[int, Any, Any]:
|
|
51
|
+
"""``(size, sha256, md5)`` hashers that have read ``path`` (none: fresh ones)."""
|
|
52
|
+
sha, md5, size = hashlib.sha256(), hashlib.md5(usedforsecurity=False), 0
|
|
53
|
+
if path:
|
|
54
|
+
with open(path, "rb") as handle:
|
|
55
|
+
while chunk := handle.read(CHUNK_SIZE):
|
|
56
|
+
sha.update(chunk)
|
|
57
|
+
md5.update(chunk)
|
|
58
|
+
size += len(chunk)
|
|
59
|
+
return size, sha, md5
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def hash_file(path: Path) -> tuple[int, str, str]:
|
|
63
|
+
"""``(size, sha256, md5)`` of a file that was not downloaded (a cached or a local one): one pass over it."""
|
|
64
|
+
size, sha, md5 = _hashed(path)
|
|
65
|
+
return size, sha.hexdigest(), md5.hexdigest()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _validator(response: httpx.Response) -> str:
|
|
69
|
+
"""What tells that a resumed transfer is of the same file: the strong ``ETag``, else ``Last-Modified`` (empty: neither)."""
|
|
70
|
+
tag = response.headers.get("ETag", "")
|
|
71
|
+
return tag if tag and not tag.startswith("W/") else response.headers.get("Last-Modified", "")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _attempt(client: httpx.Client, url: str, partial: Path, progress: ProgressCallback | None) -> tuple[int, Any, Any, int | None]:
|
|
75
|
+
"""One transfer into ``partial``, resuming what is there when the server confirms it is still the same file (``If-Range`` with the validator kept
|
|
76
|
+
next to it; without one the partial file is dropped). ``(size, sha256, md5, expected size)``."""
|
|
77
|
+
sidecar = partial.with_name(partial.name + ".validator")
|
|
78
|
+
offset = partial.stat().st_size if partial.exists() else 0
|
|
79
|
+
validator = sidecar.read_text().strip() if sidecar.exists() else ""
|
|
80
|
+
if offset and not validator: # cannot be told from a part of another file
|
|
81
|
+
partial.unlink()
|
|
82
|
+
offset = 0
|
|
83
|
+
# identity: the bytes are saved as served (a .gz stays a .gz) and their number is the Content-Length
|
|
84
|
+
headers = {"Accept-Encoding": "identity", **({"Range": f"bytes={offset}-", "If-Range": validator} if offset else {})}
|
|
85
|
+
with client.stream("GET", url, headers=headers) as response:
|
|
86
|
+
resumed = bool(offset) and response.status_code == 206
|
|
87
|
+
if response.status_code == 416 or (resumed and _range_start(response) != offset):
|
|
88
|
+
partial.unlink(missing_ok=True)
|
|
89
|
+
sidecar.unlink(missing_ok=True)
|
|
90
|
+
return _attempt(client, url, partial, progress) # from the start
|
|
91
|
+
response.raise_for_status()
|
|
92
|
+
if not resumed: # a new file (or the server says the old one changed: 200 to a ranged request)
|
|
93
|
+
if validator_now := _validator(response):
|
|
94
|
+
sidecar.write_text(validator_now)
|
|
95
|
+
else:
|
|
96
|
+
sidecar.unlink(missing_ok=True)
|
|
97
|
+
done, sha, md5 = _hashed(partial if resumed else None) # a resumed file is read once, for what is there already
|
|
98
|
+
length = response.headers.get("Content-Length")
|
|
99
|
+
total = done + int(length) if length and length.isdigit() else None
|
|
100
|
+
with open(partial, "ab" if resumed else "wb") as handle:
|
|
101
|
+
for chunk in response.iter_raw(CHUNK_SIZE):
|
|
102
|
+
handle.write(chunk)
|
|
103
|
+
sha.update(chunk)
|
|
104
|
+
md5.update(chunk)
|
|
105
|
+
done += len(chunk)
|
|
106
|
+
if progress is not None:
|
|
107
|
+
progress(partial.name.removesuffix(".part"), done, total)
|
|
108
|
+
return done, sha, md5, total
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def download(url: str, destination: Path, progress: ProgressCallback | None = None) -> Download:
|
|
112
|
+
"""Download ``url`` into ``destination`` through ``destination.part``. An interrupted transfer is resumed (read once, to be hashed) if the
|
|
113
|
+
server says the file is the same (``If-Range``), else it starts over; connection errors and ``5xx`` answers are tried again ``RETRIES``
|
|
114
|
+
times, resuming. The bytes are those the server holds (no ``Content-Encoding`` is undone). The checksums are those of the whole file."""
|
|
115
|
+
partial = destination.with_name(destination.name + ".part")
|
|
116
|
+
partial.parent.mkdir(parents=True, exist_ok=True)
|
|
117
|
+
try:
|
|
118
|
+
with httpx.Client(timeout=httpx.Timeout(None, connect=30.0), follow_redirects=True) as client:
|
|
119
|
+
for attempt in range(RETRIES + 1):
|
|
120
|
+
try:
|
|
121
|
+
done, sha, md5, total = _attempt(client, url, partial, progress)
|
|
122
|
+
break
|
|
123
|
+
except (httpx.NetworkError, httpx.TimeoutException, httpx.RemoteProtocolError, httpx.HTTPStatusError) as error:
|
|
124
|
+
if attempt == RETRIES or (isinstance(error, httpx.HTTPStatusError) and error.response.status_code < 500):
|
|
125
|
+
raise
|
|
126
|
+
time.sleep(RETRY_DELAY * 2**attempt)
|
|
127
|
+
except (httpx.HTTPError, OSError) as error:
|
|
128
|
+
raise DownloadError(f"could not download {url}: {error}") from error
|
|
129
|
+
if total is not None and done != total:
|
|
130
|
+
partial.unlink(missing_ok=True)
|
|
131
|
+
partial.with_name(partial.name + ".validator").unlink(missing_ok=True)
|
|
132
|
+
raise DownloadError(f"could not download {url}: expected {total} bytes, got {done}")
|
|
133
|
+
partial.replace(destination)
|
|
134
|
+
partial.with_name(partial.name + ".validator").unlink(missing_ok=True)
|
|
135
|
+
return Download(destination, done, sha.hexdigest(), md5.hexdigest())
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class ProgressPrinter:
|
|
139
|
+
"""Callable progress reporter: rewrites one line per whole percent."""
|
|
140
|
+
|
|
141
|
+
def __init__(self, stream: object = None) -> None:
|
|
142
|
+
self.stream = stream if stream is not None else sys.stderr
|
|
143
|
+
self._last: dict[str, int] = {}
|
|
144
|
+
|
|
145
|
+
def __call__(self, name: str, done: int, total: int | None) -> None:
|
|
146
|
+
if total:
|
|
147
|
+
percent = int(done * 100 / total)
|
|
148
|
+
if percent == self._last.get(name) and done < total:
|
|
149
|
+
return
|
|
150
|
+
self._last[name] = percent
|
|
151
|
+
print(
|
|
152
|
+
f"\r{name}: {percent:3d}% ({done / 1e6:.1f}/{total / 1e6:.1f} MB)",
|
|
153
|
+
end="\n" if done >= total else "",
|
|
154
|
+
file=self.stream,
|
|
155
|
+
flush=True,
|
|
156
|
+
)
|
|
157
|
+
else:
|
|
158
|
+
print(
|
|
159
|
+
f"\r{name}: {done / 1e6:.1f} MB",
|
|
160
|
+
end="",
|
|
161
|
+
file=self.stream,
|
|
162
|
+
flush=True,
|
|
163
|
+
)
|
omnitax/_serve.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Running the app of ``omnitax serve``: sockets and the process around uvicorn.
|
|
2
|
+
|
|
3
|
+
``uvicorn.run(uds=...)`` makes the socket file world-writable, so the sockets are bound here
|
|
4
|
+
(mode ``SOCKET_MODE``) and handed over; the socket file is removed again when the server
|
|
5
|
+
stops, also on SIGTERM, and a socket another server listens on is never taken.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import signal
|
|
12
|
+
import socket
|
|
13
|
+
import stat
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from starlette.applications import Starlette
|
|
20
|
+
|
|
21
|
+
from .paths import SOCKET_MODE
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def prepare_unix_socket(path: Path) -> None:
|
|
25
|
+
"""Remove a stale socket file, refusing to steal a live one."""
|
|
26
|
+
if not path.exists() and not path.is_symlink():
|
|
27
|
+
return
|
|
28
|
+
if not path.is_socket():
|
|
29
|
+
raise RuntimeError(f"{path} exists and is not a socket; refusing to remove it")
|
|
30
|
+
for attempt in range(3): # a server that has bound but not yet listened refuses connections as well
|
|
31
|
+
try:
|
|
32
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
|
|
33
|
+
probe.settimeout(1.0)
|
|
34
|
+
probe.connect(str(path))
|
|
35
|
+
except FileNotFoundError:
|
|
36
|
+
return
|
|
37
|
+
except ConnectionRefusedError:
|
|
38
|
+
time.sleep(0.1 if attempt < 2 else 0)
|
|
39
|
+
except OSError as error:
|
|
40
|
+
raise RuntimeError(f"cannot check whether {path} is in use: {error}") from error
|
|
41
|
+
else:
|
|
42
|
+
raise RuntimeError(f"another server is already listening on {path}")
|
|
43
|
+
path.unlink(missing_ok=True)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _bind(family: int, address: Any) -> socket.socket:
|
|
47
|
+
sock = socket.socket(family, socket.SOCK_STREAM)
|
|
48
|
+
try:
|
|
49
|
+
if family == socket.AF_UNIX:
|
|
50
|
+
sock.bind(str(address))
|
|
51
|
+
os.chmod(address, SOCKET_MODE)
|
|
52
|
+
else:
|
|
53
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
54
|
+
sock.bind(address)
|
|
55
|
+
except BaseException:
|
|
56
|
+
sock.close()
|
|
57
|
+
raise
|
|
58
|
+
return sock
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _identity(path: Path) -> tuple[int, int] | None:
|
|
62
|
+
try:
|
|
63
|
+
st = path.stat()
|
|
64
|
+
except OSError:
|
|
65
|
+
return None
|
|
66
|
+
return (st.st_dev, st.st_ino) if stat.S_ISSOCK(st.st_mode) else None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def serve(app: Starlette, *, socket_path: Path | None = None, tcp: tuple[str, int] | None = None, log_level: str = "info") -> None:
|
|
70
|
+
"""Run ``app`` until interrupted, on a Unix socket, on ``host:port``, or on both."""
|
|
71
|
+
if socket_path is None and tcp is None:
|
|
72
|
+
raise ValueError("give a socket_path, a tcp address or both")
|
|
73
|
+
import uvicorn
|
|
74
|
+
|
|
75
|
+
sockets: list[socket.socket] = []
|
|
76
|
+
ours: tuple[int, int] | None = None # the identity of the socket file we bound
|
|
77
|
+
|
|
78
|
+
def cleanup() -> None:
|
|
79
|
+
for sock in sockets:
|
|
80
|
+
sock.close()
|
|
81
|
+
if socket_path is not None and ours is not None and _identity(socket_path) == ours:
|
|
82
|
+
socket_path.unlink(missing_ok=True)
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
if socket_path is not None:
|
|
86
|
+
socket_path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
prepare_unix_socket(socket_path)
|
|
88
|
+
sockets.append(_bind(socket.AF_UNIX, socket_path))
|
|
89
|
+
ours = _identity(socket_path)
|
|
90
|
+
if tcp is not None:
|
|
91
|
+
sockets.append(_bind(socket.AF_INET6 if ":" in tcp[0] else socket.AF_INET, tcp))
|
|
92
|
+
except BaseException:
|
|
93
|
+
cleanup()
|
|
94
|
+
raise
|
|
95
|
+
previous = None
|
|
96
|
+
if socket_path is not None and threading.current_thread() is threading.main_thread():
|
|
97
|
+
# uvicorn re-raises SIGTERM after its graceful shutdown, which would kill the process
|
|
98
|
+
# before the ``finally`` below runs: clean up first, then terminate with the default action.
|
|
99
|
+
def on_sigterm(signum: int, frame: Any) -> None:
|
|
100
|
+
cleanup()
|
|
101
|
+
signal.signal(signal.SIGTERM, signal.SIG_DFL)
|
|
102
|
+
os.kill(os.getpid(), signal.SIGTERM)
|
|
103
|
+
|
|
104
|
+
previous = signal.signal(signal.SIGTERM, on_sigterm)
|
|
105
|
+
try:
|
|
106
|
+
uvicorn.Server(uvicorn.Config(app, log_level=log_level, access_log=False)).run(sockets=sockets)
|
|
107
|
+
finally:
|
|
108
|
+
cleanup()
|
|
109
|
+
if previous is not None:
|
|
110
|
+
signal.signal(signal.SIGTERM, previous)
|
omnitax/annotate.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""``annotate``: add the lineage, name, rank ... of taxa to the rows of a table, a batch of rows at a time (so a server is
|
|
2
|
+
asked once per batch, not once per row)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from collections.abc import Iterable, Iterator, Sequence
|
|
9
|
+
from itertools import batched
|
|
10
|
+
|
|
11
|
+
from .core import Linked, Taxon, Taxonomy, lineage_text
|
|
12
|
+
from .store import GENOME, GTDB_RANKS, Rec
|
|
13
|
+
|
|
14
|
+
log = logging.getLogger("omnitax")
|
|
15
|
+
|
|
16
|
+
#: The columns that can be added besides a rank (``genus``, ``species``, ...: the name of the node's ancestor of that rank).
|
|
17
|
+
COLUMNS = ("id", "name", "rank", "lineage", "lineage_string")
|
|
18
|
+
BY = ("id", "name", "link")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _cell(column: str, taxon: Taxon, chain: Sequence[Rec]) -> str:
|
|
22
|
+
match column:
|
|
23
|
+
case "id" | "name" | "rank":
|
|
24
|
+
return getattr(taxon, column)
|
|
25
|
+
case "lineage":
|
|
26
|
+
return "|".join(r.id for r in chain)
|
|
27
|
+
case "lineage_string":
|
|
28
|
+
return lineage_text(chain, GTDB_RANKS, ";", True)
|
|
29
|
+
case _: # a rank: the nearest ancestor-or-self of that rank
|
|
30
|
+
return next((r.name for r in reversed(chain) if r.rank == column), "")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def column_names(header: Sequence[str], add: Sequence[str], prefix: str | None = None) -> list[str]:
|
|
34
|
+
"""The headers of the added columns: as they are, unless the input has one of that name (then ``omnitax_`` is put before it);
|
|
35
|
+
with ``prefix`` every one gets it."""
|
|
36
|
+
return [f"{prefix}{c}" if prefix is not None else f"omnitax_{c}" if c in header else c for c in add]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def check(tax: Taxonomy, by: str = "id", add: Sequence[str] = ("id", "name", "rank"), ambiguous: str = "empty") -> None:
|
|
40
|
+
"""Refuse options that ``annotate`` cannot work with (``annotate`` is a generator: it only does so when the first row is asked for)."""
|
|
41
|
+
if by not in BY or ambiguous not in ("empty", "first"):
|
|
42
|
+
raise ValueError(f"by is one of {', '.join(BY)}; ambiguous is empty or first")
|
|
43
|
+
if bad := [c for c in add if c not in COLUMNS and c not in tax.ranks]:
|
|
44
|
+
raise ValueError(f"cannot add {', '.join(bad)}: the columns are {', '.join(COLUMNS)} and the ranks of the taxonomy ({', '.join(tax.ranks)})")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def annotate(
|
|
48
|
+
tax: Taxonomy,
|
|
49
|
+
rows: Iterable[Sequence[str]],
|
|
50
|
+
column: int = 0,
|
|
51
|
+
by: str = "id",
|
|
52
|
+
add: Sequence[str] = ("id", "name", "rank"),
|
|
53
|
+
*,
|
|
54
|
+
ambiguous: str = "empty",
|
|
55
|
+
sources: str | Sequence[str] | None = None,
|
|
56
|
+
gca_gcf: bool = False,
|
|
57
|
+
kind: str = GENOME,
|
|
58
|
+
batch: int = 1000,
|
|
59
|
+
) -> Iterator[list[str]]:
|
|
60
|
+
"""Each of ``rows`` with ``add`` appended, for the taxon its ``column`` (counting from 0) holds: ``by="id"`` its id (an old,
|
|
61
|
+
merged id gives the current node), ``"name"`` its exact name (``Taxonomy.lookup``) or ``"link"`` a key of the ``kind`` given (``Taxonomy.links``, default ``genome``:
|
|
62
|
+
an assembly accession; with ``gca_gcf`` and ``sources``). ``add``: ``id``, ``name``, ``rank``, ``lineage`` (ids, ``|``), ``lineage_string``
|
|
63
|
+
(GTDB's ``d__...;s__...``) or the name of a rank in the taxonomy (``genus``: the name of the ancestor of that rank).
|
|
64
|
+
A value that is empty or names nothing gives empty cells; one that names several taxa (homonyms, or an accession of several
|
|
65
|
+
versions or sources) gives empty cells too, or with ``ambiguous="first"`` those of the best. How many were not found or ambiguous is logged
|
|
66
|
+
(warning) when the rows are used up. Rows are handled ``batch`` at a time."""
|
|
67
|
+
check(tax, by, add, ambiguous)
|
|
68
|
+
tally: Counter[str] = Counter() # empty, missing, unclear, resolved
|
|
69
|
+
for block in batched(rows, batch):
|
|
70
|
+
keys = list(dict.fromkeys(row[column].strip() for row in block if len(row) > column and row[column].strip()))
|
|
71
|
+
found: dict[str, Taxon | None] = {}
|
|
72
|
+
for key, taxon in _resolve(tax, keys, by, ambiguous, sources, gca_gcf, kind).items():
|
|
73
|
+
found[key] = taxon
|
|
74
|
+
chains = tax.store.ancestors([t.id for t in found.values() if t], attrs=False) if any(found.values()) else {}
|
|
75
|
+
for row in block:
|
|
76
|
+
key = row[column].strip() if len(row) > column else ""
|
|
77
|
+
taxon = found.get(key) if key else None
|
|
78
|
+
tally["empty" if not key else "missing" if key not in found else "unclear" if taxon is None else "resolved"] += 1
|
|
79
|
+
yield [*row, *([_cell(c, taxon, chains[taxon.id]) for c in add] if taxon else [""] * len(add))]
|
|
80
|
+
what = {"link": "key", "name": "name"}.get(by, "id")
|
|
81
|
+
parts = [f"{tally.total():,} rows", f"{tally['resolved']:,} resolved", f"{tally['missing']:,} {what}s not found", f"{tally['unclear']:,} ambiguous"]
|
|
82
|
+
if tally["empty"]:
|
|
83
|
+
parts.insert(1, f"{tally['empty']:,} empty")
|
|
84
|
+
lost = tally["missing"] or tally["unclear"]
|
|
85
|
+
log.log(logging.WARNING if lost else logging.INFO, "annotate: %s%s", ", ".join(parts), " (left empty)" if lost else "")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _resolve(tax: Taxonomy, keys: list[str], by: str, ambiguous: str, sources: str | Sequence[str] | None, gca_gcf: bool, kind: str) -> dict[str, Taxon | None]:
|
|
89
|
+
"""The taxon of each key that names one; ``None`` for a key that names several and ``ambiguous`` says empty; keys that name nothing are left out."""
|
|
90
|
+
if by == "id":
|
|
91
|
+
return {k: t for k, t in zip(keys, tax.many(keys), strict=True) if t}
|
|
92
|
+
out: dict[str, Taxon | None] = {}
|
|
93
|
+
if by == "name":
|
|
94
|
+
for key, hits in tax.lookup(keys).items():
|
|
95
|
+
out[key] = hits[0] if len(hits) == 1 or ambiguous == "first" else None
|
|
96
|
+
return out
|
|
97
|
+
links = tax.links(keys, kind, gca_gcf=gca_gcf, sources=sources)
|
|
98
|
+
firsts = {k: found[0].node for k, found in links.items() if not isinstance(found, Linked) and ambiguous == "first"} # several versions or sources that disagree: the best
|
|
99
|
+
taxa = dict(zip(firsts, tax.many(list(firsts.values())), strict=True))
|
|
100
|
+
return {k: found.taxon if isinstance(found, Linked) else taxa.get(k) for k, found in links.items()}
|
omnitax/api.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Where a taxonomy lives: ``open`` a file, ``connect`` to a server (or the file or server the
|
|
2
|
+
environment names), ``taxonomies`` of a file. ``httpx`` is imported only when a server is used."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .core import Taxonomy
|
|
11
|
+
from .paths import default_socket_path
|
|
12
|
+
from .sqlite import SqliteStore, list_taxonomies
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def open(path: str | os.PathLike[str], taxonomy: str | None = None) -> Taxonomy:
|
|
16
|
+
"""A taxonomy of a SQLite file: ``"ncbi"`` (its newest version), ``"gtdb:232"``, or no name
|
|
17
|
+
when the file holds just one. See :meth:`Taxonomy.save` and ``omnitax build``."""
|
|
18
|
+
return Taxonomy(SqliteStore(path, taxonomy))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def taxonomies(path: str | os.PathLike[str]) -> list[dict[str, Any]]:
|
|
22
|
+
"""What a file holds: ``label``, ``kind``, ``version``, ``nodes``, ``links``, ``built``, ..."""
|
|
23
|
+
return list_taxonomies(path)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def resolve_address(url: str | None = None, socket: str | os.PathLike[str] | None = None, db: str | os.PathLike[str] | None = None) -> tuple[str, str]:
|
|
27
|
+
"""``("db" | "url" | "socket", where)``: the one argument given, else ``$OMNITAX_DB``,
|
|
28
|
+
``$OMNITAX_URL``, ``$OMNITAX_SOCKET`` (the first that is not empty), else the default socket."""
|
|
29
|
+
if sum(x is not None for x in (url, socket, db)) > 1:
|
|
30
|
+
raise ValueError("give at most one of db, url and socket")
|
|
31
|
+
for kind, value in (("db", db), ("url", url), ("socket", socket)):
|
|
32
|
+
if value is not None:
|
|
33
|
+
return kind, str(value)
|
|
34
|
+
for kind, name in (("db", "OMNITAX_DB"), ("url", "OMNITAX_URL"), ("socket", "OMNITAX_SOCKET")):
|
|
35
|
+
if os.environ.get(name):
|
|
36
|
+
return kind, os.environ[name]
|
|
37
|
+
return "socket", str(default_socket_path())
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def client_for(kind: str, where: str, *, timeout: float | None = None, retries: int = 0, headers: Mapping[str, str] | None = None, prefix: str = ""):
|
|
41
|
+
"""The client of a server address (``kind`` ``"url"`` or ``"socket"``, as :func:`resolve_address` says)."""
|
|
42
|
+
from .client import Client
|
|
43
|
+
|
|
44
|
+
return Client(**{kind: where}, timeout=timeout, retries=retries, headers=headers, prefix=prefix)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def connect(
|
|
48
|
+
*,
|
|
49
|
+
url: str | None = None,
|
|
50
|
+
socket: str | os.PathLike[str] | None = None,
|
|
51
|
+
db: str | os.PathLike[str] | None = None,
|
|
52
|
+
taxonomy: str | None = None,
|
|
53
|
+
timeout: float | None = None,
|
|
54
|
+
retries: int = 0,
|
|
55
|
+
headers: Mapping[str, str] | None = None,
|
|
56
|
+
prefix: str = "",
|
|
57
|
+
) -> Taxonomy:
|
|
58
|
+
"""A taxonomy from a file (``db``), a server on a URL or a Unix socket; none given: what the
|
|
59
|
+
environment says (see :func:`resolve_address`). ``taxonomy`` (default ``$OMNITAX_TAXONOMY``)
|
|
60
|
+
names it as in :func:`open`. ``retries`` is how often a 429 or 503 is retried after its ``Retry-After``. ``headers`` are sent with every request to a server (see :class:`omnitax.client.Client`), and ``prefix`` is the path the server's routes are mounted under (``"/taxonomy"``)."""
|
|
61
|
+
kind, where = resolve_address(url, socket, db)
|
|
62
|
+
taxonomy = taxonomy or os.environ.get("OMNITAX_TAXONOMY") or None
|
|
63
|
+
if kind == "db":
|
|
64
|
+
return open(where, taxonomy)
|
|
65
|
+
from .remote import RemoteStore
|
|
66
|
+
|
|
67
|
+
client = client_for(kind, where, timeout=timeout, retries=retries, headers=headers, prefix=prefix)
|
|
68
|
+
try:
|
|
69
|
+
return Taxonomy(RemoteStore(client, taxonomy))
|
|
70
|
+
except BaseException:
|
|
71
|
+
client.close()
|
|
72
|
+
raise
|