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
@@ -0,0 +1,718 @@
1
+ """Grid-compatible Unit system and graphical parameters (`gpar`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ from typing import Any, Iterable, Sequence
7
+
8
+ import numpy as np
9
+
10
+ from .colors import to_hex_rgba
11
+
12
+ # Unit conversion factors to millimeters
13
+ _POINTS_PER_INCH = 72.27
14
+ _BIGPTS_PER_INCH = 72.0
15
+ _MM_PER_INCH = 25.4
16
+ _MM_PER_PT = _MM_PER_INCH / _POINTS_PER_INCH
17
+ _MM_PER_BIGPT = _MM_PER_INCH / _BIGPTS_PER_INCH
18
+
19
+ _UNIT_ALIASES: dict[str, str] = {
20
+ "mm": "mm",
21
+ "millimetre": "mm",
22
+ "millimetres": "mm",
23
+ "millimeter": "mm",
24
+ "millimeters": "mm",
25
+ "cm": "cm",
26
+ "centimetre": "cm",
27
+ "centimetres": "cm",
28
+ "centimeter": "cm",
29
+ "centimeters": "cm",
30
+ "in": "inches",
31
+ "inch": "inches",
32
+ "inches": "inches",
33
+ "pt": "points",
34
+ "point": "points",
35
+ "points": "points",
36
+ "bigpts": "bigpts",
37
+ "bigpt": "bigpts",
38
+ "picas": "picas",
39
+ "pica": "picas",
40
+ "dida": "dida",
41
+ "cicero": "cicero",
42
+ "scaledpts": "scaledpts",
43
+ "line": "lines",
44
+ "lines": "lines",
45
+ "myline": "lines",
46
+ "mylines": "lines",
47
+ "char": "char",
48
+ "mychar": "char",
49
+ "npc": "npc",
50
+ "snpc": "snpc",
51
+ "native": "native",
52
+ "null": "null",
53
+ "grobwidth": "grobwidth",
54
+ "grobheight": "grobheight",
55
+ "strwidth": "strwidth",
56
+ "mystrwidth": "strwidth",
57
+ "strheight": "strheight",
58
+ "mystrheight": "strheight",
59
+ "strascent": "strascent",
60
+ "strdescent": "strdescent",
61
+ }
62
+
63
+ ABS_UNITS = frozenset({
64
+ "cm", "inches", "mm", "points", "picas", "bigpts", "dida", "cicero",
65
+ "scaledpts", "lines", "char", "strwidth", "strheight", "grobwidth",
66
+ "grobheight", "strascent", "strdescent",
67
+ })
68
+
69
+ _LTY_MAP = {
70
+ 0: "none",
71
+ 1: "solid",
72
+ 2: "dashed",
73
+ 3: "dotted",
74
+ 4: "dotdash",
75
+ 5: "longdash",
76
+ 6: "twodash",
77
+ "blank": "none",
78
+ "solid": "solid",
79
+ "dashed": "dashed",
80
+ "dotted": "dotted",
81
+ "dotdash": "dotdash",
82
+ "longdash": "longdash",
83
+ "twodash": "twodash",
84
+ "none": "none",
85
+ }
86
+
87
+ _FONTFACE_MAP = {
88
+ 1: ("normal", "normal"),
89
+ 2: ("bold", "normal"),
90
+ 3: ("normal", "italic"),
91
+ 4: ("bold", "italic"),
92
+ "plain": ("normal", "normal"),
93
+ "normal": ("normal", "normal"),
94
+ "bold": ("bold", "normal"),
95
+ "italic": ("normal", "italic"),
96
+ "oblique": ("normal", "oblique"),
97
+ "bold.italic": ("bold", "italic"),
98
+ "bold_italic": ("bold", "italic"),
99
+ "bold italic": ("bold", "italic"),
100
+ }
101
+
102
+
103
+ def _norm_unit_name(name: str) -> str:
104
+ key = name.strip().lower()
105
+ if key not in _UNIT_ALIASES:
106
+ raise ValueError(f"Unsupported unit type: {name!r}")
107
+ return _UNIT_ALIASES[key]
108
+
109
+
110
+ def _text_dims_mm(text: str, gp: dict[str, Any] | None = None, rot: float = 0.0) -> tuple[float, float]:
111
+ """Measure width and height in mm of a text string using Matplotlib's TextPath."""
112
+ from matplotlib.textpath import TextPath
113
+ from matplotlib.font_manager import FontProperties
114
+ import math
115
+
116
+ if text is None or text == "":
117
+ return (0.0, 0.0)
118
+ s = str(text)
119
+ gp = gp or {}
120
+ fontsize = gp.get("fontsize", 12.0)
121
+ if isinstance(fontsize, (list, tuple, np.ndarray)):
122
+ fontsize = float(fontsize[0])
123
+ cex = gp.get("cex", 1.0)
124
+ if isinstance(cex, (list, tuple, np.ndarray)):
125
+ cex = float(cex[0])
126
+ eff_fs = float(fontsize) * float(cex)
127
+ fontfamily = gp.get("fontfamily", "sans-serif")
128
+ if isinstance(fontfamily, (list, tuple, np.ndarray)):
129
+ fontfamily = str(fontfamily[0])
130
+ if not fontfamily:
131
+ fontfamily = "sans-serif"
132
+ fontface = gp.get("fontface", "plain")
133
+ if isinstance(fontface, (list, tuple, np.ndarray)):
134
+ fontface = fontface[0]
135
+ weight, style = _FONTFACE_MAP.get(fontface, ("normal", "normal"))
136
+ prop = FontProperties(family=fontfamily, weight=weight, style=style, size=eff_fs)
137
+
138
+ lines = s.split("\n")
139
+ max_w_pt = 0.0
140
+ total_h_pt = 0.0
141
+ line_gap_pt = eff_fs * 0.25
142
+ for idx, ln in enumerate(lines):
143
+ if ln.strip() == "":
144
+ w_pt = len(ln) * eff_fs * 0.28
145
+ h_pt = eff_fs * 0.72
146
+ else:
147
+ tp = TextPath((0, 0), ln, prop=prop)
148
+ bb = tp.get_extents()
149
+ w_pt = float(bb.width)
150
+ h_pt = max(float(bb.height), eff_fs * 0.72)
151
+ if w_pt > max_w_pt:
152
+ max_w_pt = w_pt
153
+ total_h_pt += h_pt + (line_gap_pt if idx > 0 else 0.0)
154
+
155
+ w_mm = max_w_pt * _MM_PER_BIGPT
156
+ h_mm = total_h_pt * _MM_PER_BIGPT
157
+
158
+ if rot % 360 != 0:
159
+ rad = math.radians(rot)
160
+ c = abs(math.cos(rad))
161
+ sn = abs(math.sin(rad))
162
+ w_rot = w_mm * c + h_mm * sn
163
+ h_rot = w_mm * sn + h_mm * c
164
+ return (w_rot, h_rot)
165
+ return (w_mm, h_mm)
166
+
167
+
168
+ class Unit:
169
+ """Vectorized unit expression tree analogous to R `grid::unit`."""
170
+
171
+ __slots__ = ("_op", "_values", "_unit", "_refs", "_left", "_right", "_scalar", "_items")
172
+
173
+ def __init__(
174
+ self,
175
+ values: Any = None,
176
+ units: str = "npc",
177
+ *,
178
+ _op: str | None = None,
179
+ _refs: list[Any] | None = None,
180
+ _left: "Unit | None" = None,
181
+ _right: "Unit | None" = None,
182
+ _scalar: np.ndarray | float | None = None,
183
+ _items: list["Unit"] | None = None,
184
+ ) -> None:
185
+ self._op = _op
186
+ self._refs = _refs
187
+ self._left = _left
188
+ self._right = _right
189
+ self._scalar = _scalar
190
+ self._items = _items
191
+ if _op is None:
192
+ arr = np.atleast_1d(np.asarray(values, dtype=float))
193
+ if arr.ndim != 1:
194
+ arr = arr.ravel()
195
+ self._values = arr
196
+ self._unit = _norm_unit_name(units)
197
+ else:
198
+ self._values = None
199
+ self._unit = None
200
+
201
+ def __len__(self) -> int:
202
+ if self._op is None:
203
+ return len(self._values)
204
+ if self._op in ("add", "sub", "pmax", "pmin"):
205
+ if self._items is not None:
206
+ return max(len(it) for it in self._items)
207
+ return max(len(self._left), len(self._right))
208
+ if self._op in ("mul", "div"):
209
+ l_len = len(self._left)
210
+ if isinstance(self._scalar, np.ndarray) and self._scalar.ndim >= 1:
211
+ return max(l_len, len(self._scalar))
212
+ return l_len
213
+ if self._op == "concat":
214
+ return sum(len(it) for it in self._items)
215
+ if self._op in ("sum", "max", "min"):
216
+ return 1
217
+ return 1
218
+
219
+ def __getitem__(self, idx: Any) -> "Unit":
220
+ if self._op is None:
221
+ vals = self._values[idx]
222
+ refs = None
223
+ if self._refs is not None:
224
+ if isinstance(idx, slice):
225
+ refs = self._refs[idx]
226
+ elif isinstance(idx, (int, np.integer)):
227
+ refs = [self._refs[int(idx)]]
228
+ elif isinstance(idx, (list, tuple, np.ndarray)):
229
+ arr_idx = np.asarray(idx)
230
+ if arr_idx.dtype == bool:
231
+ refs = [r for r, flag in zip(self._refs, arr_idx) if flag]
232
+ else:
233
+ refs = [self._refs[int(i)] for i in arr_idx]
234
+ return Unit(vals, self._unit, _refs=refs)
235
+
236
+ if self._op == "concat":
237
+ # Flatten elements to index accurately
238
+ flat: list[Unit] = []
239
+ for it in self._items:
240
+ for k in range(len(it)):
241
+ flat.append(it[k])
242
+ selected = flat[idx] if isinstance(idx, slice) else (
243
+ [flat[int(idx)]] if isinstance(idx, (int, np.integer)) else None
244
+ )
245
+ if selected is None:
246
+ arr_idx = np.asarray(idx)
247
+ if arr_idx.dtype == bool:
248
+ selected = [u for u, f in zip(flat, arr_idx) if f]
249
+ else:
250
+ selected = [flat[int(i)] for i in arr_idx]
251
+ if not selected:
252
+ return unit([], "mm")
253
+ if len(selected) == 1:
254
+ return selected[0]
255
+ return Unit(_op="concat", _items=selected)
256
+
257
+ if self._op in ("add", "sub", "pmax", "pmin"):
258
+ n = len(self)
259
+ def _sub_with_broadcast(u: Unit) -> Unit:
260
+ if len(u) == 1:
261
+ return u
262
+ return u[idx]
263
+ if self._items is not None:
264
+ return Unit(_op=self._op, _items=[_sub_with_broadcast(it) for it in self._items])
265
+ return Unit(_op=self._op, _left=_sub_with_broadcast(self._left), _right=_sub_with_broadcast(self._right))
266
+
267
+ if self._op in ("mul", "div"):
268
+ left_s = self._left if len(self._left) == 1 else self._left[idx]
269
+ sc = self._scalar
270
+ if isinstance(sc, np.ndarray) and sc.ndim >= 1 and len(sc) > 1:
271
+ sc = sc[idx]
272
+ return Unit(_op=self._op, _left=left_s, _scalar=sc)
273
+
274
+ return self
275
+
276
+ def __add__(self, other: Any) -> "Unit":
277
+ if not isinstance(other, Unit):
278
+ return NotImplemented
279
+ return Unit(_op="add", _left=self, _right=other)
280
+
281
+ def __radd__(self, other: Any) -> "Unit":
282
+ if other == 0:
283
+ return self
284
+ if not isinstance(other, Unit):
285
+ return NotImplemented
286
+ return Unit(_op="add", _left=other, _right=self)
287
+
288
+ def __sub__(self, other: Any) -> "Unit":
289
+ if not isinstance(other, Unit):
290
+ return NotImplemented
291
+ return Unit(_op="sub", _left=self, _right=other)
292
+
293
+ def __neg__(self) -> "Unit":
294
+ return Unit(_op="mul", _left=self, _scalar=-1.0)
295
+
296
+ def __mul__(self, other: Any) -> "Unit":
297
+ if isinstance(other, (int, float, np.number, list, tuple, np.ndarray)):
298
+ sc = float(other) if np.ndim(other) == 0 else np.asarray(other, dtype=float)
299
+ return Unit(_op="mul", _left=self, _scalar=sc)
300
+ return NotImplemented
301
+
302
+ def __rmul__(self, other: Any) -> "Unit":
303
+ return self.__mul__(other)
304
+
305
+ def __truediv__(self, other: Any) -> "Unit":
306
+ if isinstance(other, (int, float, np.number, list, tuple, np.ndarray)):
307
+ sc = float(other) if np.ndim(other) == 0 else np.asarray(other, dtype=float)
308
+ return Unit(_op="div", _left=self, _scalar=sc)
309
+ return NotImplemented
310
+
311
+ def _unit_types(self) -> set[str]:
312
+ if self._op is None:
313
+ return {self._unit}
314
+ out: set[str] = set()
315
+ if self._left is not None:
316
+ out |= self._left._unit_types()
317
+ if self._right is not None:
318
+ out |= self._right._unit_types()
319
+ if self._items is not None:
320
+ for it in self._items:
321
+ out |= it._unit_types()
322
+ return out
323
+
324
+ def is_abs(self) -> bool:
325
+ return self._unit_types().issubset(ABS_UNITS)
326
+
327
+ def _eval_mm(self, axis: str, vp: Any = None, pos_mode: bool = False) -> np.ndarray:
328
+ w_mm = getattr(vp, "w_mm", 200.0) if vp is not None else 200.0
329
+ h_mm = getattr(vp, "h_mm", 200.0) if vp is not None else 200.0
330
+ xscale = getattr(vp, "xscale", (0.0, 1.0)) if vp is not None else (0.0, 1.0)
331
+ yscale = getattr(vp, "yscale", (0.0, 1.0)) if vp is not None else (0.0, 1.0)
332
+ vp_gp = getattr(vp, "gp", {}) if vp is not None else {}
333
+ fs = float(vp_gp.get("fontsize", 12.0)) * float(vp_gp.get("cex", 1.0))
334
+
335
+ if self._op is None:
336
+ u = self._unit
337
+ vals = self._values
338
+ if u == "mm":
339
+ return vals.copy()
340
+ if u == "cm":
341
+ return vals * 10.0
342
+ if u == "inches":
343
+ return vals * _MM_PER_INCH
344
+ if u == "points":
345
+ return vals * _MM_PER_PT
346
+ if u == "bigpts":
347
+ return vals * _MM_PER_BIGPT
348
+ if u == "picas":
349
+ return vals * (12.0 * _MM_PER_PT)
350
+ if u == "dida":
351
+ return vals * 0.376
352
+ if u == "cicero":
353
+ return vals * (12.0 * 0.376)
354
+ if u == "scaledpts":
355
+ return vals * (_MM_PER_PT / 65536.0)
356
+ if u == "lines":
357
+ return vals * (fs * 1.2 * _MM_PER_BIGPT)
358
+ if u == "char":
359
+ return vals * (fs * _MM_PER_BIGPT)
360
+ if u == "npc":
361
+ dim = w_mm if axis == "x" else h_mm
362
+ return vals * dim
363
+ if u == "snpc":
364
+ return vals * min(w_mm, h_mm)
365
+ if u == "native":
366
+ if axis == "x":
367
+ s0, s1 = float(xscale[0]), float(xscale[1])
368
+ span = s1 - s0
369
+ if abs(span) < 1e-15:
370
+ return np.zeros_like(vals)
371
+ if pos_mode:
372
+ return ((vals - s0) / span) * w_mm
373
+ return (vals / abs(span)) * w_mm
374
+ else:
375
+ s0, s1 = float(yscale[0]), float(yscale[1])
376
+ span = s1 - s0
377
+ if abs(span) < 1e-15:
378
+ return np.zeros_like(vals)
379
+ if pos_mode:
380
+ return ((vals - s0) / span) * h_mm
381
+ return (vals / abs(span)) * h_mm
382
+ if u == "null":
383
+ return np.zeros_like(vals)
384
+ if u in ("grobwidth", "grobheight", "strwidth", "strheight", "strascent", "strdescent"):
385
+ out = np.zeros(len(vals), dtype=float)
386
+ refs = self._refs or []
387
+ for idx in range(len(vals)):
388
+ ref = refs[idx] if idx < len(refs) else None
389
+ if ref is None:
390
+ out[idx] = 0.0
391
+ elif u in ("strwidth", "strheight", "strascent", "strdescent"):
392
+ txt, tgp, rot = ref
393
+ tw, th = _text_dims_mm(txt, tgp, rot)
394
+ out[idx] = vals[idx] * (tw if u == "strwidth" else th)
395
+ elif hasattr(ref, "width_mm") and hasattr(ref, "height_mm"):
396
+ gw = ref.width_mm(vp)
397
+ gh = ref.height_mm(vp)
398
+ out[idx] = vals[idx] * (gw if u == "grobwidth" else gh)
399
+ return out
400
+ return vals.copy()
401
+
402
+ if self._op == "add":
403
+ a = self._left._eval_mm(axis, vp, pos_mode=pos_mode)
404
+ # In R grid, if both sides are native in position mode, pos_mode applies to sum;
405
+ # if left is native/npc and right is offset (mm/pt), right is an offset.
406
+ right_pos = False if pos_mode and not self._right._unit_types().intersection({"npc", "native"}) else pos_mode
407
+ if pos_mode and self._left._unit == "native" and self._right._unit == "native":
408
+ # R evaluates (v1 + v2 - s0)/span * dim
409
+ raw = self._left._values + self._right._values
410
+ return Unit(raw, "native")._eval_mm(axis, vp, pos_mode=True)
411
+ b = self._right._eval_mm(axis, vp, pos_mode=right_pos)
412
+ return a + b
413
+
414
+ if self._op == "sub":
415
+ a = self._left._eval_mm(axis, vp, pos_mode=pos_mode)
416
+ b = self._right._eval_mm(axis, vp, pos_mode=False)
417
+ return a - b
418
+
419
+ if self._op == "mul":
420
+ a = self._left._eval_mm(axis, vp, pos_mode=pos_mode)
421
+ return a * self._scalar
422
+
423
+ if self._op == "div":
424
+ a = self._left._eval_mm(axis, vp, pos_mode=pos_mode)
425
+ return a / self._scalar
426
+
427
+ if self._op == "concat":
428
+ parts = [it._eval_mm(axis, vp, pos_mode=pos_mode) for it in self._items]
429
+ return np.concatenate(parts) if parts else np.array([], dtype=float)
430
+
431
+ if self._op == "sum":
432
+ vals = self._left._eval_mm(axis, vp, pos_mode=pos_mode)
433
+ return np.array([float(np.sum(vals))])
434
+
435
+ if self._op == "max":
436
+ vals = np.concatenate([it._eval_mm(axis, vp, pos_mode=pos_mode) for it in self._items])
437
+ return np.array([float(np.max(vals)) if len(vals) else 0.0])
438
+
439
+ if self._op == "min":
440
+ vals = np.concatenate([it._eval_mm(axis, vp, pos_mode=pos_mode) for it in self._items])
441
+ return np.array([float(np.min(vals)) if len(vals) else 0.0])
442
+
443
+ if self._op == "pmax":
444
+ arrs = np.broadcast_arrays(*[it._eval_mm(axis, vp, pos_mode=pos_mode) for it in self._items])
445
+ return np.maximum.reduce(arrs)
446
+
447
+ if self._op == "pmin":
448
+ arrs = np.broadcast_arrays(*[it._eval_mm(axis, vp, pos_mode=pos_mode) for it in self._items])
449
+ return np.minimum.reduce(arrs)
450
+
451
+ raise ValueError(f"Unknown unit op: {self._op}")
452
+
453
+ def to_mm(self, axis: str = "x", vp: Any = None, pos_mode: bool = False) -> np.ndarray:
454
+ return self._eval_mm(axis=axis, vp=vp, pos_mode=pos_mode)
455
+
456
+ def to_mm_scalar(self, axis: str = "x", vp: Any = None, pos_mode: bool = False) -> float:
457
+ arr = self._eval_mm(axis=axis, vp=vp, pos_mode=pos_mode)
458
+ return float(arr[0]) if len(arr) else 0.0
459
+
460
+ def __repr__(self) -> str:
461
+ if self._op is None:
462
+ if len(self._values) == 1:
463
+ return f"{self._values[0]:g}{self._unit}"
464
+ vals = ", ".join(f"{v:g}{self._unit}" for v in self._values[:6])
465
+ if len(self._values) > 6:
466
+ vals += ", ..."
467
+ return f"unit([{vals}])"
468
+ if self._op == "add":
469
+ return f"({self._left!r} + {self._right!r})"
470
+ if self._op == "sub":
471
+ return f"({self._left!r} - {self._right!r})"
472
+ if self._op == "mul":
473
+ return f"({self._left!r} * {self._scalar})"
474
+ if self._op == "div":
475
+ return f"({self._left!r} / {self._scalar})"
476
+ if self._op == "concat":
477
+ return "unit.c(" + ", ".join(repr(it) for it in self._items) + ")"
478
+ return f"unit_expr({self._op})"
479
+
480
+
481
+ def unit(x: Any, units: str = "npc") -> Unit:
482
+ """Create a Unit object (equivalent to R `grid::unit`)."""
483
+ if isinstance(x, Unit):
484
+ return x
485
+ return Unit(x, units)
486
+
487
+
488
+ def is_unit(x: Any) -> bool:
489
+ return isinstance(x, Unit)
490
+
491
+
492
+ def as_unit(x: Any, default_units: str = "npc") -> Unit:
493
+ if isinstance(x, Unit):
494
+ return x
495
+ return Unit(x, default_units)
496
+
497
+
498
+ def unit_c(*args: Any) -> Unit:
499
+ """Concatenate multiple Unit objects into a single vector Unit."""
500
+ items = [a if isinstance(a, Unit) else unit(a, "npc") for a in args if a is not None]
501
+ if not items:
502
+ return unit([], "mm")
503
+ if len(items) == 1:
504
+ return items[0]
505
+ return Unit(_op="concat", _items=items)
506
+
507
+
508
+ def unit_sum(u: Unit) -> Unit:
509
+ return Unit(_op="sum", _left=u)
510
+
511
+
512
+ def unit_max(*args: Unit) -> Unit:
513
+ return Unit(_op="max", _items=[as_unit(a) for a in args])
514
+
515
+
516
+ def unit_min(*args: Unit) -> Unit:
517
+ return Unit(_op="min", _items=[as_unit(a) for a in args])
518
+
519
+
520
+ def unit_pmax(*args: Unit) -> Unit:
521
+ return Unit(_op="pmax", _items=[as_unit(a) for a in args])
522
+
523
+
524
+ def unit_pmin(*args: Unit) -> Unit:
525
+ return Unit(_op="pmin", _items=[as_unit(a) for a in args])
526
+
527
+
528
+ def unit_rep(u: Unit, times: int) -> Unit:
529
+ if len(u) == 1:
530
+ if u._op is None and u._refs is None:
531
+ return Unit(np.repeat(u._values, times), u._unit)
532
+ return Unit(_op="concat", _items=[u] * times)
533
+ return Unit(_op="concat", _items=[u] * times)
534
+
535
+
536
+ def is_abs_unit(u: Any) -> bool:
537
+ """Return True if `u` is a Unit composed exclusively of absolute units."""
538
+ if not isinstance(u, Unit):
539
+ return False
540
+ return u.is_abs()
541
+
542
+
543
+ def _resolve_vp(vp: Any) -> Any:
544
+ if vp is not None:
545
+ return vp
546
+ from .grid import _DEVICE_STACK
547
+ return _DEVICE_STACK[-1].current_vp if _DEVICE_STACK else None
548
+
549
+
550
+ def convert_unit(u: Any, unit_to: str = "mm", axis: str = "x", vp: Any = None, value_only: bool = False) -> Any:
551
+ vp = _resolve_vp(vp)
552
+ u_obj = as_unit(u, "mm")
553
+ mm_vals = u_obj.to_mm(axis=axis, vp=vp, pos_mode=False)
554
+ target = _norm_unit_name(unit_to)
555
+ scale = Unit(1.0, target).to_mm_scalar(axis=axis, vp=vp, pos_mode=False)
556
+ if scale == 0:
557
+ converted = np.zeros_like(mm_vals)
558
+ else:
559
+ converted = mm_vals / scale
560
+ if value_only:
561
+ return float(converted[0]) if len(converted) == 1 else converted
562
+ return Unit(converted[0] if len(converted) == 1 else converted, target)
563
+
564
+
565
+ def convertWidth(u: Any, unit_to: str = "mm", valueOnly: bool = False, vp: Any = None) -> Any:
566
+ return convert_unit(u, unit_to=unit_to, axis="x", vp=vp, value_only=valueOnly)
567
+
568
+
569
+ def convertHeight(u: Any, unit_to: str = "mm", valueOnly: bool = False, vp: Any = None) -> Any:
570
+ return convert_unit(u, unit_to=unit_to, axis="y", vp=vp, value_only=valueOnly)
571
+
572
+
573
+ def convertX(u: Any, unit_to: str = "mm", valueOnly: bool = False, vp: Any = None) -> Any:
574
+ vp = _resolve_vp(vp)
575
+ u_obj = as_unit(u, "npc")
576
+ mm_vals = u_obj.to_mm(axis="x", vp=vp, pos_mode=True)
577
+ target = _norm_unit_name(unit_to)
578
+ scale = Unit(1.0, target).to_mm_scalar(axis="x", vp=vp, pos_mode=False)
579
+ converted = mm_vals / scale if scale != 0 else np.zeros_like(mm_vals)
580
+ if valueOnly:
581
+ return float(converted[0]) if len(converted) == 1 else converted
582
+ return Unit(converted[0] if len(converted) == 1 else converted, target)
583
+
584
+
585
+ def convertY(u: Any, unit_to: str = "mm", valueOnly: bool = False, vp: Any = None) -> Any:
586
+ vp = _resolve_vp(vp)
587
+ u_obj = as_unit(u, "npc")
588
+ mm_vals = u_obj.to_mm(axis="y", vp=vp, pos_mode=True)
589
+ target = _norm_unit_name(unit_to)
590
+ scale = Unit(1.0, target).to_mm_scalar(axis="y", vp=vp, pos_mode=False)
591
+ converted = mm_vals / scale if scale != 0 else np.zeros_like(mm_vals)
592
+ if valueOnly:
593
+ return float(converted[0]) if len(converted) == 1 else converted
594
+ return Unit(converted[0] if len(converted) == 1 else converted, target)
595
+
596
+
597
+ # ---- Graphical parameters (gpar) ----
598
+
599
+ class Gpar(dict):
600
+ """Graphical parameters dictionary compatible with R `grid::gpar`."""
601
+
602
+ def copy(self) -> "Gpar":
603
+ return Gpar(**{k: copy.deepcopy(v) for k, v in self.items()})
604
+
605
+ def __getattr__(self, name: str) -> Any:
606
+ try:
607
+ return self[name]
608
+ except KeyError as exc:
609
+ raise AttributeError(name) from exc
610
+
611
+
612
+ def _normalize_gp_value(key: str, val: Any) -> Any:
613
+ if key in ("col", "fill", "box_fill", "box_col", "pos_fill", "neg_fill"):
614
+ if val is None:
615
+ return "#00000000"
616
+ if isinstance(val, (str, int, np.integer, float, np.floating)):
617
+ if isinstance(val, str) and val.lower() == "asis":
618
+ return "asis"
619
+ return to_hex_rgba(val)
620
+ if isinstance(val, tuple) and len(val) in (3, 4) and all(isinstance(v, (int, float, np.number)) for v in val):
621
+ return to_hex_rgba(val)
622
+ if isinstance(val, (list, tuple, np.ndarray)):
623
+ return [
624
+ "asis" if (isinstance(v, str) and v.lower() == "asis") else to_hex_rgba(v)
625
+ for v in val
626
+ ]
627
+ if key == "lty":
628
+ if isinstance(val, (list, tuple, np.ndarray)):
629
+ return [_LTY_MAP.get(v, v) for v in val]
630
+ return _LTY_MAP.get(val, val)
631
+ if key == "fontface":
632
+ return val
633
+ return val
634
+
635
+
636
+ def gpar(**kwargs: Any) -> Gpar:
637
+ """Create graphical parameters (col, fill, lwd, lty, fontsize, fontface, fontfamily, cex, alpha, ...)."""
638
+ norm = {k: _normalize_gp_value(k, v) for k, v in kwargs.items()}
639
+ return Gpar(norm)
640
+
641
+
642
+ def check_gp(gp: Any) -> Gpar:
643
+ if gp is None:
644
+ return Gpar()
645
+ if isinstance(gp, Gpar):
646
+ return gp.copy()
647
+ if isinstance(gp, dict):
648
+ return gpar(**gp)
649
+ raise TypeError("Graphical parameters must be created by `gpar(...)` or `dict`.")
650
+
651
+
652
+ def _gp_elem_len(v: Any) -> int:
653
+ if isinstance(v, (list, tuple, np.ndarray)) and not (
654
+ isinstance(v, tuple) and len(v) in (3, 4) and all(isinstance(x, (int, float, np.number)) for x in v)
655
+ ):
656
+ return len(v)
657
+ if isinstance(v, Unit):
658
+ return len(v)
659
+ return 1
660
+
661
+
662
+ def subset_gp(gp: dict[str, Any], i: Any) -> Gpar:
663
+ """Subset vectorized entries of a `gpar` object while keeping scalar entries intact."""
664
+ gp = check_gp(gp)
665
+ out = Gpar()
666
+ for k, v in gp.items():
667
+ if _gp_elem_len(v) <= 1:
668
+ if isinstance(v, (list, tuple, np.ndarray)) and not (
669
+ isinstance(v, tuple) and len(v) in (3, 4) and all(isinstance(x, (int, float, np.number)) for x in v)
670
+ ) and len(v) == 1:
671
+ out[k] = v[0]
672
+ else:
673
+ out[k] = v
674
+ elif isinstance(v, Unit):
675
+ out[k] = v[i]
676
+ elif isinstance(v, np.ndarray):
677
+ out[k] = v[i].tolist()
678
+ else:
679
+ if isinstance(i, slice):
680
+ out[k] = list(v)[i]
681
+ elif isinstance(i, (int, np.integer)):
682
+ out[k] = v[int(i)]
683
+ else:
684
+ arr_i = np.asarray(i)
685
+ if arr_i.dtype == bool:
686
+ out[k] = [val for val, flag in zip(v, arr_i) if flag]
687
+ else:
688
+ out[k] = [v[int(idx)] for idx in arr_i]
689
+ return out
690
+
691
+
692
+ def recycle_gp(gp: dict[str, Any], n: int = 1) -> Gpar:
693
+ """Recycle every entry of a `gpar` object to length `n`."""
694
+ gp = check_gp(gp)
695
+ out = Gpar()
696
+ for k, v in gp.items():
697
+ elen = _gp_elem_len(v)
698
+ if elen == 1:
699
+ scalar = v[0] if isinstance(v, (list, tuple, np.ndarray)) and not (
700
+ isinstance(v, tuple) and len(v) in (3, 4) and all(isinstance(x, (int, float, np.number)) for x in v)
701
+ ) else v
702
+ out[k] = [scalar] * n
703
+ elif elen == n:
704
+ out[k] = v if isinstance(v, Unit) else list(v)
705
+ else:
706
+ seq = list(v)
707
+ out[k] = [seq[idx % len(seq)] for idx in range(n)]
708
+ return out
709
+
710
+
711
+ def merge_gp(*gps: dict[str, Any] | None) -> Gpar:
712
+ """Merge multiple `gpar` dicts left-to-right (later overrides earlier)."""
713
+ merged = Gpar()
714
+ for gp in gps:
715
+ if gp:
716
+ for k, v in check_gp(gp).items():
717
+ merged[k] = v
718
+ return merged