viro-drift 0.1.0__tar.gz
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.
- viro_drift-0.1.0/LICENSE +21 -0
- viro_drift-0.1.0/PKG-INFO +41 -0
- viro_drift-0.1.0/README.md +23 -0
- viro_drift-0.1.0/pyproject.toml +33 -0
- viro_drift-0.1.0/setup.cfg +4 -0
- viro_drift-0.1.0/viro_drift/__init__.py +30 -0
- viro_drift-0.1.0/viro_drift/cli.py +163 -0
- viro_drift-0.1.0/viro_drift/host_partition.py +126 -0
- viro_drift-0.1.0/viro_drift/micro_assembler.py +220 -0
- viro_drift-0.1.0/viro_drift/recruitment.py +187 -0
- viro_drift-0.1.0/viro_drift/translation_bait.py +243 -0
- viro_drift-0.1.0/viro_drift.egg-info/PKG-INFO +41 -0
- viro_drift-0.1.0/viro_drift.egg-info/SOURCES.txt +15 -0
- viro_drift-0.1.0/viro_drift.egg-info/dependency_links.txt +1 -0
- viro_drift-0.1.0/viro_drift.egg-info/entry_points.txt +2 -0
- viro_drift-0.1.0/viro_drift.egg-info/requires.txt +2 -0
- viro_drift-0.1.0/viro_drift.egg-info/top_level.txt +1 -0
viro_drift-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: viro-drift
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Adaptive divergent viral discovery via 6-frame protein seed baiting and local micro-assembly
|
|
5
|
+
Author-email: "Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute" <shwetabac@gmail.com>
|
|
6
|
+
Maintainer-email: "Dr. Shweta Singh" <shwetabac@gmail.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/molecularplantpathology/Virome-Suite
|
|
9
|
+
Project-URL: Repository, https://github.com/molecularplantpathology/Virome-Suite.git
|
|
10
|
+
Project-URL: Issues, https://github.com/molecularplantpathology/Virome-Suite/issues
|
|
11
|
+
Keywords: virome,metagenomics,virus-discovery,plant-pathology,bioinformatics
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: biopython>=1.81
|
|
16
|
+
Requires-Dist: numpy>=1.24.0
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# viro-drift
|
|
20
|
+
|
|
21
|
+
**Adaptive Divergent Viral Pathogen Discovery via 6-Frame Catalytic Seed Baiting & Local Micro-Assembly**
|
|
22
|
+
|
|
23
|
+
Part of the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
|
|
24
|
+
|
|
25
|
+
## Key Features
|
|
26
|
+
- **Evidence-Preserving Host Read Partitioning:** Separates host-concordant reads, ambiguous host-viral chimeric bridges (preserved for downstream integration checks), and unmapped viral candidates.
|
|
27
|
+
- **Low-Complexity & Homopolymer Shield:** Sliding-window nucleotide Shannon entropy masking ($H < 1.20\text{ bits}$) with strict stop/ambiguous residue exclusion.
|
|
28
|
+
- **6-Frame Collinear Catalytic Baiting:** Recruits divergent viral reads (15%–35% nucleotide divergence) using reduced-alphabet amino acid $k$-mers (`kmer_seed` self-contained engine) or external `DIAMOND blastx` / `HMMER hmmsearch`.
|
|
29
|
+
- **Two-Phase Cycle-Safe Micro-Assembly:** Strand-normalized iterative paired recruitment and local de Bruijn assembly supporting both linear unitigs and closed circular viral rings.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install viro-drift
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Quick Start
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
viro-drift run --r1 unmapped_R1.fasta --r2 unmapped_R2.fasta --seeds viral_core_seeds.faa -o out_drift/
|
|
41
|
+
```
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# viro-drift
|
|
2
|
+
|
|
3
|
+
**Adaptive Divergent Viral Pathogen Discovery via 6-Frame Catalytic Seed Baiting & Local Micro-Assembly**
|
|
4
|
+
|
|
5
|
+
Part of the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
|
|
6
|
+
|
|
7
|
+
## Key Features
|
|
8
|
+
- **Evidence-Preserving Host Read Partitioning:** Separates host-concordant reads, ambiguous host-viral chimeric bridges (preserved for downstream integration checks), and unmapped viral candidates.
|
|
9
|
+
- **Low-Complexity & Homopolymer Shield:** Sliding-window nucleotide Shannon entropy masking ($H < 1.20\text{ bits}$) with strict stop/ambiguous residue exclusion.
|
|
10
|
+
- **6-Frame Collinear Catalytic Baiting:** Recruits divergent viral reads (15%–35% nucleotide divergence) using reduced-alphabet amino acid $k$-mers (`kmer_seed` self-contained engine) or external `DIAMOND blastx` / `HMMER hmmsearch`.
|
|
11
|
+
- **Two-Phase Cycle-Safe Micro-Assembly:** Strand-normalized iterative paired recruitment and local de Bruijn assembly supporting both linear unitigs and closed circular viral rings.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install viro-drift
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
viro-drift run --r1 unmapped_R1.fasta --r2 unmapped_R2.fasta --seeds viral_core_seeds.faa -o out_drift/
|
|
23
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "viro-drift"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Adaptive divergent viral discovery via 6-frame protein seed baiting and local micro-assembly"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute", email = "shwetabac@gmail.com" },
|
|
14
|
+
]
|
|
15
|
+
maintainers = [
|
|
16
|
+
{ name = "Dr. Shweta Singh", email = "shwetabac@gmail.com" },
|
|
17
|
+
]
|
|
18
|
+
keywords = ["virome", "metagenomics", "virus-discovery", "plant-pathology", "bioinformatics"]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"biopython>=1.81",
|
|
21
|
+
"numpy>=1.24.0",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/molecularplantpathology/Virome-Suite"
|
|
26
|
+
Repository = "https://github.com/molecularplantpathology/Virome-Suite.git"
|
|
27
|
+
Issues = "https://github.com/molecularplantpathology/Virome-Suite/issues"
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
viro-drift = "viro_drift.cli:main"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools]
|
|
33
|
+
packages = ["viro_drift"]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Package 1: viro_drift — Adaptive Divergent Viral Pathogen Discovery."""
|
|
2
|
+
|
|
3
|
+
from viro_drift.host_partition import PartitionedReads, build_host_kmer_index, partition_host_reads
|
|
4
|
+
from viro_drift.micro_assembler import AssembledContig, assemble_viral_contigs
|
|
5
|
+
from viro_drift.recruitment import RecruitmentResult, iterative_recruit_reads
|
|
6
|
+
from viro_drift.translation_bait import (
|
|
7
|
+
ReducedAlphabetSeedIndex,
|
|
8
|
+
bait_reads_with_seeds,
|
|
9
|
+
mask_low_complexity_nt,
|
|
10
|
+
shannon_entropy_nt,
|
|
11
|
+
translate_6frames,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"__version__",
|
|
18
|
+
"AssembledContig",
|
|
19
|
+
"PartitionedReads",
|
|
20
|
+
"RecruitmentResult",
|
|
21
|
+
"ReducedAlphabetSeedIndex",
|
|
22
|
+
"assemble_viral_contigs",
|
|
23
|
+
"bait_reads_with_seeds",
|
|
24
|
+
"build_host_kmer_index",
|
|
25
|
+
"iterative_recruit_reads",
|
|
26
|
+
"mask_low_complexity_nt",
|
|
27
|
+
"partition_host_reads",
|
|
28
|
+
"shannon_entropy_nt",
|
|
29
|
+
"translate_6frames",
|
|
30
|
+
]
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""CLI Entrypoint and Pipeline Runner for Package 1: `viro-drift`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import pathlib
|
|
8
|
+
import sys
|
|
9
|
+
from typing import Dict, List, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
from Bio import SeqIO
|
|
12
|
+
|
|
13
|
+
from viro_drift import __version__
|
|
14
|
+
from viro_drift.host_partition import build_host_kmer_index, partition_host_reads
|
|
15
|
+
from viro_drift.micro_assembler import assemble_viral_contigs
|
|
16
|
+
from viro_drift.recruitment import iterative_recruit_reads
|
|
17
|
+
from viro_drift.translation_bait import bait_reads_with_seeds, check_external_bait_tool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _detect_seq_format(path: pathlib.Path) -> str:
|
|
21
|
+
suffix = path.suffix.lower()
|
|
22
|
+
if suffix in (".fq", ".fastq"):
|
|
23
|
+
return "fastq"
|
|
24
|
+
with path.open("r", encoding="utf-8") as f:
|
|
25
|
+
first = f.readline().strip()
|
|
26
|
+
return "fastq" if first.startswith("@") else "fasta"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _load_read_pairs(
|
|
30
|
+
r1_path: pathlib.Path,
|
|
31
|
+
r2_path: Optional[pathlib.Path] = None,
|
|
32
|
+
) -> List[Tuple[str, str, Optional[str]]]:
|
|
33
|
+
fmt1 = _detect_seq_format(r1_path)
|
|
34
|
+
recs1 = list(SeqIO.parse(str(r1_path), fmt1))
|
|
35
|
+
if r2_path is None:
|
|
36
|
+
return [(r.id.split("/")[0], str(r.seq), None) for r in recs1]
|
|
37
|
+
fmt2 = _detect_seq_format(r2_path)
|
|
38
|
+
recs2 = list(SeqIO.parse(str(r2_path), fmt2))
|
|
39
|
+
if len(recs1) != len(recs2):
|
|
40
|
+
raise ValueError(f"Mismatched paired read counts: R1={len(recs1)}, R2={len(recs2)}")
|
|
41
|
+
return [
|
|
42
|
+
(a.id.split("/")[0], str(a.seq), str(b.seq))
|
|
43
|
+
for a, b in zip(recs1, recs2)
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _load_fasta_dict(path: pathlib.Path) -> Dict[str, str]:
|
|
48
|
+
records = list(SeqIO.parse(str(path), "fasta"))
|
|
49
|
+
if not records:
|
|
50
|
+
raise ValueError(f"No valid FASTA records found in {path}")
|
|
51
|
+
return {r.id: str(r.seq) for r in records}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
55
|
+
parser = argparse.ArgumentParser(
|
|
56
|
+
prog="viro-drift",
|
|
57
|
+
description="viro_drift: 6-frame translated protein-seeded viral read baiting and local micro-assembly.",
|
|
58
|
+
)
|
|
59
|
+
parser.add_argument("--version", action="version", version=f"viro-drift {__version__}")
|
|
60
|
+
sub = parser.add_subparsers(dest="subcommand", required=True)
|
|
61
|
+
|
|
62
|
+
run_p = sub.add_parser("run", help="Bait divergent viral reads and execute local micro-assembly.")
|
|
63
|
+
run_p.add_argument("--r1", type=pathlib.Path, required=True, help="Forward reads (FASTA/FASTQ).")
|
|
64
|
+
run_p.add_argument("--r2", type=pathlib.Path, required=False, help="Reverse reads (FASTA/FASTQ).")
|
|
65
|
+
run_p.add_argument("--seeds", type=pathlib.Path, required=True, help="Core viral protein seeds (FAA).")
|
|
66
|
+
run_p.add_argument("--host", type=pathlib.Path, required=False, help="Optional host reference FASTA for masking.")
|
|
67
|
+
run_p.add_argument("--mode", choices=["kmer_seed", "diamond", "hmmer"], default="kmer_seed")
|
|
68
|
+
run_p.add_argument("--max-rounds", type=int, default=5, help="Maximum iterative recruitment rounds.")
|
|
69
|
+
run_p.add_argument("-o", "--output", type=pathlib.Path, required=True, help="Output directory.")
|
|
70
|
+
return parser
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
74
|
+
parser = build_parser()
|
|
75
|
+
try:
|
|
76
|
+
args = parser.parse_args(argv)
|
|
77
|
+
except SystemExit as exc:
|
|
78
|
+
return int(exc.code) if exc.code is not None else 2
|
|
79
|
+
|
|
80
|
+
if args.subcommand == "run":
|
|
81
|
+
if not args.r1.exists() or not args.seeds.exists():
|
|
82
|
+
print("Error: Input reads or seed file does not exist.", file=sys.stderr)
|
|
83
|
+
return 2
|
|
84
|
+
if args.r2 is not None and not args.r2.exists():
|
|
85
|
+
print("Error: Specified --r2 file does not exist.", file=sys.stderr)
|
|
86
|
+
return 2
|
|
87
|
+
|
|
88
|
+
if args.mode in ("diamond", "hmmer"):
|
|
89
|
+
try:
|
|
90
|
+
check_external_bait_tool(args.mode)
|
|
91
|
+
except FileNotFoundError as exc:
|
|
92
|
+
print(f"External binary missing: {exc}", file=sys.stderr)
|
|
93
|
+
return 3
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
read_pairs = _load_read_pairs(args.r1, args.r2)
|
|
97
|
+
seeds = _load_fasta_dict(args.seeds)
|
|
98
|
+
host_seqs = list(_load_fasta_dict(args.host).values()) if (args.host and args.host.exists()) else []
|
|
99
|
+
except Exception as exc:
|
|
100
|
+
print(f"Input validation error: {exc}", file=sys.stderr)
|
|
101
|
+
return 2
|
|
102
|
+
|
|
103
|
+
args.output.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
host_kmers = build_host_kmer_index(host_seqs, k=21) if host_seqs else set()
|
|
105
|
+
partition = partition_host_reads(read_pairs, host_kmers, k=21)
|
|
106
|
+
|
|
107
|
+
seed_ids, seed_hits = bait_reads_with_seeds(
|
|
108
|
+
partition.viral_candidate,
|
|
109
|
+
seeds=seeds,
|
|
110
|
+
mode=args.mode,
|
|
111
|
+
seeds_path=args.seeds,
|
|
112
|
+
work_dir=args.output,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
out_fasta = args.output / "assembled_contigs.fasta"
|
|
116
|
+
summary_json = args.output / "viro_drift_summary.json"
|
|
117
|
+
|
|
118
|
+
if not seed_ids:
|
|
119
|
+
out_fasta.write_text("", encoding="utf-8")
|
|
120
|
+
summary = {
|
|
121
|
+
"status": "NO_VIRAL_CANDIDATES",
|
|
122
|
+
"partition": partition.summary_counts(),
|
|
123
|
+
"initial_seed_reads": 0,
|
|
124
|
+
"recruited_pairs": 0,
|
|
125
|
+
"assembled_contigs": 0,
|
|
126
|
+
}
|
|
127
|
+
summary_json.write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
rec = iterative_recruit_reads(
|
|
131
|
+
partition.viral_candidate,
|
|
132
|
+
initial_seed_ids=seed_ids,
|
|
133
|
+
host_kmer_mask=host_kmers,
|
|
134
|
+
max_rounds=args.max_rounds,
|
|
135
|
+
)
|
|
136
|
+
contigs = assemble_viral_contigs(rec.recruited_pairs)
|
|
137
|
+
|
|
138
|
+
with out_fasta.open("w", encoding="utf-8") as f:
|
|
139
|
+
for c in contigs:
|
|
140
|
+
f.write(
|
|
141
|
+
f">{c.contig_id} length={len(c.sequence)} depth={c.mean_kmer_depth} "
|
|
142
|
+
f"circular_cycle={c.is_circular_cycle}\n{c.sequence}\n"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
summary = {
|
|
146
|
+
"status": "CANDIDATES_ASSEMBLED" if contigs else "SEEDS_RECRUITED_NO_CONTIG",
|
|
147
|
+
"partition": partition.summary_counts(),
|
|
148
|
+
"initial_seed_reads": len(seed_ids),
|
|
149
|
+
"matched_seed_domains": sorted(set(seed_hits.values())),
|
|
150
|
+
"recruited_pairs": len(rec.recruited_pairs),
|
|
151
|
+
"rounds_executed": rec.rounds_executed,
|
|
152
|
+
"stop_reason": rec.stop_reason,
|
|
153
|
+
"filtered_host_decoys_count": rec.filtered_host_decoys_count,
|
|
154
|
+
"assembled_contigs": len(contigs),
|
|
155
|
+
}
|
|
156
|
+
summary_json.write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
if __name__ == "__main__":
|
|
163
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Evidence-Preserving Host Read Partitioning (`viro_drift.host_partition`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
from typing import Dict, Iterable, List, Optional, Set, Tuple
|
|
7
|
+
|
|
8
|
+
_COMP = str.maketrans("ACGTacgtNn", "TGCAtgcaNn")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def revcomp(seq: str) -> str:
|
|
12
|
+
return seq.translate(_COMP)[::-1]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def canonical_kmer(kmer: str) -> str:
|
|
16
|
+
rc = revcomp(kmer)
|
|
17
|
+
return kmer if kmer <= rc else rc
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build_host_kmer_index(host_sequences: Iterable[str], k: int = 21) -> Set[str]:
|
|
21
|
+
"""Index canonical nucleotide k-mers from host reference sequences."""
|
|
22
|
+
index: Set[str] = set()
|
|
23
|
+
for seq in host_sequences:
|
|
24
|
+
s = seq.upper()
|
|
25
|
+
n = len(s)
|
|
26
|
+
for i in range(0, n - k + 1):
|
|
27
|
+
sub = s[i : i + k]
|
|
28
|
+
if "N" not in sub:
|
|
29
|
+
index.add(canonical_kmer(sub))
|
|
30
|
+
return index
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _host_kmer_hit_profile(seq: str, host_kmers: Set[str], k: int = 21) -> Tuple[float, bool, bool]:
|
|
34
|
+
"""Return (fraction_host_kmers, has_host_segment_20bp, has_nonhost_segment_20bp)."""
|
|
35
|
+
s = seq.upper()
|
|
36
|
+
if len(s) < k or not host_kmers:
|
|
37
|
+
return 0.0, False, len(s) >= 20
|
|
38
|
+
|
|
39
|
+
total = len(s) - k + 1
|
|
40
|
+
hits = [
|
|
41
|
+
1 if ("N" not in s[i : i + k] and canonical_kmer(s[i : i + k]) in host_kmers) else 0
|
|
42
|
+
for i in range(total)
|
|
43
|
+
]
|
|
44
|
+
frac = sum(hits) / float(total)
|
|
45
|
+
|
|
46
|
+
# Check if read is chimeric: contains at least one host k-mer (>=21bp) AND at least 20bp non-host stretch
|
|
47
|
+
has_host = any(h == 1 for h in hits)
|
|
48
|
+
# Count contiguous zero run of length >= 20 - k + 1 (Wait: if hits[i]==0 for m consecutive positions,
|
|
49
|
+
# the uncovered span is m + k - 1 bp; even 2 consecutive non-host 21-mers without overlap means >=22bp non-host)
|
|
50
|
+
zero_run = 0
|
|
51
|
+
max_zero_run = 0
|
|
52
|
+
for h in hits:
|
|
53
|
+
if h == 0:
|
|
54
|
+
zero_run += 1
|
|
55
|
+
if zero_run > max_zero_run:
|
|
56
|
+
max_zero_run = zero_run
|
|
57
|
+
else:
|
|
58
|
+
zero_run = 0
|
|
59
|
+
has_nonhost_20bp = max_zero_run >= k # >= k consecutive non-host k-mer starts guarantees >= 21bp non-host free of host k-mer
|
|
60
|
+
return frac, has_host, has_nonhost_20bp
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclasses.dataclass
|
|
64
|
+
class PartitionedReads:
|
|
65
|
+
"""Three-stream evidence-preserving read partition output."""
|
|
66
|
+
|
|
67
|
+
host_concordant: List[Tuple[str, str, Optional[str]]]
|
|
68
|
+
host_spanning_ambiguous: List[Tuple[str, str, Optional[str]]]
|
|
69
|
+
viral_candidate: List[Tuple[str, str, Optional[str]]]
|
|
70
|
+
|
|
71
|
+
def summary_counts(self) -> Dict[str, int]:
|
|
72
|
+
return {
|
|
73
|
+
"host_concordant_pairs": len(self.host_concordant),
|
|
74
|
+
"host_spanning_ambiguous_pairs": len(self.host_spanning_ambiguous),
|
|
75
|
+
"viral_candidate_pairs": len(self.viral_candidate),
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def partition_host_reads(
|
|
80
|
+
read_pairs: Iterable[Tuple[str, str, Optional[str]]],
|
|
81
|
+
host_kmers: Set[str],
|
|
82
|
+
k: int = 21,
|
|
83
|
+
concordant_threshold: float = 0.70,
|
|
84
|
+
) -> PartitionedReads:
|
|
85
|
+
"""Partition paired or single-end reads into 3 mutually exclusive evidence streams.
|
|
86
|
+
|
|
87
|
+
1. host_concordant: Both mates align to host (>= concordant_threshold k-mer identity) without >=21bp non-host tails.
|
|
88
|
+
2. host_spanning_ambiguous: Discordant mate pairs (one host, one non-host) OR split chimeric reads.
|
|
89
|
+
3. viral_candidate: Unmapped non-host reads forwarded to 6-frame viral baiting.
|
|
90
|
+
"""
|
|
91
|
+
concordant: List[Tuple[str, str, Optional[str]]] = []
|
|
92
|
+
ambiguous: List[Tuple[str, str, Optional[str]]] = []
|
|
93
|
+
viral: List[Tuple[str, str, Optional[str]]] = []
|
|
94
|
+
|
|
95
|
+
for read_id, r1, r2 in read_pairs:
|
|
96
|
+
if not host_kmers:
|
|
97
|
+
viral.append((read_id, r1, r2))
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
f1, h1, nh1 = _host_kmer_hit_profile(r1, host_kmers, k=k)
|
|
101
|
+
if r2 is not None:
|
|
102
|
+
f2, h2, nh2 = _host_kmer_hit_profile(r2, host_kmers, k=k)
|
|
103
|
+
r1_pure_host = f1 >= concordant_threshold and not (h1 and nh1)
|
|
104
|
+
r2_pure_host = f2 >= concordant_threshold and not (h2 and nh2)
|
|
105
|
+
r1_pure_nonhost = not h1
|
|
106
|
+
r2_pure_nonhost = not h2
|
|
107
|
+
|
|
108
|
+
if r1_pure_host and r2_pure_host:
|
|
109
|
+
concordant.append((read_id, r1, r2))
|
|
110
|
+
elif r1_pure_nonhost and r2_pure_nonhost:
|
|
111
|
+
viral.append((read_id, r1, r2))
|
|
112
|
+
else:
|
|
113
|
+
ambiguous.append((read_id, r1, r2))
|
|
114
|
+
else:
|
|
115
|
+
if f1 >= concordant_threshold and not (h1 and nh1):
|
|
116
|
+
concordant.append((read_id, r1, None))
|
|
117
|
+
elif not h1:
|
|
118
|
+
viral.append((read_id, r1, None))
|
|
119
|
+
else:
|
|
120
|
+
ambiguous.append((read_id, r1, None))
|
|
121
|
+
|
|
122
|
+
return PartitionedReads(
|
|
123
|
+
host_concordant=concordant,
|
|
124
|
+
host_spanning_ambiguous=ambiguous,
|
|
125
|
+
viral_candidate=viral,
|
|
126
|
+
)
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Two-Phase Cycle-Safe Local De Bruijn Micro-Assembler (`viro_drift.micro_assembler`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import collections
|
|
6
|
+
import dataclasses
|
|
7
|
+
from typing import Dict, Iterable, List, Optional, Set, Tuple
|
|
8
|
+
|
|
9
|
+
from viro_drift.host_partition import revcomp
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclasses.dataclass
|
|
13
|
+
class AssembledContig:
|
|
14
|
+
"""Locally assembled viral candidate contig."""
|
|
15
|
+
|
|
16
|
+
contig_id: str
|
|
17
|
+
sequence: str
|
|
18
|
+
mean_kmer_depth: float
|
|
19
|
+
is_circular_cycle: bool
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _choose_kmer_cascade(reads: List[str]) -> Tuple[int, ...]:
|
|
23
|
+
if not reads:
|
|
24
|
+
return (21, 33, 55)
|
|
25
|
+
min_len = min(len(r) for r in reads)
|
|
26
|
+
if min_len < 60:
|
|
27
|
+
return tuple(k for k in (15, 21, 31) if k < min_len) or (11,)
|
|
28
|
+
return tuple(k for k in (21, 33, 55) if k < min_len) or (21,)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _build_dbg_and_extract_unitigs(
|
|
32
|
+
reads: List[str],
|
|
33
|
+
k: int,
|
|
34
|
+
min_edge_cov: int = 1,
|
|
35
|
+
) -> List[Tuple[str, float, bool]]:
|
|
36
|
+
"""Build directed de Bruijn graph and run Two-Phase Cycle-Safe Traversal (`P0-VD-3`).
|
|
37
|
+
|
|
38
|
+
Phase 1: Walk all non-branching paths starting from nodes with in_deg != 1 or out_deg != 1.
|
|
39
|
+
Phase 2: Walk remaining unvisited closed circular cycles starting from lexicographically
|
|
40
|
+
smallest k-mer node, traversing each cycle edge once and breaking cleanly.
|
|
41
|
+
"""
|
|
42
|
+
edge_counts: Dict[Tuple[str, str], int] = collections.Counter()
|
|
43
|
+
for r in reads:
|
|
44
|
+
s = r.upper()
|
|
45
|
+
if len(s) < k + 1:
|
|
46
|
+
continue
|
|
47
|
+
for i in range(0, len(s) - k):
|
|
48
|
+
sub = s[i : i + k + 1]
|
|
49
|
+
if "N" not in sub:
|
|
50
|
+
u, v = sub[:k], sub[1:]
|
|
51
|
+
edge_counts[(u, v)] += 1
|
|
52
|
+
|
|
53
|
+
# Filter ultra-low singleton sequencing error tips if graph has deep coverage
|
|
54
|
+
max_cov = max(edge_counts.values(), default=0)
|
|
55
|
+
eff_min_cov = max(min_edge_cov, 2 if max_cov >= 8 else 1)
|
|
56
|
+
active_edges = {e: c for e, c in edge_counts.items() if c >= eff_min_cov}
|
|
57
|
+
if not active_edges and edge_counts:
|
|
58
|
+
active_edges = dict(edge_counts)
|
|
59
|
+
|
|
60
|
+
out_adj: Dict[str, List[str]] = collections.defaultdict(list)
|
|
61
|
+
in_deg: Dict[str, int] = collections.Counter()
|
|
62
|
+
nodes: Set[str] = set()
|
|
63
|
+
|
|
64
|
+
for (u, v), _cov in sorted(active_edges.items()):
|
|
65
|
+
out_adj[u].append(v)
|
|
66
|
+
in_deg[v] += 1
|
|
67
|
+
nodes.add(u)
|
|
68
|
+
nodes.add(v)
|
|
69
|
+
|
|
70
|
+
# Sort outgoing edges by descending coverage for greedy primary path selection at bubbles
|
|
71
|
+
for u in out_adj:
|
|
72
|
+
out_adj[u].sort(key=lambda v: (-active_edges[(u, v)], v))
|
|
73
|
+
|
|
74
|
+
# Prune short dead-end tips (< 2*k bp) branching off higher-coverage nodes
|
|
75
|
+
for u in list(out_adj.keys()):
|
|
76
|
+
if len(out_adj[u]) > 1:
|
|
77
|
+
best_v = out_adj[u][0]
|
|
78
|
+
best_cov = active_edges[(u, best_v)]
|
|
79
|
+
kept = [best_v]
|
|
80
|
+
for alt_v in out_adj[u][1:]:
|
|
81
|
+
if active_edges[(u, alt_v)] * 4 >= best_cov or len(out_adj.get(alt_v, [])) > 0:
|
|
82
|
+
kept.append(alt_v)
|
|
83
|
+
else:
|
|
84
|
+
in_deg[alt_v] -= 1
|
|
85
|
+
active_edges.pop((u, alt_v), None)
|
|
86
|
+
out_adj[u] = kept
|
|
87
|
+
|
|
88
|
+
visited_edges: Set[Tuple[str, str]] = set()
|
|
89
|
+
contigs: List[Tuple[str, float, bool]] = []
|
|
90
|
+
|
|
91
|
+
# Phase 1: Start walks from all non-1-in-1-out nodes
|
|
92
|
+
start_nodes = sorted(
|
|
93
|
+
n for n in nodes if (in_deg[n] != 1 or len(out_adj.get(n, [])) != 1) and len(out_adj.get(n, [])) > 0
|
|
94
|
+
)
|
|
95
|
+
for start in start_nodes:
|
|
96
|
+
for nxt in out_adj[start]:
|
|
97
|
+
if (start, nxt) in visited_edges:
|
|
98
|
+
continue
|
|
99
|
+
seq_chars = [start, nxt[-1]]
|
|
100
|
+
covs = [active_edges[(start, nxt)]]
|
|
101
|
+
visited_edges.add((start, nxt))
|
|
102
|
+
curr = nxt
|
|
103
|
+
while in_deg[curr] == 1 and len(out_adj.get(curr, [])) == 1:
|
|
104
|
+
w = out_adj[curr][0]
|
|
105
|
+
if (curr, w) in visited_edges:
|
|
106
|
+
break
|
|
107
|
+
visited_edges.add((curr, w))
|
|
108
|
+
seq_chars.append(w[-1])
|
|
109
|
+
covs.append(active_edges[(curr, w)])
|
|
110
|
+
curr = w
|
|
111
|
+
contigs.append(("".join(seq_chars), sum(covs) / float(len(covs)), False))
|
|
112
|
+
|
|
113
|
+
# Phase 2: Pure closed circular cycles (`in_deg == 1` and `out_deg == 1` everywhere)
|
|
114
|
+
remaining_edges = sorted(e for e in active_edges if e not in visited_edges)
|
|
115
|
+
for u0, _v0 in remaining_edges:
|
|
116
|
+
if (u0, out_adj[u0][0]) in visited_edges:
|
|
117
|
+
continue
|
|
118
|
+
# Find lexicographically smallest node in this cycle for deterministic canonical start
|
|
119
|
+
cycle_nodes = [u0]
|
|
120
|
+
curr = out_adj[u0][0]
|
|
121
|
+
safety = 0
|
|
122
|
+
while curr != u0 and curr not in cycle_nodes and len(out_adj.get(curr, [])) > 0 and safety <= len(active_edges):
|
|
123
|
+
cycle_nodes.append(curr)
|
|
124
|
+
curr = out_adj[curr][0]
|
|
125
|
+
safety += 1
|
|
126
|
+
start = min(cycle_nodes)
|
|
127
|
+
curr = start
|
|
128
|
+
seq_chars = [start]
|
|
129
|
+
covs = []
|
|
130
|
+
is_closed = False
|
|
131
|
+
while len(out_adj.get(curr, [])) > 0:
|
|
132
|
+
nxt = out_adj[curr][0]
|
|
133
|
+
if (curr, nxt) in visited_edges:
|
|
134
|
+
is_closed = (nxt == start or curr == start)
|
|
135
|
+
break
|
|
136
|
+
visited_edges.add((curr, nxt))
|
|
137
|
+
covs.append(active_edges[(curr, nxt)])
|
|
138
|
+
if nxt == start:
|
|
139
|
+
# Returning to start completes exact 1.0x circular k-mer loop (plus k-1 overlap if needed)
|
|
140
|
+
is_closed = True
|
|
141
|
+
break
|
|
142
|
+
seq_chars.append(nxt[-1])
|
|
143
|
+
curr = nxt
|
|
144
|
+
if covs:
|
|
145
|
+
contigs.append(("".join(seq_chars), sum(covs) / float(len(covs)), is_closed))
|
|
146
|
+
|
|
147
|
+
return contigs
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _deduplicate_rc_contigs(
|
|
151
|
+
raw_contigs: List[Tuple[str, float, bool]],
|
|
152
|
+
min_len: int,
|
|
153
|
+
k: int = 21,
|
|
154
|
+
) -> List[Tuple[str, float, bool]]:
|
|
155
|
+
"""Collapse reverse-complement twin contigs (including rotated circular cycles)."""
|
|
156
|
+
filtered = [c for c in raw_contigs if len(c[0]) >= min_len]
|
|
157
|
+
filtered.sort(key=lambda x: (-len(x[0]), -x[1], x[0]))
|
|
158
|
+
kept: List[Tuple[str, float, bool]] = []
|
|
159
|
+
seen_linear: List[str] = []
|
|
160
|
+
seen_circular_doubled: List[str] = []
|
|
161
|
+
for seq, cov, is_circ in filtered:
|
|
162
|
+
rc = revcomp(seq)
|
|
163
|
+
if any(seq in s or rc in s for s in seen_linear):
|
|
164
|
+
continue
|
|
165
|
+
if is_circ and len(seq) > k:
|
|
166
|
+
core = seq[: -(k - 1)] if seq[: k - 1] == seq[-(k - 1) :] else seq
|
|
167
|
+
rc_core = revcomp(core)
|
|
168
|
+
if any(core in dc or rc_core in dc for dc in seen_circular_doubled):
|
|
169
|
+
continue
|
|
170
|
+
seen_circular_doubled.append(core + core)
|
|
171
|
+
kept.append((seq, cov, is_circ))
|
|
172
|
+
seen_linear.append(seq)
|
|
173
|
+
return kept
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def assemble_viral_contigs(
|
|
177
|
+
recruited_pairs: Iterable[Tuple[str, str, Optional[str]]],
|
|
178
|
+
k_values: Optional[Tuple[int, ...]] = None,
|
|
179
|
+
min_contig_len: int = 120,
|
|
180
|
+
) -> List[AssembledContig]:
|
|
181
|
+
"""Assemble isolated viral reads across an adaptive odd-k cascade and select optimal contiguity."""
|
|
182
|
+
strand_expanded_reads: List[str] = []
|
|
183
|
+
raw_reads: List[str] = []
|
|
184
|
+
for _rid, r1, r2 in recruited_pairs:
|
|
185
|
+
raw_reads.append(r1)
|
|
186
|
+
strand_expanded_reads.append(r1.upper())
|
|
187
|
+
strand_expanded_reads.append(revcomp(r1.upper()))
|
|
188
|
+
if r2:
|
|
189
|
+
raw_reads.append(r2)
|
|
190
|
+
strand_expanded_reads.append(r2.upper())
|
|
191
|
+
strand_expanded_reads.append(revcomp(r2.upper()))
|
|
192
|
+
|
|
193
|
+
if not raw_reads:
|
|
194
|
+
return []
|
|
195
|
+
|
|
196
|
+
cascade = k_values or _choose_kmer_cascade(raw_reads)
|
|
197
|
+
best_unitigs: List[Tuple[str, float, bool]] = []
|
|
198
|
+
best_max_len = -1
|
|
199
|
+
|
|
200
|
+
for k in cascade:
|
|
201
|
+
if k % 2 == 0:
|
|
202
|
+
k += 1 # Enforce odd k to prevent palindromic self-complement k-mers (`P0-VD-3`)
|
|
203
|
+
unitigs = _build_dbg_and_extract_unitigs(strand_expanded_reads, k=k)
|
|
204
|
+
dedup = _deduplicate_rc_contigs(unitigs, min_len=min(min_contig_len, max(len(r) for r in raw_reads)), k=k)
|
|
205
|
+
top_len = max((len(u[0]) for u in dedup), default=0)
|
|
206
|
+
if top_len > best_max_len:
|
|
207
|
+
best_max_len = top_len
|
|
208
|
+
best_unitigs = dedup
|
|
209
|
+
|
|
210
|
+
results: List[AssembledContig] = []
|
|
211
|
+
for idx, (seq, cov, is_circ) in enumerate(best_unitigs, start=1):
|
|
212
|
+
results.append(
|
|
213
|
+
AssembledContig(
|
|
214
|
+
contig_id=f"viro_drift_contig_{idx:03d}",
|
|
215
|
+
sequence=seq,
|
|
216
|
+
mean_kmer_depth=round(cov / 2.0, 2),
|
|
217
|
+
is_circular_cycle=is_circ,
|
|
218
|
+
)
|
|
219
|
+
)
|
|
220
|
+
return results
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Strand-Aware Canonical K-mer Iterative Paired Read Recruitment (`viro_drift.recruitment`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
from typing import Dict, Iterable, List, Optional, Set, Tuple
|
|
7
|
+
|
|
8
|
+
from viro_drift.host_partition import canonical_kmer
|
|
9
|
+
from viro_drift.translation_bait import shannon_entropy_nt
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclasses.dataclass
|
|
13
|
+
class RecruitmentResult:
|
|
14
|
+
"""Summary and recruited read pairs from iterative recruitment."""
|
|
15
|
+
|
|
16
|
+
recruited_pairs: List[Tuple[str, str, Optional[str]]]
|
|
17
|
+
rounds_executed: int
|
|
18
|
+
stop_reason: str
|
|
19
|
+
per_round_counts: List[int]
|
|
20
|
+
filtered_host_decoys_count: int
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _extract_terminal_canonical_kmers(
|
|
24
|
+
seq: str,
|
|
25
|
+
k: int,
|
|
26
|
+
host_mask: Set[str],
|
|
27
|
+
min_entropy: float = 1.30,
|
|
28
|
+
end_window: int = 35,
|
|
29
|
+
) -> Set[str]:
|
|
30
|
+
"""Extract canonical k-mers from 5' and 3' read ends (`P0-VD-3`)."""
|
|
31
|
+
s = seq.upper()
|
|
32
|
+
if len(s) < k:
|
|
33
|
+
return set()
|
|
34
|
+
out: Set[str] = set()
|
|
35
|
+
w = min(len(s), max(k, end_window))
|
|
36
|
+
regions = [s[:w], s[len(s) - w :]]
|
|
37
|
+
for reg in regions:
|
|
38
|
+
for i in range(0, len(reg) - k + 1):
|
|
39
|
+
sub = reg[i : i + k]
|
|
40
|
+
if "N" in sub:
|
|
41
|
+
continue
|
|
42
|
+
if shannon_entropy_nt(sub) < min_entropy:
|
|
43
|
+
continue
|
|
44
|
+
ck = canonical_kmer(sub)
|
|
45
|
+
if ck not in host_mask:
|
|
46
|
+
out.add(ck)
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _all_canonical_kmers(seq: str, k: int) -> Set[str]:
|
|
51
|
+
s = seq.upper()
|
|
52
|
+
if len(s) < k:
|
|
53
|
+
return set()
|
|
54
|
+
return {
|
|
55
|
+
canonical_kmer(s[i : i + k])
|
|
56
|
+
for i in range(0, len(s) - k + 1)
|
|
57
|
+
if "N" not in s[i : i + k]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _estimate_frontier_branching(seqs: Iterable[str], k: int = 21) -> float:
|
|
62
|
+
"""Compute mean out-degree on k-mer prefix -> suffix transitions to guard repeat runaway."""
|
|
63
|
+
adj: Dict[str, Set[str]] = {}
|
|
64
|
+
km1 = k - 1
|
|
65
|
+
if km1 < 5:
|
|
66
|
+
return 1.0
|
|
67
|
+
for seq in seqs:
|
|
68
|
+
s = seq.upper()
|
|
69
|
+
for i in range(0, len(s) - k + 1):
|
|
70
|
+
sub = s[i : i + k]
|
|
71
|
+
if "N" not in sub:
|
|
72
|
+
adj.setdefault(sub[:km1], set()).add(sub[1:])
|
|
73
|
+
if not adj:
|
|
74
|
+
return 0.0
|
|
75
|
+
return sum(len(v) for v in adj.values()) / float(len(adj))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def iterative_recruit_reads(
|
|
79
|
+
all_candidate_pairs: Iterable[Tuple[str, str, Optional[str]]],
|
|
80
|
+
initial_seed_ids: Set[str],
|
|
81
|
+
host_kmer_mask: Optional[Set[str]] = None,
|
|
82
|
+
k_nt: int = 21,
|
|
83
|
+
max_rounds: int = 5,
|
|
84
|
+
min_growth_rate: float = 0.01,
|
|
85
|
+
max_branching_degree: float = 4.0,
|
|
86
|
+
) -> RecruitmentResult:
|
|
87
|
+
"""Iteratively recruit paired mates and strand-aware overlapping reads (`P0-VD-3`)."""
|
|
88
|
+
pairs_map: Dict[str, Tuple[str, str, Optional[str]]] = {
|
|
89
|
+
rid: (rid, r1, r2) for rid, r1, r2 in all_candidate_pairs
|
|
90
|
+
}
|
|
91
|
+
host_mask = host_kmer_mask or set()
|
|
92
|
+
|
|
93
|
+
if not initial_seed_ids:
|
|
94
|
+
return RecruitmentResult(
|
|
95
|
+
recruited_pairs=[],
|
|
96
|
+
rounds_executed=0,
|
|
97
|
+
stop_reason="NO_SEED_READS",
|
|
98
|
+
per_round_counts=[],
|
|
99
|
+
filtered_host_decoys_count=0,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# Filter out any initial seeds that collide with host mask (>20% host k-mers)
|
|
103
|
+
recruited: Set[str] = set()
|
|
104
|
+
filtered_decoys = 0
|
|
105
|
+
for rid in initial_seed_ids:
|
|
106
|
+
if rid not in pairs_map:
|
|
107
|
+
continue
|
|
108
|
+
_, r1, r2 = pairs_map[rid]
|
|
109
|
+
c_kmers = _all_canonical_kmers(r1, k_nt) | (_all_canonical_kmers(r2, k_nt) if r2 else set())
|
|
110
|
+
if host_mask and c_kmers and (len(c_kmers & host_mask) / float(len(c_kmers))) > 0.20:
|
|
111
|
+
filtered_decoys += 1
|
|
112
|
+
continue
|
|
113
|
+
recruited.add(rid)
|
|
114
|
+
|
|
115
|
+
if not recruited:
|
|
116
|
+
return RecruitmentResult(
|
|
117
|
+
recruited_pairs=[],
|
|
118
|
+
rounds_executed=0,
|
|
119
|
+
stop_reason="ALL_SEEDS_FILTERED_AS_HOST_DECOYS",
|
|
120
|
+
per_round_counts=[],
|
|
121
|
+
filtered_host_decoys_count=filtered_decoys,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# Pre-index unrecruited candidate reads by canonical k-mers for fast lookup
|
|
125
|
+
kmer_to_rids: Dict[str, Set[str]] = {}
|
|
126
|
+
read_host_flagged: Set[str] = set()
|
|
127
|
+
counted_decoy_rids: Set[str] = set()
|
|
128
|
+
for rid, (_, r1, r2) in pairs_map.items():
|
|
129
|
+
cks = _all_canonical_kmers(r1, k_nt)
|
|
130
|
+
if r2:
|
|
131
|
+
cks |= _all_canonical_kmers(r2, k_nt)
|
|
132
|
+
if host_mask and cks and (len(cks & host_mask) / float(len(cks))) > 0.20:
|
|
133
|
+
read_host_flagged.add(rid)
|
|
134
|
+
for ck in cks:
|
|
135
|
+
kmer_to_rids.setdefault(ck, set()).add(rid)
|
|
136
|
+
|
|
137
|
+
frontier: Set[str] = set(recruited)
|
|
138
|
+
per_round_counts: List[int] = [len(recruited)]
|
|
139
|
+
stop_reason = "MAX_ROUNDS_REACHED"
|
|
140
|
+
rounds_done = 0
|
|
141
|
+
|
|
142
|
+
for _round_idx in range(1, max_rounds + 1):
|
|
143
|
+
rounds_done = _round_idx
|
|
144
|
+
frontier_seqs: List[str] = []
|
|
145
|
+
bait_kmers: Set[str] = set()
|
|
146
|
+
for rid in frontier:
|
|
147
|
+
_, r1, r2 = pairs_map[rid]
|
|
148
|
+
frontier_seqs.append(r1)
|
|
149
|
+
bait_kmers |= _extract_terminal_canonical_kmers(r1, k_nt, host_mask)
|
|
150
|
+
if r2:
|
|
151
|
+
frontier_seqs.append(r2)
|
|
152
|
+
bait_kmers |= _extract_terminal_canonical_kmers(r2, k_nt, host_mask)
|
|
153
|
+
|
|
154
|
+
if _estimate_frontier_branching(frontier_seqs, k=min(k_nt, 17)) > max_branching_degree:
|
|
155
|
+
stop_reason = "BRANCHING_CEILING_EXCEEDED"
|
|
156
|
+
break
|
|
157
|
+
|
|
158
|
+
newly_added: Set[str] = set()
|
|
159
|
+
for bk in bait_kmers:
|
|
160
|
+
for cand_rid in kmer_to_rids.get(bk, ()):
|
|
161
|
+
if cand_rid in recruited:
|
|
162
|
+
continue
|
|
163
|
+
if cand_rid in read_host_flagged:
|
|
164
|
+
if cand_rid not in counted_decoy_rids:
|
|
165
|
+
counted_decoy_rids.add(cand_rid)
|
|
166
|
+
filtered_decoys += 1
|
|
167
|
+
continue
|
|
168
|
+
newly_added.add(cand_rid)
|
|
169
|
+
|
|
170
|
+
prev_count = len(recruited)
|
|
171
|
+
recruited |= newly_added
|
|
172
|
+
per_round_counts.append(len(recruited))
|
|
173
|
+
growth = len(newly_added) / float(max(1, prev_count))
|
|
174
|
+
|
|
175
|
+
if growth < min_growth_rate:
|
|
176
|
+
stop_reason = "GROWTH_PLATEAU_REACHED"
|
|
177
|
+
break
|
|
178
|
+
frontier = newly_added
|
|
179
|
+
|
|
180
|
+
ordered_pairs = [pairs_map[rid] for rid in sorted(recruited)]
|
|
181
|
+
return RecruitmentResult(
|
|
182
|
+
recruited_pairs=ordered_pairs,
|
|
183
|
+
rounds_executed=rounds_done,
|
|
184
|
+
stop_reason=stop_reason,
|
|
185
|
+
per_round_counts=per_round_counts,
|
|
186
|
+
filtered_host_decoys_count=filtered_decoys,
|
|
187
|
+
)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""6-Frame Translated Catalytic Seed Baiting (`viro_drift.translation_bait`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import pathlib
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
from typing import Dict, Iterable, List, Optional, Set, Tuple
|
|
10
|
+
|
|
11
|
+
from Bio.Seq import Seq
|
|
12
|
+
|
|
13
|
+
from viro_drift.host_partition import revcomp
|
|
14
|
+
|
|
15
|
+
# 11-Class Chemical Equivalence Reduced Amino Acid Alphabet (`P0-VD-2`)
|
|
16
|
+
_AA_REDUCED_GROUPS = {
|
|
17
|
+
"I": "L", "L": "L", "M": "L", "V": "L",
|
|
18
|
+
"F": "F", "Y": "F", "W": "F",
|
|
19
|
+
"K": "K", "R": "K",
|
|
20
|
+
"D": "D", "E": "D",
|
|
21
|
+
"S": "S", "T": "S",
|
|
22
|
+
"N": "N", "Q": "N",
|
|
23
|
+
"A": "A",
|
|
24
|
+
"C": "C",
|
|
25
|
+
"G": "G",
|
|
26
|
+
"H": "H",
|
|
27
|
+
"P": "P",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def shannon_entropy_nt(window: str) -> float:
|
|
32
|
+
"""Compute nucleotide Shannon entropy in bits over {A, C, G, T}."""
|
|
33
|
+
counts = [0, 0, 0, 0]
|
|
34
|
+
total = 0
|
|
35
|
+
for ch in window.upper():
|
|
36
|
+
if ch == "A":
|
|
37
|
+
counts[0] += 1
|
|
38
|
+
total += 1
|
|
39
|
+
elif ch == "C":
|
|
40
|
+
counts[1] += 1
|
|
41
|
+
total += 1
|
|
42
|
+
elif ch == "G":
|
|
43
|
+
counts[2] += 1
|
|
44
|
+
total += 1
|
|
45
|
+
elif ch == "T":
|
|
46
|
+
counts[3] += 1
|
|
47
|
+
total += 1
|
|
48
|
+
if total == 0:
|
|
49
|
+
return 0.0
|
|
50
|
+
ent = 0.0
|
|
51
|
+
for c in counts:
|
|
52
|
+
if c > 0:
|
|
53
|
+
p = c / float(total)
|
|
54
|
+
ent -= p * math.log2(p)
|
|
55
|
+
return ent
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def mask_low_complexity_nt(seq: str, window_size: int = 24, min_entropy_bits: float = 1.20) -> str:
|
|
59
|
+
"""Mask low-complexity sliding windows (H < 1.20 bits) to 'N' (`P0-VD-1`)."""
|
|
60
|
+
s = seq.upper()
|
|
61
|
+
n = len(s)
|
|
62
|
+
if n == 0:
|
|
63
|
+
return ""
|
|
64
|
+
if n < window_size:
|
|
65
|
+
return "N" * n if shannon_entropy_nt(s) < min_entropy_bits else s
|
|
66
|
+
|
|
67
|
+
mask = [False] * n
|
|
68
|
+
for i in range(0, n - window_size + 1):
|
|
69
|
+
if shannon_entropy_nt(s[i : i + window_size]) < min_entropy_bits:
|
|
70
|
+
for j in range(i, i + window_size):
|
|
71
|
+
mask[j] = True
|
|
72
|
+
return "".join("N" if mask[i] else s[i] for i in range(n))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def translate_6frames(seq: str) -> List[Tuple[str, str]]:
|
|
76
|
+
"""Translate nucleotide sequence across all 6 reading frames (+0,+1,+2,-0,-1,-2)."""
|
|
77
|
+
s = seq.upper().replace("U", "T")
|
|
78
|
+
rc = revcomp(s)
|
|
79
|
+
frames: List[Tuple[str, str]] = []
|
|
80
|
+
for strand_label, template in (("+", s), ("-", rc)):
|
|
81
|
+
for offset in (0, 1, 2):
|
|
82
|
+
sub = template[offset:]
|
|
83
|
+
trim_len = (len(sub) // 3) * 3
|
|
84
|
+
if trim_len < 15:
|
|
85
|
+
frames.append((f"{strand_label}{offset}", ""))
|
|
86
|
+
continue
|
|
87
|
+
aa = str(Seq(sub[:trim_len]).translate(table=1))
|
|
88
|
+
frames.append((f"{strand_label}{offset}", aa))
|
|
89
|
+
return frames
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _reduce_peptide(peptide: str) -> str:
|
|
93
|
+
return "".join(_AA_REDUCED_GROUPS.get(ch, "X") for ch in peptide.upper())
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ReducedAlphabetSeedIndex:
|
|
97
|
+
"""Collinear reduced-alphabet and exact hexapeptide viral seed index (`P0-VD-1`, `P0-VD-2`)."""
|
|
98
|
+
|
|
99
|
+
def __init__(self, seeds: Dict[str, str], k_reduced: int = 5, k_exact: int = 6) -> None:
|
|
100
|
+
self.k_reduced = k_reduced
|
|
101
|
+
self.k_exact = k_exact
|
|
102
|
+
# reduced_kmer -> list of (seed_id, pos)
|
|
103
|
+
self.reduced_map: Dict[str, List[Tuple[str, int]]] = {}
|
|
104
|
+
# exact_kmer -> set of seed_ids
|
|
105
|
+
self.exact_map: Dict[str, Set[str]] = {}
|
|
106
|
+
|
|
107
|
+
for seed_id, aa_seq in seeds.items():
|
|
108
|
+
clean_aa = aa_seq.upper().strip()
|
|
109
|
+
for segment in self._valid_segments(clean_aa):
|
|
110
|
+
seg_seq, seg_offset = segment
|
|
111
|
+
for i in range(0, len(seg_seq) - k_exact + 1):
|
|
112
|
+
ek = seg_seq[i : i + k_exact]
|
|
113
|
+
self.exact_map.setdefault(ek, set()).add(seed_id)
|
|
114
|
+
red_seg = _reduce_peptide(seg_seq)
|
|
115
|
+
for i in range(0, len(red_seg) - k_reduced + 1):
|
|
116
|
+
rk = red_seg[i : i + k_reduced]
|
|
117
|
+
if "X" not in rk:
|
|
118
|
+
self.reduced_map.setdefault(rk, []).append((seed_id, seg_offset + i))
|
|
119
|
+
|
|
120
|
+
@staticmethod
|
|
121
|
+
def _valid_segments(aa_seq: str) -> List[Tuple[str, int]]:
|
|
122
|
+
"""Split translated polypeptide on '*' and 'X' so masked/stop residues never match (`P0-VD-1`)."""
|
|
123
|
+
segments: List[Tuple[str, int]] = []
|
|
124
|
+
start = 0
|
|
125
|
+
n = len(aa_seq)
|
|
126
|
+
i = 0
|
|
127
|
+
while i < n:
|
|
128
|
+
if aa_seq[i] in ("*", "X"):
|
|
129
|
+
if i > start:
|
|
130
|
+
segments.append((aa_seq[start:i], start))
|
|
131
|
+
start = i + 1
|
|
132
|
+
i += 1
|
|
133
|
+
if n > start:
|
|
134
|
+
segments.append((aa_seq[start:n], start))
|
|
135
|
+
return segments
|
|
136
|
+
|
|
137
|
+
def match_read(self, nt_seq: str) -> Optional[Tuple[str, str]]:
|
|
138
|
+
"""Return (matched_seed_id, frame_label) if read matches any seed with collinear consistency."""
|
|
139
|
+
masked = mask_low_complexity_nt(nt_seq)
|
|
140
|
+
if masked.count("N") == len(masked):
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
kr = self.k_reduced
|
|
144
|
+
ke = self.k_exact
|
|
145
|
+
|
|
146
|
+
for frame_label, aa_full in translate_6frames(masked):
|
|
147
|
+
if not aa_full:
|
|
148
|
+
continue
|
|
149
|
+
for seg_seq, seg_offset in self._valid_segments(aa_full):
|
|
150
|
+
if len(seg_seq) < kr:
|
|
151
|
+
continue
|
|
152
|
+
# 1. Exact contiguous match >= 6 aa (`P0-VD-2` Criterion 1)
|
|
153
|
+
for i in range(0, len(seg_seq) - ke + 1):
|
|
154
|
+
ek = seg_seq[i : i + ke]
|
|
155
|
+
if ek in self.exact_map:
|
|
156
|
+
return next(iter(self.exact_map[ek])), frame_label
|
|
157
|
+
|
|
158
|
+
# 2. Collinear reduced-alphabet double 5-mer match (`P0-VD-2` Criterion 2)
|
|
159
|
+
red_seg = _reduce_peptide(seg_seq)
|
|
160
|
+
hits_by_seed: Dict[str, List[Tuple[int, int]]] = {}
|
|
161
|
+
for i in range(0, len(red_seg) - kr + 1):
|
|
162
|
+
rk = red_seg[i : i + kr]
|
|
163
|
+
if "X" in rk or rk not in self.reduced_map:
|
|
164
|
+
continue
|
|
165
|
+
q_pos = seg_offset + i
|
|
166
|
+
for seed_id, p_pos in self.reduced_map[rk]:
|
|
167
|
+
prev_list = hits_by_seed.setdefault(seed_id, [])
|
|
168
|
+
for q1, p1 in prev_list:
|
|
169
|
+
if (q_pos - q1) >= kr and abs((q_pos - q1) - (p_pos - p1)) <= 3:
|
|
170
|
+
return seed_id, frame_label
|
|
171
|
+
prev_list.append((q_pos, p_pos))
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def check_external_bait_tool(mode: str) -> str:
|
|
176
|
+
"""Verify external binary availability when diamond/hmmer mode is explicitly requested."""
|
|
177
|
+
bin_name = "diamond" if mode == "diamond" else "hmmsearch"
|
|
178
|
+
exe = shutil.which(bin_name)
|
|
179
|
+
if exe is None:
|
|
180
|
+
raise FileNotFoundError(
|
|
181
|
+
f"Requested external mode '{mode}' requires '{bin_name}' in PATH."
|
|
182
|
+
)
|
|
183
|
+
return exe
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def bait_reads_with_seeds(
|
|
187
|
+
candidate_pairs: Iterable[Tuple[str, str, Optional[str]]],
|
|
188
|
+
seeds: Dict[str, str],
|
|
189
|
+
mode: str = "kmer_seed",
|
|
190
|
+
seeds_path: Optional[pathlib.Path] = None,
|
|
191
|
+
work_dir: Optional[pathlib.Path] = None,
|
|
192
|
+
) -> Tuple[Set[str], Dict[str, str]]:
|
|
193
|
+
"""Bait divergent viral candidate reads in 6-frame protein space.
|
|
194
|
+
|
|
195
|
+
Returns (recruited_read_ids, seed_hit_map).
|
|
196
|
+
"""
|
|
197
|
+
pairs_list = list(candidate_pairs)
|
|
198
|
+
if mode in ("diamond", "hmmer"):
|
|
199
|
+
exe = check_external_bait_tool(mode)
|
|
200
|
+
if work_dir is not None and seeds_path is not None and mode == "diamond" and pairs_list:
|
|
201
|
+
db_prefix = work_dir / "seed_db"
|
|
202
|
+
query_fa = work_dir / "candidates_query.fasta"
|
|
203
|
+
out_tsv = work_dir / "diamond_hits.tsv"
|
|
204
|
+
with query_fa.open("w", encoding="utf-8") as qf:
|
|
205
|
+
for rid, r1, r2 in pairs_list:
|
|
206
|
+
qf.write(f">{rid}/1\n{r1}\n")
|
|
207
|
+
if r2:
|
|
208
|
+
qf.write(f">{rid}/2\n{r2}\n")
|
|
209
|
+
subprocess.run([exe, "makedb", "--in", str(seeds_path), "-d", str(db_prefix), "--quiet"], check=True)
|
|
210
|
+
subprocess.run(
|
|
211
|
+
[
|
|
212
|
+
exe, "blastx", "-d", str(db_prefix), "-q", str(query_fa),
|
|
213
|
+
"-o", str(out_tsv), "--ultra-sensitive", "-e", "1e-4",
|
|
214
|
+
"--outfmt", "6", "qseqid", "sseqid", "evalue", "--quiet",
|
|
215
|
+
],
|
|
216
|
+
check=True,
|
|
217
|
+
)
|
|
218
|
+
recruited: Set[str] = set()
|
|
219
|
+
hit_map: Dict[str, str] = {}
|
|
220
|
+
if out_tsv.exists():
|
|
221
|
+
for line in out_tsv.read_text(encoding="utf-8").splitlines():
|
|
222
|
+
parts = line.split("\t")
|
|
223
|
+
if len(parts) >= 2:
|
|
224
|
+
base_id = parts[0].rsplit("/", 1)[0]
|
|
225
|
+
recruited.add(base_id)
|
|
226
|
+
hit_map[base_id] = parts[1]
|
|
227
|
+
return recruited, hit_map
|
|
228
|
+
|
|
229
|
+
index = ReducedAlphabetSeedIndex(seeds)
|
|
230
|
+
recruited_ids: Set[str] = set()
|
|
231
|
+
seed_hits: Dict[str, str] = {}
|
|
232
|
+
for rid, r1, r2 in pairs_list:
|
|
233
|
+
m1 = index.match_read(r1)
|
|
234
|
+
if m1 is not None:
|
|
235
|
+
recruited_ids.add(rid)
|
|
236
|
+
seed_hits[rid] = m1[0]
|
|
237
|
+
continue
|
|
238
|
+
if r2 is not None:
|
|
239
|
+
m2 = index.match_read(r2)
|
|
240
|
+
if m2 is not None:
|
|
241
|
+
recruited_ids.add(rid)
|
|
242
|
+
seed_hits[rid] = m2[0]
|
|
243
|
+
return recruited_ids, seed_hits
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: viro-drift
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Adaptive divergent viral discovery via 6-frame protein seed baiting and local micro-assembly
|
|
5
|
+
Author-email: "Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute" <shwetabac@gmail.com>
|
|
6
|
+
Maintainer-email: "Dr. Shweta Singh" <shwetabac@gmail.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/molecularplantpathology/Virome-Suite
|
|
9
|
+
Project-URL: Repository, https://github.com/molecularplantpathology/Virome-Suite.git
|
|
10
|
+
Project-URL: Issues, https://github.com/molecularplantpathology/Virome-Suite/issues
|
|
11
|
+
Keywords: virome,metagenomics,virus-discovery,plant-pathology,bioinformatics
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: biopython>=1.81
|
|
16
|
+
Requires-Dist: numpy>=1.24.0
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# viro-drift
|
|
20
|
+
|
|
21
|
+
**Adaptive Divergent Viral Pathogen Discovery via 6-Frame Catalytic Seed Baiting & Local Micro-Assembly**
|
|
22
|
+
|
|
23
|
+
Part of the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
|
|
24
|
+
|
|
25
|
+
## Key Features
|
|
26
|
+
- **Evidence-Preserving Host Read Partitioning:** Separates host-concordant reads, ambiguous host-viral chimeric bridges (preserved for downstream integration checks), and unmapped viral candidates.
|
|
27
|
+
- **Low-Complexity & Homopolymer Shield:** Sliding-window nucleotide Shannon entropy masking ($H < 1.20\text{ bits}$) with strict stop/ambiguous residue exclusion.
|
|
28
|
+
- **6-Frame Collinear Catalytic Baiting:** Recruits divergent viral reads (15%–35% nucleotide divergence) using reduced-alphabet amino acid $k$-mers (`kmer_seed` self-contained engine) or external `DIAMOND blastx` / `HMMER hmmsearch`.
|
|
29
|
+
- **Two-Phase Cycle-Safe Micro-Assembly:** Strand-normalized iterative paired recruitment and local de Bruijn assembly supporting both linear unitigs and closed circular viral rings.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install viro-drift
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Quick Start
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
viro-drift run --r1 unmapped_R1.fasta --r2 unmapped_R2.fasta --seeds viral_core_seeds.faa -o out_drift/
|
|
41
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
viro_drift/__init__.py
|
|
5
|
+
viro_drift/cli.py
|
|
6
|
+
viro_drift/host_partition.py
|
|
7
|
+
viro_drift/micro_assembler.py
|
|
8
|
+
viro_drift/recruitment.py
|
|
9
|
+
viro_drift/translation_bait.py
|
|
10
|
+
viro_drift.egg-info/PKG-INFO
|
|
11
|
+
viro_drift.egg-info/SOURCES.txt
|
|
12
|
+
viro_drift.egg-info/dependency_links.txt
|
|
13
|
+
viro_drift.egg-info/entry_points.txt
|
|
14
|
+
viro_drift.egg-info/requires.txt
|
|
15
|
+
viro_drift.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
viro_drift
|