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/layout.py ADDED
@@ -0,0 +1,255 @@
1
+ """Panel layout of a karyogram, free of any drawing library.
2
+
3
+ A karyogram lays chromosomes out in groups. The along axis runs down a
4
+ vertical karyogram and right across a horizontal one. Groups follow each
5
+ other along it, and the chromosomes of a group sit side by side across it.
6
+ Each chromosome column holds its slots: tracks before the body, the body,
7
+ and tracks after it. Across sizes are in body widths. Along sizes are in bp.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass
14
+ from typing import Literal
15
+
16
+ from pqplot.genome import Chromosome
17
+
18
+ TRACK_GAP = 0.2
19
+ """Space between slots of one chromosome, in body widths."""
20
+ COPY_GAP = 0.25
21
+ """Space between copies of one chromosome, in body widths."""
22
+ COLUMN_GAP = 1.0
23
+ """Space between chromosomes of one group, in body widths."""
24
+ GROUP_GAP = 24.0
25
+ """Space between groups, in points. It holds the chromosome names."""
26
+ MAX_BODY_POINTS = 14.0
27
+ """Widest body, in points. Columns center in a host wider than that allows."""
28
+
29
+ Align = Literal["start", "centromere", "end"]
30
+
31
+
32
+ def wrap[T](items: Sequence[T], groups: int) -> list[list[T]]:
33
+ """Split items into groups of even size, in order.
34
+
35
+ Parameters
36
+ ----------
37
+ items : sequence
38
+ Items to split.
39
+ groups : int
40
+ Number of groups. Fewer come back when there are fewer items.
41
+
42
+ Returns
43
+ -------
44
+ list of list
45
+
46
+ Raises
47
+ ------
48
+ ValueError
49
+ If `groups` is less than 1.
50
+
51
+ Examples
52
+ --------
53
+ >>> wrap([1, 2, 3, 4, 5], 2)
54
+ [[1, 2, 3], [4, 5]]
55
+ """
56
+ if groups < 1:
57
+ raise ValueError(f"groups must be at least 1, got {groups}")
58
+ size = -(-len(items) // groups)
59
+ return [list(items[i : i + size]) for i in range(0, len(items), size)]
60
+
61
+
62
+ def bounds(chromosomes: Sequence[Chromosome], align: Align) -> list[tuple[float, float]]:
63
+ """Return the along-axis limits that align chromosomes in one group.
64
+
65
+ Every chromosome gets limits of the same length, so the group shares one
66
+ bp scale.
67
+
68
+ Parameters
69
+ ----------
70
+ chromosomes : sequence of Chromosome
71
+ Chromosomes of one group.
72
+ align : {"start", "centromere", "end"}
73
+ Line up the starts, the centromere midpoints, or the ends. A
74
+ telocentric or unknown centromere counts as position 0.
75
+
76
+ Returns
77
+ -------
78
+ list of tuple of float
79
+ ``(low, high)`` in bp for each chromosome.
80
+
81
+ Raises
82
+ ------
83
+ ValueError
84
+ If `align` is not one of the choices.
85
+
86
+ Examples
87
+ --------
88
+ >>> row = [Chromosome("1", 1000, centromere=(400, 500)), Chromosome("2", 600)]
89
+ >>> bounds(row, "end")
90
+ [(0, 1000), (-400, 600)]
91
+ """
92
+ longest = max(c.length for c in chromosomes)
93
+ if align == "start":
94
+ return [(0, longest) for _ in chromosomes]
95
+ if align == "end":
96
+ return [(c.length - longest, c.length) for c in chromosomes]
97
+ if align != "centromere":
98
+ raise ValueError(f"align must be start, centromere or end, got {align!r}")
99
+ mids = [sum(c.centromere) / 2 if c.centromere else 0.0 for c in chromosomes]
100
+ p = max(mids)
101
+ q = max(c.length - mid for c, mid in zip(chromosomes, mids, strict=True))
102
+ return [(mid - p, mid + q) for mid in mids]
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class Slot:
107
+ """A strip across a chromosome column that holds its body or one track.
108
+
109
+ Parameters
110
+ ----------
111
+ track : str or None
112
+ Track name, or None for the body.
113
+ start : float
114
+ Distance from the column start, in body widths.
115
+ size : float
116
+ Width in body widths.
117
+
118
+ Examples
119
+ --------
120
+ >>> Slot(None, 0.0, 1.0).track is None
121
+ True
122
+ """
123
+
124
+ track: str | None
125
+ start: float
126
+ size: float
127
+
128
+
129
+ def slots(
130
+ before: Sequence[tuple[str, float]], copies: int, after: Sequence[tuple[str, float]]
131
+ ) -> list[Slot]:
132
+ """Stack the tracks and the body across one chromosome column.
133
+
134
+ Parameters
135
+ ----------
136
+ before, after : sequence of (str, float)
137
+ Track names and sizes in body widths, before and after the body.
138
+ copies : int
139
+ Number of copies drawn side by side in the body slot.
140
+
141
+ Returns
142
+ -------
143
+ list of Slot
144
+ Slots in order across the column.
145
+
146
+ Examples
147
+ --------
148
+ >>> [s.track for s in slots([("genes", 1.0)], copies=1, after=[])]
149
+ ['genes', None]
150
+ """
151
+ stack = [*before, (None, copies + (copies - 1) * COPY_GAP), *after]
152
+ result, start = [], 0.0
153
+ for track, size in stack:
154
+ result.append(Slot(track, start, size))
155
+ start += size + TRACK_GAP
156
+ return result
157
+
158
+
159
+ @dataclass(frozen=True)
160
+ class Grid:
161
+ """Rectangles of every panel, sized to fit a host.
162
+
163
+ Groups share one bp scale and fill the along extent between gaps of
164
+ `GROUP_GAP` points. Columns share one body width and fill the across
165
+ extent, up to bodies `MAX_BODY_POINTS` wide. Beyond that they center.
166
+
167
+ Parameters
168
+ ----------
169
+ spans : tuple of float
170
+ Along length of each group in bp.
171
+ columns : int
172
+ Chromosomes in the largest group.
173
+ slots : list of Slot
174
+ Slots of every column.
175
+
176
+ Examples
177
+ --------
178
+ >>> grid = Grid((1000.0,), 2, slots([], copies=1, after=[]))
179
+ >>> grid.cell(0, 1, grid.slots[0], along=100, across=30)
180
+ (0.0, 100.0, 20.0, 30.0)
181
+ """
182
+
183
+ spans: tuple[float, ...]
184
+ columns: int
185
+ slots: list[Slot]
186
+
187
+ @property
188
+ def width(self) -> float:
189
+ """Width of one column in body widths.
190
+
191
+ Examples
192
+ --------
193
+ >>> Grid((1.0,), 1, slots([("a", 1.0)], copies=1, after=[])).width
194
+ 2.2
195
+ """
196
+ last = self.slots[-1]
197
+ return last.start + last.size
198
+
199
+ def cell(
200
+ self, group: int, column: int, slot: Slot, along: float, across: float
201
+ ) -> tuple[float, float, float, float]:
202
+ """Return the rectangle of one panel inside a host.
203
+
204
+ Parameters
205
+ ----------
206
+ group, column : int
207
+ Position of the chromosome.
208
+ slot : Slot
209
+ Slot of the panel.
210
+ along, across : float
211
+ Host size in points.
212
+
213
+ Returns
214
+ -------
215
+ tuple of float
216
+ ``(along_start, along_end, across_start, across_end)`` in points
217
+ from the host's along and across starts.
218
+
219
+ Examples
220
+ --------
221
+ >>> grid = Grid((300.0, 100.0), 1, slots([], copies=1, after=[]))
222
+ >>> grid.cell(1, 0, grid.slots[0], along=424, across=10)
223
+ (324.0, 424.0, 0.0, 10.0)
224
+ """
225
+ gaps = (len(self.spans) - 1) * GROUP_GAP
226
+ points_per_bp = max(along - gaps, 0.0) / sum(self.spans)
227
+ a0 = sum(self.spans[:group]) * points_per_bp + group * GROUP_GAP
228
+ bodies = self.columns * self.width + (self.columns - 1) * COLUMN_GAP
229
+ unit = min(across / bodies, MAX_BODY_POINTS)
230
+ c0 = (across - bodies * unit) / 2 + (column * (self.width + COLUMN_GAP) + slot.start) * unit
231
+ return a0, a0 + self.spans[group] * points_per_bp, c0, c0 + slot.size * unit
232
+
233
+ def extent(self, points_per_bp: float, points_per_body: float) -> tuple[float, float]:
234
+ """Return the along and across size of the grid at a given scale.
235
+
236
+ Parameters
237
+ ----------
238
+ points_per_bp : float
239
+ Along scale.
240
+ points_per_body : float
241
+ Body width in points.
242
+
243
+ Returns
244
+ -------
245
+ tuple of float
246
+ Along and across size in points.
247
+
248
+ Examples
249
+ --------
250
+ >>> Grid((1000.0,), 2, slots([], copies=1, after=[])).extent(0.1, 10)
251
+ (100.0, 30.0)
252
+ """
253
+ along = sum(self.spans) * points_per_bp + (len(self.spans) - 1) * GROUP_GAP
254
+ across = (self.columns * self.width + (self.columns - 1) * COLUMN_GAP) * points_per_body
255
+ return along, across
pqplot/outline.py ADDED
@@ -0,0 +1,96 @@
1
+ """Chromosome outline geometry in bp, free of any drawing library.
2
+
3
+ Positions run along the chromosome in bp. Positions across it are in body
4
+ half-widths, so the body edges sit at -1 and 1.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+ from pqplot.genome import Chromosome
12
+
13
+ PINCH = 0.42
14
+ """Half-width at the centromere midpoint."""
15
+ STALK = 0.55
16
+ """Half-width along a stalk."""
17
+ KNOB = 1.6
18
+ """Length of a telocentric knob from position 0 to its waist, in caps."""
19
+ WAIST = 0.9
20
+ """Shortest half-length of the centromere waist, in caps."""
21
+ ARC = 25
22
+
23
+
24
+ def vertices(
25
+ chromosome: Chromosome, cap: float, *, stalks: bool = True
26
+ ) -> tuple[np.ndarray, np.ndarray]:
27
+ """Return the closed outline of a chromosome body.
28
+
29
+ The outline has round telomere caps, a waist at the centromere and
30
+ narrow stalks. A telocentric chromosome gets a round knob at position
31
+ 0, with its waist `KNOB` caps in. An unknown centromere gets no waist.
32
+
33
+ Parameters
34
+ ----------
35
+ chromosome : Chromosome
36
+ Chromosome to outline.
37
+ cap : float
38
+ Cap radius in bp. Pass the body half-width converted to bp, so caps
39
+ come out round. It shrinks to fit a short chromosome.
40
+ stalks : bool, default True
41
+ Whether ``stalk`` bands narrow the body.
42
+
43
+ Raises
44
+ ------
45
+ ValueError
46
+ If the cap is not positive.
47
+
48
+ Returns
49
+ -------
50
+ along, across : numpy.ndarray
51
+ Vertex positions along the chromosome in bp and across it in
52
+ half-widths. The ring runs from the left tip over the top edge and
53
+ back along the bottom edge. It does not repeat its first vertex.
54
+
55
+ Examples
56
+ --------
57
+ >>> along, across = vertices(Chromosome("chr1", 1000, centromere=(480, 520)), cap=10)
58
+ >>> float(along.min()), float(along.max()), float(across.max())
59
+ (0.0, 1000.0, 1.0)
60
+ """
61
+ if cap <= 0:
62
+ raise ValueError(f"cap must be positive, got {cap}")
63
+ cap = min(cap, chromosome.length / 2)
64
+ lo, hi = cap, chromosome.length - cap
65
+ mid, waist = None, WAIST * cap
66
+ if chromosome.telocentric:
67
+ mid = KNOB * cap
68
+ waist = mid - lo
69
+ elif chromosome.centromere is not None:
70
+ mid = sum(chromosome.centromere) / 2
71
+ waist = max(waist, np.ptp(chromosome.centromere) / 2)
72
+ spans = [(b.start, b.end) for b in chromosome.bands if stalks and b.stain.name == "stalk"]
73
+
74
+ def width(s: float, right: bool) -> float:
75
+ w = 1.0 if mid is None else 1 - (1 - PINCH) * max(0.0, 1 - abs(s - mid) / waist)
76
+ for s0, s1 in spans:
77
+ if (s0 <= s < s1) if right else (s0 < s <= s1):
78
+ w = min(w, STALK)
79
+ return w
80
+
81
+ breaks = [lo, hi, *(b for span in spans for b in span)]
82
+ if mid is not None:
83
+ breaks += [mid - waist, mid, mid + waist]
84
+ edge = []
85
+ for s in sorted({float(np.clip(b, lo, hi)) for b in breaks}):
86
+ left, right = width(s, right=False), width(s, right=True)
87
+ edge += [(s, left)] if left == right else [(s, left), (s, right)]
88
+ s, w = np.array(edge).T
89
+ tip = np.linspace(np.pi, np.pi / 2, ARC // 2 + 1)[:-1]
90
+ turn = np.linspace(np.pi / 2, -np.pi / 2, ARC)
91
+ tail = np.linspace(-np.pi / 2, -np.pi, ARC // 2 + 1)[1:-1]
92
+ along = np.concatenate(
93
+ [lo + cap * np.cos(tip), s, hi + cap * np.cos(turn), s[::-1], lo + cap * np.cos(tail)]
94
+ )
95
+ across = np.concatenate([np.sin(tip), w, np.sin(turn), -w[::-1], np.sin(tail)])
96
+ return along, across
pqplot/panels.py ADDED
@@ -0,0 +1,80 @@
1
+ """Child panels of a host Axes, placed at draw time."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Literal
7
+
8
+ from matplotlib.axes import Axes
9
+ from matplotlib.transforms import Bbox
10
+
11
+ Cell = Callable[[float, float], tuple[float, float, float, float]]
12
+ """Maps the host's along and across size in points to a panel rectangle.
13
+
14
+ The rectangle is ``(along_start, along_end, across_start, across_end)`` in
15
+ points from the host's along and across starts.
16
+ """
17
+ Orientation = Literal["horizontal", "vertical"]
18
+
19
+
20
+ def add_panel(host: Axes, cell: Cell, orientation: Orientation, **kwargs) -> Axes:
21
+ """Add a child Axes that `cell` places inside the host at each draw.
22
+
23
+ The along axis runs down a vertical host and right across a horizontal
24
+ one. The across axis runs right across a vertical host and down a
25
+ horizontal one. The panel is a child of the host, so it is not in
26
+ ``figure.axes``, and layout engines count it in the host's tight bbox.
27
+
28
+ Parameters
29
+ ----------
30
+ host : matplotlib.axes.Axes
31
+ Axes that holds the panel.
32
+ cell : callable
33
+ Rectangle of the panel for a given host size, as in `Cell`.
34
+ orientation : {"horizontal", "vertical"}
35
+ Direction of the along axis.
36
+ **kwargs
37
+ Passed to `matplotlib.axes.Axes.inset_axes`, such as ``sharex``.
38
+
39
+ Returns
40
+ -------
41
+ matplotlib.axes.Axes
42
+
43
+ Examples
44
+ --------
45
+ >>> import matplotlib.pyplot as plt
46
+ >>> fig, host = plt.subplots()
47
+ >>> panel = add_panel(host, lambda along, across: (0, along / 2, 0, across), "vertical")
48
+ >>> panel in host.child_axes
49
+ True
50
+ """
51
+ panel = host.inset_axes([0, 0, 1, 1], **kwargs)
52
+ panel.set_axes_locator(_CellLocator(host, cell, orientation))
53
+ return panel
54
+
55
+
56
+ class _CellLocator:
57
+ """Turns a cell in points into the panel's figure position."""
58
+
59
+ def __init__(self, host: Axes, cell: Cell, orientation: Orientation):
60
+ self.host = host
61
+ self.cell = cell
62
+ self.orientation = orientation
63
+
64
+ def __call__(self, ax: Axes, renderer) -> Bbox:
65
+ box = self.host.bbox
66
+ pixels_per_point = self.host.figure.dpi / 72
67
+ width, height = box.width / pixels_per_point, box.height / pixels_per_point
68
+ if self.orientation == "vertical":
69
+ a0, a1, c0, c1 = self.cell(height, width)
70
+ x0, x1, y0, y1 = c0, c1, height - a1, height - a0
71
+ else:
72
+ a0, a1, c0, c1 = self.cell(width, height)
73
+ x0, x1, y0, y1 = a0, a1, height - c1, height - c0
74
+ extents = [
75
+ box.x0 + x0 * pixels_per_point,
76
+ box.y0 + y0 * pixels_per_point,
77
+ box.x0 + x1 * pixels_per_point,
78
+ box.y0 + y1 * pixels_per_point,
79
+ ]
80
+ return Bbox.from_extents(*extents).transformed(self.host.figure.transSubfigure.inverted())
pqplot/spans.py ADDED
@@ -0,0 +1,89 @@
1
+ """Boxes over spans along a chromosome, with a minimum width in points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ import numpy as np
8
+ from matplotlib.collections import PolyCollection
9
+
10
+
11
+ class Spans(PolyCollection):
12
+ """Boxes over spans along one axis, at least `min_points` wide on screen.
13
+
14
+ Each span covers ``[start, end]`` along the axis and ``across`` on the
15
+ other axis, in the collection's transform. At each draw, spans narrower
16
+ than `min_points` widen about their middle, so they stay visible at any
17
+ scale.
18
+
19
+ Parameters
20
+ ----------
21
+ starts, ends : array-like of float
22
+ Spans along the axis, in data coordinates.
23
+ across : tuple of float
24
+ Low and high edge on the other axis.
25
+ orientation : {"horizontal", "vertical"}
26
+ Direction of the along axis. Horizontal puts it on x.
27
+ min_points : float
28
+ Smallest drawn width, in points. Zero keeps every span as given.
29
+ **kwargs
30
+ Passed to `matplotlib.collections.PolyCollection`, such as
31
+ ``transform`` or ``facecolors``.
32
+
33
+ Attributes
34
+ ----------
35
+ starts, ends : numpy.ndarray
36
+ Spans as given, before widening.
37
+
38
+ Examples
39
+ --------
40
+ >>> import matplotlib.pyplot as plt
41
+ >>> fig, ax = plt.subplots()
42
+ >>> spans = Spans([0, 50], [10, 60], (0, 1), orientation="horizontal", min_points=2)
43
+ >>> len(ax.add_collection(spans).get_paths())
44
+ 2
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ starts: object,
50
+ ends: object,
51
+ across: tuple[float, float],
52
+ *,
53
+ orientation: Literal["horizontal", "vertical"],
54
+ min_points: float,
55
+ **kwargs,
56
+ ):
57
+ self.starts = np.asarray(starts, dtype=float)
58
+ self.ends = np.asarray(ends, dtype=float)
59
+ self.across = across
60
+ self.orientation = orientation
61
+ self.min_points = min_points
62
+ super().__init__(self._boxes(self.starts, self.ends), **kwargs)
63
+
64
+ def draw(self, renderer) -> None:
65
+ """Widen narrow spans for the current scale, then draw.
66
+
67
+ Examples
68
+ --------
69
+ >>> import matplotlib.pyplot as plt
70
+ >>> fig, ax = plt.subplots()
71
+ >>> _ = ax.add_collection(Spans([0], [1], (0, 1), orientation="vertical", min_points=2))
72
+ >>> fig.draw_without_rendering()
73
+ """
74
+ if self.min_points > 0:
75
+ zero, one = self._boxes(np.zeros(1), np.ones(1))[0, :2]
76
+ p0, p1 = self.get_transform().transform([zero, one])
77
+ min_half = renderer.points_to_pixels(self.min_points) / np.hypot(*(p1 - p0)) / 2
78
+ mid = (self.starts + self.ends) / 2
79
+ half = np.maximum((self.ends - self.starts) / 2, min_half)
80
+ self.set_verts(self._boxes(mid - half, mid + half))
81
+ super().draw(renderer)
82
+
83
+ def _boxes(self, starts: np.ndarray, ends: np.ndarray) -> np.ndarray:
84
+ """Return one quad per span, starting with its two low-edge corners."""
85
+ along = np.stack([starts, ends, ends, starts], axis=1)
86
+ low, high = self.across
87
+ across = np.broadcast_to([low, low, high, high], along.shape)
88
+ pair = (along, across) if self.orientation == "horizontal" else (across, along)
89
+ return np.stack(pair, axis=-1)