pqplot 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.
pqplot-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Christian Ramirez
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.
pqplot-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: pqplot
3
+ Version: 0.1.0
4
+ Summary: Chromosome ideograms and karyograms for matplotlib.
5
+ Keywords: ideogram,karyogram,karyotype,chromosome,genomics,matplotlib
6
+ Author: Christian Ramirez
7
+ Author-email: Christian Ramirez <christian.ramirez1@umassmed.edu>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: Matplotlib
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
18
+ Classifier: Topic :: Scientific/Engineering :: Visualization
19
+ Requires-Dist: matplotlib>=3.10
20
+ Requires-Dist: numpy>=2.2
21
+ Requires-Python: >=3.12
22
+ Project-URL: Repository, https://github.com/ramirc0/pqplot
23
+ Project-URL: Issues, https://github.com/ramirc0/pqplot/issues
24
+ Project-URL: Changelog, https://github.com/ramirc0/pqplot/blob/main/CHANGELOG.md
25
+ Description-Content-Type: text/markdown
26
+
27
+ # pqplot
28
+
29
+ Chromosome ideograms and karyograms for matplotlib.
30
+
31
+ ## Description
32
+
33
+ pqplot draws banded chromosomes and puts your data on them. It covers a single
34
+ ideogram over a locus plot and whole karyotypes, vertical or horizontal. Data
35
+ can go on the bodies as painted categories or values, or in tracks beside them
36
+ as marks, labels, scatter, lines, areas, heatmaps and intervals. It also has
37
+ helpers for genome-wide plots such as Manhattan plots.
38
+
39
+ Every chromosome and track is a plain matplotlib Axes with positions in bp. You
40
+ can call any matplotlib method on it. Every entry point takes `ax=None`. Without
41
+ an Axes, it makes a figure sized to the content. With one, it fills that slot of
42
+ your figure. Input is any table with columns (polars, pandas, pyarrow, a dict)
43
+ or plain arrays. Chromosome names match across `chr1` and `1`.
44
+
45
+ Bundled assemblies are hg19, hg38, hs1 (T2T-CHM13), mm10 and mm39. Any other
46
+ genome works from a `.chrom.sizes` or `.fai` file, with an optional centromere
47
+ BED.
48
+
49
+ ## Getting Started
50
+
51
+ ### Dependencies
52
+
53
+ * Python 3.12 or later
54
+ * matplotlib 3.10 or later
55
+ * NumPy 2.2 or later
56
+
57
+ ### Installing
58
+
59
+ ```
60
+ uv add pqplot
61
+ ```
62
+
63
+ ### Executing program
64
+
65
+ A karyotype with GWAS hits as marks and gene names as labels:
66
+
67
+ ```python
68
+ import pqplot as pqp
69
+
70
+ hg38 = pqp.Genome.bundled("hg38")
71
+ kary = pqp.Karyogram(
72
+ hg38, groups=2, align="centromere", tracks=[pqp.Track("hits", side="after", size=5)]
73
+ )
74
+ kary.track("hits").mark(hits, pos="pos", color="trait")
75
+ kary.track("hits").label(genes, pos="pos", text="gene")
76
+ kary.legend(title="Trait")
77
+ kary.figure.savefig("karyotype.svg")
78
+ ```
79
+
80
+ <p align="center">
81
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_karyotype.png" alt="Karyotype with marks and labels" width="927">
82
+ </p>
83
+
84
+ An ideogram over your own locus plot, with x in bp:
85
+
86
+ ```python
87
+ import matplotlib.pyplot as plt
88
+
89
+ locus = pqp.Region.parse("chr17:43,044,295-43,125,483")
90
+ fig, (head, body) = plt.subplots(2, 1, height_ratios=[1, 3])
91
+ ideo = pqp.ideogram(hg38[locus.chrom], ax=head)
92
+ body.plot(pos, signal)
93
+ body.set_xlim(locus.start, locus.end)
94
+ ideo.zoom(locus, into=body)
95
+ ```
96
+
97
+ <p align="center">
98
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_locus.png" alt="Locus with an ideogram header" width="650">
99
+ </p>
100
+
101
+ Painting chromosome bodies by category or by value:
102
+
103
+ ```python
104
+ kary = pqp.Karyogram(hg38, groups=2)
105
+ kary.paint(
106
+ segments,
107
+ start="start",
108
+ end="end",
109
+ color="state",
110
+ palette={"gain": "tab:red", "loss": "tab:blue"},
111
+ )
112
+
113
+ kary = pqp.Karyogram(hg38, bands=False)
114
+ heat = kary.paint(bins, start="start", end="end", value="per_mb", cmap="magma")
115
+ kary.colorbar(heat, label="cCREs per Mb")
116
+ ```
117
+
118
+ <p align="center">
119
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_paint_categories.png" alt="Painted copy number" width="347">
120
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_paint_values.png" alt="Painted density" width="536">
121
+ </p>
122
+
123
+ The [`gallery/`](https://github.com/ramirc0/pqplot/tree/main/gallery) scripts
124
+ hold the full code for these figures and for data tracks, homolog pairs,
125
+ genome-wide plots and unbanded assemblies. Each script ends with a figure named
126
+ `fig`. The tests render them against the images in `tests/baseline/`.
127
+
128
+ ## Help
129
+
130
+ * Chromosome and track panels are child Axes of a hidden host Axes. They are
131
+ not in `fig.axes`, and `plt.gca()` does not return them. Get them with
132
+ `kary.panel(chrom, track=None)` or `kary.panels(track=None)`.
133
+ * Labels do not count in the layout. Size their track to fit the longest
134
+ label, or labels run into the next chromosome.
135
+ * A legend and a colorbar both sit at the top right of the karyogram. Draw one
136
+ or the other.
137
+ * Docstrings document every public name. Read them with `help()`:
138
+
139
+ ```
140
+ python -c "import pqplot; help(pqplot.Karyogram)"
141
+ ```
142
+
143
+ ## Authors
144
+
145
+ Christian Ramirez (christian.ramirez1@umassmed.edu)
146
+
147
+ ## Version History
148
+
149
+ See [CHANGELOG.md](https://github.com/ramirc0/pqplot/blob/main/CHANGELOG.md).
150
+
151
+ ## License
152
+
153
+ This project is licensed under the MIT License. See the
154
+ [LICENSE](https://github.com/ramirc0/pqplot/blob/main/LICENSE) file for
155
+ details.
156
+
157
+ ## Acknowledgments
158
+
159
+ * Cytobands for hg19, hg38, mm10 and mm39 come from the
160
+ [UCSC Genome Browser](https://genome.ucsc.edu) database, built on NCBI
161
+ assemblies.
162
+ * hs1 cytobands come from the
163
+ [T2T Consortium](https://github.com/marbl/CHM13) and are released under CC0.
164
+ * [pyideogram](https://github.com/Balthasar-eu/pyideogram),
165
+ [tagore](https://github.com/jordanlab/tagore) and
166
+ [karyoploteR](https://bioconductor.org/packages/karyoploteR) shaped the
167
+ design. pqplot shares no code with them.
pqplot-0.1.0/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # pqplot
2
+
3
+ Chromosome ideograms and karyograms for matplotlib.
4
+
5
+ ## Description
6
+
7
+ pqplot draws banded chromosomes and puts your data on them. It covers a single
8
+ ideogram over a locus plot and whole karyotypes, vertical or horizontal. Data
9
+ can go on the bodies as painted categories or values, or in tracks beside them
10
+ as marks, labels, scatter, lines, areas, heatmaps and intervals. It also has
11
+ helpers for genome-wide plots such as Manhattan plots.
12
+
13
+ Every chromosome and track is a plain matplotlib Axes with positions in bp. You
14
+ can call any matplotlib method on it. Every entry point takes `ax=None`. Without
15
+ an Axes, it makes a figure sized to the content. With one, it fills that slot of
16
+ your figure. Input is any table with columns (polars, pandas, pyarrow, a dict)
17
+ or plain arrays. Chromosome names match across `chr1` and `1`.
18
+
19
+ Bundled assemblies are hg19, hg38, hs1 (T2T-CHM13), mm10 and mm39. Any other
20
+ genome works from a `.chrom.sizes` or `.fai` file, with an optional centromere
21
+ BED.
22
+
23
+ ## Getting Started
24
+
25
+ ### Dependencies
26
+
27
+ * Python 3.12 or later
28
+ * matplotlib 3.10 or later
29
+ * NumPy 2.2 or later
30
+
31
+ ### Installing
32
+
33
+ ```
34
+ uv add pqplot
35
+ ```
36
+
37
+ ### Executing program
38
+
39
+ A karyotype with GWAS hits as marks and gene names as labels:
40
+
41
+ ```python
42
+ import pqplot as pqp
43
+
44
+ hg38 = pqp.Genome.bundled("hg38")
45
+ kary = pqp.Karyogram(
46
+ hg38, groups=2, align="centromere", tracks=[pqp.Track("hits", side="after", size=5)]
47
+ )
48
+ kary.track("hits").mark(hits, pos="pos", color="trait")
49
+ kary.track("hits").label(genes, pos="pos", text="gene")
50
+ kary.legend(title="Trait")
51
+ kary.figure.savefig("karyotype.svg")
52
+ ```
53
+
54
+ <p align="center">
55
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_karyotype.png" alt="Karyotype with marks and labels" width="927">
56
+ </p>
57
+
58
+ An ideogram over your own locus plot, with x in bp:
59
+
60
+ ```python
61
+ import matplotlib.pyplot as plt
62
+
63
+ locus = pqp.Region.parse("chr17:43,044,295-43,125,483")
64
+ fig, (head, body) = plt.subplots(2, 1, height_ratios=[1, 3])
65
+ ideo = pqp.ideogram(hg38[locus.chrom], ax=head)
66
+ body.plot(pos, signal)
67
+ body.set_xlim(locus.start, locus.end)
68
+ ideo.zoom(locus, into=body)
69
+ ```
70
+
71
+ <p align="center">
72
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_locus.png" alt="Locus with an ideogram header" width="650">
73
+ </p>
74
+
75
+ Painting chromosome bodies by category or by value:
76
+
77
+ ```python
78
+ kary = pqp.Karyogram(hg38, groups=2)
79
+ kary.paint(
80
+ segments,
81
+ start="start",
82
+ end="end",
83
+ color="state",
84
+ palette={"gain": "tab:red", "loss": "tab:blue"},
85
+ )
86
+
87
+ kary = pqp.Karyogram(hg38, bands=False)
88
+ heat = kary.paint(bins, start="start", end="end", value="per_mb", cmap="magma")
89
+ kary.colorbar(heat, label="cCREs per Mb")
90
+ ```
91
+
92
+ <p align="center">
93
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_paint_categories.png" alt="Painted copy number" width="347">
94
+ <img src="https://raw.githubusercontent.com/ramirc0/pqplot/main/tests/baseline/test_gallery_paint_values.png" alt="Painted density" width="536">
95
+ </p>
96
+
97
+ The [`gallery/`](https://github.com/ramirc0/pqplot/tree/main/gallery) scripts
98
+ hold the full code for these figures and for data tracks, homolog pairs,
99
+ genome-wide plots and unbanded assemblies. Each script ends with a figure named
100
+ `fig`. The tests render them against the images in `tests/baseline/`.
101
+
102
+ ## Help
103
+
104
+ * Chromosome and track panels are child Axes of a hidden host Axes. They are
105
+ not in `fig.axes`, and `plt.gca()` does not return them. Get them with
106
+ `kary.panel(chrom, track=None)` or `kary.panels(track=None)`.
107
+ * Labels do not count in the layout. Size their track to fit the longest
108
+ label, or labels run into the next chromosome.
109
+ * A legend and a colorbar both sit at the top right of the karyogram. Draw one
110
+ or the other.
111
+ * Docstrings document every public name. Read them with `help()`:
112
+
113
+ ```
114
+ python -c "import pqplot; help(pqplot.Karyogram)"
115
+ ```
116
+
117
+ ## Authors
118
+
119
+ Christian Ramirez (christian.ramirez1@umassmed.edu)
120
+
121
+ ## Version History
122
+
123
+ See [CHANGELOG.md](https://github.com/ramirc0/pqplot/blob/main/CHANGELOG.md).
124
+
125
+ ## License
126
+
127
+ This project is licensed under the MIT License. See the
128
+ [LICENSE](https://github.com/ramirc0/pqplot/blob/main/LICENSE) file for
129
+ details.
130
+
131
+ ## Acknowledgments
132
+
133
+ * Cytobands for hg19, hg38, mm10 and mm39 come from the
134
+ [UCSC Genome Browser](https://genome.ucsc.edu) database, built on NCBI
135
+ assemblies.
136
+ * hs1 cytobands come from the
137
+ [T2T Consortium](https://github.com/marbl/CHM13) and are released under CC0.
138
+ * [pyideogram](https://github.com/Balthasar-eu/pyideogram),
139
+ [tagore](https://github.com/jordanlab/tagore) and
140
+ [karyoploteR](https://bioconductor.org/packages/karyoploteR) shaped the
141
+ design. pqplot shares no code with them.
@@ -0,0 +1,87 @@
1
+ [project]
2
+ name = "pqplot"
3
+ version = "0.1.0"
4
+ description = "Chromosome ideograms and karyograms for matplotlib."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ dependencies = [
10
+ "matplotlib>=3.10",
11
+ "numpy>=2.2",
12
+ ]
13
+ keywords = [
14
+ "ideogram",
15
+ "karyogram",
16
+ "karyotype",
17
+ "chromosome",
18
+ "genomics",
19
+ "matplotlib",
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 4 - Beta",
23
+ "Framework :: Matplotlib",
24
+ "Intended Audience :: Science/Research",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Programming Language :: Python :: 3.14",
29
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
30
+ "Topic :: Scientific/Engineering :: Visualization",
31
+ ]
32
+
33
+ [[project.authors]]
34
+ name = "Christian Ramirez"
35
+ email = "christian.ramirez1@umassmed.edu"
36
+
37
+ [project.urls]
38
+ Repository = "https://github.com/ramirc0/pqplot"
39
+ Issues = "https://github.com/ramirc0/pqplot/issues"
40
+ Changelog = "https://github.com/ramirc0/pqplot/blob/main/CHANGELOG.md"
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.13,<0.14"]
44
+ build-backend = "uv_build"
45
+
46
+ [dependency-groups]
47
+ dev = [
48
+ "hypothesis>=6.170.15",
49
+ "pandas>=3.1.1",
50
+ "poikilos",
51
+ "polars>=2.1.0",
52
+ "pytest>=9.2",
53
+ "pytest-mpl>=0.19",
54
+ "ruff==0.17.4",
55
+ ]
56
+
57
+ [tool.uv]
58
+ exclude-newer = "1 week"
59
+
60
+ [tool.uv.exclude-newer-package]
61
+ certifi = false
62
+ pip = false
63
+
64
+ [tool.uv.sources.poikilos]
65
+ git = "https://github.com/ramirc0/poikilos"
66
+
67
+ [tool.ruff]
68
+ line-length = 100
69
+
70
+ [tool.ruff.lint]
71
+ select = [
72
+ "E",
73
+ "F",
74
+ "I",
75
+ "UP",
76
+ "B",
77
+ "NPY",
78
+ ]
79
+
80
+ [tool.pytest.ini_options]
81
+ testpaths = [
82
+ "src",
83
+ "tests",
84
+ ]
85
+ addopts = "--doctest-modules --mpl"
86
+ markers = ["images: compare rendered figures with tests/baseline"]
87
+ filterwarnings = ["error"]
@@ -0,0 +1,62 @@
1
+ [project]
2
+ name = "pqplot"
3
+ version = "0.1.0"
4
+ description = "Chromosome ideograms and karyograms for matplotlib."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Christian Ramirez", email = "christian.ramirez1@umassmed.edu" }]
9
+ requires-python = ">=3.12"
10
+ dependencies = ["matplotlib>=3.10", "numpy>=2.2"]
11
+ keywords = ["ideogram", "karyogram", "karyotype", "chromosome", "genomics", "matplotlib"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Framework :: Matplotlib",
15
+ "Intended Audience :: Science/Research",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Programming Language :: Python :: 3.14",
20
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
21
+ "Topic :: Scientific/Engineering :: Visualization",
22
+ ]
23
+
24
+ [project.urls]
25
+ Repository = "https://github.com/ramirc0/pqplot"
26
+ Issues = "https://github.com/ramirc0/pqplot/issues"
27
+ Changelog = "https://github.com/ramirc0/pqplot/blob/main/CHANGELOG.md"
28
+
29
+ [build-system]
30
+ requires = ["uv_build>=0.13,<0.14"]
31
+ build-backend = "uv_build"
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "hypothesis>=6.170.15",
36
+ "pandas>=3.1.1",
37
+ "poikilos",
38
+ "polars>=2.1.0",
39
+ "pytest>=9.2",
40
+ "pytest-mpl>=0.19",
41
+ "ruff==0.17.4",
42
+ ]
43
+
44
+ [tool.uv]
45
+ # uv.lock records these, and UV_EXCLUDE_NEWER and ~/.config/uv/uv.toml override them locally. They must match.
46
+ exclude-newer = "1 week"
47
+ exclude-newer-package = { certifi = false, pip = false }
48
+
49
+ [tool.uv.sources]
50
+ poikilos = { git = "https://github.com/ramirc0/poikilos" }
51
+
52
+ [tool.ruff]
53
+ line-length = 100
54
+
55
+ [tool.ruff.lint]
56
+ select = ["E", "F", "I", "UP", "B", "NPY"]
57
+
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["src", "tests"]
60
+ addopts = "--doctest-modules --mpl"
61
+ markers = ["images: compare rendered figures with tests/baseline"]
62
+ filterwarnings = ["error"]
@@ -0,0 +1,20 @@
1
+ """Chromosome ideograms and karyograms for matplotlib."""
2
+
3
+ from pqplot.genome import Band, Chromosome, Genome, LinearGenome, Region, Stain
4
+ from pqplot.ideograms import Ideogram, chromosome_axis, genome_strip, ideogram
5
+ from pqplot.karyogram import Karyogram, Track
6
+
7
+ __all__ = [
8
+ "Band",
9
+ "Chromosome",
10
+ "Genome",
11
+ "Ideogram",
12
+ "Karyogram",
13
+ "LinearGenome",
14
+ "Region",
15
+ "Stain",
16
+ "Track",
17
+ "chromosome_axis",
18
+ "genome_strip",
19
+ "ideogram",
20
+ ]
@@ -0,0 +1,86 @@
1
+ """Colors for categories and values, shared by every data layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ from matplotlib.artist import Artist
10
+ from matplotlib.cm import ScalarMappable
11
+ from matplotlib.colors import Normalize, to_rgba_array
12
+ from matplotlib.patches import Patch
13
+
14
+
15
+ def value_scale(values: np.ndarray, cmap: object, norm: Normalize | None) -> ScalarMappable:
16
+ """Return a color scale fit to the values unless `norm` sets its limits.
17
+
18
+ Examples
19
+ --------
20
+ >>> value_scale(np.array([2.0, 8.0]), "magma", None).norm.vmax
21
+ 8.0
22
+ """
23
+ scale = ScalarMappable(norm, cmap)
24
+ scale.set_array(values)
25
+ scale.autoscale_None()
26
+ return scale
27
+
28
+
29
+ def _swatch(color: np.ndarray) -> Artist:
30
+ """Return a legend handle for a filled category."""
31
+ return Patch(facecolor=color, edgecolor="none")
32
+
33
+
34
+ def category_colors(
35
+ values: np.ndarray | None,
36
+ rows: int,
37
+ palette: Mapping | None,
38
+ legend: dict[str, Artist],
39
+ handle: Callable[[np.ndarray], Artist] = _swatch,
40
+ ) -> tuple[np.ndarray, np.ndarray]:
41
+ """Return each row's category index and the category colors.
42
+
43
+ Categories join `legend` with handles made by `handle`. Without
44
+ categories, every row gets the first color of the theme's cycle and the
45
+ legend stays as it is.
46
+
47
+ Raises
48
+ ------
49
+ KeyError
50
+ If `palette` lacks a category.
51
+
52
+ Examples
53
+ --------
54
+ >>> legend = {}
55
+ >>> codes, swatches = category_colors(np.array(["b", "a", "b"]), 3, None, legend)
56
+ >>> codes.tolist(), list(legend)
57
+ ([0, 1, 0], ['b', 'a'])
58
+ """
59
+ if values is None:
60
+ return np.zeros(rows, dtype=int), to_rgba_array(["C0"])
61
+ labels, codes = _categories(values, palette)
62
+ cycle = plt.rcParams["axes.prop_cycle"].by_key()["color"]
63
+ swatches = to_rgba_array(
64
+ [cycle[i % len(cycle)] for i in range(len(labels))]
65
+ if palette is None
66
+ else [palette[x] for x in labels.tolist()]
67
+ )
68
+ for label, swatch in zip(labels, swatches, strict=True):
69
+ legend[str(label)] = handle(swatch)
70
+ return codes, swatches
71
+
72
+
73
+ def _categories(values: np.ndarray, palette: Mapping | None) -> tuple[np.ndarray, np.ndarray]:
74
+ """Return the categories in legend order and each row's index into them."""
75
+ uniques, first, codes = np.unique(values, return_index=True, return_inverse=True)
76
+ if palette is None:
77
+ order = np.argsort(first)
78
+ else:
79
+ missing = [u for u in uniques.tolist() if u not in palette]
80
+ if missing:
81
+ raise KeyError(f"palette lacks categories {missing}")
82
+ keys = list(palette)
83
+ order = np.argsort([keys.index(u) for u in uniques.tolist()])
84
+ rank = np.empty_like(order)
85
+ rank[order] = np.arange(len(order))
86
+ return uniques[order], rank[codes]
@@ -0,0 +1,69 @@
1
+ """Column arrays from any table, grouped by chromosome."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from pqplot.genome import chrom_key
8
+
9
+
10
+ def column(table: object, spec: object) -> np.ndarray:
11
+ """Return one column of a table as a NumPy array.
12
+
13
+ Parameters
14
+ ----------
15
+ table : DataFrame, dict or None
16
+ Any table indexed by column name, such as a polars or pandas
17
+ DataFrame, a pyarrow Table or a dict of sequences.
18
+ spec : str or array-like
19
+ Column name, or the values themselves.
20
+
21
+ Returns
22
+ -------
23
+ numpy.ndarray
24
+
25
+ Raises
26
+ ------
27
+ ValueError
28
+ If `spec` names a column but there is no table.
29
+
30
+ Examples
31
+ --------
32
+ >>> column({"pos": [5, 7]}, "pos")
33
+ array([5, 7])
34
+ >>> column(None, [1.5])
35
+ array([1.5])
36
+ """
37
+ if not isinstance(spec, str):
38
+ return np.asarray(spec)
39
+ if table is None:
40
+ raise ValueError(f"column {spec!r} needs a table; pass data or the values themselves")
41
+ return np.asarray(table[spec])
42
+
43
+
44
+ def rows_by_chrom(chroms: np.ndarray) -> dict[str, np.ndarray]:
45
+ """Group row indices by chromosome.
46
+
47
+ Parameters
48
+ ----------
49
+ chroms : numpy.ndarray
50
+ Chromosome name of each row. Names match across styles.
51
+
52
+ Returns
53
+ -------
54
+ dict of str to numpy.ndarray
55
+ Row indices in input order, keyed by `pqplot.genome.chrom_key`.
56
+
57
+ Examples
58
+ --------
59
+ >>> {k: v.tolist() for k, v in rows_by_chrom(np.array(["chr2", "1", "chr1"])).items()}
60
+ {'1': [1, 2], '2': [0]}
61
+ """
62
+ if len(chroms) == 0:
63
+ return {}
64
+ names, index = np.unique(chroms.astype(str), return_inverse=True)
65
+ keys, key_index = np.unique([chrom_key(n) for n in names], return_inverse=True)
66
+ rows = key_index[index]
67
+ order = np.argsort(rows, kind="stable")
68
+ groups = np.split(order, np.cumsum(np.bincount(rows, minlength=len(keys)))[:-1])
69
+ return dict(zip(keys.tolist(), groups, strict=True))