panaxis 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.
panaxis-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yuxing Xu
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.
panaxis-0.1.0/NOTICE ADDED
@@ -0,0 +1,39 @@
1
+ PanAxis
2
+ Copyright 2026 Yuxing Xu
3
+
4
+ The rank-based collinear block search in panaxis/consensus.py was adapted
5
+ from Yuxing Xu's synteny_block.py in yxcompgen. Xu's contributions to this
6
+ implementation are included in PanAxis under the MIT License.
7
+ Source: https://github.com/SouthernCD/yxcompgen
8
+
9
+ That implementation is based on the collinearity code listed below.
10
+ PanAxis uses its own rank-based implementation and carries the original
11
+ copyright and redistribution terms.
12
+
13
+ Upstream source: https://github.com/SunPengChuan/wgdi/blob/master/wgdi/collinearity.py
14
+ Upstream license (BSD-2-Clause): https://github.com/SunPengChuan/wgdi/blob/master/LICENSE
15
+
16
+ Copyright (c) 2018-2018, Pengchuan Sun
17
+
18
+ All rights reserved.
19
+
20
+ Redistribution and use in source and binary forms, with or without modification,
21
+ are permitted provided that the following conditions are met:
22
+
23
+ Redistributions of source code must retain the above copyright notice, this list
24
+ of conditions and the following disclaimer.
25
+
26
+ Redistributions in binary form must reproduce the above copyright notice, this
27
+ list of conditions and the following disclaimer in the documentation and/or
28
+ other materials provided with the distribution.
29
+
30
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
31
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
32
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
33
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
34
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
36
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
37
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
39
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
panaxis-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: panaxis
3
+ Version: 0.1.0
4
+ Summary: A reference-independent gene-level coordinate system for population-scale pangenomics
5
+ Author: Yuxing Xu
6
+ License-Expression: MIT AND BSD-2-Clause
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Provides-Extra: plot
12
+ Requires-Dist: matplotlib>=3.6; extra == "plot"
13
+ Requires-Dist: numpy>=1.24; extra == "plot"
14
+ Dynamic: license-file
15
+
16
+ # PanAxis
17
+
18
+ [简体中文](README.zh-CN.md)
19
+
20
+ **A reference-independent gene-level coordinate system for population-scale pangenomics.**
21
+
22
+ Pangenome studies can group genes from different accessions into hierarchical orthologous groups (HOGs). Comparing where those HOGs occur still calls for a shared chromosome coordinate system. Many ancestral chromosome reconstruction methods rely on a species tree and often draw on outgroups for evolutionary context. Within species, frequent hybridization and recombination can make a single bifurcating tree a poor description of population history.
23
+
24
+ PanAxis integrates original gene orders and collinearity across accessions to build a gene-level consensus axis for each homologous chromosome. It requires no designated reference genome, outgroup, or phylogenetic tree. The axes provide a common coordinate system for pangenome visualization, comparative genomics, and population genetic analyses.
25
+
26
+ The output includes a primary record for every HOG, including groups whose positions remain unresolved. Alternative locations and their support are also retained.
27
+
28
+ ## Quick start
29
+
30
+ Run from this directory with Python 3.10 or newer. Building and querying an axis uses the Python standard library.
31
+
32
+ ```bash
33
+ python -m pip install .
34
+ panaxis build --genes examples/genes.tsv --output-dir demo-results
35
+ panaxis locate demo-results/coordinates.tsv HOG_X HOG_Z
36
+ ```
37
+
38
+ You can also use `python -m panaxis` from this directory without installing. In the example, two accessions place `HOG_X` between `HOG_A` and `HOG_B`, and a third places it between `HOG_B` and `HOG_C`. `HOG_Z` occurs on an unplaced scaffold, so its primary row has empty coordinate fields.
39
+
40
+ ## Real example with 33 sorghum accessions
41
+
42
+ The [input preparation guide](examples/sorghum33/README.md) links to the original downloads and explains how to assemble a PanAxis input locally from Supplementary Data 7 and the original genome annotations. The input contains 988,756 gene occurrences assigned to 54,959 HOGs across 33 accessions. [Sorghum pangenome paper](https://doi.org/10.1038/s41586-026-10229-9)
43
+
44
+ PanAxis 0.1.0 placed 53,544 HOGs on 10 chromosome axes and retained 1,415 unplaced records. The bundled outputs include an [offline report](examples/sorghum33/output/report.html) with 33 dotplots and a consensus-first cohort plot, as well as [primary coordinates](examples/sorghum33/output/coordinates.tsv.gz), [candidate positions](examples/sorghum33/output/candidates.tsv.gz), and the [run summary](examples/sorghum33/output/summary.json).
45
+
46
+ ![Sorghum collinearity across 33 accessions, with the PanAxis consensus in the first row](examples/sorghum33/output/figures/cohort_collinearity.svg)
47
+
48
+ *The top row shows the PanAxis consensus. Ribbons link collinear blocks between adjacent rows.*
49
+
50
+ ![Whole-genome dotplot comparing the PanAxis sorghum consensus with BTx623](examples/sorghum33/output/figures/accession-001.svg)
51
+
52
+ *BTx623 versus the consensus. The axes show consensus HOG rank and BTx623 gene rank.*
53
+
54
+ ![Reverse HOG order in Kamjin on chromosomes 5 through 8, with comparisons to the PanAxis consensus and BTx623](docs/figures/kamjin-reverse-hog-order.png)
55
+
56
+ *Four regions in Kamjin (PI 660565) show reverse HOG order relative to the PanAxis consensus (top). The same regions show reversed order when BTx623 and Kamjin are compared using single-copy anchors (bottom). Coral marks reverse chains, and gray marks nearby same-chromosome anchors.*
57
+
58
+ ```bash
59
+ panaxis build --genes /path/to/sorghum33.genes.tsv.gz --output-dir sorghum33-rebuilt
60
+ panaxis locate examples/sorghum33/output/coordinates.tsv.gz HOG038060
61
+ ```
62
+
63
+ ## Real example with 69 Arabidopsis accessions
64
+
65
+ The [input gene loci](examples/arabidopsis69/genes.tsv.gz) contain 1,928,005 gene occurrences from the 69 newly assembled *Arabidopsis thaliana* accessions of Lian et al. (2024). This example uses 33,916 original orthogroups (OGs), including multicopy memberships and 6,708 singleton entries from the original grouping. The input field `hog` carries the published OG identifiers. All memberships matched the original gene annotations by exact gene ID. The input uses gene starts from those annotations and leaves coordinates blank for unplaced contigs. It uses the authors’ grouping before annotation-based revisions. [Gene ID audit](examples/arabidopsis69/gene_id_match.tsv) · [Paper](https://doi.org/10.1038/s41588-024-01715-9) · [Source dataset (CC0 1.0)](https://doi.org/10.17617/3.AEOJBL)
66
+
67
+ PanAxis 0.1.0 placed 33,880 OGs on five chromosome axes and retained 36 unplaced records. The [offline report](examples/arabidopsis69/output/report.html) includes chromosome evidence tracks, 69 whole-genome dotplots, and a consensus-first cohort plot. The [primary coordinates](examples/arabidopsis69/output/coordinates.tsv.gz), [candidate positions](examples/arabidopsis69/output/candidates.tsv.gz), and [run summary](examples/arabidopsis69/output/summary.json) are included.
68
+
69
+ ![Arabidopsis chromosome evidence tracks showing core anchor fraction, median position score, and alternative position fraction](examples/arabidopsis69/output/figures/chromosome_evidence.svg)
70
+
71
+ *Each window summarizes 100 consecutive OGs along the consensus axis.*
72
+
73
+ ```bash
74
+ panaxis build --genes examples/arabidopsis69/genes.tsv.gz --output-dir arabidopsis69-rebuilt
75
+ panaxis locate examples/arabidopsis69/output/coordinates.tsv.gz OG0019623 OG0007051
76
+ ```
77
+
78
+ ## Input and output
79
+
80
+ Pass a UTF-8 TSV, optionally gzip-compressed, with one row per original gene occurrence.
81
+
82
+ | Column | Meaning |
83
+ |---|---|
84
+ | `accession` | Accession identifier |
85
+ | `gene` | Gene identifier, unique within the accession |
86
+ | `hog` | HOG identifier. Keep all copies, including those on scaffolds |
87
+ | `chromosome` | Shared label for homologous chromosomes. Leave blank or use `.` for unplaced loci |
88
+ | `position` | Positive integer used to sort genes along the harmonized chromosome direction. A gene rank or gene start is suitable. Leave blank or use `.` for unplaced loci |
89
+
90
+ Assign homologous chromosome labels and harmonize directions upstream. PanAxis assumes every cohort accession is represented in the input. Homologous chromosomes missing from an accession contribute no shared anchors. The optional `--hog-inventory` is a complete one-ID-per-line list and can include unobserved HOGs. `--chromosome-order Chr01 Chr02` overrides lexical display order.
91
+
92
+ The output directory contains the following tables and report.
93
+
94
+ - `coordinates.tsv` has one row per HOG. The primary coordinate is `chromosome` plus a 1-based ordinal `rank` in the consensus gene order. Both fields are empty for unplaced HOGs. `chromosome_hint` can hold an observed chromosome for a HOG whose within-chromosome position is unresolved.
95
+ - `candidates.tsv` lists candidate locations, including their two flanking anchors when available. `selected` identifies the primary record. The fractional `position` describes placement relative to the core anchors, and `supporting_accessions` is a JSON array stored in a TSV field.
96
+ - `summary.json` records the cohort, support threshold, and counts of genes, HOGs, anchored chromosomes and removed local conflicts.
97
+ - `report.html` opens offline and links to figures in `figures/` and per-accession block calls in `collinearity.tsv`. Keep the files together. The report includes chromosome evidence in 100-HOG windows, one whole-genome dotplot per accession, and a cohort plot with the consensus at the top and accessions in lexical order. Cohort ribbons connect adjacent rows on homologous chromosomes. The accession dotplots include interchromosomal matches. Pass `--no-report` for table-only output.
98
+
99
+ ## Method and interpretation
100
+
101
+ PanAxis chooses HOGs present exactly once across each accession's supplied genome-wide loci and consistently assigned to the same chromosome. Within a chromosome it fixes these anchors by their median rank across accessions. Other HOG occurrences are projected between flanking anchors. A weighted precedence graph only orders candidates within the same anchor interval. Local edges require support from at least two distinct accessions by default.
102
+
103
+ For a candidate location, each accession contributes its strongest observation. Tight two-sided support contributes 1 vote, wider two-sided support 0.5, and one-sided support 0.25. The score is 100 times the weighted votes divided by the cohort size. Location scores summarize support for an inferred order. They have no base-pair units or probability interpretation. The tables also report chromosome support, interval support, and local ordering support separately. Axes depend on the cohort and input annotations, so use the same built coordinate table when comparing plots or analyses.
104
+
105
+ The Python API is `panaxis.build_coordinates`, which takes `panaxis.GeneLocus` records. Lower-level consensus and optional collinear-block search and comparison helpers are available in `panaxis.consensus`. Install `.[plot]` to use its dotplot helper.
106
+
107
+ ## Citation and license
108
+
109
+ If you use PanAxis in research, cite the software version you ran using the metadata in [CITATION.cff](CITATION.cff).
110
+
111
+ PanAxis is released under the [MIT License](LICENSE). The [NOTICE](NOTICE) records the provenance of the collinear-block search and includes the upstream BSD-2-Clause license and copyright. The real examples use data from the sources cited in their example sections.
@@ -0,0 +1,96 @@
1
+ # PanAxis
2
+
3
+ [简体中文](README.zh-CN.md)
4
+
5
+ **A reference-independent gene-level coordinate system for population-scale pangenomics.**
6
+
7
+ Pangenome studies can group genes from different accessions into hierarchical orthologous groups (HOGs). Comparing where those HOGs occur still calls for a shared chromosome coordinate system. Many ancestral chromosome reconstruction methods rely on a species tree and often draw on outgroups for evolutionary context. Within species, frequent hybridization and recombination can make a single bifurcating tree a poor description of population history.
8
+
9
+ PanAxis integrates original gene orders and collinearity across accessions to build a gene-level consensus axis for each homologous chromosome. It requires no designated reference genome, outgroup, or phylogenetic tree. The axes provide a common coordinate system for pangenome visualization, comparative genomics, and population genetic analyses.
10
+
11
+ The output includes a primary record for every HOG, including groups whose positions remain unresolved. Alternative locations and their support are also retained.
12
+
13
+ ## Quick start
14
+
15
+ Run from this directory with Python 3.10 or newer. Building and querying an axis uses the Python standard library.
16
+
17
+ ```bash
18
+ python -m pip install .
19
+ panaxis build --genes examples/genes.tsv --output-dir demo-results
20
+ panaxis locate demo-results/coordinates.tsv HOG_X HOG_Z
21
+ ```
22
+
23
+ You can also use `python -m panaxis` from this directory without installing. In the example, two accessions place `HOG_X` between `HOG_A` and `HOG_B`, and a third places it between `HOG_B` and `HOG_C`. `HOG_Z` occurs on an unplaced scaffold, so its primary row has empty coordinate fields.
24
+
25
+ ## Real example with 33 sorghum accessions
26
+
27
+ The [input preparation guide](examples/sorghum33/README.md) links to the original downloads and explains how to assemble a PanAxis input locally from Supplementary Data 7 and the original genome annotations. The input contains 988,756 gene occurrences assigned to 54,959 HOGs across 33 accessions. [Sorghum pangenome paper](https://doi.org/10.1038/s41586-026-10229-9)
28
+
29
+ PanAxis 0.1.0 placed 53,544 HOGs on 10 chromosome axes and retained 1,415 unplaced records. The bundled outputs include an [offline report](examples/sorghum33/output/report.html) with 33 dotplots and a consensus-first cohort plot, as well as [primary coordinates](examples/sorghum33/output/coordinates.tsv.gz), [candidate positions](examples/sorghum33/output/candidates.tsv.gz), and the [run summary](examples/sorghum33/output/summary.json).
30
+
31
+ ![Sorghum collinearity across 33 accessions, with the PanAxis consensus in the first row](examples/sorghum33/output/figures/cohort_collinearity.svg)
32
+
33
+ *The top row shows the PanAxis consensus. Ribbons link collinear blocks between adjacent rows.*
34
+
35
+ ![Whole-genome dotplot comparing the PanAxis sorghum consensus with BTx623](examples/sorghum33/output/figures/accession-001.svg)
36
+
37
+ *BTx623 versus the consensus. The axes show consensus HOG rank and BTx623 gene rank.*
38
+
39
+ ![Reverse HOG order in Kamjin on chromosomes 5 through 8, with comparisons to the PanAxis consensus and BTx623](docs/figures/kamjin-reverse-hog-order.png)
40
+
41
+ *Four regions in Kamjin (PI 660565) show reverse HOG order relative to the PanAxis consensus (top). The same regions show reversed order when BTx623 and Kamjin are compared using single-copy anchors (bottom). Coral marks reverse chains, and gray marks nearby same-chromosome anchors.*
42
+
43
+ ```bash
44
+ panaxis build --genes /path/to/sorghum33.genes.tsv.gz --output-dir sorghum33-rebuilt
45
+ panaxis locate examples/sorghum33/output/coordinates.tsv.gz HOG038060
46
+ ```
47
+
48
+ ## Real example with 69 Arabidopsis accessions
49
+
50
+ The [input gene loci](examples/arabidopsis69/genes.tsv.gz) contain 1,928,005 gene occurrences from the 69 newly assembled *Arabidopsis thaliana* accessions of Lian et al. (2024). This example uses 33,916 original orthogroups (OGs), including multicopy memberships and 6,708 singleton entries from the original grouping. The input field `hog` carries the published OG identifiers. All memberships matched the original gene annotations by exact gene ID. The input uses gene starts from those annotations and leaves coordinates blank for unplaced contigs. It uses the authors’ grouping before annotation-based revisions. [Gene ID audit](examples/arabidopsis69/gene_id_match.tsv) · [Paper](https://doi.org/10.1038/s41588-024-01715-9) · [Source dataset (CC0 1.0)](https://doi.org/10.17617/3.AEOJBL)
51
+
52
+ PanAxis 0.1.0 placed 33,880 OGs on five chromosome axes and retained 36 unplaced records. The [offline report](examples/arabidopsis69/output/report.html) includes chromosome evidence tracks, 69 whole-genome dotplots, and a consensus-first cohort plot. The [primary coordinates](examples/arabidopsis69/output/coordinates.tsv.gz), [candidate positions](examples/arabidopsis69/output/candidates.tsv.gz), and [run summary](examples/arabidopsis69/output/summary.json) are included.
53
+
54
+ ![Arabidopsis chromosome evidence tracks showing core anchor fraction, median position score, and alternative position fraction](examples/arabidopsis69/output/figures/chromosome_evidence.svg)
55
+
56
+ *Each window summarizes 100 consecutive OGs along the consensus axis.*
57
+
58
+ ```bash
59
+ panaxis build --genes examples/arabidopsis69/genes.tsv.gz --output-dir arabidopsis69-rebuilt
60
+ panaxis locate examples/arabidopsis69/output/coordinates.tsv.gz OG0019623 OG0007051
61
+ ```
62
+
63
+ ## Input and output
64
+
65
+ Pass a UTF-8 TSV, optionally gzip-compressed, with one row per original gene occurrence.
66
+
67
+ | Column | Meaning |
68
+ |---|---|
69
+ | `accession` | Accession identifier |
70
+ | `gene` | Gene identifier, unique within the accession |
71
+ | `hog` | HOG identifier. Keep all copies, including those on scaffolds |
72
+ | `chromosome` | Shared label for homologous chromosomes. Leave blank or use `.` for unplaced loci |
73
+ | `position` | Positive integer used to sort genes along the harmonized chromosome direction. A gene rank or gene start is suitable. Leave blank or use `.` for unplaced loci |
74
+
75
+ Assign homologous chromosome labels and harmonize directions upstream. PanAxis assumes every cohort accession is represented in the input. Homologous chromosomes missing from an accession contribute no shared anchors. The optional `--hog-inventory` is a complete one-ID-per-line list and can include unobserved HOGs. `--chromosome-order Chr01 Chr02` overrides lexical display order.
76
+
77
+ The output directory contains the following tables and report.
78
+
79
+ - `coordinates.tsv` has one row per HOG. The primary coordinate is `chromosome` plus a 1-based ordinal `rank` in the consensus gene order. Both fields are empty for unplaced HOGs. `chromosome_hint` can hold an observed chromosome for a HOG whose within-chromosome position is unresolved.
80
+ - `candidates.tsv` lists candidate locations, including their two flanking anchors when available. `selected` identifies the primary record. The fractional `position` describes placement relative to the core anchors, and `supporting_accessions` is a JSON array stored in a TSV field.
81
+ - `summary.json` records the cohort, support threshold, and counts of genes, HOGs, anchored chromosomes and removed local conflicts.
82
+ - `report.html` opens offline and links to figures in `figures/` and per-accession block calls in `collinearity.tsv`. Keep the files together. The report includes chromosome evidence in 100-HOG windows, one whole-genome dotplot per accession, and a cohort plot with the consensus at the top and accessions in lexical order. Cohort ribbons connect adjacent rows on homologous chromosomes. The accession dotplots include interchromosomal matches. Pass `--no-report` for table-only output.
83
+
84
+ ## Method and interpretation
85
+
86
+ PanAxis chooses HOGs present exactly once across each accession's supplied genome-wide loci and consistently assigned to the same chromosome. Within a chromosome it fixes these anchors by their median rank across accessions. Other HOG occurrences are projected between flanking anchors. A weighted precedence graph only orders candidates within the same anchor interval. Local edges require support from at least two distinct accessions by default.
87
+
88
+ For a candidate location, each accession contributes its strongest observation. Tight two-sided support contributes 1 vote, wider two-sided support 0.5, and one-sided support 0.25. The score is 100 times the weighted votes divided by the cohort size. Location scores summarize support for an inferred order. They have no base-pair units or probability interpretation. The tables also report chromosome support, interval support, and local ordering support separately. Axes depend on the cohort and input annotations, so use the same built coordinate table when comparing plots or analyses.
89
+
90
+ The Python API is `panaxis.build_coordinates`, which takes `panaxis.GeneLocus` records. Lower-level consensus and optional collinear-block search and comparison helpers are available in `panaxis.consensus`. Install `.[plot]` to use its dotplot helper.
91
+
92
+ ## Citation and license
93
+
94
+ If you use PanAxis in research, cite the software version you ran using the metadata in [CITATION.cff](CITATION.cff).
95
+
96
+ PanAxis is released under the [MIT License](LICENSE). The [NOTICE](NOTICE) records the provenance of the collinear-block search and includes the upstream BSD-2-Clause license and copyright. The real examples use data from the sources cited in their example sections.
@@ -0,0 +1,6 @@
1
+ """A reference-independent gene-level coordinate system for pangenomics."""
2
+
3
+ from .coordinates import GeneLocus, build_coordinates
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["GeneLocus", "build_coordinates"]
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -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