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,848 @@
1
+ """Color conversion, interpolation, palettes, and ColorMapping class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import math
7
+ from typing import Any, Callable, Iterable, Sequence
8
+
9
+ import matplotlib as mpl
10
+ import matplotlib.colors as mpl_colors
11
+ import numpy as np
12
+
13
+ # Default R4 categorical color palette (palette() in R >= 4.0)
14
+ R_PALETTE = [
15
+ "#000000", # 1: black
16
+ "#DF536B", # 2: red
17
+ "#61D04F", # 3: green3
18
+ "#2297E6", # 4: blue
19
+ "#28E2E5", # 5: cyan
20
+ "#CD0BBC", # 6: magenta
21
+ "#F5C710", # 7: yellow
22
+ "#9E9E9E", # 8: grey
23
+ ]
24
+
25
+ # R named colors that differ from or are absent in matplotlib CSS4 colors
26
+ _R_EXTRA_COLORS: dict[str, str] = {
27
+ "grey": "#BEBEBE",
28
+ "gray": "#BEBEBE",
29
+ "green": "#00FF00",
30
+ "green3": "#00CD00",
31
+ "green4": "#008B00",
32
+ "red2": "#EE0000",
33
+ "red3": "#CD0000",
34
+ "blue2": "#0000EE",
35
+ "blue3": "#0000CD",
36
+ "cyan2": "#00EEEE",
37
+ "cyan3": "#00CDCD",
38
+ "magenta2": "#EE00EE",
39
+ "magenta3": "#CD00CD",
40
+ "yellow2": "#EEEE00",
41
+ "yellow3": "#CDCD00",
42
+ "orange2": "#EE9A00",
43
+ "orange3": "#CD8500",
44
+ "purple": "#A020F0",
45
+ "brown": "#A52A2A",
46
+ "darkred": "#8B0000",
47
+ "darkblue": "#00008B",
48
+ "darkgreen": "#006400",
49
+ "darkorange": "#FF8C00",
50
+ "lightgrey": "#D3D3D3",
51
+ "lightgray": "#D3D3D3",
52
+ "darkgrey": "#A9A9A9",
53
+ "darkgray": "#A9A9A9",
54
+ "transparent": "#00000000",
55
+ }
56
+ for _k in range(101):
57
+ _hex_v = f"#{round(_k * 255 / 100):02X}" * 3
58
+ _R_EXTRA_COLORS[f"grey{_k}"] = _hex_v
59
+ _R_EXTRA_COLORS[f"gray{_k}"] = _hex_v
60
+
61
+
62
+ _COLOR_MAPPING_COUNTER = itertools.count(1)
63
+
64
+
65
+ def _is_missing_color(val: Any) -> bool:
66
+ if val is None:
67
+ return True
68
+ if isinstance(val, (float, np.floating)) and np.isnan(val):
69
+ return True
70
+ if isinstance(val, str):
71
+ s = val.strip().lower()
72
+ return s in ("", "na", "nan", "none")
73
+ return False
74
+
75
+
76
+ def to_hex_rgba(col: Any) -> str:
77
+ """Convert any R/Matplotlib/hex/RGB(A)/integer color specification to '#RRGGBBAA'."""
78
+ if _is_missing_color(col):
79
+ return "#00000000"
80
+ if isinstance(col, (int, np.integer)):
81
+ idx = int(col)
82
+ if idx <= 0:
83
+ return "#00000000"
84
+ base = R_PALETTE[(idx - 1) % len(R_PALETTE)]
85
+ return base + "FF"
86
+ if isinstance(col, str):
87
+ s = col.strip()
88
+ low = s.lower()
89
+ if low in _R_EXTRA_COLORS:
90
+ res = _R_EXTRA_COLORS[low]
91
+ return res if len(res) == 9 else res + "FF"
92
+ if low.startswith("#"):
93
+ if len(low) == 4:
94
+ r, g, b = low[1], low[2], low[3]
95
+ return f"#{r}{r}{g}{g}{b}{b}FF".upper()
96
+ if len(low) == 5:
97
+ r, g, b, a = low[1], low[2], low[3], low[4]
98
+ return f"#{r}{r}{g}{g}{b}{b}{a}{a}".upper()
99
+ if len(low) == 7:
100
+ return (low + "FF").upper()
101
+ if len(low) == 9:
102
+ return low.upper()
103
+ rgba = mpl_colors.to_rgba(s)
104
+ return _tuple_to_hex_rgba(rgba)
105
+ if isinstance(col, (tuple, list, np.ndarray)):
106
+ arr = [float(v) for v in col]
107
+ if len(arr) in (3, 4):
108
+ if any(v > 1.0 for v in arr[:3]):
109
+ arr = [v / 255.0 for v in arr]
110
+ if len(arr) == 3:
111
+ arr.append(1.0)
112
+ return _tuple_to_hex_rgba(tuple(arr))
113
+ rgba = mpl_colors.to_rgba(col)
114
+ return _tuple_to_hex_rgba(rgba)
115
+
116
+
117
+ def _tuple_to_hex_rgba(rgba: tuple[float, float, float, float]) -> str:
118
+ r, g, b, a = (max(0, min(255, int(round(v * 255)))) for v in rgba)
119
+ return f"#{r:02X}{g:02X}{b:02X}{a:02X}"
120
+
121
+
122
+ def to_rgba_tuple(col: Any) -> tuple[float, float, float, float]:
123
+ """Convert any color specification to normalized (r, g, b, a) floats in [0, 1]."""
124
+ hx = to_hex_rgba(col)
125
+ r = int(hx[1:3], 16) / 255.0
126
+ g = int(hx[3:5], 16) / 255.0
127
+ b = int(hx[5:7], 16) / 255.0
128
+ a = int(hx[7:9], 16) / 255.0
129
+ return (r, g, b, a)
130
+
131
+
132
+ def to_hex_rgba_list(cols: Any) -> list[str]:
133
+ """Normalize a single color or sequence of colors to a list of '#RRGGBBAA' strings."""
134
+ if isinstance(cols, (str, int, np.integer, float, np.floating)) or cols is None:
135
+ return [to_hex_rgba(cols)]
136
+ if isinstance(cols, tuple) and len(cols) in (3, 4) and all(isinstance(v, (int, float, np.number)) for v in cols):
137
+ return [to_hex_rgba(cols)]
138
+ return [to_hex_rgba(c) for c in cols]
139
+
140
+
141
+ def add_transparency(col: Any, transparency: Any = 0.0) -> Any:
142
+ """Apply transparency in [0, 1] (0 = opaque, 1 = transparent) to color(s)."""
143
+ is_scalar = isinstance(col, (str, int, np.integer)) or col is None
144
+ cols = to_hex_rgba_list(col)
145
+ if np.ndim(transparency) == 0:
146
+ trans = [float(transparency)] * len(cols)
147
+ else:
148
+ t_list = [float(v) for v in transparency]
149
+ if len(t_list) == 1:
150
+ trans = t_list * len(cols)
151
+ elif len(t_list) == len(cols):
152
+ trans = t_list
153
+ else:
154
+ if len(cols) == 1:
155
+ cols = cols * len(t_list)
156
+ trans = t_list
157
+ is_scalar = False
158
+ else:
159
+ raise ValueError("`transparency` length must match `col` length or be 1.")
160
+ out = []
161
+ for c, tr in zip(cols, trans):
162
+ tr = max(0.0, min(1.0, tr))
163
+ alpha_byte = int(round((1.0 - tr) * 255))
164
+ out.append(c[:7] + f"{alpha_byte:02X}")
165
+ return out[0] if is_scalar and len(out) == 1 else out
166
+
167
+
168
+ # ---- Color space conversions (sRGB <-> XYZ <-> Lab <-> HSV) ----
169
+
170
+ def _srgb_to_linear(c: np.ndarray) -> np.ndarray:
171
+ c = np.clip(c, 0.0, 1.0)
172
+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
173
+
174
+
175
+ def _linear_to_srgb(c: np.ndarray) -> np.ndarray:
176
+ c = np.clip(c, 0.0, 1.0)
177
+ return np.where(c <= 0.0031308, 12.92 * c, 1.055 * (np.maximum(c, 0.0) ** (1.0 / 2.4)) - 0.055)
178
+
179
+
180
+ # D65 reference white
181
+ _D65 = np.array([0.95047, 1.00000, 1.08883])
182
+ _M_RGB_TO_XYZ = np.array([
183
+ [0.4124564, 0.3575761, 0.1804375],
184
+ [0.2126729, 0.7151522, 0.0721750],
185
+ [0.0193339, 0.1191920, 0.9503041],
186
+ ])
187
+ _M_XYZ_TO_RGB = np.linalg.inv(_M_RGB_TO_XYZ)
188
+
189
+
190
+ def _srgb_to_lab(rgb: np.ndarray) -> np.ndarray:
191
+ lin = _srgb_to_linear(rgb)
192
+ xyz = lin @ _M_RGB_TO_XYZ.T
193
+ xyz_n = xyz / _D65
194
+ eps = 216.0 / 24389.0
195
+ kappa = 24389.0 / 27.0
196
+ f = np.where(xyz_n > eps, np.cbrt(np.maximum(xyz_n, 0.0)), (kappa * xyz_n + 16.0) / 116.0)
197
+ L = 116.0 * f[..., 1] - 16.0
198
+ a = 500.0 * (f[..., 0] - f[..., 1])
199
+ b = 200.0 * (f[..., 1] - f[..., 2])
200
+ return np.stack([L, a, b], axis=-1)
201
+
202
+
203
+ def _lab_to_srgb(lab: np.ndarray) -> np.ndarray:
204
+ L, a, b = lab[..., 0], lab[..., 1], lab[..., 2]
205
+ fy = (L + 16.0) / 116.0
206
+ fx = a / 500.0 + fy
207
+ fz = fy - b / 200.0
208
+ eps = 216.0 / 24389.0
209
+ kappa = 24389.0 / 27.0
210
+ xr = np.where(fx ** 3 > eps, fx ** 3, (116.0 * fx - 16.0) / kappa)
211
+ yr = np.where(L > kappa * eps, ((L + 16.0) / 116.0) ** 3, L / kappa)
212
+ zr = np.where(fz ** 3 > eps, fz ** 3, (116.0 * fz - 16.0) / kappa)
213
+ xyz = np.stack([xr, yr, zr], axis=-1) * _D65
214
+ lin = xyz @ _M_XYZ_TO_RGB.T
215
+ return np.clip(_linear_to_srgb(lin), 0.0, 1.0)
216
+
217
+
218
+ def _srgb_to_xyz(rgb: np.ndarray) -> np.ndarray:
219
+ return _srgb_to_linear(rgb) @ _M_RGB_TO_XYZ.T
220
+
221
+
222
+ def _xyz_to_srgb(xyz: np.ndarray) -> np.ndarray:
223
+ return np.clip(_linear_to_srgb(xyz @ _M_XYZ_TO_RGB.T), 0.0, 1.0)
224
+
225
+
226
+ def _srgb_to_polar_luv(rgb: np.ndarray) -> tuple[float, float, float]:
227
+ """Convert single sRGB (r, g, b) to polarLUV (H_deg, C, L)."""
228
+ xyz = _srgb_to_xyz(rgb)
229
+ X, Y, Z = float(xyz[0]), float(xyz[1]), float(xyz[2])
230
+ denom = X + 15.0 * Y + 3.0 * Z
231
+ u_prime = (4.0 * X / denom) if denom > 1e-12 else 0.0
232
+ v_prime = (9.0 * Y / denom) if denom > 1e-12 else 0.0
233
+ Xn, Yn, Zn = _D65
234
+ denom_n = Xn + 15.0 * Yn + 3.0 * Zn
235
+ un = 4.0 * Xn / denom_n
236
+ vn = 9.0 * Yn / denom_n
237
+ eps = 216.0 / 24389.0
238
+ kappa = 24389.0 / 27.0
239
+ yr = Y / Yn
240
+ L = 116.0 * (yr ** (1.0 / 3.0)) - 16.0 if yr > eps else kappa * yr
241
+ u = 13.0 * L * (u_prime - un)
242
+ v = 13.0 * L * (v_prime - vn)
243
+ C = math.hypot(u, v)
244
+ H = (math.degrees(math.atan2(v, u))) % 360.0
245
+ return H, C, L
246
+
247
+
248
+ def _polar_luv_to_srgb(H_deg: float, C: float, L: float) -> tuple[float, float, float]:
249
+ """Convert polarLUV (H_deg, C, L) to clipped sRGB tuple."""
250
+ if L <= 0.0:
251
+ return (0.0, 0.0, 0.0)
252
+ h_rad = math.radians(H_deg)
253
+ u = C * math.cos(h_rad)
254
+ v = C * math.sin(h_rad)
255
+ Xn, Yn, Zn = _D65
256
+ denom_n = Xn + 15.0 * Yn + 3.0 * Zn
257
+ un = 4.0 * Xn / denom_n
258
+ vn = 9.0 * Yn / denom_n
259
+ u_prime = u / (13.0 * L) + un
260
+ v_prime = v / (13.0 * L) + vn
261
+ eps = 216.0 / 24389.0
262
+ kappa = 24389.0 / 27.0
263
+ Y = Yn * (((L + 16.0) / 116.0) ** 3 if L > kappa * eps else L / kappa)
264
+ if abs(v_prime) < 1e-12:
265
+ return (0.0, 0.0, 0.0)
266
+ X = Y * (9.0 * u_prime) / (4.0 * v_prime)
267
+ Z = Y * (12.0 - 3.0 * u_prime - 20.0 * v_prime) / (4.0 * v_prime)
268
+ rgb = _xyz_to_srgb(np.array([X, Y, Z]))
269
+ return (float(rgb[0]), float(rgb[1]), float(rgb[2]))
270
+
271
+
272
+ def add_luminance(col: Any) -> list[str]:
273
+ """Generate 9-step sequential HCL palette like colorspace::sequential_hcl for 3D shading."""
274
+ r, g, b, _ = to_rgba_tuple(col)
275
+ H, C, L = _srgb_to_polar_luv(np.array([r, g, b]))
276
+ # Mimic colorspace::sequential_hcl(n = 9, h = H, c = C, l = L)
277
+ # sequential_hcl ramps luminance from L (darkest/base) up to ~95 (lightest)
278
+ # Note: R sequential_hcl(n=9, h=H, c=C, l=L) uses l=c(L, 90) or c(L, L)
279
+ # Actually in colorspace::sequential_hcl(n=9, h=H, c=C, l=L), single l uses l=c(L, 90)
280
+ l_end = max(L, 90.0)
281
+ c_end = C * 0.1
282
+ out = []
283
+ for i in range(9):
284
+ t = i / 8.0
285
+ li = L + t * (l_end - L)
286
+ ci = C + t * (c_end - C)
287
+ rgb = _polar_luv_to_srgb(H, ci, li)
288
+ out.append(_tuple_to_hex_rgba((rgb[0], rgb[1], rgb[2], 1.0)))
289
+ return out
290
+
291
+
292
+ def colorRamp2(
293
+ breaks: Sequence[float],
294
+ colors: Sequence[Any],
295
+ transparency: float = 0.0,
296
+ space: str = "LAB",
297
+ ) -> Callable[[Any], Any]:
298
+ """Create a continuous color mapping function analogous to circlize::colorRamp2."""
299
+ brk = np.asarray(breaks, dtype=float)
300
+ if brk.ndim != 1 or len(brk) < 2:
301
+ raise ValueError("`breaks` must be a 1D sequence of at least 2 numbers.")
302
+ if len(colors) != len(brk):
303
+ raise ValueError("`breaks` and `colors` must have the same length.")
304
+
305
+ rgba_list = np.array([to_rgba_tuple(c) for c in colors], dtype=float)
306
+ if transparency and transparency > 0:
307
+ rgba_list[:, 3] *= max(0.0, min(1.0, 1.0 - float(transparency)))
308
+
309
+ # Sort breaks if descending, preserving correspondence
310
+ order = np.argsort(brk)
311
+ brk_sorted = brk[order]
312
+ rgba_sorted = rgba_list[order]
313
+
314
+ sp = space.upper()
315
+ if sp in ("RGB", "SRGB"):
316
+ coords = rgba_sorted[:, :3]
317
+ back = lambda c: np.clip(c, 0.0, 1.0)
318
+ elif sp == "XYZ":
319
+ coords = _srgb_to_xyz(rgba_sorted[:, :3])
320
+ back = _xyz_to_srgb
321
+ elif sp == "HSV":
322
+ coords = mpl_colors.rgb_to_hsv(rgba_sorted[:, :3])
323
+ back = lambda c: np.clip(mpl_colors.hsv_to_rgb(np.clip(c, 0.0, 1.0)), 0.0, 1.0)
324
+ else: # "LAB"
325
+ coords = _srgb_to_lab(rgba_sorted[:, :3])
326
+ back = _lab_to_srgb
327
+
328
+ alphas = rgba_sorted[:, 3]
329
+
330
+ def col_fun(x: Any) -> Any:
331
+ is_scalar = np.ndim(x) == 0 and not isinstance(x, (list, tuple, np.ndarray))
332
+ arr = np.asarray(x, dtype=float)
333
+ orig_shape = arr.shape
334
+ flat = arr.ravel()
335
+ out = np.empty(len(flat), dtype=object)
336
+
337
+ nan_mask = np.isnan(flat)
338
+ valid_idx = np.where(~nan_mask)[0]
339
+ if len(valid_idx) > 0:
340
+ v = flat[valid_idx]
341
+ interp_coords = np.column_stack([
342
+ np.interp(v, brk_sorted, coords[:, d]) for d in range(coords.shape[1])
343
+ ])
344
+ interp_alpha = np.interp(v, brk_sorted, alphas)
345
+ rgb = back(interp_coords)
346
+ r_b = np.clip(np.round(rgb[:, 0] * 255), 0, 255).astype(int)
347
+ g_b = np.clip(np.round(rgb[:, 1] * 255), 0, 255).astype(int)
348
+ b_b = np.clip(np.round(rgb[:, 2] * 255), 0, 255).astype(int)
349
+ a_b = np.clip(np.round(interp_alpha * 255), 0, 255).astype(int)
350
+ for k, idx in enumerate(valid_idx):
351
+ out[idx] = f"#{r_b[k]:02X}{g_b[k]:02X}{b_b[k]:02X}{a_b[k]:02X}"
352
+
353
+ if np.any(nan_mask):
354
+ out[nan_mask] = "#00000000"
355
+
356
+ if is_scalar:
357
+ return out[0]
358
+ return out.reshape(orig_shape)
359
+
360
+ col_fun.breaks = brk
361
+ col_fun.colors = [to_hex_rgba(c) for c in colors]
362
+ col_fun.space = space
363
+ return col_fun
364
+
365
+
366
+ def rand_color(
367
+ n: int = 1,
368
+ hue: str | None = None,
369
+ luminosity: str = "random",
370
+ transparency: float = 0.0,
371
+ friendly: bool = False,
372
+ ) -> list[str] | str:
373
+ """Generate random visually distinct colors similar to circlize::rand_color."""
374
+ rng = np.random.default_rng()
375
+ hue_ranges = {
376
+ "red": (345, 375),
377
+ "orange": (15, 45),
378
+ "yellow": (45, 70),
379
+ "green": (80, 155),
380
+ "blue": (185, 255),
381
+ "purple": (260, 305),
382
+ "pink": (305, 345),
383
+ }
384
+ if hue is not None and hue.lower() in hue_ranges:
385
+ h0, h1 = hue_ranges[hue.lower()]
386
+ hues = rng.uniform(h0, h1, size=n) % 360.0
387
+ elif friendly:
388
+ hues = (np.arange(n) * 137.508 + rng.uniform(0, 360)) % 360.0
389
+ else:
390
+ hues = rng.uniform(0.0, 360.0, size=n)
391
+
392
+ lum = luminosity.lower()
393
+ if lum == "light":
394
+ s = rng.uniform(0.35, 0.75, size=n)
395
+ v = rng.uniform(0.80, 0.98, size=n)
396
+ elif lum == "dark":
397
+ s = rng.uniform(0.55, 0.95, size=n)
398
+ v = rng.uniform(0.30, 0.60, size=n)
399
+ elif lum == "bright":
400
+ s = rng.uniform(0.75, 1.00, size=n)
401
+ v = rng.uniform(0.75, 0.98, size=n)
402
+ elif friendly:
403
+ s = rng.uniform(0.55, 0.85, size=n)
404
+ v = rng.uniform(0.65, 0.90, size=n)
405
+ elif lum == "monochrome":
406
+ s = np.zeros(n)
407
+ v = rng.uniform(0.20, 0.85, size=n)
408
+ else:
409
+ s = rng.uniform(0.45, 0.95, size=n)
410
+ v = rng.uniform(0.55, 0.95, size=n)
411
+
412
+ hsv = np.stack([hues / 360.0, s, v], axis=-1)
413
+ rgb = mpl_colors.hsv_to_rgb(hsv)
414
+ alpha = max(0.0, min(1.0, 1.0 - float(transparency)))
415
+ res = [_tuple_to_hex_rgba((float(r), float(g), float(b), alpha)) for r, g, b in rgb]
416
+ return res
417
+
418
+
419
+ _HCL_ALIASES = {
420
+ "zissou 1": "RdYlBu_r",
421
+ "zissou1": "RdYlBu_r",
422
+ "vik": "RdBu_r",
423
+ "viridis": "viridis",
424
+ "plasma": "plasma",
425
+ "inferno": "inferno",
426
+ "magma": "magma",
427
+ "cividis": "cividis",
428
+ "blues": "Blues",
429
+ "reds": "Reds",
430
+ "greens": "Greens",
431
+ "ylorrd": "YlOrRd",
432
+ "rdylbu": "RdYlBu",
433
+ "rdbu": "RdBu",
434
+ "spectral": "Spectral",
435
+ "blue-red": "bwr",
436
+ "blue-yellow 2": "cividis",
437
+ }
438
+
439
+
440
+ def _get_cmap(name: str) -> Any:
441
+ if name in mpl.colormaps:
442
+ return mpl.colormaps[name]
443
+ alias = _HCL_ALIASES.get(name.strip().lower())
444
+ if alias and alias in mpl.colormaps:
445
+ return mpl.colormaps[alias]
446
+ for k in mpl.colormaps:
447
+ if k.lower() == name.strip().lower():
448
+ return mpl.colormaps[k]
449
+ return mpl.colormaps["YlOrRd"]
450
+
451
+
452
+ def brewer_pal(n: int, name: str) -> list[str]:
453
+ """Return n hex colors from a ColorBrewer / Matplotlib colormap."""
454
+ cmap = _get_cmap(name)
455
+ if hasattr(cmap, "colors") and len(cmap.colors) <= 20:
456
+ cols = [to_hex_rgba(c) for c in cmap.colors]
457
+ if n <= len(cols):
458
+ return cols[:n]
459
+ return [cols[i % len(cols)] for i in range(n)]
460
+ pts = np.linspace(0.0, 1.0, max(1, n))
461
+ return [to_hex_rgba(cmap(p)) for p in pts]
462
+
463
+
464
+ def hcl_colors(n: int, palette: str = "YlOrRd", rev: bool = False) -> list[str]:
465
+ """Approximate R's grDevices::hcl.colors."""
466
+ cmap = _get_cmap(palette)
467
+ pts = np.linspace(0.0, 1.0, max(1, n))
468
+ if rev:
469
+ pts = pts[::-1]
470
+ return [to_hex_rgba(cmap(p)) for p in pts]
471
+
472
+
473
+ def pretty_breaks(rng: Sequence[float], n: int = 3) -> np.ndarray:
474
+ """Compute human-friendly axis/legend break values similar to R's pretty(x, n)."""
475
+ lo, hi = float(rng[0]), float(rng[1])
476
+ if not np.isfinite(lo) or not np.isfinite(hi):
477
+ return np.array([0.0, 1.0])
478
+ if lo == hi:
479
+ return np.array([lo])
480
+ if lo > hi:
481
+ lo, hi = hi, lo
482
+ span = hi - lo
483
+ raw_step = span / max(1, n)
484
+ mag = 10.0 ** math.floor(math.log10(raw_step))
485
+ norm = raw_step / mag
486
+ for cand in (1.0, 2.0, 2.5, 5.0, 10.0):
487
+ if norm <= cand * 1.15:
488
+ step = cand * mag
489
+ break
490
+ else:
491
+ step = 10.0 * mag
492
+ start = math.floor(lo / step + 1e-9) * step
493
+ end = math.ceil(hi / step - 1e-9) * step
494
+ vals = []
495
+ cur = start
496
+ while cur <= end + 1e-9 * step:
497
+ vals.append(round(cur, 12))
498
+ cur += step
499
+ return np.asarray(vals, dtype=float)
500
+
501
+
502
+ def grid_pretty(rng: Sequence[float], n: int = 5) -> np.ndarray:
503
+ """Compute interior pretty tick locations inside [lo, hi] like grid::grid.pretty."""
504
+ lo, hi = float(min(rng)), float(max(rng))
505
+ br = pretty_breaks((lo, hi), n=n)
506
+ inside = br[(br >= lo - 1e-9 * (hi - lo)) & (br <= hi + 1e-9 * (hi - lo))]
507
+ return inside if len(inside) > 0 else br
508
+
509
+
510
+ def default_col(x: Any, main_matrix: bool = False) -> Any:
511
+ """Infer default color mapping (discrete dict or continuous colorRamp2) for matrix or vector."""
512
+ from ._options import ht_opt
513
+
514
+ arr = np.asarray(x)
515
+ # Check numeric vs categorical
516
+ is_num = np.issubdtype(arr.dtype, np.number) and not np.issubdtype(arr.dtype, np.bool_)
517
+ if not is_num:
518
+ # Check if object array containing only numbers + nan
519
+ flat = arr.ravel()
520
+ non_na = [v for v in flat if not _is_missing_color(v)]
521
+ if len(non_na) > 0 and all(isinstance(v, (int, float, np.number)) and not isinstance(v, (bool, np.bool_)) for v in non_na):
522
+ is_num = True
523
+ arr = np.array([np.nan if _is_missing_color(v) else float(v) for v in flat], dtype=float)
524
+
525
+ if is_num:
526
+ vals = arr.astype(float).ravel()
527
+ vals = vals[~np.isnan(vals)]
528
+ if len(vals) == 0:
529
+ return {"NA": "#CCCCCCFF"}
530
+ uniq = np.unique(vals)
531
+ if len(uniq) == 1:
532
+ return {str(uniq[0]): to_hex_rgba(rand_color(1)[0])}
533
+ colors = list(ht_opt.COLOR)
534
+ if main_matrix:
535
+ nz = vals[vals != 0]
536
+ p = float(np.sum(vals > 0)) / len(nz) if len(nz) > 0 else 0.0
537
+ if 0.25 < p < 0.75:
538
+ q1 = float(np.quantile(np.abs(vals), 0.99)) if len(uniq) >= 100 else float(np.max(np.abs(vals)))
539
+ if q1 == 0:
540
+ q1 = float(np.max(np.abs(vals)))
541
+ brks = np.linspace(-q1, q1, len(colors))
542
+ else:
543
+ if len(uniq) >= 100:
544
+ q1 = float(np.quantile(vals, 0.01))
545
+ q2 = float(np.quantile(vals, 0.99))
546
+ if q1 == q2 or len(np.unique(vals[(vals >= q1) & (vals <= q2)])) <= 1:
547
+ q1, q2 = float(np.min(vals)), float(np.max(vals))
548
+ else:
549
+ q1, q2 = float(np.min(vals)), float(np.max(vals))
550
+ brks = np.linspace(q1, q2, len(colors))
551
+ else:
552
+ q1, q2 = float(np.min(vals)), float(np.max(vals))
553
+ brks = np.linspace(q1, q2, len(colors))
554
+ return colorRamp2(brks, colors)
555
+ else:
556
+ flat = arr.ravel()
557
+ levels = []
558
+ seen = set()
559
+ for v in flat:
560
+ if _is_missing_color(v):
561
+ continue
562
+ sv = str(v)
563
+ if sv not in seen:
564
+ seen.add(sv)
565
+ levels.append(sv)
566
+ if len(levels) == 0:
567
+ return {"NA": "#CCCCCCFF"}
568
+ cols = rand_color(len(levels))
569
+ return dict(zip(levels, cols))
570
+
571
+
572
+ class ColorMapping:
573
+ """Mapping between discrete or continuous data values and RGBA hex colors."""
574
+
575
+ def __init__(
576
+ self,
577
+ name: str | None = None,
578
+ colors: dict[Any, Any] | Sequence[Any] | None = None,
579
+ levels: Sequence[Any] | None = None,
580
+ col_fun: Callable[[Any], Any] | None = None,
581
+ breaks: Sequence[float] | None = None,
582
+ na_col: Any = "#FFFFFF",
583
+ full_col: dict[Any, Any] | None = None,
584
+ ) -> None:
585
+ if name is None:
586
+ name = f"color_mapping_{next(_COLOR_MAPPING_COUNTER)}"
587
+ self.name = str(name)
588
+ self.na_col = to_hex_rgba(na_col)
589
+ self.full_col: dict[str, str] = {}
590
+ self.colors: dict[str, str] | list[str]
591
+ self.levels: list[str] | np.ndarray
592
+ self.col_fun: Callable[[Any], Any] | None = None
593
+
594
+ if colors is not None:
595
+ if isinstance(colors, dict):
596
+ levs = list(colors.keys()) if levels is None else list(levels)
597
+ col_vals = list(colors.values())
598
+ else:
599
+ col_vals = list(colors)
600
+ if levels is None:
601
+ raise ValueError("Either provide `levels` or pass `colors` as a dict.")
602
+ levs = list(levels)
603
+ if len(col_vals) != len(levs):
604
+ raise ValueError("Length of `colors` and `levels` must be the same.")
605
+ norm_cols = [to_hex_rgba(c) for c in col_vals]
606
+ str_levs = [str(lv) for lv in levs]
607
+ self.levels = str_levs
608
+ self.colors = dict(zip(str_levs, norm_cols))
609
+ if full_col is not None:
610
+ self.full_col = {str(k): to_hex_rgba(v) for k, v in full_col.items()}
611
+ self.type = "discrete"
612
+ elif col_fun is not None:
613
+ if breaks is None:
614
+ brk = getattr(col_fun, "breaks", None)
615
+ if brk is None:
616
+ raise ValueError("You should provide `breaks` when `col_fun` has no `breaks` attribute.")
617
+ rg = [float(np.min(brk)), float(np.max(brk))]
618
+ diff = rg[1] - rg[0]
619
+ rg[0] += diff * 0.05
620
+ rg[1] -= diff * 0.05
621
+ le = pretty_breaks(rg, n=3)
622
+ else:
623
+ le = np.asarray(breaks, dtype=float)
624
+ self.levels = le
625
+ mapped = col_fun(le)
626
+ self.colors = [to_hex_rgba(c) for c in mapped]
627
+ self.col_fun = col_fun
628
+ self.type = "continuous"
629
+ else:
630
+ raise ValueError("Initialization failed: specify `colors` (+ `levels`) or `col_fun`.")
631
+
632
+ def map_to_colors(self, x: Any) -> Any:
633
+ """Map scalar, 1D vector, or 2D array of values to hex RGBA colors."""
634
+ is_scalar = np.ndim(x) == 0 and not isinstance(x, (list, tuple, np.ndarray))
635
+ arr = np.asarray(x, dtype=object)
636
+ orig_shape = arr.shape
637
+ flat = arr.ravel()
638
+ out = np.empty(len(flat), dtype=object)
639
+
640
+ if self.type == "discrete":
641
+ lookup = self.full_col if self.full_col else self.colors
642
+ assert isinstance(lookup, dict)
643
+ unmapped = []
644
+ for idx, val in enumerate(flat):
645
+ if _is_missing_color(val) or (isinstance(val, str) and val.strip() == ""):
646
+ out[idx] = self.na_col
647
+ else:
648
+ sv = str(val)
649
+ # Handle float like 1.0 vs "1" if integer key was provided
650
+ if sv not in lookup and isinstance(val, (float, np.floating)) and float(val).is_integer():
651
+ sv_int = str(int(val))
652
+ if sv_int in lookup:
653
+ sv = sv_int
654
+ if sv not in lookup:
655
+ unmapped.append(sv)
656
+ else:
657
+ out[idx] = lookup[sv]
658
+ if unmapped:
659
+ uniq_bad = list(dict.fromkeys(unmapped))
660
+ raise ValueError(f"{self.name}: cannot map colors to some levels: {', '.join(uniq_bad)}")
661
+ else:
662
+ assert self.col_fun is not None
663
+ num_arr = np.empty(len(flat), dtype=float)
664
+ for idx, val in enumerate(flat):
665
+ if _is_missing_color(val):
666
+ num_arr[idx] = np.nan
667
+ else:
668
+ num_arr[idx] = float(val)
669
+ lna = np.isnan(num_arr)
670
+ if np.any(lna):
671
+ out[lna] = self.na_col
672
+ if np.any(~lna):
673
+ mapped = self.col_fun(num_arr[~lna])
674
+ out[~lna] = [to_hex_rgba(c) for c in np.atleast_1d(mapped)]
675
+
676
+ if is_scalar:
677
+ return out[0]
678
+ return out.reshape(orig_shape)
679
+
680
+ def color_mapping_legend(
681
+ self,
682
+ plot: bool = True,
683
+ color_bar: str | None = None,
684
+ title: str | None = None,
685
+ title_gp: Any = None,
686
+ title_position: str = "topleft",
687
+ grid_height: Any = None,
688
+ grid_width: Any = None,
689
+ tick_length: Any = None,
690
+ border: Any = None,
691
+ at: Sequence[Any] | None = None,
692
+ labels: Sequence[Any] | None = None,
693
+ labels_gp: Any = None,
694
+ labels_rot: float = 0.0,
695
+ nrow: int | None = None,
696
+ ncol: int = 1,
697
+ by_row: bool = False,
698
+ legend_gp: Any = None,
699
+ legend_height: Any = None,
700
+ legend_width: Any = None,
701
+ legend_direction: str = "vertical",
702
+ break_dist: Sequence[float] | None = None,
703
+ graphics: Any = None,
704
+ param: dict[str, Any] | None = None,
705
+ **draw_kwargs: Any,
706
+ ) -> Any:
707
+ from .legend import Legend
708
+ from .units import gpar, unit
709
+
710
+ local_params: dict[str, Any] = {
711
+ "color_bar": self.type if color_bar is None else color_bar,
712
+ "title": self.name if title is None else title,
713
+ "title_gp": gpar(fontsize=10, fontface="bold") if title_gp is None else title_gp,
714
+ "title_position": title_position,
715
+ "grid_height": unit(4, "mm") if grid_height is None else grid_height,
716
+ "grid_width": unit(4, "mm") if grid_width is None else grid_width,
717
+ "tick_length": unit(0.8, "mm") if tick_length is None else tick_length,
718
+ "border": border,
719
+ "at": list(self.levels) if at is None else list(at),
720
+ "labels": None if labels is None else list(labels),
721
+ "labels_gp": gpar(fontsize=10) if labels_gp is None else labels_gp,
722
+ "labels_rot": labels_rot,
723
+ "nrow": nrow,
724
+ "ncol": ncol,
725
+ "by_row": by_row,
726
+ "legend_gp": gpar() if legend_gp is None else gpar(**legend_gp),
727
+ "legend_height": legend_height,
728
+ "legend_width": legend_width,
729
+ "legend_direction": legend_direction,
730
+ "break_dist": break_dist,
731
+ "graphics": graphics,
732
+ }
733
+ if param:
734
+ for k, v in param.items():
735
+ if k == "direction":
736
+ local_params["legend_direction"] = v
737
+ else:
738
+ local_params[k] = v
739
+
740
+ if local_params["labels"] is None:
741
+ local_params["labels"] = list(local_params["at"])
742
+
743
+ cb = local_params["color_bar"]
744
+ if self.type == "discrete" and cb == "continuous":
745
+ raise ValueError("`color_bar` cannot be 'continuous' when ColorMapping is discrete.")
746
+
747
+ at_vals = list(local_params["at"])
748
+ lbl_vals = list(local_params["labels"])
749
+ if len(at_vals) != len(lbl_vals):
750
+ raise ValueError("Length of `at` must equal length of `labels`.")
751
+
752
+ if cb == "discrete" and self.type == "discrete":
753
+ valid = set(self.full_col.keys()) if self.full_col else set(self.levels)
754
+ keep = [i for i, v in enumerate(at_vals) if str(v) in valid]
755
+ at_vals = [at_vals[i] for i in keep]
756
+ lbl_vals = [lbl_vals[i] for i in keep]
757
+
758
+ if cb == "discrete":
759
+ if self.type == "continuous":
760
+ at_vals = list(reversed(at_vals))
761
+ lbl_vals = list(reversed(lbl_vals))
762
+ lgp = gpar(**local_params["legend_gp"])
763
+ if len(at_vals) == 0:
764
+ lgp["fill"] = self.na_col
765
+ at_vals = ["NA"]
766
+ lbl_vals = ["NA"]
767
+ else:
768
+ lgp["fill"] = list(self.map_to_colors(at_vals))
769
+ lgd = Legend(
770
+ at=at_vals,
771
+ labels=lbl_vals,
772
+ name=self.name,
773
+ title=local_params["title"],
774
+ title_gp=local_params["title_gp"],
775
+ grid_height=local_params["grid_height"],
776
+ grid_width=local_params["grid_width"],
777
+ tick_length=local_params["tick_length"],
778
+ border=local_params["border"],
779
+ labels_gp=local_params["labels_gp"],
780
+ direction=local_params["legend_direction"],
781
+ nrow=local_params["nrow"],
782
+ ncol=local_params["ncol"],
783
+ legend_gp=lgp,
784
+ title_position=local_params["title_position"],
785
+ by_row=local_params["by_row"],
786
+ graphics=local_params["graphics"],
787
+ break_dist=local_params["break_dist"],
788
+ )
789
+ else:
790
+ lgd = Legend(
791
+ at=at_vals,
792
+ labels=lbl_vals,
793
+ name=self.name,
794
+ col_fun=self.col_fun,
795
+ title=local_params["title"],
796
+ title_gp=local_params["title_gp"],
797
+ grid_height=local_params["grid_height"],
798
+ grid_width=local_params["grid_width"],
799
+ tick_length=local_params["tick_length"],
800
+ border=local_params["border"],
801
+ labels_gp=local_params["labels_gp"],
802
+ labels_rot=local_params["labels_rot"],
803
+ direction=local_params["legend_direction"],
804
+ legend_gp=local_params["legend_gp"],
805
+ legend_width=local_params["legend_width"],
806
+ legend_height=local_params["legend_height"],
807
+ title_position=local_params["title_position"],
808
+ by_row=local_params["by_row"],
809
+ break_dist=local_params["break_dist"],
810
+ )
811
+
812
+ if plot:
813
+ lgd.draw(**draw_kwargs)
814
+ return lgd
815
+
816
+ def __repr__(self) -> str:
817
+ if self.type == "discrete":
818
+ return (
819
+ f"Discrete color mapping:\nname: {self.name}\n"
820
+ f"levels: {self.levels}\ncolors: {list(self.colors.values())}"
821
+ )
822
+ return (
823
+ f"Continuous color mapping:\nname: {self.name}\n"
824
+ f"default breaks: {list(self.levels)}\ncolors: {self.colors}"
825
+ )
826
+
827
+
828
+ def map_to_colors(cm: ColorMapping, x: Any) -> Any:
829
+ return cm.map_to_colors(x)
830
+
831
+
832
+ def color_mapping_legend(cm: ColorMapping, plot: bool = True, **kwargs: Any) -> Any:
833
+ return cm.color_mapping_legend(plot=plot, **kwargs)
834
+
835
+
836
+ def c_ColorMapping(*cms: ColorMapping, name: str | None = None) -> ColorMapping:
837
+ """Concatenate discrete ColorMapping objects, preserving first occurrence of duplicates."""
838
+ if not cms:
839
+ raise ValueError("At least one ColorMapping is required.")
840
+ if not all(cm.type == "discrete" for cm in cms):
841
+ raise ValueError("Only discrete color mappings can be concatenated.")
842
+ merged: dict[str, str] = {}
843
+ for cm in cms:
844
+ assert isinstance(cm.colors, dict)
845
+ for k, v in cm.colors.items():
846
+ if k not in merged:
847
+ merged[k] = v
848
+ return ColorMapping(name=name, colors=merged, na_col=cms[0].na_col)