ont-bed-generator 0.4.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.
- ont_bed_generator/__init__.py +25 -0
- ont_bed_generator/__main__.py +7 -0
- ont_bed_generator/_version.py +24 -0
- ont_bed_generator/cli.py +76 -0
- ont_bed_generator/intervals.py +70 -0
- ont_bed_generator/io_inputs.py +128 -0
- ont_bed_generator/io_outputs.py +30 -0
- ont_bed_generator/model.py +56 -0
- ont_bed_generator/ordering.py +20 -0
- ont_bed_generator/resolve.py +57 -0
- ont_bed_generator-0.4.0.dist-info/METADATA +143 -0
- ont_bed_generator-0.4.0.dist-info/RECORD +15 -0
- ont_bed_generator-0.4.0.dist-info/WHEEL +4 -0
- ont_bed_generator-0.4.0.dist-info/entry_points.txt +2 -0
- ont_bed_generator-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""ont_bed_generator — BED file generation for Oxford Nanopore adaptive sampling.
|
|
2
|
+
|
|
3
|
+
Standalone reimplementation (standard library only) of the Galaxy workflow
|
|
4
|
+
"Adaptative ONT BED file generation".
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from .intervals import build_extended, merge_stranded
|
|
9
|
+
from .io_inputs import GffIndex, read_entrez_map, read_genelist, read_genome
|
|
10
|
+
from .io_outputs import write_bed, write_targets
|
|
11
|
+
from .model import DEFAULT_FLANK, GeneSpec, GffGene, Locus, Resolution
|
|
12
|
+
from .resolve import resolve
|
|
13
|
+
|
|
14
|
+
# Version is derived from git tags by hatch-vcs (see pyproject.toml).
|
|
15
|
+
try:
|
|
16
|
+
from ._version import __version__
|
|
17
|
+
except Exception: # pragma: no cover - source tree without a build/tag
|
|
18
|
+
__version__ = "0+unknown"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"GeneSpec", "GffGene", "Locus", "Resolution", "DEFAULT_FLANK",
|
|
22
|
+
"read_genome", "read_genelist", "read_entrez_map", "GffIndex",
|
|
23
|
+
"resolve", "build_extended", "merge_stranded",
|
|
24
|
+
"write_targets", "write_bed", "__version__",
|
|
25
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.4.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 4, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
ont_bed_generator/cli.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Command-line interface."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
from .intervals import build_extended, merge_stranded
|
|
9
|
+
from .io_inputs import GffIndex, read_entrez_map, read_genelist, read_genome
|
|
10
|
+
from .io_outputs import write_bed, write_targets
|
|
11
|
+
from .model import DEFAULT_FLANK
|
|
12
|
+
from .resolve import resolve
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
ap = argparse.ArgumentParser(
|
|
17
|
+
prog="ont-bed-generator",
|
|
18
|
+
description="Generate targets.bed and merged-extended.bed for ONT adaptive sampling.")
|
|
19
|
+
ap.add_argument("--genelist", required=True, help="genelist TSV")
|
|
20
|
+
ap.add_argument("--gff", required=True,
|
|
21
|
+
help="GFF3, gene features (Name= + Dbxref=GeneID:)")
|
|
22
|
+
ap.add_argument("--genome", required=True,
|
|
23
|
+
help="chrom<TAB>size (used for telomere clamping; line order irrelevant)")
|
|
24
|
+
ap.add_argument("--out-targets", default="targets.bed")
|
|
25
|
+
ap.add_argument("--out-merged", default="merged-extended.bed")
|
|
26
|
+
ap.add_argument("--flank", type=int, default=DEFAULT_FLANK,
|
|
27
|
+
help=f"default per-strand flank (default {DEFAULT_FLANK})")
|
|
28
|
+
ap.add_argument("--entrez-map",
|
|
29
|
+
help="external SYMBOL<TAB>ENTREZID table (takes priority)")
|
|
30
|
+
ap.add_argument("--strict", action="store_true",
|
|
31
|
+
help="exit with code 1 if any symbol is invalid/ambiguous")
|
|
32
|
+
ap.add_argument("--version", action="version",
|
|
33
|
+
version=f"%(prog)s {__version__}")
|
|
34
|
+
return ap
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main(argv: list[str] | None = None) -> int:
|
|
38
|
+
args = build_parser().parse_args(argv)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
sizes = read_genome(args.genome)
|
|
42
|
+
specs = read_genelist(args.genelist)
|
|
43
|
+
gff = GffIndex.load(args.gff)
|
|
44
|
+
entrez_map = read_entrez_map(args.entrez_map) if args.entrez_map else None
|
|
45
|
+
except (OSError, ValueError) as exc:
|
|
46
|
+
print(f"[error] {exc}", file=sys.stderr)
|
|
47
|
+
return 2
|
|
48
|
+
|
|
49
|
+
res = resolve(specs, gff, entrez_map)
|
|
50
|
+
|
|
51
|
+
n_targets = write_targets(res.loci, args.out_targets)
|
|
52
|
+
merged = merge_stranded(build_extended(res.loci, sizes, args.flank))
|
|
53
|
+
n_merged = write_bed(merged, args.out_merged)
|
|
54
|
+
|
|
55
|
+
e = sys.stderr
|
|
56
|
+
print(f"[ok] {len(specs)} input symbols", file=e)
|
|
57
|
+
print(f"[ok] {n_targets} loci -> {args.out_targets}", file=e)
|
|
58
|
+
print(f"[ok] {n_merged} merged intervals -> {args.out_merged}", file=e)
|
|
59
|
+
if res.ambiguous:
|
|
60
|
+
print(f"[ambiguous] {len(res.ambiguous)} symbol(s) mapping to multiple "
|
|
61
|
+
f"GeneIDs (dropped):", file=e)
|
|
62
|
+
for sym, gids in res.ambiguous:
|
|
63
|
+
print(f" {sym} -> GeneID {', '.join(gids)}", file=e)
|
|
64
|
+
if res.invalid:
|
|
65
|
+
print(f"[invalid] {len(res.invalid)} symbol(s) not found "
|
|
66
|
+
f"(fix them in the source genelist):", file=e)
|
|
67
|
+
for sym in res.invalid:
|
|
68
|
+
print(f" {sym}", file=e)
|
|
69
|
+
|
|
70
|
+
if args.strict and (res.invalid or res.ambiguous):
|
|
71
|
+
return 1
|
|
72
|
+
return 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Per-strand extension, clamping to chromosome bounds, per-strand merging."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
|
|
6
|
+
from .model import DEFAULT_FLANK, BedRow, Locus
|
|
7
|
+
from .ordering import chrom_sort_key
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def build_extended(
|
|
11
|
+
loci: list[Locus],
|
|
12
|
+
sizes: dict[str, int],
|
|
13
|
+
flank: int = DEFAULT_FLANK,
|
|
14
|
+
) -> list[BedRow]:
|
|
15
|
+
"""Two BED6 intervals per locus (+ / -), extended then clamped.
|
|
16
|
+
|
|
17
|
+
"+" strand : [ start - flank - Left , end ]
|
|
18
|
+
"-" strand : [ start , end + flank + Right ]
|
|
19
|
+
then clamped to [0, chrom_size] (equivalent to `bedtools slop -b 0`).
|
|
20
|
+
"""
|
|
21
|
+
out: list[BedRow] = []
|
|
22
|
+
for lo in loci:
|
|
23
|
+
size = sizes.get(lo.chrom)
|
|
24
|
+
if size is None:
|
|
25
|
+
raise ValueError(f"chromosome missing from genome file: {lo.chrom}")
|
|
26
|
+
|
|
27
|
+
def clamp(x: int, _s: int = size) -> int:
|
|
28
|
+
return max(0, min(x, _s))
|
|
29
|
+
|
|
30
|
+
out.append((lo.chrom, clamp(lo.start - flank - lo.left),
|
|
31
|
+
clamp(lo.end), lo.name, lo.extended, "+"))
|
|
32
|
+
out.append((lo.chrom, clamp(lo.start),
|
|
33
|
+
clamp(lo.end + flank + lo.right), lo.name, lo.extended, "-"))
|
|
34
|
+
return out
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def merge_stranded(intervals: list[BedRow]) -> list[BedRow]:
|
|
38
|
+
"""Merge per (chrom, strand): overlapping or book-ended (distance 0).
|
|
39
|
+
|
|
40
|
+
names = sorted union joined by commas;
|
|
41
|
+
score = minimum of the Extended_region flags;
|
|
42
|
+
strand = preserved.
|
|
43
|
+
Final sort: canonical karyotypic order, then start, end, strand.
|
|
44
|
+
"""
|
|
45
|
+
groups: dict[tuple[str, str], list[BedRow]] = defaultdict(list)
|
|
46
|
+
for iv in intervals:
|
|
47
|
+
groups[(iv[0], iv[5])].append(iv)
|
|
48
|
+
|
|
49
|
+
merged: list[BedRow] = []
|
|
50
|
+
for (chrom, strand), ivs in groups.items():
|
|
51
|
+
ivs.sort(key=lambda x: (x[1], x[2]))
|
|
52
|
+
start = end = 0
|
|
53
|
+
names: set[str] = set()
|
|
54
|
+
score = 0
|
|
55
|
+
has_open = False
|
|
56
|
+
for _c, s, e, name, sc, _st in ivs:
|
|
57
|
+
if not has_open:
|
|
58
|
+
start, end, names, score, has_open = s, e, {name}, sc, True
|
|
59
|
+
elif s <= end:
|
|
60
|
+
end = max(end, e)
|
|
61
|
+
names.add(name)
|
|
62
|
+
score = min(score, sc)
|
|
63
|
+
else:
|
|
64
|
+
merged.append((chrom, start, end, ",".join(sorted(names)), score, strand))
|
|
65
|
+
start, end, names, score = s, e, {name}, sc
|
|
66
|
+
if has_open:
|
|
67
|
+
merged.append((chrom, start, end, ",".join(sorted(names)), score, strand))
|
|
68
|
+
|
|
69
|
+
merged.sort(key=lambda x: (chrom_sort_key(x[0]), x[1], x[2], x[5]))
|
|
70
|
+
return merged
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Input readers: genome sizes, genelist, GFF, external Entrez table."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import gzip
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from typing import IO
|
|
7
|
+
|
|
8
|
+
from .model import GeneSpec, GffGene
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _open(path: str) -> IO[str]:
|
|
12
|
+
"""Open a text file, transparently handling gzip-compressed (.gz) input."""
|
|
13
|
+
if str(path).endswith(".gz"):
|
|
14
|
+
return gzip.open(path, "rt")
|
|
15
|
+
return open(path)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def read_genome(path: str) -> dict[str, int]:
|
|
19
|
+
"""Return chromosome sizes {name: length} (used for telomere clamping)."""
|
|
20
|
+
sizes: dict[str, int] = {}
|
|
21
|
+
with _open(path) as fh:
|
|
22
|
+
for line in fh:
|
|
23
|
+
line = line.rstrip("\n")
|
|
24
|
+
if not line or line.startswith("#"):
|
|
25
|
+
continue
|
|
26
|
+
fields = line.split("\t")
|
|
27
|
+
sizes[fields[0]] = int(fields[1])
|
|
28
|
+
if not sizes:
|
|
29
|
+
raise ValueError(f"empty/unreadable genome file: {path}")
|
|
30
|
+
return sizes
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _field_int(fields: list[str], i: int) -> int:
|
|
34
|
+
"""Parse an integer from a TSV field, defaulting to 0 when absent/empty."""
|
|
35
|
+
if len(fields) > i and fields[i].strip():
|
|
36
|
+
try:
|
|
37
|
+
return int(fields[i].strip())
|
|
38
|
+
except ValueError:
|
|
39
|
+
return 0
|
|
40
|
+
return 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _is_header_row(fields: list[str]) -> bool:
|
|
44
|
+
"""A header has a header-word first cell, or non-numeric size columns."""
|
|
45
|
+
if fields[0].strip().lower() in {"gene", "symbol", "gene_symbol", "genes"}:
|
|
46
|
+
return True
|
|
47
|
+
return any(c.strip() and not c.strip().isdigit() for c in fields[1:3])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def read_genelist(path: str) -> list[GeneSpec]:
|
|
51
|
+
"""Read the genelist TSV: columns Gene, Left_extension_bp, Right_extension_bp.
|
|
52
|
+
|
|
53
|
+
A gene counts as an extended region iff Left or Right is non-zero, so no
|
|
54
|
+
separate flag column is needed; a bare `Gene` line (no extension columns) is
|
|
55
|
+
valid and gets only the default flank. A header row, if present, is detected
|
|
56
|
+
and skipped.
|
|
57
|
+
"""
|
|
58
|
+
specs: list[GeneSpec] = []
|
|
59
|
+
with _open(path) as fh:
|
|
60
|
+
rows = [line.rstrip("\n") for line in fh]
|
|
61
|
+
start = 1 if rows and _is_header_row(rows[0].split("\t")) else 0
|
|
62
|
+
for line in rows[start:]:
|
|
63
|
+
if not line:
|
|
64
|
+
continue
|
|
65
|
+
fields = line.split("\t")
|
|
66
|
+
symbol = fields[0].strip() # chomp whitespace/tabs (Excel habit)
|
|
67
|
+
if not symbol:
|
|
68
|
+
continue
|
|
69
|
+
left = _field_int(fields, 1)
|
|
70
|
+
right = _field_int(fields, 2)
|
|
71
|
+
specs.append(GeneSpec(symbol, left, right))
|
|
72
|
+
return specs
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _attrs(s: str) -> dict[str, str]:
|
|
76
|
+
d: dict[str, str] = {}
|
|
77
|
+
for field in s.rstrip(";").split(";"):
|
|
78
|
+
if "=" in field:
|
|
79
|
+
k, _, v = field.partition("=")
|
|
80
|
+
d[k.strip()] = v.strip()
|
|
81
|
+
return d
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class GffIndex:
|
|
85
|
+
"""Index of GFF `gene` features, keyed on Entrez (GeneID)."""
|
|
86
|
+
|
|
87
|
+
def __init__(self) -> None:
|
|
88
|
+
self.geneid_to_features: dict[str, list[GffGene]] = defaultdict(list)
|
|
89
|
+
self.name_to_geneids: dict[str, set[str]] = defaultdict(set)
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def load(cls, path: str) -> GffIndex:
|
|
93
|
+
idx = cls()
|
|
94
|
+
with _open(path) as fh:
|
|
95
|
+
for line in fh:
|
|
96
|
+
if line.startswith("#") or not line.strip():
|
|
97
|
+
continue
|
|
98
|
+
fields = line.rstrip("\n").split("\t")
|
|
99
|
+
if len(fields) < 9 or fields[2] != "gene":
|
|
100
|
+
continue
|
|
101
|
+
a = _attrs(fields[8])
|
|
102
|
+
entrez = None
|
|
103
|
+
for tok in a.get("Dbxref", "").split(","):
|
|
104
|
+
if tok.startswith("GeneID:"):
|
|
105
|
+
entrez = tok.split(":", 1)[1]
|
|
106
|
+
break
|
|
107
|
+
name = a.get("Name") or a.get("gene") or ""
|
|
108
|
+
g = GffGene(fields[0], int(fields[3]), int(fields[4]), entrez, name)
|
|
109
|
+
# Without a GeneID, fall back to a synthetic key so nothing is lost.
|
|
110
|
+
key = entrez if entrez is not None else f"NONAME:{name}:{fields[0]}:{fields[3]}"
|
|
111
|
+
idx.geneid_to_features[key].append(g)
|
|
112
|
+
if name:
|
|
113
|
+
idx.name_to_geneids[name].add(key)
|
|
114
|
+
return idx
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def read_entrez_map(path: str) -> dict[str, str]:
|
|
118
|
+
"""External SYMBOL<TAB>ENTREZID table (e.g. an org.Hs.eg.db export)."""
|
|
119
|
+
m: dict[str, str] = {}
|
|
120
|
+
with _open(path) as fh:
|
|
121
|
+
for line in fh:
|
|
122
|
+
line = line.rstrip("\n")
|
|
123
|
+
if not line or line.startswith("#"):
|
|
124
|
+
continue
|
|
125
|
+
fields = line.split("\t")
|
|
126
|
+
if len(fields) >= 2 and fields[0].strip() and fields[1].strip():
|
|
127
|
+
m[fields[0].strip()] = fields[1].strip()
|
|
128
|
+
return m
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Output BED writers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .model import BedRow, Locus
|
|
5
|
+
from .ordering import chrom_sort_key
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def write_targets(loci: list[Locus], path: str) -> int:
|
|
9
|
+
"""targets.bed: (chrom, start, end, Name, 0, .), deduplicated, sorted."""
|
|
10
|
+
seen: set[tuple[str, int, int, str]] = set()
|
|
11
|
+
rows: list[BedRow] = []
|
|
12
|
+
for lo in loci:
|
|
13
|
+
key = (lo.chrom, lo.start, lo.end, lo.name)
|
|
14
|
+
if key in seen:
|
|
15
|
+
continue
|
|
16
|
+
seen.add(key)
|
|
17
|
+
rows.append((lo.chrom, lo.start, lo.end, lo.name, 0, "."))
|
|
18
|
+
rows.sort(key=lambda x: (chrom_sort_key(x[0]), x[1], x[2], x[3]))
|
|
19
|
+
with open(path, "w") as fh:
|
|
20
|
+
for r in rows:
|
|
21
|
+
fh.write("\t".join(map(str, r)) + "\n")
|
|
22
|
+
return len(rows)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def write_bed(rows: list[BedRow], path: str) -> int:
|
|
26
|
+
"""Write a list of already-ordered BED tuples."""
|
|
27
|
+
with open(path, "w") as fh:
|
|
28
|
+
for r in rows:
|
|
29
|
+
fh.write("\t".join(map(str, r)) + "\n")
|
|
30
|
+
return len(rows)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Data structures and constants."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
DEFAULT_FLANK = 10000
|
|
7
|
+
|
|
8
|
+
# A BED6 row: (chrom, start, end, name, score, strand).
|
|
9
|
+
BedRow = tuple[str, int, int, str, int, str]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class GeneSpec:
|
|
14
|
+
"""One genelist row: symbol plus per-side extension sizes (bp)."""
|
|
15
|
+
symbol: str
|
|
16
|
+
left: int
|
|
17
|
+
right: int
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def extended(self) -> int:
|
|
21
|
+
"""Derived flag: a region is 'extended' if it has a custom L/R size."""
|
|
22
|
+
return 1 if (self.left or self.right) else 0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class GffGene:
|
|
27
|
+
"""A GFF `gene` feature (1-based, inclusive coordinates)."""
|
|
28
|
+
chrom: str
|
|
29
|
+
start1: int
|
|
30
|
+
end: int
|
|
31
|
+
entrez: str | None
|
|
32
|
+
name: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Locus:
|
|
37
|
+
"""A resolved locus in BED coordinates (0-based, half-open)."""
|
|
38
|
+
chrom: str
|
|
39
|
+
start: int
|
|
40
|
+
end: int
|
|
41
|
+
name: str # canonical GFF Name=
|
|
42
|
+
left: int
|
|
43
|
+
right: int
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def extended(self) -> int:
|
|
47
|
+
"""Derived flag: a region is 'extended' if it has a custom L/R size."""
|
|
48
|
+
return 1 if (self.left or self.right) else 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Resolution:
|
|
53
|
+
"""Result of symbol -> loci resolution, with diagnostics."""
|
|
54
|
+
loci: list[Locus]
|
|
55
|
+
ambiguous: list[tuple[str, list[str]]] # (symbol, [GeneID...])
|
|
56
|
+
invalid: list[str]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Canonical karyotypic ordering of chromosome names.
|
|
2
|
+
|
|
3
|
+
Organism-agnostic: numbered autosomes first in numeric order (chr1, chr2, ...,
|
|
4
|
+
chr9, chr10, ...), then sex chromosomes (X, Y; also Z, W for other clades), then
|
|
5
|
+
the mitochondrion (M / MT), then any remaining contigs alphabetically. No
|
|
6
|
+
hard-coded per-organism list, so it works for human, mouse, etc.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def chrom_sort_key(chrom: str) -> tuple[int, int, str]:
|
|
12
|
+
"""Sort key placing chromosome names in canonical karyotypic order."""
|
|
13
|
+
name = chrom[3:] if chrom.lower().startswith("chr") else chrom
|
|
14
|
+
if name.isdigit():
|
|
15
|
+
return (0, int(name), "")
|
|
16
|
+
special = {"X": 0, "Y": 1, "Z": 2, "W": 3, "M": 4, "MT": 4}
|
|
17
|
+
rank = special.get(name.upper())
|
|
18
|
+
if rank is not None:
|
|
19
|
+
return (1, rank, "")
|
|
20
|
+
return (2, 0, name)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Resolve official gene symbols to loci, using the GFF Entrez key.
|
|
2
|
+
|
|
3
|
+
Policy: official HGNC symbols only (verifiable via
|
|
4
|
+
https://www.genenames.org/tools/multi-symbol-checker/). No synonym fallback,
|
|
5
|
+
no renaming. A symbol that is not found is reported, never guessed.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from .io_inputs import GffIndex
|
|
10
|
+
from .model import GeneSpec, Locus, Resolution
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def resolve(
|
|
14
|
+
specs: list[GeneSpec],
|
|
15
|
+
gff: GffIndex,
|
|
16
|
+
entrez_map: dict[str, str] | None = None,
|
|
17
|
+
) -> Resolution:
|
|
18
|
+
loci: list[Locus] = []
|
|
19
|
+
ambiguous: list[tuple[str, list[str]]] = []
|
|
20
|
+
invalid: list[str] = []
|
|
21
|
+
seen: set[tuple[str, int, int, str]] = set()
|
|
22
|
+
|
|
23
|
+
for spec in specs:
|
|
24
|
+
# External table first, then GFF Name=, otherwise invalid.
|
|
25
|
+
if entrez_map is not None and spec.symbol in entrez_map:
|
|
26
|
+
geneids = {entrez_map[spec.symbol]}
|
|
27
|
+
elif spec.symbol in gff.name_to_geneids:
|
|
28
|
+
geneids = set(gff.name_to_geneids[spec.symbol])
|
|
29
|
+
else:
|
|
30
|
+
invalid.append(spec.symbol)
|
|
31
|
+
continue
|
|
32
|
+
|
|
33
|
+
# A Name mapping to several distinct GeneIDs is ambiguous (e.g. tRNAs).
|
|
34
|
+
if len(geneids) > 1:
|
|
35
|
+
ambiguous.append((spec.symbol, sorted(geneids)))
|
|
36
|
+
continue
|
|
37
|
+
|
|
38
|
+
gid = next(iter(geneids))
|
|
39
|
+
recs = gff.geneid_to_features.get(gid, [])
|
|
40
|
+
if not recs:
|
|
41
|
+
invalid.append(spec.symbol)
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
# Collect by GeneID: handles PAR genes (chrX+chrY) and IG/TCR loci.
|
|
45
|
+
for g in recs:
|
|
46
|
+
start0 = g.start1 - 1
|
|
47
|
+
out_name = g.name or spec.symbol
|
|
48
|
+
key = (g.chrom, start0, g.end, out_name)
|
|
49
|
+
if key in seen:
|
|
50
|
+
continue
|
|
51
|
+
seen.add(key)
|
|
52
|
+
loci.append(
|
|
53
|
+
Locus(g.chrom, start0, g.end, out_name,
|
|
54
|
+
spec.left, spec.right)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return Resolution(loci, ambiguous, invalid)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ont-bed-generator
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Generate BED files for Oxford Nanopore adaptive sampling from a gene list and a RefSeq GFF3.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Institut-Leucemie/ont-bed-generator
|
|
6
|
+
Project-URL: Issues, https://github.com/Institut-Leucemie/ont-bed-generator/issues
|
|
7
|
+
Author: Christophe Antoniewski
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2026 Christophe Antoniewski
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Keywords: adaptive-sampling,bed,bioinformatics,genomics,nanopore
|
|
31
|
+
Classifier: Intended Audience :: Science/Research
|
|
32
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
33
|
+
Classifier: Operating System :: OS Independent
|
|
34
|
+
Classifier: Programming Language :: Python :: 3
|
|
35
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
36
|
+
Requires-Python: >=3.10
|
|
37
|
+
Provides-Extra: dev
|
|
38
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
39
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
40
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
41
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
42
|
+
Description-Content-Type: text/markdown
|
|
43
|
+
|
|
44
|
+

|
|
45
|
+
|
|
46
|
+
# ont-bed-generator
|
|
47
|
+
|
|
48
|
+
Generate **BED** files for **Oxford Nanopore adaptive sampling** from a gene
|
|
49
|
+
list and a RefSeq GFF3. Standalone reimplementation (Python standard library
|
|
50
|
+
only, **no runtime dependencies**) of the Galaxy workflow "Adaptative ONT BED
|
|
51
|
+
file generation" (which replaced BED-Craft).
|
|
52
|
+
|
|
53
|
+
Given a list of target genes and a GFF3 annotation, the tool produces:
|
|
54
|
+
|
|
55
|
+
- `targets.bed` — the raw locus of each gene (BED6);
|
|
56
|
+
- `merged-extended.bed` — two intervals per locus (`+` / `-` strands),
|
|
57
|
+
extended, clamped to chromosome bounds, then merged per strand.
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
# from source
|
|
63
|
+
git clone https://github.com/CHANGE-ME/ont-bed-generator.git
|
|
64
|
+
cd ont-bed-generator
|
|
65
|
+
pip install .
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Conda development environment (includes `bedtools`, used only by the parity
|
|
69
|
+
test):
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
conda env create -f environment.yml # or: mamba/micromamba env create -f environment.yml
|
|
73
|
+
conda activate ont-bed-generator
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Usage
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
ont-bed-generator \
|
|
80
|
+
--genelist genelist.tsv \
|
|
81
|
+
--gff annotation.genes.gff3 \
|
|
82
|
+
--genome hs1.len \
|
|
83
|
+
--out-targets targets.bed \
|
|
84
|
+
--out-merged merged-extended.bed
|
|
85
|
+
# or: python -m ont_bed_generator --genelist ... --gff ... --genome ...
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Inputs
|
|
89
|
+
|
|
90
|
+
1. **genelist TSV** — columns `Gene | Left_extension_bp | Right_extension_bp`,
|
|
91
|
+
with an (auto-detected) header row. Coordinates come from the GFF, so no
|
|
92
|
+
chromosome column is needed; a gene is treated as an extended region when
|
|
93
|
+
Left or Right is non-zero (no separate flag). A bare `Gene` line (no
|
|
94
|
+
extensions) is valid and gets only the default flank. Symbols must be
|
|
95
|
+
**official HGNC symbols** (check them with the
|
|
96
|
+
[multi-symbol checker](https://www.genenames.org/tools/multi-symbol-checker/)).
|
|
97
|
+
2. **GFF3** — a RefSeq GFF3 whose `gene` features carry `Name=` and
|
|
98
|
+
`Dbxref=GeneID:`. The **full NCBI annotation works as-is**: the tool reads
|
|
99
|
+
only `gene` features and ignores everything else, so pre-extracting them is
|
|
100
|
+
just an optional speed-up. Gzip-compressed (`.gz`) input is read transparently
|
|
101
|
+
(this applies to every input file). Example (T2T-CHM13v2.0 / hs1):
|
|
102
|
+
```bash
|
|
103
|
+
curl -sO https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/009/914/755/GCF_009914755.1_T2T-CHM13v2.0/GCF_009914755.1_T2T-CHM13v2.0_genomic.gff.gz
|
|
104
|
+
```
|
|
105
|
+
3. **genome sizes** — `chrom<TAB>size`, one line per chromosome. Used for
|
|
106
|
+
telomere clamping only; the line order does not matter (output BEDs are
|
|
107
|
+
sorted in canonical karyotypic order).
|
|
108
|
+
```bash
|
|
109
|
+
curl -sO https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.chrom.sizes
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Symbol resolution
|
|
113
|
+
|
|
114
|
+
Official symbol → GeneID (GFF `Name=`, or external `--entrez-map`) → collect
|
|
115
|
+
**all** loci carrying that GeneID. The Entrez key handles pseudoautosomal
|
|
116
|
+
regions (one GeneID on chrX and chrY yields two loci) and IG/TCR loci. A symbol
|
|
117
|
+
that is not found, or that maps to several GeneIDs, is **reported** (on stderr),
|
|
118
|
+
never guessed. `--strict` returns a non-zero exit code if any symbol is invalid
|
|
119
|
+
or ambiguous.
|
|
120
|
+
|
|
121
|
+
## Development
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
pip install -e '.[dev]'
|
|
125
|
+
pytest # unit tests (+ bedtools parity if bedtools is present)
|
|
126
|
+
ruff check .
|
|
127
|
+
mypy
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Versioning is driven by git tags (`hatch-vcs`): a release is
|
|
131
|
+
`git tag vX.Y.Z && git push --tags`.
|
|
132
|
+
|
|
133
|
+
## Intentional differences from the original Galaxy workflow
|
|
134
|
+
|
|
135
|
+
- The workflow patched non-official symbols (`MKL1→MKLN1`, a bug — MKLN1 is a
|
|
136
|
+
different gene; `LYL→LYL1`). Here **no patching**: such symbols are reported
|
|
137
|
+
for correction at the source.
|
|
138
|
+
- The Galaxy output contained a missing merge (`bedtools merge` on
|
|
139
|
+
genome-order-sorted input without `-g`). This tool performs the correct merge.
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ont_bed_generator/__init__.py,sha256=GxYbBZcGwEmx2yLF00gEtNzgDVkYMAXJudwOBu5457I,983
|
|
2
|
+
ont_bed_generator/__main__.py,sha256=1LIX2JyZNpgID3NtRHryuTXQyfmXtYkGx9hldLKFCj4,163
|
|
3
|
+
ont_bed_generator/_version.py,sha256=HGBlVvZpQ8N2kh1n_LY5PM4s9ljcIgdbOCgXN-uFje4,520
|
|
4
|
+
ont_bed_generator/cli.py,sha256=4ADDCfmCiMK1vwCcSbtLOpfRVoGWZUjXAie3yGmpwcI,3021
|
|
5
|
+
ont_bed_generator/intervals.py,sha256=FdoLq7ly9zn-YvLrF-gbNvjq2uYumxdi_4NfxsY_OdU,2508
|
|
6
|
+
ont_bed_generator/io_inputs.py,sha256=jiPtSlU3ts0NPiJZURZYzMMqyXa9o9AHaPSwMjEo8Mw,4581
|
|
7
|
+
ont_bed_generator/io_outputs.py,sha256=mGvpBjFIeK_-aiLGsEn2a66XtmzxGVL6lo5Krjhh-LI,986
|
|
8
|
+
ont_bed_generator/model.py,sha256=v7UCDq1f9tc1djOKa3u204ZrOaK43Rigbavhwkq3zZg,1330
|
|
9
|
+
ont_bed_generator/ordering.py,sha256=Qg_aAzrRvouvwKkJCIL16_D_HWw_Y5FQK9Y0BB88QvY,829
|
|
10
|
+
ont_bed_generator/resolve.py,sha256=p_sOeydkmzz9yhLtQdyGFOzD4vQ7tthxZeUaPhacPos,1908
|
|
11
|
+
ont_bed_generator-0.4.0.dist-info/METADATA,sha256=D538rs_9dc0_cHkYPj1mO3n5S4_LukYQrGigqhoeucY,5984
|
|
12
|
+
ont_bed_generator-0.4.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
13
|
+
ont_bed_generator-0.4.0.dist-info/entry_points.txt,sha256=jlNxteDDrU4hh28868TgbjiGA5pWR6qTUWIoh9KXy4k,65
|
|
14
|
+
ont_bed_generator-0.4.0.dist-info/licenses/LICENSE,sha256=gkFcMpjwos6A_Izro6rCt9XZSwO61RFAZuj0_O2_bj0,1079
|
|
15
|
+
ont_bed_generator-0.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Christophe Antoniewski
|
|
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.
|