gmeta 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.
- gmeta/__init__.py +15 -0
- gmeta/__main__.py +6 -0
- gmeta/analysis/__init__.py +125 -0
- gmeta/analysis/_envelope.py +26 -0
- gmeta/analysis/centrifuge.py +131 -0
- gmeta/analysis/coverage.py +359 -0
- gmeta/analysis/host.py +113 -0
- gmeta/analysis/kaiju.py +139 -0
- gmeta/analysis/kmcp.py +161 -0
- gmeta/analysis/kraken2.py +329 -0
- gmeta/analysis/metaphlan.py +106 -0
- gmeta/analysis/profilers.py +410 -0
- gmeta/analysis/qc.py +139 -0
- gmeta/analysis/sylph.py +200 -0
- gmeta/cli.py +769 -0
- gmeta/config.py +60 -0
- gmeta/data/genus_chinese_names.tsv +52 -0
- gmeta/data/priority_pathogens.json +188 -0
- gmeta/data/species_chinese_names.tsv +96 -0
- gmeta/data/taxid_chinese_mapping.csv +94 -0
- gmeta/dbfetch.py +307 -0
- gmeta/dbstate.py +92 -0
- gmeta/engine/__init__.py +1 -0
- gmeta/engine/_env.py +72 -0
- gmeta/report/__init__.py +50 -0
- gmeta/report/excel.py +88 -0
- gmeta/report/models.py +231 -0
- gmeta/report/network.py +518 -0
- gmeta/report/pdf.py +18 -0
- gmeta/report/priority.py +37 -0
- gmeta/report/render.py +60 -0
- gmeta/samples.py +168 -0
- gmeta/templates/report.html.j2 +112 -0
- gmeta-0.1.0.dist-info/METADATA +170 -0
- gmeta-0.1.0.dist-info/RECORD +38 -0
- gmeta-0.1.0.dist-info/WHEEL +4 -0
- gmeta-0.1.0.dist-info/entry_points.txt +2 -0
- gmeta-0.1.0.dist-info/licenses/LICENSE +21 -0
gmeta/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""gmeta — metagenomic (mNGS) profiling and surveillance reporting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = version("gmeta")
|
|
10
|
+
except PackageNotFoundError:
|
|
11
|
+
__version__ = "0.1.0.dev"
|
|
12
|
+
except Exception: # pragma: no cover — extremely defensive fallback
|
|
13
|
+
__version__ = "0.1.0.dev"
|
|
14
|
+
|
|
15
|
+
__all__ = ["__version__"]
|
gmeta/__main__.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Metagenomic profilers: kraken2/bracken, sylph (ported from gside) plus
|
|
2
|
+
centrifuge, kaiju, metaphlan, kmcp executors, third-party profile parsers,
|
|
3
|
+
and the mNGS pre-processing steps (fastp QC, bowtie2 host removal).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from gmeta.analysis._envelope import METAGENOMIC, MethodEnvelope
|
|
7
|
+
from gmeta.analysis.centrifuge import (
|
|
8
|
+
CentrifugeResult,
|
|
9
|
+
profile_centrifuge,
|
|
10
|
+
resolve_centrifuge_db,
|
|
11
|
+
run_centrifuge,
|
|
12
|
+
run_centrifuge_kreport,
|
|
13
|
+
)
|
|
14
|
+
from gmeta.analysis.coverage import (
|
|
15
|
+
CoverageStats,
|
|
16
|
+
ManifestEntry,
|
|
17
|
+
coverage_for_species,
|
|
18
|
+
coverage_per_species,
|
|
19
|
+
discover_reads,
|
|
20
|
+
fasta_sequence_lengths,
|
|
21
|
+
load_manifest,
|
|
22
|
+
resolve_reference,
|
|
23
|
+
)
|
|
24
|
+
from gmeta.analysis.host import HostRemovalStats, run_host_removal
|
|
25
|
+
from gmeta.analysis.kaiju import (
|
|
26
|
+
KaijuResult,
|
|
27
|
+
profile_kaiju,
|
|
28
|
+
resolve_kaiju_db,
|
|
29
|
+
run_kaiju,
|
|
30
|
+
run_kaiju2table,
|
|
31
|
+
)
|
|
32
|
+
from gmeta.analysis.kmcp import (
|
|
33
|
+
KmcpResult,
|
|
34
|
+
profile_kmcp,
|
|
35
|
+
resolve_kmcp_db,
|
|
36
|
+
run_kmcp_profile,
|
|
37
|
+
run_kmcp_search,
|
|
38
|
+
)
|
|
39
|
+
from gmeta.analysis.kraken2 import (
|
|
40
|
+
Kraken2Result,
|
|
41
|
+
KreportRow,
|
|
42
|
+
KreportSummary,
|
|
43
|
+
parse_bracken,
|
|
44
|
+
parse_kreport,
|
|
45
|
+
profile_kraken2,
|
|
46
|
+
resolve_kraken2_db,
|
|
47
|
+
run_bracken,
|
|
48
|
+
run_kraken2,
|
|
49
|
+
)
|
|
50
|
+
from gmeta.analysis.metaphlan import (
|
|
51
|
+
MetaphlanResult,
|
|
52
|
+
profile_metaphlan,
|
|
53
|
+
resolve_metaphlan_db,
|
|
54
|
+
run_metaphlan,
|
|
55
|
+
)
|
|
56
|
+
from gmeta.analysis.profilers import (
|
|
57
|
+
AbundanceProfile,
|
|
58
|
+
TaxonAbundance,
|
|
59
|
+
attach_kaiju_genus,
|
|
60
|
+
detect_profiler,
|
|
61
|
+
parse_centrifuge_report,
|
|
62
|
+
parse_kaiju_table,
|
|
63
|
+
parse_kmcp_profile,
|
|
64
|
+
parse_metaphlan_profile,
|
|
65
|
+
)
|
|
66
|
+
from gmeta.analysis.qc import QcMetrics, parse_fastp_json, run_fastp
|
|
67
|
+
from gmeta.analysis.sylph import SylphResult, ani_confidence, parse_profile, profile_sylph
|
|
68
|
+
|
|
69
|
+
__all__ = [
|
|
70
|
+
"AbundanceProfile",
|
|
71
|
+
"CentrifugeResult",
|
|
72
|
+
"CoverageStats",
|
|
73
|
+
"HostRemovalStats",
|
|
74
|
+
"KaijuResult",
|
|
75
|
+
"KmcpResult",
|
|
76
|
+
"KreportRow",
|
|
77
|
+
"KreportSummary",
|
|
78
|
+
"Kraken2Result",
|
|
79
|
+
"ManifestEntry",
|
|
80
|
+
"METAGENOMIC",
|
|
81
|
+
"MetaphlanResult",
|
|
82
|
+
"MethodEnvelope",
|
|
83
|
+
"QcMetrics",
|
|
84
|
+
"SylphResult",
|
|
85
|
+
"TaxonAbundance",
|
|
86
|
+
"ani_confidence",
|
|
87
|
+
"attach_kaiju_genus",
|
|
88
|
+
"coverage_for_species",
|
|
89
|
+
"coverage_per_species",
|
|
90
|
+
"detect_profiler",
|
|
91
|
+
"discover_reads",
|
|
92
|
+
"fasta_sequence_lengths",
|
|
93
|
+
"load_manifest",
|
|
94
|
+
"parse_bracken",
|
|
95
|
+
"parse_centrifuge_report",
|
|
96
|
+
"parse_fastp_json",
|
|
97
|
+
"parse_kaiju_table",
|
|
98
|
+
"parse_kmcp_profile",
|
|
99
|
+
"parse_kreport",
|
|
100
|
+
"parse_metaphlan_profile",
|
|
101
|
+
"parse_profile",
|
|
102
|
+
"profile_centrifuge",
|
|
103
|
+
"profile_kaiju",
|
|
104
|
+
"profile_kmcp",
|
|
105
|
+
"profile_kraken2",
|
|
106
|
+
"profile_metaphlan",
|
|
107
|
+
"profile_sylph",
|
|
108
|
+
"resolve_centrifuge_db",
|
|
109
|
+
"resolve_kaiju_db",
|
|
110
|
+
"resolve_kmcp_db",
|
|
111
|
+
"resolve_kraken2_db",
|
|
112
|
+
"resolve_metaphlan_db",
|
|
113
|
+
"resolve_reference",
|
|
114
|
+
"run_bracken",
|
|
115
|
+
"run_centrifuge",
|
|
116
|
+
"run_centrifuge_kreport",
|
|
117
|
+
"run_fastp",
|
|
118
|
+
"run_host_removal",
|
|
119
|
+
"run_kaiju",
|
|
120
|
+
"run_kaiju2table",
|
|
121
|
+
"run_kraken2",
|
|
122
|
+
"run_kmcp_profile",
|
|
123
|
+
"run_kmcp_search",
|
|
124
|
+
"run_metaphlan",
|
|
125
|
+
]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Shared JSON envelope for per-method results (aligned with gside)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, ClassVar
|
|
7
|
+
|
|
8
|
+
METAGENOMIC = "metagenomic_profiling"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class MethodEnvelope:
|
|
13
|
+
"""Every profiler returns ``{analysis_type, method, database, result}``."""
|
|
14
|
+
|
|
15
|
+
analysis_type: ClassVar[str] = METAGENOMIC
|
|
16
|
+
method: str = ""
|
|
17
|
+
database: dict[str, str] = field(default_factory=dict)
|
|
18
|
+
result: dict[str, Any] = field(default_factory=dict)
|
|
19
|
+
|
|
20
|
+
def to_dict(self) -> dict[str, Any]:
|
|
21
|
+
return {
|
|
22
|
+
"analysis_type": self.analysis_type,
|
|
23
|
+
"method": self.method,
|
|
24
|
+
"database": self.database,
|
|
25
|
+
"result": self.result,
|
|
26
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Centrifuge profiling: classify reads, then convert to a kraken-style kreport.
|
|
2
|
+
|
|
3
|
+
``centrifuge-kreport`` emits the kraken2 report layout, so the existing
|
|
4
|
+
kreport parser (tree pairing, 识别网 export) applies unchanged — one honest
|
|
5
|
+
tree instead of a table approximation.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import ClassVar
|
|
14
|
+
|
|
15
|
+
from gmeta.analysis._envelope import METAGENOMIC, MethodEnvelope
|
|
16
|
+
from gmeta.analysis.kraken2 import KreportSummary, parse_kreport
|
|
17
|
+
from gmeta.config import DB_DIR, which
|
|
18
|
+
from gmeta.engine._env import require_bin, run_to_file
|
|
19
|
+
|
|
20
|
+
_CENTRIFUGE_HINT = "centrifuge not found — pixi add centrifuge"
|
|
21
|
+
_KREPORT_HINT = "centrifuge-kreport not found — pixi add centrifuge"
|
|
22
|
+
|
|
23
|
+
_TOP_N = 20
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class CentrifugeResult(MethodEnvelope):
|
|
28
|
+
analysis_type: ClassVar[str] = METAGENOMIC
|
|
29
|
+
method: str = "centrifuge"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def resolve_centrifuge_db(db_dir: str | Path | None = None) -> str:
|
|
33
|
+
"""Centrifuge index prefix (files ``<prefix>.1.cf.index`` …) as a string.
|
|
34
|
+
|
|
35
|
+
Accepts either the prefix itself or a directory containing index files.
|
|
36
|
+
"""
|
|
37
|
+
candidate = Path(db_dir) if db_dir else DB_DIR / "centrifuge"
|
|
38
|
+
if candidate.suffix == ".cf" or candidate.name.endswith(".cf.index"):
|
|
39
|
+
return str(candidate)
|
|
40
|
+
if candidate.is_dir():
|
|
41
|
+
indexes = sorted(candidate.glob("*.1.cf.index*"))
|
|
42
|
+
if indexes:
|
|
43
|
+
# e.g. p_compressed.1.cf.index → prefix p_compressed
|
|
44
|
+
return str(indexes[0]).split(".1.cf.index")[0]
|
|
45
|
+
# a directory that IS the prefix (files named <dir>.1.cf.index beside it)
|
|
46
|
+
sibling = sorted(candidate.parent.glob(f"{candidate.name}.1.cf.index*"))
|
|
47
|
+
if sibling:
|
|
48
|
+
return str(candidate)
|
|
49
|
+
raise RuntimeError(
|
|
50
|
+
f"centrifuge index not found at {candidate} "
|
|
51
|
+
"(run: gmeta db fetch centrifuge, or set -D/--db-dir)"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def run_centrifuge(
|
|
56
|
+
inputs: Sequence[str | Path],
|
|
57
|
+
db_prefix: str,
|
|
58
|
+
threads: int,
|
|
59
|
+
work: Path,
|
|
60
|
+
) -> Path:
|
|
61
|
+
"""Classify reads; classification TSV is streamed to ``work/centrifuge.tsv``."""
|
|
62
|
+
centrifuge = require_bin("centrifuge", hint=_CENTRIFUGE_HINT, resolver=which)
|
|
63
|
+
cmd = [centrifuge, "-x", db_prefix, "-p", str(threads), "-t"]
|
|
64
|
+
if len(inputs) == 2:
|
|
65
|
+
cmd += ["-1", str(inputs[0]), "-2", str(inputs[1])]
|
|
66
|
+
else:
|
|
67
|
+
cmd += ["-u", str(inputs[0])]
|
|
68
|
+
return run_to_file(
|
|
69
|
+
cmd, stdout_path=work / "centrifuge.tsv", timeout=7200, name="centrifuge failed"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def run_centrifuge_kreport(db_prefix: str, classified_tsv: Path, work: Path) -> Path:
|
|
74
|
+
"""Convert the classification output to a kraken-style kreport."""
|
|
75
|
+
kreport_bin = require_bin("centrifuge-kreport", hint=_KREPORT_HINT, resolver=which)
|
|
76
|
+
return run_to_file(
|
|
77
|
+
[kreport_bin, "-x", db_prefix, str(classified_tsv)],
|
|
78
|
+
stdout_path=work / "kreport.txt",
|
|
79
|
+
timeout=600,
|
|
80
|
+
name="centrifuge-kreport failed",
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def profile_centrifuge(
|
|
85
|
+
files: Sequence[str | Path],
|
|
86
|
+
db_dir: str | Path | None = None,
|
|
87
|
+
threads: int = 4,
|
|
88
|
+
work_dir: str | Path | None = None,
|
|
89
|
+
) -> CentrifugeResult:
|
|
90
|
+
"""Classify one sample with centrifuge (1 file = single-end, 2 = paired).
|
|
91
|
+
|
|
92
|
+
With ``work_dir`` the classification TSV and kreport are kept there (used
|
|
93
|
+
by ``gmeta run`` so reports can cite them).
|
|
94
|
+
"""
|
|
95
|
+
import contextlib
|
|
96
|
+
import tempfile
|
|
97
|
+
|
|
98
|
+
db_prefix = resolve_centrifuge_db(db_dir)
|
|
99
|
+
|
|
100
|
+
if work_dir is not None:
|
|
101
|
+
work = Path(work_dir)
|
|
102
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
ctx = contextlib.nullcontext(work) # type: ignore[arg-type]
|
|
104
|
+
else:
|
|
105
|
+
ctx = tempfile.TemporaryDirectory(prefix="gmeta-centrifuge-") # type: ignore[assignment]
|
|
106
|
+
with ctx as tmp:
|
|
107
|
+
work = Path(tmp)
|
|
108
|
+
classified = run_centrifuge(files, db_prefix, threads, work)
|
|
109
|
+
kreport = run_centrifuge_kreport(db_prefix, classified, work)
|
|
110
|
+
summary: KreportSummary = parse_kreport(kreport)
|
|
111
|
+
species = [
|
|
112
|
+
{
|
|
113
|
+
"name": row.name,
|
|
114
|
+
"taxid": row.taxid,
|
|
115
|
+
"reads": row.reads_total,
|
|
116
|
+
"fraction": row.fraction,
|
|
117
|
+
"confidence": "low",
|
|
118
|
+
}
|
|
119
|
+
for row in summary.at_rank("species")
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
return CentrifugeResult(
|
|
123
|
+
database={"name": Path(db_prefix).name, "path": db_prefix},
|
|
124
|
+
result={
|
|
125
|
+
"top_species": species[:_TOP_N],
|
|
126
|
+
"total_reads": summary.total_reads,
|
|
127
|
+
"classified_reads": summary.classified_reads,
|
|
128
|
+
"classified_fraction": round(summary.classified_fraction, 6),
|
|
129
|
+
"n_species": len(species),
|
|
130
|
+
},
|
|
131
|
+
)
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""Per-species genome coverage via minimap2 + samtools.
|
|
2
|
+
|
|
3
|
+
Ported from the standalone ``calculate_coverage.py`` used for 国家致病菌识别网
|
|
4
|
+
reporting, rewritten as streaming pure Python (no numpy/pandas): depth lines
|
|
5
|
+
are aggregated on the fly, so memory stays constant regardless of genome size.
|
|
6
|
+
|
|
7
|
+
Two modes mirror the original script:
|
|
8
|
+
|
|
9
|
+
* combined (default) — one concatenated reference per sample, one alignment;
|
|
10
|
+
~10× faster for multi-species samples, but reads mapping equally well to
|
|
11
|
+
several species are assigned to one best match only.
|
|
12
|
+
* per-species — one alignment per reference, strictly independent estimates.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import csv
|
|
18
|
+
import gzip
|
|
19
|
+
import shlex
|
|
20
|
+
import subprocess
|
|
21
|
+
import tempfile
|
|
22
|
+
from collections.abc import Sequence
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from gmeta.config import which
|
|
28
|
+
from gmeta.engine._env import require_bin
|
|
29
|
+
|
|
30
|
+
_MINIMAP2_HINT = "minimap2 not found — pixi add minimap2"
|
|
31
|
+
_SAMTOOLS_HINT = "samtools not found — pixi add samtools"
|
|
32
|
+
|
|
33
|
+
_DEFAULT_MIN_DEPTHS = (1, 5, 10)
|
|
34
|
+
|
|
35
|
+
# seq ids inside a combined reference: "{key}__{idx}"
|
|
36
|
+
_SEQ_ID_SEP = "__"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class CoverageStats:
|
|
41
|
+
"""Depth statistics for one species' reference genome (percent 0..100)."""
|
|
42
|
+
|
|
43
|
+
reference_length: int = 0
|
|
44
|
+
mean_depth: float = 0.0
|
|
45
|
+
pct_covered: dict[int, float] = field(default_factory=dict) # threshold → %
|
|
46
|
+
|
|
47
|
+
def to_dict(self) -> dict[str, Any]:
|
|
48
|
+
return {
|
|
49
|
+
"reference_length": self.reference_length,
|
|
50
|
+
"mean_depth": round(self.mean_depth, 4),
|
|
51
|
+
**{f"pct_covered_{d}x": round(pct, 4) for d, pct in self.pct_covered.items()},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class ManifestEntry:
|
|
57
|
+
accession: str
|
|
58
|
+
species_taxid: int
|
|
59
|
+
scientific_name: str
|
|
60
|
+
file_path: Path
|
|
61
|
+
|
|
62
|
+
def to_dict(self) -> dict[str, Any]:
|
|
63
|
+
return {
|
|
64
|
+
"accession": self.accession,
|
|
65
|
+
"species_taxid": self.species_taxid,
|
|
66
|
+
"scientific_name": self.scientific_name,
|
|
67
|
+
"file_path": str(self.file_path),
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_manifest(path: str | Path) -> dict[int, ManifestEntry]:
|
|
72
|
+
"""Reference-genome manifest → {species_taxid: entry}.
|
|
73
|
+
|
|
74
|
+
Manifest columns: accession,species_taxid,organism_taxid,scientific_name,
|
|
75
|
+
file_path. Relative paths resolve against the manifest's directory.
|
|
76
|
+
"""
|
|
77
|
+
manifest_path = Path(path)
|
|
78
|
+
base = manifest_path.parent
|
|
79
|
+
entries: dict[int, ManifestEntry] = {}
|
|
80
|
+
with manifest_path.open(newline="", encoding="utf-8") as fh:
|
|
81
|
+
for row in csv.DictReader(fh):
|
|
82
|
+
try:
|
|
83
|
+
taxid = int(row["species_taxid"])
|
|
84
|
+
except (KeyError, TypeError, ValueError):
|
|
85
|
+
continue
|
|
86
|
+
file_path = Path(row.get("file_path") or "")
|
|
87
|
+
if not file_path.is_absolute():
|
|
88
|
+
file_path = base / file_path
|
|
89
|
+
entries[taxid] = ManifestEntry(
|
|
90
|
+
accession=(row.get("accession") or "").strip(),
|
|
91
|
+
species_taxid=taxid,
|
|
92
|
+
scientific_name=(row.get("scientific_name") or "").strip(),
|
|
93
|
+
file_path=file_path,
|
|
94
|
+
)
|
|
95
|
+
return entries
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def resolve_reference(
|
|
99
|
+
taxid: int,
|
|
100
|
+
manifest: dict[int, ManifestEntry] | None,
|
|
101
|
+
ref_dir: str | Path | None,
|
|
102
|
+
) -> tuple[ManifestEntry | None, Path | None]:
|
|
103
|
+
"""Resolve a reference genome for a species taxid.
|
|
104
|
+
|
|
105
|
+
Order: manifest entry (its own ``file_path``, or ``{accession}*.fna``
|
|
106
|
+
inside ``ref_dir`` when given) → ``{taxid}*.fna`` glob in ``ref_dir``.
|
|
107
|
+
Returns ``(entry_or_None, fasta_path_or_None)``.
|
|
108
|
+
"""
|
|
109
|
+
entry = (manifest or {}).get(taxid)
|
|
110
|
+
if entry is not None:
|
|
111
|
+
candidates: list[Path] = []
|
|
112
|
+
if ref_dir is not None and entry.accession:
|
|
113
|
+
candidates = sorted(Path(ref_dir).glob(f"{entry.accession}*.fna"))
|
|
114
|
+
if candidates:
|
|
115
|
+
return entry, candidates[0]
|
|
116
|
+
if entry.file_path.is_file():
|
|
117
|
+
return entry, entry.file_path
|
|
118
|
+
return entry, None
|
|
119
|
+
if ref_dir is not None:
|
|
120
|
+
candidates = sorted(Path(ref_dir).glob(f"{taxid}*.fna"))
|
|
121
|
+
if candidates:
|
|
122
|
+
return None, candidates[0]
|
|
123
|
+
return None, None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def fasta_sequence_lengths(path: str | Path) -> dict[str, int]:
|
|
127
|
+
"""FASTA → {seq_id: length}; gzip-aware, streams the file."""
|
|
128
|
+
lengths: dict[str, int] = {}
|
|
129
|
+
current: str | None = None
|
|
130
|
+
opener = gzip.open if str(path).endswith(".gz") else open
|
|
131
|
+
with opener(path, "rt") as fh: # type: ignore[operator]
|
|
132
|
+
for line in fh:
|
|
133
|
+
if line.startswith(">"):
|
|
134
|
+
current = line[1:].split()[0]
|
|
135
|
+
lengths[current] = 0
|
|
136
|
+
elif current is not None:
|
|
137
|
+
lengths[current] += len(line.strip())
|
|
138
|
+
return lengths
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _align_sorted(
|
|
142
|
+
ref_fasta: Path,
|
|
143
|
+
reads: Sequence[str | Path],
|
|
144
|
+
bam_out: Path,
|
|
145
|
+
threads: int,
|
|
146
|
+
preset: str = "sr",
|
|
147
|
+
) -> None:
|
|
148
|
+
"""minimap2 -ax … | samtools sort → sorted BAM (no index needed for depth)."""
|
|
149
|
+
minimap2 = require_bin("minimap2", hint=_MINIMAP2_HINT, resolver=which)
|
|
150
|
+
require_bin("samtools", hint=_SAMTOOLS_HINT, resolver=which)
|
|
151
|
+
|
|
152
|
+
align_part = [
|
|
153
|
+
minimap2,
|
|
154
|
+
"-ax",
|
|
155
|
+
preset,
|
|
156
|
+
"-t",
|
|
157
|
+
str(threads),
|
|
158
|
+
str(ref_fasta),
|
|
159
|
+
*[str(r) for r in reads],
|
|
160
|
+
]
|
|
161
|
+
sort_part = ["samtools", "sort", "-@", str(threads), "-o", str(bam_out), "-"]
|
|
162
|
+
cmd = (
|
|
163
|
+
" ".join(shlex.quote(x) for x in align_part)
|
|
164
|
+
+ " | "
|
|
165
|
+
+ " ".join(shlex.quote(x) for x in sort_part)
|
|
166
|
+
)
|
|
167
|
+
proc = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
|
168
|
+
if proc.returncode != 0:
|
|
169
|
+
detail = proc.stderr.decode(errors="ignore")[:500]
|
|
170
|
+
raise RuntimeError(f"minimap2/samtools sort failed: {detail}")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _depth_stats_from_bam(
|
|
174
|
+
bam_path: Path,
|
|
175
|
+
seq_groups: dict[str, list[str]], # group key → seq ids
|
|
176
|
+
lengths: dict[str, int],
|
|
177
|
+
min_depths: Sequence[int] = _DEFAULT_MIN_DEPTHS,
|
|
178
|
+
) -> dict[str, CoverageStats]:
|
|
179
|
+
"""Stream ``samtools depth -a`` and aggregate per group.
|
|
180
|
+
|
|
181
|
+
``-a`` emits every reference position (zero-depth included), so the
|
|
182
|
+
per-group denominator is the group's total reference length.
|
|
183
|
+
"""
|
|
184
|
+
group_len = {key: sum(lengths[seq] for seq in seqs) for key, seqs in seq_groups.items()}
|
|
185
|
+
depth_sums = {key: 0 for key in seq_groups}
|
|
186
|
+
covered = {key: {d: 0 for d in min_depths} for key in seq_groups}
|
|
187
|
+
seq_to_group = {seq: key for key, seqs in seq_groups.items() for seq in seqs}
|
|
188
|
+
|
|
189
|
+
proc = subprocess.Popen(
|
|
190
|
+
["samtools", "depth", "-a", str(bam_path)],
|
|
191
|
+
stdout=subprocess.PIPE,
|
|
192
|
+
stderr=subprocess.PIPE,
|
|
193
|
+
)
|
|
194
|
+
assert proc.stdout is not None
|
|
195
|
+
for raw in proc.stdout:
|
|
196
|
+
fields = raw.decode().rstrip("\n").split("\t")
|
|
197
|
+
if len(fields) != 3:
|
|
198
|
+
continue
|
|
199
|
+
seq_id = fields[0]
|
|
200
|
+
key = seq_to_group.get(seq_id)
|
|
201
|
+
if key is None:
|
|
202
|
+
continue
|
|
203
|
+
try:
|
|
204
|
+
depth = int(fields[2])
|
|
205
|
+
except ValueError:
|
|
206
|
+
continue
|
|
207
|
+
depth_sums[key] += depth
|
|
208
|
+
counts = covered[key]
|
|
209
|
+
for threshold in min_depths:
|
|
210
|
+
if depth >= threshold:
|
|
211
|
+
counts[threshold] += 1
|
|
212
|
+
proc.stdout.close()
|
|
213
|
+
stderr = proc.stderr.read().decode(errors="ignore") if proc.stderr else ""
|
|
214
|
+
if proc.wait() != 0:
|
|
215
|
+
raise RuntimeError(f"samtools depth failed: {stderr[:500]}")
|
|
216
|
+
|
|
217
|
+
stats: dict[str, CoverageStats] = {}
|
|
218
|
+
for key, total_len in group_len.items():
|
|
219
|
+
if total_len == 0:
|
|
220
|
+
stats[key] = CoverageStats(reference_length=0)
|
|
221
|
+
continue
|
|
222
|
+
stats[key] = CoverageStats(
|
|
223
|
+
reference_length=total_len,
|
|
224
|
+
mean_depth=depth_sums[key] / total_len,
|
|
225
|
+
pct_covered={d: 100.0 * counts / total_len for d, counts in covered[key].items()},
|
|
226
|
+
)
|
|
227
|
+
return stats
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _build_combined_reference(
|
|
231
|
+
entries: Sequence[tuple[str, Path]], # (key, fasta path)
|
|
232
|
+
out_fasta: Path,
|
|
233
|
+
) -> tuple[dict[str, list[str]], dict[str, int]]:
|
|
234
|
+
"""Concatenate references with unique ``{key}__{idx}`` sequence ids.
|
|
235
|
+
|
|
236
|
+
Returns ``(seq_groups, lengths)`` — group key → seq ids, and seq id → length.
|
|
237
|
+
"""
|
|
238
|
+
seq_groups: dict[str, list[str]] = {}
|
|
239
|
+
lengths: dict[str, int] = {}
|
|
240
|
+
with out_fasta.open("w") as out:
|
|
241
|
+
for key, ref_path in entries:
|
|
242
|
+
seq_ids: list[str] = []
|
|
243
|
+
opener = gzip.open if str(ref_path).endswith(".gz") else open
|
|
244
|
+
with opener(ref_path, "rt") as fh: # type: ignore[operator]
|
|
245
|
+
for line in fh:
|
|
246
|
+
if line.startswith(">"):
|
|
247
|
+
seq_id = f"{key}{_SEQ_ID_SEP}{len(seq_ids)}"
|
|
248
|
+
seq_ids.append(seq_id)
|
|
249
|
+
out.write(f">{seq_id}\n")
|
|
250
|
+
lengths[seq_id] = 0
|
|
251
|
+
elif seq_ids:
|
|
252
|
+
stripped = line.strip()
|
|
253
|
+
lengths[seq_ids[-1]] += len(stripped)
|
|
254
|
+
out.write(stripped + "\n")
|
|
255
|
+
seq_groups[key] = seq_ids
|
|
256
|
+
return seq_groups, lengths
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def coverage_for_species(
|
|
260
|
+
reads: Sequence[str | Path],
|
|
261
|
+
entries: Sequence[tuple[str, Path]],
|
|
262
|
+
threads: int = 4,
|
|
263
|
+
min_depths: Sequence[int] = _DEFAULT_MIN_DEPTHS,
|
|
264
|
+
work_dir: str | Path | None = None,
|
|
265
|
+
preset: str = "sr",
|
|
266
|
+
) -> dict[str, CoverageStats]:
|
|
267
|
+
"""Coverage stats per entry key, aligning once against a combined reference.
|
|
268
|
+
|
|
269
|
+
``entries`` pairs a stable key (accession or taxid string) with a FASTA
|
|
270
|
+
path. Reads can be one file (single-end) or two (paired).
|
|
271
|
+
"""
|
|
272
|
+
if not entries:
|
|
273
|
+
return {}
|
|
274
|
+
|
|
275
|
+
if work_dir is not None:
|
|
276
|
+
work = Path(work_dir)
|
|
277
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
278
|
+
else:
|
|
279
|
+
work = Path(tempfile.mkdtemp(prefix="gmeta-cov-"))
|
|
280
|
+
|
|
281
|
+
combined = work / f"combined_{abs(hash(tuple(k for k, _ in entries)))}.fna"
|
|
282
|
+
seq_groups, lengths = _build_combined_reference(entries, combined)
|
|
283
|
+
bam_out = work / (combined.stem + ".sorted.bam")
|
|
284
|
+
_align_sorted(combined, reads, bam_out, threads, preset=preset)
|
|
285
|
+
stats = _depth_stats_from_bam(bam_out, seq_groups, lengths, min_depths)
|
|
286
|
+
|
|
287
|
+
if work_dir is None:
|
|
288
|
+
import shutil
|
|
289
|
+
|
|
290
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
291
|
+
return stats
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def coverage_per_species(
|
|
295
|
+
reads: Sequence[str | Path],
|
|
296
|
+
entries: Sequence[tuple[str, Path]],
|
|
297
|
+
threads: int = 4,
|
|
298
|
+
min_depths: Sequence[int] = _DEFAULT_MIN_DEPTHS,
|
|
299
|
+
work_dir: str | Path | None = None,
|
|
300
|
+
preset: str = "sr",
|
|
301
|
+
) -> dict[str, CoverageStats]:
|
|
302
|
+
"""Coverage per entry with strictly independent alignments (slower, exact)."""
|
|
303
|
+
stats: dict[str, CoverageStats] = {}
|
|
304
|
+
for key, ref_path in entries:
|
|
305
|
+
single = coverage_for_species(
|
|
306
|
+
reads,
|
|
307
|
+
[(key, ref_path)],
|
|
308
|
+
threads=threads,
|
|
309
|
+
min_depths=min_depths,
|
|
310
|
+
work_dir=work_dir,
|
|
311
|
+
preset=preset,
|
|
312
|
+
)
|
|
313
|
+
stats.update(single)
|
|
314
|
+
return stats
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def discover_reads(
|
|
318
|
+
reads_dir: str | Path,
|
|
319
|
+
sample: str,
|
|
320
|
+
pattern: str = "{sample}_R{pair}.fastq.gz",
|
|
321
|
+
) -> list[str] | None:
|
|
322
|
+
"""FASTQ paths for a sample; None when nothing is found.
|
|
323
|
+
|
|
324
|
+
``{pair}`` in the pattern means paired-end (expanded to 1/2); compressed
|
|
325
|
+
and uncompressed variants are tried interchangeably.
|
|
326
|
+
"""
|
|
327
|
+
base = Path(reads_dir)
|
|
328
|
+
if "{pair}" in pattern:
|
|
329
|
+
reads: list[str] = []
|
|
330
|
+
for pair in ("1", "2"):
|
|
331
|
+
candidate = pattern.format(sample=sample, pair=pair)
|
|
332
|
+
found = _try_read_variants(base, candidate)
|
|
333
|
+
if found is None:
|
|
334
|
+
return None
|
|
335
|
+
reads.append(str(found))
|
|
336
|
+
return reads
|
|
337
|
+
found = _try_read_variants(base, pattern.format(sample=sample))
|
|
338
|
+
return [str(found)] if found else None
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _try_read_variants(base: Path, name: str) -> Path | None:
|
|
342
|
+
candidate = base / name
|
|
343
|
+
if candidate.exists():
|
|
344
|
+
return candidate
|
|
345
|
+
alt = name[:-3] if name.endswith(".gz") else name + ".gz"
|
|
346
|
+
alt_path = base / alt
|
|
347
|
+
return alt_path if alt_path.exists() else None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
__all__ = [
|
|
351
|
+
"CoverageStats",
|
|
352
|
+
"ManifestEntry",
|
|
353
|
+
"coverage_for_species",
|
|
354
|
+
"coverage_per_species",
|
|
355
|
+
"discover_reads",
|
|
356
|
+
"fasta_sequence_lengths",
|
|
357
|
+
"load_manifest",
|
|
358
|
+
"resolve_reference",
|
|
359
|
+
]
|