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,488 @@
|
|
|
1
|
+
"""OncoPrint plots, alteration parsing, memoSort ordering, and alteration graphics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any, Callable, Sequence
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from ._options import _ENV, ht_opt
|
|
13
|
+
from .annotations import (
|
|
14
|
+
HeatmapAnnotation,
|
|
15
|
+
anno_oncoprint_barplot,
|
|
16
|
+
anno_text,
|
|
17
|
+
rowAnnotation,
|
|
18
|
+
)
|
|
19
|
+
from .colors import brewer_pal, to_hex_rgba
|
|
20
|
+
from .grid import (
|
|
21
|
+
Viewport,
|
|
22
|
+
grid_newpage,
|
|
23
|
+
grid_points,
|
|
24
|
+
grid_polygon,
|
|
25
|
+
grid_rect,
|
|
26
|
+
grid_segments,
|
|
27
|
+
grid_text,
|
|
28
|
+
max_text_width,
|
|
29
|
+
popViewport,
|
|
30
|
+
pushViewport,
|
|
31
|
+
)
|
|
32
|
+
from .heatmap import Heatmap
|
|
33
|
+
from .legend import Legend
|
|
34
|
+
from .units import Unit, as_unit, check_gp, convertWidth, gpar, unit
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def default_get_type(x: Any) -> list[str]:
|
|
38
|
+
"""Split alteration string on `;`, `:`, `,`, or `|` (`default_get_type.Rd`)."""
|
|
39
|
+
if x is None or (isinstance(x, float) and np.isnan(x)):
|
|
40
|
+
return []
|
|
41
|
+
s = str(x).strip()
|
|
42
|
+
if s == "" or s.upper() == "NA":
|
|
43
|
+
return []
|
|
44
|
+
parts = [p.strip() for p in re.split(r"[;:,|]", s)]
|
|
45
|
+
return [p for p in parts if p != "" and p.upper() != "NA"]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def alter_graphic(
|
|
49
|
+
graphic: str = "rect",
|
|
50
|
+
width: float = 1.0,
|
|
51
|
+
height: float = 1.0,
|
|
52
|
+
horiz_margin: Any = unit(1, "pt"),
|
|
53
|
+
vertical_margin: Any = unit(1, "pt"),
|
|
54
|
+
fill: str = "red",
|
|
55
|
+
col: str | None = None,
|
|
56
|
+
pch: Any = 16,
|
|
57
|
+
size: Any = unit(1, "char"),
|
|
58
|
+
gp: dict[str, Any] | None = None,
|
|
59
|
+
**extra_gp: Any,
|
|
60
|
+
) -> Callable[[Any, Any, Any, Any], None]:
|
|
61
|
+
"""Factory returning an alteration graphic drawer `fun(x, y, w, h)` (`alter_graphic.Rd`)."""
|
|
62
|
+
graphic = str(graphic).lower()
|
|
63
|
+
if graphic not in ("rect", "point"):
|
|
64
|
+
raise ValueError("`graphic` in `alter_graphic` must be 'rect' or 'point'.")
|
|
65
|
+
hm_u = as_unit(horiz_margin, "mm")
|
|
66
|
+
vm_u = as_unit(vertical_margin, "mm")
|
|
67
|
+
base_gp = check_gp(gp or {})
|
|
68
|
+
if fill is not None:
|
|
69
|
+
base_gp["fill"] = to_hex_rgba(fill)
|
|
70
|
+
if col is not None:
|
|
71
|
+
base_gp["col"] = to_hex_rgba(col)
|
|
72
|
+
elif "col" not in base_gp:
|
|
73
|
+
base_gp["col"] = "#00000000" if graphic == "rect" else to_hex_rgba(fill)
|
|
74
|
+
for k, v in extra_gp.items():
|
|
75
|
+
base_gp[k] = v
|
|
76
|
+
|
|
77
|
+
if graphic == "rect":
|
|
78
|
+
def _draw_rect(x: Any, y: Any, w: Any, h: Any) -> None:
|
|
79
|
+
ux = as_unit(x, "npc")
|
|
80
|
+
uy = as_unit(y, "npc")
|
|
81
|
+
uw = as_unit(w, "npc") * float(width) - hm_u * 2.0
|
|
82
|
+
uh = as_unit(h, "npc") * float(height) - vm_u * 2.0
|
|
83
|
+
grid_rect(ux, uy, uw, uh, gp=base_gp)
|
|
84
|
+
return _draw_rect
|
|
85
|
+
|
|
86
|
+
sz_u = as_unit(size, "mm")
|
|
87
|
+
def _draw_point(x: Any, y: Any, w: Any, h: Any) -> None:
|
|
88
|
+
grid_points(as_unit(x, "npc"), as_unit(y, "npc"), pch=pch, size=sz_u, gp=base_gp)
|
|
89
|
+
return _draw_point
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def unify_mat_list(mat_list: Sequence[Any] | dict[str, Any], default: Any = 0) -> Any:
|
|
93
|
+
"""Align a list/dict of named matrices or DataFrames to the union of row/col names (`unify_mat_list.Rd`)."""
|
|
94
|
+
is_dict = isinstance(mat_list, dict)
|
|
95
|
+
keys = list(mat_list.keys()) if is_dict else None
|
|
96
|
+
items = list(mat_list.values()) if is_dict else list(mat_list)
|
|
97
|
+
if not items:
|
|
98
|
+
return {} if is_dict else []
|
|
99
|
+
|
|
100
|
+
dfs: list[pd.DataFrame] = []
|
|
101
|
+
for m in items:
|
|
102
|
+
if isinstance(m, pd.DataFrame):
|
|
103
|
+
dfs.append(m.copy())
|
|
104
|
+
else:
|
|
105
|
+
arr = np.asarray(m)
|
|
106
|
+
dfs.append(pd.DataFrame(arr))
|
|
107
|
+
|
|
108
|
+
all_rows: list[Any] = []
|
|
109
|
+
all_cols: list[Any] = []
|
|
110
|
+
seen_r: set[Any] = set()
|
|
111
|
+
seen_c: set[Any] = set()
|
|
112
|
+
for df in dfs:
|
|
113
|
+
for r in df.index:
|
|
114
|
+
if r not in seen_r:
|
|
115
|
+
seen_r.add(r)
|
|
116
|
+
all_rows.append(r)
|
|
117
|
+
for c in df.columns:
|
|
118
|
+
if c not in seen_c:
|
|
119
|
+
seen_c.add(c)
|
|
120
|
+
all_cols.append(c)
|
|
121
|
+
|
|
122
|
+
out_dfs = []
|
|
123
|
+
for df in dfs:
|
|
124
|
+
re = df.reindex(index=all_rows, columns=all_cols, fill_value=default)
|
|
125
|
+
out_dfs.append(re)
|
|
126
|
+
|
|
127
|
+
if is_dict:
|
|
128
|
+
assert keys is not None
|
|
129
|
+
return dict(zip(keys, out_dfs))
|
|
130
|
+
return out_dfs
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _build_default_alter_fun(all_type: list[str], col_map: dict[str, str]) -> dict[str, Callable[..., Any]]:
|
|
134
|
+
funs: dict[str, Callable[..., Any]] = {
|
|
135
|
+
"background": alter_graphic("rect", fill="#CCCCCC", horiz_margin=unit(1, "pt"), vertical_margin=unit(1, "pt"))
|
|
136
|
+
}
|
|
137
|
+
for idx, tp in enumerate(all_type):
|
|
138
|
+
# Match classic shrinking height layers for overlapping events
|
|
139
|
+
h_frac = max(0.3, 1.0 - 0.15 * min(idx, 4))
|
|
140
|
+
funs[tp] = alter_graphic(
|
|
141
|
+
"rect",
|
|
142
|
+
width=1.0,
|
|
143
|
+
height=h_frac,
|
|
144
|
+
horiz_margin=unit(1, "pt"),
|
|
145
|
+
vertical_margin=unit(1, "pt"),
|
|
146
|
+
fill=col_map.get(tp, "#E41A1C"),
|
|
147
|
+
)
|
|
148
|
+
return funs
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def test_alter_fun(
|
|
152
|
+
alter_fun: Callable[..., Any] | dict[str, Callable[..., Any]],
|
|
153
|
+
type: Sequence[str] | None = None,
|
|
154
|
+
row_names_gp: dict[str, Any] | None = None,
|
|
155
|
+
width: float = 4.0,
|
|
156
|
+
height: float = 3.0,
|
|
157
|
+
) -> Any:
|
|
158
|
+
"""Preview all alteration graphics in `alter_fun` as a visual grid (`test_alter_fun.Rd`)."""
|
|
159
|
+
if isinstance(alter_fun, dict):
|
|
160
|
+
keys = [k for k in alter_fun.keys() if k != "background"] if type is None else list(type)
|
|
161
|
+
has_bg = "background" in alter_fun
|
|
162
|
+
else:
|
|
163
|
+
if type is None:
|
|
164
|
+
raise ValueError("`type` must be supplied when `alter_fun` is a single function.")
|
|
165
|
+
keys = list(type)
|
|
166
|
+
has_bg = False
|
|
167
|
+
|
|
168
|
+
n = len(keys)
|
|
169
|
+
dev = grid_newpage(width_in=width, height_in=height)
|
|
170
|
+
gp_lbl = check_gp(row_names_gp or gpar(fontsize=10))
|
|
171
|
+
pushViewport(Viewport(x=unit(0.1, "npc"), y=unit(0.5, "npc"), width=unit(0.8, "npc"), height=unit(0.8, "npc")))
|
|
172
|
+
try:
|
|
173
|
+
for idx, tp in enumerate(keys):
|
|
174
|
+
y_pos = unit((n - idx - 0.5) / max(1, n), "npc")
|
|
175
|
+
h_cell = unit(0.8 / max(1, n), "npc")
|
|
176
|
+
w_cell = unit(0.3, "npc")
|
|
177
|
+
x_cell = unit(0.25, "npc")
|
|
178
|
+
if isinstance(alter_fun, dict):
|
|
179
|
+
if has_bg:
|
|
180
|
+
alter_fun["background"](x_cell, y_pos, w_cell, h_cell)
|
|
181
|
+
if tp in alter_fun:
|
|
182
|
+
alter_fun[tp](x_cell, y_pos, w_cell, h_cell)
|
|
183
|
+
else:
|
|
184
|
+
alter_fun(x_cell, y_pos, w_cell, h_cell, tp)
|
|
185
|
+
grid_text(tp, x=unit(0.5, "npc"), y=y_pos, just="left", gp=gp_lbl)
|
|
186
|
+
finally:
|
|
187
|
+
popViewport()
|
|
188
|
+
return dev
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _memo_sort_columns(arr: np.ndarray, gene_order: list[int]) -> list[int]:
|
|
192
|
+
"""Classic OncoPrint memoSort across columns given ordered genes `gene_order`."""
|
|
193
|
+
ng, ns, nt = arr.shape
|
|
194
|
+
if ns == 0:
|
|
195
|
+
return []
|
|
196
|
+
any_alt = np.any(arr, axis=2) # (ng, ns)
|
|
197
|
+
# Build lexicographic keys over ordered genes (altered before non-altered; among altered, earliest type)
|
|
198
|
+
keys = []
|
|
199
|
+
for s in range(ns):
|
|
200
|
+
gene_key = []
|
|
201
|
+
for g in gene_order:
|
|
202
|
+
if any_alt[g, s]:
|
|
203
|
+
t_idx = int(np.argmax(arr[g, s, :]))
|
|
204
|
+
gene_key.append((0, t_idx))
|
|
205
|
+
else:
|
|
206
|
+
gene_key.append((1, nt))
|
|
207
|
+
total_cnt = -int(np.sum(any_alt[:, s]))
|
|
208
|
+
keys.append((tuple(gene_key), total_cnt, s))
|
|
209
|
+
keys.sort()
|
|
210
|
+
return [k[-1] for k in keys]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def oncoPrint(
|
|
214
|
+
mat: Any,
|
|
215
|
+
get_type: Callable[[Any], Sequence[str]] = default_get_type,
|
|
216
|
+
alter_fun: Callable[..., Any] | dict[str, Callable[..., Any]] | None = None,
|
|
217
|
+
alter_fun_is_vectorized: bool | None = None,
|
|
218
|
+
col: dict[str, str] | Sequence[str] | None = None,
|
|
219
|
+
top_annotation: Any = "default",
|
|
220
|
+
right_annotation: Any = "default",
|
|
221
|
+
left_annotation: Any = None,
|
|
222
|
+
bottom_annotation: Any = None,
|
|
223
|
+
show_pct: bool = True,
|
|
224
|
+
pct_gp: dict[str, Any] | None = None,
|
|
225
|
+
pct_digits: int = 0,
|
|
226
|
+
pct_side: str = "left",
|
|
227
|
+
pct_include: Sequence[str] | None = None,
|
|
228
|
+
row_labels: Any = None,
|
|
229
|
+
show_row_names: bool = True,
|
|
230
|
+
row_names_side: str = "right",
|
|
231
|
+
row_names_gp: dict[str, Any] | None = None,
|
|
232
|
+
row_split: Any = None,
|
|
233
|
+
column_labels: Any = None,
|
|
234
|
+
column_names_side: str = "bottom",
|
|
235
|
+
column_names_gp: dict[str, Any] | None = None,
|
|
236
|
+
column_split: Any = None,
|
|
237
|
+
show_column_names: bool = False,
|
|
238
|
+
row_order: Any = None,
|
|
239
|
+
column_order: Any = None,
|
|
240
|
+
remove_empty_columns: bool = False,
|
|
241
|
+
remove_empty_rows: bool = False,
|
|
242
|
+
heatmap_legend_param: dict[str, Any] | None = None,
|
|
243
|
+
name: str | None = None,
|
|
244
|
+
**kwargs: Any,
|
|
245
|
+
) -> Heatmap:
|
|
246
|
+
"""Construct an OncoPrint Heatmap (`oncoPrint.Rd`)."""
|
|
247
|
+
# Parse input: character matrix/DF OR list/dict of binary matrices/DFs
|
|
248
|
+
rownames: list[str] | None = None
|
|
249
|
+
colnames: list[str] | None = None
|
|
250
|
+
|
|
251
|
+
if isinstance(mat, (dict, list, tuple)) and not (isinstance(mat, (list, tuple)) and len(mat) > 0 and isinstance(mat[0], (str, bytes))):
|
|
252
|
+
if isinstance(mat, dict):
|
|
253
|
+
type_names = list(mat.keys())
|
|
254
|
+
aligned = unify_mat_list(mat, default=0)
|
|
255
|
+
mat_dfs = [aligned[k] for k in type_names]
|
|
256
|
+
else:
|
|
257
|
+
aligned = unify_mat_list(mat, default=0)
|
|
258
|
+
type_names = [f"type_{i+1}" for i in range(len(aligned))]
|
|
259
|
+
mat_dfs = aligned
|
|
260
|
+
if not mat_dfs:
|
|
261
|
+
raise ValueError("Empty list passed to `oncoPrint`.")
|
|
262
|
+
rownames = [str(r) for r in mat_dfs[0].index]
|
|
263
|
+
colnames = [str(c) for c in mat_dfs[0].columns]
|
|
264
|
+
ng, ns = mat_dfs[0].shape
|
|
265
|
+
all_type = list(type_names)
|
|
266
|
+
arr = np.zeros((ng, ns, len(all_type)), dtype=bool)
|
|
267
|
+
for ti, df_t in enumerate(mat_dfs):
|
|
268
|
+
arr[:, :, ti] = df_t.to_numpy(dtype=float) != 0
|
|
269
|
+
str_mat = np.empty((ng, ns), dtype=object)
|
|
270
|
+
for r in range(ng):
|
|
271
|
+
for c in range(ns):
|
|
272
|
+
str_mat[r, c] = ";".join(all_type[ti] for ti in range(len(all_type)) if arr[r, c, ti])
|
|
273
|
+
else:
|
|
274
|
+
if isinstance(mat, pd.DataFrame):
|
|
275
|
+
rownames = [str(r) for r in mat.index]
|
|
276
|
+
colnames = [str(c) for c in mat.columns]
|
|
277
|
+
raw = mat.to_numpy(dtype=object)
|
|
278
|
+
else:
|
|
279
|
+
raw = np.asarray(mat, dtype=object)
|
|
280
|
+
if raw.ndim != 2:
|
|
281
|
+
raise ValueError("`mat` must be 2D matrix/DataFrame or dict/list of binary matrices.")
|
|
282
|
+
ng, ns = raw.shape
|
|
283
|
+
parsed: list[list[list[str]]] = [[list(get_type(raw[r, c])) for c in range(ns)] for r in range(ng)]
|
|
284
|
+
seen_types: list[str] = []
|
|
285
|
+
seen_set: set[str] = set()
|
|
286
|
+
for r in range(ng):
|
|
287
|
+
for c in range(ns):
|
|
288
|
+
for tp in parsed[r][c]:
|
|
289
|
+
if tp not in seen_set:
|
|
290
|
+
seen_set.add(tp)
|
|
291
|
+
seen_types.append(tp)
|
|
292
|
+
all_type = seen_types
|
|
293
|
+
if col is not None and isinstance(col, dict):
|
|
294
|
+
# Preserve col dict ordering if keys overlap
|
|
295
|
+
extra = [t for t in all_type if t not in col]
|
|
296
|
+
all_type = [t for t in col.keys() if t in seen_set] + extra
|
|
297
|
+
type_to_idx = {tp: i for i, tp in enumerate(all_type)}
|
|
298
|
+
arr = np.zeros((ng, ns, max(1, len(all_type))), dtype=bool)
|
|
299
|
+
for r in range(ng):
|
|
300
|
+
for c in range(ns):
|
|
301
|
+
for tp in parsed[r][c]:
|
|
302
|
+
arr[r, c, type_to_idx[tp]] = True
|
|
303
|
+
if len(all_type) == 0:
|
|
304
|
+
arr = np.zeros((ng, ns, 0), dtype=bool)
|
|
305
|
+
str_mat = np.array([[";".join(parsed[r][c]) for c in range(ns)] for r in range(ng)], dtype=object)
|
|
306
|
+
|
|
307
|
+
# Remove empty rows/columns if requested
|
|
308
|
+
if remove_empty_rows and ng > 0:
|
|
309
|
+
keep_r = np.any(arr, axis=(1, 2))
|
|
310
|
+
arr = arr[keep_r, :, :]
|
|
311
|
+
str_mat = str_mat[keep_r, :]
|
|
312
|
+
if rownames is not None:
|
|
313
|
+
rownames = [r for r, f in zip(rownames, keep_r) if f]
|
|
314
|
+
if row_labels is not None:
|
|
315
|
+
row_labels = [r for r, f in zip(row_labels, keep_r) if f]
|
|
316
|
+
ng = arr.shape[0]
|
|
317
|
+
if remove_empty_columns and ns > 0:
|
|
318
|
+
keep_c = np.any(arr, axis=(0, 2))
|
|
319
|
+
arr = arr[:, keep_c, :]
|
|
320
|
+
str_mat = str_mat[:, keep_c]
|
|
321
|
+
if colnames is not None:
|
|
322
|
+
colnames = [c for c, f in zip(colnames, keep_c) if f]
|
|
323
|
+
if column_labels is not None:
|
|
324
|
+
column_labels = [c for c, f in zip(column_labels, keep_c) if f]
|
|
325
|
+
ns = arr.shape[1]
|
|
326
|
+
|
|
327
|
+
# Colors
|
|
328
|
+
nt = len(all_type)
|
|
329
|
+
if col is None:
|
|
330
|
+
pal = brewer_pal(max(nt, 3), "Set1")
|
|
331
|
+
if nt > len(pal):
|
|
332
|
+
from .colors import rand_color
|
|
333
|
+
pal = list(pal) + list(rand_color(nt - len(pal)))
|
|
334
|
+
col_map = {tp: to_hex_rgba(pal[i]) for i, tp in enumerate(all_type)}
|
|
335
|
+
elif isinstance(col, dict):
|
|
336
|
+
col_map = {tp: to_hex_rgba(col.get(tp, "#E41A1C")) for tp in all_type}
|
|
337
|
+
else:
|
|
338
|
+
col_seq = [to_hex_rgba(c) for c in col]
|
|
339
|
+
col_map = {tp: col_seq[i % len(col_seq)] for i, tp in enumerate(all_type)}
|
|
340
|
+
|
|
341
|
+
if alter_fun is None:
|
|
342
|
+
eff_alter_fun = _build_default_alter_fun(all_type, col_map)
|
|
343
|
+
is_vec = True
|
|
344
|
+
elif callable(alter_fun) and not isinstance(alter_fun, dict):
|
|
345
|
+
eff_alter_fun = alter_fun
|
|
346
|
+
is_vec = bool(alter_fun_is_vectorized) if alter_fun_is_vectorized is not None else False
|
|
347
|
+
elif isinstance(alter_fun, dict):
|
|
348
|
+
eff_alter_fun = dict(alter_fun)
|
|
349
|
+
is_vec = bool(alter_fun_is_vectorized) if alter_fun_is_vectorized is not None else False
|
|
350
|
+
else:
|
|
351
|
+
raise TypeError("`alter_fun` must be a dict of callables or a callable.")
|
|
352
|
+
|
|
353
|
+
# Default gene & sample orders
|
|
354
|
+
if row_order is None:
|
|
355
|
+
gene_freq = np.sum(np.any(arr, axis=2), axis=1) if nt > 0 else np.zeros(ng, dtype=int)
|
|
356
|
+
eff_row_order = np.argsort(-gene_freq, kind="stable").tolist()
|
|
357
|
+
else:
|
|
358
|
+
eff_row_order = list(row_order)
|
|
359
|
+
|
|
360
|
+
if column_order is None:
|
|
361
|
+
eff_col_order = _memo_sort_columns(arr, eff_row_order) if nt > 0 else list(range(ns))
|
|
362
|
+
else:
|
|
363
|
+
eff_col_order = list(column_order)
|
|
364
|
+
|
|
365
|
+
# Layer function rendering OncoPrint alteration graphics
|
|
366
|
+
def _layer_fun(j: Any, i: Any, x: Any, y: Any, w: Any, h: Any, fill: Any) -> None:
|
|
367
|
+
n_cells = len(j)
|
|
368
|
+
if n_cells == 0:
|
|
369
|
+
return
|
|
370
|
+
if isinstance(eff_alter_fun, dict):
|
|
371
|
+
if "background" in eff_alter_fun:
|
|
372
|
+
bg_fn = eff_alter_fun["background"]
|
|
373
|
+
if is_vec:
|
|
374
|
+
bg_fn(x, y, w, h)
|
|
375
|
+
else:
|
|
376
|
+
for k in range(n_cells):
|
|
377
|
+
bg_fn(x[k], y[k], w[k], h[k])
|
|
378
|
+
for ti, tp in enumerate(all_type):
|
|
379
|
+
if tp not in eff_alter_fun:
|
|
380
|
+
continue
|
|
381
|
+
mask = arr[np.asarray(i, dtype=int), np.asarray(j, dtype=int), ti]
|
|
382
|
+
idx_m = np.where(mask)[0]
|
|
383
|
+
if len(idx_m) == 0:
|
|
384
|
+
continue
|
|
385
|
+
fn = eff_alter_fun[tp]
|
|
386
|
+
if is_vec:
|
|
387
|
+
fn(x[idx_m], y[idx_m], w[idx_m], h[idx_m])
|
|
388
|
+
else:
|
|
389
|
+
for k in idx_m:
|
|
390
|
+
fn(x[k], y[k], w[k], h[k])
|
|
391
|
+
else:
|
|
392
|
+
# Single callable alter_fun(x, y, w, h, v)
|
|
393
|
+
sig = inspect.signature(eff_alter_fun)
|
|
394
|
+
for k in range(n_cells):
|
|
395
|
+
v_types = [all_type[ti] for ti in range(nt) if arr[int(i[k]), int(j[k]), ti]]
|
|
396
|
+
if not v_types:
|
|
397
|
+
v_arg: Any = "background"
|
|
398
|
+
elif len(v_types) == 1:
|
|
399
|
+
v_arg = v_types[0]
|
|
400
|
+
else:
|
|
401
|
+
v_arg = v_types
|
|
402
|
+
if len(sig.parameters) >= 5:
|
|
403
|
+
eff_alter_fun(x[k], y[k], w[k], h[k], v_arg)
|
|
404
|
+
else:
|
|
405
|
+
eff_alter_fun(x[k], y[k], w[k], h[k])
|
|
406
|
+
|
|
407
|
+
# Default top and right barplot annotations
|
|
408
|
+
eff_top = HeatmapAnnotation(cbar=anno_oncoprint_barplot(), name="cbar_anno") if top_annotation == "default" else top_annotation
|
|
409
|
+
eff_right = rowAnnotation(rbar=anno_oncoprint_barplot(), name="rbar_anno") if right_annotation == "default" else right_annotation
|
|
410
|
+
eff_left = left_annotation
|
|
411
|
+
eff_bottom = bottom_annotation
|
|
412
|
+
|
|
413
|
+
# Add alteration percentage text annotation
|
|
414
|
+
if show_pct and ng > 0:
|
|
415
|
+
if pct_include is not None:
|
|
416
|
+
inc_idx = [ti for ti, tp in enumerate(all_type) if tp in set(pct_include)]
|
|
417
|
+
alt_any = np.any(arr[:, :, inc_idx], axis=2) if inc_idx else np.zeros((ng, ns), dtype=bool)
|
|
418
|
+
else:
|
|
419
|
+
alt_any = np.any(arr, axis=2) if nt > 0 else np.zeros((ng, ns), dtype=bool)
|
|
420
|
+
pct_vals = np.mean(alt_any, axis=1) * 100.0
|
|
421
|
+
pct_strs = [f"{v:.{int(pct_digits)}f}%" for v in pct_vals]
|
|
422
|
+
p_gp = check_gp(pct_gp or gpar(fontsize=10))
|
|
423
|
+
p_just = "right" if pct_side == "left" else "left"
|
|
424
|
+
p_loc = unit(1.0, "npc") if pct_side == "left" else unit(0.0, "npc")
|
|
425
|
+
pct_anno = anno_text(
|
|
426
|
+
pct_strs,
|
|
427
|
+
which="row",
|
|
428
|
+
gp=p_gp,
|
|
429
|
+
just=p_just,
|
|
430
|
+
location=p_loc,
|
|
431
|
+
width=max_text_width(pct_strs, gp=p_gp) + unit(2.0, "mm"),
|
|
432
|
+
)
|
|
433
|
+
pct_ha = rowAnnotation(pct=pct_anno, show_annotation_name=False)
|
|
434
|
+
if pct_side == "left":
|
|
435
|
+
eff_left = pct_ha if eff_left is None else (pct_ha + eff_left if isinstance(pct_ha, HeatmapAnnotation) else pct_ha)
|
|
436
|
+
if eff_left is not pct_ha:
|
|
437
|
+
from .annotations import c_HeatmapAnnotation
|
|
438
|
+
eff_left = c_HeatmapAnnotation(left_annotation, pct_ha)
|
|
439
|
+
else:
|
|
440
|
+
if eff_right is None:
|
|
441
|
+
eff_right = pct_ha
|
|
442
|
+
else:
|
|
443
|
+
from .annotations import c_HeatmapAnnotation
|
|
444
|
+
eff_right = c_HeatmapAnnotation(pct_ha, eff_right)
|
|
445
|
+
|
|
446
|
+
hlp = dict(heatmap_legend_param) if heatmap_legend_param else {"title": "Alterations", "at": all_type, "labels": all_type}
|
|
447
|
+
hlp.setdefault("title", "Alterations")
|
|
448
|
+
|
|
449
|
+
df_mat = pd.DataFrame(str_mat, index=rownames, columns=colnames)
|
|
450
|
+
ht_name = name or f"oncoprint_{_ENV.next_heatmap_index()}"
|
|
451
|
+
|
|
452
|
+
# ColorMapping representing alterations legend
|
|
453
|
+
from .colors import ColorMapping
|
|
454
|
+
cm_op = ColorMapping(name=ht_name, colors=col_map) if nt > 0 else None
|
|
455
|
+
|
|
456
|
+
ht = Heatmap(
|
|
457
|
+
df_mat,
|
|
458
|
+
col=cm_op,
|
|
459
|
+
name=ht_name,
|
|
460
|
+
rect_gp=gpar(type="none"),
|
|
461
|
+
layer_fun=_layer_fun,
|
|
462
|
+
cluster_rows=False,
|
|
463
|
+
cluster_columns=False,
|
|
464
|
+
row_order=eff_row_order,
|
|
465
|
+
column_order=eff_col_order,
|
|
466
|
+
row_labels=row_labels if row_labels is not None else rownames,
|
|
467
|
+
show_row_names=show_row_names,
|
|
468
|
+
row_names_side=row_names_side,
|
|
469
|
+
row_names_gp=row_names_gp,
|
|
470
|
+
row_split=row_split,
|
|
471
|
+
column_labels=column_labels if column_labels is not None else colnames,
|
|
472
|
+
show_column_names=show_column_names,
|
|
473
|
+
column_names_side=column_names_side,
|
|
474
|
+
column_names_gp=column_names_gp,
|
|
475
|
+
column_split=column_split,
|
|
476
|
+
top_annotation=eff_top,
|
|
477
|
+
right_annotation=eff_right,
|
|
478
|
+
left_annotation=eff_left,
|
|
479
|
+
bottom_annotation=eff_bottom,
|
|
480
|
+
heatmap_legend_param=hlp,
|
|
481
|
+
**kwargs,
|
|
482
|
+
)
|
|
483
|
+
ht._oncoprint_env = {
|
|
484
|
+
"arr": arr,
|
|
485
|
+
"all_type": all_type,
|
|
486
|
+
"col": col_map,
|
|
487
|
+
}
|
|
488
|
+
return ht
|