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,188 @@
|
|
|
1
|
+
"""3D isometric bar primitive (`bar3D`) and 3D heatmap (`Heatmap3D`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from typing import Any, Sequence
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from ._options import _ENV
|
|
11
|
+
from .colors import add_luminance, to_hex_rgba
|
|
12
|
+
from .grid import GTree, current_viewport, grid_rect, polygonGrob
|
|
13
|
+
from .heatmap import Heatmap
|
|
14
|
+
from .units import Unit, as_unit, convertWidth, gpar, unit, unit_c
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def bar3D(
|
|
18
|
+
x: Any = unit(0.5, "npc"),
|
|
19
|
+
y: Any = unit(0.5, "npc"),
|
|
20
|
+
w: Any = unit(0.2, "npc"),
|
|
21
|
+
h: Any = unit(0.2, "npc"),
|
|
22
|
+
l: Any = unit(1, "cm"),
|
|
23
|
+
theta: float = 60.0,
|
|
24
|
+
default_units: str = "npc",
|
|
25
|
+
fill: Any = "white",
|
|
26
|
+
col: Any = "black",
|
|
27
|
+
draw: bool = True,
|
|
28
|
+
**kwargs: Any,
|
|
29
|
+
) -> GTree:
|
|
30
|
+
"""Draw 3D isometric rectangular bar(s) (`bar3D.Rd`). Supports vectorized coordinates."""
|
|
31
|
+
default_units = kwargs.pop("default.units", default_units)
|
|
32
|
+
if float(theta) < 0 or float(theta) > 90:
|
|
33
|
+
raise ValueError("`theta` must be between 0 and 90 degrees.")
|
|
34
|
+
|
|
35
|
+
ux = as_unit(x, default_units)
|
|
36
|
+
uy = as_unit(y, default_units)
|
|
37
|
+
uw = as_unit(w, default_units)
|
|
38
|
+
uh = as_unit(h, default_units)
|
|
39
|
+
ul = as_unit(l, default_units)
|
|
40
|
+
|
|
41
|
+
n = max(len(ux), len(uy), len(uw), len(uh), len(ul))
|
|
42
|
+
if len(ux) == 1 and n > 1:
|
|
43
|
+
ux = unit_c(*([ux] * n))
|
|
44
|
+
if len(uy) == 1 and n > 1:
|
|
45
|
+
uy = unit_c(*([uy] * n))
|
|
46
|
+
if len(uw) == 1 and n > 1:
|
|
47
|
+
uw = unit_c(*([uw] * n))
|
|
48
|
+
if len(uh) == 1 and n > 1:
|
|
49
|
+
uh = unit_c(*([uh] * n))
|
|
50
|
+
if len(ul) == 1 and n > 1:
|
|
51
|
+
ul = unit_c(*([ul] * n))
|
|
52
|
+
|
|
53
|
+
if isinstance(fill, (str, int, np.integer, float, np.floating)) or fill is None:
|
|
54
|
+
fill_seq = [fill] * n
|
|
55
|
+
else:
|
|
56
|
+
fl = list(fill)
|
|
57
|
+
fill_seq = [fl[i % len(fl)] for i in range(n)]
|
|
58
|
+
|
|
59
|
+
th_rad = math.radians(float(theta))
|
|
60
|
+
dx = ul * math.cos(th_rad)
|
|
61
|
+
dy = ul * math.sin(th_rad)
|
|
62
|
+
|
|
63
|
+
x1 = ux - uw * 0.5
|
|
64
|
+
x2 = ux + uw * 0.5
|
|
65
|
+
y1 = uy - uh * 0.5
|
|
66
|
+
y2 = uy + uh * 0.5
|
|
67
|
+
|
|
68
|
+
xu = ux + dx
|
|
69
|
+
yu = uy + dy
|
|
70
|
+
a1 = xu - uw * 0.5
|
|
71
|
+
a2 = xu + uw * 0.5
|
|
72
|
+
b1 = yu - uh * 0.5
|
|
73
|
+
b2 = yu + uh * 0.5
|
|
74
|
+
|
|
75
|
+
px_parts: list[Unit] = []
|
|
76
|
+
py_parts: list[Unit] = []
|
|
77
|
+
pids: list[int] = []
|
|
78
|
+
pfills: list[str] = []
|
|
79
|
+
pid = 1
|
|
80
|
+
for i in range(n):
|
|
81
|
+
fill2 = add_luminance(fill_seq[i])
|
|
82
|
+
# front slope (fill2[1])
|
|
83
|
+
px_parts.extend([x1[i], a1[i], a2[i], x2[i]])
|
|
84
|
+
py_parts.extend([y1[i], b1[i], b1[i], y1[i]])
|
|
85
|
+
pids.extend([pid] * 4)
|
|
86
|
+
pfills.append(fill2[min(1, len(fill2) - 1)])
|
|
87
|
+
pid += 1
|
|
88
|
+
# left face (fill2[2])
|
|
89
|
+
px_parts.extend([x1[i], x1[i], a1[i], a1[i]])
|
|
90
|
+
py_parts.extend([y1[i], y2[i], b2[i], b1[i]])
|
|
91
|
+
pids.extend([pid] * 4)
|
|
92
|
+
pfills.append(fill2[min(2, len(fill2) - 1)])
|
|
93
|
+
pid += 1
|
|
94
|
+
# top face (fill2[0])
|
|
95
|
+
px_parts.extend([a1[i], a1[i], a2[i], a2[i]])
|
|
96
|
+
py_parts.extend([b1[i], b2[i], b2[i], b1[i]])
|
|
97
|
+
pids.extend([pid] * 4)
|
|
98
|
+
pfills.append(fill2[0])
|
|
99
|
+
pid += 1
|
|
100
|
+
|
|
101
|
+
col_val = to_hex_rgba(col) if col is not None else "transparent"
|
|
102
|
+
poly = polygonGrob(
|
|
103
|
+
x=unit_c(*px_parts),
|
|
104
|
+
y=unit_c(*py_parts),
|
|
105
|
+
id=pids,
|
|
106
|
+
gp=gpar(fill=pfills, col=col_val),
|
|
107
|
+
)
|
|
108
|
+
gt = GTree(children=[poly], cl="bar3D")
|
|
109
|
+
if draw:
|
|
110
|
+
gt.draw()
|
|
111
|
+
return gt
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def Heatmap3D(
|
|
115
|
+
matrix: Any,
|
|
116
|
+
col: Any = None,
|
|
117
|
+
name: str | None = None,
|
|
118
|
+
bar_rel_width: float = 0.6,
|
|
119
|
+
bar_rel_height: float = 0.6,
|
|
120
|
+
bar_max_length: Unit = unit(1, "cm"),
|
|
121
|
+
bar_angle: float = 60.0,
|
|
122
|
+
row_names_side: str = "left",
|
|
123
|
+
show_row_dend: bool = False,
|
|
124
|
+
show_column_dend: bool = False,
|
|
125
|
+
rect_gp: dict[str, Any] | None = None,
|
|
126
|
+
**kwargs: Any,
|
|
127
|
+
) -> Heatmap:
|
|
128
|
+
"""Create a 3D bar heatmap (`Heatmap3D.Rd`). Matrix must be numeric and non-negative."""
|
|
129
|
+
arr = np.asarray(matrix, dtype=float)
|
|
130
|
+
finite = arr[np.isfinite(arr)]
|
|
131
|
+
if len(finite) > 0 and float(np.min(finite)) < 0:
|
|
132
|
+
raise ValueError("`Heatmap3D` requires a non-negative numeric matrix.")
|
|
133
|
+
vmax = float(np.max(finite)) if len(finite) > 0 and float(np.max(finite)) > 0 else 1.0
|
|
134
|
+
|
|
135
|
+
max_len_mm = convertWidth(as_unit(bar_max_length, "mm"), "mm", valueOnly=True)
|
|
136
|
+
ht_name = name or f"heatmap3d_{_ENV.next_heatmap_index()}"
|
|
137
|
+
|
|
138
|
+
from .utils import restore_matrix
|
|
139
|
+
|
|
140
|
+
user_cell_col = (rect_gp or {}).get("col", "#444444")
|
|
141
|
+
|
|
142
|
+
def _layer_fun(j: Any, i: Any, x: Any, y: Any, w: Any, h: Any, fill: Any) -> None:
|
|
143
|
+
vp = current_viewport()
|
|
144
|
+
grid_rect(x=x, y=y, width=w, height=h, gp=gpar(col="white", fill="#EEEEEE"))
|
|
145
|
+
ind_mat = restore_matrix(j, i, x, y)
|
|
146
|
+
nr_s, nc_s = ind_mat.shape
|
|
147
|
+
x_mm = x.to_mm("x", vp, pos_mode=True) if isinstance(x, Unit) else np.asarray(x, dtype=float)
|
|
148
|
+
y_mm = y.to_mm("y", vp, pos_mode=True) if isinstance(y, Unit) else np.asarray(y, dtype=float)
|
|
149
|
+
w_mm = w.to_mm("x", vp, pos_mode=False) if isinstance(w, Unit) else np.asarray(w, dtype=float)
|
|
150
|
+
h_mm = h.to_mm("y", vp, pos_mode=False) if isinstance(h, Unit) else np.asarray(h, dtype=float)
|
|
151
|
+
|
|
152
|
+
cos_t = math.cos(math.radians(float(bar_angle)))
|
|
153
|
+
col_order = range(nc_s - 1, -1, -1) if cos_t >= 0 else range(nc_s)
|
|
154
|
+
|
|
155
|
+
for ri in range(nr_s):
|
|
156
|
+
for ci in col_order:
|
|
157
|
+
pos = int(ind_mat[ri, ci])
|
|
158
|
+
if pos < 0:
|
|
159
|
+
continue
|
|
160
|
+
orig_i = int(i[pos])
|
|
161
|
+
orig_j = int(j[pos])
|
|
162
|
+
val = float(arr[orig_i, orig_j])
|
|
163
|
+
if np.isnan(val):
|
|
164
|
+
continue
|
|
165
|
+
l_mm = (val / vmax) * max_len_mm
|
|
166
|
+
bar3D(
|
|
167
|
+
x=unit(float(x_mm[pos]), "mm"),
|
|
168
|
+
y=unit(float(y_mm[pos]), "mm"),
|
|
169
|
+
w=unit(float(w_mm[pos]) * float(bar_rel_width), "mm"),
|
|
170
|
+
h=unit(float(h_mm[pos]) * float(bar_rel_height), "mm"),
|
|
171
|
+
l=unit(l_mm, "mm"),
|
|
172
|
+
theta=bar_angle,
|
|
173
|
+
fill=fill[pos],
|
|
174
|
+
col=user_cell_col,
|
|
175
|
+
draw=True,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
return Heatmap(
|
|
179
|
+
matrix,
|
|
180
|
+
col=col,
|
|
181
|
+
name=ht_name,
|
|
182
|
+
rect_gp=gpar(type="none"),
|
|
183
|
+
layer_fun=_layer_fun,
|
|
184
|
+
row_names_side=row_names_side,
|
|
185
|
+
show_row_dend=show_row_dend,
|
|
186
|
+
show_column_dend=show_column_dend,
|
|
187
|
+
**kwargs,
|
|
188
|
+
)
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Drop-in translations of pheatmap, stats::heatmap, and gplots::heatmap.2."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Sequence
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from .annotations import HeatmapAnnotation, rowAnnotation
|
|
11
|
+
from .colors import brewer_pal, colorRamp2, hcl_colors
|
|
12
|
+
from .dendrogram import as_dendrogram, cutree, dist as calc_dist, hclust
|
|
13
|
+
from .grid import grid_text
|
|
14
|
+
from .heatmap import Heatmap
|
|
15
|
+
from .heatmap_list import HeatmapList, draw
|
|
16
|
+
from .units import Unit, check_gp, gpar, unit
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _scale_matrix(mat: np.ndarray, scale: str) -> np.ndarray:
|
|
20
|
+
x = np.asarray(mat, dtype=float).copy()
|
|
21
|
+
if scale == "row":
|
|
22
|
+
m = np.nanmean(x, axis=1, keepdims=True)
|
|
23
|
+
s = np.nanstd(x, axis=1, ddof=1, keepdims=True)
|
|
24
|
+
s = np.where((s == 0) | np.isnan(s), 1.0, s)
|
|
25
|
+
x = (x - m) / s
|
|
26
|
+
elif scale == "column":
|
|
27
|
+
m = np.nanmean(x, axis=0, keepdims=True)
|
|
28
|
+
s = np.nanstd(x, axis=0, ddof=1, keepdims=True)
|
|
29
|
+
s = np.where((s == 0) | np.isnan(s), 1.0, s)
|
|
30
|
+
x = (x - m) / s
|
|
31
|
+
return x
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def pheatmap(
|
|
35
|
+
mat: Any,
|
|
36
|
+
color: Sequence[str] | None = None,
|
|
37
|
+
kmeans_k: int | None = None,
|
|
38
|
+
breaks: Sequence[float] | None = None,
|
|
39
|
+
border_color: str | None = "#999999",
|
|
40
|
+
cellwidth: float | None = None,
|
|
41
|
+
cellheight: float | None = None,
|
|
42
|
+
scale: str = "none",
|
|
43
|
+
cluster_rows: Any = True,
|
|
44
|
+
cluster_cols: Any = True,
|
|
45
|
+
clustering_distance_rows: str = "euclidean",
|
|
46
|
+
clustering_distance_cols: str = "euclidean",
|
|
47
|
+
clustering_method: str = "complete",
|
|
48
|
+
clustering_callback: Any = None,
|
|
49
|
+
cutree_rows: int | None = None,
|
|
50
|
+
cutree_cols: int | None = None,
|
|
51
|
+
treeheight_row: float | None = None,
|
|
52
|
+
treeheight_col: float | None = None,
|
|
53
|
+
legend: bool = True,
|
|
54
|
+
legend_breaks: Sequence[float] | None = None,
|
|
55
|
+
legend_labels: Sequence[str] | None = None,
|
|
56
|
+
annotation_row: pd.DataFrame | None = None,
|
|
57
|
+
annotation_col: pd.DataFrame | None = None,
|
|
58
|
+
annotation: pd.DataFrame | None = None,
|
|
59
|
+
annotation_colors: dict[str, Any] | None = None,
|
|
60
|
+
annotation_legend: bool = True,
|
|
61
|
+
annotation_names_row: bool = True,
|
|
62
|
+
annotation_names_col: bool = True,
|
|
63
|
+
drop_levels: bool = True,
|
|
64
|
+
show_rownames: bool = True,
|
|
65
|
+
show_colnames: bool = True,
|
|
66
|
+
main: str | None = None,
|
|
67
|
+
fontsize: float = 10.0,
|
|
68
|
+
fontsize_row: float | None = None,
|
|
69
|
+
fontsize_col: float | None = None,
|
|
70
|
+
angle_col: float = 270.0,
|
|
71
|
+
display_numbers: Any = False,
|
|
72
|
+
number_format: str = "{:.2f}",
|
|
73
|
+
number_color: str = "#333333",
|
|
74
|
+
fontsize_number: float | None = None,
|
|
75
|
+
gaps_row: Sequence[int] | None = None,
|
|
76
|
+
gaps_col: Sequence[int] | None = None,
|
|
77
|
+
labels_row: Sequence[str] | None = None,
|
|
78
|
+
labels_col: Sequence[str] | None = None,
|
|
79
|
+
filename: str | None = None,
|
|
80
|
+
width: float | None = None,
|
|
81
|
+
height: float | None = None,
|
|
82
|
+
silent: bool = False,
|
|
83
|
+
na_col: str = "#DDDDDD",
|
|
84
|
+
name: str | None = None,
|
|
85
|
+
run_draw: bool = False,
|
|
86
|
+
**kwargs: Any,
|
|
87
|
+
) -> Heatmap:
|
|
88
|
+
"""R `pheatmap::pheatmap()` API translated cleanly to ComplexHeatmap (`pheatmap.Rd`)."""
|
|
89
|
+
if isinstance(mat, pd.DataFrame):
|
|
90
|
+
rn = list(mat.index.astype(str))
|
|
91
|
+
cn = list(mat.columns.astype(str))
|
|
92
|
+
arr = mat.to_numpy(dtype=float)
|
|
93
|
+
else:
|
|
94
|
+
arr = np.asarray(mat, dtype=float)
|
|
95
|
+
rn = [str(i) for i in range(arr.shape[0])]
|
|
96
|
+
cn = [str(j) for j in range(arr.shape[1])]
|
|
97
|
+
|
|
98
|
+
arr = _scale_matrix(arr, str(scale).lower())
|
|
99
|
+
df_mat = pd.DataFrame(arr, index=rn, columns=cn)
|
|
100
|
+
|
|
101
|
+
# Color scale
|
|
102
|
+
if color is None:
|
|
103
|
+
pal = hcl_colors(100, "RdYlBu", rev=True)
|
|
104
|
+
else:
|
|
105
|
+
pal = list(color)
|
|
106
|
+
finite = arr[np.isfinite(arr)]
|
|
107
|
+
vmin = float(np.min(finite)) if len(finite) else -1.0
|
|
108
|
+
vmax = float(np.max(finite)) if len(finite) else 1.0
|
|
109
|
+
if vmin == vmax:
|
|
110
|
+
vmax = vmin + 1.0
|
|
111
|
+
if breaks is not None:
|
|
112
|
+
br = np.asarray(breaks, dtype=float)
|
|
113
|
+
if len(br) == len(pal):
|
|
114
|
+
col_fun = colorRamp2(br, pal)
|
|
115
|
+
else:
|
|
116
|
+
col_fun = colorRamp2(np.linspace(float(br[0]), float(br[-1]), len(pal)), pal)
|
|
117
|
+
else:
|
|
118
|
+
col_fun = colorRamp2(np.linspace(vmin, vmax, len(pal)), pal)
|
|
119
|
+
|
|
120
|
+
# Distance aliases ('correlation' -> 'pearson')
|
|
121
|
+
d_row = "pearson" if clustering_distance_rows == "correlation" else clustering_distance_rows
|
|
122
|
+
d_col = "pearson" if clustering_distance_cols == "correlation" else clustering_distance_cols
|
|
123
|
+
|
|
124
|
+
# Row / col splits from gaps or cutree
|
|
125
|
+
row_split: Any = None
|
|
126
|
+
col_split: Any = None
|
|
127
|
+
if not cluster_rows and gaps_row:
|
|
128
|
+
grp = np.zeros(arr.shape[0], dtype=int)
|
|
129
|
+
for idx_g, g in enumerate(sorted(set(gaps_row)), start=1):
|
|
130
|
+
grp[int(g):] = idx_g
|
|
131
|
+
row_split = pd.Categorical([f"gap_{k}" for k in grp], categories=[f"gap_{k}" for k in range(max(grp) + 1)], ordered=True)
|
|
132
|
+
elif cluster_rows and cutree_rows is not None and int(cutree_rows) > 1:
|
|
133
|
+
row_split = int(cutree_rows)
|
|
134
|
+
|
|
135
|
+
if not cluster_cols and gaps_col:
|
|
136
|
+
grp = np.zeros(arr.shape[1], dtype=int)
|
|
137
|
+
for idx_g, g in enumerate(sorted(set(gaps_col)), start=1):
|
|
138
|
+
grp[int(g):] = idx_g
|
|
139
|
+
col_split = pd.Categorical([f"gap_{k}" for k in grp], categories=[f"gap_{k}" for k in range(max(grp) + 1)], ordered=True)
|
|
140
|
+
elif cluster_cols and cutree_cols is not None and int(cutree_cols) > 1:
|
|
141
|
+
col_split = int(cutree_cols)
|
|
142
|
+
|
|
143
|
+
# Annotations
|
|
144
|
+
top_anno = None
|
|
145
|
+
ann_col_df = annotation_col if annotation_col is not None else annotation
|
|
146
|
+
if ann_col_df is not None:
|
|
147
|
+
ann_df = ann_col_df.loc[cn] if isinstance(ann_col_df, pd.DataFrame) and set(cn).issubset(ann_col_df.index) else pd.DataFrame(ann_col_df)
|
|
148
|
+
top_anno = HeatmapAnnotation(
|
|
149
|
+
df=ann_df,
|
|
150
|
+
col=annotation_colors,
|
|
151
|
+
show_legend=annotation_legend,
|
|
152
|
+
show_annotation_name=annotation_names_col,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
left_anno = None
|
|
156
|
+
if annotation_row is not None:
|
|
157
|
+
ann_r_df = annotation_row.loc[rn] if isinstance(annotation_row, pd.DataFrame) and set(rn).issubset(annotation_row.index) else pd.DataFrame(annotation_row)
|
|
158
|
+
left_anno = rowAnnotation(
|
|
159
|
+
df=ann_r_df,
|
|
160
|
+
col=annotation_colors,
|
|
161
|
+
show_legend=annotation_legend,
|
|
162
|
+
show_annotation_name=annotation_names_row,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# Cell numbers
|
|
166
|
+
cell_fun = None
|
|
167
|
+
fs_num = fontsize_number if fontsize_number is not None else 0.8 * fontsize
|
|
168
|
+
if isinstance(display_numbers, np.ndarray) or isinstance(display_numbers, pd.DataFrame):
|
|
169
|
+
dn_arr = np.asarray(display_numbers, dtype=object)
|
|
170
|
+
def _cell_fun_mat(j: int, i: int, x: Unit, y: Unit, w: Unit, h: Unit, fill: str) -> None:
|
|
171
|
+
grid_text(str(dn_arr[i, j]), x, y, gp=gpar(fontsize=fs_num, col=number_color))
|
|
172
|
+
cell_fun = _cell_fun_mat
|
|
173
|
+
elif display_numbers is True:
|
|
174
|
+
def _cell_fun_num(j: int, i: int, x: Unit, y: Unit, w: Unit, h: Unit, fill: str) -> None:
|
|
175
|
+
v = arr[i, j]
|
|
176
|
+
lbl = "" if np.isnan(v) else (number_format.format(v) if "{" in number_format else (number_format % v))
|
|
177
|
+
grid_text(lbl, x, y, gp=gpar(fontsize=fs_num, col=number_color))
|
|
178
|
+
cell_fun = _cell_fun_num
|
|
179
|
+
|
|
180
|
+
# Angle mapping from pheatmap angle_col -> ComplexHeatmap column_names_rot
|
|
181
|
+
col_rot = {0: 0.0, 45: 45.0, 90: 90.0, 270: 90.0, 315: 45.0}.get(int(angle_col), float(angle_col))
|
|
182
|
+
|
|
183
|
+
hm_w = unit(cellwidth * arr.shape[1] * 25.4 / 72.0, "mm") if cellwidth is not None else None
|
|
184
|
+
hm_h = unit(cellheight * arr.shape[0] * 25.4 / 72.0, "mm") if cellheight is not None else None
|
|
185
|
+
|
|
186
|
+
rd_w = unit(0, "mm") if (treeheight_row is not None and treeheight_row == 0) else (unit(treeheight_row * 25.4 / 72.0, "mm") if treeheight_row is not None else None)
|
|
187
|
+
cd_h = unit(0, "mm") if (treeheight_col is not None and treeheight_col == 0) else (unit(treeheight_col * 25.4 / 72.0, "mm") if treeheight_col is not None else None)
|
|
188
|
+
|
|
189
|
+
hlp: dict[str, Any] = {"title": name or ""}
|
|
190
|
+
if legend_breaks is not None:
|
|
191
|
+
hlp["at"] = list(legend_breaks)
|
|
192
|
+
if legend_labels is not None:
|
|
193
|
+
hlp["labels"] = list(legend_labels)
|
|
194
|
+
|
|
195
|
+
ht = Heatmap(
|
|
196
|
+
df_mat,
|
|
197
|
+
col=col_fun,
|
|
198
|
+
name=name or "matrix",
|
|
199
|
+
na_col=na_col,
|
|
200
|
+
rect_gp=gpar(col=border_color if border_color not in (False, "none", "NA") else None),
|
|
201
|
+
cell_fun=cell_fun,
|
|
202
|
+
column_title=main if main is not None else [],
|
|
203
|
+
column_title_gp=gpar(fontsize=fontsize * 1.3, fontface="bold"),
|
|
204
|
+
cluster_rows=cluster_rows,
|
|
205
|
+
cluster_columns=cluster_cols,
|
|
206
|
+
clustering_distance_rows=d_row,
|
|
207
|
+
clustering_distance_columns=d_col,
|
|
208
|
+
clustering_method_rows=clustering_method,
|
|
209
|
+
clustering_method_columns=clustering_method,
|
|
210
|
+
row_km=kmeans_k if kmeans_k and kmeans_k > 1 else 1,
|
|
211
|
+
row_split=row_split,
|
|
212
|
+
column_split=col_split,
|
|
213
|
+
row_dend_width=rd_w,
|
|
214
|
+
column_dend_height=cd_h,
|
|
215
|
+
show_row_dend=bool(cluster_rows and (treeheight_row is None or treeheight_row > 0)),
|
|
216
|
+
show_column_dend=bool(cluster_cols and (treeheight_col is None or treeheight_col > 0)),
|
|
217
|
+
show_row_names=show_rownames,
|
|
218
|
+
show_column_names=show_colnames,
|
|
219
|
+
row_labels=list(labels_row) if labels_row is not None else None,
|
|
220
|
+
column_labels=list(labels_col) if labels_col is not None else None,
|
|
221
|
+
row_names_gp=gpar(fontsize=fontsize_row if fontsize_row is not None else fontsize),
|
|
222
|
+
column_names_gp=gpar(fontsize=fontsize_col if fontsize_col is not None else fontsize),
|
|
223
|
+
column_names_rot=col_rot,
|
|
224
|
+
top_annotation=top_anno,
|
|
225
|
+
left_annotation=left_anno,
|
|
226
|
+
width=hm_w,
|
|
227
|
+
height=hm_h,
|
|
228
|
+
show_heatmap_legend=legend,
|
|
229
|
+
heatmap_legend_param=hlp,
|
|
230
|
+
**kwargs,
|
|
231
|
+
)
|
|
232
|
+
if filename is not None or run_draw:
|
|
233
|
+
ht.draw(save=filename, width=width, height=height, show=False)
|
|
234
|
+
return ht
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def heatmap(
|
|
238
|
+
x: Any,
|
|
239
|
+
Rowv: Any = True,
|
|
240
|
+
Colv: Any = True,
|
|
241
|
+
scale: str = "row",
|
|
242
|
+
col: Sequence[str] | None = None,
|
|
243
|
+
RowSideColors: Sequence[str] | None = None,
|
|
244
|
+
ColSideColors: Sequence[str] | None = None,
|
|
245
|
+
main: str | None = None,
|
|
246
|
+
xlab: str | None = None,
|
|
247
|
+
ylab: str | None = None,
|
|
248
|
+
labRow: Sequence[str] | None = None,
|
|
249
|
+
labCol: Sequence[str] | None = None,
|
|
250
|
+
**kwargs: Any,
|
|
251
|
+
) -> Heatmap:
|
|
252
|
+
"""Translate R `stats::heatmap()` to ComplexHeatmap::Heatmap (`heatmap.Rd`)."""
|
|
253
|
+
arr = np.asarray(x, dtype=float)
|
|
254
|
+
arr = _scale_matrix(arr, str(scale).lower())
|
|
255
|
+
if col is None:
|
|
256
|
+
col = hcl_colors(12, "YlOrRd", rev=True)
|
|
257
|
+
|
|
258
|
+
cl_r = False if Rowv is None or Rowv is False else Rowv
|
|
259
|
+
cl_c = False if Colv is None or Colv is False else Colv
|
|
260
|
+
|
|
261
|
+
left_a = rowAnnotation(RowSide=list(RowSideColors), show_annotation_name=False, show_legend=False) if RowSideColors is not None else None
|
|
262
|
+
top_a = HeatmapAnnotation(ColSide=list(ColSideColors), show_annotation_name=False, show_legend=False) if ColSideColors is not None else None
|
|
263
|
+
|
|
264
|
+
return Heatmap(
|
|
265
|
+
arr,
|
|
266
|
+
col=col,
|
|
267
|
+
cluster_rows=cl_r,
|
|
268
|
+
cluster_columns=cl_c,
|
|
269
|
+
left_annotation=left_a,
|
|
270
|
+
top_annotation=top_a,
|
|
271
|
+
column_title=main or xlab or [],
|
|
272
|
+
column_title_side="top" if main else "bottom",
|
|
273
|
+
row_title=ylab or [],
|
|
274
|
+
row_title_side="right",
|
|
275
|
+
row_labels=list(labRow) if labRow is not None else None,
|
|
276
|
+
column_labels=list(labCol) if labCol is not None else None,
|
|
277
|
+
show_heatmap_legend=False,
|
|
278
|
+
**kwargs,
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def heatmap_2(
|
|
283
|
+
x: Any,
|
|
284
|
+
Rowv: Any = True,
|
|
285
|
+
Colv: Any = True,
|
|
286
|
+
dendrogram: str = "both",
|
|
287
|
+
scale: str = "none",
|
|
288
|
+
col: Sequence[str] | None = None,
|
|
289
|
+
RowSideColors: Sequence[str] | None = None,
|
|
290
|
+
ColSideColors: Sequence[str] | None = None,
|
|
291
|
+
key: bool = True,
|
|
292
|
+
key_title: str = "Color Key",
|
|
293
|
+
main: str | None = None,
|
|
294
|
+
trace: str = "none",
|
|
295
|
+
**kwargs: Any,
|
|
296
|
+
) -> Heatmap:
|
|
297
|
+
"""Translate R `gplots::heatmap.2()` to ComplexHeatmap::Heatmap (`heatmap.2.Rd`)."""
|
|
298
|
+
arr = np.asarray(x, dtype=float)
|
|
299
|
+
arr = _scale_matrix(arr, str(scale).lower())
|
|
300
|
+
if col is None:
|
|
301
|
+
col = hcl_colors(25, "RdBu", rev=True)
|
|
302
|
+
|
|
303
|
+
d_opt = str(dendrogram).lower()
|
|
304
|
+
show_r_dend = d_opt in ("both", "row")
|
|
305
|
+
show_c_dend = d_opt in ("both", "column", "col")
|
|
306
|
+
|
|
307
|
+
left_a = rowAnnotation(RowSide=list(RowSideColors), show_annotation_name=False, show_legend=False) if RowSideColors is not None else None
|
|
308
|
+
top_a = HeatmapAnnotation(ColSide=list(ColSideColors), show_annotation_name=False, show_legend=False) if ColSideColors is not None else None
|
|
309
|
+
|
|
310
|
+
return Heatmap(
|
|
311
|
+
arr,
|
|
312
|
+
col=col,
|
|
313
|
+
cluster_rows=False if Rowv is None or Rowv is False else Rowv,
|
|
314
|
+
cluster_columns=False if Colv is None or Colv is False else Colv,
|
|
315
|
+
show_row_dend=show_r_dend,
|
|
316
|
+
show_column_dend=show_c_dend,
|
|
317
|
+
left_annotation=left_a,
|
|
318
|
+
top_annotation=top_a,
|
|
319
|
+
column_title=main or [],
|
|
320
|
+
show_heatmap_legend=bool(key),
|
|
321
|
+
heatmap_legend_param={"title": key_title, "direction": "horizontal"},
|
|
322
|
+
**kwargs,
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def compare_pheatmap(mat: Any, **kwargs: Any) -> Heatmap:
|
|
327
|
+
"""Create and optionally draw ComplexHeatmap equivalent of `pheatmap(mat, ...)`."""
|
|
328
|
+
return pheatmap(mat, **kwargs)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def compare_heatmap(x: Any, **kwargs: Any) -> Heatmap:
|
|
332
|
+
"""Create ComplexHeatmap equivalent of `stats::heatmap(x, ...)`."""
|
|
333
|
+
return heatmap(x, **kwargs)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def compare_heatmap_2(x: Any, **kwargs: Any) -> Heatmap:
|
|
337
|
+
"""Create ComplexHeatmap equivalent of `gplots::heatmap.2(x, ...)`."""
|
|
338
|
+
return heatmap_2(x, **kwargs)
|