gracer 1.0.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.
Files changed (83) hide show
  1. gracer/__init__.py +103 -0
  2. gracer/__main__.py +10 -0
  3. gracer/_ncbi.py +88 -0
  4. gracer/_parallel.py +97 -0
  5. gracer/_version.py +29 -0
  6. gracer/annotation/__init__.py +0 -0
  7. gracer/annotation/germline.py +1297 -0
  8. gracer/annotation/igblast.py +1118 -0
  9. gracer/annotation/vhh_score.py +133 -0
  10. gracer/cli/__init__.py +10 -0
  11. gracer/cli/__main__.py +9 -0
  12. gracer/cli/common.py +123 -0
  13. gracer/cli/db.py +424 -0
  14. gracer/cli/renumber.py +129 -0
  15. gracer/cli/run.py +519 -0
  16. gracer/cli/validate.py +114 -0
  17. gracer/example_data/OAS_Jaffe2022_subset.fasta +20 -0
  18. gracer/exceptions.py +49 -0
  19. gracer/germline_db/__init__.py +89 -0
  20. gracer/germline_db/_imgt.py +158 -0
  21. gracer/germline_db/alignments/__init__.py +3 -0
  22. gracer/germline_db/alignments/formatting.py +681 -0
  23. gracer/germline_db/alignments/regap.py +405 -0
  24. gracer/germline_db/build_config_template.yml +92 -0
  25. gracer/germline_db/builder/__init__.py +4 -0
  26. gracer/germline_db/builder/_common.py +83 -0
  27. gracer/germline_db/builder/config.py +844 -0
  28. gracer/germline_db/builder/expand.py +270 -0
  29. gracer/germline_db/builder/igblast.py +257 -0
  30. gracer/germline_db/builder/lockfile.py +272 -0
  31. gracer/germline_db/builder/pipeline.py +949 -0
  32. gracer/germline_db/builder/steps.py +558 -0
  33. gracer/germline_db/seed_v.hmm +2415 -0
  34. gracer/germline_db/sources/__init__.py +5 -0
  35. gracer/germline_db/sources/_http.py +252 -0
  36. gracer/germline_db/sources/_pinned.py +24 -0
  37. gracer/germline_db/sources/custom_fasta.py +512 -0
  38. gracer/germline_db/sources/genedb.py +810 -0
  39. gracer/germline_db/sources/list_available.py +475 -0
  40. gracer/germline_db/sources/ogrdb.py +830 -0
  41. gracer/germline_db/sources/vquest.py +341 -0
  42. gracer/germline_db/translate.py +121 -0
  43. gracer/io.py +327 -0
  44. gracer/loci.py +64 -0
  45. gracer/models.py +861 -0
  46. gracer/nucleotide.py +188 -0
  47. gracer/numbering/__init__.py +129 -0
  48. gracer/numbering/_numba.py +29 -0
  49. gracer/numbering/cdr3_tail.py +144 -0
  50. gracer/numbering/compact.py +205 -0
  51. gracer/numbering/germline_layout.py +338 -0
  52. gracer/numbering/hmm.py +490 -0
  53. gracer/numbering/profile_nw.py +724 -0
  54. gracer/numbering/profiles.py +472 -0
  55. gracer/numbering/schemes/__init__.py +10 -0
  56. gracer/numbering/schemes/_base.py +68 -0
  57. gracer/numbering/schemes/engine.py +647 -0
  58. gracer/numbering/schemes/junctions.py +144 -0
  59. gracer/numbering/schemes/tables.py +419 -0
  60. gracer/output/__init__.py +14 -0
  61. gracer/output/columns.py +404 -0
  62. gracer/output/encoding.py +370 -0
  63. gracer/output/parallel_writer.py +539 -0
  64. gracer/output/regions.py +307 -0
  65. gracer/output/rows.py +384 -0
  66. gracer/output/writers.py +261 -0
  67. gracer/paths.py +51 -0
  68. gracer/py.typed +0 -0
  69. gracer/runner/__init__.py +13 -0
  70. gracer/runner/core.py +899 -0
  71. gracer/runner/domains.py +699 -0
  72. gracer/runner/notices.py +353 -0
  73. gracer/runner/pool.py +534 -0
  74. gracer/runner/provenance.py +98 -0
  75. gracer/runner/tables.py +312 -0
  76. gracer/runner/workers.py +402 -0
  77. gracer/structure.py +898 -0
  78. gracer-1.0.0.dist-info/METADATA +217 -0
  79. gracer-1.0.0.dist-info/RECORD +83 -0
  80. gracer-1.0.0.dist-info/WHEEL +5 -0
  81. gracer-1.0.0.dist-info/entry_points.txt +2 -0
  82. gracer-1.0.0.dist-info/licenses/LICENSE +21 -0
  83. gracer-1.0.0.dist-info/top_level.txt +1 -0
gracer/__init__.py ADDED
@@ -0,0 +1,103 @@
1
+ __all__ = [
2
+ "GracerError",
3
+ "SchemeError",
4
+ "DatabaseError",
5
+ "AlignmentError",
6
+ "WorkerError",
7
+ "GracerWarning",
8
+ "DomainResult",
9
+ "SequenceResult",
10
+ "GracerResults",
11
+ "number",
12
+ "stream",
13
+ "annotate",
14
+ "number_dataframe",
15
+ "renumber",
16
+ "to_dataframe",
17
+ "encode_positions",
18
+ "align_embeddings",
19
+ "available_species",
20
+ "scheme_supports_species",
21
+ "CHAIN_TYPE_TO_LOCUS",
22
+ "LOCUS_TO_CHAIN",
23
+ "get_genedb_dataframe",
24
+ "get_ogrdb_dataframe",
25
+ "build_database",
26
+ "export_lockfile",
27
+ "init_build_config",
28
+ "get_database_info",
29
+ "list_ogrdb_available",
30
+ "list_genedb_available",
31
+ "list_vquest_available",
32
+ ]
33
+
34
+ from .exceptions import (
35
+ AlignmentError,
36
+ DatabaseError,
37
+ GracerError,
38
+ GracerWarning,
39
+ SchemeError,
40
+ WorkerError,
41
+ )
42
+
43
+ # Typed for mypy and IDEs without importing anything at runtime: `import
44
+ # gracer` stays cheap (no pyhmmer, numba or germline JSON) until a name is
45
+ # used. A local constant rather than typing.TYPE_CHECKING keeps typing itself
46
+ # out of the import. Every name here must also be in _LAZY_MODULES;
47
+ # tests/test_public_api.py checks the two agree.
48
+ TYPE_CHECKING = False
49
+ if TYPE_CHECKING:
50
+ from .germline_db.builder.lockfile import export_lockfile
51
+ from .germline_db.builder.pipeline import build_database, get_database_info, init_build_config
52
+ from .germline_db.sources.genedb import get_genedb_dataframe
53
+ from .germline_db.sources.list_available import (
54
+ list_genedb_available,
55
+ list_ogrdb_available,
56
+ list_vquest_available,
57
+ )
58
+ from .germline_db.sources.ogrdb import get_ogrdb_dataframe
59
+ from .loci import CHAIN_TYPE_TO_LOCUS, LOCUS_TO_CHAIN
60
+ from .models import DomainResult, GracerResults, SequenceResult
61
+ from .output.encoding import align_embeddings, encode_positions
62
+ from .output.writers import to_dataframe
63
+ from .runner.core import number, stream
64
+ from .runner.domains import available_species, scheme_supports_species
65
+ from .runner.tables import annotate, number_dataframe
66
+ from .structure import renumber
67
+
68
+ # Where each lazily exported name is defined, relative to this package.
69
+ _LAZY_MODULES: dict[str, tuple[str, ...]] = {
70
+ ".models": ("DomainResult", "SequenceResult", "GracerResults"),
71
+ ".runner.core": ("number", "stream"),
72
+ ".runner.tables": ("annotate", "number_dataframe"),
73
+ ".output.writers": ("to_dataframe",),
74
+ ".structure": ("renumber",),
75
+ ".output.encoding": ("encode_positions", "align_embeddings"),
76
+ ".runner.domains": ("available_species", "scheme_supports_species"),
77
+ ".loci": ("CHAIN_TYPE_TO_LOCUS", "LOCUS_TO_CHAIN"),
78
+ ".germline_db.sources.genedb": ("get_genedb_dataframe",),
79
+ ".germline_db.sources.ogrdb": ("get_ogrdb_dataframe",),
80
+ ".germline_db.builder.lockfile": ("export_lockfile",),
81
+ ".germline_db.builder.pipeline": ("build_database", "get_database_info", "init_build_config"),
82
+ ".germline_db.sources.list_available": (
83
+ "list_ogrdb_available",
84
+ "list_genedb_available",
85
+ "list_vquest_available",
86
+ ),
87
+ }
88
+ _LAZY = {name: module for module, names in _LAZY_MODULES.items() for name in names}
89
+
90
+
91
+ def __getattr__(name: str) -> object:
92
+ if name == "__version__":
93
+ from gracer._version import gracer_version
94
+
95
+ globals()["__version__"] = gracer_version()
96
+ return globals()["__version__"]
97
+ if name in _LAZY:
98
+ from importlib import import_module
99
+
100
+ value = getattr(import_module(_LAZY[name], __name__), name)
101
+ globals()[name] = value
102
+ return value
103
+ raise AttributeError(f"module 'gracer' has no attribute {name!r}")
gracer/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """``python -m gracer``: the gracer command line, as the ``gracer`` script runs it.
2
+
3
+ The one module outside ``gracer/cli/`` that imports it: this is the command
4
+ line's own entry point, not library code that would come to depend on it.
5
+ """
6
+
7
+ from gracer.cli.__main__ import main
8
+
9
+ if __name__ == "__main__":
10
+ main()
gracer/_ncbi.py ADDED
@@ -0,0 +1,88 @@
1
+ """Running NCBI BLAST+ / IgBLAST tools without trusting the working directory.
2
+
3
+ The NCBI toolkit looks for its configuration (``<tool>.ini``, then
4
+ ``.ncbirc``) in ``.`` before anywhere else (``CMetaRegistry::
5
+ GetDefaultSearchPath``), and IgBLAST reads ``internal_data`` from ``.``
6
+ before ``$IGDATA``. A config planted in the directory gracer runs from can
7
+ log the environment, secrets included, to a file of the planter's choosing;
8
+ a planted ``internal_data`` shifts IgBLAST's region calls. :func:`run` starts
9
+ every tool in a private, empty temporary directory, with only the
10
+ environment the tools need, and :func:`find_tool` skips relative ``PATH``
11
+ entries (an empty one is the cwd).
12
+ """
13
+
14
+ import contextlib
15
+ import os
16
+ import shutil
17
+ import subprocess
18
+ import tempfile
19
+ from collections.abc import Sequence
20
+ from pathlib import Path
21
+
22
+ # What the tools read from the environment. IGDATA locates IgBLAST's
23
+ # internal_data and optional_file (bioconda's wrappers set it); NCBI and
24
+ # NCBI_CONFIG_PATH are where a user keeps their own config. Everything else,
25
+ # tokens and cloud credentials included, stays out of reach of a config's
26
+ # LogEnvironment.
27
+ _KEPT_ENV = ("PATH", "HOME", "TMPDIR", "LANG", "IGDATA", "NCBI", "NCBI_CONFIG_PATH")
28
+
29
+
30
+ def _search_path() -> str:
31
+ return os.pathsep.join(
32
+ p for p in os.environ.get("PATH", os.defpath).split(os.pathsep) if os.path.isabs(p)
33
+ )
34
+
35
+
36
+ def find_tool(name: str) -> str | None:
37
+ """Absolute path of *name* on ``PATH``, ignoring relative entries."""
38
+ return shutil.which(name, path=_search_path())
39
+
40
+
41
+ def _env() -> dict[str, str]:
42
+ env = {k: v for k, v in os.environ.items() if k in _KEPT_ENV or k.startswith("LC_")}
43
+ env["PATH"] = _search_path()
44
+ return env
45
+
46
+
47
+ def run(cmd: Sequence[str | Path], cwd: Path | None = None) -> "subprocess.CompletedProcess[str]":
48
+ """Run an NCBI tool from a private empty directory, capturing its output.
49
+
50
+ ``cmd[0]`` must be an absolute path (from :func:`find_tool`). Every
51
+ ``Path`` argument is made absolute against the caller's cwd before the
52
+ tool starts elsewhere, so pass file arguments as ``Path``, never ``str``.
53
+
54
+ *cwd* runs the tool in a directory of gracer's own making instead (one
55
+ nothing else can write to), for a ``str`` argument naming a file in it:
56
+ an alias database records such a name as given, and BLAST resolves it
57
+ from the alias file's own directory, wherever that is reached from.
58
+ """
59
+ tool = str(cmd[0])
60
+ if not os.path.isabs(tool):
61
+ raise ValueError(f"NCBI tool path must be absolute, got {tool!r}")
62
+ with contextlib.ExitStack() as stack:
63
+ where = cwd or Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="gracer_ncbi_")))
64
+ args = [tool] + [_argument(a, where) for a in cmd[1:]]
65
+ return subprocess.run(args, cwd=where, env=_env(), capture_output=True, text=True)
66
+
67
+
68
+ def _argument(arg: str | Path, cwd: Path) -> str:
69
+ """*arg* as the tool should see it, from *cwd*.
70
+
71
+ BLAST splits database names on whitespace (several databases can be given
72
+ in one argument), even within one argv entry, so a path with a space in a
73
+ directory name is reached through a link in *cwd* instead: a relative
74
+ database name is looked up from the working directory first."""
75
+ if not isinstance(arg, Path):
76
+ return arg
77
+ path = arg.absolute()
78
+ if not any(c.isspace() for c in str(path.parent)):
79
+ return str(path)
80
+ # One link per directory: igblastn crashes when one database is reached
81
+ # under two names (one passed as two segments' database, say).
82
+ for link in cwd.iterdir():
83
+ if link.is_symlink() and link.readlink() == path.parent:
84
+ break
85
+ else:
86
+ link = cwd / f"p{len(list(cwd.iterdir()))}"
87
+ link.symlink_to(path.parent, target_is_directory=True)
88
+ return f"{link.name}/{path.name}"
gracer/_parallel.py ADDED
@@ -0,0 +1,97 @@
1
+ """Chunked thread fan-out shared by the NW kernel and the igblast runners,
2
+ and the CPU count every "use all cores" default sizes itself from.
3
+
4
+ Leaf module: imports nothing from gracer.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import os
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from pathlib import Path
13
+ from typing import Callable, TypeVar
14
+
15
+ _T = TypeVar("_T")
16
+ _R = TypeVar("_R")
17
+
18
+
19
+ def map_chunks(
20
+ fn: Callable[[list[_T]], _R],
21
+ items: list[_T],
22
+ ncpu: int | None,
23
+ ) -> list[_R]:
24
+ """``fn`` over ``ncpu`` contiguous chunks of ``items`` in a thread pool,
25
+ one result per chunk, in order.
26
+
27
+ One task per chunk rather than per item keeps dispatch overhead flat at
28
+ scale. Threads only help when ``fn`` releases the GIL (numba ``nogil``
29
+ kernels, subprocesses). With ``ncpu`` <= 1 or fewer than two items, ``fn``
30
+ runs once, inline, on the whole list.
31
+ """
32
+ if not ncpu or ncpu <= 1 or len(items) < 2:
33
+ return [fn(items)]
34
+ size = math.ceil(len(items) / ncpu)
35
+ chunks = [items[i : i + size] for i in range(0, len(items), size)]
36
+ with ThreadPoolExecutor(max_workers=ncpu) as ex:
37
+ return list(ex.map(fn, chunks))
38
+
39
+
40
+ def available_cpus(
41
+ cgroup_root: Path = Path("/sys/fs/cgroup"),
42
+ proc_cgroup: Path = Path("/proc/self/cgroup"),
43
+ ) -> int:
44
+ """CPUs this process can actually run on: its affinity mask, capped by
45
+ a cgroup CPU quota.
46
+
47
+ ``os.cpu_count()`` counts the host's cores, so a container limited with
48
+ ``docker --cpus 2`` (or a Kubernetes CPU limit, or a Slurm job's cgroup)
49
+ on a 64-core host started 64 workers that the quota then throttled.
50
+ """
51
+ affinity = getattr(os, "sched_getaffinity", None) # absent on macOS
52
+ n = len(affinity(0)) if affinity else (os.cpu_count() or 1)
53
+ quota = _cgroup_cpu_quota(cgroup_root, proc_cgroup)
54
+ if quota is not None:
55
+ n = min(n, max(1, math.ceil(quota)))
56
+ return max(1, n)
57
+
58
+
59
+ def _cgroup_cpu_quota(root: Path, proc_cgroup: Path) -> float | None:
60
+ """The tightest CPU quota, in CPUs, on this process's cgroup or its
61
+ ancestors; None when there is none or no cgroup filesystem (macOS)."""
62
+ try:
63
+ entries = proc_cgroup.read_text().splitlines()
64
+ except OSError:
65
+ return None
66
+ limits: list[float] = []
67
+ for entry in entries:
68
+ hierarchy, controllers, path = entry.split(":", 2)
69
+ rel = Path(path.lstrip("/"))
70
+ if hierarchy == "0" and controllers == "":
71
+ # cgroup v2: "max 100000" (none) or "<quota> <period>" in cpu.max,
72
+ # on this cgroup and each parent up to the mount root.
73
+ for d in [root / rel, *(root / p for p in rel.parents)]:
74
+ limits += _ratio(d / "cpu.max")
75
+ elif "cpu" in controllers.split(","):
76
+ # cgroup v1: cfs_quota_us (-1 = none) over cfs_period_us. In a
77
+ # container the hierarchy is mounted at the container's own
78
+ # cgroup, so the host path in /proc/self/cgroup may not exist.
79
+ for base in (root / "cpu,cpuacct", root / "cpu"):
80
+ for d in (base / rel, base):
81
+ limits += _ratio(d / "cpu.cfs_quota_us", d / "cpu.cfs_period_us")
82
+ return min(limits) if limits else None
83
+
84
+
85
+ def _ratio(quota_file: Path, period_file: Path | None = None) -> list[float]:
86
+ """[quota / period] from cgroup files, or [] when absent or unlimited.
87
+ Without *period_file*, both come from *quota_file* (v2's cpu.max)."""
88
+ try:
89
+ if period_file is None:
90
+ quota, period = quota_file.read_text().split()
91
+ else:
92
+ quota = quota_file.read_text().strip()
93
+ period = period_file.read_text().strip()
94
+ q, p = int(quota), int(period)
95
+ except (OSError, ValueError): # missing file, "max", or malformed
96
+ return []
97
+ return [q / p] if q > 0 and p > 0 else []
gracer/_version.py ADDED
@@ -0,0 +1,29 @@
1
+ """gracer's version, for lockfiles, messages and ``--version``.
2
+
3
+ Leaf module: imports nothing from gracer.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import functools
9
+ import re
10
+ from importlib.metadata import PackageNotFoundError, version
11
+ from pathlib import Path
12
+
13
+
14
+ @functools.cache
15
+ def gracer_version() -> str:
16
+ """The installed distribution's version; in a source tree run without
17
+ installing it (``PYTHONPATH=.``), the version pyproject.toml beside the
18
+ package gives, else ``"unknown"``. A missing distribution used to crash
19
+ ``gracer --version``, and a build only once it had run to the end."""
20
+ try:
21
+ return version("gracer")
22
+ except PackageNotFoundError:
23
+ pass
24
+ try:
25
+ text = (Path(__file__).parent.parent / "pyproject.toml").read_text(encoding="utf-8")
26
+ except OSError:
27
+ return "unknown"
28
+ found = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE)
29
+ return found.group(1) if found else "unknown"
File without changes