pqplot 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.
pqplot/__init__.py ADDED
@@ -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
+ ]
pqplot/colors.py ADDED
@@ -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]
pqplot/columns.py ADDED
@@ -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))
pqplot/cytobands.py ADDED
@@ -0,0 +1,103 @@
1
+ """Readers for cytoband tables, chromosome sizes and centromere BED files.
2
+
3
+ The readers return every contig in a file. `Genome` picks the chromosomes.
4
+ """
5
+
6
+ import gzip
7
+ from collections import defaultdict
8
+ from collections.abc import Iterator
9
+ from os import PathLike
10
+
11
+ type BandRow = tuple[int, int, str, str]
12
+
13
+
14
+ def read_bands(path: str | PathLike) -> dict[str, list[BandRow]]:
15
+ """Read a cytoband table such as UCSC ``cytoBand.txt.gz`` or the T2T BED.
16
+
17
+ Parameters
18
+ ----------
19
+ path : str or PathLike
20
+ Tab-separated file, gzipped or plain, with columns chrom, start, end,
21
+ band name and stain.
22
+
23
+ Returns
24
+ -------
25
+ dict of str to list of tuple
26
+ ``(start, end, name, stain)`` rows for each chromosome, in file order.
27
+
28
+ Examples
29
+ --------
30
+ >>> from importlib.resources import files
31
+ >>> bands = read_bands(files("pqplot") / "data/hg38/cytoBand.txt.gz")
32
+ >>> bands["chr1"][0]
33
+ (0, 2300000, 'p36.33', 'gneg')
34
+ """
35
+ rows = defaultdict(list)
36
+ for chrom, start, end, *rest in _fields(path):
37
+ name, stain = (rest + ["", ""])[:2]
38
+ rows[chrom].append((int(start), int(end), name, stain))
39
+ return dict(rows)
40
+
41
+
42
+ def read_sizes(path: str | PathLike) -> dict[str, int]:
43
+ """Read chromosome lengths from a ``.chrom.sizes`` or ``.fai`` file.
44
+
45
+ Parameters
46
+ ----------
47
+ path : str or PathLike
48
+ Tab-separated file, gzipped or plain, whose first two columns are the
49
+ chromosome name and its length.
50
+
51
+ Returns
52
+ -------
53
+ dict of str to int
54
+ Length of each chromosome, in file order.
55
+
56
+ Examples
57
+ --------
58
+ >>> import tempfile
59
+ >>> from pathlib import Path
60
+ >>> path = Path(tempfile.mkdtemp()) / "x.chrom.sizes"
61
+ >>> _ = path.write_text("chr1\\t1000\\nchr2\\t500\\n")
62
+ >>> read_sizes(path)
63
+ {'chr1': 1000, 'chr2': 500}
64
+ """
65
+ return {chrom: int(length) for chrom, length, *_ in _fields(path)}
66
+
67
+
68
+ def read_centromeres(path: str | PathLike) -> dict[str, tuple[int, int]]:
69
+ """Read centromere spans from a BED file.
70
+
71
+ Parameters
72
+ ----------
73
+ path : str or PathLike
74
+ BED file, gzipped or plain. Several rows for one chromosome merge into
75
+ the span from their lowest start to their highest end.
76
+
77
+ Returns
78
+ -------
79
+ dict of str to tuple of int
80
+ ``(start, end)`` of each chromosome's centromere.
81
+
82
+ Examples
83
+ --------
84
+ >>> import tempfile
85
+ >>> from pathlib import Path
86
+ >>> path = Path(tempfile.mkdtemp()) / "centromeres.bed"
87
+ >>> _ = path.write_text("chr1\\t120\\t130\\nchr1\\t100\\t110\\n")
88
+ >>> read_centromeres(path)
89
+ {'chr1': (100, 130)}
90
+ """
91
+ spans = {}
92
+ for chrom, start, end, *_ in _fields(path):
93
+ lo, hi = spans.get(chrom, (int(start), int(end)))
94
+ spans[chrom] = (min(lo, int(start)), max(hi, int(end)))
95
+ return spans
96
+
97
+
98
+ def _fields(path: str | PathLike) -> Iterator[list[str]]:
99
+ opener = gzip.open if str(path).endswith(".gz") else open
100
+ with opener(path, "rt") as handle:
101
+ for line in handle:
102
+ if line.strip() and not line.startswith("#"):
103
+ yield line.rstrip("\n").split("\t")
Binary file
Binary file