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,2244 @@
1
+ """Single Heatmap class, clustering/splitting engine, 9x9 layout, and component drawing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import inspect
7
+ import math
8
+ from typing import Any, Callable, Sequence
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ from ._base import AdditiveUnit
14
+ from ._options import _ENV, ht_opt
15
+ from .annotations import AnnotationFunction, HeatmapAnnotation, SingleAnnotation, anno_text
16
+ from .colors import ColorMapping, default_col, to_hex_rgba, to_rgba_tuple
17
+ from .dendrogram import (
18
+ Dendrogram,
19
+ Hclust,
20
+ adjust_dend_by_x,
21
+ as_dendrogram,
22
+ cut_dendrogram,
23
+ dend_heights,
24
+ dist as calc_dist,
25
+ dist2,
26
+ grid_dendrogram,
27
+ hclust,
28
+ merge_dendrogram,
29
+ nobs,
30
+ order_dendrogram,
31
+ reorder_dendrogram,
32
+ )
33
+ from .grid import (
34
+ Viewport,
35
+ grid_raster,
36
+ grid_rect,
37
+ grid_segments,
38
+ grid_text,
39
+ max_text_height,
40
+ max_text_width,
41
+ popViewport,
42
+ pushViewport,
43
+ textGrob,
44
+ )
45
+ from .legend import Legends
46
+ from .text import GridText
47
+ from .units import (
48
+ Unit,
49
+ as_unit,
50
+ check_gp,
51
+ convertHeight,
52
+ convertWidth,
53
+ gpar,
54
+ is_abs_unit,
55
+ subset_gp,
56
+ unit,
57
+ unit_c,
58
+ unit_sum,
59
+ )
60
+
61
+
62
+ HEATMAP_LAYOUT_COLUMN_COMPONENTS = (
63
+ "column_title_top",
64
+ "column_dend_top",
65
+ "column_names_top",
66
+ "column_anno_top",
67
+ "heatmap_body",
68
+ "column_anno_bottom",
69
+ "column_names_bottom",
70
+ "column_dend_bottom",
71
+ "column_title_bottom",
72
+ )
73
+
74
+ HEATMAP_LAYOUT_ROW_COMPONENTS = (
75
+ "row_title_left",
76
+ "row_dend_left",
77
+ "row_names_left",
78
+ "row_anno_left",
79
+ "heatmap_body",
80
+ "row_anno_right",
81
+ "row_names_right",
82
+ "row_dend_right",
83
+ "row_title_right",
84
+ )
85
+
86
+
87
+ def _heatmap_layout_index(nm: str) -> tuple[int, int]:
88
+ if nm in HEATMAP_LAYOUT_COLUMN_COMPONENTS and nm != "heatmap_body":
89
+ return (HEATMAP_LAYOUT_COLUMN_COMPONENTS.index(nm), HEATMAP_LAYOUT_ROW_COMPONENTS.index("heatmap_body"))
90
+ if nm in HEATMAP_LAYOUT_ROW_COMPONENTS and nm != "heatmap_body":
91
+ return (HEATMAP_LAYOUT_COLUMN_COMPONENTS.index("heatmap_body"), HEATMAP_LAYOUT_ROW_COMPONENTS.index(nm))
92
+ if nm == "heatmap_body":
93
+ return (HEATMAP_LAYOUT_COLUMN_COMPONENTS.index("heatmap_body"), HEATMAP_LAYOUT_ROW_COMPONENTS.index("heatmap_body"))
94
+ raise ValueError(f"Unknown heatmap layout component: {nm!r}")
95
+
96
+
97
+ def _is_na(v: Any) -> bool:
98
+ if v is None:
99
+ return True
100
+ if isinstance(v, (float, np.floating)) and math.isnan(float(v)):
101
+ return True
102
+ try:
103
+ res = pd.isna(v)
104
+ if isinstance(res, (bool, np.bool_)):
105
+ return bool(res)
106
+ except Exception:
107
+ pass
108
+ return False
109
+
110
+
111
+ def _is_empty_title(title: Any) -> bool:
112
+ if title is None or isinstance(title, (list, tuple)) and len(title) == 0:
113
+ return True
114
+ if isinstance(title, np.ndarray) and title.size == 0:
115
+ return True
116
+ if isinstance(title, str) and title == "":
117
+ return True
118
+ if isinstance(title, float) and math.isnan(title):
119
+ return True
120
+ return False
121
+
122
+
123
+ def _normalize_title_list(title: Any) -> list[Any]:
124
+ if _is_empty_title(title):
125
+ return []
126
+ if isinstance(title, GridText):
127
+ return [title]
128
+ if isinstance(title, (str, bytes)):
129
+ s = title.decode() if isinstance(title, bytes) else title
130
+ return [] if s == "" else [s]
131
+ if isinstance(title, (list, tuple, pd.Series, pd.Index, np.ndarray)):
132
+ out = []
133
+ for x in title:
134
+ if not _is_empty_title(x):
135
+ out.append(x)
136
+ return out
137
+ return [str(title)]
138
+
139
+
140
+ def _normalize_side(val: Any, valid: tuple[str, ...], arg_name: str) -> str:
141
+ if isinstance(val, (list, tuple)):
142
+ val = val[0]
143
+ s = str(val).lower()
144
+ if s not in valid:
145
+ raise ValueError(f"`{arg_name}` must be one of {valid}, got {val!r}.")
146
+ return s
147
+
148
+
149
+ def _get_text_just(rot: float, side: str) -> Any:
150
+ rot = float(rot) % 360
151
+ if side == "left":
152
+ if rot == 0:
153
+ return "right"
154
+ if rot == 90:
155
+ return "center"
156
+ if rot == 270:
157
+ return "center"
158
+ return "right"
159
+ if side == "right":
160
+ if rot == 0:
161
+ return "left"
162
+ if rot == 90:
163
+ return "center"
164
+ if rot == 270:
165
+ return "center"
166
+ return "left"
167
+ if side == "top":
168
+ if rot == 0:
169
+ return "center"
170
+ if rot == 90:
171
+ return "left"
172
+ if rot == 270:
173
+ return "right"
174
+ return "center"
175
+ # bottom
176
+ if rot == 0:
177
+ return "center"
178
+ if rot == 90:
179
+ return "right"
180
+ if rot == 270:
181
+ return "left"
182
+ return "center"
183
+
184
+
185
+ def _dimname_just_and_loc(side: str, rot: float, centered: bool) -> tuple[Any, Unit]:
186
+ rot_m = float(rot) % 360
187
+ if side == "left":
188
+ if centered:
189
+ return "center", unit(0.5, "npc")
190
+ if rot_m == 90:
191
+ return "bottom", unit(1.0, "npc")
192
+ if rot_m == 270:
193
+ return "top", unit(1.0, "npc")
194
+ return "right", unit(1.0, "npc")
195
+ if side == "right":
196
+ if centered:
197
+ return "center", unit(0.5, "npc")
198
+ if rot_m == 90:
199
+ return "top", unit(0.0, "npc")
200
+ if rot_m == 270:
201
+ return "bottom", unit(0.0, "npc")
202
+ return "left", unit(0.0, "npc")
203
+ if side == "top":
204
+ if centered:
205
+ return "center", unit(0.5, "npc")
206
+ if rot_m == 0:
207
+ return "bottom", unit(0.0, "npc")
208
+ if rot_m == 90:
209
+ return "left", unit(0.0, "npc")
210
+ if rot_m == 270:
211
+ return "right", unit(0.0, "npc")
212
+ return "left", unit(0.0, "npc")
213
+ # bottom
214
+ if centered:
215
+ return "center", unit(0.5, "npc")
216
+ if rot_m == 0:
217
+ return "top", unit(1.0, "npc")
218
+ if rot_m == 90:
219
+ return "right", unit(1.0, "npc")
220
+ if rot_m == 270:
221
+ return "left", unit(1.0, "npc")
222
+ return "right", unit(1.0, "npc")
223
+
224
+
225
+ def _title_padding_unit(gp: dict[str, Any]) -> Unit:
226
+ tp = ht_opt.TITLE_PADDING
227
+ if tp is not None:
228
+ return as_unit(tp, "mm")
229
+ fs = float(gp.get("fontsize", 13.2))
230
+ # 5.5pt + approximate descender height (~0.25em)
231
+ pad0_pt = 5.5 + 0.25 * fs
232
+ return unit([pad0_pt * 25.4 / 72.0, 0.0], "mm")
233
+
234
+
235
+ def _parse_matrix(matrix: Any, name: str | None) -> tuple[np.ndarray, bool, list[str] | None, list[str] | None, list[str] | None]:
236
+ """Normalize input into a 2D numpy array + numeric flag + rownames + colnames + factor levels."""
237
+ rn: list[str] | None = None
238
+ cn: list[str] | None = None
239
+ fa_levels: list[str] | None = None
240
+
241
+ if isinstance(matrix, pd.DataFrame):
242
+ rn = [str(x) for x in matrix.index]
243
+ cn = [str(x) for x in matrix.columns]
244
+ all_num = all(pd.api.types.is_numeric_dtype(dt) and not pd.api.types.is_bool_dtype(dt) for dt in matrix.dtypes)
245
+ if all_num:
246
+ arr = matrix.to_numpy(dtype=float, copy=True)
247
+ is_num = True
248
+ else:
249
+ arr = matrix.to_numpy(dtype=object, copy=True)
250
+ is_num = False
251
+ return arr, is_num, rn, cn, fa_levels
252
+
253
+ if isinstance(matrix, pd.Series):
254
+ if isinstance(matrix.dtype, pd.CategoricalDtype):
255
+ fa_levels = [str(c) for c in matrix.cat.categories]
256
+ rn = [str(x) for x in matrix.index]
257
+ col_nm = str(matrix.name) if matrix.name is not None else (name or "V1")
258
+ cn = [col_nm]
259
+ if pd.api.types.is_numeric_dtype(matrix.dtype) and not pd.api.types.is_bool_dtype(matrix.dtype):
260
+ arr = matrix.to_numpy(dtype=float, copy=True).reshape(-1, 1)
261
+ is_num = True
262
+ else:
263
+ arr = matrix.to_numpy(dtype=object, copy=True).reshape(-1, 1)
264
+ is_num = False
265
+ return arr, is_num, rn, cn, fa_levels
266
+
267
+ if isinstance(matrix, pd.Categorical):
268
+ fa_levels = [str(c) for c in matrix.categories]
269
+ arr = np.asarray(matrix, dtype=object).reshape(-1, 1)
270
+ cn = [name] if name else None
271
+ return arr, False, None, cn, fa_levels
272
+
273
+ arr_raw = np.asarray(matrix)
274
+ if arr_raw.ndim == 0:
275
+ arr_raw = arr_raw.reshape(1, 1)
276
+ elif arr_raw.ndim == 1:
277
+ arr_raw = arr_raw.reshape(-1, 1)
278
+ if name is not None:
279
+ cn = [name]
280
+ elif arr_raw.ndim != 2:
281
+ raise ValueError(f"`matrix` must be 1D or 2D, got shape {arr_raw.shape}.")
282
+
283
+ # Distinguish numeric vs bool/str/object
284
+ if np.issubdtype(arr_raw.dtype, np.bool_):
285
+ arr = np.where(arr_raw, "TRUE", "FALSE").astype(object)
286
+ is_num = False
287
+ elif np.issubdtype(arr_raw.dtype, np.number):
288
+ arr = arr_raw.astype(float, copy=True)
289
+ is_num = True
290
+ else:
291
+ # Try checking if object array is purely numeric or None/nan
292
+ flat = arr_raw.ravel()
293
+ non_na = [x for x in flat if not _is_na(x)]
294
+ if non_na and all(isinstance(x, (int, float, np.integer, np.floating)) and not isinstance(x, (bool, np.bool_)) for x in non_na):
295
+ arr = np.empty(arr_raw.shape, dtype=float)
296
+ for idx, v in np.ndenumerate(arr_raw):
297
+ arr[idx] = np.nan if _is_na(v) else float(v)
298
+ is_num = True
299
+ elif not non_na:
300
+ # Empty / all NA numeric matrix by default unless object
301
+ arr = np.full(arr_raw.shape, np.nan, dtype=float)
302
+ is_num = True
303
+ else:
304
+ arr = arr_raw.astype(object, copy=True)
305
+ is_num = False
306
+
307
+ return arr, is_num, rn, cn, fa_levels
308
+
309
+
310
+ def _format_labels_input(labels: Any, mat_names: list[str] | None, expected_len: int, arg_name: str) -> Any:
311
+ if labels is None:
312
+ return None if mat_names is None else list(mat_names)
313
+ if isinstance(labels, GridText):
314
+ if len(labels) != expected_len:
315
+ raise ValueError(f"Length of `{arg_name}` ({len(labels)}) must equal {expected_len}.")
316
+ return labels
317
+ if isinstance(labels, (list, tuple, pd.Index, pd.Series, np.ndarray)):
318
+ out = [str(x) for x in labels]
319
+ if len(out) == 0:
320
+ return None
321
+ if len(out) != expected_len:
322
+ raise ValueError(f"Length of `{arg_name}` ({len(out)}) must equal {expected_len}.")
323
+ return out
324
+ return [str(labels)]
325
+
326
+
327
+ def _normalize_split_df(split: Any, n: int, arg_name: str) -> tuple[pd.DataFrame, list[str], list[list[Any]]]:
328
+ """Normalize `split` into a DataFrame of ordered categorical columns, slice labels, and ordered index groups."""
329
+ if isinstance(split, pd.DataFrame):
330
+ df = split.copy()
331
+ elif isinstance(split, (list, tuple)) and len(split) > 0 and isinstance(split[0], (list, tuple, pd.Series, pd.Categorical, np.ndarray)):
332
+ df = pd.DataFrame({f"s{i}": list(col) for i, col in enumerate(split)})
333
+ else:
334
+ if isinstance(split, pd.Categorical):
335
+ df = pd.DataFrame({"s0": pd.Series(split)})
336
+ else:
337
+ df = pd.DataFrame({"s0": pd.Series(list(split) if not isinstance(split, np.ndarray) else split.tolist())})
338
+
339
+ if len(df) != n:
340
+ raise ValueError(f"Length of `{arg_name}` ({len(df)}) must match dimension size ({n}).")
341
+
342
+ # Convert each column to ordered Categorical mirroring R factor rules
343
+ for col in df.columns:
344
+ s = df[col]
345
+ if isinstance(s.dtype, pd.CategoricalDtype):
346
+ present = set(s.dropna().unique())
347
+ cats = [c for c in s.cat.categories if c in present]
348
+ df[col] = pd.Categorical(s, categories=cats, ordered=True)
349
+ elif pd.api.types.is_numeric_dtype(s.dtype) and not pd.api.types.is_bool_dtype(s.dtype):
350
+ uniq_sorted = sorted(s.dropna().unique().tolist())
351
+ cats = [str(u) for u in uniq_sorted]
352
+ df[col] = pd.Categorical([str(v) if not _is_na(v) else np.nan for v in s], categories=cats, ordered=True)
353
+ else:
354
+ vals = [str(v) if not _is_na(v) else np.nan for v in s]
355
+ uniq_sorted = sorted({v for v in vals if not _is_na(v)})
356
+ df[col] = pd.Categorical(vals, categories=uniq_sorted, ordered=True)
357
+
358
+ # Lexicographical sort by categorical codes (matching R `do.call("order", split)`)
359
+ codes_cols = [df[c].cat.codes.to_numpy() for c in df.columns]
360
+ row_keys = list(zip(*codes_cols))
361
+ sorted_row_pos = sorted(range(n), key=lambda i: row_keys[i])
362
+
363
+ # Build combined slice label per row
364
+ str_mat = np.column_stack([[str(v) for v in df[c]] for c in df.columns])
365
+ comb_names = [",".join(str_mat[i, :]) for i in range(n)]
366
+
367
+ seen: dict[str, list[int]] = {}
368
+ ordered_levels: list[str] = []
369
+ for pos in sorted_row_pos:
370
+ lbl = comb_names[pos]
371
+ if lbl not in seen:
372
+ seen[lbl] = []
373
+ ordered_levels.append(lbl)
374
+ seen[lbl].append(pos)
375
+
376
+ groups = [seen[lbl] for lbl in ordered_levels]
377
+ return df, ordered_levels, groups
378
+
379
+
380
+ def _compute_distance(submat: np.ndarray, distance: Any) -> Any:
381
+ """Compute DistMatrix on rows of `submat`."""
382
+ if isinstance(distance, str):
383
+ return calc_dist(submat, method=distance)
384
+ if callable(distance):
385
+ sig = inspect.signature(distance)
386
+ params = [p for p in sig.parameters.values() if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
387
+ if len(params) == 1:
388
+ return distance(submat)
389
+ return dist2(submat, distance)
390
+ raise TypeError(f"Unsupported clustering distance specification: {distance!r}")
391
+
392
+
393
+ def _cluster_submatrix(submat: np.ndarray, cluster: Any, distance: Any, method: str) -> Hclust | Dendrogram:
394
+ """Run hierarchical clustering or user-provided clustering function on rows of `submat`."""
395
+ if callable(cluster):
396
+ res = cluster(submat)
397
+ if isinstance(res, (Hclust, Dendrogram)):
398
+ return res
399
+ # Allow scipy linkage ndarray directly
400
+ if isinstance(res, np.ndarray) and res.ndim == 2 and res.shape[1] == 4:
401
+ return Hclust(res, method=method)
402
+ raise TypeError("Custom clustering function must return an Hclust, Dendrogram, or linkage matrix.")
403
+ d = _compute_distance(submat, distance)
404
+ return hclust(d, method=method)
405
+
406
+
407
+ def _kmeans_single(mat: np.ndarray, k: int, rng: np.random.Generator, max_iter: int = 50) -> tuple[np.ndarray, float]:
408
+ """Deterministic/seeded k-means++ with Lloyd updates handling NaNs via column-mean imputation."""
409
+ x = np.asarray(mat, dtype=float)
410
+ n, p = x.shape
411
+ if k >= n:
412
+ return np.arange(n, dtype=int), 0.0
413
+ # Impute any NaN with column mean (or 0 if all NaN)
414
+ if np.any(np.isnan(x)):
415
+ x = x.copy()
416
+ col_means = np.nanmean(x, axis=0)
417
+ col_means = np.where(np.isnan(col_means), 0.0, col_means)
418
+ r_na, c_na = np.where(np.isnan(x))
419
+ x[r_na, c_na] = col_means[c_na]
420
+
421
+ # k-means++ initialization
422
+ centers = np.empty((k, p), dtype=float)
423
+ idx0 = int(rng.integers(0, n))
424
+ centers[0] = x[idx0]
425
+ sq_dists = np.sum((x - centers[0]) ** 2, axis=1)
426
+ for c in range(1, k):
427
+ tot = float(np.sum(sq_dists))
428
+ if tot <= 0:
429
+ rem = [i for i in range(n) if i not in set(range(c))]
430
+ centers[c] = x[rem[0] if rem else 0]
431
+ else:
432
+ probs = sq_dists / tot
433
+ idx = int(rng.choice(n, p=probs))
434
+ centers[c] = x[idx]
435
+ d_new = np.sum((x - centers[c]) ** 2, axis=1)
436
+ sq_dists = np.minimum(sq_dists, d_new)
437
+
438
+ labels = np.zeros(n, dtype=int)
439
+ for _ in range(max_iter):
440
+ # Assign to nearest centroid
441
+ dmat = np.sum((x[:, None, :] - centers[None, :, :]) ** 2, axis=2)
442
+ new_labels = np.argmin(dmat, axis=1)
443
+ if np.array_equal(new_labels, labels):
444
+ # Re-verify at least once cleanly
445
+ labels = new_labels
446
+ break
447
+ labels = new_labels
448
+ for c in range(k):
449
+ mask = labels == c
450
+ if np.any(mask):
451
+ centers[c] = np.mean(x[mask], axis=0)
452
+ else:
453
+ # Re-seed empty cluster to farthest point
454
+ far = int(np.argmax(np.min(dmat, axis=1)))
455
+ centers[c] = x[far]
456
+
457
+ inertia = 0.0
458
+ for c in range(k):
459
+ mask = labels == c
460
+ if np.any(mask):
461
+ inertia += float(np.sum((x[mask] - centers[c]) ** 2))
462
+ return labels, inertia
463
+
464
+
465
+ def _consensus_kmeans(mat: np.ndarray, centers: int, km_repeats: int = 1) -> np.ndarray:
466
+ """K-means clustering with optional multi-run consensus partitioning."""
467
+ n = mat.shape[0]
468
+ if centers >= n:
469
+ return np.arange(n, dtype=int)
470
+
471
+ seed = ht_opt.kmeans_seed if hasattr(ht_opt, "kmeans_seed") and ht_opt.kmeans_seed is not None else None
472
+ rng = np.random.default_rng(seed)
473
+
474
+ if km_repeats <= 1:
475
+ best_lbl = None
476
+ best_iner = np.inf
477
+ # Multiple random starts even for single consensus run (like nstart)
478
+ for _ in range(5):
479
+ lbl, iner = _kmeans_single(mat, centers, rng)
480
+ if iner < best_iner:
481
+ best_iner = iner
482
+ best_lbl = lbl
483
+ return best_lbl if best_lbl is not None else np.zeros(n, dtype=int)
484
+
485
+ # Co-association matrix consensus across km_repeats runs
486
+ coassoc = np.zeros((n, n), dtype=float)
487
+ runs: list[np.ndarray] = []
488
+ for _ in range(int(km_repeats)):
489
+ lbl, _ = _kmeans_single(mat, centers, rng)
490
+ runs.append(lbl)
491
+ same = (lbl[:, None] == lbl[None, :]).astype(float)
492
+ coassoc += same
493
+ coassoc /= float(km_repeats)
494
+ dist_mat = np.maximum(0.0, 1.0 - coassoc)
495
+ np.fill_diagonal(dist_mat, 0.0)
496
+ # Cluster the consensus distance matrix with average linkage & cut into `centers`
497
+ from .dendrogram import as_dist, cutree
498
+ hc = hclust(as_dist(dist_mat), method="average")
499
+ cl = cutree(hc, k=centers)
500
+ # Remap to consecutive 0..k-1
501
+ uniq = sorted(set(int(v) for v in cl))
502
+ mp = {u: idx for idx, u in enumerate(uniq)}
503
+ return np.array([mp[int(v)] for v in cl], dtype=int)
504
+
505
+
506
+ def _format_slice_titles(title_list: list[Any], slice_names: list[str] | None, n_slices: int) -> list[Any]:
507
+ if not title_list:
508
+ return []
509
+ if len(title_list) == 1:
510
+ t0 = title_list[0]
511
+ if isinstance(t0, GridText) or n_slices <= 1:
512
+ return title_list
513
+ if "%s" in str(t0) and slice_names is not None:
514
+ return [str(t0).replace("%s", nm) for nm in slice_names]
515
+ return [t0]
516
+ if len(title_list) < n_slices:
517
+ return [title_list[i % len(title_list)] for i in range(n_slices)]
518
+ return title_list[:n_slices]
519
+
520
+
521
+ def _normalize_annotation(anno: Any, side: str, n_obs: int, mat_names: list[str] | None) -> tuple[HeatmapAnnotation | None, dict[str, Any]]:
522
+ if anno is None:
523
+ return None, {"side": side}
524
+ if not isinstance(anno, HeatmapAnnotation):
525
+ raise TypeError(f"`{side}_annotation` must be a HeatmapAnnotation (or rowAnnotation for left/right).")
526
+ expected_which = "column" if side in ("top", "bottom") else "row"
527
+ if anno.which != expected_which:
528
+ raise ValueError(f"`{side}_annotation` must have which={expected_which!r}, got {anno.which!r}.")
529
+ a_nobs = anno.nobs()
530
+ if a_nobs is not None and a_nobs != n_obs and n_obs > 0:
531
+ raise ValueError(f"`{side}_annotation` length ({a_nobs}) does not match matrix {'columns' if expected_which == 'column' else 'rows'} ({n_obs}).")
532
+ param: dict[str, Any] = {"side": side}
533
+ if side in ("top", "bottom"):
534
+ param["height"] = anno.height + as_unit(ht_opt.COLUMN_ANNO_PADDING, "mm")
535
+ else:
536
+ param["width"] = anno.width + as_unit(ht_opt.ROW_ANNO_PADDING, "mm")
537
+ return anno, param
538
+
539
+
540
+ def _calc_slice_layout(counts: Sequence[int], gap: Unit, axis: str) -> tuple[Unit, Unit]:
541
+ """Compute slice start positions (`x` left-to-right or `y` top-to-bottom) and slice sizes as `Unit`s."""
542
+ n_slice = len(counts)
543
+ total = sum(counts)
544
+ if total == 0:
545
+ fracs = np.full(n_slice, 1.0 / max(1, n_slice))
546
+ else:
547
+ fracs = np.asarray(counts, dtype=float) / float(total)
548
+
549
+ if n_slice == 1:
550
+ sizes = unit(1.0, "npc")
551
+ starts = unit(0.0, "npc") if axis == "x" else unit(1.0, "npc")
552
+ return starts, sizes
553
+
554
+ # Recycle gap to length n_slice - 1
555
+ gap_mm = gap.to_mm(axis)
556
+ g_vals = [float(gap_mm[i % len(gap_mm)]) for i in range(n_slice - 1)]
557
+ gaps_u = [unit(g, "mm") for g in g_vals]
558
+ total_gap_u = unit(sum(g_vals), "mm")
559
+ avail = unit(1.0, "npc") - total_gap_u
560
+ sizes = avail * fracs
561
+
562
+ pos_list: list[Unit] = []
563
+ if axis == "x":
564
+ cur = unit(0.0, "npc")
565
+ for i in range(n_slice):
566
+ pos_list.append(cur)
567
+ if i < n_slice - 1:
568
+ cur = cur + sizes[i] + gaps_u[i]
569
+ else:
570
+ cur = unit(1.0, "npc")
571
+ for i in range(n_slice):
572
+ pos_list.append(cur)
573
+ if i < n_slice - 1:
574
+ cur = cur - sizes[i] - gaps_u[i]
575
+ return unit_c(*pos_list), sizes
576
+
577
+
578
+ class Heatmap(AdditiveUnit):
579
+ """Single heatmap component with clustering, splitting, annotations, and 9x9 layout."""
580
+
581
+ def __init__(
582
+ self,
583
+ matrix: Any,
584
+ col: Any = None,
585
+ name: str | None = None,
586
+ na_col: str = "grey",
587
+ color_space: str = "LAB",
588
+ rect_gp: dict[str, Any] | None = None,
589
+ border: Any = None,
590
+ border_gp: dict[str, Any] | None = None,
591
+ cell_fun: Callable[..., Any] | None = None,
592
+ layer_fun: Callable[..., Any] | None = None,
593
+ jitter: Any = False,
594
+
595
+ row_title: Any = None,
596
+ row_title_side: str = "left",
597
+ row_title_gp: dict[str, Any] | None = None,
598
+ row_title_rot: float | None = None,
599
+ column_title: Any = None,
600
+ column_title_side: str = "top",
601
+ column_title_gp: dict[str, Any] | None = None,
602
+ column_title_rot: float = 0.0,
603
+
604
+ cluster_rows: Any = True,
605
+ cluster_row_slices: bool = True,
606
+ clustering_distance_rows: Any = "euclidean",
607
+ clustering_method_rows: str = "complete",
608
+ row_dend_side: str = "left",
609
+ row_dend_width: Unit | None = None,
610
+ show_row_dend: bool = True,
611
+ row_dend_reorder: Any = None,
612
+ row_dend_gp: dict[str, Any] | None = None,
613
+
614
+ cluster_columns: Any = True,
615
+ cluster_column_slices: bool = True,
616
+ clustering_distance_columns: Any = "euclidean",
617
+ clustering_method_columns: str = "complete",
618
+ column_dend_side: str = "top",
619
+ column_dend_height: Unit | None = None,
620
+ show_column_dend: bool = True,
621
+ column_dend_reorder: Any = None,
622
+ column_dend_gp: dict[str, Any] | None = None,
623
+
624
+ row_order: Any = None,
625
+ column_order: Any = None,
626
+
627
+ row_labels: Any = None,
628
+ row_names_side: str = "right",
629
+ show_row_names: bool = True,
630
+ row_names_max_width: Unit | None = None,
631
+ row_names_gp: dict[str, Any] | None = None,
632
+ row_names_rot: float = 0.0,
633
+ row_names_centered: bool = False,
634
+
635
+ column_labels: Any = None,
636
+ column_names_side: str = "bottom",
637
+ show_column_names: bool = True,
638
+ column_names_max_height: Unit | None = None,
639
+ column_names_gp: dict[str, Any] | None = None,
640
+ column_names_rot: float = 90.0,
641
+ column_names_centered: bool = False,
642
+
643
+ top_annotation: HeatmapAnnotation | None = None,
644
+ bottom_annotation: HeatmapAnnotation | None = None,
645
+ left_annotation: HeatmapAnnotation | None = None,
646
+ right_annotation: HeatmapAnnotation | None = None,
647
+
648
+ km: int = 1,
649
+ km_repeats: int = 1,
650
+ split: Any = None,
651
+ row_km: int | None = None,
652
+ row_km_repeats: int | None = None,
653
+ row_split: Any = None,
654
+ column_km: int = 1,
655
+ column_km_repeats: int = 1,
656
+ column_split: Any = None,
657
+ gap: Unit | None = None,
658
+ row_gap: Unit | None = None,
659
+ column_gap: Unit | None = None,
660
+ show_parent_dend_line: bool | None = None,
661
+
662
+ heatmap_width: Unit | None = None,
663
+ width: Unit | None = None,
664
+ heatmap_height: Unit | None = None,
665
+ height: Unit | None = None,
666
+
667
+ show_heatmap_legend: bool = True,
668
+ heatmap_legend_param: dict[str, Any] | None = None,
669
+
670
+ use_raster: bool | None = None,
671
+ raster_device: str = "png",
672
+ raster_quality: float = 1.0,
673
+ raster_device_param: dict[str, Any] | None = None,
674
+ raster_resize_mat: Any = False,
675
+ raster_by_magick: bool = False,
676
+ raster_magick_filter: str | None = None,
677
+ post_fun: Callable[..., Any] | None = None,
678
+ ) -> None:
679
+ if name is None:
680
+ name = f"matrix_{_ENV.next_heatmap_index()}"
681
+ else:
682
+ name = str(name)
683
+ if name == "":
684
+ raise ValueError("Heatmap `name` cannot be empty string.")
685
+ self.name = name
686
+
687
+ # Apply ht_opt defaults when args omitted
688
+ if row_names_gp is None:
689
+ row_names_gp = ht_opt.heatmap_row_names_gp if ht_opt.heatmap_row_names_gp is not None else gpar(fontsize=12)
690
+ if column_names_gp is None:
691
+ column_names_gp = ht_opt.heatmap_column_names_gp if ht_opt.heatmap_column_names_gp is not None else gpar(fontsize=12)
692
+ if row_title_gp is None:
693
+ row_title_gp = ht_opt.heatmap_row_title_gp if ht_opt.heatmap_row_title_gp is not None else gpar(fontsize=13.2)
694
+ if column_title_gp is None:
695
+ column_title_gp = ht_opt.heatmap_column_title_gp if ht_opt.heatmap_column_title_gp is not None else gpar(fontsize=13.2)
696
+
697
+ hlp = dict(heatmap_legend_param) if heatmap_legend_param is not None else {"title": name}
698
+ hlp.setdefault("title", name)
699
+ for opt_key in ("title_gp", "title_position", "labels_gp", "grid_width", "grid_height", "border"):
700
+ if opt_key not in hlp:
701
+ gval = ht_opt.get(f"legend_{opt_key}")
702
+ if gval is not None:
703
+ hlp[opt_key] = gval
704
+
705
+ mat, is_num, mat_rn, mat_cn, fa_levels = _parse_matrix(matrix, name)
706
+ nr, nc = mat.shape
707
+ self.matrix = mat
708
+ self._is_numeric = is_num
709
+ self._rownames = mat_rn
710
+ self._colnames = mat_cn
711
+
712
+ eff_rect_gp = check_gp(gpar(col=None) if rect_gp is None else rect_gp)
713
+ if border is None:
714
+ border = ht_opt.heatmap_border if ht_opt.heatmap_border is not None else False
715
+ eff_border_gp = check_gp(gpar(col="black") if border_gp is None else border_gp)
716
+
717
+ # Normalize km / split / gap aliases
718
+ eff_row_km = int(km if row_km is None else row_km)
719
+ eff_row_km_repeats = int(km_repeats if row_km_repeats is None else row_km_repeats)
720
+ eff_row_split = split if row_split is None else row_split
721
+ eff_column_km = int(column_km)
722
+ eff_column_km_repeats = int(column_km_repeats)
723
+ eff_column_split = column_split
724
+
725
+ eff_row_gap = as_unit(unit(1, "mm") if (gap is None and row_gap is None) else (gap if row_gap is None else row_gap), "mm")
726
+ eff_column_gap = as_unit(unit(1, "mm") if column_gap is None else column_gap, "mm")
727
+
728
+ if show_parent_dend_line is None:
729
+ show_parent_dend_line = bool(ht_opt.show_parent_dend_line)
730
+
731
+ # Matrix ColorMapping
732
+ self.matrix_color_mapping: ColorMapping | None = None
733
+ if nr > 0 and nc > 0:
734
+ if col is None:
735
+ if eff_rect_gp.get("type") == "none" and np.all([_is_na(v) for v in mat.ravel()]):
736
+ self.matrix_color_mapping = None
737
+ else:
738
+ inferred = default_col(mat, main_matrix=True)
739
+ if callable(inferred):
740
+ self.matrix_color_mapping = ColorMapping(name=name, col_fun=inferred, na_col=na_col)
741
+ else:
742
+ if fa_levels is not None and not is_num:
743
+ # Preserve categorical level ordering
744
+ lvl_cols = {str(lv): default_col([str(x) for x in fa_levels], main_matrix=True)[str(lv)] for lv in fa_levels if str(lv) in inferred}
745
+ self.matrix_color_mapping = ColorMapping(name=name, colors=lvl_cols or inferred, na_col=na_col)
746
+ else:
747
+ self.matrix_color_mapping = ColorMapping(name=name, colors=inferred, na_col=na_col)
748
+ elif isinstance(col, ColorMapping):
749
+ self.matrix_color_mapping = copy.copy(col)
750
+ elif callable(col):
751
+ self.matrix_color_mapping = ColorMapping(name=name, col_fun=col, na_col=na_col)
752
+ elif isinstance(col, dict):
753
+ eff_na = col.get("_NA_", na_col)
754
+ clean = {str(k): v for k, v in col.items() if k != "_NA_"}
755
+ self.matrix_color_mapping = ColorMapping(name=name, colors=clean, na_col=eff_na, full_col=clean)
756
+ elif isinstance(col, (list, tuple, np.ndarray)):
757
+ col_seq = [str(c) for c in col]
758
+ if not is_num:
759
+ uniq = list(dict.fromkeys(str(v) for v in mat.ravel() if not _is_na(v)))
760
+ if len(col_seq) < len(uniq):
761
+ raise ValueError(f"Length of `col` ({len(col_seq)}) < unique discrete levels ({len(uniq)}).")
762
+ mp = dict(zip(uniq, col_seq[: len(uniq)]))
763
+ self.matrix_color_mapping = ColorMapping(name=name, colors=mp, na_col=na_col)
764
+ else:
765
+ from .colors import colorRamp2
766
+ vals = mat.astype(float)
767
+ finite = vals[np.isfinite(vals)]
768
+ if len(finite) == 0:
769
+ vmin, vmax = 0.0, 1.0
770
+ else:
771
+ vmin, vmax = float(np.min(finite)), float(np.max(finite))
772
+ if vmin == vmax:
773
+ vmax = vmin + 1.0
774
+ if len(col_seq) == 1:
775
+ col_seq = [col_seq[0], col_seq[0]]
776
+ cf = colorRamp2(np.linspace(vmin, vmax, len(col_seq)), col_seq, space=color_space)
777
+ self.matrix_color_mapping = ColorMapping(name=name, col_fun=cf, na_col=na_col)
778
+ else:
779
+ raise TypeError(f"Unsupported `col` type: {type(col)}")
780
+
781
+ self.matrix_legend_param = hlp
782
+
783
+ # Width / height validation & normalization
784
+ if width is not None and heatmap_width is not None:
785
+ raise ValueError("Cannot specify both `width` and `heatmap_width`.")
786
+ if height is not None and heatmap_height is not None:
787
+ raise ValueError("Cannot specify both `height` and `heatmap_height`.")
788
+
789
+ if width is not None:
790
+ w_u = as_unit(width, "mm")
791
+ hw_u = unit(1.0, "npc")
792
+ elif heatmap_width is not None:
793
+ w_u = unit(1.0, "npc")
794
+ hw_u = as_unit(heatmap_width, "mm")
795
+ else:
796
+ w_u = unit(1.0, "npc")
797
+ hw_u = unit(1.0, "npc")
798
+
799
+ if height is not None:
800
+ h_u = as_unit(height, "mm")
801
+ hh_u = unit(1.0, "npc")
802
+ elif heatmap_height is not None:
803
+ h_u = unit(1.0, "npc")
804
+ hh_u = as_unit(heatmap_height, "mm")
805
+ else:
806
+ h_u = unit(1.0, "npc")
807
+ hh_u = unit(1.0, "npc")
808
+
809
+ # Validate body dims for clusterability
810
+ self.matrix_param: dict[str, Any] = {
811
+ "row_km": eff_row_km,
812
+ "row_km_repeats": eff_row_km_repeats,
813
+ "row_split": eff_row_split,
814
+ "row_gap": eff_row_gap,
815
+ "column_km": eff_column_km,
816
+ "column_km_repeats": eff_column_km_repeats,
817
+ "column_split": eff_column_split,
818
+ "column_gap": eff_column_gap,
819
+ "border": border,
820
+ "border_gp": eff_border_gp,
821
+ "rect_gp": eff_rect_gp,
822
+ "jitter": jitter,
823
+ "cell_fun": cell_fun,
824
+ "layer_fun": layer_fun,
825
+ "width": w_u,
826
+ "height": h_u,
827
+ "_user_split_row": eff_row_split,
828
+ "_user_split_column": eff_column_split,
829
+ }
830
+
831
+ # Titles
832
+ rt_side = _normalize_side(row_title_side, ("left", "right"), "row_title_side")
833
+ ct_side = _normalize_side(column_title_side, ("top", "bottom"), "column_title_side")
834
+ rt_rot = (90.0 if rt_side == "left" else 270.0) if row_title_rot is None else float(row_title_rot)
835
+ ct_rot = float(column_title_rot)
836
+
837
+ self.row_title = _normalize_title_list(row_title)
838
+ self.row_title_param: dict[str, Any] = {
839
+ "side": rt_side,
840
+ "gp": check_gp(row_title_gp),
841
+ "rot": rt_rot,
842
+ "just": _get_text_just(rt_rot, rt_side),
843
+ }
844
+ self.column_title = _normalize_title_list(column_title)
845
+ self.column_title_param: dict[str, Any] = {
846
+ "side": ct_side,
847
+ "gp": check_gp(column_title_gp),
848
+ "rot": ct_rot,
849
+ "just": _get_text_just(ct_rot, ct_side),
850
+ }
851
+
852
+ # Row clustering parameters
853
+ rd_side = _normalize_side(row_dend_side, ("left", "right"), "row_dend_side")
854
+ cd_side = _normalize_side(column_dend_side, ("top", "bottom"), "column_dend_side")
855
+ rd_w = unit(10, "mm") if row_dend_width is None else as_unit(row_dend_width, "mm")
856
+ cd_h = unit(10, "mm") if column_dend_height is None else as_unit(column_dend_height, "mm")
857
+
858
+ def _parse_cluster_arg(cl_arg: Any, n_items: int, manual_order: Any, axis_nm: str, reorder_arg: Any) -> dict[str, Any]:
859
+ is_obj = isinstance(cl_arg, (Hclust, Dendrogram)) or (isinstance(cl_arg, np.ndarray) and cl_arg.ndim == 2 and cl_arg.shape[1] == 4)
860
+ is_fn = callable(cl_arg)
861
+ if isinstance(cl_arg, (bool, np.bool_)):
862
+ do_cl = bool(cl_arg)
863
+ obj = None
864
+ fun = None
865
+ elif is_obj:
866
+ do_cl = True
867
+ obj = as_dendrogram(Hclust(cl_arg) if isinstance(cl_arg, np.ndarray) else cl_arg)
868
+ fun = None
869
+ elif is_fn:
870
+ do_cl = True
871
+ obj = None
872
+ fun = cl_arg
873
+ else:
874
+ raise TypeError(f"`cluster_{axis_nm}` must be bool, Hclust, Dendrogram, linkage array, or callable.")
875
+
876
+ if n_items <= 1 or not is_num and not is_obj and not is_fn and not callable(distance_arg_for(axis_nm)):
877
+ pass
878
+
879
+ eff_reorder = (isinstance(cl_arg, (bool, np.bool_)) or is_fn) if reorder_arg is None else reorder_arg
880
+ return {
881
+ "cluster": do_cl,
882
+ "obj": obj,
883
+ "fun": fun,
884
+ "reorder": eff_reorder,
885
+ }
886
+
887
+ def distance_arg_for(axis_nm: str) -> Any:
888
+ return clustering_distance_rows if axis_nm == "rows" else clustering_distance_columns
889
+
890
+ def _normalize_manual_order(ord_val: Any, names_list: list[str] | None, n_items: int, axis_nm: str) -> tuple[list[int], bool]:
891
+ if ord_val is None:
892
+ return list(range(n_items)), False
893
+ seq = list(ord_val)
894
+ if len(seq) != n_items:
895
+ raise ValueError(f"Length of `{axis_nm}_order` ({len(seq)}) must equal {n_items}.")
896
+ if all(isinstance(x, str) for x in seq):
897
+ if names_list is None:
898
+ raise ValueError(f"Character `{axis_nm}_order` requires matrix {axis_nm} names.")
899
+ lookup = {nm: i for i, nm in enumerate(names_list)}
900
+ return [lookup[s] for s in seq], True
901
+ idx = [int(x) for x in seq]
902
+ # Support 1-based R order passed accidentally? Wait: in Python tests we stick strictly to 0-based!
903
+ # Only validate range 0 .. n_items - 1 cleanly.
904
+ if any(i < 0 or i >= n_items for i in idx):
905
+ raise IndexError(f"`{axis_nm}_order` contains out-of-range 0-based indices for length {n_items}.")
906
+ return idx, True
907
+
908
+ r_ord_norm, r_ord_set = _normalize_manual_order(row_order, mat_rn, nr, "row")
909
+ c_ord_norm, c_ord_set = _normalize_manual_order(column_order, mat_cn, nc, "column")
910
+
911
+ if r_ord_set:
912
+ cluster_rows_eff: Any = False
913
+ else:
914
+ cluster_rows_eff = cluster_rows
915
+ if c_ord_set:
916
+ cluster_cols_eff: Any = False
917
+ else:
918
+ cluster_cols_eff = cluster_columns
919
+
920
+ # Non-numeric matrices disable default clustering unless user provides distance func/cluster obj
921
+ rc_info = _parse_cluster_arg(cluster_rows_eff, nr, row_order, "rows", row_dend_reorder)
922
+ if not is_num and rc_info["obj"] is None and rc_info["fun"] is None and not callable(clustering_distance_rows):
923
+ rc_info["cluster"] = False
924
+ if nr <= 1 or nc == 0:
925
+ if rc_info["obj"] is None:
926
+ rc_info["cluster"] = False
927
+
928
+ cc_info = _parse_cluster_arg(cluster_cols_eff, nc, column_order, "columns", column_dend_reorder)
929
+ if not is_num and cc_info["obj"] is None and cc_info["fun"] is None and not callable(clustering_distance_columns):
930
+ cc_info["cluster"] = False
931
+ if nc <= 1 or nr == 0:
932
+ if cc_info["obj"] is None:
933
+ cc_info["cluster"] = False
934
+
935
+ # Adjust dend width with DENDROGRAM_PADDING when shown
936
+ dend_pad = convertWidth(as_unit(ht_opt.DENDROGRAM_PADDING, "mm"), "mm", valueOnly=True)
937
+ rd_w_mm = convertWidth(rd_w, "mm", valueOnly=True)
938
+ cd_h_mm = convertHeight(cd_h, "mm", valueOnly=True)
939
+ eff_show_rd = bool(show_row_dend and rc_info["cluster"] and nr > 1 and rd_w_mm > 0)
940
+ eff_show_cd = bool(show_column_dend and cc_info["cluster"] and nc > 1 and cd_h_mm > 0)
941
+
942
+ self.row_dend_param: dict[str, Any] = {
943
+ "cluster": rc_info["cluster"],
944
+ "obj": rc_info["obj"],
945
+ "fun": rc_info["fun"],
946
+ "cluster_slices": bool(cluster_row_slices),
947
+ "distance": clustering_distance_rows,
948
+ "method": clustering_method_rows,
949
+ "side": rd_side,
950
+ "width": unit(rd_w_mm + dend_pad, "mm") if eff_show_rd else unit(0.0, "mm"),
951
+ "show": eff_show_rd,
952
+ "gp": check_gp(gpar() if row_dend_gp is None else row_dend_gp),
953
+ "reorder": rc_info["reorder"],
954
+ "split_by_cutree": False,
955
+ }
956
+ self.column_dend_param: dict[str, Any] = {
957
+ "cluster": cc_info["cluster"],
958
+ "obj": cc_info["obj"],
959
+ "fun": cc_info["fun"],
960
+ "cluster_slices": bool(cluster_column_slices),
961
+ "distance": clustering_distance_columns,
962
+ "method": clustering_method_columns,
963
+ "side": cd_side,
964
+ "height": unit(cd_h_mm + dend_pad, "mm") if eff_show_cd else unit(0.0, "mm"),
965
+ "show": eff_show_cd,
966
+ "gp": check_gp(gpar() if column_dend_gp is None else column_dend_gp),
967
+ "reorder": cc_info["reorder"],
968
+ "split_by_cutree": False,
969
+ }
970
+
971
+ self.row_dend_list: list[Dendrogram | None] = []
972
+ self.row_dend_slice: Dendrogram | None = None
973
+ self.row_order: list[int] = r_ord_norm
974
+ self.row_order_list: list[list[int]] = [list(r_ord_norm)] if nr > 0 else [[]]
975
+
976
+ self.column_dend_list: list[Dendrogram | None] = []
977
+ self.column_dend_slice: Dendrogram | None = None
978
+ self.column_order: list[int] = c_ord_norm
979
+ self.column_order_list: list[list[int]] = [list(c_ord_norm)] if nc > 0 else [[]]
980
+
981
+ # Dimension names annotations
982
+ rn_side = _normalize_side(row_names_side, ("right", "left"), "row_names_side")
983
+ cn_side = _normalize_side(column_names_side, ("bottom", "top"), "column_names_side")
984
+ rn_max_w = unit(6, "cm") if row_names_max_width is None else as_unit(row_names_max_width, "mm")
985
+ cn_max_h = unit(6, "cm") if column_names_max_height is None else as_unit(column_names_max_height, "mm")
986
+
987
+ r_labels_fmt = _format_labels_input(row_labels, mat_rn, nr, "row_labels")
988
+ c_labels_fmt = _format_labels_input(column_labels, mat_cn, nc, "column_labels")
989
+ rn_anno = None
990
+ eff_show_rn = bool(show_row_names and r_labels_fmt is not None and len(r_labels_fmt) > 0 and nr > 0)
991
+ if eff_show_rn:
992
+ r_just, r_loc = _dimname_just_and_loc(rn_side, row_names_rot, row_names_centered)
993
+ rn_anno = anno_text(
994
+ r_labels_fmt,
995
+ which="row",
996
+ gp=check_gp(row_names_gp),
997
+ rot=float(row_names_rot),
998
+ just=r_just,
999
+ location=r_loc,
1000
+ width=max_text_width(r_labels_fmt, gp=check_gp(row_names_gp), rot=float(row_names_rot)),
1001
+ )
1002
+
1003
+ cn_anno = None
1004
+ eff_show_cn = bool(show_column_names and c_labels_fmt is not None and len(c_labels_fmt) > 0 and nc > 0)
1005
+ if eff_show_cn:
1006
+ c_just, c_loc = _dimname_just_and_loc(cn_side, column_names_rot, column_names_centered)
1007
+ cn_anno = anno_text(
1008
+ c_labels_fmt,
1009
+ which="column",
1010
+ gp=check_gp(column_names_gp),
1011
+ rot=float(column_names_rot),
1012
+ just=c_just,
1013
+ location=c_loc,
1014
+ height=max_text_height(c_labels_fmt, gp=check_gp(column_names_gp), rot=float(column_names_rot)),
1015
+ )
1016
+
1017
+ self.row_names_param: dict[str, Any] = {
1018
+ "labels": r_labels_fmt,
1019
+ "side": rn_side,
1020
+ "show": eff_show_rn,
1021
+ "gp": check_gp(row_names_gp),
1022
+ "rot": float(row_names_rot),
1023
+ "centered": bool(row_names_centered),
1024
+ "max_width": rn_max_w,
1025
+ "anno": rn_anno,
1026
+ }
1027
+ self.column_names_param: dict[str, Any] = {
1028
+ "labels": c_labels_fmt,
1029
+ "side": cn_side,
1030
+ "show": eff_show_cn,
1031
+ "gp": check_gp(column_names_gp),
1032
+ "rot": float(column_names_rot),
1033
+ "centered": bool(column_names_centered),
1034
+ "max_height": cn_max_h,
1035
+ "anno": cn_anno,
1036
+ }
1037
+
1038
+ # Top/Bottom/Left/Right annotations
1039
+ self.top_annotation, self.top_annotation_param = _normalize_annotation(top_annotation, "top", nc, mat_cn)
1040
+ self.bottom_annotation, self.bottom_annotation_param = _normalize_annotation(bottom_annotation, "bottom", nc, mat_cn)
1041
+ self.left_annotation, self.left_annotation_param = _normalize_annotation(left_annotation, "left", nr, mat_rn)
1042
+ self.right_annotation, self.right_annotation_param = _normalize_annotation(right_annotation, "right", nr, mat_rn)
1043
+
1044
+ # Raster & global heatmap parameters
1045
+ if use_raster is None:
1046
+ eff_raster = bool(((nr > 2000 and nc > 10) or (nc > 2000 and nr > 10)) and cell_fun is None and eff_rect_gp.get("type") != "none")
1047
+ else:
1048
+ eff_raster = bool(use_raster)
1049
+ if cell_fun is not None:
1050
+ eff_raster = False
1051
+
1052
+ self.heatmap_param: dict[str, Any] = {
1053
+ "width": hw_u,
1054
+ "height": hh_u,
1055
+ "show_heatmap_legend": bool(show_heatmap_legend and self.matrix_color_mapping is not None and nr > 0 and nc > 0),
1056
+ "use_raster": eff_raster,
1057
+ "raster_device": raster_device,
1058
+ "raster_quality": float(raster_quality),
1059
+ "raster_device_param": dict(raster_device_param or {}),
1060
+ "raster_resize_mat": raster_resize_mat,
1061
+ "raster_by_magick": bool(raster_by_magick),
1062
+ "raster_magick_filter": raster_magick_filter,
1063
+ "show_parent_dend_line": bool(show_parent_dend_line),
1064
+ "post_fun": post_fun,
1065
+ "direction": "horizontal",
1066
+ }
1067
+
1068
+ self.layout: dict[str, Any] = {
1069
+ "initialized": False,
1070
+ "layout_size": {
1071
+ "column_title_top_height": unit(0, "mm"),
1072
+ "column_dend_top_height": unit(0, "mm"),
1073
+ "column_names_top_height": unit(0, "mm"),
1074
+ "column_anno_top_height": unit(0, "mm"),
1075
+ "column_anno_bottom_height": unit(0, "mm"),
1076
+ "column_names_bottom_height": unit(0, "mm"),
1077
+ "column_dend_bottom_height": unit(0, "mm"),
1078
+ "column_title_bottom_height": unit(0, "mm"),
1079
+ "row_title_left_width": unit(0, "mm"),
1080
+ "row_dend_left_width": unit(0, "mm"),
1081
+ "row_names_left_width": unit(0, "mm"),
1082
+ "row_anno_left_width": unit(0, "mm"),
1083
+ "row_anno_right_width": unit(0, "mm"),
1084
+ "row_names_right_width": unit(0, "mm"),
1085
+ "row_dend_right_width": unit(0, "mm"),
1086
+ "row_title_right_width": unit(0, "mm"),
1087
+ },
1088
+ "layout_index": [],
1089
+ "graphic_fun_list": [],
1090
+ "slice": {},
1091
+ }
1092
+
1093
+ # ---- Dimensions & Properties ----
1094
+
1095
+ _oncoprint_env: dict[str, Any] | None = None
1096
+
1097
+ @property
1098
+ def _matrix(self) -> np.ndarray:
1099
+ return self.matrix
1100
+
1101
+ @property
1102
+ def _matrix_color_mapping(self) -> ColorMapping | None:
1103
+ return self.matrix_color_mapping
1104
+
1105
+ @property
1106
+ def _row_split_df(self) -> pd.DataFrame | None:
1107
+ return self.matrix_param.get("_row_split_df")
1108
+
1109
+ @property
1110
+ def _column_split_df(self) -> pd.DataFrame | None:
1111
+ return self.matrix_param.get("_column_split_df")
1112
+
1113
+ @property
1114
+ def nrow(self) -> int:
1115
+ return int(self.matrix.shape[0])
1116
+
1117
+ @property
1118
+ def ncol(self) -> int:
1119
+ return int(self.matrix.shape[1])
1120
+
1121
+ @property
1122
+ def shape(self) -> tuple[int, int]:
1123
+ return (self.nrow, self.ncol)
1124
+
1125
+ def dim(self) -> tuple[int, int]:
1126
+ return self.shape
1127
+
1128
+ def copy_all(self) -> "Heatmap":
1129
+ return copy.deepcopy(self)
1130
+
1131
+ # ---- Annotations Attachment ----
1132
+
1133
+ def attach_annotation(self, ha: HeatmapAnnotation, side: str = "top", gap: Unit | None = None) -> "Heatmap":
1134
+ side = _normalize_side(side, ("top", "bottom", "left", "right"), "side")
1135
+ cp = copy.copy(self)
1136
+ from .annotations import c_HeatmapAnnotation
1137
+ slot_name = f"{side}_annotation"
1138
+ cur = getattr(cp, slot_name)
1139
+ if cur is None:
1140
+ combined = ha
1141
+ else:
1142
+ combined = c_HeatmapAnnotation(cur, ha, gap=gap) if gap is not None else c_HeatmapAnnotation(cur, ha)
1143
+ n_obs = cp.ncol if side in ("top", "bottom") else cp.nrow
1144
+ nm_list = cp._colnames if side in ("top", "bottom") else cp._rownames
1145
+ anno_obj, param = _normalize_annotation(combined, side, n_obs, nm_list)
1146
+ setattr(cp, slot_name, anno_obj)
1147
+ setattr(cp, f"{side}_annotation_param", param)
1148
+ return cp
1149
+
1150
+ # ---- Clustering Engine ----
1151
+
1152
+ def _make_axis_cluster(self, which: str) -> None:
1153
+ is_row = which == "row"
1154
+ mat_work = self.matrix if is_row else self.matrix.T
1155
+ n_items = mat_work.shape[0]
1156
+ if n_items == 0:
1157
+ if is_row:
1158
+ self.row_order = []
1159
+ self.row_order_list = [[]]
1160
+ self.row_dend_list = [None]
1161
+ self.row_dend_slice = None
1162
+ else:
1163
+ self.column_order = []
1164
+ self.column_order_list = [[]]
1165
+ self.column_dend_list = [None]
1166
+ self.column_dend_slice = None
1167
+ return
1168
+
1169
+ # Optional jitter for clustering only
1170
+ jitter = self.matrix_param["jitter"]
1171
+ if jitter is not False and self._is_numeric:
1172
+ jit_val = 1e-10 if jitter is True else float(jitter)
1173
+ rng_jit = np.random.default_rng(0)
1174
+ mat_work = mat_work.astype(float) + rng_jit.uniform(0.0, jit_val, size=mat_work.shape)
1175
+
1176
+ dend_param = self.row_dend_param if is_row else self.column_dend_param
1177
+ order_init = list(self.row_order if is_row else self.column_order)
1178
+ km = self.matrix_param["row_km" if is_row else "column_km"]
1179
+ km_repeats = self.matrix_param["row_km_repeats" if is_row else "column_km_repeats"]
1180
+ split = self.matrix_param["row_split" if is_row else "column_split"]
1181
+
1182
+ dend_param["split_by_cutree"] = False
1183
+ dend_list: list[Dendrogram | None] = []
1184
+ dend_slice: Dendrogram | None = None
1185
+ order_list: list[list[int]] = []
1186
+ slice_names: list[str] | None = None
1187
+
1188
+ cluster = dend_param["cluster"]
1189
+ cluster_slices = dend_param["cluster_slices"]
1190
+ reorder = dend_param["reorder"]
1191
+ distance = dend_param["distance"]
1192
+ method = dend_param["method"]
1193
+
1194
+ # Helper to compute weights for reordering dendrograms
1195
+ def _weight_vec() -> np.ndarray | None:
1196
+ if reorder is False or reorder is None:
1197
+ return None
1198
+ if reorder is True:
1199
+ if not self._is_numeric:
1200
+ return None
1201
+ with np.errstate(all="ignore"):
1202
+ w = -np.nanmean(mat_work.astype(float), axis=1)
1203
+ return np.where(np.isnan(w), 0.0, w)
1204
+ arr_w = np.asarray(reorder, dtype=float).ravel()
1205
+ if len(arr_w) != n_items:
1206
+ raise ValueError(f"Length of `{which}_dend_reorder` ({len(arr_w)}) must equal {n_items}.")
1207
+ return arr_w
1208
+
1209
+ weights_full = _weight_vec()
1210
+
1211
+ # Case 1: Path A (cutree on single dendrogram when cluster=True and split is single int >= 1)
1212
+ is_scalar_int_split = isinstance(split, (int, np.integer)) and not isinstance(split, (bool, np.bool_))
1213
+ if cluster and (dend_param["obj"] is not None or is_scalar_int_split):
1214
+ if km > 1 and dend_param["obj"] is not None:
1215
+ raise ValueError("Cannot perform k-means when clustering object is supplied.")
1216
+ if is_scalar_int_split and km <= 1:
1217
+ k_cut = int(split)
1218
+ if k_cut < 1:
1219
+ raise ValueError(f"`{which}_split` integer must be >= 1.")
1220
+ if dend_param["obj"] is None:
1221
+ hc_full = _cluster_submatrix(mat_work, True if dend_param["fun"] is None else dend_param["fun"], distance, method)
1222
+ dend_full = as_dendrogram(hc_full)
1223
+ else:
1224
+ dend_full = as_dendrogram(dend_param["obj"])
1225
+
1226
+ if weights_full is not None and dend_param["obj"] is None:
1227
+ dend_full = reorder_dendrogram(dend_full, weights_full, agglo_fun=np.mean)
1228
+
1229
+ if k_cut == 1:
1230
+ dend_list = [dend_full]
1231
+ order_list = [order_dendrogram(dend_full)]
1232
+ dend_slice = None
1233
+ else:
1234
+ dend_param["split_by_cutree"] = True
1235
+ ct = cut_dendrogram(dend_full, k=k_cut)
1236
+ dend_list = list(ct["lower"])
1237
+ dend_slice = ct["upper"]
1238
+ order_list = [order_dendrogram(sub_d) for sub_d in dend_list]
1239
+ # Check order consistency: in R cut_dendrogram produces lower branches ordered by global order
1240
+ if len(order_list) == k_cut:
1241
+ slice_names = [str(i + 1) for i in range(k_cut)]
1242
+ else:
1243
+ # Clustering object with split=None (or scalar split=1 already handled)
1244
+ dend_full = as_dendrogram(dend_param["obj"])
1245
+ if split is None:
1246
+ dend_list = [dend_full]
1247
+ order_list = [order_dendrogram(dend_full)]
1248
+ else:
1249
+ raise ValueError(f"When clustering object is supplied, `{which}_split` can only be an integer count.")
1250
+
1251
+ # Save into slots & adjust x positions
1252
+ final_order = [idx for sl in order_list for idx in sl]
1253
+ # Normalize dendrogram x leaf coordinates within each slice (0.5 .. n_s - 0.5)
1254
+ adj_dends: list[Dendrogram | None] = []
1255
+ for sub_d in dend_list:
1256
+ if sub_d is not None and nobs(sub_d) > 0:
1257
+ adj_dends.append(adjust_dend_by_x(sub_d, np.arange(nobs(sub_d), dtype=float) + 0.5))
1258
+ else:
1259
+ adj_dends.append(sub_d)
1260
+ if is_row:
1261
+ self.row_dend_list = adj_dends
1262
+ self.row_dend_slice = dend_slice
1263
+ self.row_order_list = order_list
1264
+ self.row_order = final_order
1265
+ if slice_names and len(self.row_title) == 1 and "%s" in str(self.row_title[0]):
1266
+ self.row_title = _format_slice_titles(self.row_title, slice_names, len(order_list))
1267
+ else:
1268
+ self.column_dend_list = adj_dends
1269
+ self.column_dend_slice = dend_slice
1270
+ self.column_order_list = order_list
1271
+ self.column_order = final_order
1272
+ if slice_names and len(self.column_title) == 1 and "%s" in str(self.column_title[0]):
1273
+ self.column_title = _format_slice_titles(self.column_title, slice_names, len(order_list))
1274
+ return
1275
+
1276
+ # Case 2: Path B (slice-first: k-means + categorical split DF -> within-slice clustering -> slice dendrogram)
1277
+ split_df: pd.DataFrame | None = None
1278
+ if split is not None and not is_scalar_int_split:
1279
+ if isinstance(split, pd.DataFrame):
1280
+ split_df = split.copy()
1281
+ elif isinstance(split, pd.Categorical):
1282
+ split_df = pd.DataFrame({"split": pd.Series(split)})
1283
+ elif isinstance(split, (list, tuple)) and len(split) > 0 and isinstance(split[0], (list, tuple, pd.Series, pd.Categorical, np.ndarray)):
1284
+ split_df = pd.DataFrame({f"s{i}": list(col) for i, col in enumerate(split)})
1285
+ else:
1286
+ split_df = pd.DataFrame({"split": list(split) if not isinstance(split, np.ndarray) else split.tolist()})
1287
+
1288
+ if km > 1 and self._is_numeric and mat_work.shape[1] > 0:
1289
+ cl = _consensus_kmeans(mat_work, km, km_repeats=km_repeats)
1290
+ uniq_cl = sorted(set(int(v) for v in cl))
1291
+ with np.errstate(all="ignore"):
1292
+ mean_vecs = [np.nanmean(mat_work[cl == c, :], axis=0) for c in uniq_cl]
1293
+ mean_mat = np.vstack(mean_vecs) # shape (k_eff, p)
1294
+ if weights_full is not None:
1295
+ slice_wts = np.array([float(np.nanmean(weights_full[cl == c])) for c in uniq_cl])
1296
+ else:
1297
+ slice_wts = np.nanmean(mean_mat, axis=1)
1298
+
1299
+ if cluster_slices and len(uniq_cl) > 1:
1300
+ hc_s = hclust(calc_dist(mean_mat), method="complete")
1301
+ dend_s = reorder_dendrogram(as_dendrogram(hc_s), slice_wts, agglo_fun=np.mean)
1302
+ cl_ord = order_dendrogram(dend_s)
1303
+ else:
1304
+ cl_ord = np.argsort(slice_wts, kind="stable").tolist()
1305
+
1306
+ remap = {uniq_cl[old_pos]: str(new_pos + 1) for new_pos, old_pos in enumerate(cl_ord)}
1307
+ km_cats = [str(i + 1) for i in range(len(cl_ord))]
1308
+ km_col = pd.Categorical([remap[int(c)] for c in cl], categories=km_cats, ordered=True)
1309
+ if split_df is None:
1310
+ split_df = pd.DataFrame({"km": km_col})
1311
+ else:
1312
+ split_df.insert(0, "km", km_col)
1313
+
1314
+ if split_df is None:
1315
+ order_list = [order_init]
1316
+ slice_names = None
1317
+ else:
1318
+ norm_df, slice_names, groups = _normalize_split_df(split_df, n_items, f"{which}_split")
1319
+ # Intersect each group with user's manual order_init to respect row_order/column_order!
1320
+ order_set_map = {idx: pos for pos, idx in enumerate(order_init)}
1321
+ order_list = [sorted(grp, key=lambda idx: order_set_map[idx]) for grp in groups]
1322
+ if is_row:
1323
+ self.matrix_param["_row_split_df"] = norm_df
1324
+ else:
1325
+ self.matrix_param["_column_split_df"] = norm_df
1326
+
1327
+ n_slices = len(order_list)
1328
+ dend_list = [None] * n_slices
1329
+
1330
+ # Cluster within each slice
1331
+ if cluster:
1332
+ for k_s, idx_slice in enumerate(order_list):
1333
+ m_s = len(idx_slice)
1334
+ if m_s == 0:
1335
+ continue
1336
+ if m_s == 1:
1337
+ # Single-leaf dendrogram
1338
+ dend_list[k_s] = Dendrogram(leaf=True, value=int(idx_slice[0]), height=0.0, members=1)
1339
+ continue
1340
+ submat = mat_work[idx_slice, :]
1341
+ cl_obj = _cluster_submatrix(submat, True if dend_param["fun"] is None else dend_param["fun"], distance, method)
1342
+ sub_dend = as_dendrogram(cl_obj)
1343
+ # Map local leaf values (0..m_s-1) back to global matrix indices idx_slice
1344
+ def _remap_leaf_ids(node: Dendrogram, mapping: list[int]) -> None:
1345
+ if node.is_leaf:
1346
+ node.value = int(mapping[int(node.value)])
1347
+ else:
1348
+ for ch in node.children:
1349
+ _remap_leaf_ids(ch, mapping)
1350
+
1351
+ _remap_leaf_ids(sub_dend, idx_slice)
1352
+ if weights_full is not None:
1353
+ sub_dend = reorder_dendrogram(sub_dend, weights_full, agglo_fun=np.mean)
1354
+ sub_dend = adjust_dend_by_x(sub_dend, np.arange(m_s, dtype=float) + 0.5)
1355
+ dend_list[k_s] = sub_dend
1356
+ order_list[k_s] = order_dendrogram(sub_dend)
1357
+
1358
+ # Cluster between slices if n_slices > 1 and cluster_slices
1359
+ if n_slices > 1 and cluster_slices:
1360
+ mean_rows = []
1361
+ for idx_slice in order_list:
1362
+ with np.errstate(all="ignore"):
1363
+ mv = np.nanmean(mat_work[idx_slice, :].astype(float), axis=0)
1364
+ mv = np.where(np.isnan(mv), 0.0, mv)
1365
+ mean_rows.append(mv)
1366
+ mean_mat_s = np.vstack(mean_rows)
1367
+ try:
1368
+ d_s = _compute_distance(mean_mat_s, distance)
1369
+ hc_slice = hclust(d_s, method=method)
1370
+ except Exception:
1371
+ hc_slice = hclust(calc_dist(mean_mat_s, method="euclidean"), method=method)
1372
+ dend_slice = as_dendrogram(hc_slice)
1373
+ if weights_full is not None:
1374
+ s_wts = np.array([float(np.nanmean(weights_full[idx_slice])) for idx_slice in order_list])
1375
+ dend_slice = reorder_dendrogram(dend_slice, s_wts, agglo_fun=np.mean)
1376
+ slice_od = order_dendrogram(dend_slice)
1377
+ order_list = [order_list[i] for i in slice_od]
1378
+ dend_list = [dend_list[i] for i in slice_od]
1379
+ if slice_names is not None:
1380
+ slice_names = [slice_names[i] for i in slice_od]
1381
+ # Remap slice leaf values of dend_slice to new sorted order 0..n_slices-1
1382
+ inv_od = {old_i: new_i for new_i, old_i in enumerate(slice_od)}
1383
+ def _remap_slice_leaves(node: Dendrogram) -> None:
1384
+ if node.is_leaf:
1385
+ node.value = inv_od[int(node.value)]
1386
+ else:
1387
+ for ch in node.children:
1388
+ _remap_slice_leaves(ch)
1389
+ _remap_slice_leaves(dend_slice)
1390
+ dend_slice = adjust_dend_by_x(dend_slice, np.arange(n_slices, dtype=float) + 0.5)
1391
+
1392
+ final_order = [idx for sl in order_list for idx in sl]
1393
+ if is_row:
1394
+ self.row_dend_list = dend_list
1395
+ self.row_dend_slice = dend_slice
1396
+ self.row_order_list = order_list
1397
+ self.row_order = final_order
1398
+ if slice_names is not None:
1399
+ self.row_title = _format_slice_titles(self.row_title, slice_names, n_slices)
1400
+ elif len(self.row_title) > n_slices:
1401
+ self.row_title = self.row_title[:n_slices]
1402
+ else:
1403
+ self.column_dend_list = dend_list
1404
+ self.column_dend_slice = dend_slice
1405
+ self.column_order_list = order_list
1406
+ self.column_order = final_order
1407
+ if slice_names is not None:
1408
+ self.column_title = _format_slice_titles(self.column_title, slice_names, n_slices)
1409
+ elif len(self.column_title) > n_slices:
1410
+ self.column_title = self.column_title[:n_slices]
1411
+
1412
+ def make_row_cluster(self) -> "Heatmap":
1413
+ self._make_axis_cluster("row")
1414
+ return self
1415
+
1416
+ def make_column_cluster(self) -> "Heatmap":
1417
+ self._make_axis_cluster("column")
1418
+ return self
1419
+
1420
+ # ---- Layout Preparation ----
1421
+
1422
+ def prepare(self, process_rows: bool = True, process_columns: bool = True) -> "Heatmap":
1423
+ if process_rows:
1424
+ self.make_row_cluster()
1425
+ if process_columns:
1426
+ self.make_column_cluster()
1427
+ self.make_layout()
1428
+ return self
1429
+
1430
+ def make_layout(self) -> "Heatmap":
1431
+ if self.layout["initialized"]:
1432
+ return self
1433
+
1434
+ nr_slice = max(1, len(self.row_order_list))
1435
+ nc_slice = max(1, len(self.column_order_list))
1436
+ snr = [len(s) for s in self.row_order_list] if self.row_order_list else [0]
1437
+ snc = [len(s) for s in self.column_order_list] if self.column_order_list else [0]
1438
+
1439
+ slice_y, slice_height = _calc_slice_layout(snr, self.matrix_param["row_gap"], "y")
1440
+ slice_x, slice_width = _calc_slice_layout(snc, self.matrix_param["column_gap"], "x")
1441
+ self.layout["slice"] = {
1442
+ "x": slice_x,
1443
+ "y": slice_y,
1444
+ "width": slice_width,
1445
+ "height": slice_height,
1446
+ }
1447
+
1448
+ layout_size = self.layout["layout_size"]
1449
+ layout_index: list[tuple[int, int]] = []
1450
+ graphic_funs: list[Callable[[], None]] = []
1451
+
1452
+ # 1. Heatmap Body
1453
+ if self.nrow > 0 and self.ncol > 0:
1454
+ layout_index.append(_heatmap_layout_index("heatmap_body"))
1455
+
1456
+ def _draw_all_bodies() -> None:
1457
+ for kr in range(1, nr_slice + 1):
1458
+ for kc in range(1, nc_slice + 1):
1459
+ self.draw_heatmap_body(
1460
+ kr=kr,
1461
+ kc=kc,
1462
+ x=slice_x[kc - 1],
1463
+ y=slice_y[kr - 1],
1464
+ width=slice_width[kc - 1],
1465
+ height=slice_height[kr - 1],
1466
+ just=("left", "top"),
1467
+ )
1468
+
1469
+ graphic_funs.append(_draw_all_bodies)
1470
+
1471
+ # 2. Column Title
1472
+ if self.column_title:
1473
+ ct_side = self.column_title_param["side"]
1474
+ ct_gp = self.column_title_param["gp"]
1475
+ ct_rot = self.column_title_param["rot"]
1476
+ pad_c = _title_padding_unit(ct_gp)
1477
+ ct_h = max_text_height(self.column_title, gp=ct_gp, rot=ct_rot) + unit_sum(pad_c)
1478
+ if ct_side == "top":
1479
+ layout_size["column_title_top_height"] = ct_h
1480
+ layout_index.append(_heatmap_layout_index("column_title_top"))
1481
+ else:
1482
+ layout_size["column_title_bottom_height"] = ct_h
1483
+ layout_index.append(_heatmap_layout_index("column_title_bottom"))
1484
+
1485
+ def _draw_col_titles() -> None:
1486
+ if len(self.column_title) == 1 and nc_slice > 1:
1487
+ self.draw_title(which="column", k=1)
1488
+ else:
1489
+ for kc in range(1, nc_slice + 1):
1490
+ self.draw_title(which="column", k=kc, x=slice_x[kc - 1], width=slice_width[kc - 1], just="left")
1491
+
1492
+ graphic_funs.append(_draw_col_titles)
1493
+
1494
+ # 3. Row Title
1495
+ if self.row_title:
1496
+ rt_side = self.row_title_param["side"]
1497
+ rt_gp = self.row_title_param["gp"]
1498
+ rt_rot = self.row_title_param["rot"]
1499
+ pad_r = _title_padding_unit(rt_gp)
1500
+ rt_w = max_text_width(self.row_title, gp=rt_gp, rot=rt_rot) + unit_sum(pad_r)
1501
+ if rt_side == "left":
1502
+ layout_size["row_title_left_width"] = rt_w
1503
+ layout_index.append(_heatmap_layout_index("row_title_left"))
1504
+ else:
1505
+ layout_size["row_title_right_width"] = rt_w
1506
+ layout_index.append(_heatmap_layout_index("row_title_right"))
1507
+
1508
+ def _draw_row_titles() -> None:
1509
+ if len(self.row_title) == 1 and nr_slice > 1:
1510
+ self.draw_title(which="row", k=1)
1511
+ else:
1512
+ for kr in range(1, nr_slice + 1):
1513
+ self.draw_title(which="row", k=kr, y=slice_y[kr - 1], height=slice_height[kr - 1], just="top")
1514
+
1515
+ graphic_funs.append(_draw_row_titles)
1516
+
1517
+ # 4. Row Dendrogram
1518
+ if self.row_dend_param["show"] and any(d is not None and nobs(d) > 1 for d in self.row_dend_list):
1519
+ rd_side = self.row_dend_param["side"]
1520
+ rd_w = self.row_dend_param["width"]
1521
+ if rd_side == "left":
1522
+ layout_size["row_dend_left_width"] = rd_w
1523
+ layout_index.append(_heatmap_layout_index("row_dend_left"))
1524
+ else:
1525
+ layout_size["row_dend_right_width"] = rd_w
1526
+ layout_index.append(_heatmap_layout_index("row_dend_right"))
1527
+
1528
+ child_heights = [dend_heights(d) for d in self.row_dend_list if d is not None]
1529
+ max_child_h = max(child_heights) if child_heights else 0.0
1530
+ if self.row_dend_param["split_by_cutree"] and self.row_dend_slice is not None:
1531
+ row_dend_max_h = dend_heights(self.row_dend_slice)
1532
+ elif self.row_dend_slice is not None and self.row_dend_param["cluster_slices"]:
1533
+ row_dend_max_h = dend_heights(self.row_dend_slice) + max_child_h
1534
+ else:
1535
+ row_dend_max_h = max_child_h
1536
+ if row_dend_max_h <= 0:
1537
+ row_dend_max_h = 1.0
1538
+
1539
+ def _draw_row_dends() -> None:
1540
+ pad_u = as_unit(ht_opt.DENDROGRAM_PADDING, "mm")
1541
+ if rd_side == "left":
1542
+ pushViewport(Viewport(x=unit(0, "npc"), width=unit(1, "npc") - pad_u, just="left"))
1543
+ else:
1544
+ pushViewport(Viewport(x=pad_u, width=unit(1, "npc") - pad_u, just="left"))
1545
+ try:
1546
+ for kr in range(1, nr_slice + 1):
1547
+ self.draw_dend(which="row", k=kr, max_height=row_dend_max_h, y=slice_y[kr - 1], height=slice_height[kr - 1], just="top")
1548
+ if nr_slice > 1 and self.row_dend_param["cluster_slices"] and self.row_dend_slice is not None:
1549
+ pushViewport(Viewport(xscale=(0.0, float(row_dend_max_h)), yscale=(0.0, 1.0)))
1550
+ try:
1551
+ leaf_pos_units = []
1552
+ for kr in range(nr_slice):
1553
+ d_k = self.row_dend_list[kr]
1554
+ if d_k is not None and d_k.x is None:
1555
+ d_k = adjust_dend_by_x(d_k)
1556
+ p_k = float(d_k.x) / max(1, nobs(d_k)) if d_k is not None else 0.5
1557
+ leaf_pos_units.append(slice_y[kr] - slice_height[kr] * p_k)
1558
+ leaf_pos_u = unit_c(*leaf_pos_units)
1559
+ slice_d = self.row_dend_slice
1560
+ if not self.row_dend_param["split_by_cutree"]:
1561
+ slice_d = merge_dendrogram(slice_d, [d for d in self.row_dend_list if d is not None], only_parent=True)
1562
+ slice_d = adjust_dend_by_x(slice_d, leaf_pos_u)
1563
+ grid_dendrogram(slice_d, gp=self.row_dend_param["gp"], facing="right" if rd_side == "left" else "left")
1564
+ if not self.row_dend_param["split_by_cutree"] and self.heatmap_param["show_parent_dend_line"]:
1565
+ x_line = unit(row_dend_max_h - max_child_h, "native") - unit(0.5, "mm") if rd_side == "left" else unit(max_child_h, "native") + unit(0.5, "mm")
1566
+ grid_segments(x_line, unit(0.0, "npc"), x_line, unit(1.0, "npc"), gp=gpar(lty="dotted", col="#666666"))
1567
+ finally:
1568
+ popViewport()
1569
+ finally:
1570
+ popViewport()
1571
+
1572
+ graphic_funs.append(_draw_row_dends)
1573
+
1574
+ # 5. Column Dendrogram
1575
+ if self.column_dend_param["show"] and any(d is not None and nobs(d) > 1 for d in self.column_dend_list):
1576
+ cd_side = self.column_dend_param["side"]
1577
+ cd_h = self.column_dend_param["height"]
1578
+ if cd_side == "top":
1579
+ layout_size["column_dend_top_height"] = cd_h
1580
+ layout_index.append(_heatmap_layout_index("column_dend_top"))
1581
+ else:
1582
+ layout_size["column_dend_bottom_height"] = cd_h
1583
+ layout_index.append(_heatmap_layout_index("column_dend_bottom"))
1584
+
1585
+ child_heights_c = [dend_heights(d) for d in self.column_dend_list if d is not None]
1586
+ max_child_hc = max(child_heights_c) if child_heights_c else 0.0
1587
+ if self.column_dend_param["split_by_cutree"] and self.column_dend_slice is not None:
1588
+ col_dend_max_h = dend_heights(self.column_dend_slice)
1589
+ elif self.column_dend_slice is not None and self.column_dend_param["cluster_slices"]:
1590
+ col_dend_max_h = dend_heights(self.column_dend_slice) + max_child_hc
1591
+ else:
1592
+ col_dend_max_h = max_child_hc
1593
+ if col_dend_max_h <= 0:
1594
+ col_dend_max_h = 1.0
1595
+
1596
+ def _draw_col_dends() -> None:
1597
+ pad_u = as_unit(ht_opt.DENDROGRAM_PADDING, "mm")
1598
+ if cd_side == "top":
1599
+ pushViewport(Viewport(y=pad_u, height=unit(1, "npc") - pad_u, just="bottom"))
1600
+ else:
1601
+ pushViewport(Viewport(y=unit(0, "npc"), height=unit(1, "npc") - pad_u, just="bottom"))
1602
+ try:
1603
+ for kc in range(1, nc_slice + 1):
1604
+ self.draw_dend(which="column", k=kc, max_height=col_dend_max_h, x=slice_x[kc - 1], width=slice_width[kc - 1], just="left")
1605
+ if nc_slice > 1 and self.column_dend_param["cluster_slices"] and self.column_dend_slice is not None:
1606
+ pushViewport(Viewport(xscale=(0.0, 1.0), yscale=(0.0, float(col_dend_max_h))))
1607
+ try:
1608
+ leaf_pos_units = []
1609
+ for kc in range(nc_slice):
1610
+ d_k = self.column_dend_list[kc]
1611
+ if d_k is not None and d_k.x is None:
1612
+ d_k = adjust_dend_by_x(d_k)
1613
+ p_k = float(d_k.x) / max(1, nobs(d_k)) if d_k is not None else 0.5
1614
+ leaf_pos_units.append(slice_x[kc] + slice_width[kc] * p_k)
1615
+ leaf_pos_u = unit_c(*leaf_pos_units)
1616
+ slice_d = self.column_dend_slice
1617
+ if not self.column_dend_param["split_by_cutree"]:
1618
+ slice_d = merge_dendrogram(slice_d, [d for d in self.column_dend_list if d is not None], only_parent=True)
1619
+ slice_d = adjust_dend_by_x(slice_d, leaf_pos_u)
1620
+ grid_dendrogram(slice_d, gp=self.column_dend_param["gp"], facing="bottom" if cd_side == "top" else "top")
1621
+ if not self.column_dend_param["split_by_cutree"] and self.heatmap_param["show_parent_dend_line"]:
1622
+ y_line = unit(col_dend_max_h - max_child_hc, "native") - unit(0.5, "mm") if cd_side == "bottom" else unit(max_child_hc, "native") + unit(0.5, "mm")
1623
+ grid_segments(unit(0.0, "npc"), y_line, unit(1.0, "npc"), y_line, gp=gpar(lty="dotted", col="#666666"))
1624
+ finally:
1625
+ popViewport()
1626
+ finally:
1627
+ popViewport()
1628
+
1629
+ graphic_funs.append(_draw_col_dends)
1630
+
1631
+ # 6. Row Names
1632
+ if self.row_names_param["show"] and self.row_names_param["anno"] is not None:
1633
+ dim_pad_mm = convertWidth(as_unit(ht_opt.DIMNAME_PADDING, "mm"), "mm", valueOnly=True)
1634
+ rn_w_mm = convertWidth(self.row_names_param["anno"].width, "mm", valueOnly=True) + 2.0 * dim_pad_mm
1635
+ rn_max_mm = convertWidth(self.row_names_param["max_width"], "mm", valueOnly=True)
1636
+ rn_w_u = unit(min(rn_w_mm, rn_max_mm), "mm")
1637
+ if self.row_names_param["side"] == "left":
1638
+ layout_size["row_names_left_width"] = rn_w_u
1639
+ layout_index.append(_heatmap_layout_index("row_names_left"))
1640
+ else:
1641
+ layout_size["row_names_right_width"] = rn_w_u
1642
+ layout_index.append(_heatmap_layout_index("row_names_right"))
1643
+
1644
+ def _draw_row_names() -> None:
1645
+ pad_mm_u = as_unit(ht_opt.DIMNAME_PADDING, "mm")
1646
+ for kr in range(1, nr_slice + 1):
1647
+ self.draw_dimnames(which="row", k=kr, y=slice_y[kr - 1], height=slice_height[kr - 1], width=unit(1, "npc") - pad_mm_u * 2.0, just="top")
1648
+
1649
+ graphic_funs.append(_draw_row_names)
1650
+
1651
+ # 7. Column Names
1652
+ if self.column_names_param["show"] and self.column_names_param["anno"] is not None:
1653
+ dim_pad_mm = convertHeight(as_unit(ht_opt.DIMNAME_PADDING, "mm"), "mm", valueOnly=True)
1654
+ cn_h_mm = convertHeight(self.column_names_param["anno"].height, "mm", valueOnly=True) + 2.0 * dim_pad_mm
1655
+ cn_max_mm = convertHeight(self.column_names_param["max_height"], "mm", valueOnly=True)
1656
+ cn_h_u = unit(min(cn_h_mm, cn_max_mm), "mm")
1657
+ if self.column_names_param["side"] == "top":
1658
+ layout_size["column_names_top_height"] = cn_h_u
1659
+ layout_index.append(_heatmap_layout_index("column_names_top"))
1660
+ else:
1661
+ layout_size["column_names_bottom_height"] = cn_h_u
1662
+ layout_index.append(_heatmap_layout_index("column_names_bottom"))
1663
+
1664
+ def _draw_col_names() -> None:
1665
+ pad_mm_u = as_unit(ht_opt.DIMNAME_PADDING, "mm")
1666
+ for kc in range(1, nc_slice + 1):
1667
+ self.draw_dimnames(which="column", k=kc, x=slice_x[kc - 1], width=slice_width[kc - 1], height=unit(1, "npc") - pad_mm_u * 2.0, just="left")
1668
+
1669
+ graphic_funs.append(_draw_col_names)
1670
+
1671
+ # 8. Top / Bottom / Left / Right Annotations
1672
+ if self.top_annotation is not None and len(self.top_annotation) > 0:
1673
+ layout_size["column_anno_top_height"] = self.top_annotation.height + as_unit(ht_opt.COLUMN_ANNO_PADDING, "mm")
1674
+ layout_index.append(_heatmap_layout_index("column_anno_top"))
1675
+
1676
+ def _draw_top_anno() -> None:
1677
+ pad = as_unit(ht_opt.COLUMN_ANNO_PADDING, "mm")
1678
+ for kc in range(1, nc_slice + 1):
1679
+ self.draw_annotation("top", k=kc, x=slice_x[kc - 1], width=slice_width[kc - 1], y=pad, height=unit(1, "npc") - pad, just=("left", "bottom"))
1680
+
1681
+ graphic_funs.append(_draw_top_anno)
1682
+
1683
+ if self.bottom_annotation is not None and len(self.bottom_annotation) > 0:
1684
+ layout_size["column_anno_bottom_height"] = self.bottom_annotation.height + as_unit(ht_opt.COLUMN_ANNO_PADDING, "mm")
1685
+ layout_index.append(_heatmap_layout_index("column_anno_bottom"))
1686
+
1687
+ def _draw_bottom_anno() -> None:
1688
+ pad = as_unit(ht_opt.COLUMN_ANNO_PADDING, "mm")
1689
+ for kc in range(1, nc_slice + 1):
1690
+ self.draw_annotation("bottom", k=kc, x=slice_x[kc - 1], width=slice_width[kc - 1], y=unit(0, "npc"), height=unit(1, "npc") - pad, just=("left", "bottom"))
1691
+
1692
+ graphic_funs.append(_draw_bottom_anno)
1693
+
1694
+ if self.left_annotation is not None and len(self.left_annotation) > 0:
1695
+ layout_size["row_anno_left_width"] = self.left_annotation.width + as_unit(ht_opt.ROW_ANNO_PADDING, "mm")
1696
+ layout_index.append(_heatmap_layout_index("row_anno_left"))
1697
+
1698
+ def _draw_left_anno() -> None:
1699
+ pad = as_unit(ht_opt.ROW_ANNO_PADDING, "mm")
1700
+ for kr in range(1, nr_slice + 1):
1701
+ self.draw_annotation("left", k=kr, y=slice_y[kr - 1], height=slice_height[kr - 1], x=unit(0, "npc"), width=unit(1, "npc") - pad, just=("left", "top"))
1702
+
1703
+ graphic_funs.append(_draw_left_anno)
1704
+
1705
+ if self.right_annotation is not None and len(self.right_annotation) > 0:
1706
+ layout_size["row_anno_right_width"] = self.right_annotation.width + as_unit(ht_opt.ROW_ANNO_PADDING, "mm")
1707
+ layout_index.append(_heatmap_layout_index("row_anno_right"))
1708
+
1709
+ def _draw_right_anno() -> None:
1710
+ pad = as_unit(ht_opt.ROW_ANNO_PADDING, "mm")
1711
+ for kr in range(1, nr_slice + 1):
1712
+ self.draw_annotation("right", k=kr, y=slice_y[kr - 1], height=slice_height[kr - 1], x=pad, width=unit(1, "npc") - pad, just=("left", "top"))
1713
+
1714
+ graphic_funs.append(_draw_right_anno)
1715
+
1716
+ # 9. Resolve heatmap_width vs matrix_param["width"] and heatmap_height vs matrix_param["height"]
1717
+ fixed_w_mm = sum(convertWidth(layout_size[f"{c}_width"], "mm", valueOnly=True) for c in HEATMAP_LAYOUT_ROW_COMPONENTS if c != "heatmap_body")
1718
+ fixed_h_mm = sum(convertHeight(layout_size[f"{c}_height"], "mm", valueOnly=True) for c in HEATMAP_LAYOUT_COLUMN_COMPONENTS if c != "heatmap_body")
1719
+
1720
+ if is_abs_unit(self.heatmap_param["width"]):
1721
+ tot_w_mm = convertWidth(self.heatmap_param["width"], "mm", valueOnly=True)
1722
+ body_w_mm = tot_w_mm - fixed_w_mm
1723
+ if body_w_mm <= 0:
1724
+ raise ValueError("Computed heatmap body width is non-positive; `heatmap_width` is too small for titles/dends/names/annotations.")
1725
+ self.matrix_param["width"] = unit(body_w_mm, "mm")
1726
+ elif is_abs_unit(self.matrix_param["width"]):
1727
+ body_w_mm = convertWidth(self.matrix_param["width"], "mm", valueOnly=True)
1728
+ self.heatmap_param["width"] = unit(fixed_w_mm + body_w_mm, "mm")
1729
+ else:
1730
+ self.heatmap_param["width"] = unit(1.0, "npc")
1731
+
1732
+ if is_abs_unit(self.heatmap_param["height"]):
1733
+ tot_h_mm = convertHeight(self.heatmap_param["height"], "mm", valueOnly=True)
1734
+ body_h_mm = tot_h_mm - fixed_h_mm
1735
+ if body_h_mm <= 0:
1736
+ raise ValueError("Computed heatmap body height is non-positive; `heatmap_height` is too small for titles/dends/names/annotations.")
1737
+ self.matrix_param["height"] = unit(body_h_mm, "mm")
1738
+ elif is_abs_unit(self.matrix_param["height"]):
1739
+ body_h_mm = convertHeight(self.matrix_param["height"], "mm", valueOnly=True)
1740
+ self.heatmap_param["height"] = unit(fixed_h_mm + body_h_mm, "mm")
1741
+ else:
1742
+ self.heatmap_param["height"] = unit(1.0, "npc")
1743
+
1744
+ self.layout["layout_index"] = layout_index
1745
+ self.layout["graphic_fun_list"] = graphic_funs
1746
+ self.layout["initialized"] = True
1747
+ return self
1748
+
1749
+ def component_widths_mm(self) -> list[float | None]:
1750
+ """Return widths of the 9 row components in mm (`None` means flexible/npc body)."""
1751
+ ls = self.layout["layout_size"]
1752
+ out: list[float | None] = []
1753
+ for c in HEATMAP_LAYOUT_ROW_COMPONENTS:
1754
+ if c == "heatmap_body":
1755
+ bw = self.matrix_param["width"]
1756
+ out.append(convertWidth(bw, "mm", valueOnly=True) if is_abs_unit(bw) else None)
1757
+ else:
1758
+ out.append(convertWidth(ls[f"{c}_width"], "mm", valueOnly=True))
1759
+ return out
1760
+
1761
+ def component_heights_mm(self) -> list[float | None]:
1762
+ """Return heights of the 9 column components in mm (`None` means flexible/npc body)."""
1763
+ ls = self.layout["layout_size"]
1764
+ out: list[float | None] = []
1765
+ for c in HEATMAP_LAYOUT_COLUMN_COMPONENTS:
1766
+ if c == "heatmap_body":
1767
+ bh = self.matrix_param["height"]
1768
+ out.append(convertHeight(bh, "mm", valueOnly=True) if is_abs_unit(bh) else None)
1769
+ else:
1770
+ out.append(convertHeight(ls[f"{c}_height"], "mm", valueOnly=True))
1771
+ return out
1772
+
1773
+ # ---- Component Drawing ----
1774
+
1775
+ def draw_heatmap_body(self, kr: int = 1, kc: int = 1, **vp_kwargs: Any) -> None:
1776
+ r_idx = self.row_order_list[kr - 1]
1777
+ c_idx = self.column_order_list[kc - 1]
1778
+ nr_s = len(r_idx)
1779
+ nc_s = len(c_idx)
1780
+ vp_name = f"{self.name}_heatmap_body_{kr}_{kc}"
1781
+
1782
+ pushViewport(Viewport(name=vp_name, xscale=(0.0, float(max(1, nc_s))), yscale=(0.0, float(max(1, nr_s))), **vp_kwargs))
1783
+ try:
1784
+ if nr_s > 0 and nc_s > 0:
1785
+ submat = self.matrix[np.ix_(r_idx, c_idx)]
1786
+ rect_gp = self.matrix_param["rect_gp"]
1787
+ rect_type = rect_gp.get("type", None)
1788
+ if self.matrix_color_mapping is not None and self._oncoprint_env is None and (
1789
+ rect_type != "none" or self.matrix_param["layer_fun"] is not None or self.matrix_param["cell_fun"] is not None
1790
+ ):
1791
+ col_mat = self.matrix_color_mapping.map_to_colors(submat)
1792
+ else:
1793
+ col_mat = np.full((nr_s, nc_s), "#FFFFFFFF", dtype=object)
1794
+
1795
+ # Vectorized cell coordinates in npc (row 0 at top -> y = (nr_s - r - 0.5)/nr_s)
1796
+ if rect_type != "none":
1797
+ if self.heatmap_param["use_raster"]:
1798
+ # Downsample if raster_resize_mat is set and matrix is numeric
1799
+ resize_opt = self.heatmap_param["raster_resize_mat"]
1800
+ rgba_img = np.zeros((nr_s, nc_s, 4), dtype=float)
1801
+ if resize_opt and self._is_numeric and (nr_s > 400 or nc_s > 400):
1802
+ fn = np.nanmean if resize_opt is True else resize_opt
1803
+ tgt_r = min(nr_s, 400)
1804
+ tgt_c = min(nc_s, 400)
1805
+ r_bins = np.array_split(np.arange(nr_s), tgt_r)
1806
+ c_bins = np.array_split(np.arange(nc_s), tgt_c)
1807
+ sub_small = np.empty((tgt_r, tgt_c), dtype=float)
1808
+ for ri, rb in enumerate(r_bins):
1809
+ for ci, cb in enumerate(c_bins):
1810
+ with np.errstate(all="ignore"):
1811
+ sub_small[ri, ci] = fn(submat[np.ix_(rb, cb)])
1812
+ col_small = self.matrix_color_mapping.map_to_colors(sub_small)
1813
+ rgba_img = np.zeros((tgt_r, tgt_c, 4), dtype=float)
1814
+ for ri in range(tgt_r):
1815
+ for ci in range(tgt_c):
1816
+ rgba_img[ri, ci] = to_rgba_tuple(col_small[ri, ci])
1817
+ else:
1818
+ for ri in range(nr_s):
1819
+ for ci in range(nc_s):
1820
+ rgba_img[ri, ci] = to_rgba_tuple(col_mat[ri, ci])
1821
+ grid_raster(rgba_img, x=0.5, y=0.5, width=1.0, height=1.0, interpolate=False)
1822
+ else:
1823
+ # Column-major flattening to align with layer_fun & restore_matrix
1824
+ x_vec = np.repeat((np.arange(nc_s, dtype=float) + 0.5) / nc_s, nr_s)
1825
+ y_vec = np.tile((nr_s - np.arange(nr_s, dtype=float) - 0.5) / nr_s, nc_s)
1826
+ fill_vec = [col_mat[ri, ci] for ci in range(nc_s) for ri in range(nr_s)]
1827
+ gp_cells = check_gp(rect_gp)
1828
+ gp_cells["fill"] = fill_vec
1829
+ grid_rect(
1830
+ x=unit(x_vec, "npc"),
1831
+ y=unit(y_vec, "npc"),
1832
+ width=unit(1.0 / nc_s, "npc"),
1833
+ height=unit(1.0 / nr_s, "npc"),
1834
+ gp=gp_cells,
1835
+ )
1836
+
1837
+ # layer_fun (vectorized)
1838
+ layer_fun = self.matrix_param["layer_fun"]
1839
+ if layer_fun is not None:
1840
+ j_vec = np.repeat(np.asarray(c_idx, dtype=int), nr_s)
1841
+ i_vec = np.tile(np.asarray(r_idx, dtype=int), nc_s)
1842
+ x_u = unit(np.repeat((np.arange(nc_s, dtype=float) + 0.5) / nc_s, nr_s), "npc")
1843
+ y_u = unit(np.tile((nr_s - np.arange(nr_s, dtype=float) - 0.5) / nr_s, nc_s), "npc")
1844
+ w_u = unit(np.full(nr_s * nc_s, 1.0 / nc_s), "npc")
1845
+ h_u = unit(np.full(nr_s * nc_s, 1.0 / nr_s), "npc")
1846
+ fill_vec = np.array([col_mat[ri, ci] for ci in range(nc_s) for ri in range(nr_s)], dtype=object)
1847
+
1848
+ sig = inspect.signature(layer_fun)
1849
+ pos_params = [p for p in sig.parameters.values() if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
1850
+ has_var = any(p.kind == p.VAR_POSITIONAL for p in sig.parameters.values())
1851
+ if len(pos_params) >= 9:
1852
+ layer_fun(j_vec, i_vec, x_u, y_u, w_u, h_u, fill_vec, kr, kc)
1853
+ elif has_var:
1854
+ # Pass 7 or check? In R 9 args vs 7 args: default 7 unless 9 requested
1855
+ layer_fun(j_vec, i_vec, x_u, y_u, w_u, h_u, fill_vec)
1856
+ else:
1857
+ layer_fun(j_vec, i_vec, x_u, y_u, w_u, h_u, fill_vec)
1858
+
1859
+ # cell_fun (per cell)
1860
+ cell_fun = self.matrix_param["cell_fun"]
1861
+ if cell_fun is not None:
1862
+ w_cell = unit(1.0 / nc_s, "npc")
1863
+ h_cell = unit(1.0 / nr_s, "npc")
1864
+ for ri, orig_i in enumerate(r_idx):
1865
+ y_cell = unit((nr_s - ri - 0.5) / nr_s, "npc")
1866
+ for ci, orig_j in enumerate(c_idx):
1867
+ x_cell = unit((ci + 0.5) / nc_s, "npc")
1868
+ cell_fun(int(orig_j), int(orig_i), x_cell, y_cell, w_cell, h_cell, col_mat[ri, ci])
1869
+
1870
+ # Slice border
1871
+ border = self.matrix_param["border"]
1872
+ if border is True or (isinstance(border, str) and border.lower() not in ("", "na", "none")):
1873
+ bgp = dict(self.matrix_param["border_gp"])
1874
+ bgp["fill"] = "transparent"
1875
+ if isinstance(border, str):
1876
+ bgp["col"] = border
1877
+ grid_rect(gp=bgp)
1878
+ finally:
1879
+ popViewport()
1880
+
1881
+ def draw_dend(self, which: str = "row", k: int = 1, max_height: float | None = None, **vp_kwargs: Any) -> None:
1882
+ if which == "row":
1883
+ side = self.row_dend_param["side"]
1884
+ dend = self.row_dend_list[k - 1]
1885
+ gp = self.row_dend_param["gp"]
1886
+ else:
1887
+ side = self.column_dend_param["side"]
1888
+ dend = self.column_dend_list[k - 1]
1889
+ gp = self.column_dend_param["gp"]
1890
+
1891
+ if dend is None or nobs(dend) <= 1:
1892
+ return
1893
+ if max_height is None:
1894
+ max_height = dend_heights(dend)
1895
+ if max_height <= 0:
1896
+ max_height = 1.0
1897
+
1898
+ nb = float(nobs(dend))
1899
+ if side in ("left", "right"):
1900
+ xscale = (0.0, float(max_height))
1901
+ yscale = (0.0, nb)
1902
+ vp_name = f"{self.name}_dend_row_{k}"
1903
+ else:
1904
+ xscale = (0.0, nb)
1905
+ yscale = (0.0, float(max_height))
1906
+ vp_name = f"{self.name}_dend_column_{k}"
1907
+
1908
+ pushViewport(Viewport(**vp_kwargs))
1909
+ pushViewport(Viewport(name=vp_name, xscale=xscale, yscale=yscale, width=unit(1, "npc"), height=unit(1, "npc")))
1910
+ try:
1911
+ facing_map = {"left": "right", "right": "left", "top": "bottom", "bottom": "top"}
1912
+ order_mode = "reverse" if side in ("left", "right") else "normal"
1913
+ grid_dendrogram(dend, gp=gp, facing=facing_map[side], order=order_mode)
1914
+ finally:
1915
+ popViewport(2)
1916
+
1917
+ def draw_dimnames(self, which: str = "row", k: int = 1, **vp_kwargs: Any) -> None:
1918
+ if which == "row":
1919
+ anno = self.row_names_param["anno"]
1920
+ ind = self.row_order_list[k - 1]
1921
+ else:
1922
+ anno = self.column_names_param["anno"]
1923
+ ind = self.column_order_list[k - 1]
1924
+ if anno is None or not ind:
1925
+ return
1926
+
1927
+ vp_name = f"{self.name}_{which}_names_{k}"
1928
+ pushViewport(Viewport(name=vp_name, **vp_kwargs))
1929
+ try:
1930
+ anno.draw(ind, k=k, n=len(self.row_order_list if which == "row" else self.column_order_list))
1931
+ finally:
1932
+ popViewport()
1933
+
1934
+ def draw_title(self, which: str = "row", k: int = 1, **vp_kwargs: Any) -> None:
1935
+ if which == "row":
1936
+ side = self.row_title_param["side"]
1937
+ gp = subset_gp(self.row_title_param["gp"], k - 1)
1938
+ title = self.row_title[k - 1]
1939
+ rot = self.row_title_param["rot"]
1940
+ just = self.row_title_param["just"]
1941
+ vp_name = f"{self.name}_row_title_{k}"
1942
+ else:
1943
+ side = self.column_title_param["side"]
1944
+ gp = subset_gp(self.column_title_param["gp"], k - 1)
1945
+ title = self.column_title[k - 1]
1946
+ rot = self.column_title_param["rot"]
1947
+ just = self.column_title_param["just"]
1948
+ vp_name = f"{self.name}_column_title_{k}"
1949
+
1950
+ pad = _title_padding_unit(gp)
1951
+ pushViewport(Viewport(name=vp_name, clip=False, **vp_kwargs))
1952
+ try:
1953
+ gp2 = dict(gp)
1954
+ if "border" in gp2:
1955
+ gp2["col"] = gp2["border"]
1956
+ if "border" in gp or "fill" in gp:
1957
+ grid_rect(gp=gp2)
1958
+ if which == "row":
1959
+ if side == "left":
1960
+ grid_text(title, x=unit(1, "npc") - pad[0], y=unit(0.5, "npc"), rot=rot, just=just, gp=gp)
1961
+ else:
1962
+ grid_text(title, x=pad[0], y=unit(0.5, "npc"), rot=rot, just=just, gp=gp)
1963
+ else:
1964
+ if side == "top":
1965
+ grid_text(title, x=unit(0.5, "npc"), y=pad[0], rot=rot, just=just, gp=gp)
1966
+ else:
1967
+ grid_text(title, x=unit(0.5, "npc"), y=unit(1, "npc") - pad[0], rot=rot, just=just, gp=gp)
1968
+ finally:
1969
+ popViewport()
1970
+
1971
+ def draw_annotation(self, which: str = "top", k: int = 1, **vp_kwargs: Any) -> None:
1972
+ annotation = getattr(self, f"{which}_annotation")
1973
+ if annotation is None or len(annotation) == 0:
1974
+ return
1975
+ if which in ("top", "bottom"):
1976
+ index = self.column_order_list[k - 1]
1977
+ n = len(self.column_order_list)
1978
+ else:
1979
+ index = self.row_order_list[k - 1]
1980
+ n = len(self.row_order_list)
1981
+
1982
+ # Build anno_mark_param when multi-slice has anno_mark / anno_zoom
1983
+ anno_mark_param: dict[str, Any] = {}
1984
+ anno_types = [sa.fun.fun_name for sa in annotation.anno_list.values()]
1985
+ if any(t in ("anno_mark", "anno_zoom") for t in anno_types):
1986
+ if which in ("left", "right"):
1987
+ slice_y = self.layout["slice"]["y"]
1988
+ slice_h = self.layout["slice"]["height"]
1989
+ ro_lt = self.row_order_list
1990
+ if len(ro_lt) > 1:
1991
+ pos_units = []
1992
+ for i_s, idx_s in enumerate(ro_lt):
1993
+ m_s = max(1, len(idx_s))
1994
+ rel = (np.arange(m_s, dtype=float) + 0.5) / m_s
1995
+ for r_f in rel:
1996
+ pos_units.append(slice_y[i_s] - slice_h[i_s] * r_f)
1997
+ anno_mark_param[".scale"] = (0.0, 1.0)
1998
+ anno_mark_param[".pos"] = convertHeight(unit_c(*pos_units), "npc", valueOnly=True) if False else None
1999
+ # Convert inside vp once pushed or store Unit list!
2000
+ anno_mark_param["_pos_unit"] = unit_c(*pos_units)
2001
+ anno_mark_param["index"] = [idx for sl in ro_lt for idx in sl]
2002
+ else:
2003
+ slice_x = self.layout["slice"]["x"]
2004
+ slice_w = self.layout["slice"]["width"]
2005
+ co_lt = self.column_order_list
2006
+ if len(co_lt) > 1:
2007
+ pos_units = []
2008
+ for i_s, idx_s in enumerate(co_lt):
2009
+ m_s = max(1, len(idx_s))
2010
+ rel = (np.arange(m_s, dtype=float) + 0.5) / m_s
2011
+ for c_f in rel:
2012
+ pos_units.append(slice_x[i_s] + slice_w[i_s] * c_f)
2013
+ anno_mark_param[".scale"] = (0.0, 1.0)
2014
+ anno_mark_param["_pos_unit"] = unit_c(*pos_units)
2015
+ anno_mark_param["index"] = [idx for sl in co_lt for idx in sl]
2016
+
2017
+ prev_ht = _ENV.current_heatmap
2018
+ _ENV.current_heatmap = self
2019
+ try:
2020
+ if "_pos_unit" in anno_mark_param:
2021
+ u_p = anno_mark_param.pop("_pos_unit")
2022
+ from .grid import current_viewport
2023
+ full_vp = current_viewport()
2024
+ if which in ("left", "right"):
2025
+ anno_mark_param[".pos"] = u_p.to_mm("y", full_vp, pos_mode=True) / max(1e-9, full_vp.height_mm)
2026
+ anno_mark_param["vp_height"] = unit(full_vp.height_mm / 10.0, "cm")
2027
+ anno_mark_param["vp_width"] = unit(1.0, "npc")
2028
+ anno_mark_param["vp_just"] = "top"
2029
+ anno_mark_param["vp_x"] = unit(0.5, "npc")
2030
+ anno_mark_param["vp_y"] = unit(1.0, "npc")
2031
+ else:
2032
+ anno_mark_param[".pos"] = u_p.to_mm("x", full_vp, pos_mode=True) / max(1e-9, full_vp.width_mm)
2033
+ anno_mark_param["vp_height"] = unit(1.0, "npc")
2034
+ anno_mark_param["vp_width"] = unit(full_vp.width_mm / 10.0, "cm")
2035
+ anno_mark_param["vp_just"] = "left"
2036
+ anno_mark_param["vp_x"] = unit(0.0, "npc")
2037
+ anno_mark_param["vp_y"] = unit(0.5, "npc")
2038
+ pushViewport(Viewport(**vp_kwargs))
2039
+ try:
2040
+ annotation.draw(index=index, k=k, n=n, anno_mark_param=anno_mark_param)
2041
+ finally:
2042
+ popViewport()
2043
+ finally:
2044
+ _ENV.current_heatmap = prev_ht
2045
+
2046
+ def draw_in_viewport(self) -> None:
2047
+ """Render the 9x9 layout grid of this prepared Heatmap in the current viewport."""
2048
+ if not self.layout["initialized"]:
2049
+ self.prepare()
2050
+
2051
+ from .grid import current_viewport
2052
+
2053
+ parent_vp = current_viewport()
2054
+ col_widths_mm = self.component_widths_mm()
2055
+ row_heights_mm = self.component_heights_mm()
2056
+
2057
+ fixed_w = sum(w for w in col_widths_mm if w is not None)
2058
+ fixed_h = sum(h for h in row_heights_mm if h is not None)
2059
+ rem_w = max(0.0, parent_vp.width_mm - fixed_w)
2060
+ rem_h = max(0.0, parent_vp.height_mm - fixed_h)
2061
+
2062
+ final_w = [rem_w if w is None else w for w in col_widths_mm]
2063
+ final_h = [rem_h if h is None else h for h in row_heights_mm]
2064
+
2065
+ # Compute cell boxes inside parent_vp (row 0 is top, col 0 is left)
2066
+ x_starts = [0.0] * 9
2067
+ cur_x = 0.0
2068
+ for c in range(9):
2069
+ x_starts[c] = cur_x
2070
+ cur_x += final_w[c]
2071
+
2072
+ y_tops = [0.0] * 9
2073
+ cur_y = sum(final_h)
2074
+ for r in range(9):
2075
+ y_tops[r] = cur_y
2076
+ cur_y -= final_h[r]
2077
+
2078
+ for (r_idx, c_idx), gfun in zip(self.layout["layout_index"], self.layout["graphic_fun_list"]):
2079
+ w_cell = final_w[c_idx]
2080
+ h_cell = final_h[r_idx]
2081
+ pushViewport(
2082
+ Viewport(
2083
+ x=unit(x_starts[c_idx], "mm"),
2084
+ y=unit(y_tops[r_idx], "mm"),
2085
+ width=unit(w_cell, "mm"),
2086
+ height=unit(h_cell, "mm"),
2087
+ just=("left", "top"),
2088
+ )
2089
+ )
2090
+ try:
2091
+ gfun()
2092
+ finally:
2093
+ popViewport()
2094
+
2095
+ # ---- Subsetting ----
2096
+
2097
+ def __getitem__(self, key: Any) -> "Heatmap":
2098
+ if self.layout["initialized"]:
2099
+ raise RuntimeError("Subsetting is only allowed on a Heatmap before layout initialization.")
2100
+ if isinstance(key, tuple):
2101
+ if len(key) != 2:
2102
+ raise IndexError("Heatmap expects 1D (rows) or 2D (rows, cols) indexing.")
2103
+ i_key, j_key = key
2104
+ else:
2105
+ i_key, j_key = key, slice(None)
2106
+
2107
+ cp = self.copy_all()
2108
+ if not (isinstance(i_key, slice) and i_key == slice(None)):
2109
+ cp = _subset_heatmap_rows(cp, i_key)
2110
+ if not (isinstance(j_key, slice) and j_key == slice(None)):
2111
+ cp = _subset_heatmap_cols(cp, j_key)
2112
+ return cp
2113
+
2114
+ # ---- High-level Draw ----
2115
+
2116
+ def draw(self, **kwargs: Any) -> Any:
2117
+ from .heatmap_list import HeatmapList
2118
+ hl = HeatmapList([self], direction="horizontal")
2119
+ return hl.draw(**kwargs)
2120
+
2121
+ def show(self) -> Any:
2122
+ return self.draw()
2123
+
2124
+ def summary(self) -> str:
2125
+ lines = [
2126
+ f"A Heatmap object: {self.name}",
2127
+ f" dimension: {self.nrow} x {self.ncol}",
2128
+ f" color mapping: {self.matrix_color_mapping.type if self.matrix_color_mapping else 'none'}",
2129
+ f" cluster rows: {self.row_dend_param['cluster']}",
2130
+ f" cluster columns: {self.column_dend_param['cluster']}",
2131
+ ]
2132
+ txt = "\n".join(lines)
2133
+ print(txt)
2134
+ return txt
2135
+
2136
+ def _repr_png_(self) -> bytes:
2137
+ import io
2138
+ import matplotlib.pyplot as plt
2139
+ dev = self.draw(show=False)
2140
+ buf = io.BytesIO()
2141
+ dev._device.fig.savefig(buf, format="png", dpi=120)
2142
+ plt.close(dev._device.fig)
2143
+ return buf.getvalue()
2144
+
2145
+ def __repr__(self) -> str:
2146
+ return f"Heatmap(name={self.name!r}, shape=({self.nrow}, {self.ncol}))"
2147
+
2148
+
2149
+ def _resolve_index_list(idx_spec: Any, n: int, names_list: list[str] | None) -> list[int]:
2150
+ if isinstance(idx_spec, slice):
2151
+ return list(range(*idx_spec.indices(n)))
2152
+ if isinstance(idx_spec, (int, np.integer)):
2153
+ i = int(idx_spec)
2154
+ if i < 0:
2155
+ i += n
2156
+ if i < 0 or i >= n:
2157
+ raise IndexError(f"Index {idx_spec} out of range for length {n}.")
2158
+ return [i]
2159
+ if isinstance(idx_spec, str):
2160
+ if names_list is None:
2161
+ raise KeyError("Cannot subset by name when names are absent.")
2162
+ return [names_list.index(idx_spec)]
2163
+ seq = list(idx_spec)
2164
+ if seq and all(isinstance(x, (bool, np.bool_)) for x in seq):
2165
+ if len(seq) != n:
2166
+ raise IndexError(f"Boolean mask length ({len(seq)}) must equal {n}.")
2167
+ return [i for i, fl in enumerate(seq) if fl]
2168
+ if seq and all(isinstance(x, str) for x in seq):
2169
+ if names_list is None:
2170
+ raise KeyError("Cannot subset by name when names are absent.")
2171
+ lookup = {nm: i for i, nm in enumerate(names_list)}
2172
+ return [lookup[s] for s in seq]
2173
+ return [int(x) + (n if int(x) < 0 else 0) for x in seq]
2174
+
2175
+
2176
+ def _subset_heatmap_rows(ht: Heatmap, i_spec: Any) -> Heatmap:
2177
+ if ht.row_dend_param["obj"] is not None:
2178
+ raise ValueError("Cannot subset rows when `cluster_rows` is an explicit Dendrogram/Hclust.")
2179
+ ind = _resolve_index_list(i_spec, ht.nrow, ht._rownames)
2180
+ ind_set = set(ind)
2181
+ ht.matrix = ht.matrix[ind, :]
2182
+ if ht._rownames is not None:
2183
+ ht._rownames = [ht._rownames[i] for i in ind]
2184
+ if ht.row_names_param["labels"] is not None:
2185
+ lbl = ht.row_names_param["labels"]
2186
+ ht.row_names_param["labels"] = lbl[ind] if isinstance(lbl, GridText) else [lbl[i] for i in ind]
2187
+ ht.row_names_param["anno"] = ht.row_names_param["anno"][ind]
2188
+ ht.row_names_param["gp"] = subset_gp(ht.row_names_param["gp"], ind)
2189
+ # Remap manual row_order preserving relative positions
2190
+ pos_map = {old_i: new_i for new_i, old_i in enumerate(ind)}
2191
+ kept = [pos_map[old_i] for old_i in ht.row_order if old_i in ind_set]
2192
+ ht.row_order = kept if len(kept) == len(ind) else list(range(len(ind)))
2193
+ ht.row_order_list = [list(ht.row_order)]
2194
+ if ht.matrix_param["row_split"] is not None and not isinstance(ht.matrix_param["row_split"], (int, np.integer)):
2195
+ rs = ht.matrix_param["row_split"]
2196
+ if isinstance(rs, pd.DataFrame):
2197
+ ht.matrix_param["row_split"] = rs.iloc[ind].reset_index(drop=True)
2198
+ else:
2199
+ ht.matrix_param["row_split"] = [rs[i] for i in ind]
2200
+ if isinstance(ht.row_dend_param["reorder"], (list, tuple, np.ndarray, pd.Series)):
2201
+ ht.row_dend_param["reorder"] = [ht.row_dend_param["reorder"][i] for i in ind]
2202
+ if ht.left_annotation is not None:
2203
+ ht.left_annotation = ht.left_annotation[ind]
2204
+ if ht.right_annotation is not None:
2205
+ ht.right_annotation = ht.right_annotation[ind]
2206
+ if ht.nrow <= 1:
2207
+ ht.row_dend_param["cluster"] = False
2208
+ ht.row_dend_param["show"] = False
2209
+ return ht
2210
+
2211
+
2212
+ def _subset_heatmap_cols(ht: Heatmap, j_spec: Any) -> Heatmap:
2213
+ if ht.column_dend_param["obj"] is not None:
2214
+ raise ValueError("Cannot subset columns when `cluster_columns` is an explicit Dendrogram/Hclust.")
2215
+ ind = _resolve_index_list(j_spec, ht.ncol, ht._colnames)
2216
+ ind_set = set(ind)
2217
+ ht.matrix = ht.matrix[:, ind]
2218
+ if ht._colnames is not None:
2219
+ ht._colnames = [ht._colnames[j] for j in ind]
2220
+ if ht.column_names_param["labels"] is not None:
2221
+ lbl = ht.column_names_param["labels"]
2222
+ ht.column_names_param["labels"] = lbl[ind] if isinstance(lbl, GridText) else [lbl[j] for j in ind]
2223
+ ht.column_names_param["anno"] = ht.column_names_param["anno"][ind]
2224
+ ht.column_names_param["gp"] = subset_gp(ht.column_names_param["gp"], ind)
2225
+ pos_map = {old_j: new_j for new_j, old_j in enumerate(ind)}
2226
+ kept = [pos_map[old_j] for old_j in ht.column_order if old_j in ind_set]
2227
+ ht.column_order = kept if len(kept) == len(ind) else list(range(len(ind)))
2228
+ ht.column_order_list = [list(ht.column_order)]
2229
+ if ht.matrix_param["column_split"] is not None and not isinstance(ht.matrix_param["column_split"], (int, np.integer)):
2230
+ cs = ht.matrix_param["column_split"]
2231
+ if isinstance(cs, pd.DataFrame):
2232
+ ht.matrix_param["column_split"] = cs.iloc[ind].reset_index(drop=True)
2233
+ else:
2234
+ ht.matrix_param["column_split"] = [cs[j] for j in ind]
2235
+ if isinstance(ht.column_dend_param["reorder"], (list, tuple, np.ndarray, pd.Series)):
2236
+ ht.column_dend_param["reorder"] = [ht.column_dend_param["reorder"][j] for j in ind]
2237
+ if ht.top_annotation is not None:
2238
+ ht.top_annotation = ht.top_annotation[ind]
2239
+ if ht.bottom_annotation is not None:
2240
+ ht.bottom_annotation = ht.bottom_annotation[ind]
2241
+ if ht.ncol <= 1:
2242
+ ht.column_dend_param["cluster"] = False
2243
+ ht.column_dend_param["show"] = False
2244
+ return ht