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,1569 @@
1
+ """HeatmapList orchestration, multi-heatmap alignment, legend packing, and 7x7 canvas layout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from typing import Any, Callable, Sequence
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from ._base import AdditiveUnit
13
+ from ._options import GLOBAL_PADDING, _ENV, ht_opt
14
+ from .annotations import AnnotationFunction, HeatmapAnnotation, c_HeatmapAnnotation
15
+ from .colors import ColorMapping, c_ColorMapping
16
+ from .dendrogram import Dendrogram
17
+ from .grid import (
18
+ Grob,
19
+ Viewport,
20
+ current_device,
21
+ grid_newpage,
22
+ grid_rect,
23
+ grid_text,
24
+ max_text_height,
25
+ max_text_width,
26
+ popViewport,
27
+ pushViewport,
28
+ )
29
+ from .heatmap import (
30
+ HEATMAP_LAYOUT_COLUMN_COMPONENTS,
31
+ HEATMAP_LAYOUT_ROW_COMPONENTS,
32
+ Heatmap,
33
+ _calc_slice_layout,
34
+ _get_text_just,
35
+ _normalize_side,
36
+ _normalize_title_list,
37
+ _subset_heatmap_cols,
38
+ _subset_heatmap_rows,
39
+ _title_padding_unit,
40
+ )
41
+ from .legend import Legends, packLegend
42
+ from .units import (
43
+ Unit,
44
+ as_unit,
45
+ check_gp,
46
+ convertHeight,
47
+ convertWidth,
48
+ gpar,
49
+ is_abs_unit,
50
+ unit,
51
+ unit_c,
52
+ unit_sum,
53
+ )
54
+
55
+
56
+ HEATMAP_LIST_COLUMN_COMPONENTS = (
57
+ "annotation_legend_top",
58
+ "heatmap_legend_top",
59
+ "column_title_top",
60
+ "heatmap_list",
61
+ "column_title_bottom",
62
+ "heatmap_legend_bottom",
63
+ "annotation_legend_bottom",
64
+ )
65
+
66
+ HEATMAP_LIST_ROW_COMPONENTS = (
67
+ "annotation_legend_left",
68
+ "heatmap_legend_left",
69
+ "row_title_left",
70
+ "heatmap_list",
71
+ "row_title_right",
72
+ "heatmap_legend_right",
73
+ "annotation_legend_right",
74
+ )
75
+
76
+
77
+ def _normalize_ht_gap(ht_gap: Any, n_ht: int) -> Unit:
78
+ gap_u = unit(2, "mm") if ht_gap is None else as_unit(ht_gap, "mm")
79
+ vals = gap_u.to_mm("x")
80
+ if n_ht <= 1:
81
+ return unit([0.0], "mm")
82
+ out = [float(vals[i % len(vals)]) for i in range(n_ht - 1)]
83
+ return unit(out, "mm")
84
+
85
+
86
+ def _normalize_padding(padding: Any) -> list[float]:
87
+ """Return `[bottom, left, top, right]` padding in mm."""
88
+ if padding is None:
89
+ raw = ht_opt.PAGE_PADDING if hasattr(ht_opt, "PAGE_PADDING") and ht_opt.PAGE_PADDING is not None else GLOBAL_PADDING
90
+ else:
91
+ raw = padding
92
+ u = as_unit(raw, "mm")
93
+ vals = [float(v) for v in u.to_mm("x")]
94
+ if len(vals) == 1:
95
+ return vals * 4
96
+ if len(vals) == 2:
97
+ return [vals[0], vals[1], vals[0], vals[1]]
98
+ if len(vals) == 4:
99
+ return vals
100
+ raise ValueError("`padding` must have length 1, 2, or 4.")
101
+
102
+
103
+ def add_heatmap(object: Any, x: Any, direction: str = "horizontal") -> "HeatmapList":
104
+ """Concatenate Heatmaps, HeatmapAnnotations, or HeatmapLists horizontally (`+`) or vertically (`%v%`)."""
105
+ direction = _normalize_side(direction, ("horizontal", "vertical"), "direction")
106
+
107
+ if object is None and x is None:
108
+ return HeatmapList([], direction=direction)
109
+ if object is None:
110
+ if isinstance(x, HeatmapList):
111
+ cp = copy.copy(x)
112
+ return cp
113
+ return add_heatmap(HeatmapList([], direction=direction), x, direction=direction)
114
+ if x is None:
115
+ if isinstance(object, HeatmapList):
116
+ return copy.copy(object)
117
+ return add_heatmap(HeatmapList([], direction=direction), object, direction=direction)
118
+
119
+ # Coerce left object into a HeatmapList
120
+ if isinstance(object, HeatmapList):
121
+ ht_list = copy.copy(object)
122
+ ht_list.ht_list = list(object.ht_list)
123
+ ht_list.ht_list_param = copy.deepcopy(object.ht_list_param)
124
+ ht_list.layout = copy.deepcopy(object.layout)
125
+ if ht_list.ht_list and ht_list.direction != direction:
126
+ raise ValueError(
127
+ f"Cannot concatenate {direction!r} item onto a {ht_list.direction!r} HeatmapList. "
128
+ "Wrap the first group explicitly or keep directions consistent."
129
+ )
130
+ ht_list.direction = direction
131
+ elif isinstance(object, (Heatmap, HeatmapAnnotation)):
132
+ if isinstance(object, HeatmapAnnotation):
133
+ expected = "row" if direction == "horizontal" else "column"
134
+ if object.which != expected:
135
+ raise ValueError(
136
+ f"Cannot concatenate `{object.which}` HeatmapAnnotation {direction}ly; "
137
+ f"expected `which={expected!r}`."
138
+ )
139
+ ht_list = HeatmapList([object], direction=direction)
140
+ else:
141
+ raise TypeError(f"Cannot add {type(object).__name__} to HeatmapList.")
142
+
143
+ # Extract items from right operand x
144
+ if isinstance(x, HeatmapList):
145
+ if x.ht_list and len(ht_list.ht_list) > 0 and x.direction != direction:
146
+ raise ValueError(f"Cannot combine a {x.direction!r} HeatmapList with {direction!r} concatenation.")
147
+ new_items = list(x.ht_list)
148
+ elif isinstance(x, (Heatmap, HeatmapAnnotation)):
149
+ if isinstance(x, HeatmapAnnotation):
150
+ expected = "row" if direction == "horizontal" else "column"
151
+ if x.which != expected:
152
+ raise ValueError(
153
+ f"Cannot concatenate `{x.which}` HeatmapAnnotation {direction}ly; "
154
+ f"expected `which={expected!r}` (use `rowAnnotation` for `+`, `HeatmapAnnotation` for `%v%`)."
155
+ )
156
+ new_items = [x]
157
+ else:
158
+ raise TypeError(f"Cannot concatenate {type(x).__name__} onto HeatmapList.")
159
+
160
+ # Validate compatible row/column counts
161
+ for item in new_items:
162
+ ht_list._validate_and_append(item)
163
+
164
+ return ht_list
165
+
166
+
167
+ def attach_annotation(object: Heatmap, ha: HeatmapAnnotation, side: str = "top", gap: Unit | None = None) -> Heatmap:
168
+ """Attach a HeatmapAnnotation onto an existing side of a Heatmap."""
169
+ return object.attach_annotation(ha, side=side, gap=gap)
170
+
171
+
172
+ def _merge_cm_and_params(cm_list: list[ColorMapping], lp_list: list[dict[str, Any]]) -> list[Legends]:
173
+ """Deduplicate ColorMappings by name (merging discrete mappings) and render Legends grobs."""
174
+ if not cm_list:
175
+ return []
176
+ grouped: dict[str, list[tuple[ColorMapping, dict[str, Any]]]] = {}
177
+ order_names: list[str] = []
178
+ for cm, lp in zip(cm_list, lp_list):
179
+ if cm is None:
180
+ continue
181
+ nm = str(cm.name)
182
+ if nm not in grouped:
183
+ grouped[nm] = []
184
+ order_names.append(nm)
185
+ grouped[nm].append((cm, dict(lp or {})))
186
+
187
+ out_legends: list[Legends] = []
188
+ for nm in order_names:
189
+ pairs = grouped[nm]
190
+ if len(pairs) == 1:
191
+ cm, lp = pairs[0]
192
+ out_legends.append(cm.color_mapping_legend(plot=False, **lp))
193
+ else:
194
+ cms = [p[0] for p in pairs]
195
+ if all(c.type == "discrete" for c in cms):
196
+ merged = c_ColorMapping(*cms, name=nm)
197
+ lp0 = pairs[0][1]
198
+ out_legends.append(merged.color_mapping_legend(plot=False, **lp0))
199
+ elif all(c.type == "continuous" for c in cms):
200
+ # Keep first if identical breakpoints/colors, else keep distinct
201
+ c0, lp0 = pairs[0]
202
+ out_legends.append(c0.color_mapping_legend(plot=False, **lp0))
203
+ for ck, lpk in pairs[1:]:
204
+ if not (np.array_equal(ck.levels, c0.levels) and list(ck.colors) == list(c0.colors)):
205
+ out_legends.append(ck.color_mapping_legend(plot=False, **lpk))
206
+ else:
207
+ for ck, lpk in pairs:
208
+ out_legends.append(ck.color_mapping_legend(plot=False, **lpk))
209
+ return out_legends
210
+
211
+
212
+ class HeatmapList(AdditiveUnit):
213
+ """Collection of vertically or horizontally concatenated Heatmaps and HeatmapAnnotations."""
214
+
215
+ def __init__(self, ht_list: Sequence[Heatmap | HeatmapAnnotation] = (), direction: str = "horizontal") -> None:
216
+ self.direction = _normalize_side(direction, ("horizontal", "vertical"), "direction")
217
+ self.ht_list: list[Heatmap | HeatmapAnnotation] = []
218
+ self.ht_list_param: dict[str, Any] = {
219
+ "ht_gap": unit(2, "mm"),
220
+ "main_heatmap": None,
221
+ "merge_legends": False,
222
+ "legend_grouping": "adjusted",
223
+ "padding": None,
224
+ "auto_adjust": True,
225
+ "initialized": False,
226
+ }
227
+ self.row_title: list[Any] = []
228
+ self.row_title_param: dict[str, Any] = {}
229
+ self.column_title: list[Any] = []
230
+ self.column_title_param: dict[str, Any] = {}
231
+ self.heatmap_legend_param: dict[str, Any] = {"show": False, "side": "right", "size": unit([0, 0], "mm"), "list": []}
232
+ self.annotation_legend_param: dict[str, Any] = {"show": False, "side": "right", "size": unit([0, 0], "mm"), "list": []}
233
+ self.layout: dict[str, Any] = {
234
+ "initialized": False,
235
+ "layout_size": {
236
+ "annotation_legend_top_height": unit(0, "mm"),
237
+ "heatmap_legend_top_height": unit(0, "mm"),
238
+ "column_title_top_height": unit(0, "mm"),
239
+ "column_title_bottom_height": unit(0, "mm"),
240
+ "heatmap_legend_bottom_height": unit(0, "mm"),
241
+ "annotation_legend_bottom_height": unit(0, "mm"),
242
+ "annotation_legend_left_width": unit(0, "mm"),
243
+ "heatmap_legend_left_width": unit(0, "mm"),
244
+ "row_title_left_width": unit(0, "mm"),
245
+ "row_title_right_width": unit(0, "mm"),
246
+ "heatmap_legend_right_width": unit(0, "mm"),
247
+ "annotation_legend_right_width": unit(0, "mm"),
248
+ },
249
+ "heatmap_list_padding": [0.0, 0.0, 0.0, 0.0],
250
+ }
251
+ self._device: Any = None
252
+ for item in ht_list:
253
+ self._validate_and_append(item)
254
+
255
+ def _item_axis_n(self, item: Heatmap | HeatmapAnnotation) -> int | None:
256
+ if isinstance(item, Heatmap):
257
+ return item.nrow if self.direction == "horizontal" else item.ncol
258
+ return item.nobs()
259
+
260
+ def _validate_and_append(self, item: Heatmap | HeatmapAnnotation) -> None:
261
+ if isinstance(item, HeatmapAnnotation):
262
+ expected = "row" if self.direction == "horizontal" else "column"
263
+ if item.which != expected:
264
+ raise ValueError(f"HeatmapAnnotation with `which={item.which!r}` cannot be in {self.direction!r} HeatmapList.")
265
+ elif not isinstance(item, Heatmap):
266
+ raise TypeError(f"Expected Heatmap or HeatmapAnnotation, got {type(item).__name__}.")
267
+
268
+ new_n = self._item_axis_n(item)
269
+ if new_n is not None:
270
+ for existing in self.ht_list:
271
+ ex_n = self._item_axis_n(existing)
272
+ if ex_n is not None and ex_n != new_n:
273
+ dim_nm = "rows" if self.direction == "horizontal" else "columns"
274
+ raise ValueError(f"Number of {dim_nm} ({new_n}) must match existing items ({ex_n}).")
275
+ self.ht_list.append(copy.deepcopy(item))
276
+
277
+ def copy_all(self) -> "HeatmapList":
278
+ return copy.deepcopy(self)
279
+
280
+ def __len__(self) -> int:
281
+ return len(self.ht_list)
282
+
283
+ @property
284
+ def names(self) -> list[str]:
285
+ return [item.name for item in self.ht_list]
286
+
287
+ def __getitem__(self, key: Any) -> "HeatmapList":
288
+ if self.layout["initialized"]:
289
+ raise RuntimeError("Subsetting is only allowed before layout initialization.")
290
+ if isinstance(key, tuple):
291
+ if len(key) != 2:
292
+ raise IndexError("HeatmapList expects 1D or 2D indexing.")
293
+ i_key, j_key = key
294
+ else:
295
+ i_key, j_key = key, slice(None)
296
+
297
+ def _select_components(items: list[Any], sel: Any) -> list[Any]:
298
+ if isinstance(sel, slice):
299
+ if sel == slice(None):
300
+ return list(items)
301
+ return list(items[sel])
302
+ if isinstance(sel, (int, np.integer)):
303
+ return [items[int(sel)]]
304
+ if isinstance(sel, str):
305
+ matched = []
306
+ for item in items:
307
+ if isinstance(item, Heatmap):
308
+ if item.name == sel:
309
+ matched.append(item)
310
+ else:
311
+ if sel in item.names:
312
+ matched.append(item[:, [sel]])
313
+ elif item.name == sel:
314
+ matched.append(item)
315
+ if not matched:
316
+ raise KeyError(f"Component {sel!r} not found in HeatmapList.")
317
+ return matched
318
+ seq = list(sel)
319
+ if seq and all(isinstance(v, (bool, np.bool_)) for v in seq):
320
+ if len(seq) != len(items):
321
+ raise IndexError("Boolean component mask length does not match HeatmapList length.")
322
+ return [it for it, flag in zip(items, seq) if flag]
323
+ if seq and all(isinstance(v, str) for v in seq):
324
+ sel_set = set(seq)
325
+ matched = []
326
+ found_names: set[str] = set()
327
+ for item in items:
328
+ if isinstance(item, Heatmap):
329
+ if item.name in sel_set:
330
+ matched.append(item)
331
+ found_names.add(item.name)
332
+ else:
333
+ sub_names = [nm for nm in item.names if nm in sel_set]
334
+ if sub_names:
335
+ matched.append(item[:, sub_names])
336
+ found_names.update(sub_names)
337
+ elif item.name in sel_set:
338
+ matched.append(item)
339
+ found_names.add(item.name)
340
+ missing = [s for s in seq if s not in found_names]
341
+ if missing:
342
+ raise KeyError(f"Components not found in HeatmapList: {missing}")
343
+ return matched
344
+ return [items[int(idx)] for idx in seq]
345
+
346
+ cp = self.copy_all()
347
+ if self.direction == "horizontal":
348
+ if not (isinstance(j_key, slice) and j_key == slice(None)):
349
+ cp.ht_list = _select_components(cp.ht_list, j_key)
350
+ if not (isinstance(i_key, slice) and i_key == slice(None)):
351
+ new_items = []
352
+ for item in cp.ht_list:
353
+ if isinstance(item, Heatmap):
354
+ new_items.append(_subset_heatmap_rows(item, i_key))
355
+ else:
356
+ new_items.append(item[i_key])
357
+ cp.ht_list = new_items
358
+ else:
359
+ if not (isinstance(i_key, slice) and i_key == slice(None)):
360
+ cp.ht_list = _select_components(cp.ht_list, i_key)
361
+ if not (isinstance(j_key, slice) and j_key == slice(None)):
362
+ new_items = []
363
+ for item in cp.ht_list:
364
+ if isinstance(item, Heatmap):
365
+ new_items.append(_subset_heatmap_cols(item, j_key))
366
+ else:
367
+ new_items.append(item[j_key])
368
+ cp.ht_list = new_items
369
+ return cp
370
+
371
+ # ---- Layout & Alignment ----
372
+
373
+ def _find_main_heatmap_index(self, main_heatmap: int | str | None) -> int | None:
374
+ ht_indices = [i for i, item in enumerate(self.ht_list) if isinstance(item, Heatmap)]
375
+ if not ht_indices:
376
+ return None
377
+ if main_heatmap is None:
378
+ for i in ht_indices:
379
+ ht = self.ht_list[i]
380
+ assert isinstance(ht, Heatmap)
381
+ if ht.nrow > 0 and ht.ncol > 0:
382
+ return i
383
+ return ht_indices[0]
384
+ if isinstance(main_heatmap, (int, np.integer)):
385
+ idx = int(main_heatmap)
386
+ if idx < 0 or idx >= len(self.ht_list) or not isinstance(self.ht_list[idx], Heatmap):
387
+ raise IndexError(f"`main_heatmap={main_heatmap}` does not index a Heatmap.")
388
+ return idx
389
+ for i in ht_indices:
390
+ if self.ht_list[i].name == str(main_heatmap):
391
+ return i
392
+ raise KeyError(f"Heatmap named {main_heatmap!r} not found in HeatmapList.")
393
+
394
+ def _collect_legends(self, which: str) -> list[Legends]:
395
+ """Collect either `'heatmap'` or `'annotation'` Legends (respecting merge_legends & legend_grouping)."""
396
+ merge_legends = bool(self.ht_list_param["merge_legends"])
397
+ legend_grouping = self.ht_list_param["legend_grouping"]
398
+ cm_list: list[ColorMapping] = []
399
+ lp_list: list[dict[str, Any]] = []
400
+
401
+ want_heatmap = which == "heatmap"
402
+ if not want_heatmap and merge_legends:
403
+ return []
404
+
405
+ for item in self.ht_list:
406
+ if isinstance(item, Heatmap):
407
+ # Left / right / top / bottom annotations
408
+ side_map = [
409
+ ("left", item.left_annotation),
410
+ ("top", item.top_annotation),
411
+ ("bottom", item.bottom_annotation),
412
+ ("right", item.right_annotation),
413
+ ]
414
+ for side, anno in side_map:
415
+ if anno is None:
416
+ continue
417
+ is_row_anno = side in ("left", "right")
418
+ belongs_to_main = (
419
+ merge_legends
420
+ or (legend_grouping == "adjusted" and (
421
+ (self.direction == "horizontal" and is_row_anno)
422
+ or (self.direction == "vertical" and not is_row_anno)
423
+ ))
424
+ )
425
+ if (want_heatmap and belongs_to_main) or (not want_heatmap and not belongs_to_main):
426
+ cm_list.extend(anno.get_color_mapping_list())
427
+ lp_list.extend(anno.get_legend_param_list())
428
+ # Main matrix legend
429
+ if want_heatmap and item.heatmap_param["show_heatmap_legend"] and item.matrix_color_mapping is not None:
430
+ cm_list.append(item.matrix_color_mapping)
431
+ lp_list.append(item.matrix_legend_param)
432
+ elif isinstance(item, HeatmapAnnotation):
433
+ belongs_to_main = merge_legends or (legend_grouping == "adjusted")
434
+ if (want_heatmap and belongs_to_main) or (not want_heatmap and not belongs_to_main):
435
+ cm_list.extend(item.get_color_mapping_list())
436
+ lp_list.extend(item.get_legend_param_list())
437
+
438
+ return _merge_cm_and_params(cm_list, lp_list)
439
+
440
+ def make_layout(
441
+ self,
442
+ row_title: Any = None,
443
+ row_title_side: str = "left",
444
+ row_title_gp: dict[str, Any] | None = None,
445
+ column_title: Any = None,
446
+ column_title_side: str = "top",
447
+ column_title_gp: dict[str, Any] | None = None,
448
+
449
+ heatmap_legend_side: str = "right",
450
+ merge_legends: bool = False,
451
+ show_heatmap_legend: bool = True,
452
+ heatmap_legend_list: Sequence[Legends | Grob] = (),
453
+ annotation_legend_side: str = "right",
454
+ show_annotation_legend: bool = True,
455
+ annotation_legend_list: Sequence[Legends | Grob] = (),
456
+ align_heatmap_legend: str | None = None,
457
+ align_annotation_legend: str | None = None,
458
+ legend_grouping: str = "adjusted",
459
+
460
+ ht_gap: Unit | None = None,
461
+ main_heatmap: int | str | None = None,
462
+ padding: Any = None,
463
+ auto_adjust: bool = True,
464
+
465
+ row_dend_side: str = "original",
466
+ row_sub_title_side: str = "original",
467
+ column_dend_side: str = "original",
468
+ column_sub_title_side: str = "original",
469
+
470
+ # Overrides forwarded to main_heatmap
471
+ row_km: int | None = None,
472
+ row_km_repeats: int | None = None,
473
+ row_split: Any = None,
474
+ row_gap: Unit | None = None,
475
+ cluster_rows: Any = None,
476
+ cluster_row_slices: bool | None = None,
477
+ clustering_distance_rows: Any = None,
478
+ clustering_method_rows: str | None = None,
479
+ row_dend_width: Unit | None = None,
480
+ show_row_dend: bool | None = None,
481
+ row_dend_reorder: Any = None,
482
+ row_dend_gp: dict[str, Any] | None = None,
483
+ row_order: Any = None,
484
+ height: Unit | None = None,
485
+ heatmap_height: Unit | None = None,
486
+
487
+ column_km: int | None = None,
488
+ column_km_repeats: int | None = None,
489
+ column_split: Any = None,
490
+ column_gap: Unit | None = None,
491
+ cluster_columns: Any = None,
492
+ cluster_column_slices: bool | None = None,
493
+ clustering_distance_columns: Any = None,
494
+ clustering_method_columns: str | None = None,
495
+ column_dend_height: Unit | None = None,
496
+ show_column_dend: bool | None = None,
497
+ column_dend_reorder: Any = None,
498
+ column_dend_gp: dict[str, Any] | None = None,
499
+ column_order: Any = None,
500
+ width: Unit | None = None,
501
+ heatmap_width: Unit | None = None,
502
+
503
+ use_raster: bool | None = None,
504
+ page_size_mm: tuple[float, float] = (200.0, 200.0),
505
+ ) -> "HeatmapList":
506
+ if self.ht_list_param["initialized"]:
507
+ return self
508
+
509
+ work = self.copy_all()
510
+ if not work.ht_list:
511
+ work.ht_list_param["initialized"] = True
512
+ work.layout["initialized"] = True
513
+ return work
514
+
515
+ gap_arg = ht_opt.ht_gap if ht_gap is None and hasattr(ht_opt, "ht_gap") and ht_opt.ht_gap is not None else ht_gap
516
+ eff_auto_adjust = bool(auto_adjust)
517
+ legend_grouping = _normalize_side(legend_grouping, ("adjusted", "original"), "legend_grouping")
518
+ hm_leg_side = _normalize_side(heatmap_legend_side, ("right", "left", "bottom", "top"), "heatmap_legend_side")
519
+ an_leg_side = _normalize_side(annotation_legend_side, ("right", "left", "bottom", "top"), "annotation_legend_side")
520
+ rt_side = _normalize_side(row_title_side, ("left", "right"), "row_title_side")
521
+ ct_side = _normalize_side(column_title_side, ("top", "bottom"), "column_title_side")
522
+
523
+ # Identify main heatmap
524
+ i_main = work._find_main_heatmap_index(main_heatmap)
525
+ has_heatmap = i_main is not None
526
+
527
+ if has_heatmap:
528
+ assert i_main is not None
529
+ ht_main = work.ht_list[i_main]
530
+ assert isinstance(ht_main, Heatmap)
531
+
532
+ # Forward draw() overrides
533
+ if use_raster is not None:
534
+ for item in work.ht_list:
535
+ if isinstance(item, Heatmap):
536
+ item.heatmap_param["use_raster"] = bool(use_raster)
537
+
538
+ if work.direction == "horizontal":
539
+ if row_km is not None:
540
+ ht_main.matrix_param["row_km"] = int(row_km)
541
+ if row_km_repeats is not None:
542
+ ht_main.matrix_param["row_km_repeats"] = int(row_km_repeats)
543
+ if row_split is not None:
544
+ ht_main.matrix_param["row_split"] = row_split
545
+ if row_gap is not None:
546
+ ht_main.matrix_param["row_gap"] = as_unit(row_gap, "mm")
547
+ if cluster_rows is not None:
548
+ if isinstance(cluster_rows, (bool, np.bool_)):
549
+ ht_main.row_dend_param["cluster"] = bool(cluster_rows)
550
+ ht_main.row_dend_param["obj"] = None
551
+ elif callable(cluster_rows):
552
+ ht_main.row_dend_param["cluster"] = True
553
+ ht_main.row_dend_param["fun"] = cluster_rows
554
+ else:
555
+ from .dendrogram import as_dendrogram
556
+ ht_main.row_dend_param["cluster"] = True
557
+ ht_main.row_dend_param["obj"] = as_dendrogram(cluster_rows)
558
+ if cluster_row_slices is not None:
559
+ ht_main.row_dend_param["cluster_slices"] = bool(cluster_row_slices)
560
+ if clustering_distance_rows is not None:
561
+ ht_main.row_dend_param["distance"] = clustering_distance_rows
562
+ if clustering_method_rows is not None:
563
+ ht_main.row_dend_param["method"] = clustering_method_rows
564
+ if row_dend_width is not None:
565
+ pad_d = convertWidth(as_unit(ht_opt.DENDROGRAM_PADDING, "mm"), "mm", valueOnly=True)
566
+ rd_mm = convertWidth(as_unit(row_dend_width, "mm"), "mm", valueOnly=True)
567
+ ht_main.row_dend_param["width"] = unit(0.0 if rd_mm == 0 else rd_mm + pad_d, "mm")
568
+ if show_row_dend is not None:
569
+ ht_main.row_dend_param["show"] = bool(show_row_dend)
570
+ if row_dend_reorder is not None:
571
+ ht_main.row_dend_param["reorder"] = row_dend_reorder
572
+ if row_dend_gp is not None:
573
+ ht_main.row_dend_param["gp"] = check_gp(row_dend_gp)
574
+ if row_order is not None:
575
+ ht_main.row_order = [int(x) for x in row_order]
576
+ ht_main.row_dend_param["cluster"] = False
577
+ ht_main.row_dend_param["show"] = False
578
+ if height is not None:
579
+ ht_main.matrix_param["height"] = as_unit(height, "mm")
580
+ ht_main.heatmap_param["height"] = unit(1.0, "npc")
581
+ elif heatmap_height is not None:
582
+ ht_main.matrix_param["height"] = unit(1.0, "npc")
583
+ ht_main.heatmap_param["height"] = as_unit(heatmap_height, "mm")
584
+ else:
585
+ if column_km is not None:
586
+ ht_main.matrix_param["column_km"] = int(column_km)
587
+ if column_km_repeats is not None:
588
+ ht_main.matrix_param["column_km_repeats"] = int(column_km_repeats)
589
+ if column_split is not None:
590
+ ht_main.matrix_param["column_split"] = column_split
591
+ if column_gap is not None:
592
+ ht_main.matrix_param["column_gap"] = as_unit(column_gap, "mm")
593
+ if cluster_columns is not None:
594
+ if isinstance(cluster_columns, (bool, np.bool_)):
595
+ ht_main.column_dend_param["cluster"] = bool(cluster_columns)
596
+ ht_main.column_dend_param["obj"] = None
597
+ elif callable(cluster_columns):
598
+ ht_main.column_dend_param["cluster"] = True
599
+ ht_main.column_dend_param["fun"] = cluster_columns
600
+ else:
601
+ from .dendrogram import as_dendrogram
602
+ ht_main.column_dend_param["cluster"] = True
603
+ ht_main.column_dend_param["obj"] = as_dendrogram(cluster_columns)
604
+ if cluster_column_slices is not None:
605
+ ht_main.column_dend_param["cluster_slices"] = bool(cluster_column_slices)
606
+ if clustering_distance_columns is not None:
607
+ ht_main.column_dend_param["distance"] = clustering_distance_columns
608
+ if clustering_method_columns is not None:
609
+ ht_main.column_dend_param["method"] = clustering_method_columns
610
+ if column_dend_height is not None:
611
+ pad_d = convertHeight(as_unit(ht_opt.DENDROGRAM_PADDING, "mm"), "mm", valueOnly=True)
612
+ cd_mm = convertHeight(as_unit(column_dend_height, "mm"), "mm", valueOnly=True)
613
+ ht_main.column_dend_param["height"] = unit(0.0 if cd_mm == 0 else cd_mm + pad_d, "mm")
614
+ if show_column_dend is not None:
615
+ ht_main.column_dend_param["show"] = bool(show_column_dend)
616
+ if column_dend_reorder is not None:
617
+ ht_main.column_dend_param["reorder"] = column_dend_reorder
618
+ if column_dend_gp is not None:
619
+ ht_main.column_dend_param["gp"] = check_gp(column_dend_gp)
620
+ if column_order is not None:
621
+ ht_main.column_order = [int(x) for x in column_order]
622
+ ht_main.column_dend_param["cluster"] = False
623
+ ht_main.column_dend_param["show"] = False
624
+ if width is not None:
625
+ ht_main.matrix_param["width"] = as_unit(width, "mm")
626
+ ht_main.heatmap_param["width"] = unit(1.0, "npc")
627
+ elif heatmap_width is not None:
628
+ ht_main.matrix_param["width"] = unit(1.0, "npc")
629
+ ht_main.heatmap_param["width"] = as_unit(heatmap_width, "mm")
630
+
631
+ # Cluster main heatmap on shared axis
632
+ if work.direction == "horizontal":
633
+ ht_main.make_row_cluster()
634
+ else:
635
+ ht_main.make_column_cluster()
636
+
637
+ n_ht = len(work.ht_list)
638
+ eff_ht_gap = _normalize_ht_gap(gap_arg, n_ht)
639
+
640
+ # Outer zero-dim Heatmap scaffolding if dendrograms/subtitles must sit outside a leading/trailing HeatmapAnnotation
641
+ rd_side_opt = _normalize_side(row_dend_side, ("original", "left", "right"), "row_dend_side")
642
+ rs_side_opt = _normalize_side(row_sub_title_side, ("original", "left", "right"), "row_sub_title_side")
643
+ cd_side_opt = _normalize_side(column_dend_side, ("original", "top", "bottom"), "column_dend_side")
644
+ cs_side_opt = _normalize_side(column_sub_title_side, ("original", "top", "bottom"), "column_sub_title_side")
645
+
646
+ if len(work.ht_list) > 1 and eff_auto_adjust:
647
+ if work.direction == "horizontal":
648
+ if (rd_side_opt == "left" or rs_side_opt == "left") and isinstance(work.ht_list[0], HeatmapAnnotation):
649
+ dummy = Heatmap(np.empty((ht_main.nrow, 0)), name=f"_scaffold_l_{_ENV.next_heatmap_index()}", show_heatmap_legend=False)
650
+ dummy.row_order = list(ht_main.row_order)
651
+ dummy.row_order_list = [list(s) for s in ht_main.row_order_list]
652
+ work.ht_list.insert(0, dummy)
653
+ eff_ht_gap = unit_c(unit(0.0, "mm"), eff_ht_gap)
654
+ i_main += 1
655
+ if (rd_side_opt == "right" or rs_side_opt == "right") and isinstance(work.ht_list[-1], HeatmapAnnotation):
656
+ dummy = Heatmap(np.empty((ht_main.nrow, 0)), name=f"_scaffold_r_{_ENV.next_heatmap_index()}", show_heatmap_legend=False)
657
+ dummy.row_order = list(ht_main.row_order)
658
+ dummy.row_order_list = [list(s) for s in ht_main.row_order_list]
659
+ work.ht_list.append(dummy)
660
+ eff_ht_gap = unit_c(eff_ht_gap, unit(0.0, "mm"))
661
+ else:
662
+ if (cd_side_opt == "top" or cs_side_opt == "top") and isinstance(work.ht_list[0], HeatmapAnnotation):
663
+ dummy = Heatmap(np.empty((0, ht_main.ncol)), name=f"_scaffold_t_{_ENV.next_heatmap_index()}", show_heatmap_legend=False)
664
+ dummy.column_order = list(ht_main.column_order)
665
+ dummy.column_order_list = [list(s) for s in ht_main.column_order_list]
666
+ work.ht_list.insert(0, dummy)
667
+ eff_ht_gap = unit_c(unit(0.0, "mm"), eff_ht_gap)
668
+ i_main += 1
669
+ if (cd_side_opt == "bottom" or cs_side_opt == "bottom") and isinstance(work.ht_list[-1], HeatmapAnnotation):
670
+ dummy = Heatmap(np.empty((0, ht_main.ncol)), name=f"_scaffold_b_{_ENV.next_heatmap_index()}", show_heatmap_legend=False)
671
+ dummy.column_order = list(ht_main.column_order)
672
+ dummy.column_order_list = [list(s) for s in ht_main.column_order_list]
673
+ work.ht_list.append(dummy)
674
+ eff_ht_gap = unit_c(eff_ht_gap, unit(0.0, "mm"))
675
+
676
+ n_ht = len(work.ht_list)
677
+
678
+ # Propagate shared ordering, splits, gaps, auto-adjustment, and outer dends/subtitles
679
+ if work.direction == "horizontal":
680
+ for i, item in enumerate(work.ht_list):
681
+ if isinstance(item, Heatmap) and i != i_main:
682
+ item.row_order_list = [list(s) for s in ht_main.row_order_list]
683
+ item.row_order = list(ht_main.row_order)
684
+ item.row_dend_param["show"] = False
685
+ item.row_dend_param["cluster"] = False
686
+ item.matrix_param["row_gap"] = ht_main.matrix_param["row_gap"]
687
+ item.matrix_param["_row_split_df"] = ht_main.matrix_param.get("_row_split_df")
688
+ item.matrix_param["height"] = ht_main.matrix_param["height"]
689
+ item.heatmap_param["height"] = ht_main.heatmap_param["height"]
690
+ item.row_title = []
691
+
692
+ if eff_auto_adjust and n_ht > 1:
693
+ for i, item in enumerate(work.ht_list):
694
+ if isinstance(item, Heatmap):
695
+ keep_left = (i == 0 and item.row_names_param["side"] == "left")
696
+ keep_right = (i == n_ht - 1 and item.row_names_param["side"] == "right")
697
+ if not (keep_left or keep_right):
698
+ item.row_names_param["show"] = False
699
+ item.row_names_param["anno"] = None
700
+
701
+ if rd_side_opt in ("left", "right"):
702
+ target_i = 0 if rd_side_opt == "left" else n_ht - 1
703
+ if isinstance(work.ht_list[target_i], Heatmap) and target_i != i_main:
704
+ tgt = work.ht_list[target_i]
705
+ assert isinstance(tgt, Heatmap)
706
+ tgt.row_dend_list = ht_main.row_dend_list
707
+ tgt.row_dend_slice = ht_main.row_dend_slice
708
+ tgt.row_dend_param = dict(ht_main.row_dend_param)
709
+ tgt.row_dend_param["side"] = rd_side_opt
710
+ ht_main.row_dend_param["show"] = False
711
+ elif target_i == i_main:
712
+ ht_main.row_dend_param["side"] = rd_side_opt
713
+
714
+ if rs_side_opt in ("left", "right"):
715
+ target_i = 0 if rs_side_opt == "left" else n_ht - 1
716
+ if isinstance(work.ht_list[target_i], Heatmap) and target_i != i_main:
717
+ tgt = work.ht_list[target_i]
718
+ assert isinstance(tgt, Heatmap)
719
+ tgt.row_title = list(ht_main.row_title)
720
+ tgt.row_title_param = dict(ht_main.row_title_param)
721
+ tgt.row_title_param["side"] = rs_side_opt
722
+ tgt.row_title_param["just"] = _get_text_just(tgt.row_title_param["rot"], rs_side_opt)
723
+ ht_main.row_title = []
724
+ elif target_i == i_main:
725
+ ht_main.row_title_param["side"] = rs_side_opt
726
+ ht_main.row_title_param["just"] = _get_text_just(ht_main.row_title_param["rot"], rs_side_opt)
727
+
728
+ for item in work.ht_list:
729
+ if isinstance(item, Heatmap):
730
+ item.prepare(process_rows=False, process_columns=True)
731
+ else:
732
+ for i, item in enumerate(work.ht_list):
733
+ if isinstance(item, Heatmap) and i != i_main:
734
+ item.column_order_list = [list(s) for s in ht_main.column_order_list]
735
+ item.column_order = list(ht_main.column_order)
736
+ item.column_dend_param["show"] = False
737
+ item.column_dend_param["cluster"] = False
738
+ item.matrix_param["column_gap"] = ht_main.matrix_param["column_gap"]
739
+ item.matrix_param["_column_split_df"] = ht_main.matrix_param.get("_column_split_df")
740
+ item.matrix_param["width"] = ht_main.matrix_param["width"]
741
+ item.heatmap_param["width"] = ht_main.heatmap_param["width"]
742
+ item.column_title = []
743
+
744
+ if eff_auto_adjust and n_ht > 1:
745
+ for i, item in enumerate(work.ht_list):
746
+ if isinstance(item, Heatmap):
747
+ keep_top = (i == 0 and item.column_names_param["side"] == "top")
748
+ keep_bottom = (i == n_ht - 1 and item.column_names_param["side"] == "bottom")
749
+ if not (keep_top or keep_bottom):
750
+ item.column_names_param["show"] = False
751
+ item.column_names_param["anno"] = None
752
+
753
+ if cd_side_opt in ("top", "bottom"):
754
+ target_i = 0 if cd_side_opt == "top" else n_ht - 1
755
+ if isinstance(work.ht_list[target_i], Heatmap) and target_i != i_main:
756
+ tgt = work.ht_list[target_i]
757
+ assert isinstance(tgt, Heatmap)
758
+ tgt.column_dend_list = ht_main.column_dend_list
759
+ tgt.column_dend_slice = ht_main.column_dend_slice
760
+ tgt.column_dend_param = dict(ht_main.column_dend_param)
761
+ tgt.column_dend_param["side"] = cd_side_opt
762
+ ht_main.column_dend_param["show"] = False
763
+ elif target_i == i_main:
764
+ ht_main.column_dend_param["side"] = cd_side_opt
765
+
766
+ if cs_side_opt in ("top", "bottom"):
767
+ target_i = 0 if cs_side_opt == "top" else n_ht - 1
768
+ if isinstance(work.ht_list[target_i], Heatmap) and target_i != i_main:
769
+ tgt = work.ht_list[target_i]
770
+ assert isinstance(tgt, Heatmap)
771
+ tgt.column_title = list(ht_main.column_title)
772
+ tgt.column_title_param = dict(ht_main.column_title_param)
773
+ tgt.column_title_param["side"] = cs_side_opt
774
+ tgt.column_title_param["just"] = _get_text_just(tgt.column_title_param["rot"], cs_side_opt)
775
+ ht_main.column_title = []
776
+ elif target_i == i_main:
777
+ ht_main.column_title_param["side"] = cs_side_opt
778
+ ht_main.column_title_param["just"] = _get_text_just(ht_main.column_title_param["rot"], cs_side_opt)
779
+
780
+ for item in work.ht_list:
781
+ if isinstance(item, Heatmap):
782
+ item.prepare(process_rows=True, process_columns=False)
783
+
784
+ work.ht_list_param["main_heatmap"] = i_main
785
+ work.ht_list_param["ht_gap"] = eff_ht_gap
786
+ else:
787
+ # Annotation-only HeatmapList
788
+ work.ht_list_param["main_heatmap"] = None
789
+ work.ht_list_param["ht_gap"] = _normalize_ht_gap(gap_arg, len(work.ht_list))
790
+
791
+ work.ht_list_param["merge_legends"] = bool(merge_legends)
792
+ work.ht_list_param["legend_grouping"] = legend_grouping
793
+ work.ht_list_param["auto_adjust"] = eff_auto_adjust
794
+ work.ht_list_param["padding"] = padding
795
+
796
+ # Equalize perpendicular layout components across heatmaps
797
+ work._adjust_heatmap_list()
798
+
799
+ # Global titles
800
+ ct_gp = check_gp(gpar(fontsize=14) if column_title_gp is None else column_title_gp)
801
+ rt_gp = check_gp(gpar(fontsize=14) if row_title_gp is None else row_title_gp)
802
+ work.column_title = _normalize_title_list(column_title)
803
+ work.column_title_param = {"side": ct_side, "gp": ct_gp}
804
+ work.row_title = _normalize_title_list(row_title)
805
+ work.row_title_param = {"side": rt_side, "gp": rt_gp}
806
+
807
+ ls = work.layout["layout_size"]
808
+ if work.column_title:
809
+ ct_str = work.column_title[0]
810
+ ct_h = max_text_height(ct_str, gp=ct_gp) + unit_sum(_title_padding_unit(ct_gp))
811
+ ls[f"column_title_{ct_side}_height"] = ct_h
812
+ if work.row_title:
813
+ rt_str = work.row_title[0]
814
+ rt_w = max_text_width(rt_str, gp=rt_gp, rot=90.0 if rt_side == "left" else 270.0) + unit_sum(_title_padding_unit(rt_gp))
815
+ ls[f"row_title_{rt_side}_width"] = rt_w
816
+
817
+ # Legends
818
+ hm_leg_list_items = work._collect_legends("heatmap") if show_heatmap_legend else []
819
+ if heatmap_legend_list:
820
+ extra_hm = [heatmap_legend_list] if isinstance(heatmap_legend_list, (Legends, Grob)) else list(heatmap_legend_list)
821
+ hm_leg_list_items.extend(extra_hm)
822
+
823
+ an_leg_list_items = [] if merge_legends or not show_annotation_legend else work._collect_legends("annotation")
824
+ if annotation_legend_list:
825
+ extra_an = [annotation_legend_list] if isinstance(annotation_legend_list, (Legends, Grob)) else list(annotation_legend_list)
826
+ if merge_legends and show_heatmap_legend:
827
+ hm_leg_list_items.extend(extra_an)
828
+ elif show_annotation_legend:
829
+ an_leg_list_items.extend(extra_an)
830
+
831
+ max_leg_w = unit(page_size_mm[0] * 0.9, "mm")
832
+ max_leg_h = unit(page_size_mm[1] * 0.9, "mm")
833
+
834
+ if hm_leg_list_items:
835
+ hm_pad_u = as_unit(ht_opt.HEATMAP_LEGEND_PADDING, "mm")
836
+ hm_pad_mm = convertWidth(hm_pad_u, "mm", valueOnly=True)
837
+ hm_dir = "vertical" if hm_leg_side in ("left", "right") else "horizontal"
838
+ packed_hm = packLegend(
839
+ *hm_leg_list_items,
840
+ direction=hm_dir,
841
+ max_height=max_leg_h if hm_dir == "vertical" else None,
842
+ max_width=max_leg_w if hm_dir == "horizontal" else None,
843
+ )
844
+ w_mm = convertWidth(packed_hm.width, "mm", valueOnly=True)
845
+ h_mm = convertHeight(packed_hm.height, "mm", valueOnly=True)
846
+ work.heatmap_legend_param = {
847
+ "show": True,
848
+ "side": hm_leg_side,
849
+ "packed": packed_hm,
850
+ "align": align_heatmap_legend or "heatmap_center",
851
+ "padding_mm": hm_pad_mm,
852
+ "size": unit([w_mm + (hm_pad_mm if hm_leg_side in ("left", "right") else 0.0), h_mm + (hm_pad_mm if hm_leg_side in ("top", "bottom") else 0.0)], "mm"),
853
+ }
854
+ if hm_leg_side in ("left", "right"):
855
+ ls[f"heatmap_legend_{hm_leg_side}_width"] = unit(w_mm + hm_pad_mm, "mm")
856
+ else:
857
+ ls[f"heatmap_legend_{hm_leg_side}_height"] = unit(h_mm + hm_pad_mm, "mm")
858
+ else:
859
+ work.heatmap_legend_param = {"show": False, "side": hm_leg_side, "packed": None, "size": unit([0, 0], "mm")}
860
+
861
+ if an_leg_list_items:
862
+ an_pad_u = as_unit(ht_opt.ANNOTATION_LEGEND_PADDING, "mm")
863
+ an_pad_mm = convertWidth(an_pad_u, "mm", valueOnly=True)
864
+ an_dir = "vertical" if an_leg_side in ("left", "right") else "horizontal"
865
+ packed_an = packLegend(
866
+ *an_leg_list_items,
867
+ direction=an_dir,
868
+ max_height=max_leg_h if an_dir == "vertical" else None,
869
+ max_width=max_leg_w if an_dir == "horizontal" else None,
870
+ )
871
+ w_mm = convertWidth(packed_an.width, "mm", valueOnly=True)
872
+ h_mm = convertHeight(packed_an.height, "mm", valueOnly=True)
873
+ work.annotation_legend_param = {
874
+ "show": True,
875
+ "side": an_leg_side,
876
+ "packed": packed_an,
877
+ "align": align_annotation_legend or "heatmap_center",
878
+ "padding_mm": an_pad_mm,
879
+ "size": unit([w_mm + (an_pad_mm if an_leg_side in ("left", "right") else 0.0), h_mm + (an_pad_mm if an_leg_side in ("top", "bottom") else 0.0)], "mm"),
880
+ }
881
+ if an_leg_side in ("left", "right"):
882
+ ls[f"annotation_legend_{an_leg_side}_width"] = unit(w_mm + an_pad_mm, "mm")
883
+ else:
884
+ ls[f"annotation_legend_{an_leg_side}_height"] = unit(h_mm + an_pad_mm, "mm")
885
+ else:
886
+ work.annotation_legend_param = {"show": False, "side": an_leg_side, "packed": None, "size": unit([0, 0], "mm")}
887
+
888
+ work.ht_list_param["initialized"] = True
889
+ work.layout["initialized"] = True
890
+ return work
891
+
892
+ def _adjust_heatmap_list(self) -> None:
893
+ ht_indices = [i for i, item in enumerate(self.ht_list) if isinstance(item, Heatmap)]
894
+ if not ht_indices:
895
+ self.layout["heatmap_list_padding"] = [0.0, 0.0, 0.0, 0.0]
896
+ return
897
+
898
+ if self.direction == "horizontal":
899
+ col_pad_mm = convertHeight(as_unit(ht_opt.COLUMN_ANNO_PADDING, "mm"), "mm", valueOnly=True)
900
+ # Resize all top & bottom annotations to common max height
901
+ top_hs = [convertHeight(self.ht_list[i].top_annotation.height, "mm", valueOnly=True) for i in ht_indices if self.ht_list[i].top_annotation is not None]
902
+ bot_hs = [convertHeight(self.ht_list[i].bottom_annotation.height, "mm", valueOnly=True) for i in ht_indices if self.ht_list[i].bottom_annotation is not None]
903
+ max_top_a = max(top_hs, default=0.0)
904
+ max_bot_a = max(bot_hs, default=0.0)
905
+ for i in ht_indices:
906
+ ht = self.ht_list[i]
907
+ assert isinstance(ht, Heatmap)
908
+ if ht.top_annotation is not None and max_top_a > 0:
909
+ ht.top_annotation.re_size(height=unit(max_top_a, "mm"))
910
+ ht.layout["layout_size"]["column_anno_top_height"] = unit(max_top_a + col_pad_mm, "mm")
911
+ if ht.bottom_annotation is not None and max_bot_a > 0:
912
+ ht.bottom_annotation.re_size(height=unit(max_bot_a, "mm"))
913
+ ht.layout["layout_size"]["column_anno_bottom_height"] = unit(max_bot_a + col_pad_mm, "mm")
914
+
915
+ max_ct_top = max(convertHeight(self.ht_list[i].layout["layout_size"]["column_title_top_height"], "mm", valueOnly=True) for i in ht_indices)
916
+ max_ct_bot = max(convertHeight(self.ht_list[i].layout["layout_size"]["column_title_bottom_height"], "mm", valueOnly=True) for i in ht_indices)
917
+ max_top_comp = max(
918
+ sum(convertHeight(self.ht_list[i].layout["layout_size"][k], "mm", valueOnly=True) for k in ("column_dend_top_height", "column_names_top_height", "column_anno_top_height"))
919
+ for i in ht_indices
920
+ )
921
+ max_bot_comp = max(
922
+ sum(convertHeight(self.ht_list[i].layout["layout_size"][k], "mm", valueOnly=True) for k in ("column_dend_bottom_height", "column_names_bottom_height", "column_anno_bottom_height"))
923
+ for i in ht_indices
924
+ )
925
+
926
+ for i in ht_indices:
927
+ ls_i = self.ht_list[i].layout["layout_size"]
928
+ ls_i["column_title_top_height"] = unit(max_ct_top, "mm")
929
+ ls_i["column_title_bottom_height"] = unit(max_ct_bot, "mm")
930
+ used_top = convertHeight(ls_i["column_names_top_height"], "mm", valueOnly=True) + convertHeight(ls_i["column_anno_top_height"], "mm", valueOnly=True)
931
+ used_bot = convertHeight(ls_i["column_names_bottom_height"], "mm", valueOnly=True) + convertHeight(ls_i["column_anno_bottom_height"], "mm", valueOnly=True)
932
+ ls_i["column_dend_top_height"] = unit(max(0.0, max_top_comp - used_top), "mm")
933
+ ls_i["column_dend_bottom_height"] = unit(max(0.0, max_bot_comp - used_bot), "mm")
934
+
935
+ # Compute outer padding needed when row-annotation extended labels extend past top/bottom components
936
+ ext_top = 0.0
937
+ ext_bot = 0.0
938
+ for item in self.ht_list:
939
+ if isinstance(item, HeatmapAnnotation):
940
+ e = item.extended.to_mm("x")
941
+ ext_bot = max(ext_bot, float(e[0]))
942
+ ext_top = max(ext_top, float(e[2]))
943
+ elif isinstance(item, Heatmap):
944
+ for ann in (item.left_annotation, item.right_annotation):
945
+ if ann is not None:
946
+ e = ann.extended.to_mm("x")
947
+ ext_bot = max(ext_bot, float(e[0]))
948
+ ext_top = max(ext_top, float(e[2]))
949
+ pad_top = max(0.0, ext_top - max_top_comp - max_ct_top)
950
+ pad_bot = max(0.0, ext_bot - max_bot_comp - max_ct_bot)
951
+
952
+ ext_left = 0.0
953
+ ext_right = 0.0
954
+ first_item = self.ht_list[0]
955
+ if isinstance(first_item, Heatmap):
956
+ left_used = sum(convertWidth(first_item.layout["layout_size"][f"{c}_width"], "mm", valueOnly=True) for c in ("row_title_left", "row_dend_left", "row_names_left", "row_anno_left"))
957
+ e_l = 0.0
958
+ for ann in (first_item.top_annotation, first_item.bottom_annotation):
959
+ if ann is not None:
960
+ e_l = max(e_l, float(ann.extended.to_mm("x")[1]))
961
+ ext_left = max(0.0, e_l - left_used)
962
+ last_item = self.ht_list[-1]
963
+ if isinstance(last_item, Heatmap):
964
+ right_used = sum(convertWidth(last_item.layout["layout_size"][f"{c}_width"], "mm", valueOnly=True) for c in ("row_title_right", "row_dend_right", "row_names_right", "row_anno_right"))
965
+ e_r = 0.0
966
+ for ann in (last_item.top_annotation, last_item.bottom_annotation):
967
+ if ann is not None:
968
+ e_r = max(e_r, float(ann.extended.to_mm("x")[3]))
969
+ ext_right = max(0.0, e_r - right_used)
970
+ self.layout["heatmap_list_padding"] = [pad_bot, ext_left, pad_top, ext_right]
971
+ else:
972
+ row_pad_mm = convertWidth(as_unit(ht_opt.ROW_ANNO_PADDING, "mm"), "mm", valueOnly=True)
973
+ left_ws = [convertWidth(self.ht_list[i].left_annotation.width, "mm", valueOnly=True) for i in ht_indices if self.ht_list[i].left_annotation is not None]
974
+ right_ws = [convertWidth(self.ht_list[i].right_annotation.width, "mm", valueOnly=True) for i in ht_indices if self.ht_list[i].right_annotation is not None]
975
+ max_left_a = max(left_ws, default=0.0)
976
+ max_right_a = max(right_ws, default=0.0)
977
+ for i in ht_indices:
978
+ ht = self.ht_list[i]
979
+ assert isinstance(ht, Heatmap)
980
+ if ht.left_annotation is not None and max_left_a > 0:
981
+ ht.left_annotation.re_size(width=unit(max_left_a, "mm"))
982
+ ht.layout["layout_size"]["row_anno_left_width"] = unit(max_left_a + row_pad_mm, "mm")
983
+ if ht.right_annotation is not None and max_right_a > 0:
984
+ ht.right_annotation.re_size(width=unit(max_right_a, "mm"))
985
+ ht.layout["layout_size"]["row_anno_right_width"] = unit(max_right_a + row_pad_mm, "mm")
986
+
987
+ max_rt_left = max(convertWidth(self.ht_list[i].layout["layout_size"]["row_title_left_width"], "mm", valueOnly=True) for i in ht_indices)
988
+ max_rt_right = max(convertWidth(self.ht_list[i].layout["layout_size"]["row_title_right_width"], "mm", valueOnly=True) for i in ht_indices)
989
+ max_left_comp = max(
990
+ sum(convertWidth(self.ht_list[i].layout["layout_size"][k], "mm", valueOnly=True) for k in ("row_dend_left_width", "row_names_left_width", "row_anno_left_width"))
991
+ for i in ht_indices
992
+ )
993
+ max_right_comp = max(
994
+ sum(convertWidth(self.ht_list[i].layout["layout_size"][k], "mm", valueOnly=True) for k in ("row_dend_right_width", "row_names_right_width", "row_anno_right_width"))
995
+ for i in ht_indices
996
+ )
997
+ for i in ht_indices:
998
+ ls_i = self.ht_list[i].layout["layout_size"]
999
+ ls_i["row_title_left_width"] = unit(max_rt_left, "mm")
1000
+ ls_i["row_title_right_width"] = unit(max_rt_right, "mm")
1001
+ used_l = convertWidth(ls_i["row_names_left_width"], "mm", valueOnly=True) + convertWidth(ls_i["row_anno_left_width"], "mm", valueOnly=True)
1002
+ used_r = convertWidth(ls_i["row_names_right_width"], "mm", valueOnly=True) + convertWidth(ls_i["row_anno_right_width"], "mm", valueOnly=True)
1003
+ ls_i["row_dend_left_width"] = unit(max(0.0, max_left_comp - used_l), "mm")
1004
+ ls_i["row_dend_right_width"] = unit(max(0.0, max_right_comp - used_r), "mm")
1005
+ self.layout["heatmap_list_padding"] = [0.0, 0.0, 0.0, 0.0]
1006
+
1007
+ def _compute_heatmap_list_spans(self, avail_w_mm: float, avail_h_mm: float) -> list[float]:
1008
+ """Allocate exact mm widths (horizontal) or heights (vertical) for each item in `ht_list`."""
1009
+ n = len(self.ht_list)
1010
+ if n == 0:
1011
+ return []
1012
+ gaps_mm = self.ht_list_param["ht_gap"].to_mm("x")
1013
+ total_gap = sum(float(gaps_mm[i]) for i in range(max(0, n - 1)))
1014
+
1015
+ if self.direction == "horizontal":
1016
+ fixed_total = 0.0
1017
+ flex_weights: list[float] = []
1018
+ item_fixed_w: list[float | None] = []
1019
+ for item in self.ht_list:
1020
+ if isinstance(item, HeatmapAnnotation):
1021
+ w_mm = convertWidth(item.width, "mm", valueOnly=True)
1022
+ item_fixed_w.append(w_mm)
1023
+ fixed_total += w_mm
1024
+ else:
1025
+ if is_abs_unit(item.heatmap_param["width"]):
1026
+ w_mm = convertWidth(item.heatmap_param["width"], "mm", valueOnly=True)
1027
+ item_fixed_w.append(w_mm)
1028
+ fixed_total += w_mm
1029
+ elif is_abs_unit(item.matrix_param["width"]):
1030
+ ws = item.component_widths_mm()
1031
+ w_mm = sum(x or 0.0 for x in ws)
1032
+ item_fixed_w.append(w_mm)
1033
+ fixed_total += w_mm
1034
+ else:
1035
+ # Flexible body: track fixed non-body components + weight for body
1036
+ ws = item.component_widths_mm()
1037
+ fixed_non_body = sum(x or 0.0 for x in ws)
1038
+ fixed_total += fixed_non_body
1039
+ item_fixed_w.append(None)
1040
+ flex_weights.append(float(max(1, item.ncol)))
1041
+
1042
+ rem = max(0.0, avail_w_mm - total_gap - fixed_total)
1043
+ tot_wt = sum(flex_weights)
1044
+ out_w: list[float] = []
1045
+ f_idx = 0
1046
+ for i, item in enumerate(self.ht_list):
1047
+ if item_fixed_w[i] is not None:
1048
+ out_w.append(float(item_fixed_w[i]))
1049
+ else:
1050
+ wt = flex_weights[f_idx]
1051
+ f_idx += 1
1052
+ ws = item.component_widths_mm()
1053
+ fixed_non_body = sum(x or 0.0 for x in ws)
1054
+ body_w = rem * (wt / tot_wt) if tot_wt > 0 else 0.0
1055
+ out_w.append(fixed_non_body + body_w)
1056
+ return out_w
1057
+
1058
+ # vertical
1059
+ fixed_total = 0.0
1060
+ flex_weights = []
1061
+ item_fixed_h: list[float | None] = []
1062
+ for item in self.ht_list:
1063
+ if isinstance(item, HeatmapAnnotation):
1064
+ h_mm = convertHeight(item.height, "mm", valueOnly=True)
1065
+ item_fixed_h.append(h_mm)
1066
+ fixed_total += h_mm
1067
+ else:
1068
+ if is_abs_unit(item.heatmap_param["height"]):
1069
+ h_mm = convertHeight(item.heatmap_param["height"], "mm", valueOnly=True)
1070
+ item_fixed_h.append(h_mm)
1071
+ fixed_total += h_mm
1072
+ elif is_abs_unit(item.matrix_param["height"]):
1073
+ hs = item.component_heights_mm()
1074
+ h_mm = sum(x or 0.0 for x in hs)
1075
+ item_fixed_h.append(h_mm)
1076
+ fixed_total += h_mm
1077
+ else:
1078
+ hs = item.component_heights_mm()
1079
+ fixed_non_body = sum(x or 0.0 for x in hs)
1080
+ fixed_total += fixed_non_body
1081
+ item_fixed_h.append(None)
1082
+ flex_weights.append(float(max(1, item.nrow)))
1083
+
1084
+ rem = max(0.0, avail_h_mm - total_gap - fixed_total)
1085
+ tot_wt = sum(flex_weights)
1086
+ out_h: list[float] = []
1087
+ f_idx = 0
1088
+ for i, item in enumerate(self.ht_list):
1089
+ if item_fixed_h[i] is not None:
1090
+ out_h.append(float(item_fixed_h[i]))
1091
+ else:
1092
+ wt = flex_weights[f_idx]
1093
+ f_idx += 1
1094
+ hs = item.component_heights_mm()
1095
+ fixed_non_body = sum(x or 0.0 for x in hs)
1096
+ body_h = rem * (wt / tot_wt) if tot_wt > 0 else 0.0
1097
+ out_h.append(fixed_non_body + body_h)
1098
+ return out_h
1099
+
1100
+ def _draw_standalone_annotation(self, anno: HeatmapAnnotation, body_start_mm: float, body_len_mm: float) -> None:
1101
+ i_main = self.ht_list_param["main_heatmap"]
1102
+ ht_main = self.ht_list[i_main] if i_main is not None else None
1103
+ prev_ht = _ENV.current_heatmap
1104
+ _ENV.current_heatmap = ht_main
1105
+ try:
1106
+ if self.direction == "horizontal":
1107
+ # rowAnnotation placed aligned vertically with heatmap_body band
1108
+ if ht_main is not None and isinstance(ht_main, Heatmap):
1109
+ ro_lt = ht_main.row_order_list
1110
+ slice_y, slice_h = _calc_slice_layout([len(s) for s in ro_lt], ht_main.matrix_param["row_gap"], "y")
1111
+ pushViewport(Viewport(x=unit(0, "npc"), y=unit(body_start_mm, "mm"), width=unit(1, "npc"), height=unit(body_len_mm, "mm"), just=("left", "top")))
1112
+ try:
1113
+ for kr, idx_s in enumerate(ro_lt, start=1):
1114
+ anno.draw(index=idx_s, k=kr, n=len(ro_lt), x=unit(0.5, "npc"), y=slice_y[kr - 1], width=unit(1, "npc"), height=slice_h[kr - 1], just=("center", "top"))
1115
+ finally:
1116
+ popViewport()
1117
+ else:
1118
+ n = anno.nobs() or 1
1119
+ anno.draw(index=list(range(n)), k=1, n=1, x=unit(0.5, "npc"), y=unit(0.5, "npc"), width=unit(1, "npc"), height=unit(1, "npc"))
1120
+ else:
1121
+ # columnAnnotation placed aligned horizontally with heatmap_body band
1122
+ if ht_main is not None and isinstance(ht_main, Heatmap):
1123
+ co_lt = ht_main.column_order_list
1124
+ slice_x, slice_w = _calc_slice_layout([len(s) for s in co_lt], ht_main.matrix_param["column_gap"], "x")
1125
+ pushViewport(Viewport(x=unit(body_start_mm, "mm"), y=unit(0, "npc"), width=unit(body_len_mm, "mm"), height=unit(1, "npc"), just=("left", "bottom")))
1126
+ try:
1127
+ for kc, idx_s in enumerate(co_lt, start=1):
1128
+ anno.draw(index=idx_s, k=kc, n=len(co_lt), x=slice_x[kc - 1], y=unit(0.5, "npc"), width=slice_w[kc - 1], height=unit(1, "npc"), just=("left", "center"))
1129
+ finally:
1130
+ popViewport()
1131
+ else:
1132
+ n = anno.nobs() or 1
1133
+ anno.draw(index=list(range(n)), k=1, n=1, x=unit(0.5, "npc"), y=unit(0.5, "npc"), width=unit(1, "npc"), height=unit(1, "npc"))
1134
+ finally:
1135
+ _ENV.current_heatmap = prev_ht
1136
+
1137
+ # ---- Canvas Drawing ----
1138
+
1139
+ def draw(
1140
+ self,
1141
+ *,
1142
+ newpage: bool = True,
1143
+ background: str = "white",
1144
+ padding: Any = None,
1145
+ width: float | None = None,
1146
+ height: float | None = None,
1147
+ fig: Any = None,
1148
+ dpi: float = 100.0,
1149
+ save: str | None = None,
1150
+ show: bool = False,
1151
+ post_fun: Callable[..., Any] | None = None,
1152
+ **layout_kwargs: Any,
1153
+ ) -> "HeatmapList":
1154
+ # Default figure dimensions in inches (~ 8x7 in unless user provides size or existing device)
1155
+ if fig is not None:
1156
+ dev = grid_newpage(dpi=dpi, fig=fig) if newpage else current_device()
1157
+ elif newpage:
1158
+ w_in = float(width) if width is not None else 8.0
1159
+ h_in = float(height) if height is not None else 6.5
1160
+ dev = grid_newpage(width_in=w_in, height_in=h_in, dpi=dpi)
1161
+ else:
1162
+ dev = current_device()
1163
+
1164
+ page_w_mm = dev.width_mm
1165
+ page_h_mm = dev.height_mm
1166
+
1167
+ prepared = self.make_layout(padding=padding, page_size_mm=(page_w_mm, page_h_mm), **layout_kwargs)
1168
+ prepared._device = dev
1169
+
1170
+ # Fill canvas background
1171
+ if background and str(background).lower() != "transparent":
1172
+ grid_rect(gp=gpar(fill=background, col=None))
1173
+
1174
+ pad_mm = _normalize_padding(prepared.ht_list_param["padding"]) # [bottom, left, top, right]
1175
+ global_w_mm = max(10.0, page_w_mm - pad_mm[1] - pad_mm[3])
1176
+ global_h_mm = max(10.0, page_h_mm - pad_mm[0] - pad_mm[2])
1177
+
1178
+ pushViewport(
1179
+ Viewport(
1180
+ name="global",
1181
+ x=unit(pad_mm[1], "mm"),
1182
+ y=unit(pad_mm[0], "mm"),
1183
+ width=unit(global_w_mm, "mm"),
1184
+ height=unit(global_h_mm, "mm"),
1185
+ just=("left", "bottom"),
1186
+ )
1187
+ )
1188
+ try:
1189
+ ls = prepared.layout["layout_size"]
1190
+ hl_pad = prepared.layout["heatmap_list_padding"]
1191
+
1192
+ # 7 outer column widths (left -> right) and 7 outer row heights (top -> bottom)
1193
+ col_fixed = [
1194
+ convertWidth(ls[f"{c}_width"], "mm", valueOnly=True) if c != "heatmap_list" else None
1195
+ for c in HEATMAP_LIST_ROW_COMPONENTS
1196
+ ]
1197
+ row_fixed = [
1198
+ convertHeight(ls[f"{r}_height"], "mm", valueOnly=True) if r != "heatmap_list" else None
1199
+ for r in HEATMAP_LIST_COLUMN_COMPONENTS
1200
+ ]
1201
+
1202
+ hl_w_mm = max(10.0, global_w_mm - sum(v for v in col_fixed if v is not None))
1203
+ hl_h_mm = max(10.0, global_h_mm - sum(v for v in row_fixed if v is not None))
1204
+ final_cols = [hl_w_mm if v is None else v for v in col_fixed]
1205
+ final_rows = [hl_h_mm if v is None else v for v in row_fixed]
1206
+
1207
+ x_cols = [0.0] * 7
1208
+ cx = 0.0
1209
+ for c_i in range(7):
1210
+ x_cols[c_i] = cx
1211
+ cx += final_cols[c_i]
1212
+
1213
+ y_rows_top = [0.0] * 7
1214
+ cy = sum(final_rows)
1215
+ for r_i in range(7):
1216
+ y_rows_top[r_i] = cy
1217
+ cy -= final_rows[r_i]
1218
+
1219
+ # Inner heatmap_list box (row=3, col=3) minus annotation extended padding
1220
+ hl_x = x_cols[3] + hl_pad[1]
1221
+ hl_y_top = y_rows_top[3] - hl_pad[2]
1222
+ inner_w = max(5.0, final_cols[3] - hl_pad[1] - hl_pad[3])
1223
+ inner_h = max(5.0, final_rows[3] - hl_pad[0] - hl_pad[2])
1224
+
1225
+ # Locate heatmap_body perpendicular band for aligning standalone annotations & centering legends
1226
+ i_main = prepared.ht_list_param["main_heatmap"]
1227
+ body_top_rel = inner_h
1228
+ body_h_mm = inner_h
1229
+ body_left_rel = 0.0
1230
+ body_w_mm = inner_w
1231
+
1232
+ # Draw heatmap_list items
1233
+ pushViewport(
1234
+ Viewport(
1235
+ name="heatmap_list",
1236
+ x=unit(hl_x, "mm"),
1237
+ y=unit(hl_y_top, "mm"),
1238
+ width=unit(inner_w, "mm"),
1239
+ height=unit(inner_h, "mm"),
1240
+ just=("left", "top"),
1241
+ )
1242
+ )
1243
+ try:
1244
+ if prepared.ht_list:
1245
+ spans = prepared._compute_heatmap_list_spans(inner_w, inner_h)
1246
+ gaps_mm = prepared.ht_list_param["ht_gap"].to_mm("x")
1247
+
1248
+ if i_main is not None:
1249
+ ht_main = prepared.ht_list[i_main]
1250
+ assert isinstance(ht_main, Heatmap)
1251
+ if prepared.direction == "horizontal":
1252
+ hs_main = ht_main.component_heights_mm()
1253
+ fixed_h = sum(x for x in hs_main if x is not None)
1254
+ body_h_mm = max(0.0, inner_h - fixed_h) if hs_main[4] is None else hs_main[4]
1255
+ body_top_rel = inner_h - sum(x or 0.0 for x in hs_main[:4])
1256
+ else:
1257
+ ws_main = ht_main.component_widths_mm()
1258
+ fixed_w = sum(x for x in ws_main if x is not None)
1259
+ body_w_mm = max(0.0, inner_w - fixed_w) if ws_main[4] is None else ws_main[4]
1260
+ body_left_rel = sum(x or 0.0 for x in ws_main[:4])
1261
+
1262
+ if prepared.direction == "horizontal":
1263
+ cur_x = 0.0
1264
+ for idx_it, item in enumerate(prepared.ht_list):
1265
+ sp_w = spans[idx_it]
1266
+ pushViewport(Viewport(x=unit(cur_x, "mm"), y=unit(inner_h, "mm"), width=unit(sp_w, "mm"), height=unit(inner_h, "mm"), just=("left", "top")))
1267
+ try:
1268
+ if isinstance(item, Heatmap):
1269
+ item.draw_in_viewport()
1270
+ else:
1271
+ prepared._draw_standalone_annotation(item, body_top_rel, body_h_mm)
1272
+ finally:
1273
+ popViewport()
1274
+ if idx_it < len(prepared.ht_list) - 1:
1275
+ cur_x += sp_w + float(gaps_mm[idx_it])
1276
+ else:
1277
+ cur_y_top = inner_h
1278
+ for idx_it, item in enumerate(prepared.ht_list):
1279
+ sp_h = spans[idx_it]
1280
+ pushViewport(Viewport(x=unit(0.0, "mm"), y=unit(cur_y_top, "mm"), width=unit(inner_w, "mm"), height=unit(sp_h, "mm"), just=("left", "top")))
1281
+ try:
1282
+ if isinstance(item, Heatmap):
1283
+ item.draw_in_viewport()
1284
+ else:
1285
+ prepared._draw_standalone_annotation(item, body_left_rel, body_w_mm)
1286
+ finally:
1287
+ popViewport()
1288
+ if idx_it < len(prepared.ht_list) - 1:
1289
+ cur_y_top -= sp_h + float(gaps_mm[idx_it])
1290
+ finally:
1291
+ popViewport()
1292
+
1293
+ # Draw global column title
1294
+ if prepared.column_title:
1295
+ ct_side = prepared.column_title_param["side"]
1296
+ r_ct = 2 if ct_side == "top" else 4
1297
+ pushViewport(Viewport(name=f"global_column_title_{ct_side}", x=unit(x_cols[3], "mm"), y=unit(y_rows_top[r_ct], "mm"), width=unit(final_cols[3], "mm"), height=unit(final_rows[r_ct], "mm"), just=("left", "top")))
1298
+ try:
1299
+ ct_gp = prepared.column_title_param["gp"]
1300
+ pad_c = _title_padding_unit(ct_gp)
1301
+ if ct_side == "top":
1302
+ grid_text(prepared.column_title[0], x=unit(0.5, "npc"), y=pad_c[0], just="bottom", gp=ct_gp)
1303
+ else:
1304
+ grid_text(prepared.column_title[0], x=unit(0.5, "npc"), y=unit(1, "npc") - pad_c[0], just="top", gp=ct_gp)
1305
+ finally:
1306
+ popViewport()
1307
+
1308
+ # Draw global row title
1309
+ if prepared.row_title:
1310
+ rt_side = prepared.row_title_param["side"]
1311
+ c_rt = 2 if rt_side == "left" else 4
1312
+ pushViewport(Viewport(name=f"global_row_title_{rt_side}", x=unit(x_cols[c_rt], "mm"), y=unit(y_rows_top[3], "mm"), width=unit(final_cols[c_rt], "mm"), height=unit(final_rows[3], "mm"), just=("left", "top")))
1313
+ try:
1314
+ rt_gp = prepared.row_title_param["gp"]
1315
+ pad_r = _title_padding_unit(rt_gp)
1316
+ rot_r = 90.0 if rt_side == "left" else 270.0
1317
+ if rt_side == "left":
1318
+ grid_text(prepared.row_title[0], x=unit(1, "npc") - pad_r[0], y=unit(0.5, "npc"), rot=rot_r, just="center", gp=rt_gp)
1319
+ else:
1320
+ grid_text(prepared.row_title[0], x=pad_r[0], y=unit(0.5, "npc"), rot=rot_r, just="center", gp=rt_gp)
1321
+ finally:
1322
+ popViewport()
1323
+
1324
+ # Draw heatmap & annotation legends in outer slots
1325
+ def _draw_outer_legend(leg_param: dict[str, Any], is_heatmap: bool) -> None:
1326
+ if not leg_param.get("show") or leg_param.get("packed") is None:
1327
+ return
1328
+ side = leg_param["side"]
1329
+ packed: Legends = leg_param["packed"]
1330
+ pad_l = float(leg_param.get("padding_mm", 2.0))
1331
+ if side == "right":
1332
+ c_idx = 5 if is_heatmap else 6
1333
+ r_idx = 3
1334
+ y_ref = y_rows_top[3] - inner_h + body_top_rel - 0.5 * body_h_mm
1335
+ x_ref = x_cols[c_idx] + pad_l
1336
+ pushViewport(Viewport(x=unit(x_ref, "mm"), y=unit(y_ref, "mm"), width=unit(max(1.0, final_cols[c_idx] - pad_l), "mm"), height=unit(final_rows[r_idx], "mm"), just=("left", "center")))
1337
+ try:
1338
+ packed.draw(x=unit(0, "npc"), y=unit(0.5, "npc"), just="left")
1339
+ finally:
1340
+ popViewport()
1341
+ elif side == "left":
1342
+ c_idx = 1 if is_heatmap else 0
1343
+ r_idx = 3
1344
+ y_ref = y_rows_top[3] - inner_h + body_top_rel - 0.5 * body_h_mm
1345
+ x_ref = x_cols[c_idx] + final_cols[c_idx] - pad_l
1346
+ pushViewport(Viewport(x=unit(x_ref, "mm"), y=unit(y_ref, "mm"), width=unit(max(1.0, final_cols[c_idx] - pad_l), "mm"), height=unit(final_rows[r_idx], "mm"), just=("right", "center")))
1347
+ try:
1348
+ packed.draw(x=unit(1, "npc"), y=unit(0.5, "npc"), just="right")
1349
+ finally:
1350
+ popViewport()
1351
+ elif side == "top":
1352
+ c_idx = 3
1353
+ r_idx = 1 if is_heatmap else 0
1354
+ x_ref = x_cols[3] + body_left_rel + 0.5 * body_w_mm
1355
+ y_ref = y_rows_top[r_idx] - final_rows[r_idx] + pad_l
1356
+ pushViewport(Viewport(x=unit(x_ref, "mm"), y=unit(y_ref, "mm"), width=unit(final_cols[c_idx], "mm"), height=unit(max(1.0, final_rows[r_idx] - pad_l), "mm"), just=("center", "bottom")))
1357
+ try:
1358
+ packed.draw(x=unit(0.5, "npc"), y=unit(0, "npc"), just="bottom")
1359
+ finally:
1360
+ popViewport()
1361
+ else: # bottom
1362
+ c_idx = 3
1363
+ r_idx = 5 if is_heatmap else 6
1364
+ x_ref = x_cols[3] + body_left_rel + 0.5 * body_w_mm
1365
+ y_ref = y_rows_top[r_idx] - pad_l
1366
+ pushViewport(Viewport(x=unit(x_ref, "mm"), y=unit(y_ref, "mm"), width=unit(final_cols[c_idx], "mm"), height=unit(max(1.0, final_rows[r_idx] - pad_l), "mm"), just=("center", "top")))
1367
+ try:
1368
+ packed.draw(x=unit(0.5, "npc"), y=unit(1, "npc"), just="top")
1369
+ finally:
1370
+ popViewport()
1371
+
1372
+ _draw_outer_legend(prepared.heatmap_legend_param, is_heatmap=True)
1373
+ _draw_outer_legend(prepared.annotation_legend_param, is_heatmap=False)
1374
+
1375
+ # Run any per-heatmap post_fun and top-level post_fun
1376
+ for item in prepared.ht_list:
1377
+ if isinstance(item, Heatmap) and item.heatmap_param.get("post_fun") is not None:
1378
+ item.heatmap_param["post_fun"](prepared)
1379
+ if post_fun is not None:
1380
+ post_fun(prepared)
1381
+ finally:
1382
+ popViewport()
1383
+
1384
+ _ENV.last = prepared
1385
+ if save is not None:
1386
+ dev.fig.savefig(save, dpi=dpi, facecolor=dev.fig.get_facecolor())
1387
+ if show:
1388
+ import matplotlib.pyplot as plt
1389
+ plt.show()
1390
+ return prepared
1391
+
1392
+ def show(self) -> "HeatmapList":
1393
+ return self.draw()
1394
+
1395
+ def summary(self) -> str:
1396
+ lines = [f"A HeatmapList ({self.direction}) with {len(self.ht_list)} component(s):"]
1397
+ for i, item in enumerate(self.ht_list):
1398
+ if isinstance(item, Heatmap):
1399
+ lines.append(f" [{i}] Heatmap {item.name!r}: {item.nrow} x {item.ncol}")
1400
+ else:
1401
+ lines.append(f" [{i}] HeatmapAnnotation {item.name!r}: which={item.which}, len={len(item)}")
1402
+ txt = "\n".join(lines)
1403
+ print(txt)
1404
+ return txt
1405
+
1406
+ def _repr_png_(self) -> bytes:
1407
+ import io
1408
+ import matplotlib.pyplot as plt
1409
+ res = self.draw(show=False)
1410
+ buf = io.BytesIO()
1411
+ res._device.fig.savefig(buf, format="png", dpi=120)
1412
+ plt.close(res._device.fig)
1413
+ return buf.getvalue()
1414
+
1415
+ def __repr__(self) -> str:
1416
+ return f"HeatmapList(direction={self.direction!r}, components={self.names})"
1417
+
1418
+
1419
+ # ---- Top-level Dispatchers & Accessors ----
1420
+
1421
+ def draw(object: Any, **kwargs: Any) -> Any:
1422
+ """Draw a Heatmap, HeatmapList, HeatmapAnnotation, SingleAnnotation, AnnotationFunction, Legends, or Grob."""
1423
+ if isinstance(object, (Heatmap, HeatmapList)):
1424
+ return object.draw(**kwargs)
1425
+ if hasattr(object, "draw") and callable(object.draw):
1426
+ return object.draw(**kwargs)
1427
+ raise TypeError(f"Object of type {type(object).__name__} cannot be drawn.")
1428
+
1429
+
1430
+ def ht_size(ht_list: Heatmap | HeatmapList, unit_name: str = "mm", valueOnly: bool = False) -> Any:
1431
+ """Return total width and height of a Heatmap or HeatmapList."""
1432
+ hl = HeatmapList([ht_list]) if isinstance(ht_list, Heatmap) else ht_list
1433
+ prep = hl if hl.layout["initialized"] else hl.make_layout()
1434
+ ls = prep.layout["layout_size"]
1435
+ hl_pad = prep.layout["heatmap_list_padding"]
1436
+ w_outer = sum(convertWidth(ls[f"{c}_width"], "mm", valueOnly=True) for c in HEATMAP_LIST_ROW_COMPONENTS if c != "heatmap_list")
1437
+ h_outer = sum(convertHeight(ls[f"{r}_height"], "mm", valueOnly=True) for r in HEATMAP_LIST_COLUMN_COMPONENTS if r != "heatmap_list")
1438
+
1439
+ gaps_mm = prep.ht_list_param["ht_gap"].to_mm("x")
1440
+ n = len(prep.ht_list)
1441
+ gap_sum = sum(float(gaps_mm[i]) for i in range(max(0, n - 1)))
1442
+
1443
+ if prep.direction == "horizontal":
1444
+ w_in = gap_sum + hl_pad[1] + hl_pad[3]
1445
+ h_in = hl_pad[0] + hl_pad[2]
1446
+ for item in prep.ht_list:
1447
+ if isinstance(item, Heatmap):
1448
+ ws = item.component_widths_mm()
1449
+ hs = item.component_heights_mm()
1450
+ w_in += sum(x if x is not None else max(10.0, item.ncol * 4.0) for x in ws)
1451
+ h_in = max(h_in, sum(x if x is not None else max(10.0, item.nrow * 4.0) for x in hs) + hl_pad[0] + hl_pad[2])
1452
+ else:
1453
+ w_in += convertWidth(item.width, "mm", valueOnly=True)
1454
+ else:
1455
+ w_in = hl_pad[1] + hl_pad[3]
1456
+ h_in = gap_sum + hl_pad[0] + hl_pad[2]
1457
+ for item in prep.ht_list:
1458
+ if isinstance(item, Heatmap):
1459
+ ws = item.component_widths_mm()
1460
+ hs = item.component_heights_mm()
1461
+ w_in = max(w_in, sum(x if x is not None else max(10.0, item.ncol * 4.0) for x in ws) + hl_pad[1] + hl_pad[3])
1462
+ h_in += sum(x if x is not None else max(10.0, item.nrow * 4.0) for x in hs)
1463
+ else:
1464
+ h_in += convertHeight(item.height, "mm", valueOnly=True)
1465
+
1466
+ tot_w = w_outer + w_in
1467
+ tot_h = h_outer + h_in
1468
+ u = unit([tot_w, tot_h], "mm")
1469
+ if valueOnly:
1470
+ return [convertWidth(unit(tot_w, "mm"), unit_name, valueOnly=True), convertHeight(unit(tot_h, "mm"), unit_name, valueOnly=True)]
1471
+ if unit_name == "mm":
1472
+ return u
1473
+ return unit(
1474
+ [convertWidth(unit(tot_w, "mm"), unit_name, valueOnly=True), convertHeight(unit(tot_h, "mm"), unit_name, valueOnly=True)],
1475
+ unit_name,
1476
+ )
1477
+
1478
+
1479
+ def _get_target_heatmap(obj: Heatmap | HeatmapList, name: str | int | None = None) -> list[Heatmap]:
1480
+ if isinstance(obj, Heatmap):
1481
+ if not obj.layout["initialized"]:
1482
+ obj.prepare()
1483
+ return [obj]
1484
+ if isinstance(obj, HeatmapList):
1485
+ if not obj.layout["initialized"]:
1486
+ obj = obj.make_layout()
1487
+ hms = [x for x in obj.ht_list if isinstance(x, Heatmap) and not x.name.startswith("_scaffold_")]
1488
+ if name is not None:
1489
+ if isinstance(name, (int, np.integer)):
1490
+ return [hms[int(name)]]
1491
+ return [h for h in hms if h.name == str(name)]
1492
+ return hms
1493
+ raise TypeError(f"Expected Heatmap or HeatmapList, got {type(obj).__name__}.")
1494
+
1495
+
1496
+ def row_order(object: Heatmap | HeatmapList, name: str | int | None = None) -> Any:
1497
+ """Return ordered 0-based row indices from a Heatmap or HeatmapList."""
1498
+ if isinstance(object, Heatmap):
1499
+ if not object.layout["initialized"]:
1500
+ object.prepare()
1501
+ return object.row_order_list[0] if len(object.row_order_list) == 1 else list(object.row_order_list)
1502
+
1503
+ if isinstance(object, HeatmapList):
1504
+ hms = _get_target_heatmap(object, name=name)
1505
+ if not hms:
1506
+ return []
1507
+ if object.direction == "horizontal" or name is not None or len(hms) == 1:
1508
+ hm = hms[0]
1509
+ return hm.row_order_list[0] if len(hm.row_order_list) == 1 else list(hm.row_order_list)
1510
+ return {hm.name: (hm.row_order_list[0] if len(hm.row_order_list) == 1 else list(hm.row_order_list)) for hm in hms}
1511
+ raise TypeError(f"Unsupported type for `row_order`: {type(object).__name__}")
1512
+
1513
+
1514
+ def column_order(object: Heatmap | HeatmapList, name: str | int | None = None) -> Any:
1515
+ """Return ordered 0-based column indices from a Heatmap or HeatmapList."""
1516
+ if isinstance(object, Heatmap):
1517
+ if not object.layout["initialized"]:
1518
+ object.prepare()
1519
+ return object.column_order_list[0] if len(object.column_order_list) == 1 else list(object.column_order_list)
1520
+
1521
+ if isinstance(object, HeatmapList):
1522
+ hms = _get_target_heatmap(object, name=name)
1523
+ if not hms:
1524
+ return []
1525
+ if object.direction == "vertical" or name is not None or len(hms) == 1:
1526
+ hm = hms[0]
1527
+ return hm.column_order_list[0] if len(hm.column_order_list) == 1 else list(hm.column_order_list)
1528
+ return {hm.name: (hm.column_order_list[0] if len(hm.column_order_list) == 1 else list(hm.column_order_list)) for hm in hms}
1529
+ raise TypeError(f"Unsupported type for `column_order`: {type(object).__name__}")
1530
+
1531
+
1532
+ def row_dend(object: Heatmap | HeatmapList, name: str | int | None = None, on_slice: bool = False) -> Any:
1533
+ """Return row Dendrogram(s) from a Heatmap or HeatmapList."""
1534
+ if isinstance(object, Heatmap):
1535
+ if not object.layout["initialized"]:
1536
+ object.prepare()
1537
+ if on_slice:
1538
+ return object.row_dend_slice
1539
+ return object.row_dend_list[0] if len(object.row_dend_list) == 1 else list(object.row_dend_list)
1540
+
1541
+ hms = _get_target_heatmap(object, name=name)
1542
+ if not hms:
1543
+ return None
1544
+ if object.direction == "horizontal" or name is not None or len(hms) == 1:
1545
+ hm = hms[0]
1546
+ if on_slice:
1547
+ return hm.row_dend_slice
1548
+ return hm.row_dend_list[0] if len(hm.row_dend_list) == 1 else list(hm.row_dend_list)
1549
+ return {hm.name: (hm.row_dend_slice if on_slice else (hm.row_dend_list[0] if len(hm.row_dend_list) == 1 else list(hm.row_dend_list))) for hm in hms}
1550
+
1551
+
1552
+ def column_dend(object: Heatmap | HeatmapList, name: str | int | None = None, on_slice: bool = False) -> Any:
1553
+ """Return column Dendrogram(s) from a Heatmap or HeatmapList."""
1554
+ if isinstance(object, Heatmap):
1555
+ if not object.layout["initialized"]:
1556
+ object.prepare()
1557
+ if on_slice:
1558
+ return object.column_dend_slice
1559
+ return object.column_dend_list[0] if len(object.column_dend_list) == 1 else list(object.column_dend_list)
1560
+
1561
+ hms = _get_target_heatmap(object, name=name)
1562
+ if not hms:
1563
+ return None
1564
+ if object.direction == "vertical" or name is not None or len(hms) == 1:
1565
+ hm = hms[0]
1566
+ if on_slice:
1567
+ return hm.column_dend_slice
1568
+ return hm.column_dend_list[0] if len(hm.column_dend_list) == 1 else list(hm.column_dend_list)
1569
+ return {hm.name: (hm.column_dend_slice if on_slice else (hm.column_dend_list[0] if len(hm.column_dend_list) == 1 else list(hm.column_dend_list))) for hm in hms}