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/ideograms.py ADDED
@@ -0,0 +1,638 @@
1
+ """Ideogram artist, single-chromosome plots and genome-wide axis helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ from matplotlib.artist import Artist
10
+ from matplotlib.axes import Axes
11
+ from matplotlib.collections import PolyCollection
12
+ from matplotlib.colors import to_rgba, to_rgba_array
13
+ from matplotlib.patches import PathPatch
14
+ from matplotlib.path import Path
15
+ from matplotlib.text import Text
16
+ from matplotlib.transforms import IdentityTransform
17
+ from matplotlib.typing import ColorType
18
+
19
+ from pqplot import outline
20
+ from pqplot.genome import Chromosome, LinearGenome, Region, Stain, chrom_key
21
+ from pqplot.spans import Spans
22
+
23
+ STAIN_COLORS = {"acen": "#b5524a", "gvar": "#c8d1dc", "stalk": "#7f8fa6"}
24
+ """Colors of stains that are not G-bands. G-bands blend the theme's colors."""
25
+ BODY = 0.12
26
+ """Share of the foreground color in an unbanded body."""
27
+ SHADE = 0.06
28
+ """Share of the foreground color in shaded chromosome spans."""
29
+ BOX = 1.35
30
+ """Half-height of a locus box, in body half-widths."""
31
+ MIN_BOX_POINTS = 3.0
32
+ """Smallest width of a locus box, in points."""
33
+ STRIP_HALF = 0.3
34
+ """Body half-width in a genome strip, as a share of half the Axes height."""
35
+ MIN_PAINT_POINTS = 1.5
36
+ """Smallest width of a painted span, in points."""
37
+ OVERSHOOT = 1.2
38
+
39
+
40
+ class Ideogram(PathPatch):
41
+ """One chromosome drawn in an Axes, with positions in bp.
42
+
43
+ The artist is the chromosome outline. Its round caps and centromere
44
+ waist are sized at draw time, so they stay round after a resize. The
45
+ bands are a separate collection clipped to the outline. Colors come from
46
+ the active theme when the ideogram is made.
47
+
48
+ Parameters
49
+ ----------
50
+ chromosome : Chromosome
51
+ Chromosome to draw.
52
+ ax : matplotlib.axes.Axes
53
+ Axes to draw into.
54
+ orientation : {"horizontal", "vertical"}, default "horizontal"
55
+ Direction of the chromosome. Horizontal puts bp on the x axis.
56
+ offset : float, default 0
57
+ Axis position of the chromosome's position 0.
58
+ center : float, default 0
59
+ Axis position of the body's midline, across the chromosome.
60
+ half : float, default 0.5
61
+ Body half-width in axis units, across the chromosome.
62
+ bands : bool, default True
63
+ Whether to draw bands and stalks. Without them the body is one
64
+ plain span.
65
+ **kwargs
66
+ Passed to `matplotlib.patches.PathPatch` to style the outline.
67
+
68
+ Attributes
69
+ ----------
70
+ chromosome : Chromosome
71
+ The chromosome drawn.
72
+ bands : pqplot.spans.Spans
73
+ Band fills, one polygon per band.
74
+
75
+ Examples
76
+ --------
77
+ >>> import matplotlib.pyplot as plt
78
+ >>> from pqplot import Genome
79
+ >>> fig, ax = plt.subplots()
80
+ >>> ideo = Ideogram(Genome.bundled("hg38")["chr17"], ax)
81
+ >>> len(ideo.bands.get_paths())
82
+ 24
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ chromosome: Chromosome,
88
+ ax: Axes,
89
+ *,
90
+ orientation: Literal["horizontal", "vertical"] = "horizontal",
91
+ offset: float = 0.0,
92
+ center: float = 0.0,
93
+ half: float = 0.5,
94
+ bands: bool = True,
95
+ **kwargs,
96
+ ):
97
+ if orientation not in ("horizontal", "vertical"):
98
+ raise ValueError(f"orientation must be horizontal or vertical, got {orientation!r}")
99
+ kwargs = {
100
+ "facecolor": "none",
101
+ "edgecolor": plt.rcParams["axes.edgecolor"],
102
+ "linewidth": 0.5,
103
+ "zorder": 1.5,
104
+ "gid": f"{chromosome.name}-outline",
105
+ **kwargs,
106
+ }
107
+ super().__init__(Path(np.zeros((1, 2))), clip_on=False, **kwargs)
108
+ self.chromosome = chromosome
109
+ self.orientation = orientation
110
+ self.offset = offset
111
+ self.center = center
112
+ self.half = half
113
+ self._stalks = bands
114
+ ax.add_patch(self)
115
+ ax.autoscale_view()
116
+ starts, ends, colors = _spans(chromosome, bands)
117
+ # A thin edge in each band's own color hides seams in PDF viewers.
118
+ self.bands = Spans(
119
+ starts + offset,
120
+ ends + offset,
121
+ self._overshoot(),
122
+ orientation=orientation,
123
+ min_points=0,
124
+ facecolors=colors,
125
+ edgecolors=colors,
126
+ linewidths=0.25,
127
+ zorder=self.get_zorder() - 0.1,
128
+ gid=f"{chromosome.name}-bands",
129
+ )
130
+ ax.add_collection(self.bands, autolim=False)
131
+ self.bands.set_clip_path(self)
132
+ self.bands.set_clip_box(None)
133
+ if chromosome.telocentric:
134
+ acen = STAIN_COLORS["acen"]
135
+ knob = _Knob(
136
+ self,
137
+ facecolor=acen,
138
+ edgecolor=acen,
139
+ linewidth=0.25,
140
+ zorder=self.get_zorder() - 0.05,
141
+ gid=f"{chromosome.name}-knob",
142
+ )
143
+ ax.add_artist(knob)
144
+ knob.set_clip_path(self)
145
+ knob.set_clip_box(None)
146
+
147
+ def xy(self, along: object, across: object) -> np.ndarray:
148
+ """Map chromosome coordinates to data coordinates.
149
+
150
+ Parameters
151
+ ----------
152
+ along : array-like of float
153
+ Positions along the chromosome in bp.
154
+ across : array-like of float
155
+ Positions across it in body half-widths. The body edges are at
156
+ -1 and 1.
157
+
158
+ Returns
159
+ -------
160
+ numpy.ndarray
161
+ Data coordinates with a last axis of length 2.
162
+
163
+ Examples
164
+ --------
165
+ >>> import matplotlib.pyplot as plt
166
+ >>> from pqplot import Chromosome
167
+ >>> fig, ax = plt.subplots()
168
+ >>> Ideogram(Chromosome("chr1", 100), ax, offset=10, half=0.4).xy([5], [1]).tolist()
169
+ [[15.0, 0.4]]
170
+ """
171
+ along, across = np.broadcast_arrays(
172
+ self.offset + np.asarray(along, dtype=float),
173
+ self.center + self.half * np.asarray(across, dtype=float),
174
+ )
175
+ pair = (along, across) if self.orientation == "horizontal" else (across, along)
176
+ return np.stack(pair, axis=-1)
177
+
178
+ def paint(self, starts: object, ends: object, colors: object, **kwargs) -> Spans:
179
+ """Fill spans of the body with color, over the bands.
180
+
181
+ Spans narrower than `MIN_PAINT_POINTS` widen about their middle at
182
+ draw time, so small spans stay visible. Narrower spans draw over
183
+ wider ones. The fills are clipped to the outline and sit under a
184
+ telocentric knob.
185
+
186
+ Parameters
187
+ ----------
188
+ starts, ends : array-like of float
189
+ Spans along the chromosome in bp.
190
+ colors : color or sequence of color
191
+ One color for every span, or one per span.
192
+ **kwargs
193
+ Passed to `matplotlib.collections.PolyCollection`.
194
+
195
+ Returns
196
+ -------
197
+ pqplot.spans.Spans
198
+ The fills, widest first.
199
+
200
+ Raises
201
+ ------
202
+ ValueError
203
+ If the number of colors matches neither 1 nor the spans.
204
+
205
+ Examples
206
+ --------
207
+ >>> from pqplot import Genome
208
+ >>> ideo = ideogram(Genome.bundled("hg38")["chr9"])
209
+ >>> fills = ideo.paint([0, 1e8], [4e7, 1.2e8], ["tab:red", "tab:blue"])
210
+ >>> len(fills.get_facecolors())
211
+ 2
212
+ """
213
+ starts, ends = np.asarray(starts, dtype=float), np.asarray(ends, dtype=float)
214
+ colors = to_rgba_array(colors)
215
+ if len(colors) not in (1, len(starts)):
216
+ raise ValueError(f"got {len(colors)} colors for {len(starts)} spans")
217
+ order = np.argsort(starts - ends, kind="stable")
218
+ if len(colors) > 1:
219
+ colors = colors[order]
220
+ kwargs = {
221
+ "facecolors": colors,
222
+ "edgecolors": colors,
223
+ "linewidths": 0.25,
224
+ "zorder": self.get_zorder() - 0.08,
225
+ "gid": f"{self.chromosome.name}-paint",
226
+ **kwargs,
227
+ }
228
+ fills = Spans(
229
+ self.offset + starts[order],
230
+ self.offset + ends[order],
231
+ self._overshoot(),
232
+ orientation=self.orientation,
233
+ min_points=MIN_PAINT_POINTS,
234
+ **kwargs,
235
+ )
236
+ self.axes.add_collection(fills, autolim=False)
237
+ fills.set_clip_path(self)
238
+ fills.set_clip_box(None)
239
+ return fills
240
+
241
+ def get_path(self) -> Path:
242
+ """Return the outline, sized for the current Axes scale.
243
+
244
+ Examples
245
+ --------
246
+ >>> import matplotlib.pyplot as plt
247
+ >>> from pqplot import Chromosome
248
+ >>> fig, ax = plt.subplots()
249
+ >>> Ideogram(Chromosome("chr1", 100), ax).get_path().vertices.shape[1]
250
+ 2
251
+ """
252
+ along, across = outline.vertices(self.chromosome, self._cap(), stalks=self._stalks)
253
+ xy = self.xy(along, across)
254
+ return Path(np.vstack([xy, xy[:1]]), closed=True)
255
+
256
+ def zoom(
257
+ self, region: Region, into: Axes, *, color: ColorType = "C3"
258
+ ) -> tuple[PathPatch, PathPatch]:
259
+ """Box a locus on the ideogram and connect it to another Axes.
260
+
261
+ The box keeps a width of at least `MIN_BOX_POINTS`, so small loci
262
+ stay visible. Two lines join the box to the near corners of the
263
+ target Axes. Both are placed at draw time and follow layout changes.
264
+
265
+ Parameters
266
+ ----------
267
+ region : Region
268
+ Locus on this chromosome.
269
+ into : matplotlib.axes.Axes
270
+ Axes that shows the locus, usually with x limits set to it.
271
+ color : color, default "C3"
272
+ Color of the box and the lines.
273
+
274
+ Returns
275
+ -------
276
+ box, lines : matplotlib.patches.PathPatch
277
+ The locus box and the connecting lines.
278
+
279
+ Raises
280
+ ------
281
+ ValueError
282
+ If the region lies on another chromosome.
283
+
284
+ Examples
285
+ --------
286
+ >>> import matplotlib.pyplot as plt
287
+ >>> from pqplot import Genome, Region
288
+ >>> locus = Region.parse("chr17:43,044,295-43,125,483")
289
+ >>> fig, (head, body) = plt.subplots(2, 1, height_ratios=[1, 5])
290
+ >>> ideo = ideogram(Genome.bundled("hg38")[locus.chrom], ax=head)
291
+ >>> _ = body.set_xlim(locus.start, locus.end)
292
+ >>> box, lines = ideo.zoom(locus, into=body)
293
+ """
294
+ if chrom_key(region.chrom) != chrom_key(self.chromosome.name):
295
+ raise ValueError(f"region on {region.chrom} is not on {self.chromosome.name}")
296
+ box = _LocusBox(
297
+ self,
298
+ region,
299
+ edgecolor=color,
300
+ facecolor="none",
301
+ linewidth=0.75,
302
+ zorder=self.get_zorder() + 0.1,
303
+ clip_on=False,
304
+ )
305
+ self.axes.add_artist(box)
306
+ lines = _ZoomLines(box, into, edgecolor=color, facecolor="none", linewidth=0.5)
307
+ lines.set_in_layout(False)
308
+ self.figure.add_artist(lines)
309
+ return box, lines
310
+
311
+ def _cap(self) -> float:
312
+ """Return the cap radius in bp at the current Axes scale."""
313
+ pixels_per_bp, half_pixels = self._scale()
314
+ cap = half_pixels / pixels_per_bp if pixels_per_bp > 0 and half_pixels > 0 else None
315
+ return cap or 0.02 * self.chromosome.length
316
+
317
+ def _overshoot(self) -> tuple[float, float]:
318
+ """Return the across edges of fills that overshoot the body, for clipping."""
319
+ return self.center - OVERSHOOT * self.half, self.center + OVERSHOOT * self.half
320
+
321
+ def _scale(self) -> tuple[float, float]:
322
+ """Return pixels per bp along the body and the body half-width in pixels."""
323
+ length = self.chromosome.length
324
+ p0, p1, p2 = self.axes.transData.transform(self.xy([0, length, 0], [0, 0, 1]))
325
+ return float(np.hypot(*(p1 - p0)) / length), float(np.hypot(*(p2 - p0)))
326
+
327
+
328
+ class _LocusBox(PathPatch):
329
+ """Box around a locus, at least `MIN_BOX_POINTS` wide."""
330
+
331
+ def __init__(self, ideogram: Ideogram, region: Region, **kwargs):
332
+ super().__init__(Path(np.zeros((1, 2))), **kwargs)
333
+ self.ideogram = ideogram
334
+ self.region = region
335
+
336
+ def extent(self) -> tuple[float, float]:
337
+ pixels_per_bp, _ = self.ideogram._scale()
338
+ min_bp = MIN_BOX_POINTS * self.figure.dpi / 72 / pixels_per_bp
339
+ mid = (self.region.start + self.region.end) / 2
340
+ half = max((self.region.end - self.region.start) / 2, min_bp / 2)
341
+ return mid - half, mid + half
342
+
343
+ def get_path(self) -> Path:
344
+ return _span(self.ideogram, *self.extent(), BOX)
345
+
346
+
347
+ class _Knob(PathPatch):
348
+ """Centromere fill of a telocentric knob, from position 0 to its waist."""
349
+
350
+ def __init__(self, ideogram: Ideogram, **kwargs):
351
+ super().__init__(Path(np.zeros((1, 2))), **kwargs)
352
+ self.ideogram = ideogram
353
+
354
+ def get_path(self) -> Path:
355
+ return _span(self.ideogram, 0, outline.KNOB * self.ideogram._cap(), OVERSHOOT)
356
+
357
+
358
+ def _span(ideogram: Ideogram, start: float, end: float, half: float) -> Path:
359
+ """Return a closed box over a chromosome span, `half` body half-widths tall."""
360
+ return Path(
361
+ ideogram.xy([start, end, end, start, start], [-half, -half, half, half, -half]),
362
+ closed=True,
363
+ )
364
+
365
+
366
+ class _ZoomLines(PathPatch):
367
+ """Two lines from a locus box to the near corners of an Axes, in pixels."""
368
+
369
+ def __init__(self, box: _LocusBox, target: Axes, **kwargs):
370
+ super().__init__(Path(np.zeros((1, 2))), transform=IdentityTransform(), **kwargs)
371
+ self.box = box
372
+ self.target = target
373
+
374
+ def get_path(self) -> Path:
375
+ ideogram = self.box.ideogram
376
+ s0, s1 = self.box.extent()
377
+ sides = [
378
+ ideogram.axes.transData.transform(ideogram.xy([s0, s1], [t, t])) for t in (-BOX, BOX)
379
+ ]
380
+ bbox = self.target.get_window_extent()
381
+ center = (bbox.p0 + bbox.p1) / 2
382
+ side = min(sides, key=lambda pts: np.hypot(*(pts.mean(axis=0) - center)))
383
+ along = 0 if ideogram.orientation == "horizontal" else 1
384
+ side = side[np.argsort(side[:, along])]
385
+ ends = np.empty((2, 2))
386
+ ends[:, along] = sorted([bbox.p0[along], bbox.p1[along]])
387
+ edge = bbox.p1 if side[0, 1 - along] > center[1 - along] else bbox.p0
388
+ ends[:, 1 - along] = edge[1 - along]
389
+ return Path(
390
+ [side[0], ends[0], side[1], ends[1]],
391
+ [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO],
392
+ )
393
+
394
+
395
+ class _SparseLabels(Artist):
396
+ """Shows only the labels that fit from left to right, decided at draw time."""
397
+
398
+ def __init__(self, ax: Axes, texts: list[Text], gap_points: float = 2.0):
399
+ super().__init__()
400
+ self.texts = sorted(texts, key=lambda t: t.get_position()[0])
401
+ self.gap_points = gap_points
402
+ self.set_zorder(min(t.get_zorder() for t in texts) - 0.1)
403
+ self.set_in_layout(False)
404
+ ax.add_artist(self)
405
+
406
+ def draw(self, renderer) -> None:
407
+ for text in self.texts:
408
+ text.set_visible(True)
409
+ boxes = [text.get_window_extent(renderer) for text in self.texts]
410
+ gap = renderer.points_to_pixels(self.gap_points)
411
+ for text, keep in zip(
412
+ self.texts, _fitting([(b.x0, b.x1) for b in boxes], gap), strict=True
413
+ ):
414
+ text.set_visible(keep)
415
+
416
+
417
+ class _SparseTicks(Artist):
418
+ """Blanks the x tick labels that would overlap a neighbor, decided at draw time."""
419
+
420
+ def __init__(self, ax: Axes, names: list[str], gap_points: float = 2.0):
421
+ super().__init__()
422
+ self.names = names
423
+ self.gap_points = gap_points
424
+ self.set_zorder(ax.xaxis.get_zorder() - 0.1)
425
+ self.set_in_layout(False)
426
+ ax.add_artist(self)
427
+
428
+ def draw(self, renderer) -> None:
429
+ axis = self.axes.xaxis
430
+ font = axis.get_ticklabels()[0].get_fontproperties()
431
+ locs = axis.get_ticklocs()
432
+ x = self.axes.transData.transform(np.column_stack([locs, np.zeros_like(locs)]))[:, 0]
433
+ widths = [
434
+ renderer.get_text_width_height_descent(n, font, ismath=False)[0] for n in self.names
435
+ ]
436
+ spans = [(xi - w / 2, xi + w / 2) for xi, w in zip(x, widths, strict=True)]
437
+ keep = _fitting(spans, renderer.points_to_pixels(self.gap_points))
438
+ axis.set_ticklabels([n if k else "" for n, k in zip(self.names, keep, strict=True)])
439
+
440
+
441
+ def ideogram(
442
+ chromosome: Chromosome, ax: Axes | None = None, *, bands: bool = True, labels: bool = True
443
+ ) -> Ideogram:
444
+ """Draw one chromosome across an Axes, with x in bp.
445
+
446
+ The name goes to the left of the chromosome. Band names go below it,
447
+ and those that would overlap a neighbor are hidden at draw time.
448
+
449
+ Parameters
450
+ ----------
451
+ chromosome : Chromosome
452
+ Chromosome to draw.
453
+ ax : matplotlib.axes.Axes, optional
454
+ Axes to draw into. By default, a new figure sized for one
455
+ chromosome.
456
+ bands : bool, default True
457
+ Whether to draw bands.
458
+ labels : bool, default True
459
+ Whether to name the bands.
460
+
461
+ Returns
462
+ -------
463
+ Ideogram
464
+
465
+ Examples
466
+ --------
467
+ >>> from pqplot import Genome
468
+ >>> ideo = ideogram(Genome.bundled("hg38")["chr17"])
469
+ >>> ideo.axes.get_xlim() == (0, ideo.chromosome.length)
470
+ True
471
+ """
472
+ if ax is None:
473
+ _, ax = plt.subplots(figsize=(6.5, 0.75), layout="constrained")
474
+ ideo = Ideogram(chromosome, ax, bands=bands)
475
+ ax.set(xlim=(0, chromosome.length), ylim=(-1, 1))
476
+ ax.set_axis_off()
477
+ ax.annotate(
478
+ chromosome.name,
479
+ xy=(0, 0.5),
480
+ xycoords=ideo,
481
+ xytext=(-4, 0),
482
+ textcoords="offset points",
483
+ ha="right",
484
+ va="center",
485
+ )
486
+ if labels and chromosome.bands:
487
+ _SparseLabels(
488
+ ax, [_below(ax, (b.start + b.end) / 2, b.name, ideo.half) for b in chromosome.bands]
489
+ )
490
+ return ideo
491
+
492
+
493
+ def genome_strip(
494
+ linear: LinearGenome, ax: Axes | None = None, *, bands: bool = True, labels: bool = True
495
+ ) -> list[Ideogram]:
496
+ """Draw every chromosome of a concatenated genome in one row.
497
+
498
+ Parameters
499
+ ----------
500
+ linear : LinearGenome
501
+ Chromosomes and their offsets on the axis.
502
+ ax : matplotlib.axes.Axes, optional
503
+ Axes to draw into. By default, a new figure sized for one strip.
504
+ bands : bool, default True
505
+ Whether to draw bands.
506
+ labels : bool, default True
507
+ Whether to name the chromosomes below the strip. Names that would
508
+ overlap a neighbor are hidden at draw time.
509
+
510
+ Returns
511
+ -------
512
+ list of Ideogram
513
+ One per chromosome, in axis order.
514
+
515
+ Examples
516
+ --------
517
+ >>> from pqplot import Genome
518
+ >>> strip = genome_strip(Genome.bundled("mm39").concatenated(gap=5_000_000))
519
+ >>> len(strip), strip[1].offset
520
+ (21, 200154279.0)
521
+ """
522
+ if ax is None:
523
+ _, ax = plt.subplots(figsize=(10, 0.6), layout="constrained")
524
+ ideograms = [
525
+ Ideogram(c, ax, offset=linear.offset(c.name), half=STRIP_HALF, bands=bands)
526
+ for c in linear.genome
527
+ ]
528
+ ax.set(xlim=(0, linear.length), ylim=(-1, 1))
529
+ ax.set_axis_off()
530
+ if labels:
531
+ _SparseLabels(
532
+ ax,
533
+ [
534
+ _below(ax, i.offset + i.chromosome.length / 2, i.chromosome.label, STRIP_HALF)
535
+ for i in ideograms
536
+ ],
537
+ )
538
+ return ideograms
539
+
540
+
541
+ def chromosome_axis(
542
+ linear: LinearGenome, ax: Axes, *, shade: bool | ColorType = True
543
+ ) -> PolyCollection | None:
544
+ """Label a concatenated x axis by chromosome, for genome-wide plots.
545
+
546
+ Ticks go to the chromosome midpoints, named without the ``chr`` prefix.
547
+ Names that would overlap a neighbor are hidden at draw time. Every other
548
+ chromosome gets a shaded background. The x limits are set to
549
+ the whole genome.
550
+
551
+ Parameters
552
+ ----------
553
+ linear : LinearGenome
554
+ Chromosomes and their offsets on the axis.
555
+ ax : matplotlib.axes.Axes
556
+ Axes whose x axis holds concatenated positions.
557
+ shade : bool or color, default True
558
+ Shading of the second, fourth and later chromosomes. True blends a
559
+ little of the theme's foreground into the background. False draws
560
+ none.
561
+
562
+ Returns
563
+ -------
564
+ matplotlib.collections.PolyCollection or None
565
+ The shaded spans, or None without shading.
566
+
567
+ Examples
568
+ --------
569
+ >>> import matplotlib.pyplot as plt
570
+ >>> from pqplot import Genome
571
+ >>> linear = Genome.bundled("hg38").concatenated(gap=5_000_000)
572
+ >>> fig, ax = plt.subplots()
573
+ >>> _ = ax.scatter(linear.position(["chr1", "chr2"], [1e6, 5e7]), [3.0, 8.0])
574
+ >>> shade = chromosome_axis(linear, ax)
575
+ >>> [label.get_text() for label in ax.get_xticklabels()][:3]
576
+ ['1', '2', '3']
577
+ """
578
+ chromosomes = list(linear.genome)
579
+ starts = np.array([linear.offset(c.name) for c in chromosomes])
580
+ ends = starts + [c.length for c in chromosomes]
581
+ ax.set_xticks((starts + ends) / 2, [c.label for c in chromosomes])
582
+ ax.tick_params(axis="x", length=0)
583
+ _SparseTicks(ax, [c.label for c in chromosomes])
584
+ ax.set_xlim(0, linear.length)
585
+ if shade is False:
586
+ return None
587
+ x0, x1 = starts[1::2], ends[1::2]
588
+ quads = np.stack(
589
+ [np.stack([x0, x1, x1, x0], axis=1), np.tile([0, 0, 1, 1], (len(x0), 1))], axis=-1
590
+ )
591
+ spans = PolyCollection(
592
+ quads,
593
+ facecolors=_blend(SHADE) if shade is True else shade,
594
+ linewidths=0,
595
+ zorder=0,
596
+ transform=ax.get_xaxis_transform(),
597
+ gid="chromosome-shade",
598
+ )
599
+ ax.add_collection(spans, autolim=False)
600
+ return spans
601
+
602
+
603
+ def _fitting(spans: list[tuple[float, float]], gap: float) -> list[bool]:
604
+ """Keep spans from left to right that clear the last kept span by `gap`."""
605
+ keep, right = [], -np.inf
606
+ for x0, x1 in spans:
607
+ keep.append(bool(x0 >= right + gap))
608
+ if keep[-1]:
609
+ right = x1
610
+ return keep
611
+
612
+
613
+ def _below(ax: Axes, x: float, text: str, half: float) -> Text:
614
+ return ax.text(x, -half - 0.1, text, ha="center", va="top", fontsize="x-small", clip_on=False)
615
+
616
+
617
+ def _blend(share: float) -> tuple[float, float, float, float]:
618
+ """Mix the theme's foreground into its background."""
619
+ paper = np.array(to_rgba(plt.rcParams["axes.facecolor"]))
620
+ ink = np.array(to_rgba(plt.rcParams["axes.edgecolor"]))
621
+ return tuple((1 - share) * paper + share * ink)
622
+
623
+
624
+ def _stain_color(stain: Stain) -> ColorType:
625
+ density = stain.density
626
+ if density is not None:
627
+ return _blend(density)
628
+ return STAIN_COLORS.get(stain.name, _blend(0))
629
+
630
+
631
+ def _spans(chromosome: Chromosome, bands: bool) -> tuple[np.ndarray, np.ndarray, list]:
632
+ """Return starts, ends and colors of the body fills."""
633
+ if bands and chromosome.bands:
634
+ spans = [(b.start, b.end, _stain_color(b.stain)) for b in chromosome.bands]
635
+ else:
636
+ spans = [(0, chromosome.length, _blend(BODY))]
637
+ starts, ends, colors = zip(*spans, strict=True)
638
+ return np.array(starts, dtype=float), np.array(ends, dtype=float), list(colors)