panaxis 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.
- panaxis/__init__.py +6 -0
- panaxis/__main__.py +4 -0
- panaxis/cli.py +136 -0
- panaxis/consensus.py +688 -0
- panaxis/coordinates.py +132 -0
- panaxis/report.py +364 -0
- panaxis-0.1.0.dist-info/METADATA +111 -0
- panaxis-0.1.0.dist-info/RECORD +13 -0
- panaxis-0.1.0.dist-info/WHEEL +5 -0
- panaxis-0.1.0.dist-info/entry_points.txt +2 -0
- panaxis-0.1.0.dist-info/licenses/LICENSE +21 -0
- panaxis-0.1.0.dist-info/licenses/NOTICE +39 -0
- panaxis-0.1.0.dist-info/top_level.txt +1 -0
panaxis/__init__.py
ADDED
panaxis/__main__.py
ADDED
panaxis/cli.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Command-line TSV input, coordinate publication, and HOG lookup."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import csv
|
|
5
|
+
import gzip
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from tempfile import TemporaryDirectory
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .coordinates import GeneLocus, _build_axis
|
|
13
|
+
from .report import write_report
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _open_text(path):
|
|
17
|
+
if path.suffix == ".gz":
|
|
18
|
+
return gzip.open(path, "rt", encoding="utf-8-sig", newline="")
|
|
19
|
+
return path.open(encoding="utf-8-sig", newline="")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _table(handle, required):
|
|
23
|
+
reader = csv.DictReader(handle, delimiter="\t")
|
|
24
|
+
header = reader.fieldnames or []
|
|
25
|
+
if not required <= set(header) or len(header) != len(set(header)):
|
|
26
|
+
raise ValueError(f"{handle.name}: expected unique headers including {', '.join(sorted(required))}.")
|
|
27
|
+
return reader
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _read_gene_loci(path):
|
|
31
|
+
fields = {"accession", "gene", "hog", "chromosome", "position"}
|
|
32
|
+
with _open_text(path) as handle:
|
|
33
|
+
reader = _table(handle, fields)
|
|
34
|
+
for row in reader:
|
|
35
|
+
if None in row or any(value is None for value in row.values()):
|
|
36
|
+
raise ValueError(f"{path}:{reader.line_num}: wrong number of columns.")
|
|
37
|
+
chromosome = row["chromosome"].strip()
|
|
38
|
+
chromosome = None if chromosome in {"", "."} else chromosome
|
|
39
|
+
value = row["position"].strip()
|
|
40
|
+
try:
|
|
41
|
+
position = None if value in {"", "."} else int(value)
|
|
42
|
+
except ValueError as error:
|
|
43
|
+
raise ValueError(f"{path}:{reader.line_num}: invalid position {value!r}.") from error
|
|
44
|
+
if (chromosome is not None and position is None) or (position is not None and position < 1):
|
|
45
|
+
raise ValueError(f"{path}:{reader.line_num}: expected a positive position for a mapped locus.")
|
|
46
|
+
yield GeneLocus(
|
|
47
|
+
row["accession"].strip(), row["gene"].strip(), row["hog"].strip(),
|
|
48
|
+
chromosome, position,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _write_table(path, rows):
|
|
53
|
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
|
54
|
+
writer = csv.DictWriter(handle, fieldnames=rows[0].keys(), delimiter="\t", lineterminator="\n")
|
|
55
|
+
writer.writeheader()
|
|
56
|
+
for row in rows:
|
|
57
|
+
writer.writerow({**row, "supporting_accessions": json.dumps(
|
|
58
|
+
row["supporting_accessions"], ensure_ascii=False,
|
|
59
|
+
)})
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _build(args):
|
|
63
|
+
destination = args.output_dir
|
|
64
|
+
if destination.exists():
|
|
65
|
+
raise FileExistsError(f"Output directory already exists: {destination}")
|
|
66
|
+
inventory = None
|
|
67
|
+
if args.hog_inventory is not None:
|
|
68
|
+
with _open_text(args.hog_inventory) as handle:
|
|
69
|
+
inventory = {line.strip() for line in handle if line.strip()}
|
|
70
|
+
coordinates, candidates, summary, accession_paths = _build_axis(
|
|
71
|
+
_read_gene_loci(args.genes), hog_inventory=inventory, chromosome_order=args.chromosome_order,
|
|
72
|
+
min_local_support=args.min_local_support, keep_paths=not args.no_report,
|
|
73
|
+
)
|
|
74
|
+
summary["panaxis_version"] = __version__
|
|
75
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
with TemporaryDirectory(dir=destination.parent, prefix=".panaxis-") as folder:
|
|
77
|
+
staging = Path(folder) / "output"
|
|
78
|
+
staging.mkdir()
|
|
79
|
+
_write_table(staging / "coordinates.tsv", coordinates)
|
|
80
|
+
_write_table(staging / "candidates.tsv", candidates)
|
|
81
|
+
(staging / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
|
|
82
|
+
if not args.no_report:
|
|
83
|
+
write_report(staging, coordinates, candidates, summary, accession_paths)
|
|
84
|
+
if destination.exists():
|
|
85
|
+
raise FileExistsError(f"Output directory already exists: {destination}")
|
|
86
|
+
staging.rename(destination)
|
|
87
|
+
print(f"{summary['n_hogs']:,} HOGs, {summary['n_placed']:,} placed on "
|
|
88
|
+
f"{len(summary['chromosomes'])} chromosomes: {destination}")
|
|
89
|
+
if not args.no_report:
|
|
90
|
+
print(f"Report: {destination / 'report.html'}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _locate(args):
|
|
94
|
+
requested = set(args.hogs)
|
|
95
|
+
matches = {}
|
|
96
|
+
with _open_text(args.coordinates) as handle:
|
|
97
|
+
reader = _table(handle, {"hog", "chromosome", "rank"})
|
|
98
|
+
for row in reader:
|
|
99
|
+
if row["hog"] in requested:
|
|
100
|
+
if row["hog"] in matches:
|
|
101
|
+
raise ValueError(f"Coordinate table has more than one row for {row['hog']!r}.")
|
|
102
|
+
matches[row["hog"]] = row
|
|
103
|
+
missing = requested - matches.keys()
|
|
104
|
+
if missing:
|
|
105
|
+
raise ValueError(f"HOGs absent from the coordinate table: {', '.join(sorted(missing))}")
|
|
106
|
+
writer = csv.DictWriter(sys.stdout, fieldnames=reader.fieldnames, delimiter="\t", lineterminator="\n")
|
|
107
|
+
writer.writeheader()
|
|
108
|
+
writer.writerows(matches[hog] for hog in args.hogs)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def main(argv=None):
|
|
112
|
+
parser = argparse.ArgumentParser(
|
|
113
|
+
prog="panaxis",
|
|
114
|
+
description="A reference-independent gene-level coordinate system for population-scale pangenomics.",
|
|
115
|
+
)
|
|
116
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
117
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
118
|
+
build = commands.add_parser("build", help="Build chromosome axes from a gene-locus table.")
|
|
119
|
+
build.add_argument("--genes", type=Path, required=True, help="Input gene-locus TSV or TSV.GZ.")
|
|
120
|
+
build.add_argument("--output-dir", type=Path, required=True, help="New directory for results.")
|
|
121
|
+
build.add_argument("--hog-inventory", type=Path, help="Optional full inventory with one HOG per line.")
|
|
122
|
+
build.add_argument("--chromosome-order", nargs="+", help="Ordered chromosome labels. Defaults to lexical order.")
|
|
123
|
+
build.add_argument("--min-local-support", type=int, default=2, metavar="N",
|
|
124
|
+
help="Minimum distinct accessions for a local order edge (default: 2).")
|
|
125
|
+
build.add_argument("--no-report", action="store_true", help="Write coordinate tables without figures or HTML.")
|
|
126
|
+
build.set_defaults(run=_build)
|
|
127
|
+
locate = commands.add_parser("locate", help="Look up one or more HOGs in the primary coordinate table.")
|
|
128
|
+
locate.add_argument("coordinates", type=Path, help="Primary coordinate table, TSV or TSV.GZ.")
|
|
129
|
+
locate.add_argument("hogs", nargs="+", metavar="HOG")
|
|
130
|
+
locate.set_defaults(run=_locate)
|
|
131
|
+
args = parser.parse_args(argv)
|
|
132
|
+
try:
|
|
133
|
+
args.run(args)
|
|
134
|
+
except (OSError, ValueError, csv.Error) as error:
|
|
135
|
+
parser.exit(2, f"panaxis: {error}\n")
|
|
136
|
+
return 0
|