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/karyogram.py ADDED
@@ -0,0 +1,595 @@
1
+ """Whole-genome karyograms built from child panels."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass
7
+ from functools import partial
8
+ from typing import Literal
9
+
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ from matplotlib.artist import Artist
13
+ from matplotlib.axes import Axes
14
+ from matplotlib.cm import ScalarMappable
15
+ from matplotlib.colorbar import Colorbar
16
+ from matplotlib.colors import Colormap, Normalize
17
+ from matplotlib.figure import Figure
18
+ from matplotlib.legend import Legend
19
+ from matplotlib.transforms import Bbox
20
+ from matplotlib.typing import ColorType
21
+
22
+ from pqplot import layout
23
+ from pqplot.colors import category_colors, value_scale
24
+ from pqplot.columns import column, rows_by_chrom
25
+ from pqplot.genome import Chromosome, Genome, chrom_key
26
+ from pqplot.ideograms import Ideogram
27
+ from pqplot.panels import Orientation, add_panel
28
+ from pqplot.tracks import TrackPanels, style_track
29
+
30
+ BODY_POINTS = 7.0
31
+ """Body width in a karyogram's own figure, in points."""
32
+ LONGEST_POINTS = {"vertical": 180.0, "horizontal": 432.0}
33
+ """Length of the longest group in a karyogram's own figure, in points."""
34
+ NAME_POINTS = {"vertical": 16.0, "horizontal": 40.0}
35
+ """Room for chromosome names in a karyogram's own figure, in points."""
36
+ PAD_POINTS = 6.0
37
+ """Room for the layout engine's padding in a karyogram's own figure, in points."""
38
+ COLORBAR_POINTS = (7.0, 144.0)
39
+ """Width and longest length of a colorbar, in points."""
40
+ COLORBAR_GAP = 8.0
41
+ """Space between the karyogram and its colorbar, in points."""
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Track:
46
+ """A strip of data beside every chromosome of a karyogram.
47
+
48
+ Parameters
49
+ ----------
50
+ name : str
51
+ Name used to find the track's panels.
52
+ side : {"before", "after"}, default "before"
53
+ Side of the body, in order across the chromosome column. Before is
54
+ left of a vertical karyogram and above a horizontal one.
55
+ size : float, default 2
56
+ Width across the chromosome, in body widths.
57
+
58
+ Examples
59
+ --------
60
+ >>> Track("cnv", side="after", size=1.5).size
61
+ 1.5
62
+ """
63
+
64
+ name: str
65
+ side: Literal["before", "after"] = "before"
66
+ size: float = 2.0
67
+
68
+ def __post_init__(self):
69
+ if self.side not in ("before", "after"):
70
+ raise ValueError(f"side must be before or after, got {self.side!r}")
71
+
72
+
73
+ class Karyogram:
74
+ """Chromosomes of a genome side by side, each in its own panel.
75
+
76
+ The host Axes is hidden. Each chromosome gets a body panel and one panel
77
+ per track. Panels are plain Axes with positions in bp, so matplotlib
78
+ calls draw on them directly. They are placed at draw time and follow
79
+ resizes and layout engines. Every panel shares one bp scale.
80
+
81
+ Parameters
82
+ ----------
83
+ genome : Genome
84
+ Chromosomes to draw.
85
+ ax : matplotlib.axes.Axes, optional
86
+ Host Axes to fill. By default, a new figure sized to the content.
87
+ orientation : {"vertical", "horizontal"}, default "vertical"
88
+ Direction of the chromosomes. A horizontal karyogram is the vertical
89
+ one transposed.
90
+ groups : int or sequence of sequence of str, default 1
91
+ Number of groups to wrap the chromosomes into, or the chromosome
92
+ names of each group. Groups stack down a vertical karyogram and sit
93
+ side by side in a horizontal one.
94
+ align : {"start", "centromere", "end"}, default "start"
95
+ What lines up within a group: the starts, the centromeres or the
96
+ ends. Starts are at the top of a vertical karyogram and on the left
97
+ of a horizontal one.
98
+ chroms : sequence of str, optional
99
+ Chromosomes to draw, in order. By default, all of `genome`. Not
100
+ allowed with explicit `groups`.
101
+ copies : int, default 1
102
+ Copies of each chromosome drawn side by side, such as 2 for
103
+ homologs.
104
+ bands : bool, default True
105
+ Whether to draw bands.
106
+ tracks : sequence of Track, optional
107
+ Data tracks beside every chromosome, in order across it.
108
+
109
+ Raises
110
+ ------
111
+ ValueError
112
+ If an argument is out of range or track names repeat.
113
+ KeyError
114
+ If a chromosome is not in `genome`.
115
+
116
+ Attributes
117
+ ----------
118
+ ax : matplotlib.axes.Axes
119
+ Host Axes.
120
+
121
+ Examples
122
+ --------
123
+ >>> from pqplot import Genome
124
+ >>> kary = Karyogram(Genome.bundled("hg38"), groups=2, align="centromere")
125
+ >>> len(kary.panels())
126
+ 24
127
+ """
128
+
129
+ def __init__(
130
+ self,
131
+ genome: Genome,
132
+ ax: Axes | None = None,
133
+ *,
134
+ orientation: Orientation = "vertical",
135
+ groups: int | Sequence[Sequence[str]] = 1,
136
+ align: layout.Align = "start",
137
+ chroms: Sequence[str] | None = None,
138
+ copies: int = 1,
139
+ bands: bool = True,
140
+ tracks: Sequence[Track] = (),
141
+ ):
142
+ if orientation not in ("horizontal", "vertical"):
143
+ raise ValueError(f"orientation must be horizontal or vertical, got {orientation!r}")
144
+ if copies < 1:
145
+ raise ValueError(f"copies must be at least 1, got {copies}")
146
+ names = [t.name for t in tracks]
147
+ if len(set(names)) < len(names):
148
+ raise ValueError(f"track names must be unique, got {names}")
149
+ if isinstance(groups, int):
150
+ chosen = [genome[c] for c in chroms] if chroms is not None else list(genome)
151
+ grouped = layout.wrap(chosen, groups)
152
+ elif chroms is not None:
153
+ raise ValueError("pass chroms or explicit groups, not both")
154
+ else:
155
+ grouped = [[genome[c] for c in group] for group in groups]
156
+ limits = [layout.bounds(group, align) for group in grouped]
157
+ grid = layout.Grid(
158
+ tuple(bounds[0][1] - bounds[0][0] for bounds in limits),
159
+ max(len(group) for group in grouped),
160
+ layout.slots(
161
+ [(t.name, t.size) for t in tracks if t.side == "before"],
162
+ copies,
163
+ [(t.name, t.size) for t in tracks if t.side == "after"],
164
+ ),
165
+ )
166
+ self._sized_to_content = ax is None
167
+ if ax is None:
168
+ ax = _own_axes(grid, orientation)
169
+ ax.set_axis_off()
170
+ self.ax = ax
171
+ self._panels: dict[tuple[str, str | None], Axes] = {}
172
+ self._ideograms: dict[str, list[Ideogram]] = {}
173
+ self._legend: dict[str, Artist] = {}
174
+ self._orientation = orientation
175
+ self._tracks = {t.name: t for t in tracks}
176
+ body = next(s for s in grid.slots if s.track is None)
177
+ tracks_first: dict[str, Axes] = {}
178
+ along, value = ("sharey", "sharex") if orientation == "vertical" else ("sharex", "sharey")
179
+ for g, group in enumerate(grouped):
180
+ for j, (chromosome, (lo, hi)) in enumerate(zip(group, limits[g], strict=True)):
181
+ key = chrom_key(chromosome.name)
182
+ panel = add_panel(ax, partial(grid.cell, g, j, body), orientation)
183
+ self._ideograms[key] = _draw_body(
184
+ panel, chromosome, orientation, copies, bands, lo, hi
185
+ )
186
+ self._panels[key, None] = panel
187
+ for slot in grid.slots:
188
+ if slot.track is None:
189
+ continue
190
+ first = tracks_first.get(slot.track)
191
+ track = add_panel(
192
+ ax,
193
+ partial(grid.cell, g, j, slot),
194
+ orientation,
195
+ **{along: panel, value: first},
196
+ )
197
+ edge = 0 if orientation == "vertical" else len(grouped) - 1
198
+ style_track(track, orientation, labels=(g, j) == (edge, 0))
199
+ tracks_first.setdefault(slot.track, track)
200
+ self._panels[key, slot.track] = track
201
+
202
+ @property
203
+ def figure(self) -> Figure:
204
+ """Figure that holds the karyogram.
205
+
206
+ Examples
207
+ --------
208
+ >>> from pqplot import Genome
209
+ >>> Karyogram(Genome.bundled("mm39")).figure.get_layout_engine() is not None
210
+ True
211
+ """
212
+ return self.ax.figure
213
+
214
+ def panel(self, chrom: str, track: str | None = None) -> Axes:
215
+ """Return the panel of one chromosome.
216
+
217
+ Parameters
218
+ ----------
219
+ chrom : str
220
+ Chromosome name. Names match across styles.
221
+ track : str, optional
222
+ Track name. By default, the body panel.
223
+
224
+ Returns
225
+ -------
226
+ matplotlib.axes.Axes
227
+ Plain Axes with positions in bp along the chromosome.
228
+
229
+ Raises
230
+ ------
231
+ KeyError
232
+ If the chromosome or track is not drawn.
233
+
234
+ Examples
235
+ --------
236
+ >>> from pqplot import Genome
237
+ >>> hg38 = Genome.bundled("hg38")
238
+ >>> kary = Karyogram(hg38, orientation="horizontal")
239
+ >>> kary.panel("chr17").get_xlim() == (0, hg38["chr1"].length)
240
+ True
241
+ """
242
+ try:
243
+ return self._panels[chrom_key(chrom), track]
244
+ except KeyError:
245
+ raise KeyError(f"no panel for chromosome {chrom!r} and track {track!r}") from None
246
+
247
+ def panels(self, track: str | None = None) -> dict[str, Axes]:
248
+ """Return the panels of one track for every chromosome, in order.
249
+
250
+ Parameters
251
+ ----------
252
+ track : str, optional
253
+ Track name. By default, the body panels.
254
+
255
+ Returns
256
+ -------
257
+ dict of str to matplotlib.axes.Axes
258
+ Panels keyed by chromosome name.
259
+
260
+ Examples
261
+ --------
262
+ >>> from pqplot import Genome
263
+ >>> kary = Karyogram(Genome.bundled("hg38"), chroms=["1", "2"], tracks=[Track("cnv")])
264
+ >>> list(kary.panels("cnv"))
265
+ ['chr1', 'chr2']
266
+ """
267
+ return {
268
+ ideograms[0].chromosome.name: self._panels[key, track]
269
+ for key, ideograms in self._ideograms.items()
270
+ if (key, track) in self._panels
271
+ }
272
+
273
+ def track(self, name: str) -> TrackPanels:
274
+ """Return the panels of one track, to draw data into.
275
+
276
+ Parameters
277
+ ----------
278
+ name : str
279
+ Track name.
280
+
281
+ Returns
282
+ -------
283
+ TrackPanels
284
+
285
+ Raises
286
+ ------
287
+ KeyError
288
+ If the karyogram has no such track.
289
+
290
+ Examples
291
+ --------
292
+ >>> from pqplot import Genome
293
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("cnv")])
294
+ >>> points = kary.track("cnv").scatter({"chrom": ["chr1"], "pos": [5e6], "value": [0.3]})
295
+ >>> list(points)
296
+ ['chr1']
297
+ """
298
+ if name not in self._tracks:
299
+ raise KeyError(f"no track {name!r}")
300
+ side = self._tracks[name].side
301
+ return TrackPanels(self.panels(name), self._orientation, side, self._legend)
302
+
303
+ def ideograms(self, chrom: str) -> list[Ideogram]:
304
+ """Return the drawn copies of one chromosome.
305
+
306
+ Parameters
307
+ ----------
308
+ chrom : str
309
+ Chromosome name. Names match across styles.
310
+
311
+ Returns
312
+ -------
313
+ list of Ideogram
314
+ One per copy, in order across the body panel.
315
+
316
+ Examples
317
+ --------
318
+ >>> from pqplot import Genome
319
+ >>> len(Karyogram(Genome.bundled("hg38"), copies=2).ideograms("chrX"))
320
+ 2
321
+ """
322
+ return self._ideograms[chrom_key(chrom)]
323
+
324
+ def paint(
325
+ self,
326
+ data: object = None,
327
+ *,
328
+ chrom: object = "chrom",
329
+ start: object = None,
330
+ end: object = None,
331
+ color: object = None,
332
+ value: object = None,
333
+ palette: Mapping[object, ColorType] | None = None,
334
+ cmap: str | Colormap | None = None,
335
+ norm: Normalize | None = None,
336
+ copy: object = None,
337
+ ) -> ScalarMappable | None:
338
+ """Fill chromosome bodies by category or by value.
339
+
340
+ Touching spans of one category merge into one. Small spans keep a
341
+ minimum width in points and draw over larger ones. Rows on
342
+ chromosomes that are not drawn are skipped.
343
+
344
+ Each column argument is a column name in `data` or the values
345
+ themselves.
346
+
347
+ Parameters
348
+ ----------
349
+ data : DataFrame or dict, optional
350
+ Table with one row per span, such as a polars or pandas
351
+ DataFrame.
352
+ chrom : str or array-like, default "chrom"
353
+ Chromosome of each span. Names match across styles.
354
+ start, end : str or array-like, optional
355
+ Span in bp. Without them, each row fills its whole chromosome.
356
+ color : str or array-like, optional
357
+ Category of each span. Categories get colors from `palette` and
358
+ appear in `legend`. Without `color` or `value`, every span gets
359
+ the first color of the theme's cycle.
360
+ value : str or array-like, optional
361
+ Number for each span, colored through `cmap` and `norm`.
362
+ palette : mapping, optional
363
+ Color of each category, in legend order. By default, the
364
+ theme's color cycle in order of first appearance.
365
+ cmap : str or matplotlib.colors.Colormap, optional
366
+ Colormap for `value`. By default, the theme's.
367
+ norm : matplotlib.colors.Normalize, optional
368
+ Scaling of `value`. By default, its minimum to its maximum.
369
+ copy : str or array-like, optional
370
+ Copy of each span, such as the haplotype. Sorted levels map to
371
+ copies left to right. Without it, spans fill every copy.
372
+
373
+ Returns
374
+ -------
375
+ matplotlib.cm.ScalarMappable or None
376
+ The mapping for `value`, for a colorbar. None for categories.
377
+
378
+ Raises
379
+ ------
380
+ ValueError
381
+ If both `color` and `value` are given, only one of `start` and
382
+ `end` is given, or `copy` has more levels than drawn copies.
383
+ KeyError
384
+ If `palette` lacks a category.
385
+
386
+ Examples
387
+ --------
388
+ >>> from pqplot import Genome
389
+ >>> kary = Karyogram(Genome.bundled("hg38"), groups=2)
390
+ >>> segments = {"chrom": ["chr1", "chr7"], "start": [0, 5e6], "end": [4e7, 9e6],
391
+ ... "state": ["gain", "loss"]}
392
+ >>> kary.paint(segments, start="start", end="end", color="state")
393
+ >>> bins = {"chrom": ["chr2"] * 2, "start": [0, 1e6], "end": [1e6, 2e6], "n": [3, 9]}
394
+ >>> heat = kary.paint(bins, start="start", end="end", value="n", cmap="magma")
395
+ >>> heat.norm.vmax
396
+ 9.0
397
+ """
398
+ if color is not None and value is not None:
399
+ raise ValueError("pass color or value, not both")
400
+ if (start is None) != (end is None):
401
+ raise ValueError("pass start and end together, or neither")
402
+ chroms = column(data, chrom)
403
+ copy_index = None
404
+ if copy is not None:
405
+ levels, copy_index = np.unique(column(data, copy), return_inverse=True)
406
+ copies = len(next(iter(self._ideograms.values())))
407
+ if len(levels) > copies:
408
+ raise ValueError(f"copy has {len(levels)} levels for {copies} copies")
409
+ mappable = None
410
+ if value is not None:
411
+ values = column(data, value).astype(float)
412
+ mappable = value_scale(values, cmap, norm)
413
+ # Each row is its own category, so no spans merge.
414
+ codes, swatches = np.arange(len(values)), mappable.to_rgba(values)
415
+ else:
416
+ categories = None if color is None else column(data, color)
417
+ codes, swatches = category_colors(categories, len(chroms), palette, self._legend)
418
+ starts = None if start is None else column(data, start).astype(float)
419
+ ends = None if end is None else column(data, end).astype(float)
420
+ for key, rows in rows_by_chrom(chroms).items():
421
+ for k, ideo in enumerate(self._ideograms.get(key, [])):
422
+ mine = rows if copy_index is None else rows[copy_index[rows] == k]
423
+ if len(mine) == 0:
424
+ continue
425
+ if starts is None:
426
+ s0, s1 = np.zeros(len(mine)), np.full(len(mine), ideo.chromosome.length)
427
+ else:
428
+ s0, s1 = starts[mine], ends[mine]
429
+ s0, s1, c = _merge(s0, s1, codes[mine])
430
+ ideo.paint(s0, s1, swatches[c])
431
+ return mappable
432
+
433
+ def colorbar(self, mappable: ScalarMappable, label: str | None = None, **kwargs) -> Colorbar:
434
+ """Draw a colorbar right of the karyogram, top-aligned.
435
+
436
+ The bar is `COLORBAR_POINTS` in size, whatever the size of the
437
+ karyogram. When the karyogram made its own figure, the figure widens
438
+ to hold the bar, so the chromosomes keep their size. A legend also
439
+ sits at the top right, so move one of them when drawing both.
440
+
441
+ Parameters
442
+ ----------
443
+ mappable : matplotlib.cm.ScalarMappable
444
+ Color scale, such as the return value of `paint` or
445
+ `TrackPanels.heatmap`.
446
+ label : str, optional
447
+ Label along the bar.
448
+ **kwargs
449
+ Passed to `matplotlib.figure.Figure.colorbar`.
450
+
451
+ Returns
452
+ -------
453
+ matplotlib.colorbar.Colorbar
454
+
455
+ Examples
456
+ --------
457
+ >>> from pqplot import Genome
458
+ >>> kary = Karyogram(Genome.bundled("hg38"), chroms=["1"])
459
+ >>> bins = {"chrom": ["1"], "start": [0], "end": [1e6], "n": [7.0]}
460
+ >>> heat = kary.paint(bins, start="start", end="end", value="n")
461
+ >>> kary.colorbar(heat, label="cCREs per Mb").ax.get_ylabel()
462
+ 'cCREs per Mb'
463
+ """
464
+ cax = self.ax.inset_axes([1, 0, 0, 1])
465
+ cax.set_axes_locator(partial(_beside, self.ax))
466
+ bar = self.figure.colorbar(mappable, cax=cax, label=label, **kwargs)
467
+ if self._sized_to_content:
468
+ room = cax.get_tightbbox().width / self.figure.dpi + COLORBAR_GAP / 72
469
+ self.figure.set_figwidth(self.figure.get_figwidth() + room)
470
+ return bar
471
+
472
+ def legend(self, title: str | None = None, **kwargs) -> Legend:
473
+ """Draw a legend of the categories painted or marked so far.
474
+
475
+ Parameters
476
+ ----------
477
+ title : str, optional
478
+ Legend title.
479
+ **kwargs
480
+ Passed to `matplotlib.axes.Axes.legend`. By default, the
481
+ legend sits outside the host Axes, at its top right, without a
482
+ frame.
483
+
484
+ When the karyogram made its own figure, the figure widens to hold
485
+ the legend, so the chromosomes keep their size.
486
+
487
+ Returns
488
+ -------
489
+ matplotlib.legend.Legend
490
+
491
+ Examples
492
+ --------
493
+ >>> from pqplot import Genome
494
+ >>> kary = Karyogram(Genome.bundled("hg38"), chroms=["1"])
495
+ >>> kary.paint({"chrom": ["1"], "split": ["test"]}, color="split")
496
+ >>> [t.get_text() for t in kary.legend(title="Split").get_texts()]
497
+ ['test']
498
+ """
499
+ old = self.ax.get_legend()
500
+ room = _inches(old) if old else -PAD_POINTS / 72
501
+ options = {"loc": "upper left", "bbox_to_anchor": (1, 1), "frameon": False}
502
+ legend = self.ax.legend(
503
+ list(self._legend.values()), list(self._legend), title=title, **options | kwargs
504
+ )
505
+ if self._sized_to_content:
506
+ self.figure.set_figwidth(self.figure.get_figwidth() + _inches(legend) - room)
507
+ return legend
508
+
509
+
510
+ def _beside(host: Axes, cax: Axes, renderer) -> Bbox:
511
+ """Place a colorbar right of the host, top-aligned, with a fixed size in points."""
512
+ box = host.bbox
513
+ pixels_per_point = host.figure.dpi / 72
514
+ width, longest = (size * pixels_per_point for size in COLORBAR_POINTS)
515
+ height = min(box.height, longest)
516
+ x0 = box.x1 + COLORBAR_GAP * pixels_per_point
517
+ return Bbox.from_bounds(x0, box.y1 - height, width, height).transformed(
518
+ host.figure.transSubfigure.inverted()
519
+ )
520
+
521
+
522
+ def _inches(artist: Artist) -> float:
523
+ """Return the width of an artist in inches."""
524
+ return artist.get_window_extent().width / artist.figure.dpi
525
+
526
+
527
+ def _merge(
528
+ starts: np.ndarray, ends: np.ndarray, codes: np.ndarray
529
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
530
+ """Merge spans that touch or overlap the previous span of the same code, by start."""
531
+ order = np.argsort(starts, kind="stable")
532
+ starts, ends, codes = starts[order], ends[order], codes[order]
533
+ head = np.ones(len(starts), dtype=bool)
534
+ head[1:] = (codes[1:] != codes[:-1]) | (starts[1:] > ends[:-1])
535
+ heads = np.flatnonzero(head)
536
+ return starts[heads], np.maximum.reduceat(ends, heads), codes[heads]
537
+
538
+
539
+ def _draw_body(
540
+ panel: Axes,
541
+ chromosome: Chromosome,
542
+ orientation: Orientation,
543
+ copies: int,
544
+ bands: bool,
545
+ lo: float,
546
+ hi: float,
547
+ ) -> list[Ideogram]:
548
+ """Draw the copies of one chromosome and its name into a body panel."""
549
+ ideograms = [
550
+ Ideogram(
551
+ chromosome,
552
+ panel,
553
+ orientation=orientation,
554
+ center=k * (1 + layout.COPY_GAP) + 0.5,
555
+ bands=bands,
556
+ )
557
+ for k in range(copies)
558
+ ]
559
+ across = (0, copies + (copies - 1) * layout.COPY_GAP)
560
+ panel.set_axis_off()
561
+ if orientation == "vertical":
562
+ panel.set(xlim=across, ylim=(hi, lo))
563
+ panel.annotate(
564
+ chromosome.label,
565
+ (0.5, 0),
566
+ xycoords="axes fraction",
567
+ xytext=(0, -3),
568
+ textcoords="offset points",
569
+ ha="center",
570
+ va="top",
571
+ fontsize="small",
572
+ )
573
+ else:
574
+ panel.set(xlim=(lo, hi), ylim=across[::-1])
575
+ panel.annotate(
576
+ chromosome.name,
577
+ (0, 0.5),
578
+ xycoords="axes fraction",
579
+ xytext=(-4, 0),
580
+ textcoords="offset points",
581
+ ha="right",
582
+ va="center",
583
+ fontsize="small",
584
+ )
585
+ return ideograms
586
+
587
+
588
+ def _own_axes(grid: layout.Grid, orientation: Orientation) -> Axes:
589
+ """Make a figure sized so the grid gets its default scale."""
590
+ along, across = grid.extent(LONGEST_POINTS[orientation] / max(grid.spans), BODY_POINTS)
591
+ along += NAME_POINTS[orientation]
592
+ width, height = (across, along) if orientation == "vertical" else (along, across)
593
+ size = ((width + PAD_POINTS) / 72, (height + PAD_POINTS) / 72)
594
+ _, ax = plt.subplots(figsize=size, layout="constrained")
595
+ return ax
pqplot/labels.py ADDED
@@ -0,0 +1,71 @@
1
+ """Label placement along a chromosome, free of any drawing library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def capacity(gap: float, low: float, high: float) -> int:
9
+ """Return how many labels fit between two bounds at a given spacing.
10
+
11
+ Examples
12
+ --------
13
+ >>> capacity(4, 0, 10)
14
+ 3
15
+ """
16
+ return int(np.floor((high - low) / gap + 1e-9)) + 1
17
+
18
+
19
+ def spread(targets: np.ndarray, gap: float, low: float, high: float) -> np.ndarray:
20
+ """Place labels at least `gap` apart, as close to their targets as possible.
21
+
22
+ The result minimizes the squared distance to the targets, keeps their
23
+ order and stays inside the bounds. It uses pool-adjacent-violators
24
+ isotonic regression, so it runs in linear time and is deterministic.
25
+
26
+ Parameters
27
+ ----------
28
+ targets : numpy.ndarray
29
+ Positions the labels point at, sorted.
30
+ gap : float
31
+ Smallest distance between neighboring labels.
32
+ low, high : float
33
+ Bounds of the placed labels.
34
+
35
+ Returns
36
+ -------
37
+ numpy.ndarray
38
+ Label positions, in the order of `targets`.
39
+
40
+ Raises
41
+ ------
42
+ ValueError
43
+ If `targets` is not sorted or more than `capacity` labels are given.
44
+
45
+ Examples
46
+ --------
47
+ >>> spread(np.array([50.0, 50.0, 50.0]), 4, 0, 100).tolist()
48
+ [46.0, 50.0, 54.0]
49
+ """
50
+ if np.any(np.diff(targets) < 0):
51
+ raise ValueError("targets must be sorted")
52
+ if len(targets) > capacity(gap, low, high):
53
+ raise ValueError(f"{len(targets)} labels do not fit {gap} apart in [{low}, {high}]")
54
+ if len(targets) == 0:
55
+ return targets.astype(float)
56
+ steps = gap * np.arange(len(targets))
57
+ return np.clip(_isotonic(targets - steps), low, high - steps[-1]) + steps
58
+
59
+
60
+ def _isotonic(values: np.ndarray) -> np.ndarray:
61
+ """Return the non-decreasing least-squares fit to `values`."""
62
+ means, weights = [], []
63
+ for value in values:
64
+ means.append(float(value))
65
+ weights.append(1)
66
+ while len(means) > 1 and means[-2] > means[-1]:
67
+ m2, w2 = means.pop(), weights.pop()
68
+ m1, w1 = means.pop(), weights.pop()
69
+ means.append((m1 * w1 + m2 * w2) / (w1 + w2))
70
+ weights.append(w1 + w2)
71
+ return np.repeat(means, weights)