ComplexHeatmap-py 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.
Files changed (52) hide show
  1. ComplexHeatmap.py +7 -0
  2. complexheatmap/__init__.py +221 -0
  3. complexheatmap/_base.py +56 -0
  4. complexheatmap/_options.py +165 -0
  5. complexheatmap/anno_funcs.py +2781 -0
  6. complexheatmap/annotations.py +1611 -0
  7. complexheatmap/colors.py +848 -0
  8. complexheatmap/data/dmr_summary/cgi_anno.csv +9 -0
  9. complexheatmap/data/dmr_summary/dist_tss.csv +9 -0
  10. complexheatmap/data/dmr_summary/gene_anno.csv +9 -0
  11. complexheatmap/data/dmr_summary/label.csv +9 -0
  12. complexheatmap/data/dmr_summary/mat_enrich_gf.csv +9 -0
  13. complexheatmap/data/dmr_summary/mat_enrich_st.csv +9 -0
  14. complexheatmap/data/dmr_summary/mat_pct_st.csv +9 -0
  15. complexheatmap/data/dmr_summary/mean_meth.csv +9 -0
  16. complexheatmap/data/dmr_summary/n_corr.csv +9 -0
  17. complexheatmap/data/dmr_summary/n_gr.csv +9 -0
  18. complexheatmap/data/gene_expression.csv +156 -0
  19. complexheatmap/data/gr.csv +2416 -0
  20. complexheatmap/data/measles.csv +60 -0
  21. complexheatmap/data/meth/enhancer.csv +1001 -0
  22. complexheatmap/data/meth/expr.csv +1001 -0
  23. complexheatmap/data/meth/meth.csv +1001 -0
  24. complexheatmap/data/meth/row_meta.csv +1001 -0
  25. complexheatmap/data/rand_mat.csv +19 -0
  26. complexheatmap/data/random_meth_expr_data/anno.csv +21 -0
  27. complexheatmap/data/random_meth_expr_data/anno_states.csv +1001 -0
  28. complexheatmap/data/random_meth_expr_data/mat_expr.csv +1001 -0
  29. complexheatmap/data/random_meth_expr_data/mat_meth.csv +1001 -0
  30. complexheatmap/data/random_meth_expr_data/row_meta.csv +1001 -0
  31. complexheatmap/data/sample_order.txt +172 -0
  32. complexheatmap/data/tcga_lung_adenocarcinoma.csv +27 -0
  33. complexheatmap/decorate.py +159 -0
  34. complexheatmap/dendrogram.py +937 -0
  35. complexheatmap/density.py +276 -0
  36. complexheatmap/genomic.py +348 -0
  37. complexheatmap/grid.py +1580 -0
  38. complexheatmap/heatmap.py +2244 -0
  39. complexheatmap/heatmap_list.py +1569 -0
  40. complexheatmap/legend.py +992 -0
  41. complexheatmap/oncoprint.py +488 -0
  42. complexheatmap/text.py +655 -0
  43. complexheatmap/three_d.py +188 -0
  44. complexheatmap/translate.py +338 -0
  45. complexheatmap/units.py +718 -0
  46. complexheatmap/upset.py +886 -0
  47. complexheatmap/utils.py +183 -0
  48. complexheatmap_py-0.1.0.dist-info/METADATA +96 -0
  49. complexheatmap_py-0.1.0.dist-info/RECORD +52 -0
  50. complexheatmap_py-0.1.0.dist-info/WHEEL +5 -0
  51. complexheatmap_py-0.1.0.dist-info/licenses/LICENSE +24 -0
  52. complexheatmap_py-0.1.0.dist-info/top_level.txt +2 -0
complexheatmap/grid.py ADDED
@@ -0,0 +1,1580 @@
1
+ """Matplotlib-backed Grid Graphics, Viewports, Grobs, and Primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import OrderedDict
6
+ import copy
7
+ import math
8
+ from typing import Any, Callable, Sequence
9
+
10
+ import matplotlib
11
+ import matplotlib.pyplot as plt
12
+ from matplotlib.collections import LineCollection, PolyCollection
13
+ from matplotlib.lines import Line2D
14
+ from matplotlib.patches import Circle, FancyBboxPatch, Polygon, Rectangle
15
+ from matplotlib.transforms import Bbox, TransformedBbox
16
+ import numpy as np
17
+
18
+ from .colors import grid_pretty, pretty_breaks, to_hex_rgba, to_rgba_tuple
19
+ from .units import (
20
+ ABS_UNITS,
21
+ Gpar,
22
+ Unit,
23
+ _MM_PER_BIGPT,
24
+ _MM_PER_INCH,
25
+ _text_dims_mm,
26
+ as_unit,
27
+ check_gp,
28
+ gpar,
29
+ recycle_gp,
30
+ subset_gp,
31
+ unit,
32
+ )
33
+
34
+ # Justification helper
35
+ _JUST_MAP = {
36
+ "center": (0.5, 0.5),
37
+ "centre": (0.5, 0.5),
38
+ "left": (0.0, 0.5),
39
+ "right": (1.0, 0.5),
40
+ "bottom": (0.5, 0.0),
41
+ "top": (0.5, 1.0),
42
+ }
43
+
44
+
45
+ def parse_just(just: Any) -> tuple[float, float]:
46
+ if just is None:
47
+ return (0.5, 0.5)
48
+ if isinstance(just, str):
49
+ k = just.strip().lower()
50
+ if k in _JUST_MAP:
51
+ return _JUST_MAP[k]
52
+ raise ValueError(f"Unknown just value: {just!r}")
53
+ if isinstance(just, (int, float, np.number)):
54
+ v = float(just)
55
+ return (v, v)
56
+ if isinstance(just, (list, tuple, np.ndarray)):
57
+ vals = list(just)
58
+ if len(vals) == 1:
59
+ return parse_just(vals[0])
60
+ if len(vals) >= 2:
61
+ jx = _JUST_MAP[vals[0].lower()][0] if isinstance(vals[0], str) else float(vals[0])
62
+ jy = _JUST_MAP[vals[1].lower()][1] if isinstance(vals[1], str) else float(vals[1])
63
+ return (jx, jy)
64
+ return (0.5, 0.5)
65
+
66
+
67
+ def _just_to_ha_va(jx: float, jy: float) -> tuple[str, str]:
68
+ ha = "left" if jx < 0.25 else ("right" if jx > 0.75 else "center")
69
+ va = "bottom" if jy < 0.25 else ("top" if jy > 0.75 else "center")
70
+ return ha, va
71
+
72
+
73
+ def _linestyle_for_mpl(lty: Any) -> Any:
74
+ if lty is None or lty == "solid" or lty == 1:
75
+ return "-"
76
+ if lty == "dashed" or lty == 2:
77
+ return (0, (4, 4))
78
+ if lty == "dotted" or lty == 3:
79
+ return (0, (1, 2))
80
+ if lty == "dotdash" or lty == 4:
81
+ return (0, (1, 2, 4, 2))
82
+ if lty == "longdash" or lty == 5:
83
+ return (0, (7, 3))
84
+ if lty == "twodash" or lty == 6:
85
+ return (0, (2, 2, 6, 2))
86
+ if lty in ("none", "blank", 0):
87
+ return "None"
88
+ return lty
89
+
90
+
91
+ def _unwrap_scalar(v: Any) -> Any:
92
+ if isinstance(v, (list, tuple, np.ndarray)) and len(v) > 0:
93
+ return v[0]
94
+ return v
95
+
96
+
97
+ def _font_props(gp: dict[str, Any]) -> tuple[float, str, str, str]:
98
+ fs = float(_unwrap_scalar(gp.get("fontsize", 12.0))) * float(_unwrap_scalar(gp.get("cex", 1.0)))
99
+ ff = _unwrap_scalar(gp.get("fontfamily", "sans-serif")) or "sans-serif"
100
+ face = _unwrap_scalar(gp.get("fontface", "plain"))
101
+ if face in (2, "bold"):
102
+ weight, style = "bold", "normal"
103
+ elif face in (3, "italic"):
104
+ weight, style = "normal", "italic"
105
+ elif face in (4, "bold.italic", "bold_italic", "bold italic"):
106
+ weight, style = "bold", "italic"
107
+ elif face == "oblique":
108
+ weight, style = "normal", "oblique"
109
+ else:
110
+ weight, style = "normal", "normal"
111
+ return fs, str(ff), weight, style
112
+
113
+
114
+ class Viewport:
115
+ """Grid viewport representing a rectangular millimeter region and native coordinate scales."""
116
+
117
+ def __init__(
118
+ self,
119
+ x: Any = None,
120
+ y: Any = None,
121
+ width: Any = None,
122
+ height: Any = None,
123
+ just: Any = "centre",
124
+ xscale: Sequence[float] = (0.0, 1.0),
125
+ yscale: Sequence[float] = (0.0, 1.0),
126
+ clip: bool | str = "inherit",
127
+ name: str | None = None,
128
+ gp: dict[str, Any] | None = None,
129
+ layout: Any = None,
130
+ layout_pos_row: int | tuple[int, int] | None = None,
131
+ layout_pos_col: int | tuple[int, int] | None = None,
132
+ ) -> None:
133
+ self.x = unit(0.5, "npc") if x is None else as_unit(x, "npc")
134
+ self.y = unit(0.5, "npc") if y is None else as_unit(y, "npc")
135
+ self.width = unit(1.0, "npc") if width is None else as_unit(width, "npc")
136
+ self.height = unit(1.0, "npc") if height is None else as_unit(height, "npc")
137
+ self.just = just
138
+ self.xscale = (float(xscale[0]), float(xscale[1]))
139
+ self.yscale = (float(yscale[0]), float(yscale[1]))
140
+ self.clip = clip
141
+ self.name = name
142
+ self.gp = check_gp(gp)
143
+ self.layout = layout
144
+ self.layout_pos_row = layout_pos_row
145
+ self.layout_pos_col = layout_pos_col
146
+
147
+ # Resolved geometry in figure millimeters (populated upon pushViewport)
148
+ self.x0_mm: float = 0.0
149
+ self.y0_mm: float = 0.0
150
+ self.w_mm: float = 200.0
151
+ self.h_mm: float = 200.0
152
+ self.clip_rect_mm: tuple[float, float, float, float] | None = None
153
+
154
+ @property
155
+ def width_mm(self) -> float:
156
+ return self.w_mm
157
+
158
+ @property
159
+ def height_mm(self) -> float:
160
+ return self.h_mm
161
+
162
+
163
+ def viewport(
164
+ x: Any = None,
165
+ y: Any = None,
166
+ width: Any = None,
167
+ height: Any = None,
168
+ just: Any = "centre",
169
+ xscale: Sequence[float] = (0.0, 1.0),
170
+ yscale: Sequence[float] = (0.0, 1.0),
171
+ clip: bool | str = "inherit",
172
+ name: str | None = None,
173
+ gp: dict[str, Any] | None = None,
174
+ **kwargs: Any,
175
+ ) -> Viewport:
176
+ return Viewport(
177
+ x=x,
178
+ y=y,
179
+ width=width,
180
+ height=height,
181
+ just=just,
182
+ xscale=xscale,
183
+ yscale=yscale,
184
+ clip=clip,
185
+ name=name,
186
+ gp=gp,
187
+ **kwargs,
188
+ )
189
+
190
+
191
+ class Grob:
192
+ """Base graphical object with intrinsic millimeter size."""
193
+
194
+ def __init__(self, name: str | None = None, gp: dict[str, Any] | None = None, vp: Viewport | None = None) -> None:
195
+ self.name = name
196
+ self.gp = check_gp(gp)
197
+ self.vp = vp
198
+
199
+ def width_mm(self, vp: Viewport | None = None) -> float:
200
+ return 0.0
201
+
202
+ def height_mm(self, vp: Viewport | None = None) -> float:
203
+ return 0.0
204
+
205
+ def draw(self, device: "GridDevice | None" = None) -> None:
206
+ raise NotImplementedError
207
+
208
+
209
+ class TextGrob(Grob):
210
+ def __init__(
211
+ self,
212
+ label: Any,
213
+ x: Any = None,
214
+ y: Any = None,
215
+ just: Any = "centre",
216
+ rot: float = 0.0,
217
+ gp: dict[str, Any] | None = None,
218
+ default_units: str = "npc",
219
+ name: str | None = None,
220
+ vp: Viewport | None = None,
221
+ ) -> None:
222
+ super().__init__(name=name, gp=gp, vp=vp)
223
+ self.label = label
224
+ self.x = unit(0.5, "npc") if x is None else as_unit(x, default_units)
225
+ self.y = unit(0.5, "npc") if y is None else as_unit(y, default_units)
226
+ self.just = just
227
+ self.rot = float(rot)
228
+
229
+ def width_mm(self, vp: Viewport | None = None) -> float:
230
+ from .text import GridText, _richtext_dims_mm
231
+
232
+ if isinstance(self.label, GridText):
233
+ w, _ = _richtext_dims_mm(self.label[0] if len(self.label) else "", self.gp, self.label.param, self.rot)
234
+ return w
235
+ w, _ = _text_dims_mm(str(self.label), self.gp, self.rot)
236
+ return w
237
+
238
+ def height_mm(self, vp: Viewport | None = None) -> float:
239
+ from .text import GridText, _richtext_dims_mm
240
+
241
+ if isinstance(self.label, GridText):
242
+ _, h = _richtext_dims_mm(self.label[0] if len(self.label) else "", self.gp, self.label.param, self.rot)
243
+ return h
244
+ _, h = _text_dims_mm(str(self.label), self.gp, self.rot)
245
+ return h
246
+
247
+ def draw(self, device: "GridDevice | None" = None) -> None:
248
+ dev = device or current_device()
249
+ if self.vp is not None:
250
+ dev.push_viewport(self.vp)
251
+ try:
252
+ dev.draw_text(self.label, x=self.x, y=self.y, just=self.just, rot=self.rot, gp=self.gp)
253
+ finally:
254
+ if self.vp is not None:
255
+ dev.pop_viewport(1)
256
+
257
+
258
+ class RectGrob(Grob):
259
+ def __init__(
260
+ self,
261
+ x: Any = None,
262
+ y: Any = None,
263
+ width: Any = None,
264
+ height: Any = None,
265
+ just: Any = "centre",
266
+ gp: dict[str, Any] | None = None,
267
+ default_units: str = "npc",
268
+ name: str | None = None,
269
+ vp: Viewport | None = None,
270
+ ) -> None:
271
+ super().__init__(name=name, gp=gp, vp=vp)
272
+ self.x = unit(0.5, "npc") if x is None else as_unit(x, default_units)
273
+ self.y = unit(0.5, "npc") if y is None else as_unit(y, default_units)
274
+ self.width = unit(1.0, "npc") if width is None else as_unit(width, default_units)
275
+ self.height = unit(1.0, "npc") if height is None else as_unit(height, default_units)
276
+ self.just = just
277
+
278
+ def width_mm(self, vp: Viewport | None = None) -> float:
279
+ return float(np.max(self.width.to_mm("x", vp)))
280
+
281
+ def height_mm(self, vp: Viewport | None = None) -> float:
282
+ return float(np.max(self.height.to_mm("y", vp)))
283
+
284
+ def draw(self, device: "GridDevice | None" = None) -> None:
285
+ dev = device or current_device()
286
+ if self.vp is not None:
287
+ dev.push_viewport(self.vp)
288
+ try:
289
+ dev.draw_rect(x=self.x, y=self.y, width=self.width, height=self.height, just=self.just, gp=self.gp)
290
+ finally:
291
+ if self.vp is not None:
292
+ dev.pop_viewport(1)
293
+
294
+
295
+ class RoundRectGrob(RectGrob):
296
+ def __init__(self, *args: Any, r: Any = None, **kwargs: Any) -> None:
297
+ super().__init__(*args, **kwargs)
298
+ self.r = unit(0.1, "snpc") if r is None else as_unit(r, "snpc")
299
+
300
+ def draw(self, device: "GridDevice | None" = None) -> None:
301
+ dev = device or current_device()
302
+ if self.vp is not None:
303
+ dev.push_viewport(self.vp)
304
+ try:
305
+ dev.draw_roundrect(
306
+ x=self.x, y=self.y, width=self.width, height=self.height,
307
+ r=self.r, just=self.just, gp=self.gp,
308
+ )
309
+ finally:
310
+ if self.vp is not None:
311
+ dev.pop_viewport(1)
312
+
313
+
314
+ class LinesGrob(Grob):
315
+ def __init__(self, x: Any, y: Any, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> None:
316
+ super().__init__(name=name, gp=gp, vp=vp)
317
+ self.x = as_unit(x, default_units)
318
+ self.y = as_unit(y, default_units)
319
+
320
+ def draw(self, device: "GridDevice | None" = None) -> None:
321
+ dev = device or current_device()
322
+ if self.vp is not None:
323
+ dev.push_viewport(self.vp)
324
+ try:
325
+ dev.draw_lines(self.x, self.y, gp=self.gp)
326
+ finally:
327
+ if self.vp is not None:
328
+ dev.pop_viewport(1)
329
+
330
+
331
+ class SegmentsGrob(Grob):
332
+ def __init__(self, x0: Any, y0: Any, x1: Any, y1: Any, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> None:
333
+ super().__init__(name=name, gp=gp, vp=vp)
334
+ self.x0 = as_unit(x0, default_units)
335
+ self.y0 = as_unit(y0, default_units)
336
+ self.x1 = as_unit(x1, default_units)
337
+ self.y1 = as_unit(y1, default_units)
338
+
339
+ def draw(self, device: "GridDevice | None" = None) -> None:
340
+ dev = device or current_device()
341
+ if self.vp is not None:
342
+ dev.push_viewport(self.vp)
343
+ try:
344
+ dev.draw_segments(self.x0, self.y0, self.x1, self.y1, gp=self.gp)
345
+ finally:
346
+ if self.vp is not None:
347
+ dev.pop_viewport(1)
348
+
349
+
350
+ class PolygonGrob(Grob):
351
+ def __init__(self, x: Any, y: Any, id: Any = None, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> None:
352
+ super().__init__(name=name, gp=gp, vp=vp)
353
+ self.x = as_unit(x, default_units)
354
+ self.y = as_unit(y, default_units)
355
+ self.id = id
356
+
357
+ def draw(self, device: "GridDevice | None" = None) -> None:
358
+ dev = device or current_device()
359
+ if self.vp is not None:
360
+ dev.push_viewport(self.vp)
361
+ try:
362
+ dev.draw_polygon(self.x, self.y, id=self.id, gp=self.gp)
363
+ finally:
364
+ if self.vp is not None:
365
+ dev.pop_viewport(1)
366
+
367
+
368
+ class PointsGrob(Grob):
369
+ def __init__(self, x: Any, y: Any, pch: Any = 1, size: Any = None, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> None:
370
+ super().__init__(name=name, gp=gp, vp=vp)
371
+ self.x = as_unit(x, default_units)
372
+ self.y = as_unit(y, default_units)
373
+ self.pch = pch
374
+ self.size = unit(2.0, "mm") if size is None else as_unit(size, "mm")
375
+
376
+ def draw(self, device: "GridDevice | None" = None) -> None:
377
+ dev = device or current_device()
378
+ if self.vp is not None:
379
+ dev.push_viewport(self.vp)
380
+ try:
381
+ dev.draw_points(self.x, self.y, pch=self.pch, size=self.size, gp=self.gp)
382
+ finally:
383
+ if self.vp is not None:
384
+ dev.pop_viewport(1)
385
+
386
+
387
+ class GTree(Grob):
388
+ """Composite container of child Grobs inside an optional viewport."""
389
+
390
+ def __init__(
391
+ self,
392
+ children: Sequence[Grob] = (),
393
+ vp: Viewport | None = None,
394
+ cl: str | None = None,
395
+ width: Unit | None = None,
396
+ height: Unit | None = None,
397
+ name: str | None = None,
398
+ gp: dict[str, Any] | None = None,
399
+ ) -> None:
400
+ super().__init__(name=name, gp=gp, vp=vp)
401
+ self.children: list[Grob] = [c for c in children if c is not None]
402
+ self.cl = cl
403
+ self._width = width
404
+ self._height = height
405
+
406
+ def width_mm(self, vp: Viewport | None = None) -> float:
407
+ if self._width is not None:
408
+ return self._width.to_mm_scalar("x", vp)
409
+ if self.vp is not None and self.vp.width is not None:
410
+ return self.vp.width.to_mm_scalar("x", vp)
411
+ return max((c.width_mm(vp) for c in self.children), default=0.0)
412
+
413
+ def height_mm(self, vp: Viewport | None = None) -> float:
414
+ if self._height is not None:
415
+ return self._height.to_mm_scalar("y", vp)
416
+ if self.vp is not None and self.vp.height is not None:
417
+ return self.vp.height.to_mm_scalar("y", vp)
418
+ return max((c.height_mm(vp) for c in self.children), default=0.0)
419
+
420
+ def draw(self, device: "GridDevice | None" = None) -> None:
421
+ dev = device or current_device()
422
+ if self.vp is not None:
423
+ dev.push_viewport(self.vp)
424
+ try:
425
+ for ch in self.children:
426
+ ch.draw(dev)
427
+ finally:
428
+ if self.vp is not None:
429
+ dev.pop_viewport(1)
430
+
431
+
432
+ def _scale_abs_unit(u: Unit, factor: float) -> Unit:
433
+ """Scale absolute-unit subexpressions by `factor` while leaving relative (`npc`, `native`, `snpc`) intact."""
434
+ if abs(factor - 1.0) < 1e-6:
435
+ return u
436
+ if u._op is None:
437
+ if u._unit in ABS_UNITS:
438
+ return Unit(u._values * factor, u._unit, _refs=u._refs)
439
+ return u
440
+ if u._op in ("add", "sub"):
441
+ left = _scale_abs_unit(u._left, factor)
442
+ right = _scale_abs_unit(u._right, factor)
443
+ return Unit(_op=u._op, _left=left, _right=right)
444
+ if u._op in ("mul", "div"):
445
+ return Unit(_op=u._op, _left=_scale_abs_unit(u._left, factor), _scalar=u._scalar)
446
+ if u._op in ("concat", "pmax", "pmin", "max", "min"):
447
+ return Unit(_op=u._op, _items=[_scale_abs_unit(it, factor) for it in (u._items or [])])
448
+ if u._op == "sum":
449
+ return Unit(_op="sum", _left=_scale_abs_unit(u._left, factor))
450
+ return u
451
+
452
+
453
+ def _scale_coord(val: Any, default_units: str, factor: float) -> Any:
454
+ if val is None or abs(factor - 1.0) < 1e-6:
455
+ return val
456
+ return _scale_abs_unit(as_unit(val, default_units), factor)
457
+
458
+
459
+ class CapturedGrob(Grob):
460
+ """Replayable grob captured via `grid.grabExpr`."""
461
+
462
+ def __init__(self, commands: list[tuple[str, tuple[Any, ...], dict[str, Any]]], width_mm: float, height_mm: float) -> None:
463
+ super().__init__()
464
+ self._commands = commands
465
+ self._w_mm = float(width_mm)
466
+ self._h_mm = float(height_mm)
467
+
468
+ def width_mm(self, vp: Viewport | None = None) -> float:
469
+ return self._w_mm
470
+
471
+ def height_mm(self, vp: Viewport | None = None) -> float:
472
+ return self._h_mm
473
+
474
+ def draw(self, device: "GridDevice | None" = None) -> None:
475
+ dev = device or current_device()
476
+ cur = dev.current_vp
477
+ sx = cur.w_mm / self._w_mm if self._w_mm > 0 else 1.0
478
+ sy = cur.h_mm / self._h_mm if self._h_mm > 0 else 1.0
479
+ smin = min(sx, sy)
480
+ wrapper = Viewport(
481
+ x=unit(0.5, "npc"), y=unit(0.5, "npc"),
482
+ width=unit(1.0, "npc"), height=unit(1.0, "npc"),
483
+ clip=cur.clip,
484
+ )
485
+ dev.push_viewport(wrapper)
486
+ base_depth = len(dev.vp_stack)
487
+ try:
488
+ for kind, args, kwargs in self._commands:
489
+ if kind == "push_vp":
490
+ vp_copy = copy.deepcopy(args[0])
491
+ vp_copy.x = _scale_abs_unit(vp_copy.x, sx)
492
+ vp_copy.y = _scale_abs_unit(vp_copy.y, sy)
493
+ vp_copy.width = _scale_abs_unit(vp_copy.width, sx)
494
+ vp_copy.height = _scale_abs_unit(vp_copy.height, sy)
495
+ if vp_copy.gp and abs(smin - 1.0) > 1e-6:
496
+ if "fontsize" in vp_copy.gp and isinstance(vp_copy.gp["fontsize"], (int, float, np.number)):
497
+ vp_copy.gp["fontsize"] = float(vp_copy.gp["fontsize"]) * smin
498
+ dev.push_viewport(vp_copy)
499
+ elif kind == "pop_vp":
500
+ n = min(args[0], len(dev.vp_stack) - base_depth)
501
+ if n > 0:
502
+ dev.pop_viewport(n)
503
+ elif kind == "seek_vp":
504
+ if args[0] in dev.named_viewports:
505
+ dev.seek_viewport(args[0])
506
+ elif kind == "rect":
507
+ x, y, width, height, just, gp, du = args
508
+ dev.draw_rect(
509
+ x=_scale_coord(x, du, sx), y=_scale_coord(y, du, sy),
510
+ width=_scale_coord(width, du, sx), height=_scale_coord(height, du, sy),
511
+ just=just, gp=gp, default_units=du, **kwargs,
512
+ )
513
+ elif kind == "roundrect":
514
+ x, y, width, height, r, just, gp, du = args
515
+ dev.draw_roundrect(
516
+ x=_scale_coord(x, du, sx), y=_scale_coord(y, du, sy),
517
+ width=_scale_coord(width, du, sx), height=_scale_coord(height, du, sy),
518
+ r=_scale_coord(r, "snpc", smin), just=just, gp=gp, default_units=du, **kwargs,
519
+ )
520
+ elif kind == "lines":
521
+ x, y, gp, du = args
522
+ dev.draw_lines(_scale_coord(x, du, sx), _scale_coord(y, du, sy), gp=gp, default_units=du, **kwargs)
523
+ elif kind == "segments":
524
+ x0, y0, x1, y1, gp, du = args
525
+ dev.draw_segments(
526
+ _scale_coord(x0, du, sx), _scale_coord(y0, du, sy),
527
+ _scale_coord(x1, du, sx), _scale_coord(y1, du, sy),
528
+ gp=gp, default_units=du, **kwargs,
529
+ )
530
+ elif kind == "polygon":
531
+ x, y, gid, gp, du = args
532
+ dev.draw_polygon(_scale_coord(x, du, sx), _scale_coord(y, du, sy), id=gid, gp=gp, default_units=du, **kwargs)
533
+ elif kind == "points":
534
+ x, y, pch, sz, gp, du = args
535
+ dev.draw_points(
536
+ _scale_coord(x, du, sx), _scale_coord(y, du, sy),
537
+ pch=pch, size=_scale_coord(sz, "mm", smin), gp=gp, default_units=du, **kwargs,
538
+ )
539
+ elif kind == "circle":
540
+ x, y, r, gp, du = args
541
+ dev.draw_circle(
542
+ x=_scale_coord(x, du, sx), y=_scale_coord(y, du, sy),
543
+ r=_scale_coord(r, du, smin), gp=gp, default_units=du, **kwargs,
544
+ )
545
+ elif kind == "text":
546
+ lbl, x, y, just, rot, gp, du = args
547
+ dev.draw_text(lbl, x=_scale_coord(x, du, sx), y=_scale_coord(y, du, sy), just=just, rot=rot, gp=gp, default_units=du, **kwargs)
548
+ elif kind == "raster":
549
+ img, x, y, width, height, just, interp, du = args
550
+ dev.draw_raster(
551
+ img, x=_scale_coord(x, du, sx), y=_scale_coord(y, du, sy),
552
+ width=_scale_coord(width, du, sx), height=_scale_coord(height, du, sy),
553
+ just=just, interpolate=interp, default_units=du, **kwargs,
554
+ )
555
+ finally:
556
+ while len(dev.vp_stack) > base_depth:
557
+ dev.pop_viewport(1)
558
+ dev.pop_viewport(1)
559
+
560
+
561
+ class GridDevice:
562
+ """Active Matplotlib figure + viewport stack acting as an R grid graphics device."""
563
+
564
+ def __init__(
565
+ self,
566
+ width_in: float = 8.0,
567
+ height_in: float = 8.0,
568
+ dpi: float = 100.0,
569
+ fig: matplotlib.figure.Figure | None = None,
570
+ record: bool = False,
571
+ ) -> None:
572
+ self.dpi = float(dpi)
573
+ self.record = record
574
+ self.commands: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = []
575
+ if fig is None:
576
+ self.fig = plt.figure(figsize=(width_in, height_in), dpi=self.dpi)
577
+ else:
578
+ self.fig = fig
579
+ self.fig.clf()
580
+ width_in, height_in = self.fig.get_size_inches()
581
+ self.w_mm = float(width_in) * _MM_PER_INCH
582
+ self.h_mm = float(height_in) * _MM_PER_INCH
583
+ self.ax = self.fig.add_axes([0.0, 0.0, 1.0, 1.0])
584
+ self.ax.set_xlim(0.0, self.w_mm)
585
+ self.ax.set_ylim(0.0, self.h_mm)
586
+ self.ax.set_axis_off()
587
+ self.ax.set_aspect("auto")
588
+
589
+ root = Viewport(
590
+ x=unit(0.5, "npc"), y=unit(0.5, "npc"),
591
+ width=unit(self.w_mm, "mm"), height=unit(self.h_mm, "mm"),
592
+ clip=False, name="ROOT",
593
+ )
594
+ root.x0_mm = 0.0
595
+ root.y0_mm = 0.0
596
+ root.w_mm = self.w_mm
597
+ root.h_mm = self.h_mm
598
+ root.clip_rect_mm = None
599
+
600
+ self.vp_stack: list[Viewport] = [root]
601
+ self.named_viewports: OrderedDict[str, Viewport] = OrderedDict()
602
+
603
+ @property
604
+ def current_vp(self) -> Viewport:
605
+ return self.vp_stack[-1]
606
+
607
+ @property
608
+ def width_mm(self) -> float:
609
+ return self.w_mm
610
+
611
+ @property
612
+ def height_mm(self) -> float:
613
+ return self.h_mm
614
+
615
+ def resize(self, width_in: float, height_in: float) -> None:
616
+ self.fig.set_size_inches(width_in, height_in, forward=True)
617
+ self.w_mm = float(width_in) * _MM_PER_INCH
618
+ self.h_mm = float(height_in) * _MM_PER_INCH
619
+ self.ax.set_xlim(0.0, self.w_mm)
620
+ self.ax.set_ylim(0.0, self.h_mm)
621
+ root = self.vp_stack[0]
622
+ root.w_mm = self.w_mm
623
+ root.h_mm = self.h_mm
624
+ root.width = unit(self.w_mm, "mm")
625
+ root.height = unit(self.h_mm, "mm")
626
+
627
+ def _clip_bbox(self, vp: Viewport) -> Any:
628
+ if vp.clip_rect_mm is None:
629
+ return None
630
+ x0, y0, w, h = vp.clip_rect_mm
631
+ if w <= 0 or h <= 0:
632
+ return TransformedBbox(Bbox.from_bounds(x0, y0, 0.001, 0.001), self.ax.transData)
633
+ return TransformedBbox(Bbox.from_bounds(x0, y0, w, h), self.ax.transData)
634
+
635
+ def push_viewport(self, vp: Viewport) -> Viewport:
636
+ if self.record:
637
+ self.commands.append(("push_vp", (vp,), {}))
638
+ parent = self.current_vp
639
+ vp_copy = copy.copy(vp)
640
+ if not vp_copy.gp:
641
+ vp_copy.gp = parent.gp.copy()
642
+ else:
643
+ merged = parent.gp.copy()
644
+ merged.update(vp_copy.gp)
645
+ vp_copy.gp = merged
646
+
647
+ w_mm = vp_copy.width.to_mm_scalar("x", parent, pos_mode=False)
648
+ h_mm = vp_copy.height.to_mm_scalar("y", parent, pos_mode=False)
649
+ ax_mm = parent.x0_mm + vp_copy.x.to_mm_scalar("x", parent, pos_mode=True)
650
+ ay_mm = parent.y0_mm + vp_copy.y.to_mm_scalar("y", parent, pos_mode=True)
651
+ jx, jy = parse_just(vp_copy.just)
652
+ vp_copy.w_mm = w_mm
653
+ vp_copy.h_mm = h_mm
654
+ vp_copy.x0_mm = ax_mm - jx * w_mm
655
+ vp_copy.y0_mm = ay_mm - jy * h_mm
656
+
657
+ if vp_copy.clip is True or vp_copy.clip == "on":
658
+ vp_copy.clip_rect_mm = (vp_copy.x0_mm, vp_copy.y0_mm, vp_copy.w_mm, vp_copy.h_mm)
659
+ elif vp_copy.clip is False or vp_copy.clip == "off":
660
+ vp_copy.clip_rect_mm = None
661
+ else: # "inherit"
662
+ vp_copy.clip_rect_mm = parent.clip_rect_mm
663
+
664
+ self.vp_stack.append(vp_copy)
665
+ if vp_copy.name:
666
+ self.named_viewports[vp_copy.name] = vp_copy
667
+ return vp_copy
668
+
669
+ def pop_viewport(self, n: int = 1) -> None:
670
+ if self.record:
671
+ self.commands.append(("pop_vp", (n,), {}))
672
+ if n == 0:
673
+ self.vp_stack = self.vp_stack[:1]
674
+ return
675
+ for _ in range(n):
676
+ if len(self.vp_stack) > 1:
677
+ self.vp_stack.pop()
678
+
679
+ def seek_viewport(self, name: str) -> Viewport:
680
+ if self.record:
681
+ self.commands.append(("seek_vp", (name,), {}))
682
+ if name == "ROOT":
683
+ self.vp_stack = self.vp_stack[:1]
684
+ return self.current_vp
685
+ if name not in self.named_viewports:
686
+ raise KeyError(f"Viewport {name!r} not found.")
687
+ target = self.named_viewports[name]
688
+ # Replace top with a clean stack [root, target]
689
+ self.vp_stack = [self.vp_stack[0], target]
690
+ return target
691
+
692
+ def _xy_mm(self, x: Any, y: Any, default_units: str = "npc") -> tuple[np.ndarray, np.ndarray]:
693
+ vp = self.current_vp
694
+ ux = as_unit(x, default_units)
695
+ uy = as_unit(y, default_units)
696
+ xmm = vp.x0_mm + ux.to_mm("x", vp, pos_mode=True)
697
+ ymm = vp.y0_mm + uy.to_mm("y", vp, pos_mode=True)
698
+ xmm, ymm = np.broadcast_arrays(xmm, ymm)
699
+ return np.atleast_1d(xmm), np.atleast_1d(ymm)
700
+
701
+ def draw_rect(
702
+ self,
703
+ x: Any = None,
704
+ y: Any = None,
705
+ width: Any = None,
706
+ height: Any = None,
707
+ just: Any = "centre",
708
+ gp: dict[str, Any] | None = None,
709
+ default_units: str = "npc",
710
+ ) -> None:
711
+ if self.record:
712
+ self.commands.append(("rect", (x, y, width, height, just, gp, default_units), {}))
713
+ vp = self.current_vp
714
+ ux = unit(0.5, "npc") if x is None else as_unit(x, default_units)
715
+ uy = unit(0.5, "npc") if y is None else as_unit(y, default_units)
716
+ uw = unit(1.0, "npc") if width is None else as_unit(width, default_units)
717
+ uh = unit(1.0, "npc") if height is None else as_unit(height, default_units)
718
+
719
+ xmm = vp.x0_mm + ux.to_mm("x", vp, pos_mode=True)
720
+ ymm = vp.y0_mm + uy.to_mm("y", vp, pos_mode=True)
721
+ wmm = uw.to_mm("x", vp, pos_mode=False)
722
+ hmm = uh.to_mm("y", vp, pos_mode=False)
723
+ xmm, ymm, wmm, hmm = np.broadcast_arrays(xmm, ymm, wmm, hmm)
724
+ n = len(xmm)
725
+ if n == 0:
726
+ return
727
+
728
+ jx, jy = parse_just(just)
729
+ x0 = xmm - jx * wmm
730
+ y0 = ymm - jy * hmm
731
+
732
+ gp_n = recycle_gp(gp or {}, n)
733
+ fills = gp_n.get("fill", ["#00000000"] * n)
734
+ # Note: in R grid, default rect border col is "black" if unspecified,
735
+ # unless gp has col=NA / col=None. When gp is empty gpar(), R draws black outline & transparent fill!
736
+ has_col = "col" in (gp or {})
737
+ cols = gp_n.get("col", ["#000000FF"] * n if has_col or "fill" not in (gp or {}) else ["#000000FF"] * n)
738
+ if not has_col and "fill" in (gp or {}):
739
+ # In R grid, grid.rect(gp = gpar(fill="red")) still has black default col unless col=NA.
740
+ # Keep black border when col is omitted, matching R grid!
741
+ cols = ["#000000FF"] * n
742
+ lwds = gp_n.get("lwd", [1.0] * n)
743
+ ltys = gp_n.get("lty", ["solid"] * n)
744
+ alphas = gp_n.get("alpha", [None] * n)
745
+
746
+ verts = []
747
+ fc = []
748
+ ec = []
749
+ lw_list = []
750
+ ls_list = []
751
+ for k in range(n):
752
+ xk, yk, wk, hk = float(x0[k]), float(y0[k]), float(wmm[k]), float(hmm[k])
753
+ if wk < 0:
754
+ xk += wk
755
+ wk = -wk
756
+ if hk < 0:
757
+ yk += hk
758
+ hk = -hk
759
+ verts.append([(xk, yk), (xk + wk, yk), (xk + wk, yk + hk), (xk, yk + hk)])
760
+ f_rgba = list(to_rgba_tuple(fills[k]))
761
+ c_rgba = list(to_rgba_tuple(cols[k]))
762
+ if alphas[k] is not None:
763
+ f_rgba[3] *= float(alphas[k])
764
+ c_rgba[3] *= float(alphas[k])
765
+ fc.append(tuple(f_rgba))
766
+ ec.append(tuple(c_rgba))
767
+ lwd_k = float(lwds[k]) * 0.75
768
+ if c_rgba[3] == 0.0 or ltys[k] in ("none", "blank", 0):
769
+ lwd_k = 0.0
770
+ lw_list.append(lwd_k)
771
+ ls_list.append(_linestyle_for_mpl(ltys[k]))
772
+
773
+ pc = PolyCollection(verts, facecolors=fc, edgecolors=ec, linewidths=lw_list, linestyles=ls_list, antialiaseds=True)
774
+ cb = self._clip_bbox(vp)
775
+ if cb is not None:
776
+ pc.set_clip_path(cb.bounds if False else None)
777
+ pc.set_clip_box(cb)
778
+ self.ax.add_collection(pc)
779
+
780
+ def draw_roundrect(
781
+ self,
782
+ x: Any = None,
783
+ y: Any = None,
784
+ width: Any = None,
785
+ height: Any = None,
786
+ r: Any = None,
787
+ just: Any = "centre",
788
+ gp: dict[str, Any] | None = None,
789
+ default_units: str = "npc",
790
+ ) -> None:
791
+ if self.record:
792
+ self.commands.append(("roundrect", (x, y, width, height, r, just, gp, default_units), {}))
793
+ vp = self.current_vp
794
+ ux = unit(0.5, "npc") if x is None else as_unit(x, default_units)
795
+ uy = unit(0.5, "npc") if y is None else as_unit(y, default_units)
796
+ uw = unit(1.0, "npc") if width is None else as_unit(width, default_units)
797
+ uh = unit(1.0, "npc") if height is None else as_unit(height, default_units)
798
+ ur = unit(0.1, "snpc") if r is None else as_unit(r, "snpc")
799
+
800
+ xmm = vp.x0_mm + ux.to_mm("x", vp, pos_mode=True)
801
+ ymm = vp.y0_mm + uy.to_mm("y", vp, pos_mode=True)
802
+ wmm = uw.to_mm("x", vp, pos_mode=False)
803
+ hmm = uh.to_mm("y", vp, pos_mode=False)
804
+ rmm = ur.to_mm("x", vp, pos_mode=False)
805
+ xmm, ymm, wmm, hmm, rmm = np.broadcast_arrays(xmm, ymm, wmm, hmm, rmm)
806
+ jx, jy = parse_just(just)
807
+ n = len(xmm)
808
+ gp_n = recycle_gp(gp or {}, n)
809
+ fills = gp_n.get("fill", ["#00000000"] * n)
810
+ cols = gp_n.get("col", ["#000000FF"] * n)
811
+ lwds = gp_n.get("lwd", [1.0] * n)
812
+ cb = self._clip_bbox(vp)
813
+ for k in range(n):
814
+ wk, hk = float(wmm[k]), float(hmm[k])
815
+ xk = float(xmm[k]) - jx * wk
816
+ yk = float(ymm[k]) - jy * hk
817
+ if wk < 0:
818
+ xk += wk
819
+ wk = -wk
820
+ if hk < 0:
821
+ yk += hk
822
+ hk = -hk
823
+ rk = min(float(rmm[k]), wk * 0.5, hk * 0.5)
824
+ c_rgba = to_rgba_tuple(cols[k])
825
+ f_rgba = to_rgba_tuple(fills[k])
826
+ patch = FancyBboxPatch(
827
+ (xk, yk), wk, hk,
828
+ boxstyle=f"round,pad=0,rounding_size={max(0.0, rk)}",
829
+ facecolor=f_rgba,
830
+ edgecolor=c_rgba,
831
+ linewidth=float(lwds[k]) * 0.75 if c_rgba[3] > 0 else 0.0,
832
+ )
833
+ if cb is not None:
834
+ patch.set_clip_box(cb)
835
+ self.ax.add_patch(patch)
836
+
837
+ def draw_lines(
838
+ self,
839
+ x: Any,
840
+ y: Any,
841
+ gp: dict[str, Any] | None = None,
842
+ default_units: str = "npc",
843
+ ) -> None:
844
+ if self.record:
845
+ self.commands.append(("lines", (x, y, gp, default_units), {}))
846
+ xmm, ymm = self._xy_mm(x, y, default_units)
847
+ if len(xmm) < 2:
848
+ return
849
+ gp_d = check_gp(gp)
850
+ col_val = _unwrap_scalar(gp_d.get("col", "#000000FF"))
851
+ col = to_rgba_tuple(col_val)
852
+ if col[3] == 0.0:
853
+ return
854
+ lwd = float(_unwrap_scalar(gp_d.get("lwd", 1.0))) * 0.75
855
+ ls = _linestyle_for_mpl(_unwrap_scalar(gp_d.get("lty", "solid")))
856
+ alpha = _unwrap_scalar(gp_d.get("alpha", None))
857
+ if alpha is not None:
858
+ col = (col[0], col[1], col[2], col[3] * float(alpha))
859
+ # Split on NaN
860
+ valid = np.isfinite(xmm) & np.isfinite(ymm)
861
+ if np.all(valid):
862
+ line = Line2D(xmm, ymm, color=col, linewidth=lwd, linestyle=ls, solid_capstyle="butt")
863
+ cb = self._clip_bbox(self.current_vp)
864
+ if cb is not None:
865
+ line.set_clip_box(cb)
866
+ self.ax.add_line(line)
867
+ else:
868
+ # Draw contiguous runs
869
+ i = 0
870
+ n = len(xmm)
871
+ cb = self._clip_bbox(self.current_vp)
872
+ while i < n:
873
+ while i < n and not valid[i]:
874
+ i += 1
875
+ j = i
876
+ while j < n and valid[j]:
877
+ j += 1
878
+ if j - i >= 2:
879
+ line = Line2D(xmm[i:j], ymm[i:j], color=col, linewidth=lwd, linestyle=ls)
880
+ if cb is not None:
881
+ line.set_clip_box(cb)
882
+ self.ax.add_line(line)
883
+ i = j
884
+
885
+ def draw_segments(
886
+ self,
887
+ x0: Any,
888
+ y0: Any,
889
+ x1: Any,
890
+ y1: Any,
891
+ gp: dict[str, Any] | None = None,
892
+ default_units: str = "npc",
893
+ ) -> None:
894
+ if self.record:
895
+ self.commands.append(("segments", (x0, y0, x1, y1, gp, default_units), {}))
896
+ vp = self.current_vp
897
+ x0_mm = vp.x0_mm + as_unit(x0, default_units).to_mm("x", vp, pos_mode=True)
898
+ y0_mm = vp.y0_mm + as_unit(y0, default_units).to_mm("y", vp, pos_mode=True)
899
+ x1_mm = vp.x0_mm + as_unit(x1, default_units).to_mm("x", vp, pos_mode=True)
900
+ y1_mm = vp.y0_mm + as_unit(y1, default_units).to_mm("y", vp, pos_mode=True)
901
+ x0_mm, y0_mm, x1_mm, y1_mm = np.broadcast_arrays(x0_mm, y0_mm, x1_mm, y1_mm)
902
+ n = len(x0_mm)
903
+ if n == 0:
904
+ return
905
+ gp_n = recycle_gp(gp or {}, n)
906
+ cols = gp_n.get("col", ["#000000FF"] * n)
907
+ lwds = gp_n.get("lwd", [1.0] * n)
908
+ ltys = gp_n.get("lty", ["solid"] * n)
909
+ segs = []
910
+ colors = []
911
+ widths = []
912
+ styles = []
913
+ for k in range(n):
914
+ c = to_rgba_tuple(cols[k])
915
+ if c[3] == 0.0 or ltys[k] in ("none", "blank", 0):
916
+ continue
917
+ segs.append([(float(x0_mm[k]), float(y0_mm[k])), (float(x1_mm[k]), float(y1_mm[k]))])
918
+ colors.append(c)
919
+ widths.append(float(lwds[k]) * 0.75)
920
+ styles.append(_linestyle_for_mpl(ltys[k]))
921
+ if not segs:
922
+ return
923
+ lc = LineCollection(segs, colors=colors, linewidths=widths, linestyles=styles)
924
+ cb = self._clip_bbox(vp)
925
+ if cb is not None:
926
+ lc.set_clip_box(cb)
927
+ self.ax.add_collection(lc)
928
+
929
+ def draw_polygon(
930
+ self,
931
+ x: Any,
932
+ y: Any,
933
+ id: Any = None,
934
+ gp: dict[str, Any] | None = None,
935
+ default_units: str = "npc",
936
+ ) -> None:
937
+ if self.record:
938
+ self.commands.append(("polygon", (x, y, id, gp, default_units), {}))
939
+ xmm, ymm = self._xy_mm(x, y, default_units)
940
+ if len(xmm) < 3:
941
+ return
942
+ if id is None:
943
+ groups = [np.arange(len(xmm))]
944
+ else:
945
+ id_arr = np.asarray(id)
946
+ seen: OrderedDict[Any, list[int]] = OrderedDict()
947
+ for idx, gid in enumerate(id_arr):
948
+ seen.setdefault(gid, []).append(idx)
949
+ groups = [np.asarray(idxs, dtype=int) for idxs in seen.values()]
950
+
951
+ ng = len(groups)
952
+ gp_n = recycle_gp(gp or {}, ng)
953
+ fills = gp_n.get("fill", ["#00000000"] * ng)
954
+ cols = gp_n.get("col", ["#000000FF"] * ng)
955
+ lwds = gp_n.get("lwd", [1.0] * ng)
956
+ ltys = gp_n.get("lty", ["solid"] * ng)
957
+
958
+ verts = []
959
+ fc = []
960
+ ec = []
961
+ lws = []
962
+ lss = []
963
+ for k, idxs in enumerate(groups):
964
+ pts = list(zip(xmm[idxs], ymm[idxs]))
965
+ verts.append(pts)
966
+ f_c = to_rgba_tuple(fills[k])
967
+ e_c = to_rgba_tuple(cols[k])
968
+ fc.append(f_c)
969
+ ec.append(e_c)
970
+ lws.append(float(lwds[k]) * 0.75 if e_c[3] > 0 else 0.0)
971
+ lss.append(_linestyle_for_mpl(ltys[k]))
972
+
973
+ pc = PolyCollection(verts, facecolors=fc, edgecolors=ec, linewidths=lws, linestyles=lss, antialiaseds=True)
974
+ cb = self._clip_bbox(self.current_vp)
975
+ if cb is not None:
976
+ pc.set_clip_box(cb)
977
+ self.ax.add_collection(pc)
978
+
979
+ def draw_circle(
980
+ self,
981
+ x: Any = None,
982
+ y: Any = None,
983
+ r: Any = None,
984
+ gp: dict[str, Any] | None = None,
985
+ default_units: str = "npc",
986
+ ) -> None:
987
+ if self.record:
988
+ self.commands.append(("circle", (x, y, r, gp, default_units), {}))
989
+ vp = self.current_vp
990
+ ux = unit(0.5, "npc") if x is None else as_unit(x, default_units)
991
+ uy = unit(0.5, "npc") if y is None else as_unit(y, default_units)
992
+ ur = unit(0.5, "snpc") if r is None else as_unit(r, default_units)
993
+ xmm = vp.x0_mm + ux.to_mm("x", vp, pos_mode=True)
994
+ ymm = vp.y0_mm + uy.to_mm("y", vp, pos_mode=True)
995
+ rmm = ur.to_mm("x", vp, pos_mode=False)
996
+ xmm, ymm, rmm = np.broadcast_arrays(xmm, ymm, rmm)
997
+ n = len(xmm)
998
+ gp_n = recycle_gp(gp or {}, n)
999
+ fills = gp_n.get("fill", ["#00000000"] * n)
1000
+ cols = gp_n.get("col", ["#000000FF"] * n)
1001
+ lwds = gp_n.get("lwd", [1.0] * n)
1002
+ cb = self._clip_bbox(vp)
1003
+ for k in range(n):
1004
+ f_c = to_rgba_tuple(fills[k])
1005
+ e_c = to_rgba_tuple(cols[k])
1006
+ patch = Circle(
1007
+ (float(xmm[k]), float(ymm[k])),
1008
+ radius=max(0.0, float(rmm[k])),
1009
+ facecolor=f_c,
1010
+ edgecolor=e_c,
1011
+ linewidth=float(lwds[k]) * 0.75 if e_c[3] > 0 else 0.0,
1012
+ )
1013
+ if cb is not None:
1014
+ patch.set_clip_box(cb)
1015
+ self.ax.add_patch(patch)
1016
+
1017
+ def draw_points(
1018
+ self,
1019
+ x: Any,
1020
+ y: Any,
1021
+ pch: Any = 1,
1022
+ size: Any = None,
1023
+ gp: dict[str, Any] | None = None,
1024
+ default_units: str = "native",
1025
+ ) -> None:
1026
+ if self.record:
1027
+ self.commands.append(("points", (x, y, pch, size, gp, default_units), {}))
1028
+ vp = self.current_vp
1029
+ xmm, ymm = self._xy_mm(x, y, default_units)
1030
+ n = len(xmm)
1031
+ if n == 0:
1032
+ return
1033
+ sz_u = unit(1.0, "char") if size is None else as_unit(size, "mm")
1034
+ sz_mm = np.broadcast_to(sz_u.to_mm("x", vp, pos_mode=False), (n,))
1035
+ if isinstance(pch, (int, np.integer, str)) or pch is None:
1036
+ pchs = [pch] * n
1037
+ else:
1038
+ p_list = list(pch)
1039
+ pchs = [p_list[i % len(p_list)] for i in range(n)]
1040
+
1041
+ gp_n = recycle_gp(gp or {}, n)
1042
+ cols = gp_n.get("col", ["#000000FF"] * n)
1043
+ fills = gp_n.get("fill", ["#00000000"] * n)
1044
+ lwds = gp_n.get("lwd", [1.0] * n)
1045
+ cb = self._clip_bbox(vp)
1046
+
1047
+ # Group simple markers or draw per-point accurately in mm
1048
+ for k in range(n):
1049
+ xk, yk, sk = float(xmm[k]), float(ymm[k]), float(sz_mm[k])
1050
+ if not (math.isfinite(xk) and math.isfinite(yk)):
1051
+ continue
1052
+ pk = pchs[k]
1053
+ if pk is None or (isinstance(pk, float) and math.isnan(pk)):
1054
+ continue
1055
+ col_k = to_rgba_tuple(cols[k])
1056
+ fill_k = to_rgba_tuple(fills[k])
1057
+ lwd_k = float(lwds[k]) * 0.75
1058
+
1059
+ if isinstance(pk, str):
1060
+ fs = max(4.0, sk / _MM_PER_BIGPT)
1061
+ txt = self.ax.text(xk, yk, pk, fontsize=fs, color=col_k, ha="center", va="center")
1062
+ if cb is not None:
1063
+ txt.set_clip_box(cb)
1064
+ continue
1065
+
1066
+ code = int(pk)
1067
+ r = sk * 0.45
1068
+ if code in (26, 27, 28):
1069
+ # Custom ComplexHeatmap diagonal markers
1070
+ segs = []
1071
+ if code in (26, 28):
1072
+ segs.append([(xk - r, yk - r), (xk + r, yk + r)])
1073
+ if code in (27, 28):
1074
+ segs.append([(xk - r, yk + r), (xk + r, yk - r)])
1075
+ lc = LineCollection(segs, colors=[col_k] * len(segs), linewidths=lwd_k)
1076
+ if cb is not None:
1077
+ lc.set_clip_box(cb)
1078
+ self.ax.add_collection(lc)
1079
+ continue
1080
+
1081
+ # Matplotlib scatter uses area in pt^2
1082
+ s_pt = max(1.0, sk / _MM_PER_BIGPT)
1083
+ if code == 20:
1084
+ s_pt *= 0.67
1085
+ area = s_pt ** 2
1086
+
1087
+ filled_no_edge = {15: "s", 16: "o", 17: "^", 18: "D", 19: "o", 20: "o"}
1088
+ hollow_map = {0: "s", 1: "o", 2: "^", 5: "D", 6: "v"}
1089
+ line_map = {3: "+", 4: "x", 8: "*"}
1090
+ filled_edge_map = {21: "o", 22: "s", 23: "D", 24: "^", 25: "v"}
1091
+
1092
+ if code in filled_no_edge:
1093
+ sc = self.ax.scatter([xk], [yk], s=area, marker=filled_no_edge[code], c=[col_k], edgecolors="none")
1094
+ if cb is not None:
1095
+ sc.set_clip_box(cb)
1096
+ elif code in hollow_map:
1097
+ sc = self.ax.scatter([xk], [yk], s=area, marker=hollow_map[code], facecolors="none", edgecolors=[col_k], linewidths=lwd_k)
1098
+ if cb is not None:
1099
+ sc.set_clip_box(cb)
1100
+ elif code in line_map:
1101
+ sc = self.ax.scatter([xk], [yk], s=area, marker=line_map[code], c=[col_k], linewidths=lwd_k)
1102
+ if cb is not None:
1103
+ sc.set_clip_box(cb)
1104
+ elif code in filled_edge_map:
1105
+ sc = self.ax.scatter([xk], [yk], s=area, marker=filled_edge_map[code], facecolors=[fill_k], edgecolors=[col_k], linewidths=lwd_k)
1106
+ if cb is not None:
1107
+ sc.set_clip_box(cb)
1108
+ else:
1109
+ # Composite markers (7, 9, 10, 11, 12, 13, 14)
1110
+ base = {7: "s", 9: "D", 10: "o", 12: "s", 13: "o", 14: "s"}.get(code, "o")
1111
+ sc = self.ax.scatter([xk], [yk], s=area, marker=base, facecolors="none", edgecolors=[col_k], linewidths=lwd_k)
1112
+ if cb is not None:
1113
+ sc.set_clip_box(cb)
1114
+ extra_segs = []
1115
+ if code in (7, 13):
1116
+ extra_segs = [[(xk - r, yk - r), (xk + r, yk + r)], [(xk - r, yk + r), (xk + r, yk - r)]]
1117
+ elif code in (9, 10, 12):
1118
+ extra_segs = [[(xk - r, yk), (xk + r, yk)], [(xk, yk - r), (xk, yk + r)]]
1119
+ elif code == 11:
1120
+ sc2 = self.ax.scatter([xk], [yk], s=area, marker="^", facecolors="none", edgecolors=[col_k], linewidths=lwd_k)
1121
+ sc3 = self.ax.scatter([xk], [yk], s=area, marker="v", facecolors="none", edgecolors=[col_k], linewidths=lwd_k)
1122
+ if cb is not None:
1123
+ sc2.set_clip_box(cb)
1124
+ sc3.set_clip_box(cb)
1125
+ if extra_segs:
1126
+ lc = LineCollection(extra_segs, colors=[col_k] * len(extra_segs), linewidths=lwd_k)
1127
+ if cb is not None:
1128
+ lc.set_clip_box(cb)
1129
+ self.ax.add_collection(lc)
1130
+
1131
+ def draw_text(
1132
+ self,
1133
+ label: Any,
1134
+ x: Any = None,
1135
+ y: Any = None,
1136
+ just: Any = "centre",
1137
+ rot: float = 0.0,
1138
+ gp: dict[str, Any] | None = None,
1139
+ default_units: str = "npc",
1140
+ ) -> None:
1141
+ if self.record:
1142
+ self.commands.append(("text", (label, x, y, just, rot, gp, default_units), {}))
1143
+ from .text import GridText, draw_richtext
1144
+
1145
+ if isinstance(label, GridText):
1146
+ draw_richtext(self, label, x=x, y=y, just=just, rot=rot, gp=gp, default_units=default_units)
1147
+ return
1148
+
1149
+ vp = self.current_vp
1150
+ labels = [label] if isinstance(label, (str, int, float, np.number)) or label is None else list(label)
1151
+ n = len(labels)
1152
+ if n == 0:
1153
+ return
1154
+ ux = unit(0.5, "npc") if x is None else as_unit(x, default_units)
1155
+ uy = unit(0.5, "npc") if y is None else as_unit(y, default_units)
1156
+ xmm = vp.x0_mm + ux.to_mm("x", vp, pos_mode=True)
1157
+ ymm = vp.y0_mm + uy.to_mm("y", vp, pos_mode=True)
1158
+ xmm, ymm = np.broadcast_arrays(xmm, ymm, np.zeros(n))[:2]
1159
+ jx, jy = parse_just(just)
1160
+ ha, va = _just_to_ha_va(jx, jy)
1161
+ gp_n = recycle_gp(gp or {}, n)
1162
+ cb = self._clip_bbox(vp)
1163
+ for k in range(n):
1164
+ lbl = labels[k]
1165
+ if lbl is None or (isinstance(lbl, float) and math.isnan(lbl)):
1166
+ continue
1167
+ gpk = subset_gp(gp_n, k)
1168
+ col = to_rgba_tuple(gpk.get("col", "#000000FF"))
1169
+ if col[3] == 0.0:
1170
+ continue
1171
+ fs, ff, weight, style = _font_props(gpk)
1172
+ t = self.ax.text(
1173
+ float(xmm[k]),
1174
+ float(ymm[k]),
1175
+ str(lbl),
1176
+ fontsize=fs,
1177
+ fontfamily=ff,
1178
+ fontweight=weight,
1179
+ fontstyle=style,
1180
+ color=col,
1181
+ rotation=float(rot),
1182
+ rotation_mode="anchor",
1183
+ ha=ha,
1184
+ va=va,
1185
+ )
1186
+ if cb is not None:
1187
+ t.set_clip_box(cb)
1188
+
1189
+ def draw_raster(
1190
+ self,
1191
+ image: np.ndarray,
1192
+ x: Any = None,
1193
+ y: Any = None,
1194
+ width: Any = None,
1195
+ height: Any = None,
1196
+ just: Any = "centre",
1197
+ interpolate: bool = False,
1198
+ default_units: str = "npc",
1199
+ ) -> None:
1200
+ if self.record:
1201
+ self.commands.append(("raster", (image, x, y, width, height, just, interpolate, default_units), {}))
1202
+ vp = self.current_vp
1203
+ ux = unit(0.5, "npc") if x is None else as_unit(x, default_units)
1204
+ uy = unit(0.5, "npc") if y is None else as_unit(y, default_units)
1205
+ uw = unit(1.0, "npc") if width is None else as_unit(width, default_units)
1206
+ uh = unit(1.0, "npc") if height is None else as_unit(height, default_units)
1207
+ cx = vp.x0_mm + ux.to_mm("x", vp, pos_mode=True)[0]
1208
+ cy = vp.y0_mm + uy.to_mm("y", vp, pos_mode=True)[0]
1209
+ w = uw.to_mm("x", vp, pos_mode=False)[0]
1210
+ h = uh.to_mm("y", vp, pos_mode=False)[0]
1211
+ jx, jy = parse_just(just)
1212
+ x0 = cx - jx * w
1213
+ y0 = cy - jy * h
1214
+ im = self.ax.imshow(
1215
+ image,
1216
+ extent=(x0, x0 + w, y0, y0 + h),
1217
+ aspect="auto",
1218
+ interpolation="bilinear" if interpolate else "nearest",
1219
+ origin="upper",
1220
+ )
1221
+ cb = self._clip_bbox(vp)
1222
+ if cb is not None:
1223
+ im.set_clip_box(cb)
1224
+
1225
+
1226
+ _DEVICE_STACK: list[GridDevice] = []
1227
+
1228
+
1229
+ def current_device(create: bool = True) -> GridDevice:
1230
+ if not _DEVICE_STACK:
1231
+ if not create:
1232
+ raise RuntimeError("No active GridDevice.")
1233
+ _DEVICE_STACK.append(GridDevice())
1234
+ return _DEVICE_STACK[-1]
1235
+
1236
+
1237
+ def set_current_device(dev: GridDevice) -> None:
1238
+ if not _DEVICE_STACK:
1239
+ _DEVICE_STACK.append(dev)
1240
+ else:
1241
+ _DEVICE_STACK[-1] = dev
1242
+
1243
+
1244
+ def grid_newpage(width_in: float = 8.0, height_in: float = 8.0, dpi: float = 100.0, fig: matplotlib.figure.Figure | None = None) -> GridDevice:
1245
+ dev = GridDevice(width_in=width_in, height_in=height_in, dpi=dpi, fig=fig)
1246
+ set_current_device(dev)
1247
+ return dev
1248
+
1249
+
1250
+ def pushViewport(vp: Viewport) -> Viewport:
1251
+ return current_device().push_viewport(vp)
1252
+
1253
+
1254
+ def popViewport(n: int = 1) -> None:
1255
+ current_device().pop_viewport(n)
1256
+
1257
+
1258
+ def upViewport(n: int = 1) -> None:
1259
+ current_device().pop_viewport(n)
1260
+
1261
+
1262
+ def seekViewport(name: str) -> Viewport:
1263
+ return current_device().seek_viewport(name)
1264
+
1265
+
1266
+ def current_viewport() -> Viewport:
1267
+ return current_device().current_vp
1268
+
1269
+
1270
+ def list_components(pattern: str | None = None) -> list[str]:
1271
+ """List named viewports on the active device, optionally filtered by regex."""
1272
+ import re
1273
+
1274
+ dev = current_device(create=False) if _DEVICE_STACK else None
1275
+ if dev is None:
1276
+ return []
1277
+ names = [nm for nm in dev.named_viewports.keys() if not re.fullmatch(r"\d+", nm) and not nm.startswith("GRID.VP")]
1278
+ if pattern is not None:
1279
+ rx = re.compile(pattern)
1280
+ names = [nm for nm in names if rx.search(nm)]
1281
+ return names
1282
+
1283
+
1284
+ def getXY_in_parent_vp(u: dict[str, Unit] | tuple[Unit, Unit]) -> dict[str, Unit]:
1285
+ """Convert point `(x, y)` in the current viewport into parent viewport's `mm` units."""
1286
+ dev = current_device()
1287
+ if len(dev.vp_stack) < 2:
1288
+ raise RuntimeError("Current viewport is ROOT; no parent viewport.")
1289
+ cur = dev.vp_stack[-1]
1290
+ parent = dev.vp_stack[-2]
1291
+ if isinstance(u, dict):
1292
+ ux, uy = as_unit(u["x"], "npc"), as_unit(u["y"], "npc")
1293
+ else:
1294
+ ux, uy = as_unit(u[0], "npc"), as_unit(u[1], "npc")
1295
+ px = (cur.x0_mm + ux.to_mm("x", cur, pos_mode=True)) - parent.x0_mm
1296
+ py = (cur.y0_mm + uy.to_mm("y", cur, pos_mode=True)) - parent.y0_mm
1297
+ return {"x": unit(px[0] if len(px) == 1 else px, "mm"), "y": unit(py[0] if len(py) == 1 else py, "mm")}
1298
+
1299
+
1300
+ def textGrob(label: Any, x: Any = None, y: Any = None, just: Any = "centre", rot: float = 0.0, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> TextGrob:
1301
+ return TextGrob(label=label, x=x, y=y, just=just, rot=rot, gp=gp, default_units=default_units, name=name, vp=vp)
1302
+
1303
+
1304
+ def rectGrob(x: Any = None, y: Any = None, width: Any = None, height: Any = None, just: Any = "centre", gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> RectGrob:
1305
+ return RectGrob(x=x, y=y, width=width, height=height, just=just, gp=gp, default_units=default_units, name=name, vp=vp)
1306
+
1307
+
1308
+ def roundrectGrob(x: Any = None, y: Any = None, width: Any = None, height: Any = None, r: Any = None, just: Any = "centre", gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> RoundRectGrob:
1309
+ return RoundRectGrob(x=x, y=y, width=width, height=height, r=r, just=just, gp=gp, default_units=default_units, name=name, vp=vp)
1310
+
1311
+
1312
+ def linesGrob(x: Any, y: Any, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> LinesGrob:
1313
+ return LinesGrob(x=x, y=y, gp=gp, default_units=default_units, name=name, vp=vp)
1314
+
1315
+
1316
+ def segmentsGrob(x0: Any, y0: Any, x1: Any, y1: Any, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> SegmentsGrob:
1317
+ return SegmentsGrob(x0=x0, y0=y0, x1=x1, y1=y1, gp=gp, default_units=default_units, name=name, vp=vp)
1318
+
1319
+
1320
+ def polygonGrob(x: Any, y: Any, id: Any = None, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> PolygonGrob:
1321
+ return PolygonGrob(x=x, y=y, id=id, gp=gp, default_units=default_units, name=name, vp=vp)
1322
+
1323
+
1324
+ def pointsGrob(x: Any, y: Any, pch: Any = 1, size: Any = None, gp: dict[str, Any] | None = None, default_units: str = "npc", name: str | None = None, vp: Viewport | None = None) -> PointsGrob:
1325
+ return PointsGrob(x=x, y=y, pch=pch, size=size, gp=gp, default_units=default_units, name=name, vp=vp)
1326
+
1327
+
1328
+ def grobWidth(grob: Grob) -> Unit:
1329
+ return Unit([1.0], "grobwidth", _refs=[grob])
1330
+
1331
+
1332
+ def grobHeight(grob: Grob) -> Unit:
1333
+ return Unit([1.0], "grobheight", _refs=[grob])
1334
+
1335
+
1336
+ def stringWidth(text: str, gp: dict[str, Any] | None = None, rot: float = 0.0) -> Unit:
1337
+ return Unit([1.0], "strwidth", _refs=[(text, gp or {}, rot)])
1338
+
1339
+
1340
+ def stringHeight(text: str, gp: dict[str, Any] | None = None, rot: float = 0.0) -> Unit:
1341
+ return Unit([1.0], "strheight", _refs=[(text, gp or {}, rot)])
1342
+
1343
+
1344
+ def max_text_width(text: Any, gp: dict[str, Any] | None = None, rot: float = 0.0) -> Unit:
1345
+ """Maximum rendered width of text items in mm."""
1346
+ if text is None:
1347
+ return unit(0.0, "mm")
1348
+ from .text import GridText
1349
+
1350
+ if isinstance(text, GridText):
1351
+ n = len(text)
1352
+ if n == 0:
1353
+ return unit(0.0, "mm")
1354
+ gp_n = recycle_gp(gp or {}, n)
1355
+ mx = 0.0
1356
+ for i in range(n):
1357
+ g = textGrob(text[i], gp=subset_gp(gp_n, i), rot=rot)
1358
+ mx = max(mx, g.width_mm())
1359
+ return unit(mx, "mm")
1360
+ items = [text] if isinstance(text, (str, int, float, np.number)) else list(text)
1361
+ if not items:
1362
+ return unit(0.0, "mm")
1363
+ gp_n = recycle_gp(gp or {}, len(items))
1364
+ mx = max(textGrob(items[i], gp=subset_gp(gp_n, i), rot=rot).width_mm() for i in range(len(items)))
1365
+ return unit(mx, "mm")
1366
+
1367
+
1368
+ def max_text_height(text: Any, gp: dict[str, Any] | None = None, rot: float = 0.0) -> Unit:
1369
+ """Maximum rendered height of text items in mm."""
1370
+ if text is None:
1371
+ return unit(0.0, "mm")
1372
+ from .text import GridText
1373
+
1374
+ if isinstance(text, GridText):
1375
+ n = len(text)
1376
+ if n == 0:
1377
+ return unit(0.0, "mm")
1378
+ gp_n = recycle_gp(gp or {}, n)
1379
+ mx = 0.0
1380
+ for i in range(n):
1381
+ g = textGrob(text[i], gp=subset_gp(gp_n, i), rot=rot)
1382
+ mx = max(mx, g.height_mm())
1383
+ return unit(mx, "mm")
1384
+ items = [text] if isinstance(text, (str, int, float, np.number)) else list(text)
1385
+ if not items:
1386
+ return unit(0.0, "mm")
1387
+ gp_n = recycle_gp(gp or {}, len(items))
1388
+ mx = max(textGrob(items[i], gp=subset_gp(gp_n, i), rot=rot).height_mm() for i in range(len(items)))
1389
+ return unit(mx, "mm")
1390
+
1391
+
1392
+ def grid_rect(x: Any = None, y: Any = None, width: Any = None, height: Any = None, just: Any = "centre", gp: dict[str, Any] | None = None, default_units: str = "npc", **kwargs: Any) -> None:
1393
+ default_units = kwargs.pop("default.units", default_units)
1394
+ current_device().draw_rect(x=x, y=y, width=width, height=height, just=just, gp=gp, default_units=default_units)
1395
+
1396
+
1397
+ def grid_roundrect(x: Any = None, y: Any = None, width: Any = None, height: Any = None, r: Any = None, just: Any = "centre", gp: dict[str, Any] | None = None, default_units: str = "npc", **kwargs: Any) -> None:
1398
+ default_units = kwargs.pop("default.units", default_units)
1399
+ current_device().draw_roundrect(x=x, y=y, width=width, height=height, r=r, just=just, gp=gp, default_units=default_units)
1400
+
1401
+
1402
+ def grid_lines(x: Any, y: Any, gp: dict[str, Any] | None = None, default_units: str = "npc", **kwargs: Any) -> None:
1403
+ default_units = kwargs.pop("default.units", default_units)
1404
+ current_device().draw_lines(x=x, y=y, gp=gp, default_units=default_units)
1405
+
1406
+
1407
+ def grid_segments(x0: Any, y0: Any, x1: Any, y1: Any, gp: dict[str, Any] | None = None, default_units: str = "npc", **kwargs: Any) -> None:
1408
+ default_units = kwargs.pop("default.units", default_units)
1409
+ current_device().draw_segments(x0=x0, y0=y0, x1=x1, y1=y1, gp=gp, default_units=default_units)
1410
+
1411
+
1412
+ def grid_polygon(x: Any, y: Any, id: Any = None, gp: dict[str, Any] | None = None, default_units: str = "npc", **kwargs: Any) -> None:
1413
+ default_units = kwargs.pop("default.units", default_units)
1414
+ current_device().draw_polygon(x=x, y=y, id=id, gp=gp, default_units=default_units)
1415
+
1416
+
1417
+ def grid_circle(x: Any = None, y: Any = None, r: Any = None, gp: dict[str, Any] | None = None, default_units: str = "npc", **kwargs: Any) -> None:
1418
+ default_units = kwargs.pop("default.units", default_units)
1419
+ current_device().draw_circle(x=x, y=y, r=r, gp=gp, default_units=default_units)
1420
+
1421
+
1422
+ def grid_points(x: Any, y: Any, pch: Any = 1, size: Any = None, gp: dict[str, Any] | None = None, default_units: str = "native", **kwargs: Any) -> None:
1423
+ default_units = kwargs.pop("default.units", default_units)
1424
+ current_device().draw_points(x=x, y=y, pch=pch, size=size, gp=gp, default_units=default_units)
1425
+
1426
+
1427
+ def grid_text(label: Any, x: Any = None, y: Any = None, just: Any = "centre", rot: float = 0.0, gp: dict[str, Any] | None = None, default_units: str = "npc", **kwargs: Any) -> None:
1428
+ default_units = kwargs.pop("default.units", default_units)
1429
+ current_device().draw_text(label=label, x=x, y=y, just=just, rot=rot, gp=gp, default_units=default_units)
1430
+
1431
+
1432
+ def grid_raster(image: np.ndarray, x: Any = None, y: Any = None, width: Any = None, height: Any = None, just: Any = "centre", interpolate: bool = False, default_units: str = "npc", **kwargs: Any) -> None:
1433
+ default_units = kwargs.pop("default.units", default_units)
1434
+ current_device().draw_raster(image=image, x=x, y=y, width=width, height=height, just=just, interpolate=interpolate, default_units=default_units)
1435
+
1436
+
1437
+ def grid_xaxis(at: Sequence[float] | None = None, label: Sequence[str] | bool = True, main: bool = True, gp: dict[str, Any] | None = None) -> None:
1438
+ vp = current_viewport()
1439
+ scale = vp.xscale
1440
+ ticks = grid_pretty(scale) if at is None else np.asarray(at, dtype=float)
1441
+ y_pos = 0.0 if main else 1.0
1442
+ tick_dy = unit(-1.5 if main else 1.5, "mm")
1443
+ lbl_dy = unit(-2.5 if main else 2.5, "mm")
1444
+ grid_lines([scale[0], scale[1]], [y_pos, y_pos], gp=gp, default_units="native")
1445
+ # Actually y is npc, x is native:
1446
+ grid_segments(unit(scale[0], "native"), unit(y_pos, "npc"), unit(scale[1], "native"), unit(y_pos, "npc"), gp=gp)
1447
+ if len(ticks) > 0:
1448
+ grid_segments(unit(ticks, "native"), unit(y_pos, "npc"), unit(ticks, "native"), unit(y_pos, "npc") + tick_dy, gp=gp)
1449
+ if label is not False:
1450
+ lbls = [f"{v:g}" for v in ticks] if label is True else [str(v) for v in label]
1451
+ grid_text(lbls, unit(ticks, "native"), unit(y_pos, "npc") + lbl_dy, just="top" if main else "bottom", gp=gp)
1452
+
1453
+
1454
+ def grid_yaxis(at: Sequence[float] | None = None, label: Sequence[str] | bool = True, main: bool = True, gp: dict[str, Any] | None = None) -> None:
1455
+ vp = current_viewport()
1456
+ scale = vp.yscale
1457
+ ticks = grid_pretty(scale) if at is None else np.asarray(at, dtype=float)
1458
+ x_pos = 0.0 if main else 1.0
1459
+ tick_dx = unit(-1.5 if main else 1.5, "mm")
1460
+ lbl_dx = unit(-2.5 if main else 2.5, "mm")
1461
+ grid_segments(unit(x_pos, "npc"), unit(scale[0], "native"), unit(x_pos, "npc"), unit(scale[1], "native"), gp=gp)
1462
+ if len(ticks) > 0:
1463
+ grid_segments(unit(x_pos, "npc"), unit(ticks, "native"), unit(x_pos, "npc") + tick_dx, unit(ticks, "native"), gp=gp)
1464
+ if label is not False:
1465
+ lbls = [f"{v:g}" for v in ticks] if label is True else [str(v) for v in label]
1466
+ grid_text(lbls, unit(x_pos, "npc") + lbl_dx, unit(ticks, "native"), just="right" if main else "left", gp=gp)
1467
+
1468
+
1469
+ def grid_draw(obj: Any, **kwargs: Any) -> None:
1470
+ if hasattr(obj, "draw") and callable(obj.draw):
1471
+ # Check if it's a Legends or Grob object
1472
+ obj.draw(**kwargs) if not isinstance(obj, Grob) else obj.draw()
1473
+ else:
1474
+ raise TypeError(f"Cannot draw object of type {type(obj).__name__}.")
1475
+
1476
+
1477
+ def grid_grabExpr(expr_fn: Callable[[], Any], width_in: float = 8.0, height_in: float = 8.0) -> CapturedGrob:
1478
+ """Execute `expr_fn()` on an offscreen recording GridDevice and return a replayable CapturedGrob."""
1479
+ rec = GridDevice(width_in=width_in, height_in=height_in, record=True)
1480
+ _DEVICE_STACK.append(rec)
1481
+ try:
1482
+ expr_fn()
1483
+ finally:
1484
+ _DEVICE_STACK.pop()
1485
+ plt.close(rec.fig)
1486
+ return CapturedGrob(rec.commands, width_mm=rec.w_mm, height_mm=rec.h_mm)
1487
+
1488
+
1489
+ def grid_boxplot(
1490
+ value: Sequence[float],
1491
+ pos: float = 0.5,
1492
+ outline: bool = True,
1493
+ box_width: float = 0.6,
1494
+ pch: Any = 1,
1495
+ size: Any = None,
1496
+ gp: dict[str, Any] | None = None,
1497
+ direction: str = "vertical",
1498
+ ) -> None:
1499
+ """Draw a single boxplot at `pos` in native coordinates inside the current viewport."""
1500
+ arr = np.asarray(value, dtype=float)
1501
+ arr = arr[np.isfinite(arr)]
1502
+ if len(arr) == 0:
1503
+ return
1504
+ q1, med, q3 = np.quantile(arr, [0.25, 0.5, 0.75])
1505
+ iqr = q3 - q1
1506
+ lo_fence = q1 - 1.5 * iqr
1507
+ hi_fence = q3 + 1.5 * iqr
1508
+ in_whisk = arr[(arr >= lo_fence) & (arr <= hi_fence)]
1509
+ w_lo = float(np.min(in_whisk)) if len(in_whisk) else float(q1)
1510
+ w_hi = float(np.max(in_whisk)) if len(in_whisk) else float(q3)
1511
+ outliers = arr[(arr < w_lo) | (arr > w_hi)]
1512
+
1513
+ gp_d = gpar(fill="#CCCCCC", col="black")
1514
+ if gp:
1515
+ gp_d.update(check_gp(gp))
1516
+ line_gp = subset_gp(gp_d, 0)
1517
+ line_gp.pop("fill", None)
1518
+ sz = unit(2.0, "mm") if size is None else as_unit(size, "mm")
1519
+ hw = 0.5 * float(box_width)
1520
+
1521
+ if direction == "vertical":
1522
+ grid_rect(x=pos, y=q1, width=box_width, height=max(0.0, q3 - q1), just="bottom", gp=gp_d, default_units="native")
1523
+ grid_segments([pos - hw, pos, pos, pos - hw * 0.5, pos - hw * 0.5], [med, q3, q1, w_hi, w_lo],
1524
+ [pos + hw, pos, pos, pos + hw * 0.5, pos + hw * 0.5], [med, w_hi, w_lo, w_hi, w_lo],
1525
+ gp=line_gp, default_units="native")
1526
+ if outline and len(outliers) > 0:
1527
+ grid_points(np.full(len(outliers), pos), outliers, pch=pch, size=sz, gp=line_gp, default_units="native")
1528
+ else:
1529
+ grid_rect(x=q1, y=pos, width=max(0.0, q3 - q1), height=box_width, just="left", gp=gp_d, default_units="native")
1530
+ grid_segments([med, q3, q1, w_hi, w_lo], [pos - hw, pos, pos, pos - hw * 0.5, pos - hw * 0.5],
1531
+ [med, w_hi, w_lo, w_hi, w_lo], [pos + hw, pos, pos, pos + hw * 0.5, pos + hw * 0.5],
1532
+ gp=line_gp, default_units="native")
1533
+ if outline and len(outliers) > 0:
1534
+ grid_points(outliers, np.full(len(outliers), pos), pch=pch, size=sz, gp=line_gp, default_units="native")
1535
+
1536
+
1537
+ class _GridNamespace:
1538
+ """R-style `grid.*` namespace object (supports `grid.rect(...)`, `grid.newpage()`, etc.)."""
1539
+
1540
+ newpage = staticmethod(grid_newpage)
1541
+ rect = staticmethod(grid_rect)
1542
+ roundrect = staticmethod(grid_roundrect)
1543
+ lines = staticmethod(grid_lines)
1544
+ segments = staticmethod(grid_segments)
1545
+ polygon = staticmethod(grid_polygon)
1546
+ circle = staticmethod(grid_circle)
1547
+ points = staticmethod(grid_points)
1548
+ text = staticmethod(grid_text)
1549
+ raster = staticmethod(grid_raster)
1550
+ xaxis = staticmethod(grid_xaxis)
1551
+ yaxis = staticmethod(grid_yaxis)
1552
+ draw = staticmethod(grid_draw)
1553
+ grabExpr = staticmethod(grid_grabExpr)
1554
+ boxplot = staticmethod(grid_boxplot)
1555
+ pretty = staticmethod(grid_pretty)
1556
+ ls = staticmethod(list_components)
1557
+ viewport = staticmethod(viewport)
1558
+ pushViewport = staticmethod(pushViewport)
1559
+ popViewport = staticmethod(popViewport)
1560
+ upViewport = staticmethod(upViewport)
1561
+ seekViewport = staticmethod(seekViewport)
1562
+ current_viewport = staticmethod(current_viewport)
1563
+
1564
+ @property
1565
+ def dendrogram(self):
1566
+ from .dendrogram import grid_dendrogram
1567
+ return grid_dendrogram
1568
+
1569
+ @property
1570
+ def textbox(self):
1571
+ from .text import grid_textbox
1572
+ return grid_textbox
1573
+
1574
+ @property
1575
+ def annotation_axis(self):
1576
+ from .annotations import grid_annotation_axis
1577
+ return grid_annotation_axis
1578
+
1579
+
1580
+ grid = _GridNamespace()