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.
- ComplexHeatmap.py +7 -0
- complexheatmap/__init__.py +221 -0
- complexheatmap/_base.py +56 -0
- complexheatmap/_options.py +165 -0
- complexheatmap/anno_funcs.py +2781 -0
- complexheatmap/annotations.py +1611 -0
- complexheatmap/colors.py +848 -0
- complexheatmap/data/dmr_summary/cgi_anno.csv +9 -0
- complexheatmap/data/dmr_summary/dist_tss.csv +9 -0
- complexheatmap/data/dmr_summary/gene_anno.csv +9 -0
- complexheatmap/data/dmr_summary/label.csv +9 -0
- complexheatmap/data/dmr_summary/mat_enrich_gf.csv +9 -0
- complexheatmap/data/dmr_summary/mat_enrich_st.csv +9 -0
- complexheatmap/data/dmr_summary/mat_pct_st.csv +9 -0
- complexheatmap/data/dmr_summary/mean_meth.csv +9 -0
- complexheatmap/data/dmr_summary/n_corr.csv +9 -0
- complexheatmap/data/dmr_summary/n_gr.csv +9 -0
- complexheatmap/data/gene_expression.csv +156 -0
- complexheatmap/data/gr.csv +2416 -0
- complexheatmap/data/measles.csv +60 -0
- complexheatmap/data/meth/enhancer.csv +1001 -0
- complexheatmap/data/meth/expr.csv +1001 -0
- complexheatmap/data/meth/meth.csv +1001 -0
- complexheatmap/data/meth/row_meta.csv +1001 -0
- complexheatmap/data/rand_mat.csv +19 -0
- complexheatmap/data/random_meth_expr_data/anno.csv +21 -0
- complexheatmap/data/random_meth_expr_data/anno_states.csv +1001 -0
- complexheatmap/data/random_meth_expr_data/mat_expr.csv +1001 -0
- complexheatmap/data/random_meth_expr_data/mat_meth.csv +1001 -0
- complexheatmap/data/random_meth_expr_data/row_meta.csv +1001 -0
- complexheatmap/data/sample_order.txt +172 -0
- complexheatmap/data/tcga_lung_adenocarcinoma.csv +27 -0
- complexheatmap/decorate.py +159 -0
- complexheatmap/dendrogram.py +937 -0
- complexheatmap/density.py +276 -0
- complexheatmap/genomic.py +348 -0
- complexheatmap/grid.py +1580 -0
- complexheatmap/heatmap.py +2244 -0
- complexheatmap/heatmap_list.py +1569 -0
- complexheatmap/legend.py +992 -0
- complexheatmap/oncoprint.py +488 -0
- complexheatmap/text.py +655 -0
- complexheatmap/three_d.py +188 -0
- complexheatmap/translate.py +338 -0
- complexheatmap/units.py +718 -0
- complexheatmap/upset.py +886 -0
- complexheatmap/utils.py +183 -0
- complexheatmap_py-0.1.0.dist-info/METADATA +96 -0
- complexheatmap_py-0.1.0.dist-info/RECORD +52 -0
- complexheatmap_py-0.1.0.dist-info/WHEEL +5 -0
- complexheatmap_py-0.1.0.dist-info/licenses/LICENSE +24 -0
- complexheatmap_py-0.1.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,1611 @@
|
|
|
1
|
+
"""AnnotationFunction, SingleAnnotation, HeatmapAnnotation, columnAnnotation, rowAnnotation, and Axis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import inspect
|
|
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 _ENV, ht_opt
|
|
14
|
+
from .colors import ColorMapping, default_col, pretty_breaks, to_hex_rgba
|
|
15
|
+
from .grid import (
|
|
16
|
+
GTree,
|
|
17
|
+
Grob,
|
|
18
|
+
Viewport,
|
|
19
|
+
current_viewport,
|
|
20
|
+
grid_draw,
|
|
21
|
+
grid_newpage,
|
|
22
|
+
grid_rect,
|
|
23
|
+
grid_text,
|
|
24
|
+
linesGrob,
|
|
25
|
+
popViewport,
|
|
26
|
+
pushViewport,
|
|
27
|
+
segmentsGrob,
|
|
28
|
+
textGrob,
|
|
29
|
+
)
|
|
30
|
+
from .units import (
|
|
31
|
+
Gpar,
|
|
32
|
+
Unit,
|
|
33
|
+
as_unit,
|
|
34
|
+
check_gp,
|
|
35
|
+
convertHeight,
|
|
36
|
+
convertWidth,
|
|
37
|
+
gpar,
|
|
38
|
+
is_abs_unit,
|
|
39
|
+
recycle_gp,
|
|
40
|
+
subset_gp,
|
|
41
|
+
unit,
|
|
42
|
+
unit_c,
|
|
43
|
+
unit_sum,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def subset_vector(x: Any, i: Any) -> Any:
|
|
48
|
+
if isinstance(x, Unit):
|
|
49
|
+
return x[i]
|
|
50
|
+
if isinstance(x, np.ndarray):
|
|
51
|
+
return x[i]
|
|
52
|
+
if isinstance(x, (list, tuple)):
|
|
53
|
+
if isinstance(i, slice):
|
|
54
|
+
return list(x)[i]
|
|
55
|
+
if isinstance(i, (int, np.integer)):
|
|
56
|
+
return [x[int(i)]]
|
|
57
|
+
arr_i = np.asarray(i)
|
|
58
|
+
if arr_i.dtype == bool:
|
|
59
|
+
return [v for v, f in zip(x, arr_i) if f]
|
|
60
|
+
return [x[int(k)] for k in arr_i]
|
|
61
|
+
if hasattr(x, "iloc"):
|
|
62
|
+
return x.iloc[i]
|
|
63
|
+
return x
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def subset_matrix_by_row(x: Any, i: Any) -> Any:
|
|
67
|
+
arr = np.asarray(x)
|
|
68
|
+
if isinstance(i, (int, np.integer)):
|
|
69
|
+
return arr[[int(i)], :]
|
|
70
|
+
return arr[i, :]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def subset_no(x: Any, i: Any) -> Any:
|
|
74
|
+
return x
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def subset_by_intersect(x: Any, i: Any) -> list[Any]:
|
|
78
|
+
s = set(int(v) for v in i)
|
|
79
|
+
return [v for v in x if int(v) in s]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def anno_width_and_height(
|
|
83
|
+
which: str,
|
|
84
|
+
width: Unit | None = None,
|
|
85
|
+
height: Unit | None = None,
|
|
86
|
+
default: Unit = unit(10, "mm"),
|
|
87
|
+
) -> dict[str, Unit]:
|
|
88
|
+
if which == "column":
|
|
89
|
+
if height is None:
|
|
90
|
+
height = default
|
|
91
|
+
else:
|
|
92
|
+
height = as_unit(height, "mm")
|
|
93
|
+
if not is_abs_unit(height):
|
|
94
|
+
raise ValueError("Height of a column annotation must be an absolute unit.")
|
|
95
|
+
if width is None:
|
|
96
|
+
width = unit(1.0, "npc")
|
|
97
|
+
else:
|
|
98
|
+
width = as_unit(width, "npc")
|
|
99
|
+
elif which == "row":
|
|
100
|
+
if width is None:
|
|
101
|
+
width = default
|
|
102
|
+
else:
|
|
103
|
+
width = as_unit(width, "mm")
|
|
104
|
+
if not is_abs_unit(width):
|
|
105
|
+
raise ValueError("Width of a row annotation must be an absolute unit.")
|
|
106
|
+
if height is None:
|
|
107
|
+
height = unit(1.0, "npc")
|
|
108
|
+
else:
|
|
109
|
+
height = as_unit(height, "npc")
|
|
110
|
+
else:
|
|
111
|
+
raise ValueError(f"`which` must be 'column' or 'row', got {which!r}")
|
|
112
|
+
return {"width": width, "height": height}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ---- Axis System ----
|
|
116
|
+
|
|
117
|
+
def default_axis_param(which: str = "column") -> dict[str, Any]:
|
|
118
|
+
which = which.lower()
|
|
119
|
+
return {
|
|
120
|
+
"at": None,
|
|
121
|
+
"labels": None,
|
|
122
|
+
"labels_rot": 0 if which == "column" else 90,
|
|
123
|
+
"gp": gpar(fontsize=8),
|
|
124
|
+
"side": "left" if which == "column" else "bottom",
|
|
125
|
+
"facing": "outside",
|
|
126
|
+
"direction": "normal",
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def validate_axis_param(axis_param: dict[str, Any] | None, which: str) -> dict[str, Any]:
|
|
131
|
+
d = default_axis_param(which)
|
|
132
|
+
if axis_param:
|
|
133
|
+
for k, v in axis_param.items():
|
|
134
|
+
d[k] = v
|
|
135
|
+
d["gp"] = check_gp(d.get("gp"))
|
|
136
|
+
if "fontsize" not in d["gp"]:
|
|
137
|
+
d["gp"]["fontsize"] = 8.0
|
|
138
|
+
if which == "column" and d["side"] not in ("left", "right"):
|
|
139
|
+
raise ValueError("For column annotation, `axis_param['side']` must be 'left' or 'right'.")
|
|
140
|
+
if which == "row" and d["side"] not in ("top", "bottom"):
|
|
141
|
+
raise ValueError("For row annotation, `axis_param['side']` must be 'top' or 'bottom'.")
|
|
142
|
+
if d["facing"] not in ("outside", "inside"):
|
|
143
|
+
raise ValueError("`axis_param['facing']` must be 'outside' or 'inside'.")
|
|
144
|
+
if d["direction"] not in ("normal", "reverse"):
|
|
145
|
+
raise ValueError("`axis_param['direction']` must be 'normal' or 'reverse'.")
|
|
146
|
+
return d
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def annotation_axis_grob(
|
|
150
|
+
at: Sequence[float] | None = None,
|
|
151
|
+
labels: Sequence[Any] | None = None,
|
|
152
|
+
labels_rot: float = 0.0,
|
|
153
|
+
gp: dict[str, Any] | None = None,
|
|
154
|
+
side: str = "left",
|
|
155
|
+
facing: str = "outside",
|
|
156
|
+
direction: str = "normal",
|
|
157
|
+
scale: Sequence[float] | None = None,
|
|
158
|
+
) -> GTree:
|
|
159
|
+
"""Build an `annotation_axis` grob with ticks and labels."""
|
|
160
|
+
if side not in ("left", "right", "top", "bottom"):
|
|
161
|
+
raise ValueError("`side` must be 'left', 'right', 'top', or 'bottom'.")
|
|
162
|
+
if facing not in ("inside", "outside"):
|
|
163
|
+
raise ValueError("`facing` must be 'inside' or 'outside'.")
|
|
164
|
+
if direction not in ("normal", "reverse"):
|
|
165
|
+
raise ValueError("`direction` must be 'normal' or 'reverse'.")
|
|
166
|
+
|
|
167
|
+
gp_d = check_gp(gp)
|
|
168
|
+
if scale is None:
|
|
169
|
+
vp = current_viewport()
|
|
170
|
+
scale = vp.xscale if side in ("top", "bottom") else vp.yscale
|
|
171
|
+
sc = (float(scale[0]), float(scale[1]))
|
|
172
|
+
|
|
173
|
+
if at is None:
|
|
174
|
+
at_vals = pretty_breaks(sc, n=3)
|
|
175
|
+
lo, hi = min(sc), max(sc)
|
|
176
|
+
at_vals = at_vals[(at_vals >= lo - 1e-12) & (at_vals <= hi + 1e-12)]
|
|
177
|
+
if len(at_vals) <= 2:
|
|
178
|
+
at_vals = pretty_breaks(sc, n=5)
|
|
179
|
+
at_vals = at_vals[(at_vals >= lo - 1e-12) & (at_vals <= hi + 1e-12)]
|
|
180
|
+
else:
|
|
181
|
+
at_vals = np.atleast_1d(np.asarray(at, dtype=float))
|
|
182
|
+
|
|
183
|
+
lbls = [f"{v:g}" for v in at_vals] if labels is None else [str(v) for v in labels]
|
|
184
|
+
|
|
185
|
+
if direction == "reverse":
|
|
186
|
+
at_pos = sc[1] - at_vals + sc[0]
|
|
187
|
+
else:
|
|
188
|
+
at_pos = at_vals
|
|
189
|
+
|
|
190
|
+
rot = float(labels_rot) % 360.0
|
|
191
|
+
children: list[Grob] = []
|
|
192
|
+
|
|
193
|
+
if side == "left" and facing == "inside":
|
|
194
|
+
txt_g = textGrob(lbls, unit(2, "mm"), at_pos, default_units="native", rot=0, just="left", gp=gp_d)
|
|
195
|
+
# Note x is 2mm, y is native
|
|
196
|
+
txt_g = textGrob(lbls, unit(2, "mm"), unit(at_pos, "native"), rot=0, just="left", gp=gp_d)
|
|
197
|
+
children = [
|
|
198
|
+
linesGrob(unit([0, 0], "npc"), unit([0, 1], "npc"), gp=gp_d),
|
|
199
|
+
segmentsGrob(unit(np.ones(len(at_pos)), "mm"), unit(at_pos, "native"), unit(np.zeros(len(at_pos)), "npc"), unit(at_pos, "native"), gp=gp_d),
|
|
200
|
+
txt_g,
|
|
201
|
+
]
|
|
202
|
+
w = unit(max((textGrob(l, gp=gp_d).width_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
203
|
+
h = unit(1.0, "npc")
|
|
204
|
+
elif side == "left" and facing == "outside":
|
|
205
|
+
txt_g = textGrob(lbls, unit(-2, "mm"), unit(at_pos, "native"), rot=0, just="right", gp=gp_d)
|
|
206
|
+
children = [
|
|
207
|
+
linesGrob(unit([0, 0], "npc"), unit([0, 1], "npc"), gp=gp_d),
|
|
208
|
+
segmentsGrob(unit(-np.ones(len(at_pos)), "mm"), unit(at_pos, "native"), unit(np.zeros(len(at_pos)), "npc"), unit(at_pos, "native"), gp=gp_d),
|
|
209
|
+
txt_g,
|
|
210
|
+
]
|
|
211
|
+
w = unit(max((textGrob(l, gp=gp_d).width_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
212
|
+
h = unit(1.0, "npc")
|
|
213
|
+
elif side == "right" and facing == "inside":
|
|
214
|
+
txt_g = textGrob(lbls, unit(1, "npc") - unit(2, "mm"), unit(at_pos, "native"), rot=0, just="right", gp=gp_d)
|
|
215
|
+
children = [
|
|
216
|
+
linesGrob(unit([1, 1], "npc"), unit([0, 1], "npc"), gp=gp_d),
|
|
217
|
+
segmentsGrob(unit(1, "npc") - unit(1, "mm"), unit(at_pos, "native"), unit(1, "npc"), unit(at_pos, "native"), gp=gp_d),
|
|
218
|
+
txt_g,
|
|
219
|
+
]
|
|
220
|
+
w = unit(max((textGrob(l, gp=gp_d).width_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
221
|
+
h = unit(1.0, "npc")
|
|
222
|
+
elif side == "right" and facing == "outside":
|
|
223
|
+
txt_g = textGrob(lbls, unit(1, "npc") + unit(2, "mm"), unit(at_pos, "native"), rot=0, just="left", gp=gp_d)
|
|
224
|
+
children = [
|
|
225
|
+
linesGrob(unit([1, 1], "npc"), unit([0, 1], "npc"), gp=gp_d),
|
|
226
|
+
segmentsGrob(unit(1, "npc") + unit(1, "mm"), unit(at_pos, "native"), unit(1, "npc"), unit(at_pos, "native"), gp=gp_d),
|
|
227
|
+
txt_g,
|
|
228
|
+
]
|
|
229
|
+
w = unit(max((textGrob(l, gp=gp_d).width_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
230
|
+
h = unit(1.0, "npc")
|
|
231
|
+
elif side == "top" and facing == "inside":
|
|
232
|
+
j = "top" if rot == 0 else "right"
|
|
233
|
+
txt_g = textGrob(lbls, unit(at_pos, "native"), unit(1, "npc") - unit(2, "mm"), rot=rot, just=j, gp=gp_d)
|
|
234
|
+
children = [
|
|
235
|
+
linesGrob(unit([0, 1], "npc"), unit([1, 1], "npc"), gp=gp_d),
|
|
236
|
+
segmentsGrob(unit(at_pos, "native"), unit(1, "npc") - unit(1, "mm"), unit(at_pos, "native"), unit(1, "npc"), gp=gp_d),
|
|
237
|
+
txt_g,
|
|
238
|
+
]
|
|
239
|
+
w = unit(1.0, "npc")
|
|
240
|
+
h = unit(max((textGrob(l, gp=gp_d, rot=rot).height_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
241
|
+
elif side == "top" and facing == "outside":
|
|
242
|
+
j = "bottom" if rot == 0 else "left"
|
|
243
|
+
txt_g = textGrob(lbls, unit(at_pos, "native"), unit(1, "npc") + unit(2, "mm"), rot=rot, just=j, gp=gp_d)
|
|
244
|
+
children = [
|
|
245
|
+
linesGrob(unit([0, 1], "npc"), unit([1, 1], "npc"), gp=gp_d),
|
|
246
|
+
segmentsGrob(unit(at_pos, "native"), unit(1, "npc") + unit(1, "mm"), unit(at_pos, "native"), unit(1, "npc"), gp=gp_d),
|
|
247
|
+
txt_g,
|
|
248
|
+
]
|
|
249
|
+
w = unit(1.0, "npc")
|
|
250
|
+
h = unit(max((textGrob(l, gp=gp_d, rot=rot).height_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
251
|
+
elif side == "bottom" and facing == "inside":
|
|
252
|
+
j = "bottom" if rot == 0 else "left"
|
|
253
|
+
txt_g = textGrob(lbls, unit(at_pos, "native"), unit(2, "mm"), rot=rot, just=j, gp=gp_d)
|
|
254
|
+
children = [
|
|
255
|
+
linesGrob(unit([0, 1], "npc"), unit([0, 0], "npc"), gp=gp_d),
|
|
256
|
+
segmentsGrob(unit(at_pos, "native"), unit(1, "mm"), unit(at_pos, "native"), unit(0, "npc"), gp=gp_d),
|
|
257
|
+
txt_g,
|
|
258
|
+
]
|
|
259
|
+
w = unit(1.0, "npc")
|
|
260
|
+
h = unit(max((textGrob(l, gp=gp_d, rot=rot).height_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
261
|
+
else: # bottom & outside
|
|
262
|
+
j = "top" if rot == 0 else "right"
|
|
263
|
+
txt_g = textGrob(lbls, unit(at_pos, "native"), unit(-2, "mm"), rot=rot, just=j, gp=gp_d)
|
|
264
|
+
children = [
|
|
265
|
+
linesGrob(unit([0, 1], "npc"), unit([0, 0], "npc"), gp=gp_d),
|
|
266
|
+
segmentsGrob(unit(at_pos, "native"), unit(-1, "mm"), unit(at_pos, "native"), unit(0, "npc"), gp=gp_d),
|
|
267
|
+
txt_g,
|
|
268
|
+
]
|
|
269
|
+
w = unit(1.0, "npc")
|
|
270
|
+
h = unit(max((textGrob(l, gp=gp_d, rot=rot).height_mm() for l in lbls), default=0.0) + 2.0, "mm")
|
|
271
|
+
|
|
272
|
+
return GTree(children=children, cl="annotation_axis", width=w, height=h)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def grid_annotation_axis(
|
|
276
|
+
at: Sequence[float] | None = None,
|
|
277
|
+
labels: Sequence[Any] | None = None,
|
|
278
|
+
labels_rot: float = 0.0,
|
|
279
|
+
gp: dict[str, Any] | None = None,
|
|
280
|
+
side: str = "left",
|
|
281
|
+
facing: str = "outside",
|
|
282
|
+
direction: str = "normal",
|
|
283
|
+
scale: Sequence[float] | None = None,
|
|
284
|
+
) -> GTree:
|
|
285
|
+
gb = annotation_axis_grob(
|
|
286
|
+
at=at, labels=labels, labels_rot=labels_rot, gp=gp,
|
|
287
|
+
side=side, facing=facing, direction=direction, scale=scale,
|
|
288
|
+
)
|
|
289
|
+
gb.draw()
|
|
290
|
+
return gb
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def construct_axis_grob(axis_param: dict[str, Any], which: str, data_scale: Sequence[float]) -> GTree:
|
|
294
|
+
return annotation_axis_grob(
|
|
295
|
+
at=axis_param.get("at"),
|
|
296
|
+
labels=axis_param.get("labels"),
|
|
297
|
+
labels_rot=axis_param.get("labels_rot", 0 if which == "column" else 90),
|
|
298
|
+
gp=axis_param.get("gp"),
|
|
299
|
+
side=axis_param["side"],
|
|
300
|
+
facing=axis_param["facing"],
|
|
301
|
+
direction=axis_param["direction"],
|
|
302
|
+
scale=(float(data_scale[0]), float(data_scale[1])),
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def update_anno_extend(anno: "AnnotationFunction", axis_grob: GTree | None, axis_param: dict[str, Any]) -> Unit:
|
|
307
|
+
# extended: [bottom, left, top, right] in mm
|
|
308
|
+
ext = [0.0, 0.0, 0.0, 0.0]
|
|
309
|
+
if axis_grob is None or axis_param.get("facing") != "outside":
|
|
310
|
+
return unit(ext, "mm")
|
|
311
|
+
side = axis_param["side"]
|
|
312
|
+
if side == "bottom":
|
|
313
|
+
ext[0] = axis_grob.height_mm()
|
|
314
|
+
elif side == "left":
|
|
315
|
+
ext[1] = axis_grob.width_mm()
|
|
316
|
+
elif side == "top":
|
|
317
|
+
ext[2] = axis_grob.height_mm()
|
|
318
|
+
elif side == "right":
|
|
319
|
+
ext[3] = axis_grob.width_mm()
|
|
320
|
+
return unit(ext, "mm")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
# ---- Core Annotation Classes ----
|
|
324
|
+
|
|
325
|
+
class AnnotationFunction:
|
|
326
|
+
"""Subsettable graphic function for row or column heatmap annotations."""
|
|
327
|
+
|
|
328
|
+
def __init__(
|
|
329
|
+
self,
|
|
330
|
+
fun: Callable | None = None,
|
|
331
|
+
fun_name: str = "",
|
|
332
|
+
which: str = "column",
|
|
333
|
+
cell_fun: Callable[[int], None] | None = None,
|
|
334
|
+
var_import: dict[str, Any] | None = None,
|
|
335
|
+
n: int | None = None,
|
|
336
|
+
data_scale: Sequence[float] = (0.0, 1.0),
|
|
337
|
+
subset_rule: dict[str, Callable[[Any, Any], Any]] | None = None,
|
|
338
|
+
subsettable: bool | None = None,
|
|
339
|
+
show_name: bool = True,
|
|
340
|
+
width: Unit | None = None,
|
|
341
|
+
height: Unit | None = None,
|
|
342
|
+
*,
|
|
343
|
+
_which_explicit: bool = True,
|
|
344
|
+
_reorient_fn: Callable[[str], "AnnotationFunction"] | None = None,
|
|
345
|
+
) -> None:
|
|
346
|
+
self.which = which.lower()
|
|
347
|
+
self.fun_name = fun_name
|
|
348
|
+
sz = anno_width_and_height(self.which, width, height, unit(1.0, "cm"))
|
|
349
|
+
self.width: Unit = sz["width"]
|
|
350
|
+
self.height: Unit = sz["height"]
|
|
351
|
+
self.n: int | None = None if n is None or (isinstance(n, float) and np.isnan(n)) else int(n)
|
|
352
|
+
self.data_scale: tuple[float, float] = (float(data_scale[0]), float(data_scale[1]))
|
|
353
|
+
self.extended: Unit = unit([0.0, 0.0, 0.0, 0.0], "mm")
|
|
354
|
+
self.show_name: bool = bool(show_name)
|
|
355
|
+
self.var_env: dict[str, Any] = dict(var_import) if var_import else {}
|
|
356
|
+
self._which_explicit = _which_explicit
|
|
357
|
+
self._reorient_fn = _reorient_fn
|
|
358
|
+
self._called_args: dict[str, Any] | None = None
|
|
359
|
+
|
|
360
|
+
if cell_fun is not None:
|
|
361
|
+
def _wrapped_cell(index, k=1, n_slices=1, env=None):
|
|
362
|
+
m = len(index)
|
|
363
|
+
for pos_i, orig_i in enumerate(index):
|
|
364
|
+
if self.which == "column":
|
|
365
|
+
pushViewport(Viewport(x=unit((pos_i + 1) / m, "npc"), width=unit(1.0 / m, "npc"), just="right"))
|
|
366
|
+
else:
|
|
367
|
+
pushViewport(Viewport(y=unit(1.0 - (pos_i + 1) / m, "npc"), height=unit(1.0 / m, "npc"), just="bottom"))
|
|
368
|
+
try:
|
|
369
|
+
cell_fun(int(orig_i))
|
|
370
|
+
finally:
|
|
371
|
+
popViewport()
|
|
372
|
+
self.fun = _wrapped_cell
|
|
373
|
+
self._takes_env = True
|
|
374
|
+
subsettable_eff = True
|
|
375
|
+
else:
|
|
376
|
+
if fun is None:
|
|
377
|
+
def fun(index, k=1, n=1):
|
|
378
|
+
return None
|
|
379
|
+
self.fun = fun
|
|
380
|
+
sig = inspect.signature(fun)
|
|
381
|
+
params = list(sig.parameters.keys())
|
|
382
|
+
self._takes_env = "env" in params
|
|
383
|
+
self._n_pos_params = sum(
|
|
384
|
+
1 for p in sig.parameters.values()
|
|
385
|
+
if p.kind in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
|
|
386
|
+
and p.name != "env"
|
|
387
|
+
)
|
|
388
|
+
subsettable_eff = bool(subset_rule) if subsettable is None else bool(subsettable)
|
|
389
|
+
|
|
390
|
+
if subset_rule is None:
|
|
391
|
+
self.subset_rule: dict[str, Callable[[Any, Any], Any]] = {}
|
|
392
|
+
for k_v, v_val in self.var_env.items():
|
|
393
|
+
if isinstance(v_val, np.ndarray) and v_val.ndim == 2:
|
|
394
|
+
self.subset_rule[k_v] = subset_matrix_by_row
|
|
395
|
+
elif isinstance(v_val, Gpar):
|
|
396
|
+
self.subset_rule[k_v] = subset_gp
|
|
397
|
+
elif isinstance(v_val, (list, tuple, np.ndarray, Unit)) and len(v_val) > 1:
|
|
398
|
+
self.subset_rule[k_v] = subset_vector
|
|
399
|
+
if self.subset_rule and subsettable is None:
|
|
400
|
+
subsettable_eff = True
|
|
401
|
+
else:
|
|
402
|
+
self.subset_rule = dict(subset_rule)
|
|
403
|
+
|
|
404
|
+
self.subsettable: bool = subsettable_eff
|
|
405
|
+
|
|
406
|
+
def reorient(self, new_which: str) -> "AnnotationFunction":
|
|
407
|
+
if self.which == new_which:
|
|
408
|
+
return self
|
|
409
|
+
if not self._which_explicit and self._reorient_fn is not None:
|
|
410
|
+
return self._reorient_fn(new_which)
|
|
411
|
+
raise ValueError(f"`which` in AnnotationFunction ({self.which!r}) differs from container ({new_which!r}).")
|
|
412
|
+
|
|
413
|
+
def copy_all(self) -> "AnnotationFunction":
|
|
414
|
+
cp = copy.copy(self)
|
|
415
|
+
cp.var_env = copy.deepcopy(self.var_env)
|
|
416
|
+
cp.subset_rule = dict(self.subset_rule)
|
|
417
|
+
if self._called_args is not None:
|
|
418
|
+
cp._called_args = copy.deepcopy(self._called_args)
|
|
419
|
+
return cp
|
|
420
|
+
|
|
421
|
+
def __getitem__(self, i: Any) -> "AnnotationFunction":
|
|
422
|
+
if not self.subsettable:
|
|
423
|
+
raise ValueError("This AnnotationFunction is not subsettable.")
|
|
424
|
+
if isinstance(i, slice):
|
|
425
|
+
if self.n is None or self.n < 0:
|
|
426
|
+
raise ValueError("Cannot slice AnnotationFunction with unknown observation count.")
|
|
427
|
+
idx = list(range(*i.indices(self.n)))
|
|
428
|
+
elif isinstance(i, (int, np.integer)):
|
|
429
|
+
idx = [int(i)]
|
|
430
|
+
else:
|
|
431
|
+
arr_i = np.asarray(i)
|
|
432
|
+
if arr_i.dtype == bool:
|
|
433
|
+
idx = np.where(arr_i)[0].tolist()
|
|
434
|
+
else:
|
|
435
|
+
idx = [int(k) for k in arr_i]
|
|
436
|
+
|
|
437
|
+
if self.fun_name == "anno_mark" and self._called_args is not None:
|
|
438
|
+
from .anno_funcs import anno_mark
|
|
439
|
+
ca = copy.deepcopy(self._called_args)
|
|
440
|
+
idx_sorted = sorted(idx)
|
|
441
|
+
pos_map = {orig: new_i for new_i, orig in enumerate(idx_sorted)}
|
|
442
|
+
keep_mask = [a in pos_map for a in ca["at"]]
|
|
443
|
+
ca["at"] = [pos_map[a] for a, fl in zip(ca["at"], keep_mask) if fl]
|
|
444
|
+
ca["labels"] = [lb for lb, fl in zip(ca["labels"], keep_mask) if fl]
|
|
445
|
+
ca["link_gp"] = subset_gp(ca["link_gp"], keep_mask)
|
|
446
|
+
ca["labels_gp"] = subset_gp(ca["labels_gp"], keep_mask)
|
|
447
|
+
return anno_mark(**ca)
|
|
448
|
+
|
|
449
|
+
cp = self.copy_all()
|
|
450
|
+
for var, rule in cp.subset_rule.items():
|
|
451
|
+
if var in cp.var_env:
|
|
452
|
+
cp.var_env[var] = rule(cp.var_env[var], idx)
|
|
453
|
+
cp.n = len(idx)
|
|
454
|
+
return cp
|
|
455
|
+
|
|
456
|
+
def nobs(self) -> int | None:
|
|
457
|
+
if self.n is None or self.n <= 0:
|
|
458
|
+
return None
|
|
459
|
+
return int(self.n)
|
|
460
|
+
|
|
461
|
+
@property
|
|
462
|
+
def size(self) -> Unit:
|
|
463
|
+
return self.width if self.which == "row" else self.height
|
|
464
|
+
|
|
465
|
+
@size.setter
|
|
466
|
+
def size(self, val: Any) -> None:
|
|
467
|
+
u = as_unit(val, "mm")
|
|
468
|
+
if self.which == "row":
|
|
469
|
+
self.width = u
|
|
470
|
+
else:
|
|
471
|
+
self.height = u
|
|
472
|
+
|
|
473
|
+
def draw(
|
|
474
|
+
self,
|
|
475
|
+
index: Sequence[int] | None = None,
|
|
476
|
+
k: int = 1,
|
|
477
|
+
n: int = 1,
|
|
478
|
+
test: bool | str = False,
|
|
479
|
+
**vp_kwargs: Any,
|
|
480
|
+
) -> None:
|
|
481
|
+
if isinstance(test, str):
|
|
482
|
+
is_test = True
|
|
483
|
+
test_label = test
|
|
484
|
+
else:
|
|
485
|
+
is_test = bool(test)
|
|
486
|
+
test_label = ""
|
|
487
|
+
if is_test:
|
|
488
|
+
grid_newpage()
|
|
489
|
+
pushViewport(Viewport(width=unit(0.8, "npc"), height=unit(0.8, "npc")))
|
|
490
|
+
if self.n is None:
|
|
491
|
+
self.n = 1
|
|
492
|
+
if index is None:
|
|
493
|
+
cnt = self.n if (self.n is not None and self.n > 0) else 1
|
|
494
|
+
index = list(range(cnt))
|
|
495
|
+
|
|
496
|
+
pushViewport(Viewport(width=self.width, height=self.height, **vp_kwargs))
|
|
497
|
+
try:
|
|
498
|
+
if self._takes_env:
|
|
499
|
+
self.fun(index, k, n, env=self.var_env)
|
|
500
|
+
elif self._n_pos_params <= 1:
|
|
501
|
+
self.fun(index)
|
|
502
|
+
elif self._n_pos_params == 2:
|
|
503
|
+
self.fun(index, k)
|
|
504
|
+
else:
|
|
505
|
+
self.fun(index, k, n)
|
|
506
|
+
|
|
507
|
+
if is_test:
|
|
508
|
+
if test_label:
|
|
509
|
+
grid_text(test_label, y=unit(1, "npc") + unit(2, "mm"), just="bottom")
|
|
510
|
+
ext = self.extended.to_mm("x")
|
|
511
|
+
if ext[0] > 0:
|
|
512
|
+
grid_rect(y=unit(1, "npc"), height=unit(1, "npc") + unit(ext[0], "mm"), just="top", gp=gpar(fill="transparent", col="red", lty=2))
|
|
513
|
+
elif ext[1] > 0:
|
|
514
|
+
grid_rect(x=unit(1, "npc"), width=unit(1, "npc") + unit(ext[1], "mm"), just="right", gp=gpar(fill="transparent", col="red", lty=2))
|
|
515
|
+
elif ext[2] > 0:
|
|
516
|
+
grid_rect(y=unit(0, "npc"), height=unit(1, "npc") + unit(ext[2], "mm"), just="bottom", gp=gpar(fill="transparent", col="red", lty=2))
|
|
517
|
+
elif ext[3] > 0:
|
|
518
|
+
grid_rect(x=unit(0, "npc"), width=unit(1, "npc") + unit(ext[3], "mm"), just="left", gp=gpar(fill="transparent", col="red", lty=2))
|
|
519
|
+
finally:
|
|
520
|
+
popViewport()
|
|
521
|
+
if is_test:
|
|
522
|
+
popViewport()
|
|
523
|
+
|
|
524
|
+
def _repr_png_(self) -> bytes:
|
|
525
|
+
import io
|
|
526
|
+
import matplotlib.pyplot as plt
|
|
527
|
+
dev = grid_newpage(width_in=6.0, height_in=4.0)
|
|
528
|
+
self.draw(test=self.fun_name or "AnnotationFunction")
|
|
529
|
+
buf = io.BytesIO()
|
|
530
|
+
dev.fig.savefig(buf, format="png", dpi=120)
|
|
531
|
+
plt.close(dev.fig)
|
|
532
|
+
return buf.getvalue()
|
|
533
|
+
|
|
534
|
+
def __repr__(self) -> str:
|
|
535
|
+
fn = f"{self.fun_name}()" if self.fun_name else "user-defined"
|
|
536
|
+
return (
|
|
537
|
+
f"An AnnotationFunction object\n"
|
|
538
|
+
f" function: {fn}\n"
|
|
539
|
+
f" position: {self.which}\n"
|
|
540
|
+
f" items: {self.n if self.n is not None else 'unknown'}\n"
|
|
541
|
+
f" width: {self.width}\n"
|
|
542
|
+
f" height: {self.height}\n"
|
|
543
|
+
f" subsettable: {self.subsettable}"
|
|
544
|
+
)
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _normalize_anno_matrix_or_vec(val: Any) -> tuple[Any, bool, list[str] | None]:
|
|
548
|
+
"""Normalize atomic vector / DataFrame / 2D array for simple annotation."""
|
|
549
|
+
if isinstance(val, pd.Series):
|
|
550
|
+
arr = val.to_numpy()
|
|
551
|
+
return arr, False, None
|
|
552
|
+
if isinstance(val, pd.DataFrame):
|
|
553
|
+
cnames = [str(c) for c in val.columns]
|
|
554
|
+
arr = val.to_numpy()
|
|
555
|
+
if arr.shape[1] == 1:
|
|
556
|
+
return arr[:, 0], False, None
|
|
557
|
+
return arr, True, cnames
|
|
558
|
+
arr = np.asarray(val)
|
|
559
|
+
if arr.ndim == 2:
|
|
560
|
+
if arr.shape[1] == 1:
|
|
561
|
+
return arr[:, 0], False, None
|
|
562
|
+
return arr, True, None
|
|
563
|
+
return arr, False, None
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
class SingleAnnotation:
|
|
567
|
+
"""Single track or complex annotation with name, optional ColorMapping, and legend params."""
|
|
568
|
+
|
|
569
|
+
def __init__(
|
|
570
|
+
self,
|
|
571
|
+
name: str | None = None,
|
|
572
|
+
value: Any = None,
|
|
573
|
+
col: Any = None,
|
|
574
|
+
fun: AnnotationFunction | Callable | None = None,
|
|
575
|
+
label: Any = None,
|
|
576
|
+
na_col: str = "grey",
|
|
577
|
+
which: str = "column",
|
|
578
|
+
show_legend: bool = True,
|
|
579
|
+
gp: dict[str, Any] | None = None,
|
|
580
|
+
border: bool = False,
|
|
581
|
+
legend_param: dict[str, Any] | None = None,
|
|
582
|
+
show_name: bool = True,
|
|
583
|
+
name_gp: dict[str, Any] | None = None,
|
|
584
|
+
name_offset: Any = None,
|
|
585
|
+
name_side: str | None = None,
|
|
586
|
+
name_rot: float | None = None,
|
|
587
|
+
simple_anno_size: Unit | None = None,
|
|
588
|
+
width: Unit | None = None,
|
|
589
|
+
height: Unit | None = None,
|
|
590
|
+
) -> None:
|
|
591
|
+
from .anno_funcs import anno_simple
|
|
592
|
+
|
|
593
|
+
self.which = which.lower()
|
|
594
|
+
if name is None:
|
|
595
|
+
name = f"anno{next(_ENV.anno_counter)}"
|
|
596
|
+
self.name = str(name)
|
|
597
|
+
self.label = self.name if label is None else label
|
|
598
|
+
self.show_legend = bool(show_legend)
|
|
599
|
+
self.color_mapping: ColorMapping | None = None
|
|
600
|
+
self.color_is_random = False
|
|
601
|
+
self.is_anno_matrix = False
|
|
602
|
+
self.anno_matrix_colnames: list[str] | None = None
|
|
603
|
+
self.anno_matrix_k: int = 1
|
|
604
|
+
self.name_to_data_vp = False
|
|
605
|
+
|
|
606
|
+
# Merge global legend defaults
|
|
607
|
+
lp = dict(legend_param) if legend_param else {}
|
|
608
|
+
for opt_n in ("title_gp", "title_position", "labels_gp", "grid_width", "grid_height", "border"):
|
|
609
|
+
if opt_n not in lp:
|
|
610
|
+
gv = getattr(ht_opt, f"legend_{opt_n}")
|
|
611
|
+
if gv is not None:
|
|
612
|
+
lp[opt_n] = gv
|
|
613
|
+
self.legend_param = lp
|
|
614
|
+
|
|
615
|
+
if simple_anno_size is None:
|
|
616
|
+
simple_anno_size = ht_opt.simple_anno_size
|
|
617
|
+
if name_side is None:
|
|
618
|
+
name_side = "right" if self.which == "column" else "bottom"
|
|
619
|
+
name_gp_d = check_gp(name_gp or gpar(fontsize=12))
|
|
620
|
+
if "fontsize" not in name_gp_d:
|
|
621
|
+
name_gp_d["fontsize"] = 12.0
|
|
622
|
+
|
|
623
|
+
is_offset_called = name_offset is not None
|
|
624
|
+
is_rot_called = name_rot is not None
|
|
625
|
+
|
|
626
|
+
if fun is not None:
|
|
627
|
+
if isinstance(fun, AnnotationFunction):
|
|
628
|
+
af = fun.reorient(self.which)
|
|
629
|
+
elif callable(fun):
|
|
630
|
+
af = AnnotationFunction(fun=fun, which=self.which, width=width, height=height)
|
|
631
|
+
else:
|
|
632
|
+
raise TypeError("`fun` must be an AnnotationFunction or callable.")
|
|
633
|
+
self.fun = af
|
|
634
|
+
self.show_legend = False
|
|
635
|
+
if not af.show_name:
|
|
636
|
+
show_name = False
|
|
637
|
+
self.extended = af.extended
|
|
638
|
+
self.width = af.width
|
|
639
|
+
self.height = af.height
|
|
640
|
+
self.subsettable = af.subsettable
|
|
641
|
+
else:
|
|
642
|
+
if value is None:
|
|
643
|
+
raise ValueError("Either `value` or `fun` must be provided to SingleAnnotation.")
|
|
644
|
+
norm_val, is_mat, cnames = _normalize_anno_matrix_or_vec(value)
|
|
645
|
+
if np.asarray(norm_val).dtype == bool:
|
|
646
|
+
norm_val = np.where(norm_val, "TRUE", "FALSE")
|
|
647
|
+
self.is_anno_matrix = is_mat
|
|
648
|
+
self.anno_matrix_colnames = cnames
|
|
649
|
+
self.anno_matrix_k = norm_val.shape[1] if is_mat else 1
|
|
650
|
+
|
|
651
|
+
# Resolve col -> ColorMapping
|
|
652
|
+
if isinstance(col, ColorMapping):
|
|
653
|
+
cm = col
|
|
654
|
+
elif col is None:
|
|
655
|
+
self.color_is_random = True
|
|
656
|
+
inferred = default_col(norm_val)
|
|
657
|
+
if callable(inferred):
|
|
658
|
+
cm = ColorMapping(name=self.name, col_fun=inferred, na_col=na_col)
|
|
659
|
+
else:
|
|
660
|
+
cm = ColorMapping(name=self.name, colors=inferred, na_col=na_col)
|
|
661
|
+
elif callable(col):
|
|
662
|
+
cm = ColorMapping(name=self.name, col_fun=col, na_col=na_col)
|
|
663
|
+
elif isinstance(col, dict):
|
|
664
|
+
eff_na = col.get("_NA_", na_col)
|
|
665
|
+
clean_col = {k: v for k, v in col.items() if k != "_NA_"}
|
|
666
|
+
cm = ColorMapping(name=self.name, colors=clean_col, na_col=eff_na, full_col=clean_col)
|
|
667
|
+
else:
|
|
668
|
+
# Sequence of colors without names
|
|
669
|
+
col_seq = list(col)
|
|
670
|
+
arr_v = np.asarray(norm_val)
|
|
671
|
+
is_num = np.issubdtype(arr_v.dtype, np.number)
|
|
672
|
+
uniq = list(dict.fromkeys(v for v in arr_v.ravel() if v is not None and not (isinstance(v, float) and np.isnan(v))))
|
|
673
|
+
if len(col_seq) == len(uniq):
|
|
674
|
+
keys = [str(u) for u in sorted(uniq)]
|
|
675
|
+
cm = ColorMapping(name=self.name, colors=dict(zip(keys, col_seq)), na_col=na_col)
|
|
676
|
+
elif is_num:
|
|
677
|
+
from .colors import colorRamp2
|
|
678
|
+
vals = arr_v.astype(float)
|
|
679
|
+
vmin, vmax = float(np.nanmin(vals)), float(np.nanmax(vals))
|
|
680
|
+
if vmin == vmax:
|
|
681
|
+
vmax = vmin + 1e-6
|
|
682
|
+
cf = colorRamp2(np.linspace(vmin, vmax, len(col_seq)), col_seq)
|
|
683
|
+
cm = ColorMapping(name=self.name, col_fun=cf, na_col=na_col)
|
|
684
|
+
else:
|
|
685
|
+
raise ValueError("Unnamed `col` vector length does not match unique levels.")
|
|
686
|
+
|
|
687
|
+
self.color_mapping = cm
|
|
688
|
+
self.fun = anno_simple(
|
|
689
|
+
norm_val,
|
|
690
|
+
col=cm,
|
|
691
|
+
na_col=na_col,
|
|
692
|
+
which=self.which,
|
|
693
|
+
border=border,
|
|
694
|
+
gp=gp or gpar(col=None),
|
|
695
|
+
simple_anno_size=simple_anno_size,
|
|
696
|
+
width=width,
|
|
697
|
+
height=height,
|
|
698
|
+
)
|
|
699
|
+
self.width = self.fun.width
|
|
700
|
+
self.height = self.fun.height
|
|
701
|
+
self.extended = self.fun.extended
|
|
702
|
+
self.subsettable = self.fun.subsettable
|
|
703
|
+
|
|
704
|
+
# Compute name placement parameters
|
|
705
|
+
ext_mm = self.extended.to_mm("x")
|
|
706
|
+
off_u = unit(1.0, "mm") if name_offset is None else as_unit(name_offset, "mm")
|
|
707
|
+
rot = (0.0 if self.which == "column" else 90.0) if name_rot is None else float(name_rot)
|
|
708
|
+
rot = rot % 360.0
|
|
709
|
+
|
|
710
|
+
if self.which == "column":
|
|
711
|
+
if name_side not in ("left", "right"):
|
|
712
|
+
raise ValueError(f"{self.name}: `name_side` must be 'left' or 'right' for column annotation.")
|
|
713
|
+
if name_side == "left":
|
|
714
|
+
if ext_mm[1] > 0:
|
|
715
|
+
if not is_offset_called:
|
|
716
|
+
off_u = off_u + unit(ext_mm[1], "mm")
|
|
717
|
+
if not is_rot_called:
|
|
718
|
+
rot = 90.0
|
|
719
|
+
if self.is_anno_matrix and self.anno_matrix_colnames:
|
|
720
|
+
nc = self.anno_matrix_k
|
|
721
|
+
nx = unit(np.zeros(nc), "npc") - off_u
|
|
722
|
+
ny = unit((nc - np.arange(nc) - 0.5) / nc, "npc")
|
|
723
|
+
lbl_txt = self.anno_matrix_colnames
|
|
724
|
+
else:
|
|
725
|
+
nx = unit(0.0, "npc") - off_u
|
|
726
|
+
ny = unit(0.5, "npc")
|
|
727
|
+
lbl_txt = self.label
|
|
728
|
+
just = {0: "right", 90: "bottom", 180: "left", 270: "top"}.get(rot, "right")
|
|
729
|
+
else:
|
|
730
|
+
if ext_mm[3] > 0:
|
|
731
|
+
if not is_offset_called:
|
|
732
|
+
off_u = off_u + unit(ext_mm[3], "mm")
|
|
733
|
+
if not is_rot_called:
|
|
734
|
+
rot = 90.0
|
|
735
|
+
if self.is_anno_matrix and self.anno_matrix_colnames:
|
|
736
|
+
nc = self.anno_matrix_k
|
|
737
|
+
nx = unit(np.ones(nc), "npc") + off_u
|
|
738
|
+
ny = unit((nc - np.arange(nc) - 0.5) / nc, "npc")
|
|
739
|
+
lbl_txt = self.anno_matrix_colnames
|
|
740
|
+
else:
|
|
741
|
+
nx = unit(1.0, "npc") + off_u
|
|
742
|
+
ny = unit(0.5, "npc")
|
|
743
|
+
lbl_txt = self.label
|
|
744
|
+
just = {0: "left", 90: "top", 180: "right", 270: "bottom"}.get(rot, "left")
|
|
745
|
+
else:
|
|
746
|
+
if name_side not in ("top", "bottom"):
|
|
747
|
+
raise ValueError(f"{self.name}: `name_side` must be 'top' or 'bottom' for row annotation.")
|
|
748
|
+
if name_side == "top":
|
|
749
|
+
if ext_mm[2] > 0:
|
|
750
|
+
if not is_offset_called:
|
|
751
|
+
off_u = off_u + unit(ext_mm[2], "mm")
|
|
752
|
+
if not is_rot_called:
|
|
753
|
+
rot = 0.0
|
|
754
|
+
if self.is_anno_matrix and self.anno_matrix_colnames:
|
|
755
|
+
nc = self.anno_matrix_k
|
|
756
|
+
nx = unit((np.arange(nc) + 0.5) / nc, "npc")
|
|
757
|
+
ny = unit(np.ones(nc), "npc") + off_u
|
|
758
|
+
lbl_txt = self.anno_matrix_colnames
|
|
759
|
+
else:
|
|
760
|
+
nx = unit(0.5, "npc")
|
|
761
|
+
ny = unit(1.0, "npc") + off_u
|
|
762
|
+
lbl_txt = self.label
|
|
763
|
+
just = {0: "bottom", 90: "left", 180: "top", 270: "right"}.get(rot, "bottom")
|
|
764
|
+
else:
|
|
765
|
+
if ext_mm[0] > 0:
|
|
766
|
+
if not is_offset_called:
|
|
767
|
+
off_u = off_u + unit(ext_mm[0], "mm")
|
|
768
|
+
if not is_rot_called:
|
|
769
|
+
rot = 0.0
|
|
770
|
+
if self.is_anno_matrix and self.anno_matrix_colnames:
|
|
771
|
+
nc = self.anno_matrix_k
|
|
772
|
+
nx = unit((np.arange(nc) + 0.5) / nc, "npc")
|
|
773
|
+
ny = unit(np.zeros(nc), "npc") - off_u
|
|
774
|
+
lbl_txt = self.anno_matrix_colnames
|
|
775
|
+
else:
|
|
776
|
+
nx = unit(0.5, "npc")
|
|
777
|
+
ny = unit(0.0, "npc") - off_u
|
|
778
|
+
lbl_txt = self.label
|
|
779
|
+
just = {0: "top", 90: "right", 180: "bottom", 270: "left"}.get(rot, "top")
|
|
780
|
+
|
|
781
|
+
self.name_param = {
|
|
782
|
+
"show": bool(show_name),
|
|
783
|
+
"x": nx,
|
|
784
|
+
"y": ny,
|
|
785
|
+
"just": just,
|
|
786
|
+
"rot": rot,
|
|
787
|
+
"gp": name_gp_d,
|
|
788
|
+
"side": name_side,
|
|
789
|
+
"offset": off_u,
|
|
790
|
+
"label": lbl_txt,
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
def copy_all(self) -> "SingleAnnotation":
|
|
794
|
+
cp = copy.copy(self)
|
|
795
|
+
cp.fun = self.fun.copy_all()
|
|
796
|
+
cp.name_param = copy.deepcopy(self.name_param)
|
|
797
|
+
cp.legend_param = copy.deepcopy(self.legend_param)
|
|
798
|
+
return cp
|
|
799
|
+
|
|
800
|
+
def nobs(self) -> int | None:
|
|
801
|
+
return self.fun.nobs()
|
|
802
|
+
|
|
803
|
+
@property
|
|
804
|
+
def size(self) -> Unit:
|
|
805
|
+
return self.width if self.which == "row" else self.height
|
|
806
|
+
|
|
807
|
+
@size.setter
|
|
808
|
+
def size(self, val: Unit) -> None:
|
|
809
|
+
u = as_unit(val, "mm")
|
|
810
|
+
if self.which == "row":
|
|
811
|
+
self.width = u
|
|
812
|
+
self.fun.width = u
|
|
813
|
+
else:
|
|
814
|
+
self.height = u
|
|
815
|
+
self.fun.height = u
|
|
816
|
+
|
|
817
|
+
def __getitem__(self, i: Any) -> "SingleAnnotation":
|
|
818
|
+
cp = self.copy_all()
|
|
819
|
+
cp.fun = cp.fun[i]
|
|
820
|
+
cp.width = cp.fun.width
|
|
821
|
+
cp.height = cp.fun.height
|
|
822
|
+
return cp
|
|
823
|
+
|
|
824
|
+
def draw(
|
|
825
|
+
self,
|
|
826
|
+
index: Sequence[int] | None = None,
|
|
827
|
+
k: int = 1,
|
|
828
|
+
n: int = 1,
|
|
829
|
+
test: bool | str = False,
|
|
830
|
+
anno_mark_param: dict[str, Any] | None = None,
|
|
831
|
+
) -> None:
|
|
832
|
+
if isinstance(test, str):
|
|
833
|
+
is_test = True
|
|
834
|
+
test_label = test
|
|
835
|
+
else:
|
|
836
|
+
is_test = bool(test)
|
|
837
|
+
test_label = ""
|
|
838
|
+
if is_test:
|
|
839
|
+
grid_newpage()
|
|
840
|
+
if self.which == "column":
|
|
841
|
+
pushViewport(Viewport(width=unit(1, "npc") - unit(3, "cm"), height=self.height))
|
|
842
|
+
else:
|
|
843
|
+
pushViewport(Viewport(height=unit(1, "npc") - unit(3, "cm"), width=self.width))
|
|
844
|
+
|
|
845
|
+
if index is None:
|
|
846
|
+
cnt = self.fun.n if (self.fun.n is not None and self.fun.n > 0) else 1
|
|
847
|
+
index = list(range(cnt))
|
|
848
|
+
|
|
849
|
+
amp = anno_mark_param or {}
|
|
850
|
+
is_mark_or_zoom = self.fun.fun_name in ("anno_mark", "anno_zoom") and bool(amp)
|
|
851
|
+
if is_mark_or_zoom and k > 1:
|
|
852
|
+
if is_test:
|
|
853
|
+
popViewport()
|
|
854
|
+
return
|
|
855
|
+
|
|
856
|
+
if is_mark_or_zoom:
|
|
857
|
+
# Draw in spanning viewport covering all slices
|
|
858
|
+
self.fun.var_env[".pos"] = amp.get(".pos")
|
|
859
|
+
if ".scale" in amp:
|
|
860
|
+
self.fun.var_env[".scale"] = amp[".scale"]
|
|
861
|
+
if self.which == "row":
|
|
862
|
+
vp = Viewport(
|
|
863
|
+
x=unit(0.5, "npc"), y=amp.get("y", unit(0.5, "npc")),
|
|
864
|
+
width=self.width, height=amp.get("height", unit(1.0, "npc")),
|
|
865
|
+
just=amp.get("just", "centre"),
|
|
866
|
+
xscale=self.fun.data_scale, yscale=(0.5, len(index) + 0.5),
|
|
867
|
+
name=f"annotation_{self.name}_{k}",
|
|
868
|
+
)
|
|
869
|
+
else:
|
|
870
|
+
vp = Viewport(
|
|
871
|
+
x=amp.get("x", unit(0.5, "npc")), y=unit(0.5, "npc"),
|
|
872
|
+
width=amp.get("width", unit(1.0, "npc")), height=self.height,
|
|
873
|
+
just=amp.get("just", "centre"),
|
|
874
|
+
xscale=(0.5, len(index) + 0.5), yscale=self.fun.data_scale,
|
|
875
|
+
name=f"annotation_{self.name}_{k}",
|
|
876
|
+
)
|
|
877
|
+
pushViewport(vp)
|
|
878
|
+
try:
|
|
879
|
+
idx_arg = amp.get("index", index)
|
|
880
|
+
if self.fun._takes_env:
|
|
881
|
+
self.fun.fun(idx_arg, 1, 1, env=self.fun.var_env)
|
|
882
|
+
elif self.fun._n_pos_params <= 1:
|
|
883
|
+
self.fun.fun(idx_arg)
|
|
884
|
+
else:
|
|
885
|
+
self.fun.fun(idx_arg, 1, 1)
|
|
886
|
+
finally:
|
|
887
|
+
popViewport()
|
|
888
|
+
if is_test:
|
|
889
|
+
popViewport()
|
|
890
|
+
return
|
|
891
|
+
|
|
892
|
+
m_obs = max(1, len(index))
|
|
893
|
+
if self.which == "column":
|
|
894
|
+
vp = Viewport(
|
|
895
|
+
width=self.width, height=self.height,
|
|
896
|
+
xscale=(0.5, m_obs + 0.5), yscale=self.fun.data_scale,
|
|
897
|
+
name=f"annotation_{self.name}_{k}",
|
|
898
|
+
)
|
|
899
|
+
else:
|
|
900
|
+
vp = Viewport(
|
|
901
|
+
width=self.width, height=self.height,
|
|
902
|
+
xscale=self.fun.data_scale, yscale=(0.5, m_obs + 0.5),
|
|
903
|
+
name=f"annotation_{self.name}_{k}",
|
|
904
|
+
)
|
|
905
|
+
|
|
906
|
+
pushViewport(vp)
|
|
907
|
+
try:
|
|
908
|
+
if self.fun._takes_env:
|
|
909
|
+
self.fun.fun(index, k, n, env=self.fun.var_env)
|
|
910
|
+
elif self.fun._n_pos_params <= 1:
|
|
911
|
+
self.fun.fun(index)
|
|
912
|
+
elif self.fun._n_pos_params == 2:
|
|
913
|
+
self.fun.fun(index, k)
|
|
914
|
+
else:
|
|
915
|
+
self.fun.fun(index, k, n)
|
|
916
|
+
|
|
917
|
+
if self.name_param["show"]:
|
|
918
|
+
side = self.name_param["side"]
|
|
919
|
+
show_this_slice = (n == 1) or (k == 1 and side in ("left", "top")) or (k == n and side in ("right", "bottom"))
|
|
920
|
+
if show_this_slice:
|
|
921
|
+
grid_text(
|
|
922
|
+
self.name_param["label"],
|
|
923
|
+
x=self.name_param["x"],
|
|
924
|
+
y=self.name_param["y"],
|
|
925
|
+
just=self.name_param["just"],
|
|
926
|
+
rot=self.name_param["rot"],
|
|
927
|
+
gp=self.name_param["gp"],
|
|
928
|
+
)
|
|
929
|
+
finally:
|
|
930
|
+
popViewport()
|
|
931
|
+
if is_test:
|
|
932
|
+
if test_label:
|
|
933
|
+
grid_text(test_label, y=unit(1, "npc") + unit(2, "mm"), just="bottom")
|
|
934
|
+
popViewport()
|
|
935
|
+
|
|
936
|
+
def _repr_png_(self) -> bytes:
|
|
937
|
+
import io
|
|
938
|
+
import matplotlib.pyplot as plt
|
|
939
|
+
dev = grid_newpage(width_in=6.0, height_in=3.5)
|
|
940
|
+
self.draw(test=self.name)
|
|
941
|
+
buf = io.BytesIO()
|
|
942
|
+
dev.fig.savefig(buf, format="png", dpi=120)
|
|
943
|
+
plt.close(dev.fig)
|
|
944
|
+
return buf.getvalue()
|
|
945
|
+
|
|
946
|
+
def __repr__(self) -> str:
|
|
947
|
+
return f"A SingleAnnotation object named {self.name!r} (which={self.which!r}, nobs={self.nobs()})"
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def _recycle_param(val: Any, names: list[str], default: Any = None, as_list: bool = False) -> Any:
|
|
951
|
+
n = len(names)
|
|
952
|
+
if val is None:
|
|
953
|
+
return [default] * n
|
|
954
|
+
if isinstance(val, dict):
|
|
955
|
+
return [val.get(nm, default) for nm in names]
|
|
956
|
+
if isinstance(val, (str, bool, int, float, np.number, Unit)):
|
|
957
|
+
if isinstance(val, Unit) and len(val) > 1:
|
|
958
|
+
return [val[i] for i in range(n)]
|
|
959
|
+
return [val] * n
|
|
960
|
+
seq = list(val)
|
|
961
|
+
if len(seq) == 1:
|
|
962
|
+
return seq * n
|
|
963
|
+
if len(seq) != n:
|
|
964
|
+
raise ValueError(f"Parameter length ({len(seq)}) must be 1 or match annotation count ({n}).")
|
|
965
|
+
return seq
|
|
966
|
+
|
|
967
|
+
|
|
968
|
+
class HeatmapAnnotation(AdditiveUnit):
|
|
969
|
+
"""Collection of row or column annotations aligned to a Heatmap."""
|
|
970
|
+
|
|
971
|
+
def __init__(
|
|
972
|
+
self,
|
|
973
|
+
_annotations: dict[str, Any] | None = None,
|
|
974
|
+
*,
|
|
975
|
+
df: pd.DataFrame | dict[str, Any] | None = None,
|
|
976
|
+
name: str | None = None,
|
|
977
|
+
col: dict[str, Any] | None = None,
|
|
978
|
+
na_col: str = "grey",
|
|
979
|
+
annotation_legend_param: Any = None,
|
|
980
|
+
show_legend: Any = True,
|
|
981
|
+
which: str = "column",
|
|
982
|
+
gp: dict[str, Any] | None = None,
|
|
983
|
+
border: Any = None,
|
|
984
|
+
gap: Any = unit(1, "points"),
|
|
985
|
+
show_annotation_name: Any = True,
|
|
986
|
+
annotation_label: Any = None,
|
|
987
|
+
annotation_name_gp: Any = None,
|
|
988
|
+
annotation_name_offset: Any = None,
|
|
989
|
+
annotation_name_side: Any = None,
|
|
990
|
+
annotation_name_rot: Any = None,
|
|
991
|
+
annotation_name_align: bool = False,
|
|
992
|
+
annotation_height: Any = None,
|
|
993
|
+
annotation_width: Any = None,
|
|
994
|
+
height: Any = None,
|
|
995
|
+
width: Any = None,
|
|
996
|
+
simple_anno_size: Unit | None = None,
|
|
997
|
+
simple_anno_size_adjust: bool = False,
|
|
998
|
+
**kwargs: Any,
|
|
999
|
+
) -> None:
|
|
1000
|
+
self.which = which.lower()
|
|
1001
|
+
if self.which not in ("column", "row"):
|
|
1002
|
+
raise ValueError("`which` must be 'column' or 'row'.")
|
|
1003
|
+
if name is None:
|
|
1004
|
+
name = f"heatmap_annotation_{next(_ENV.anno_counter)}"
|
|
1005
|
+
self.name = str(name)
|
|
1006
|
+
if simple_anno_size is None:
|
|
1007
|
+
simple_anno_size = ht_opt.simple_anno_size
|
|
1008
|
+
|
|
1009
|
+
is_height_set = height is not None
|
|
1010
|
+
is_width_set = width is not None
|
|
1011
|
+
is_anno_h_set = annotation_height is not None
|
|
1012
|
+
is_anno_w_set = annotation_width is not None
|
|
1013
|
+
|
|
1014
|
+
anno_values: dict[str, Any] = {}
|
|
1015
|
+
if _annotations:
|
|
1016
|
+
anno_values.update(_annotations)
|
|
1017
|
+
for k_arg, v_arg in kwargs.items():
|
|
1018
|
+
if k_arg == "anno_simple_size":
|
|
1019
|
+
raise ValueError("Use `simple_anno_size` instead of `anno_simple_size`.")
|
|
1020
|
+
anno_values[k_arg] = v_arg
|
|
1021
|
+
|
|
1022
|
+
if df is not None:
|
|
1023
|
+
if not isinstance(df, pd.DataFrame):
|
|
1024
|
+
df = pd.DataFrame(df)
|
|
1025
|
+
for cname in df.columns:
|
|
1026
|
+
sc = str(cname)
|
|
1027
|
+
if sc in anno_values:
|
|
1028
|
+
raise ValueError(f"Annotation name {sc!r} duplicates a column in `df`.")
|
|
1029
|
+
anno_values[sc] = df[cname].to_numpy()
|
|
1030
|
+
|
|
1031
|
+
if not anno_values:
|
|
1032
|
+
raise ValueError("HeatmapAnnotation requires at least one named annotation or `df`.")
|
|
1033
|
+
|
|
1034
|
+
an = list(anno_values.keys())
|
|
1035
|
+
n_total = len(an)
|
|
1036
|
+
is_simple = [not (isinstance(anno_values[k], AnnotationFunction) or callable(anno_values[k])) for k in an]
|
|
1037
|
+
simple_names = [nm for nm, fl in zip(an, is_simple) if fl]
|
|
1038
|
+
n_simple = len(simple_names)
|
|
1039
|
+
|
|
1040
|
+
# Normalize show_legend for simple annotations
|
|
1041
|
+
if isinstance(show_legend, dict):
|
|
1042
|
+
sl_list = [bool(show_legend.get(nm, True)) for nm in simple_names]
|
|
1043
|
+
elif isinstance(show_legend, (bool, np.bool_)):
|
|
1044
|
+
sl_list = [bool(show_legend)] * n_simple
|
|
1045
|
+
else:
|
|
1046
|
+
seq_sl = list(show_legend)
|
|
1047
|
+
if len(seq_sl) == n_total and not all(is_simple):
|
|
1048
|
+
sl_list = [bool(s) for s, fl in zip(seq_sl, is_simple) if fl]
|
|
1049
|
+
elif len(seq_sl) == n_simple:
|
|
1050
|
+
sl_list = [bool(s) for s in seq_sl]
|
|
1051
|
+
else:
|
|
1052
|
+
sl_list = [bool(seq_sl[i % len(seq_sl)]) for i in range(n_simple)]
|
|
1053
|
+
|
|
1054
|
+
# Normalize annotation_legend_param
|
|
1055
|
+
if not annotation_legend_param:
|
|
1056
|
+
alp_list: list[dict[str, Any]] = [{} for _ in range(n_simple)]
|
|
1057
|
+
elif isinstance(annotation_legend_param, dict):
|
|
1058
|
+
if annotation_legend_param and all(isinstance(v, dict) for v in annotation_legend_param.values()):
|
|
1059
|
+
bad = set(annotation_legend_param.keys()) - set(simple_names)
|
|
1060
|
+
if bad:
|
|
1061
|
+
raise ValueError(f"Unknown simple annotation names in `annotation_legend_param`: {bad}")
|
|
1062
|
+
alp_list = [dict(annotation_legend_param.get(nm, {})) for nm in simple_names]
|
|
1063
|
+
else:
|
|
1064
|
+
alp_list = [dict(annotation_legend_param) for _ in range(n_simple)]
|
|
1065
|
+
else:
|
|
1066
|
+
seq_alp = list(annotation_legend_param)
|
|
1067
|
+
alp_list = [dict(seq_alp[i]) if i < len(seq_alp) else {} for i in range(n_simple)]
|
|
1068
|
+
|
|
1069
|
+
if border is None:
|
|
1070
|
+
border = ht_opt.annotation_border if ht_opt.annotation_border is not None else False
|
|
1071
|
+
if annotation_name_side is None:
|
|
1072
|
+
annotation_name_side = "right" if self.which == "column" else "bottom"
|
|
1073
|
+
|
|
1074
|
+
show_name_rec = _recycle_param(show_annotation_name, an, True)
|
|
1075
|
+
side_rec = _recycle_param(annotation_name_side, an, annotation_name_side)
|
|
1076
|
+
off_rec = _recycle_param(annotation_name_offset, an, None)
|
|
1077
|
+
rot_rec = _recycle_param(annotation_name_rot, an, None)
|
|
1078
|
+
border_rec = _recycle_param(border, an, False)
|
|
1079
|
+
name_gp_rec = recycle_gp(annotation_name_gp or gpar(), n_total)
|
|
1080
|
+
lbl_rec = _recycle_param(annotation_label, an, None)
|
|
1081
|
+
|
|
1082
|
+
# Validate col dict
|
|
1083
|
+
col_dict = col or {}
|
|
1084
|
+
if col_dict and not isinstance(col_dict, dict):
|
|
1085
|
+
raise TypeError("`col` must be a dict mapping simple annotation names to colors/functions.")
|
|
1086
|
+
|
|
1087
|
+
# Reorient flexible AnnotationFunctions to `self.which` before validating observation lengths
|
|
1088
|
+
for nm in an:
|
|
1089
|
+
val = anno_values[nm]
|
|
1090
|
+
if isinstance(val, AnnotationFunction) and val.which != self.which:
|
|
1091
|
+
anno_values[nm] = val.reorient(self.which)
|
|
1092
|
+
|
|
1093
|
+
# Validate consistent observation counts
|
|
1094
|
+
obs_lens = []
|
|
1095
|
+
for nm, val in anno_values.items():
|
|
1096
|
+
if isinstance(val, AnnotationFunction):
|
|
1097
|
+
nb = val.nobs()
|
|
1098
|
+
if nb is not None:
|
|
1099
|
+
obs_lens.append(nb)
|
|
1100
|
+
elif callable(val):
|
|
1101
|
+
pass
|
|
1102
|
+
else:
|
|
1103
|
+
arr = np.asarray(val)
|
|
1104
|
+
obs_lens.append(arr.shape[0])
|
|
1105
|
+
if len(set(obs_lens)) > 1:
|
|
1106
|
+
raise ValueError(f"Length of annotations differs: {obs_lens}")
|
|
1107
|
+
|
|
1108
|
+
self.anno_list: dict[str, SingleAnnotation] = {}
|
|
1109
|
+
i_simple = 0
|
|
1110
|
+
for idx, nm in enumerate(an):
|
|
1111
|
+
val = anno_values[nm]
|
|
1112
|
+
common = dict(
|
|
1113
|
+
name=nm,
|
|
1114
|
+
which=self.which,
|
|
1115
|
+
label=lbl_rec[idx],
|
|
1116
|
+
show_name=bool(show_name_rec[idx]),
|
|
1117
|
+
name_gp=subset_gp(name_gp_rec, idx),
|
|
1118
|
+
name_offset=off_rec[idx],
|
|
1119
|
+
name_side=side_rec[idx],
|
|
1120
|
+
name_rot=rot_rec[idx],
|
|
1121
|
+
border=border_rec[idx],
|
|
1122
|
+
)
|
|
1123
|
+
if isinstance(val, AnnotationFunction) or callable(val):
|
|
1124
|
+
self.anno_list[nm] = SingleAnnotation(fun=val, **common)
|
|
1125
|
+
else:
|
|
1126
|
+
sa = SingleAnnotation(
|
|
1127
|
+
value=val,
|
|
1128
|
+
col=col_dict.get(nm),
|
|
1129
|
+
na_col=na_col,
|
|
1130
|
+
gp=gp or gpar(col=None),
|
|
1131
|
+
show_legend=sl_list[i_simple],
|
|
1132
|
+
legend_param=alp_list[i_simple],
|
|
1133
|
+
simple_anno_size=simple_anno_size,
|
|
1134
|
+
**common,
|
|
1135
|
+
)
|
|
1136
|
+
self.anno_list[nm] = sa
|
|
1137
|
+
i_simple += 1
|
|
1138
|
+
|
|
1139
|
+
# Zoomed anno_empty check
|
|
1140
|
+
if n_total > 1:
|
|
1141
|
+
for sa in self.anno_list.values():
|
|
1142
|
+
if sa.fun.fun_name == "anno_empty" and sa.fun.var_env.get("zoom", False):
|
|
1143
|
+
raise ValueError("`anno_empty(zoom=True)` must be the sole annotation in HeatmapAnnotation.")
|
|
1144
|
+
|
|
1145
|
+
# Gap setup
|
|
1146
|
+
if gap is None or gap == 0:
|
|
1147
|
+
gap_u = unit(np.zeros(n_total), "mm")
|
|
1148
|
+
else:
|
|
1149
|
+
gap_raw = as_unit(gap, "points")
|
|
1150
|
+
if len(gap_raw) == 1:
|
|
1151
|
+
gap_u = unit(np.full(n_total, convertWidth(gap_raw, "mm", valueOnly=True)), "mm")
|
|
1152
|
+
elif len(gap_raw) == n_total - 1:
|
|
1153
|
+
gap_u = unit_c(gap_raw, unit(0.0, "mm"))
|
|
1154
|
+
elif len(gap_raw) >= n_total:
|
|
1155
|
+
gap_u = gap_raw[:n_total]
|
|
1156
|
+
else:
|
|
1157
|
+
raise ValueError("Length of `gap` does not match number of annotations.")
|
|
1158
|
+
self.gap: Unit = unit(gap_u.to_mm("x"), "mm")
|
|
1159
|
+
|
|
1160
|
+
# Initial sizing
|
|
1161
|
+
if self.which == "column":
|
|
1162
|
+
sizes_mm = [convertHeight(sa.height, "mm", valueOnly=True) for sa in self.anno_list.values()]
|
|
1163
|
+
self.anno_size = unit(sizes_mm, "mm")
|
|
1164
|
+
self.height = unit(sum(sizes_mm) + sum(self.gap.to_mm("y")[:-1]), "mm") if height is None else as_unit(height, "mm")
|
|
1165
|
+
self.width = unit(1.0, "npc") if width is None else as_unit(width, "mm")
|
|
1166
|
+
for sa in self.anno_list.values():
|
|
1167
|
+
sa.width = self.width
|
|
1168
|
+
sa.fun.width = self.width
|
|
1169
|
+
else:
|
|
1170
|
+
sizes_mm = [convertWidth(sa.width, "mm", valueOnly=True) for sa in self.anno_list.values()]
|
|
1171
|
+
self.anno_size = unit(sizes_mm, "mm")
|
|
1172
|
+
self.width = unit(sum(sizes_mm) + sum(self.gap.to_mm("x")[:-1]), "mm") if width is None else as_unit(width, "mm")
|
|
1173
|
+
self.height = unit(1.0, "npc") if height is None else as_unit(height, "mm")
|
|
1174
|
+
for sa in self.anno_list.values():
|
|
1175
|
+
sa.height = self.height
|
|
1176
|
+
sa.fun.height = self.height
|
|
1177
|
+
|
|
1178
|
+
if annotation_name_align:
|
|
1179
|
+
self._align_annotation_names()
|
|
1180
|
+
|
|
1181
|
+
self.subsettable = all(sa.subsettable for sa in self.anno_list.values())
|
|
1182
|
+
self.extended = self._compute_extended()
|
|
1183
|
+
self.param = {
|
|
1184
|
+
"simple_anno_size": simple_anno_size,
|
|
1185
|
+
"simple_anno_size_adjust": simple_anno_size_adjust,
|
|
1186
|
+
"is_height_set": is_height_set,
|
|
1187
|
+
"is_width_set": is_width_set,
|
|
1188
|
+
"is_annotation_height_set": is_anno_h_set,
|
|
1189
|
+
"is_annotation_width_set": is_anno_w_set,
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
if self.which == "column":
|
|
1193
|
+
self.re_size(height=self.height if is_height_set else None, annotation_height=annotation_height)
|
|
1194
|
+
else:
|
|
1195
|
+
self.re_size(width=self.width if is_width_set else None, annotation_width=annotation_width)
|
|
1196
|
+
|
|
1197
|
+
def _compute_extended(self) -> Unit:
|
|
1198
|
+
ext = [0.0, 0.0, 0.0, 0.0]
|
|
1199
|
+
for sa in self.anno_list.values():
|
|
1200
|
+
v = sa.extended.to_mm("x")
|
|
1201
|
+
for i in range(4):
|
|
1202
|
+
ext[i] = max(ext[i], float(v[i]))
|
|
1203
|
+
return unit(ext, "mm")
|
|
1204
|
+
|
|
1205
|
+
def _align_annotation_names(self) -> None:
|
|
1206
|
+
for side, coord_key, sign, base_val in (
|
|
1207
|
+
("bottom", "y", -1.0, 0.0),
|
|
1208
|
+
("top", "y", 1.0, 1.0),
|
|
1209
|
+
("left", "x", -1.0, 0.0),
|
|
1210
|
+
("right", "x", 1.0, 1.0),
|
|
1211
|
+
):
|
|
1212
|
+
targets = [sa for sa in self.anno_list.values() if sa.name_param["side"] == side and sa.name_param["show"] and sa.fun.fun_name != "anno_simple"]
|
|
1213
|
+
if len(targets) > 1:
|
|
1214
|
+
mx = max(convertWidth(sa.name_param["offset"], "mm", valueOnly=True) for sa in targets)
|
|
1215
|
+
u_mx = unit(mx, "mm")
|
|
1216
|
+
for sa in targets:
|
|
1217
|
+
sa.name_param["offset"] = u_mx
|
|
1218
|
+
sa.name_param[coord_key] = unit(base_val, "npc") + sign * u_mx
|
|
1219
|
+
|
|
1220
|
+
def re_size(
|
|
1221
|
+
self,
|
|
1222
|
+
annotation_height: Any = None,
|
|
1223
|
+
annotation_width: Any = None,
|
|
1224
|
+
height: Any = None,
|
|
1225
|
+
width: Any = None,
|
|
1226
|
+
simple_anno_size: Unit | None = None,
|
|
1227
|
+
simple_anno_size_adjust: bool | None = None,
|
|
1228
|
+
) -> "HeatmapAnnotation":
|
|
1229
|
+
if simple_anno_size_adjust is None:
|
|
1230
|
+
simple_anno_size_adjust = self.param.get("simple_anno_size_adjust", False)
|
|
1231
|
+
annos = list(self.anno_list.values())
|
|
1232
|
+
n = len(annos)
|
|
1233
|
+
all_simple = all(sa.fun.fun_name == "anno_simple" for sa in annos)
|
|
1234
|
+
gaps_mm = self.gap.to_mm("x")
|
|
1235
|
+
gap_sum = float(np.sum(gaps_mm[:-1])) if n > 1 else 0.0
|
|
1236
|
+
|
|
1237
|
+
anno_size_arg = annotation_height if self.which == "column" else annotation_width
|
|
1238
|
+
tot_size_arg = height if self.which == "column" else width
|
|
1239
|
+
|
|
1240
|
+
if anno_size_arg is not None:
|
|
1241
|
+
if isinstance(anno_size_arg, Unit):
|
|
1242
|
+
if is_abs_unit(anno_size_arg):
|
|
1243
|
+
s_mm = anno_size_arg.to_mm("x")
|
|
1244
|
+
if len(s_mm) == 1:
|
|
1245
|
+
s_mm = np.repeat(s_mm[0], n)
|
|
1246
|
+
for sa, v in zip(annos, s_mm):
|
|
1247
|
+
sa.size = unit(float(v), "mm")
|
|
1248
|
+
self.anno_size = unit(s_mm, "mm")
|
|
1249
|
+
tot = float(np.sum(s_mm)) + gap_sum
|
|
1250
|
+
if self.which == "column":
|
|
1251
|
+
self.height = unit(tot, "mm")
|
|
1252
|
+
else:
|
|
1253
|
+
self.width = unit(tot, "mm")
|
|
1254
|
+
return self
|
|
1255
|
+
else:
|
|
1256
|
+
# Unit with null weights
|
|
1257
|
+
weights = anno_size_arg._values if anno_size_arg._op is None else np.ones(n)
|
|
1258
|
+
else:
|
|
1259
|
+
arr = np.atleast_1d(np.asarray(anno_size_arg, dtype=float))
|
|
1260
|
+
weights = np.repeat(arr[0], n) if len(arr) == 1 else arr
|
|
1261
|
+
if tot_size_arg is None:
|
|
1262
|
+
tot_size_arg = self.height if self.which == "column" else self.width
|
|
1263
|
+
tot_mm = convertHeight(as_unit(tot_size_arg, "mm"), "mm", valueOnly=True)
|
|
1264
|
+
avail = max(0.0, tot_mm - gap_sum)
|
|
1265
|
+
s_mm = avail * (weights / float(np.sum(weights)))
|
|
1266
|
+
for sa, v in zip(annos, s_mm):
|
|
1267
|
+
sa.size = unit(float(v), "mm")
|
|
1268
|
+
self.anno_size = unit(s_mm, "mm")
|
|
1269
|
+
if self.which == "column":
|
|
1270
|
+
self.height = unit(tot_mm, "mm")
|
|
1271
|
+
else:
|
|
1272
|
+
self.width = unit(tot_mm, "mm")
|
|
1273
|
+
return self
|
|
1274
|
+
|
|
1275
|
+
if tot_size_arg is None:
|
|
1276
|
+
return self
|
|
1277
|
+
|
|
1278
|
+
if not simple_anno_size_adjust and all_simple:
|
|
1279
|
+
cur_mm = self.anno_size.to_mm("x")
|
|
1280
|
+
tot = float(np.sum(cur_mm)) + gap_sum
|
|
1281
|
+
if self.which == "column":
|
|
1282
|
+
self.height = unit(tot, "mm")
|
|
1283
|
+
else:
|
|
1284
|
+
self.width = unit(tot, "mm")
|
|
1285
|
+
return self
|
|
1286
|
+
|
|
1287
|
+
tot_mm = convertHeight(as_unit(tot_size_arg, "mm"), "mm", valueOnly=True)
|
|
1288
|
+
cur_mm = self.anno_size.to_mm("x")
|
|
1289
|
+
if simple_anno_size_adjust or not any(sa.fun.fun_name == "anno_simple" for sa in annos):
|
|
1290
|
+
avail = max(0.0, tot_mm - gap_sum)
|
|
1291
|
+
denom = float(np.sum(cur_mm))
|
|
1292
|
+
s_mm = cur_mm * (avail / denom) if denom > 0 else np.full(n, avail / n)
|
|
1293
|
+
else:
|
|
1294
|
+
simple_mask = np.array([sa.fun.fun_name == "anno_simple" for sa in annos])
|
|
1295
|
+
fixed_mm = float(np.sum(cur_mm[simple_mask]))
|
|
1296
|
+
rem_avail = max(0.0, tot_mm - gap_sum - fixed_mm)
|
|
1297
|
+
comp_sum = float(np.sum(cur_mm[~simple_mask]))
|
|
1298
|
+
s_mm = cur_mm.copy()
|
|
1299
|
+
if comp_sum > 0:
|
|
1300
|
+
s_mm[~simple_mask] = cur_mm[~simple_mask] * (rem_avail / comp_sum)
|
|
1301
|
+
|
|
1302
|
+
for sa, v in zip(annos, s_mm):
|
|
1303
|
+
sa.size = unit(float(v), "mm")
|
|
1304
|
+
self.anno_size = unit(s_mm, "mm")
|
|
1305
|
+
if self.which == "column":
|
|
1306
|
+
self.height = unit(tot_mm, "mm")
|
|
1307
|
+
else:
|
|
1308
|
+
self.width = unit(tot_mm, "mm")
|
|
1309
|
+
return self
|
|
1310
|
+
|
|
1311
|
+
@property
|
|
1312
|
+
def size(self) -> Unit:
|
|
1313
|
+
return self.width if self.which == "row" else self.height
|
|
1314
|
+
|
|
1315
|
+
@size.setter
|
|
1316
|
+
def size(self, val: Unit) -> None:
|
|
1317
|
+
if self.which == "row":
|
|
1318
|
+
self.re_size(width=val, simple_anno_size_adjust=True)
|
|
1319
|
+
else:
|
|
1320
|
+
self.re_size(height=val, simple_anno_size_adjust=True)
|
|
1321
|
+
|
|
1322
|
+
@property
|
|
1323
|
+
def names(self) -> list[str]:
|
|
1324
|
+
return list(self.anno_list.keys())
|
|
1325
|
+
|
|
1326
|
+
@names.setter
|
|
1327
|
+
def names(self, value: Sequence[str]) -> None:
|
|
1328
|
+
new_nms = [str(v) for v in value]
|
|
1329
|
+
if len(new_nms) != len(self.anno_list):
|
|
1330
|
+
raise ValueError("Length of new names must match number of annotations.")
|
|
1331
|
+
if len(set(new_nms)) != len(new_nms):
|
|
1332
|
+
raise ValueError("Annotation names must be unique.")
|
|
1333
|
+
new_dict: dict[str, SingleAnnotation] = {}
|
|
1334
|
+
for old_sa, nm in zip(self.anno_list.values(), new_nms):
|
|
1335
|
+
if old_sa.label == old_sa.name:
|
|
1336
|
+
old_sa.label = nm
|
|
1337
|
+
old_sa.name = nm
|
|
1338
|
+
old_sa.name_param["label"] = nm
|
|
1339
|
+
if old_sa.color_mapping is not None:
|
|
1340
|
+
old_sa.color_mapping.name = nm
|
|
1341
|
+
new_dict[nm] = old_sa
|
|
1342
|
+
self.anno_list = new_dict
|
|
1343
|
+
|
|
1344
|
+
def __len__(self) -> int:
|
|
1345
|
+
return len(self.anno_list)
|
|
1346
|
+
|
|
1347
|
+
def nobs(self) -> int | None:
|
|
1348
|
+
for sa in self.anno_list.values():
|
|
1349
|
+
n = sa.nobs()
|
|
1350
|
+
if n is not None:
|
|
1351
|
+
return n
|
|
1352
|
+
return None
|
|
1353
|
+
|
|
1354
|
+
def copy_all(self) -> "HeatmapAnnotation":
|
|
1355
|
+
cp = copy.copy(self)
|
|
1356
|
+
cp.anno_list = {k: sa.copy_all() for k, sa in self.anno_list.items()}
|
|
1357
|
+
cp.param = dict(self.param)
|
|
1358
|
+
return cp
|
|
1359
|
+
|
|
1360
|
+
def get_color_mapping_list(self) -> list[ColorMapping]:
|
|
1361
|
+
return [sa.color_mapping for sa in self.anno_list.values() if sa.show_legend and sa.color_mapping is not None]
|
|
1362
|
+
|
|
1363
|
+
def get_legend_param_list(self) -> list[dict[str, Any]]:
|
|
1364
|
+
return [sa.legend_param for sa in self.anno_list.values() if sa.show_legend and sa.color_mapping is not None]
|
|
1365
|
+
|
|
1366
|
+
def __getitem__(self, key: Any) -> "HeatmapAnnotation":
|
|
1367
|
+
if isinstance(key, tuple):
|
|
1368
|
+
if len(key) != 2:
|
|
1369
|
+
raise IndexError("HeatmapAnnotation expects 1D or 2D indexing.")
|
|
1370
|
+
obs_idx, anno_idx = key
|
|
1371
|
+
else:
|
|
1372
|
+
obs_idx, anno_idx = key, slice(None)
|
|
1373
|
+
|
|
1374
|
+
cp = self.copy_all()
|
|
1375
|
+
all_names = list(cp.anno_list.keys())
|
|
1376
|
+
if isinstance(anno_idx, slice):
|
|
1377
|
+
sel_indices = list(range(*anno_idx.indices(len(all_names))))
|
|
1378
|
+
elif isinstance(anno_idx, str):
|
|
1379
|
+
sel_indices = [all_names.index(anno_idx)]
|
|
1380
|
+
elif isinstance(anno_idx, (int, np.integer)):
|
|
1381
|
+
sel_indices = [int(anno_idx)]
|
|
1382
|
+
else:
|
|
1383
|
+
sel_indices = []
|
|
1384
|
+
for item in anno_idx:
|
|
1385
|
+
if isinstance(item, str):
|
|
1386
|
+
sel_indices.append(all_names.index(item))
|
|
1387
|
+
elif isinstance(item, (bool, np.bool_)):
|
|
1388
|
+
pass
|
|
1389
|
+
else:
|
|
1390
|
+
sel_indices.append(int(item))
|
|
1391
|
+
if not sel_indices and all(isinstance(x, (bool, np.bool_)) for x in anno_idx):
|
|
1392
|
+
sel_indices = [k for k, fl in enumerate(anno_idx) if fl]
|
|
1393
|
+
|
|
1394
|
+
sel_names = [all_names[k] for k in sel_indices]
|
|
1395
|
+
cp.anno_list = {nm: cp.anno_list[nm] for nm in sel_names}
|
|
1396
|
+
gaps_mm = self.gap.to_mm("x")
|
|
1397
|
+
new_gaps = [gaps_mm[k] for k in sel_indices]
|
|
1398
|
+
if new_gaps:
|
|
1399
|
+
new_gaps[-1] = 0.0
|
|
1400
|
+
cp.gap = unit(new_gaps, "mm")
|
|
1401
|
+
|
|
1402
|
+
if not (isinstance(obs_idx, slice) and obs_idx == slice(None)):
|
|
1403
|
+
for nm in sel_names:
|
|
1404
|
+
cp.anno_list[nm] = cp.anno_list[nm][obs_idx]
|
|
1405
|
+
|
|
1406
|
+
sizes_mm = [convertWidth(sa.size, "mm", valueOnly=True) for sa in cp.anno_list.values()]
|
|
1407
|
+
cp.anno_size = unit(sizes_mm, "mm")
|
|
1408
|
+
tot_mm = sum(sizes_mm) + (sum(new_gaps[:-1]) if len(new_gaps) > 1 else 0.0)
|
|
1409
|
+
if cp.which == "column":
|
|
1410
|
+
cp.height = unit(tot_mm, "mm")
|
|
1411
|
+
else:
|
|
1412
|
+
cp.width = unit(tot_mm, "mm")
|
|
1413
|
+
cp.extended = cp._compute_extended()
|
|
1414
|
+
cp.subsettable = all(sa.subsettable for sa in cp.anno_list.values())
|
|
1415
|
+
return cp
|
|
1416
|
+
|
|
1417
|
+
def draw(
|
|
1418
|
+
self,
|
|
1419
|
+
index: Sequence[int] | None = None,
|
|
1420
|
+
k: int = 1,
|
|
1421
|
+
n: int = 1,
|
|
1422
|
+
test: bool | str = False,
|
|
1423
|
+
anno_mark_param: dict[str, Any] | None = None,
|
|
1424
|
+
**vp_kwargs: Any,
|
|
1425
|
+
) -> None:
|
|
1426
|
+
if isinstance(test, str):
|
|
1427
|
+
is_test = True
|
|
1428
|
+
test_label = test
|
|
1429
|
+
else:
|
|
1430
|
+
is_test = bool(test)
|
|
1431
|
+
test_label = ""
|
|
1432
|
+
|
|
1433
|
+
if is_test:
|
|
1434
|
+
grid_newpage()
|
|
1435
|
+
ext = self.extended.to_mm("x")
|
|
1436
|
+
if self.which == "column":
|
|
1437
|
+
pushViewport(Viewport(width=unit(1, "npc") - unit(3, "cm") - unit(ext[1] + ext[3], "mm"), height=self.height))
|
|
1438
|
+
else:
|
|
1439
|
+
pushViewport(Viewport(height=unit(1, "npc") - unit(3, "cm") - unit(ext[0] + ext[2], "mm"), width=self.width))
|
|
1440
|
+
else:
|
|
1441
|
+
pushViewport(Viewport(**vp_kwargs))
|
|
1442
|
+
|
|
1443
|
+
try:
|
|
1444
|
+
if index is None:
|
|
1445
|
+
nb = self.nobs()
|
|
1446
|
+
if nb is None:
|
|
1447
|
+
raise ValueError("Cannot infer number of observations for HeatmapAnnotation.")
|
|
1448
|
+
index = list(range(nb))
|
|
1449
|
+
|
|
1450
|
+
annos = list(self.anno_list.values())
|
|
1451
|
+
n_anno = len(annos)
|
|
1452
|
+
sizes_mm = self.anno_size.to_mm("x")
|
|
1453
|
+
gaps_mm = self.gap.to_mm("x")
|
|
1454
|
+
|
|
1455
|
+
if self.which == "column":
|
|
1456
|
+
for i in range(n_anno):
|
|
1457
|
+
y_top = float(np.sum(sizes_mm[i:]) + np.sum(gaps_mm[i:]) - gaps_mm[-1])
|
|
1458
|
+
pushViewport(Viewport(y=unit(y_top, "mm"), height=unit(float(sizes_mm[i]), "mm"), just=("center", "top")))
|
|
1459
|
+
try:
|
|
1460
|
+
annos[i].draw(index, k=k, n=n, anno_mark_param=anno_mark_param)
|
|
1461
|
+
finally:
|
|
1462
|
+
popViewport()
|
|
1463
|
+
else:
|
|
1464
|
+
for i in range(n_anno):
|
|
1465
|
+
x_right = float(np.sum(sizes_mm[: i + 1]) + np.sum(gaps_mm[: i + 1]) - gaps_mm[i])
|
|
1466
|
+
pushViewport(Viewport(x=unit(x_right, "mm"), width=unit(float(sizes_mm[i]), "mm"), just=("right", "center")))
|
|
1467
|
+
try:
|
|
1468
|
+
annos[i].draw(index, k=k, n=n, anno_mark_param=anno_mark_param)
|
|
1469
|
+
finally:
|
|
1470
|
+
popViewport()
|
|
1471
|
+
|
|
1472
|
+
if is_test and test_label:
|
|
1473
|
+
grid_text(test_label, y=unit(1, "npc") + unit(2, "mm"), just="bottom")
|
|
1474
|
+
finally:
|
|
1475
|
+
popViewport()
|
|
1476
|
+
|
|
1477
|
+
def _repr_png_(self) -> bytes:
|
|
1478
|
+
import io
|
|
1479
|
+
import matplotlib.pyplot as plt
|
|
1480
|
+
dev = grid_newpage(width_in=7.0, height_in=3.5)
|
|
1481
|
+
self.draw(test=self.name)
|
|
1482
|
+
buf = io.BytesIO()
|
|
1483
|
+
dev.fig.savefig(buf, format="png", dpi=120)
|
|
1484
|
+
plt.close(dev.fig)
|
|
1485
|
+
return buf.getvalue()
|
|
1486
|
+
|
|
1487
|
+
def __repr__(self) -> str:
|
|
1488
|
+
lines = [
|
|
1489
|
+
f"A HeatmapAnnotation object with {len(self.anno_list)} annotation(s)",
|
|
1490
|
+
f" name: {self.name}",
|
|
1491
|
+
f" position: {self.which}",
|
|
1492
|
+
f" items: {self.nobs() or 'unknown'}",
|
|
1493
|
+
f" width: {self.width}",
|
|
1494
|
+
f" height: {self.height}",
|
|
1495
|
+
f" annotations: {list(self.anno_list.keys())}",
|
|
1496
|
+
]
|
|
1497
|
+
return "\n".join(lines)
|
|
1498
|
+
|
|
1499
|
+
|
|
1500
|
+
def rowAnnotation(*args: Any, **kwargs: Any) -> HeatmapAnnotation:
|
|
1501
|
+
"""Create a row HeatmapAnnotation (`which='row'`)."""
|
|
1502
|
+
kwargs.setdefault("which", "row")
|
|
1503
|
+
if args:
|
|
1504
|
+
if len(args) == 1 and isinstance(args[0], dict):
|
|
1505
|
+
return HeatmapAnnotation(_annotations=args[0], **kwargs)
|
|
1506
|
+
raise TypeError("rowAnnotation accepts named keyword arguments or a single dict.")
|
|
1507
|
+
return HeatmapAnnotation(**kwargs)
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def columnAnnotation(*args: Any, **kwargs: Any) -> HeatmapAnnotation:
|
|
1511
|
+
"""Create a column HeatmapAnnotation (`which='column'`)."""
|
|
1512
|
+
kwargs.setdefault("which", "column")
|
|
1513
|
+
if args:
|
|
1514
|
+
if len(args) == 1 and isinstance(args[0], dict):
|
|
1515
|
+
return HeatmapAnnotation(_annotations=args[0], **kwargs)
|
|
1516
|
+
raise TypeError("columnAnnotation accepts named keyword arguments or a single dict.")
|
|
1517
|
+
return HeatmapAnnotation(**kwargs)
|
|
1518
|
+
|
|
1519
|
+
|
|
1520
|
+
def c_HeatmapAnnotation(*annos: HeatmapAnnotation | None, gap: Any = unit(1, "points")) -> HeatmapAnnotation | None:
|
|
1521
|
+
"""Concatenate multiple `HeatmapAnnotation` objects with identical `which`."""
|
|
1522
|
+
items = [a for a in annos if a is not None]
|
|
1523
|
+
if not items:
|
|
1524
|
+
return None
|
|
1525
|
+
if len(items) == 1:
|
|
1526
|
+
return items[0]
|
|
1527
|
+
whiches = {a.which for a in items}
|
|
1528
|
+
if len(whiches) != 1:
|
|
1529
|
+
raise ValueError("All concatenated HeatmapAnnotations must have the same `which`.")
|
|
1530
|
+
|
|
1531
|
+
gap_u = as_unit(gap, "points")
|
|
1532
|
+
n = len(items)
|
|
1533
|
+
if len(gap_u) == 1:
|
|
1534
|
+
g_vals = [convertWidth(gap_u, "mm", valueOnly=True)] * n
|
|
1535
|
+
elif len(gap_u) == n - 1:
|
|
1536
|
+
g_vals = list(gap_u.to_mm("x")) + [0.0]
|
|
1537
|
+
else:
|
|
1538
|
+
g_vals = list(gap_u.to_mm("x")[:n])
|
|
1539
|
+
|
|
1540
|
+
out = items[0].copy_all()
|
|
1541
|
+
all_sizes = list(out.anno_size.to_mm("x"))
|
|
1542
|
+
all_gaps = list(out.gap.to_mm("x"))
|
|
1543
|
+
all_gaps[-1] = g_vals[0]
|
|
1544
|
+
|
|
1545
|
+
existing_names = list(out.anno_list.keys())
|
|
1546
|
+
new_list = dict(out.anno_list)
|
|
1547
|
+
|
|
1548
|
+
for idx in range(1, n):
|
|
1549
|
+
other = items[idx].copy_all()
|
|
1550
|
+
o_gaps = list(other.gap.to_mm("x"))
|
|
1551
|
+
o_gaps[-1] = g_vals[idx]
|
|
1552
|
+
all_sizes.extend(other.anno_size.to_mm("x"))
|
|
1553
|
+
all_gaps.extend(o_gaps)
|
|
1554
|
+
for nm, sa in other.anno_list.items():
|
|
1555
|
+
new_nm = nm
|
|
1556
|
+
if new_nm in new_list:
|
|
1557
|
+
suffix = 2
|
|
1558
|
+
while f"{nm}_{suffix}" in new_list:
|
|
1559
|
+
suffix += 1
|
|
1560
|
+
new_nm = f"{nm}_{suffix}"
|
|
1561
|
+
if sa.label == sa.name:
|
|
1562
|
+
sa.label = new_nm
|
|
1563
|
+
sa.name = new_nm
|
|
1564
|
+
sa.name_param["label"] = new_nm
|
|
1565
|
+
if sa.color_mapping is not None:
|
|
1566
|
+
sa.color_mapping.name = new_nm
|
|
1567
|
+
new_list[new_nm] = sa
|
|
1568
|
+
|
|
1569
|
+
all_gaps[-1] = 0.0
|
|
1570
|
+
out.anno_list = new_list
|
|
1571
|
+
out.anno_size = unit(all_sizes, "mm")
|
|
1572
|
+
out.gap = unit(all_gaps, "mm")
|
|
1573
|
+
tot = sum(all_sizes) + (sum(all_gaps[:-1]) if len(all_gaps) > 1 else 0.0)
|
|
1574
|
+
if out.which == "column":
|
|
1575
|
+
out.height = unit(tot, "mm")
|
|
1576
|
+
else:
|
|
1577
|
+
out.width = unit(tot, "mm")
|
|
1578
|
+
out.extended = out._compute_extended()
|
|
1579
|
+
out.subsettable = all(sa.subsettable for sa in out.anno_list.values())
|
|
1580
|
+
return out
|
|
1581
|
+
|
|
1582
|
+
|
|
1583
|
+
from .anno_funcs import ( # noqa: E402, F401
|
|
1584
|
+
anno_barplot,
|
|
1585
|
+
anno_block,
|
|
1586
|
+
anno_boxplot,
|
|
1587
|
+
anno_customize,
|
|
1588
|
+
anno_density,
|
|
1589
|
+
anno_empty,
|
|
1590
|
+
anno_histogram,
|
|
1591
|
+
anno_horizon,
|
|
1592
|
+
anno_image,
|
|
1593
|
+
anno_joyplot,
|
|
1594
|
+
anno_lines,
|
|
1595
|
+
anno_link,
|
|
1596
|
+
anno_mark,
|
|
1597
|
+
anno_numeric,
|
|
1598
|
+
anno_oncoprint_barplot,
|
|
1599
|
+
anno_points,
|
|
1600
|
+
anno_simple,
|
|
1601
|
+
anno_summary,
|
|
1602
|
+
anno_text,
|
|
1603
|
+
anno_textbox,
|
|
1604
|
+
anno_zoom,
|
|
1605
|
+
row_anno_barplot,
|
|
1606
|
+
row_anno_boxplot,
|
|
1607
|
+
row_anno_density,
|
|
1608
|
+
row_anno_histogram,
|
|
1609
|
+
row_anno_points,
|
|
1610
|
+
row_anno_text,
|
|
1611
|
+
)
|