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,2781 @@
|
|
|
1
|
+
"""Built-in annotation functions (`anno_*` and `row_anno_*` aliases)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import os
|
|
7
|
+
from typing import Any, Callable, Sequence
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
from PIL import Image
|
|
12
|
+
from scipy.interpolate import make_interp_spline
|
|
13
|
+
from scipy.stats import gaussian_kde
|
|
14
|
+
|
|
15
|
+
from ._options import _ENV, ht_opt
|
|
16
|
+
from .annotations import (
|
|
17
|
+
AnnotationFunction,
|
|
18
|
+
anno_width_and_height,
|
|
19
|
+
construct_axis_grob,
|
|
20
|
+
default_axis_param,
|
|
21
|
+
subset_by_intersect,
|
|
22
|
+
subset_matrix_by_row,
|
|
23
|
+
subset_no,
|
|
24
|
+
subset_vector,
|
|
25
|
+
update_anno_extend,
|
|
26
|
+
validate_axis_param,
|
|
27
|
+
)
|
|
28
|
+
from .colors import ColorMapping, add_transparency, brewer_pal, colorRamp2, default_col, to_hex_rgba
|
|
29
|
+
from .grid import (
|
|
30
|
+
Viewport,
|
|
31
|
+
current_viewport,
|
|
32
|
+
grid_boxplot,
|
|
33
|
+
grid_draw,
|
|
34
|
+
grid_lines,
|
|
35
|
+
grid_points,
|
|
36
|
+
grid_polygon,
|
|
37
|
+
grid_raster,
|
|
38
|
+
grid_rect,
|
|
39
|
+
grid_roundrect,
|
|
40
|
+
grid_segments,
|
|
41
|
+
grid_text,
|
|
42
|
+
popViewport,
|
|
43
|
+
pushViewport,
|
|
44
|
+
textGrob,
|
|
45
|
+
)
|
|
46
|
+
from .text import smartAlign, smartAlign2, textbox_grob
|
|
47
|
+
from .units import (
|
|
48
|
+
Unit,
|
|
49
|
+
as_unit,
|
|
50
|
+
check_gp,
|
|
51
|
+
convertHeight,
|
|
52
|
+
convertWidth,
|
|
53
|
+
gpar,
|
|
54
|
+
recycle_gp,
|
|
55
|
+
subset_gp,
|
|
56
|
+
unit,
|
|
57
|
+
unit_c,
|
|
58
|
+
)
|
|
59
|
+
from .grid import max_text_height, max_text_width
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _rle_runs(seq: Sequence[Any]) -> list[tuple[Any, int, int]]:
|
|
63
|
+
"""Return (value, start_idx, length) runs for contiguous identical values."""
|
|
64
|
+
if len(seq) == 0:
|
|
65
|
+
return []
|
|
66
|
+
runs: list[tuple[Any, int, int]] = []
|
|
67
|
+
cur = seq[0]
|
|
68
|
+
start = 0
|
|
69
|
+
for i in range(1, len(seq)):
|
|
70
|
+
if seq[i] != cur:
|
|
71
|
+
runs.append((cur, start, i - start))
|
|
72
|
+
cur = seq[i]
|
|
73
|
+
start = i
|
|
74
|
+
runs.append((cur, start, len(seq) - start))
|
|
75
|
+
return runs
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _reverse_vals(vals: np.ndarray, data_scale: tuple[float, float], direction: str) -> np.ndarray:
|
|
79
|
+
if direction == "reverse":
|
|
80
|
+
return data_scale[1] - vals + data_scale[0]
|
|
81
|
+
return vals
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _draw_background(border: Any, background: bool) -> None:
|
|
85
|
+
if background:
|
|
86
|
+
grid_rect(gp=gpar(fill="#DDDDDD", col=None))
|
|
87
|
+
if border is True:
|
|
88
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
89
|
+
elif isinstance(border, str):
|
|
90
|
+
grid_rect(gp=gpar(fill="transparent", col=border))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _recycle_seq(val: Any, n: int) -> list[Any]:
|
|
94
|
+
if isinstance(val, Unit):
|
|
95
|
+
if len(val) == 1:
|
|
96
|
+
return [val] * n
|
|
97
|
+
return [val[i % len(val)] for i in range(n)]
|
|
98
|
+
if isinstance(val, (str, int, float, np.number, bool, np.bool_)) or val is None:
|
|
99
|
+
return [val] * n
|
|
100
|
+
seq = list(val)
|
|
101
|
+
if len(seq) == 0:
|
|
102
|
+
return [None] * n
|
|
103
|
+
return [seq[i % len(seq)] for i in range(n)]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _to_obs_series(x: Any, which: str) -> list[np.ndarray]:
|
|
107
|
+
"""Convert matrix/DataFrame/list-of-vectors into a list of 1D finite float arrays."""
|
|
108
|
+
if isinstance(x, pd.DataFrame):
|
|
109
|
+
arr = x.to_numpy(dtype=float)
|
|
110
|
+
if which == "column":
|
|
111
|
+
return [arr[:, c] for c in range(arr.shape[1])]
|
|
112
|
+
return [arr[r, :] for r in range(arr.shape[0])]
|
|
113
|
+
if isinstance(x, np.ndarray) and x.ndim == 2:
|
|
114
|
+
arr = x.astype(float)
|
|
115
|
+
if which == "column":
|
|
116
|
+
return [arr[:, c] for c in range(arr.shape[1])]
|
|
117
|
+
return [arr[r, :] for r in range(arr.shape[0])]
|
|
118
|
+
if isinstance(x, dict):
|
|
119
|
+
return [np.asarray(v, dtype=float).ravel() for v in x.values()]
|
|
120
|
+
return [np.asarray(v, dtype=float).ravel() for v in x]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ---- 1. anno_simple ----
|
|
124
|
+
|
|
125
|
+
def anno_simple(
|
|
126
|
+
x: Any,
|
|
127
|
+
col: Any = None,
|
|
128
|
+
na_col: str = "grey",
|
|
129
|
+
which: str | None = None,
|
|
130
|
+
border: bool = False,
|
|
131
|
+
gp: dict[str, Any] | None = None,
|
|
132
|
+
pch: Any = None,
|
|
133
|
+
pt_size: Any = None,
|
|
134
|
+
pt_gp: dict[str, Any] | None = None,
|
|
135
|
+
simple_anno_size: Unit | None = None,
|
|
136
|
+
width: Unit | None = None,
|
|
137
|
+
height: Unit | None = None,
|
|
138
|
+
) -> AnnotationFunction:
|
|
139
|
+
which_explicit = which is not None
|
|
140
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
141
|
+
|
|
142
|
+
if simple_anno_size is None:
|
|
143
|
+
simple_anno_size = ht_opt.simple_anno_size
|
|
144
|
+
sas_mm = convertWidth(as_unit(simple_anno_size, "mm"), "mm", valueOnly=True)
|
|
145
|
+
|
|
146
|
+
arr = np.asarray(x, dtype=object)
|
|
147
|
+
if arr.ndim == 2 and arr.shape[1] == 1:
|
|
148
|
+
arr = arr[:, 0]
|
|
149
|
+
is_mat = arr.ndim == 2
|
|
150
|
+
n = arr.shape[0]
|
|
151
|
+
nc = arr.shape[1] if is_mat else 1
|
|
152
|
+
|
|
153
|
+
if isinstance(col, ColorMapping):
|
|
154
|
+
cm = col
|
|
155
|
+
elif col is None:
|
|
156
|
+
inferred = default_col(arr)
|
|
157
|
+
if callable(inferred):
|
|
158
|
+
cm = ColorMapping(col_fun=inferred, na_col=na_col)
|
|
159
|
+
else:
|
|
160
|
+
cm = ColorMapping(colors=inferred, na_col=na_col)
|
|
161
|
+
elif callable(col):
|
|
162
|
+
cm = ColorMapping(col_fun=col, na_col=na_col)
|
|
163
|
+
elif isinstance(col, dict):
|
|
164
|
+
eff_na = col.get("_NA_", na_col)
|
|
165
|
+
clean = {k: v for k, v in col.items() if k != "_NA_"}
|
|
166
|
+
cm = ColorMapping(colors=clean, na_col=eff_na, full_col=clean)
|
|
167
|
+
else:
|
|
168
|
+
col_seq = list(col)
|
|
169
|
+
uniq = list(dict.fromkeys(v for v in arr.ravel() if v is not None and not (isinstance(v, float) and np.isnan(v))))
|
|
170
|
+
if len(col_seq) == len(uniq):
|
|
171
|
+
cm = ColorMapping(colors=dict(zip([str(u) for u in sorted(uniq)], col_seq)), na_col=na_col)
|
|
172
|
+
else:
|
|
173
|
+
vals = arr.astype(float)
|
|
174
|
+
cf = colorRamp2(np.linspace(float(np.nanmin(vals)), float(np.nanmax(vals)), len(col_seq)), col_seq)
|
|
175
|
+
cm = ColorMapping(col_fun=cf, na_col=na_col)
|
|
176
|
+
|
|
177
|
+
sz_default = unit(sas_mm * nc, "mm")
|
|
178
|
+
gp_d = check_gp(gp)
|
|
179
|
+
pt_gp_d = check_gp(pt_gp)
|
|
180
|
+
if pt_size is None:
|
|
181
|
+
pt_sz_u = unit(0.8 / max(1, nc), "snpc")
|
|
182
|
+
else:
|
|
183
|
+
pt_sz_u = as_unit(pt_size, "mm")
|
|
184
|
+
|
|
185
|
+
pch_arr = None if pch is None else np.asarray(pch, dtype=object)
|
|
186
|
+
|
|
187
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
188
|
+
sz = anno_width_and_height(target_which, width, height, sz_default)
|
|
189
|
+
|
|
190
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
191
|
+
val = env["value"]
|
|
192
|
+
sub = val[index] if val.ndim == 1 else val[index, :]
|
|
193
|
+
fill_mat = cm.map_to_colors(sub)
|
|
194
|
+
m = len(index)
|
|
195
|
+
if m == 0:
|
|
196
|
+
return
|
|
197
|
+
p_sub = None
|
|
198
|
+
if env["pch"] is not None:
|
|
199
|
+
pa = env["pch"]
|
|
200
|
+
p_sub = pa[index] if pa.ndim == 1 else pa[index, :]
|
|
201
|
+
if target_which == "column":
|
|
202
|
+
pushViewport(Viewport(xscale=(0.0, float(m)), yscale=(0.0, float(nc)), clip=False))
|
|
203
|
+
try:
|
|
204
|
+
if not is_mat:
|
|
205
|
+
fills = list(fill_mat)
|
|
206
|
+
if cm.type == "discrete" and gp_d.get("col", "#00000000") == "#00000000":
|
|
207
|
+
for col_val, st, ln in _rle_runs(fills):
|
|
208
|
+
grid_rect(x=st + ln * 0.5, y=0.5, width=ln, height=1.0, gp=gpar(fill=col_val, col=None), default_units="native")
|
|
209
|
+
else:
|
|
210
|
+
rec_gp = recycle_gp(gp_d, m)
|
|
211
|
+
rec_gp["fill"] = fills
|
|
212
|
+
grid_rect(x=np.arange(m) + 0.5, y=np.full(m, 0.5), width=np.ones(m), height=np.ones(m), gp=rec_gp, default_units="native")
|
|
213
|
+
if p_sub is not None:
|
|
214
|
+
valid = [i for i, pv in enumerate(p_sub) if pv is not None and not (isinstance(pv, float) and np.isnan(pv))]
|
|
215
|
+
if valid:
|
|
216
|
+
grid_points(
|
|
217
|
+
np.array(valid, dtype=float) + 0.5,
|
|
218
|
+
np.full(len(valid), 0.5),
|
|
219
|
+
pch=[p_sub[i] for i in valid],
|
|
220
|
+
size=pt_sz_u if len(pt_sz_u) == 1 else pt_sz_u[index][valid],
|
|
221
|
+
gp=subset_gp(recycle_gp(pt_gp_d, n), [index[i] for i in valid]),
|
|
222
|
+
default_units="native",
|
|
223
|
+
)
|
|
224
|
+
else:
|
|
225
|
+
for c_i in range(nc):
|
|
226
|
+
y_c = nc - c_i - 0.5
|
|
227
|
+
fills = list(fill_mat[:, c_i])
|
|
228
|
+
rec_gp = recycle_gp(gp_d, m)
|
|
229
|
+
rec_gp["fill"] = fills
|
|
230
|
+
grid_rect(x=np.arange(m) + 0.5, y=np.full(m, y_c), width=np.ones(m), height=np.ones(m), gp=rec_gp, default_units="native")
|
|
231
|
+
if p_sub is not None:
|
|
232
|
+
p_col = p_sub[:, c_i] if p_sub.ndim == 2 else p_sub
|
|
233
|
+
valid = [i for i, pv in enumerate(p_col) if pv is not None and not (isinstance(pv, float) and np.isnan(pv))]
|
|
234
|
+
if valid:
|
|
235
|
+
grid_points(
|
|
236
|
+
np.array(valid, dtype=float) + 0.5,
|
|
237
|
+
np.full(len(valid), y_c),
|
|
238
|
+
pch=[p_col[i] for i in valid],
|
|
239
|
+
size=pt_sz_u,
|
|
240
|
+
gp=pt_gp_d,
|
|
241
|
+
default_units="native",
|
|
242
|
+
)
|
|
243
|
+
if border:
|
|
244
|
+
grid_rect(gp=gpar(fill="transparent", col="black" if border is True else border))
|
|
245
|
+
finally:
|
|
246
|
+
popViewport()
|
|
247
|
+
else:
|
|
248
|
+
pushViewport(Viewport(xscale=(0.0, float(nc)), yscale=(0.0, float(m)), clip=False))
|
|
249
|
+
try:
|
|
250
|
+
if not is_mat:
|
|
251
|
+
fills = list(fill_mat)
|
|
252
|
+
if cm.type == "discrete" and gp_d.get("col", "#00000000") == "#00000000":
|
|
253
|
+
for col_val, st, ln in _rle_runs(fills):
|
|
254
|
+
y_mid = m - (st + ln * 0.5)
|
|
255
|
+
grid_rect(x=0.5, y=y_mid, width=1.0, height=ln, gp=gpar(fill=col_val, col=None), default_units="native")
|
|
256
|
+
else:
|
|
257
|
+
rec_gp = recycle_gp(gp_d, m)
|
|
258
|
+
rec_gp["fill"] = fills
|
|
259
|
+
grid_rect(x=np.full(m, 0.5), y=m - np.arange(m) - 0.5, width=np.ones(m), height=np.ones(m), gp=rec_gp, default_units="native")
|
|
260
|
+
if p_sub is not None:
|
|
261
|
+
valid = [i for i, pv in enumerate(p_sub) if pv is not None and not (isinstance(pv, float) and np.isnan(pv))]
|
|
262
|
+
if valid:
|
|
263
|
+
grid_points(
|
|
264
|
+
np.full(len(valid), 0.5),
|
|
265
|
+
m - np.array(valid, dtype=float) - 0.5,
|
|
266
|
+
pch=[p_sub[i] for i in valid],
|
|
267
|
+
size=pt_sz_u if len(pt_sz_u) == 1 else pt_sz_u[index][valid],
|
|
268
|
+
gp=subset_gp(recycle_gp(pt_gp_d, n), [index[i] for i in valid]),
|
|
269
|
+
default_units="native",
|
|
270
|
+
)
|
|
271
|
+
else:
|
|
272
|
+
for c_i in range(nc):
|
|
273
|
+
x_c = c_i + 0.5
|
|
274
|
+
fills = list(fill_mat[:, c_i])
|
|
275
|
+
rec_gp = recycle_gp(gp_d, m)
|
|
276
|
+
rec_gp["fill"] = fills
|
|
277
|
+
grid_rect(x=np.full(m, x_c), y=m - np.arange(m) - 0.5, width=np.ones(m), height=np.ones(m), gp=rec_gp, default_units="native")
|
|
278
|
+
if p_sub is not None:
|
|
279
|
+
p_col = p_sub[:, c_i] if p_sub.ndim == 2 else p_sub
|
|
280
|
+
valid = [i for i, pv in enumerate(p_col) if pv is not None and not (isinstance(pv, float) and np.isnan(pv))]
|
|
281
|
+
if valid:
|
|
282
|
+
grid_points(
|
|
283
|
+
np.full(len(valid), x_c),
|
|
284
|
+
m - np.array(valid, dtype=float) - 0.5,
|
|
285
|
+
pch=[p_col[i] for i in valid],
|
|
286
|
+
size=pt_sz_u,
|
|
287
|
+
gp=pt_gp_d,
|
|
288
|
+
default_units="native",
|
|
289
|
+
)
|
|
290
|
+
if border:
|
|
291
|
+
grid_rect(gp=gpar(fill="transparent", col="black" if border is True else border))
|
|
292
|
+
finally:
|
|
293
|
+
popViewport()
|
|
294
|
+
|
|
295
|
+
rules = {"value": subset_matrix_by_row if is_mat else subset_vector}
|
|
296
|
+
if pch_arr is not None:
|
|
297
|
+
rules["pch"] = subset_matrix_by_row if pch_arr.ndim == 2 else subset_vector
|
|
298
|
+
return AnnotationFunction(
|
|
299
|
+
fun=_draw,
|
|
300
|
+
fun_name="anno_simple",
|
|
301
|
+
which=target_which,
|
|
302
|
+
width=sz["width"],
|
|
303
|
+
height=sz["height"],
|
|
304
|
+
n=n,
|
|
305
|
+
var_import={"value": arr, "pch": pch_arr},
|
|
306
|
+
subset_rule=rules,
|
|
307
|
+
subsettable=True,
|
|
308
|
+
show_name=True,
|
|
309
|
+
_which_explicit=which_explicit,
|
|
310
|
+
_reorient_fn=_build,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
return _build(eff_which)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# ---- 2. anno_empty ----
|
|
317
|
+
|
|
318
|
+
def anno_empty(
|
|
319
|
+
which: str | None = None,
|
|
320
|
+
border: bool = True,
|
|
321
|
+
zoom: bool = False,
|
|
322
|
+
width: Unit | None = None,
|
|
323
|
+
height: Unit | None = None,
|
|
324
|
+
show_name: bool = False,
|
|
325
|
+
) -> AnnotationFunction:
|
|
326
|
+
which_explicit = which is not None
|
|
327
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
328
|
+
|
|
329
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
330
|
+
sz = anno_width_and_height(target_which, width, height, unit(1.0, "cm"))
|
|
331
|
+
|
|
332
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
333
|
+
if border:
|
|
334
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
335
|
+
|
|
336
|
+
return AnnotationFunction(
|
|
337
|
+
fun=_draw,
|
|
338
|
+
fun_name="anno_empty",
|
|
339
|
+
which=target_which,
|
|
340
|
+
width=sz["width"],
|
|
341
|
+
height=sz["height"],
|
|
342
|
+
n=None,
|
|
343
|
+
var_import={"zoom": bool(zoom), "border": border},
|
|
344
|
+
subset_rule={},
|
|
345
|
+
subsettable=True,
|
|
346
|
+
show_name=show_name,
|
|
347
|
+
_which_explicit=which_explicit,
|
|
348
|
+
_reorient_fn=_build,
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
return _build(eff_which)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
# ---- 3. anno_points ----
|
|
355
|
+
|
|
356
|
+
def anno_points(
|
|
357
|
+
x: Any,
|
|
358
|
+
which: str | None = None,
|
|
359
|
+
border: bool = True,
|
|
360
|
+
gp: dict[str, Any] | None = None,
|
|
361
|
+
pch: Any = 16,
|
|
362
|
+
size: Any = unit(2, "mm"),
|
|
363
|
+
ylim: Sequence[float] | None = None,
|
|
364
|
+
extend: float = 0.05,
|
|
365
|
+
axis: bool = True,
|
|
366
|
+
background: bool = False,
|
|
367
|
+
axis_param: dict[str, Any] | None = None,
|
|
368
|
+
width: Unit | None = None,
|
|
369
|
+
height: Unit | None = None,
|
|
370
|
+
pch_as_image: bool = False,
|
|
371
|
+
) -> AnnotationFunction:
|
|
372
|
+
which_explicit = which is not None
|
|
373
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
374
|
+
|
|
375
|
+
arr = np.asarray(x, dtype=float)
|
|
376
|
+
if arr.ndim == 2 and arr.shape[1] == 1:
|
|
377
|
+
arr = arr[:, 0]
|
|
378
|
+
is_mat = arr.ndim == 2
|
|
379
|
+
n = arr.shape[0]
|
|
380
|
+
nc = arr.shape[1] if is_mat else 1
|
|
381
|
+
|
|
382
|
+
if ylim is None:
|
|
383
|
+
lo, hi = float(np.nanmin(arr)), float(np.nanmax(arr))
|
|
384
|
+
else:
|
|
385
|
+
lo, hi = float(ylim[0]), float(ylim[1])
|
|
386
|
+
if lo == hi:
|
|
387
|
+
lo -= 0.5
|
|
388
|
+
hi += 0.5
|
|
389
|
+
span = hi - lo
|
|
390
|
+
data_scale = (lo - extend * span, hi + extend * span)
|
|
391
|
+
|
|
392
|
+
gp_d = check_gp(gp)
|
|
393
|
+
if not is_mat:
|
|
394
|
+
gp_rec = recycle_gp(gp_d, n)
|
|
395
|
+
pch_rec = _recycle_seq(pch, n)
|
|
396
|
+
sz_rec = as_unit(size, "mm")
|
|
397
|
+
if len(sz_rec) == 1:
|
|
398
|
+
sz_rec = unit(np.full(n, convertWidth(sz_rec, "mm", valueOnly=True)), "mm")
|
|
399
|
+
else:
|
|
400
|
+
gp_rec = recycle_gp(gp_d, nc)
|
|
401
|
+
pch_rec = _recycle_seq(pch, nc)
|
|
402
|
+
sz_rec = as_unit(size, "mm")
|
|
403
|
+
if len(sz_rec) == 1:
|
|
404
|
+
sz_rec = unit(np.full(nc, convertWidth(sz_rec, "mm", valueOnly=True)), "mm")
|
|
405
|
+
|
|
406
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
407
|
+
sz = anno_width_and_height(target_which, width, height, unit(1.0, "cm"))
|
|
408
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
409
|
+
ax_grob = construct_axis_grob(ap, target_which, data_scale) if axis else None
|
|
410
|
+
|
|
411
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
412
|
+
val = env["value"]
|
|
413
|
+
m = len(index)
|
|
414
|
+
if m == 0:
|
|
415
|
+
return
|
|
416
|
+
if target_which == "column":
|
|
417
|
+
pushViewport(Viewport(xscale=(0.5, m + 0.5), yscale=data_scale, clip=False))
|
|
418
|
+
try:
|
|
419
|
+
_draw_background(border, background)
|
|
420
|
+
if not is_mat:
|
|
421
|
+
sub_v = _reverse_vals(val[index], data_scale, ap["direction"])
|
|
422
|
+
sub_gp = subset_gp(env["gp"], index)
|
|
423
|
+
sub_pch = subset_vector(env["pch"], index)
|
|
424
|
+
sub_sz = env["size"][index]
|
|
425
|
+
if pch_as_image:
|
|
426
|
+
for idx_i, (yv, pth) in enumerate(zip(sub_v, sub_pch)):
|
|
427
|
+
if pth and isinstance(pth, str) and os.path.exists(pth):
|
|
428
|
+
img = np.asarray(Image.open(pth).convert("RGBA"))
|
|
429
|
+
grid_raster(img, x=idx_i + 1, y=yv, width=sub_sz[idx_i], height=sub_sz[idx_i], default_units="native")
|
|
430
|
+
else:
|
|
431
|
+
grid_points(np.arange(1, m + 1), sub_v, pch=sub_pch, size=sub_sz, gp=sub_gp, default_units="native")
|
|
432
|
+
else:
|
|
433
|
+
sub_v = _reverse_vals(val[index, :], data_scale, ap["direction"])
|
|
434
|
+
for c_i in range(nc):
|
|
435
|
+
grid_points(np.arange(1, m + 1), sub_v[:, c_i], pch=pch_rec[c_i], size=sz_rec[c_i], gp=subset_gp(gp_rec, c_i), default_units="native")
|
|
436
|
+
show_ax = axis and ((ap["side"] == "left" and k == 1) or (ap["side"] == "right" and k == n_slices))
|
|
437
|
+
if show_ax and ax_grob is not None:
|
|
438
|
+
grid_draw(ax_grob)
|
|
439
|
+
finally:
|
|
440
|
+
popViewport()
|
|
441
|
+
else:
|
|
442
|
+
pushViewport(Viewport(xscale=data_scale, yscale=(0.5, m + 0.5), clip=False))
|
|
443
|
+
try:
|
|
444
|
+
_draw_background(border, background)
|
|
445
|
+
ys = m - np.arange(m, dtype=float)
|
|
446
|
+
if not is_mat:
|
|
447
|
+
sub_v = _reverse_vals(val[index], data_scale, ap["direction"])
|
|
448
|
+
sub_gp = subset_gp(env["gp"], index)
|
|
449
|
+
sub_pch = subset_vector(env["pch"], index)
|
|
450
|
+
sub_sz = env["size"][index]
|
|
451
|
+
grid_points(sub_v, ys, pch=sub_pch, size=sub_sz, gp=sub_gp, default_units="native")
|
|
452
|
+
else:
|
|
453
|
+
sub_v = _reverse_vals(val[index, :], data_scale, ap["direction"])
|
|
454
|
+
for c_i in range(nc):
|
|
455
|
+
grid_points(sub_v[:, c_i], ys, pch=pch_rec[c_i], size=sz_rec[c_i], gp=subset_gp(gp_rec, c_i), default_units="native")
|
|
456
|
+
show_ax = axis and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices))
|
|
457
|
+
if show_ax and ax_grob is not None:
|
|
458
|
+
grid_draw(ax_grob)
|
|
459
|
+
finally:
|
|
460
|
+
popViewport()
|
|
461
|
+
|
|
462
|
+
rules = {"value": subset_matrix_by_row if is_mat else subset_vector}
|
|
463
|
+
if not is_mat:
|
|
464
|
+
rules.update({"gp": subset_gp, "pch": subset_vector, "size": subset_vector})
|
|
465
|
+
anno = AnnotationFunction(
|
|
466
|
+
fun=_draw,
|
|
467
|
+
fun_name="anno_points",
|
|
468
|
+
which=target_which,
|
|
469
|
+
width=sz["width"],
|
|
470
|
+
height=sz["height"],
|
|
471
|
+
n=n,
|
|
472
|
+
data_scale=data_scale,
|
|
473
|
+
var_import={"value": arr, "gp": gp_rec, "pch": pch_rec, "size": sz_rec},
|
|
474
|
+
subset_rule=rules,
|
|
475
|
+
subsettable=True,
|
|
476
|
+
_which_explicit=which_explicit,
|
|
477
|
+
_reorient_fn=_build,
|
|
478
|
+
)
|
|
479
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
480
|
+
return anno
|
|
481
|
+
|
|
482
|
+
return _build(eff_which)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# ---- 4. anno_lines ----
|
|
486
|
+
|
|
487
|
+
def anno_lines(
|
|
488
|
+
x: Any,
|
|
489
|
+
which: str | None = None,
|
|
490
|
+
border: bool = True,
|
|
491
|
+
gp: dict[str, Any] | None = None,
|
|
492
|
+
add_points: bool | Sequence[bool] | None = None,
|
|
493
|
+
smooth: bool = False,
|
|
494
|
+
pch: Any = 16,
|
|
495
|
+
size: Any = unit(2, "mm"),
|
|
496
|
+
pt_gp: dict[str, Any] | None = None,
|
|
497
|
+
ylim: Sequence[float] | None = None,
|
|
498
|
+
extend: float = 0.05,
|
|
499
|
+
axis: bool = True,
|
|
500
|
+
axis_param: dict[str, Any] | None = None,
|
|
501
|
+
background: bool = False,
|
|
502
|
+
width: Unit | None = None,
|
|
503
|
+
height: Unit | None = None,
|
|
504
|
+
) -> AnnotationFunction:
|
|
505
|
+
which_explicit = which is not None
|
|
506
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
507
|
+
|
|
508
|
+
if add_points is None:
|
|
509
|
+
add_points = smooth
|
|
510
|
+
|
|
511
|
+
arr = np.asarray(x, dtype=float)
|
|
512
|
+
if arr.ndim == 2 and arr.shape[1] == 1:
|
|
513
|
+
arr = arr[:, 0]
|
|
514
|
+
is_mat = arr.ndim == 2
|
|
515
|
+
n = arr.shape[0]
|
|
516
|
+
nc = arr.shape[1] if is_mat else 1
|
|
517
|
+
|
|
518
|
+
if ylim is None:
|
|
519
|
+
lo, hi = float(np.nanmin(arr)), float(np.nanmax(arr))
|
|
520
|
+
else:
|
|
521
|
+
lo, hi = float(ylim[0]), float(ylim[1])
|
|
522
|
+
if lo == hi:
|
|
523
|
+
lo -= 0.5
|
|
524
|
+
hi += 0.5
|
|
525
|
+
span = hi - lo
|
|
526
|
+
data_scale = (lo - extend * span, hi + extend * span)
|
|
527
|
+
|
|
528
|
+
gp_d = check_gp(gp)
|
|
529
|
+
pt_gp_d = check_gp(pt_gp)
|
|
530
|
+
if not is_mat:
|
|
531
|
+
gp_line = recycle_gp(gp_d, 1)
|
|
532
|
+
pt_gp_rec = recycle_gp(pt_gp_d, n)
|
|
533
|
+
pch_rec = _recycle_seq(pch, n)
|
|
534
|
+
sz_rec = as_unit(size, "mm")
|
|
535
|
+
if len(sz_rec) == 1:
|
|
536
|
+
sz_rec = unit(np.full(n, convertWidth(sz_rec, "mm", valueOnly=True)), "mm")
|
|
537
|
+
add_pts = [bool(add_points)]
|
|
538
|
+
else:
|
|
539
|
+
gp_line = recycle_gp(gp_d, nc)
|
|
540
|
+
pt_gp_rec = recycle_gp(pt_gp_d, nc)
|
|
541
|
+
pch_rec = _recycle_seq(pch, nc)
|
|
542
|
+
sz_rec = as_unit(size, "mm")
|
|
543
|
+
if len(sz_rec) == 1:
|
|
544
|
+
sz_rec = unit(np.full(nc, convertWidth(sz_rec, "mm", valueOnly=True)), "mm")
|
|
545
|
+
add_pts = [bool(add_points)] * nc if isinstance(add_points, (bool, np.bool_)) else [bool(b) for b in add_points]
|
|
546
|
+
|
|
547
|
+
def _smooth_series(t: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
548
|
+
mask = np.isfinite(y)
|
|
549
|
+
tv, yv = t[mask], y[mask]
|
|
550
|
+
if len(tv) < 4:
|
|
551
|
+
return tv, yv
|
|
552
|
+
# Local quadratic regression (LOESS-like) on 100 points
|
|
553
|
+
t_grid = np.linspace(tv[0], tv[-1], 100)
|
|
554
|
+
y_grid = np.empty_like(t_grid)
|
|
555
|
+
bw = 0.75 * (tv[-1] - tv[0])
|
|
556
|
+
for gi, tg in enumerate(t_grid):
|
|
557
|
+
d = np.abs(tv - tg)
|
|
558
|
+
w_rad = max(np.partition(d, min(len(d) - 1, max(2, int(0.75 * len(d)))))[min(len(d) - 1, max(2, int(0.75 * len(d))))], 1e-9)
|
|
559
|
+
u = np.clip(d / w_rad, 0.0, 1.0)
|
|
560
|
+
w = (1.0 - u ** 3) ** 3
|
|
561
|
+
if np.sum(w > 0) >= 3:
|
|
562
|
+
poly = np.polyfit(tv, yv, deg=2, w=np.sqrt(w))
|
|
563
|
+
y_grid[gi] = float(np.polyval(poly, tg))
|
|
564
|
+
else:
|
|
565
|
+
y_grid[gi] = float(np.interp(tg, tv, yv))
|
|
566
|
+
return t_grid, y_grid
|
|
567
|
+
|
|
568
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
569
|
+
sz = anno_width_and_height(target_which, width, height, unit(1.0, "cm"))
|
|
570
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
571
|
+
ax_grob = construct_axis_grob(ap, target_which, data_scale) if axis else None
|
|
572
|
+
|
|
573
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
574
|
+
val = env["value"]
|
|
575
|
+
m = len(index)
|
|
576
|
+
if m == 0:
|
|
577
|
+
return
|
|
578
|
+
if target_which == "column":
|
|
579
|
+
pushViewport(Viewport(xscale=(0.5, m + 0.5), yscale=data_scale, clip=False))
|
|
580
|
+
try:
|
|
581
|
+
_draw_background(border, background)
|
|
582
|
+
xs = np.arange(1, m + 1, dtype=float)
|
|
583
|
+
if not is_mat:
|
|
584
|
+
yv = _reverse_vals(val[index], data_scale, ap["direction"])
|
|
585
|
+
lx, ly = _smooth_series(xs, yv) if smooth else (xs, yv)
|
|
586
|
+
grid_lines(lx, ly, gp=subset_gp(gp_line, 0), default_units="native")
|
|
587
|
+
if add_pts[0]:
|
|
588
|
+
grid_points(xs, yv, pch=subset_vector(env["pch"], index), size=env["size"][index], gp=subset_gp(env["pt_gp"], index), default_units="native")
|
|
589
|
+
else:
|
|
590
|
+
sub_v = _reverse_vals(val[index, :], data_scale, ap["direction"])
|
|
591
|
+
for c_i in range(nc):
|
|
592
|
+
yv = sub_v[:, c_i]
|
|
593
|
+
lx, ly = _smooth_series(xs, yv) if smooth else (xs, yv)
|
|
594
|
+
grid_lines(lx, ly, gp=subset_gp(gp_line, c_i), default_units="native")
|
|
595
|
+
if add_pts[c_i]:
|
|
596
|
+
grid_points(xs, yv, pch=pch_rec[c_i], size=sz_rec[c_i], gp=subset_gp(pt_gp_rec, c_i), default_units="native")
|
|
597
|
+
show_ax = axis and ((ap["side"] == "left" and k == 1) or (ap["side"] == "right" and k == n_slices))
|
|
598
|
+
if show_ax and ax_grob is not None:
|
|
599
|
+
grid_draw(ax_grob)
|
|
600
|
+
finally:
|
|
601
|
+
popViewport()
|
|
602
|
+
else:
|
|
603
|
+
pushViewport(Viewport(xscale=data_scale, yscale=(0.5, m + 0.5), clip=False))
|
|
604
|
+
try:
|
|
605
|
+
_draw_background(border, background)
|
|
606
|
+
ys = m - np.arange(m, dtype=float)
|
|
607
|
+
if not is_mat:
|
|
608
|
+
xv = _reverse_vals(val[index], data_scale, ap["direction"])
|
|
609
|
+
ly, lx = _smooth_series(ys[::-1], xv[::-1]) if smooth else (ys, xv)
|
|
610
|
+
grid_lines(lx, ly, gp=subset_gp(gp_line, 0), default_units="native")
|
|
611
|
+
if add_pts[0]:
|
|
612
|
+
grid_points(xv, ys, pch=subset_vector(env["pch"], index), size=env["size"][index], gp=subset_gp(env["pt_gp"], index), default_units="native")
|
|
613
|
+
else:
|
|
614
|
+
sub_v = _reverse_vals(val[index, :], data_scale, ap["direction"])
|
|
615
|
+
for c_i in range(nc):
|
|
616
|
+
xv = sub_v[:, c_i]
|
|
617
|
+
ly, lx = _smooth_series(ys[::-1], xv[::-1]) if smooth else (ys, xv)
|
|
618
|
+
grid_lines(lx, ly, gp=subset_gp(gp_line, c_i), default_units="native")
|
|
619
|
+
if add_pts[c_i]:
|
|
620
|
+
grid_points(xv, ys, pch=pch_rec[c_i], size=sz_rec[c_i], gp=subset_gp(pt_gp_rec, c_i), default_units="native")
|
|
621
|
+
show_ax = axis and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices))
|
|
622
|
+
if show_ax and ax_grob is not None:
|
|
623
|
+
grid_draw(ax_grob)
|
|
624
|
+
finally:
|
|
625
|
+
popViewport()
|
|
626
|
+
|
|
627
|
+
rules = {"value": subset_matrix_by_row if is_mat else subset_vector}
|
|
628
|
+
if not is_mat:
|
|
629
|
+
rules.update({"pt_gp": subset_gp, "pch": subset_vector, "size": subset_vector})
|
|
630
|
+
anno = AnnotationFunction(
|
|
631
|
+
fun=_draw,
|
|
632
|
+
fun_name="anno_lines",
|
|
633
|
+
which=target_which,
|
|
634
|
+
width=sz["width"],
|
|
635
|
+
height=sz["height"],
|
|
636
|
+
n=n,
|
|
637
|
+
data_scale=data_scale,
|
|
638
|
+
var_import={"value": arr, "pt_gp": pt_gp_rec, "pch": pch_rec, "size": sz_rec},
|
|
639
|
+
subset_rule=rules,
|
|
640
|
+
subsettable=True,
|
|
641
|
+
_which_explicit=which_explicit,
|
|
642
|
+
_reorient_fn=_build,
|
|
643
|
+
)
|
|
644
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
645
|
+
return anno
|
|
646
|
+
|
|
647
|
+
return _build(eff_which)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
# ---- 5. anno_barplot ----
|
|
651
|
+
|
|
652
|
+
def anno_barplot(
|
|
653
|
+
x: Any,
|
|
654
|
+
baseline: float | str = 0.0,
|
|
655
|
+
which: str | None = None,
|
|
656
|
+
border: bool = True,
|
|
657
|
+
bar_width: float = 0.6,
|
|
658
|
+
beside: bool = False,
|
|
659
|
+
attach: bool = False,
|
|
660
|
+
gp: dict[str, Any] | None = None,
|
|
661
|
+
ylim: Sequence[float] | None = None,
|
|
662
|
+
extend: float = 0.05,
|
|
663
|
+
axis: bool = True,
|
|
664
|
+
background: bool = False,
|
|
665
|
+
axis_param: dict[str, Any] | None = None,
|
|
666
|
+
add_numbers: bool = False,
|
|
667
|
+
numbers_gp: dict[str, Any] | None = None,
|
|
668
|
+
numbers_rot: float | None = None,
|
|
669
|
+
numbers_offset: Any = unit(2, "mm"),
|
|
670
|
+
labels_format: Callable[[Any], Sequence[str]] | None = None,
|
|
671
|
+
width: Unit | None = None,
|
|
672
|
+
height: Unit | None = None,
|
|
673
|
+
) -> AnnotationFunction:
|
|
674
|
+
which_explicit = which is not None
|
|
675
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
676
|
+
|
|
677
|
+
if isinstance(x, (list, tuple)) and x and isinstance(x[0], (list, tuple, np.ndarray)):
|
|
678
|
+
arr = np.column_stack([np.asarray(col, dtype=float) for col in x])
|
|
679
|
+
else:
|
|
680
|
+
arr = np.asarray(x, dtype=float)
|
|
681
|
+
if arr.ndim == 2 and arr.shape[1] == 1:
|
|
682
|
+
arr = arr[:, 0]
|
|
683
|
+
is_mat = arr.ndim == 2
|
|
684
|
+
n = arr.shape[0]
|
|
685
|
+
nc = arr.shape[1] if is_mat else 1
|
|
686
|
+
|
|
687
|
+
if gp is None:
|
|
688
|
+
if is_mat:
|
|
689
|
+
shades = ["#" + f"{int(round(v)):02X}" * 3 for v in np.linspace(230, 80, nc)]
|
|
690
|
+
gp_d = gpar(fill=shades)
|
|
691
|
+
else:
|
|
692
|
+
gp_d = gpar(fill="#CCCCCC")
|
|
693
|
+
else:
|
|
694
|
+
gp_d = check_gp(gp)
|
|
695
|
+
|
|
696
|
+
if not is_mat:
|
|
697
|
+
gp_rec = recycle_gp(gp_d, n)
|
|
698
|
+
if baseline == "min":
|
|
699
|
+
base_val = float(np.nanmin(arr))
|
|
700
|
+
elif baseline == "max":
|
|
701
|
+
base_val = float(np.nanmax(arr))
|
|
702
|
+
else:
|
|
703
|
+
base_val = float(baseline)
|
|
704
|
+
if ylim is None:
|
|
705
|
+
lo = min(base_val, float(np.nanmin(arr)))
|
|
706
|
+
hi = max(base_val, float(np.nanmax(arr)))
|
|
707
|
+
else:
|
|
708
|
+
lo, hi = float(ylim[0]), float(ylim[1])
|
|
709
|
+
else:
|
|
710
|
+
gp_rec = recycle_gp(gp_d, nc)
|
|
711
|
+
if baseline == "min":
|
|
712
|
+
base_val = float(np.nanmin(arr))
|
|
713
|
+
elif baseline == "max":
|
|
714
|
+
base_val = float(np.nanmax(arr))
|
|
715
|
+
else:
|
|
716
|
+
base_val = float(baseline)
|
|
717
|
+
if ylim is None:
|
|
718
|
+
if beside:
|
|
719
|
+
lo = min(base_val, float(np.nanmin(arr)))
|
|
720
|
+
hi = max(base_val, float(np.nanmax(arr)))
|
|
721
|
+
else:
|
|
722
|
+
rsums = np.nansum(arr, axis=1)
|
|
723
|
+
lo = min(base_val, float(np.nanmin(rsums)), 0.0 if base_val == 0 else float(np.nanmin(rsums)))
|
|
724
|
+
hi = max(base_val, float(np.nanmax(rsums)))
|
|
725
|
+
else:
|
|
726
|
+
lo, hi = float(ylim[0]), float(ylim[1])
|
|
727
|
+
|
|
728
|
+
if lo == hi:
|
|
729
|
+
hi = lo + 1.0
|
|
730
|
+
span = hi - lo
|
|
731
|
+
|
|
732
|
+
# Proportion matrix clamp [0, 1]
|
|
733
|
+
is_prop = is_mat and not beside and base_val == 0.0 and np.allclose(np.nansum(arr, axis=1), 1.0)
|
|
734
|
+
if ylim is not None:
|
|
735
|
+
data_scale = (lo, hi)
|
|
736
|
+
elif is_prop:
|
|
737
|
+
data_scale = (0.0, 1.0)
|
|
738
|
+
else:
|
|
739
|
+
lo_e = 0.0 if base_val == 0.0 and lo == 0.0 else lo - extend * span
|
|
740
|
+
hi_e = 0.0 if base_val == 0.0 and hi == 0.0 else hi + extend * span
|
|
741
|
+
if add_numbers and not is_mat:
|
|
742
|
+
hi_e += 0.15 * span
|
|
743
|
+
data_scale = (lo_e, hi_e)
|
|
744
|
+
|
|
745
|
+
fmt_fn = labels_format or getattr(x, "labels_format", None)
|
|
746
|
+
num_gp_d = check_gp(numbers_gp or gpar(fontsize=8))
|
|
747
|
+
off_u = as_unit(numbers_offset, "mm")
|
|
748
|
+
|
|
749
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
750
|
+
sz = anno_width_and_height(target_which, width, height, unit(1.0, "cm"))
|
|
751
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
752
|
+
ax_grob = construct_axis_grob(ap, target_which, data_scale) if axis else None
|
|
753
|
+
rot_num = (45.0 if target_which == "column" else 0.0) if numbers_rot is None else float(numbers_rot)
|
|
754
|
+
|
|
755
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
756
|
+
val = env["value"]
|
|
757
|
+
m = len(index)
|
|
758
|
+
if m == 0:
|
|
759
|
+
return
|
|
760
|
+
b_rev = float(_reverse_vals(np.array([base_val]), data_scale, ap["direction"])[0])
|
|
761
|
+
if target_which == "column":
|
|
762
|
+
pushViewport(Viewport(xscale=(0.5, m + 0.5), yscale=data_scale, clip=False))
|
|
763
|
+
try:
|
|
764
|
+
_draw_background(border, background)
|
|
765
|
+
xs = np.arange(1, m + 1, dtype=float)
|
|
766
|
+
if not is_mat:
|
|
767
|
+
sub_v = val[index]
|
|
768
|
+
v_rev = _reverse_vals(sub_v, data_scale, ap["direction"])
|
|
769
|
+
sub_gp = subset_gp(env["gp"], index)
|
|
770
|
+
y_pos = np.minimum(v_rev, b_rev)
|
|
771
|
+
h_bar = np.abs(v_rev - b_rev)
|
|
772
|
+
grid_rect(x=xs, y=y_pos, width=np.full(m, bar_width), height=h_bar, just="bottom", gp=sub_gp, default_units="native")
|
|
773
|
+
if add_numbers:
|
|
774
|
+
lbls = list(fmt_fn(sub_v)) if fmt_fn else [f"{v:g}" for v in sub_v]
|
|
775
|
+
off_mm = convertHeight(off_u, "mm", valueOnly=True)
|
|
776
|
+
for xi, yi, lb in zip(xs, v_rev, lbls):
|
|
777
|
+
grid_text(lb, x=unit(xi, "native"), y=unit(yi, "native") + unit(off_mm, "mm"), just="bottom" if rot_num == 0 else "left", rot=rot_num, gp=num_gp_d)
|
|
778
|
+
elif not beside:
|
|
779
|
+
sub_v = val[index, :]
|
|
780
|
+
cum = np.zeros(m, dtype=float)
|
|
781
|
+
for c_i in range(nc):
|
|
782
|
+
col_vals = sub_v[:, c_i]
|
|
783
|
+
y0_raw = base_val + cum
|
|
784
|
+
y1_raw = y0_raw + col_vals
|
|
785
|
+
y0_r = _reverse_vals(y0_raw, data_scale, ap["direction"])
|
|
786
|
+
y1_r = _reverse_vals(y1_raw, data_scale, ap["direction"])
|
|
787
|
+
grid_rect(
|
|
788
|
+
x=xs,
|
|
789
|
+
y=np.minimum(y0_r, y1_r),
|
|
790
|
+
width=np.full(m, bar_width),
|
|
791
|
+
height=np.abs(y1_r - y0_r),
|
|
792
|
+
just="bottom",
|
|
793
|
+
gp=subset_gp(gp_rec, c_i),
|
|
794
|
+
default_units="native",
|
|
795
|
+
)
|
|
796
|
+
cum = cum + col_vals
|
|
797
|
+
else:
|
|
798
|
+
sub_v = val[index, :]
|
|
799
|
+
sub_w = bar_width / nc if attach else (bar_width * 0.85) / nc
|
|
800
|
+
step_w = bar_width / nc
|
|
801
|
+
for c_i in range(nc):
|
|
802
|
+
x_off = (c_i - 0.5 * (nc - 1)) * step_w
|
|
803
|
+
v_rev = _reverse_vals(sub_v[:, c_i], data_scale, ap["direction"])
|
|
804
|
+
grid_rect(
|
|
805
|
+
x=xs + x_off,
|
|
806
|
+
y=np.minimum(v_rev, b_rev),
|
|
807
|
+
width=np.full(m, sub_w),
|
|
808
|
+
height=np.abs(v_rev - b_rev),
|
|
809
|
+
just="bottom",
|
|
810
|
+
gp=subset_gp(gp_rec, c_i),
|
|
811
|
+
default_units="native",
|
|
812
|
+
)
|
|
813
|
+
show_ax = axis and ((ap["side"] == "left" and k == 1) or (ap["side"] == "right" and k == n_slices))
|
|
814
|
+
if show_ax and ax_grob is not None:
|
|
815
|
+
grid_draw(ax_grob)
|
|
816
|
+
finally:
|
|
817
|
+
popViewport()
|
|
818
|
+
else:
|
|
819
|
+
pushViewport(Viewport(xscale=data_scale, yscale=(0.5, m + 0.5), clip=False))
|
|
820
|
+
try:
|
|
821
|
+
_draw_background(border, background)
|
|
822
|
+
ys = m - np.arange(m, dtype=float)
|
|
823
|
+
if not is_mat:
|
|
824
|
+
sub_v = val[index]
|
|
825
|
+
v_rev = _reverse_vals(sub_v, data_scale, ap["direction"])
|
|
826
|
+
sub_gp = subset_gp(env["gp"], index)
|
|
827
|
+
x_pos = np.minimum(v_rev, b_rev)
|
|
828
|
+
w_bar = np.abs(v_rev - b_rev)
|
|
829
|
+
grid_rect(x=x_pos, y=ys, width=w_bar, height=np.full(m, bar_width), just="left", gp=sub_gp, default_units="native")
|
|
830
|
+
if add_numbers:
|
|
831
|
+
lbls = list(fmt_fn(sub_v)) if fmt_fn else [f"{v:g}" for v in sub_v]
|
|
832
|
+
off_mm = convertWidth(off_u, "mm", valueOnly=True)
|
|
833
|
+
for xi, yi, lb in zip(v_rev, ys, lbls):
|
|
834
|
+
grid_text(lb, x=unit(xi, "native") + unit(off_mm, "mm"), y=unit(yi, "native"), just="left", rot=rot_num, gp=num_gp_d)
|
|
835
|
+
elif not beside:
|
|
836
|
+
sub_v = val[index, :]
|
|
837
|
+
cum = np.zeros(m, dtype=float)
|
|
838
|
+
for c_i in range(nc):
|
|
839
|
+
col_vals = sub_v[:, c_i]
|
|
840
|
+
x0_raw = base_val + cum
|
|
841
|
+
x1_raw = x0_raw + col_vals
|
|
842
|
+
x0_r = _reverse_vals(x0_raw, data_scale, ap["direction"])
|
|
843
|
+
x1_r = _reverse_vals(x1_raw, data_scale, ap["direction"])
|
|
844
|
+
grid_rect(
|
|
845
|
+
x=np.minimum(x0_r, x1_r),
|
|
846
|
+
y=ys,
|
|
847
|
+
width=np.abs(x1_r - x0_r),
|
|
848
|
+
height=np.full(m, bar_width),
|
|
849
|
+
just="left",
|
|
850
|
+
gp=subset_gp(gp_rec, c_i),
|
|
851
|
+
default_units="native",
|
|
852
|
+
)
|
|
853
|
+
cum = cum + col_vals
|
|
854
|
+
else:
|
|
855
|
+
sub_v = val[index, :]
|
|
856
|
+
sub_h = bar_width / nc if attach else (bar_width * 0.85) / nc
|
|
857
|
+
step_h = bar_width / nc
|
|
858
|
+
for c_i in range(nc):
|
|
859
|
+
y_off = (0.5 * (nc - 1) - c_i) * step_h
|
|
860
|
+
v_rev = _reverse_vals(sub_v[:, c_i], data_scale, ap["direction"])
|
|
861
|
+
grid_rect(
|
|
862
|
+
x=np.minimum(v_rev, b_rev),
|
|
863
|
+
y=ys + y_off,
|
|
864
|
+
width=np.abs(v_rev - b_rev),
|
|
865
|
+
height=np.full(m, sub_h),
|
|
866
|
+
just="left",
|
|
867
|
+
gp=subset_gp(gp_rec, c_i),
|
|
868
|
+
default_units="native",
|
|
869
|
+
)
|
|
870
|
+
show_ax = axis and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices))
|
|
871
|
+
if show_ax and ax_grob is not None:
|
|
872
|
+
grid_draw(ax_grob)
|
|
873
|
+
finally:
|
|
874
|
+
popViewport()
|
|
875
|
+
|
|
876
|
+
rules = {"value": subset_matrix_by_row if is_mat else subset_vector}
|
|
877
|
+
if not is_mat:
|
|
878
|
+
rules["gp"] = subset_gp
|
|
879
|
+
anno = AnnotationFunction(
|
|
880
|
+
fun=_draw,
|
|
881
|
+
fun_name="anno_barplot",
|
|
882
|
+
which=target_which,
|
|
883
|
+
width=sz["width"],
|
|
884
|
+
height=sz["height"],
|
|
885
|
+
n=n,
|
|
886
|
+
data_scale=data_scale,
|
|
887
|
+
var_import={"value": arr, "gp": gp_rec},
|
|
888
|
+
subset_rule=rules,
|
|
889
|
+
subsettable=True,
|
|
890
|
+
_which_explicit=which_explicit,
|
|
891
|
+
_reorient_fn=_build,
|
|
892
|
+
)
|
|
893
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
894
|
+
return anno
|
|
895
|
+
|
|
896
|
+
return _build(eff_which)
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
# ---- 6. anno_boxplot ----
|
|
900
|
+
|
|
901
|
+
def anno_boxplot(
|
|
902
|
+
x: Any,
|
|
903
|
+
which: str | None = None,
|
|
904
|
+
border: bool = True,
|
|
905
|
+
gp: dict[str, Any] | None = None,
|
|
906
|
+
ylim: Sequence[float] | None = None,
|
|
907
|
+
extend: float = 0.05,
|
|
908
|
+
outline: bool = True,
|
|
909
|
+
box_width: float = 0.6,
|
|
910
|
+
add_points: bool = False,
|
|
911
|
+
pch: Any = 16,
|
|
912
|
+
size: Any = unit(4, "pt"),
|
|
913
|
+
pt_gp: dict[str, Any] | None = None,
|
|
914
|
+
axis: bool = True,
|
|
915
|
+
background: bool = False,
|
|
916
|
+
axis_param: dict[str, Any] | None = None,
|
|
917
|
+
width: Unit | None = None,
|
|
918
|
+
height: Unit | None = None,
|
|
919
|
+
) -> AnnotationFunction:
|
|
920
|
+
which_explicit = which is not None
|
|
921
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
922
|
+
|
|
923
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
924
|
+
series = _to_obs_series(x, target_which)
|
|
925
|
+
n = len(series)
|
|
926
|
+
if ylim is None:
|
|
927
|
+
if not outline:
|
|
928
|
+
lo_vals, hi_vals = [], []
|
|
929
|
+
for s in series:
|
|
930
|
+
sf = s[np.isfinite(s)]
|
|
931
|
+
if len(sf):
|
|
932
|
+
q1, q3 = np.quantile(sf, [0.25, 0.75])
|
|
933
|
+
iqr = q3 - q1
|
|
934
|
+
in_w = sf[(sf >= q1 - 1.5 * iqr) & (sf <= q3 + 1.5 * iqr)]
|
|
935
|
+
lo_vals.append(float(np.min(in_w)) if len(in_w) else float(q1))
|
|
936
|
+
hi_vals.append(float(np.max(in_w)) if len(in_w) else float(q3))
|
|
937
|
+
lo, hi = min(lo_vals), max(hi_vals)
|
|
938
|
+
else:
|
|
939
|
+
all_v = np.concatenate(series) if n else np.array([0.0, 1.0])
|
|
940
|
+
lo, hi = float(np.nanmin(all_v)), float(np.nanmax(all_v))
|
|
941
|
+
else:
|
|
942
|
+
lo, hi = float(ylim[0]), float(ylim[1])
|
|
943
|
+
if lo == hi:
|
|
944
|
+
lo -= 0.5
|
|
945
|
+
hi += 0.5
|
|
946
|
+
span = hi - lo
|
|
947
|
+
data_scale = (lo - extend * span, hi + extend * span)
|
|
948
|
+
|
|
949
|
+
sz = anno_width_and_height(target_which, width, height, unit(2.0, "cm"))
|
|
950
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
951
|
+
ax_grob = construct_axis_grob(ap, target_which, data_scale) if axis else None
|
|
952
|
+
|
|
953
|
+
gp_rec = recycle_gp(gp or gpar(fill="#CCCCCC"), n)
|
|
954
|
+
pt_gp_rec = recycle_gp(pt_gp or gpar(), n)
|
|
955
|
+
pch_rec = _recycle_seq(pch, n)
|
|
956
|
+
sz_u = as_unit(size, "pt")
|
|
957
|
+
sz_rec = unit(np.full(n, convertWidth(sz_u, "mm", valueOnly=True)), "mm") if len(sz_u) == 1 else sz_u
|
|
958
|
+
|
|
959
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
960
|
+
val = env["value"]
|
|
961
|
+
m = len(index)
|
|
962
|
+
if m == 0:
|
|
963
|
+
return
|
|
964
|
+
rng = np.random.default_rng(42)
|
|
965
|
+
if target_which == "column":
|
|
966
|
+
pushViewport(Viewport(xscale=(0.5, m + 0.5), yscale=data_scale, clip=False))
|
|
967
|
+
try:
|
|
968
|
+
_draw_background(border, background)
|
|
969
|
+
for pos_i, orig_i in enumerate(index):
|
|
970
|
+
v = _reverse_vals(val[orig_i], data_scale, ap["direction"])
|
|
971
|
+
grid_boxplot(
|
|
972
|
+
v,
|
|
973
|
+
pos=float(pos_i + 1),
|
|
974
|
+
outline=outline and not add_points,
|
|
975
|
+
box_width=box_width,
|
|
976
|
+
pch=env["pch"][orig_i],
|
|
977
|
+
size=env["size"][orig_i],
|
|
978
|
+
gp=subset_gp(env["gp"], orig_i),
|
|
979
|
+
direction="vertical",
|
|
980
|
+
)
|
|
981
|
+
if add_points:
|
|
982
|
+
vf = v[np.isfinite(v)]
|
|
983
|
+
jitter_x = (pos_i + 1) + rng.uniform(-0.25 * box_width, 0.25 * box_width, size=len(vf))
|
|
984
|
+
grid_points(jitter_x, vf, pch=env["pch"][orig_i], size=env["size"][orig_i], gp=subset_gp(env["pt_gp"], orig_i), default_units="native")
|
|
985
|
+
show_ax = axis and ((ap["side"] == "left" and k == 1) or (ap["side"] == "right" and k == n_slices))
|
|
986
|
+
if show_ax and ax_grob is not None:
|
|
987
|
+
grid_draw(ax_grob)
|
|
988
|
+
finally:
|
|
989
|
+
popViewport()
|
|
990
|
+
else:
|
|
991
|
+
pushViewport(Viewport(xscale=data_scale, yscale=(0.5, m + 0.5), clip=False))
|
|
992
|
+
try:
|
|
993
|
+
_draw_background(border, background)
|
|
994
|
+
for pos_i, orig_i in enumerate(index):
|
|
995
|
+
v = _reverse_vals(val[orig_i], data_scale, ap["direction"])
|
|
996
|
+
grid_boxplot(
|
|
997
|
+
v,
|
|
998
|
+
pos=float(m - pos_i),
|
|
999
|
+
outline=outline and not add_points,
|
|
1000
|
+
box_width=box_width,
|
|
1001
|
+
pch=env["pch"][orig_i],
|
|
1002
|
+
size=env["size"][orig_i],
|
|
1003
|
+
gp=subset_gp(env["gp"], orig_i),
|
|
1004
|
+
direction="horizontal",
|
|
1005
|
+
)
|
|
1006
|
+
if add_points:
|
|
1007
|
+
vf = v[np.isfinite(v)]
|
|
1008
|
+
jitter_y = (m - pos_i) + rng.uniform(-0.25 * box_width, 0.25 * box_width, size=len(vf))
|
|
1009
|
+
grid_points(vf, jitter_y, pch=env["pch"][orig_i], size=env["size"][orig_i], gp=subset_gp(env["pt_gp"], orig_i), default_units="native")
|
|
1010
|
+
show_ax = axis and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices))
|
|
1011
|
+
if show_ax and ax_grob is not None:
|
|
1012
|
+
grid_draw(ax_grob)
|
|
1013
|
+
finally:
|
|
1014
|
+
popViewport()
|
|
1015
|
+
|
|
1016
|
+
anno = AnnotationFunction(
|
|
1017
|
+
fun=_draw,
|
|
1018
|
+
fun_name="anno_boxplot",
|
|
1019
|
+
which=target_which,
|
|
1020
|
+
width=sz["width"],
|
|
1021
|
+
height=sz["height"],
|
|
1022
|
+
n=n,
|
|
1023
|
+
data_scale=data_scale,
|
|
1024
|
+
var_import={"value": series, "gp": gp_rec, "pt_gp": pt_gp_rec, "pch": pch_rec, "size": sz_rec},
|
|
1025
|
+
subset_rule={"value": subset_vector, "gp": subset_gp, "pt_gp": subset_gp, "pch": subset_vector, "size": subset_vector},
|
|
1026
|
+
subsettable=True,
|
|
1027
|
+
_which_explicit=which_explicit,
|
|
1028
|
+
_reorient_fn=_build,
|
|
1029
|
+
)
|
|
1030
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
1031
|
+
return anno
|
|
1032
|
+
|
|
1033
|
+
return _build(eff_which)
|
|
1034
|
+
|
|
1035
|
+
|
|
1036
|
+
# ---- 7. anno_histogram ----
|
|
1037
|
+
|
|
1038
|
+
def anno_histogram(
|
|
1039
|
+
x: Any,
|
|
1040
|
+
which: str | None = None,
|
|
1041
|
+
n_breaks: int = 11,
|
|
1042
|
+
border: bool = False,
|
|
1043
|
+
gp: dict[str, Any] | None = None,
|
|
1044
|
+
axis: bool = True,
|
|
1045
|
+
axis_param: dict[str, Any] | None = None,
|
|
1046
|
+
width: Unit | None = None,
|
|
1047
|
+
height: Unit | None = None,
|
|
1048
|
+
) -> AnnotationFunction:
|
|
1049
|
+
which_explicit = which is not None
|
|
1050
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
1051
|
+
|
|
1052
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
1053
|
+
series = _to_obs_series(x, target_which)
|
|
1054
|
+
n = len(series)
|
|
1055
|
+
all_v = np.concatenate(series) if n else np.array([0.0, 1.0])
|
|
1056
|
+
lo, hi = float(np.nanmin(all_v)), float(np.nanmax(all_v))
|
|
1057
|
+
if lo == hi:
|
|
1058
|
+
lo -= 0.5
|
|
1059
|
+
hi += 0.5
|
|
1060
|
+
edges = np.linspace(lo, hi, int(n_breaks))
|
|
1061
|
+
data_scale = (lo, hi)
|
|
1062
|
+
|
|
1063
|
+
hists = [np.histogram(s[np.isfinite(s)], bins=edges)[0] for s in series]
|
|
1064
|
+
max_cnt = max((int(np.max(h)) for h in hists), default=1)
|
|
1065
|
+
if max_cnt <= 0:
|
|
1066
|
+
max_cnt = 1
|
|
1067
|
+
|
|
1068
|
+
sz = anno_width_and_height(target_which, width, height, unit(4.0, "cm"))
|
|
1069
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
1070
|
+
ap["direction"] = "normal"
|
|
1071
|
+
ax_grob = construct_axis_grob(ap, target_which, data_scale) if axis else None
|
|
1072
|
+
gp_rec = recycle_gp(gp or gpar(fill="#CCCCCC"), n)
|
|
1073
|
+
|
|
1074
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1075
|
+
m = len(index)
|
|
1076
|
+
if m == 0:
|
|
1077
|
+
return
|
|
1078
|
+
if target_which == "row":
|
|
1079
|
+
for pos_i, orig_i in enumerate(index):
|
|
1080
|
+
pushViewport(Viewport(x=unit(0.0, "npc"), y=unit((m - pos_i - 1) / m, "npc"), height=unit(1.0 / m, "npc"), just=("left", "bottom"), xscale=data_scale, yscale=(0.0, float(max_cnt) * 1.05)))
|
|
1081
|
+
try:
|
|
1082
|
+
cnts = hists[orig_i]
|
|
1083
|
+
sub_gp = subset_gp(env["gp"], orig_i)
|
|
1084
|
+
grid_rect(x=edges[:-1], y=np.zeros(len(cnts)), width=np.diff(edges), height=cnts, just=("left", "bottom"), gp=sub_gp, default_units="native")
|
|
1085
|
+
if border:
|
|
1086
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
1087
|
+
finally:
|
|
1088
|
+
popViewport()
|
|
1089
|
+
pushViewport(Viewport(xscale=data_scale))
|
|
1090
|
+
try:
|
|
1091
|
+
if axis and ax_grob is not None and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices)):
|
|
1092
|
+
grid_draw(ax_grob)
|
|
1093
|
+
finally:
|
|
1094
|
+
popViewport()
|
|
1095
|
+
else:
|
|
1096
|
+
for pos_i, orig_i in enumerate(index):
|
|
1097
|
+
pushViewport(Viewport(x=unit(pos_i / m, "npc"), y=unit(0.0, "npc"), width=unit(1.0 / m, "npc"), just=("left", "bottom"), xscale=(0.0, float(max_cnt) * 1.05), yscale=data_scale))
|
|
1098
|
+
try:
|
|
1099
|
+
cnts = hists[orig_i]
|
|
1100
|
+
sub_gp = subset_gp(env["gp"], orig_i)
|
|
1101
|
+
grid_rect(x=np.zeros(len(cnts)), y=edges[:-1], width=cnts, height=np.diff(edges), just=("left", "bottom"), gp=sub_gp, default_units="native")
|
|
1102
|
+
if border:
|
|
1103
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
1104
|
+
finally:
|
|
1105
|
+
popViewport()
|
|
1106
|
+
pushViewport(Viewport(yscale=data_scale))
|
|
1107
|
+
try:
|
|
1108
|
+
if axis and ax_grob is not None and ((ap["side"] == "left" and k == 1) or (ap["side"] == "right" and k == n_slices)):
|
|
1109
|
+
grid_draw(ax_grob)
|
|
1110
|
+
finally:
|
|
1111
|
+
popViewport()
|
|
1112
|
+
|
|
1113
|
+
anno = AnnotationFunction(
|
|
1114
|
+
fun=_draw,
|
|
1115
|
+
fun_name="anno_histogram",
|
|
1116
|
+
which=target_which,
|
|
1117
|
+
width=sz["width"],
|
|
1118
|
+
height=sz["height"],
|
|
1119
|
+
n=n,
|
|
1120
|
+
data_scale=data_scale,
|
|
1121
|
+
var_import={"value": hists, "gp": gp_rec},
|
|
1122
|
+
subset_rule={"value": subset_vector, "gp": subset_gp},
|
|
1123
|
+
subsettable=True,
|
|
1124
|
+
_which_explicit=which_explicit,
|
|
1125
|
+
_reorient_fn=_build,
|
|
1126
|
+
)
|
|
1127
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
1128
|
+
return anno
|
|
1129
|
+
|
|
1130
|
+
return _build(eff_which)
|
|
1131
|
+
|
|
1132
|
+
|
|
1133
|
+
# ---- 8. anno_density ----
|
|
1134
|
+
|
|
1135
|
+
def anno_density(
|
|
1136
|
+
x: Any,
|
|
1137
|
+
which: str | None = None,
|
|
1138
|
+
type: str = "lines",
|
|
1139
|
+
xlim: Sequence[float] | None = None,
|
|
1140
|
+
max_density: float | None = None,
|
|
1141
|
+
heatmap_colors: Sequence[Any] | None = None,
|
|
1142
|
+
joyplot_scale: float = 1.0,
|
|
1143
|
+
border: bool = True,
|
|
1144
|
+
gp: dict[str, Any] | None = None,
|
|
1145
|
+
axis: bool = True,
|
|
1146
|
+
axis_param: dict[str, Any] | None = None,
|
|
1147
|
+
width: Unit | None = None,
|
|
1148
|
+
height: Unit | None = None,
|
|
1149
|
+
) -> AnnotationFunction:
|
|
1150
|
+
which_explicit = which is not None
|
|
1151
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
1152
|
+
if heatmap_colors is None:
|
|
1153
|
+
heatmap_colors = list(reversed(brewer_pal(11, "RdYlBu")))
|
|
1154
|
+
|
|
1155
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
1156
|
+
series = _to_obs_series(x, target_which)
|
|
1157
|
+
n = len(series)
|
|
1158
|
+
all_v = np.concatenate(series) if n else np.array([0.0, 1.0])
|
|
1159
|
+
if xlim is None:
|
|
1160
|
+
lo, hi = float(np.nanmin(all_v)), float(np.nanmax(all_v))
|
|
1161
|
+
pad = 0.1 * (hi - lo) if hi > lo else 1.0
|
|
1162
|
+
data_scale = (lo - pad, hi + pad)
|
|
1163
|
+
else:
|
|
1164
|
+
data_scale = (float(xlim[0]), float(xlim[1]))
|
|
1165
|
+
|
|
1166
|
+
grid_pts = np.linspace(data_scale[0], data_scale[1], 256)
|
|
1167
|
+
dens_list: list[np.ndarray] = []
|
|
1168
|
+
for s in series:
|
|
1169
|
+
sf = s[np.isfinite(s)]
|
|
1170
|
+
if len(sf) >= 2 and np.std(sf) > 1e-12:
|
|
1171
|
+
kde = gaussian_kde(sf)
|
|
1172
|
+
dens_list.append(kde(grid_pts))
|
|
1173
|
+
else:
|
|
1174
|
+
dens_list.append(np.zeros_like(grid_pts))
|
|
1175
|
+
|
|
1176
|
+
max_d = float(max_density) if max_density is not None else max((float(np.max(d)) for d in dens_list), default=1.0)
|
|
1177
|
+
if max_d <= 0:
|
|
1178
|
+
max_d = 1.0
|
|
1179
|
+
col_fun = colorRamp2(np.linspace(0.0, max_d, len(heatmap_colors)), heatmap_colors)
|
|
1180
|
+
|
|
1181
|
+
sz = anno_width_and_height(target_which, width, height, unit(4.0, "cm"))
|
|
1182
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
1183
|
+
ap["direction"] = "normal"
|
|
1184
|
+
ax_grob = construct_axis_grob(ap, target_which, data_scale) if axis else None
|
|
1185
|
+
gp_rec = recycle_gp(gp or gpar(fill="#CCCCCC"), n)
|
|
1186
|
+
|
|
1187
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1188
|
+
m = len(index)
|
|
1189
|
+
if m == 0:
|
|
1190
|
+
return
|
|
1191
|
+
if target_which == "row":
|
|
1192
|
+
for pos_i, orig_i in enumerate(index):
|
|
1193
|
+
y_scale = (0.0, max_d) if type == "lines" else (0.0, 1.0)
|
|
1194
|
+
pushViewport(Viewport(x=unit(0.0, "npc"), y=unit((m - pos_i - 1) / m, "npc"), height=unit(1.0 / m, "npc"), just=("left", "bottom"), xscale=data_scale, yscale=y_scale))
|
|
1195
|
+
try:
|
|
1196
|
+
dv = dens_list[orig_i]
|
|
1197
|
+
sub_gp = subset_gp(env["gp"], orig_i)
|
|
1198
|
+
if type == "lines":
|
|
1199
|
+
px = np.concatenate([[grid_pts[0]], grid_pts, [grid_pts[-1]]])
|
|
1200
|
+
py = np.concatenate([[0.0], dv * joyplot_scale, [0.0]])
|
|
1201
|
+
grid_polygon(px, py, gp=sub_gp, default_units="native")
|
|
1202
|
+
elif type == "violin":
|
|
1203
|
+
d_norm = 0.45 * dv / max(float(np.max(dv)), 1e-12)
|
|
1204
|
+
px = np.concatenate([grid_pts, grid_pts[::-1]])
|
|
1205
|
+
py = np.concatenate([0.5 + d_norm, 0.5 - d_norm[::-1]])
|
|
1206
|
+
grid_polygon(px, py, gp=sub_gp, default_units="native")
|
|
1207
|
+
sf = series[orig_i][np.isfinite(series[orig_i])]
|
|
1208
|
+
if len(sf):
|
|
1209
|
+
q1, med, q3 = np.quantile(sf, [0.25, 0.5, 0.75])
|
|
1210
|
+
grid_segments([q1], [0.5], [q3], [0.5], gp=gpar(col="black", lwd=2), default_units="native")
|
|
1211
|
+
grid_points([med], [0.5], pch=16, size=unit(2, "mm"), gp=gpar(col="white"), default_units="native")
|
|
1212
|
+
elif type == "heatmap":
|
|
1213
|
+
cols_h = list(col_fun(dv))
|
|
1214
|
+
step = (data_scale[1] - data_scale[0]) / len(dv)
|
|
1215
|
+
grid_rect(x=grid_pts, y=np.full(len(dv), 0.5), width=np.full(len(dv), step * 1.05), height=np.ones(len(dv)), gp=gpar(fill=cols_h, col=None), default_units="native")
|
|
1216
|
+
if border:
|
|
1217
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
1218
|
+
finally:
|
|
1219
|
+
popViewport()
|
|
1220
|
+
pushViewport(Viewport(xscale=data_scale))
|
|
1221
|
+
try:
|
|
1222
|
+
if axis and ax_grob is not None and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices)):
|
|
1223
|
+
grid_draw(ax_grob)
|
|
1224
|
+
finally:
|
|
1225
|
+
popViewport()
|
|
1226
|
+
else:
|
|
1227
|
+
for pos_i, orig_i in enumerate(index):
|
|
1228
|
+
x_scale = (0.0, max_d) if type == "lines" else (0.0, 1.0)
|
|
1229
|
+
pushViewport(Viewport(x=unit(pos_i / m, "npc"), y=unit(0.0, "npc"), width=unit(1.0 / m, "npc"), just=("left", "bottom"), xscale=x_scale, yscale=data_scale))
|
|
1230
|
+
try:
|
|
1231
|
+
dv = dens_list[orig_i]
|
|
1232
|
+
sub_gp = subset_gp(env["gp"], orig_i)
|
|
1233
|
+
if type == "lines":
|
|
1234
|
+
py = np.concatenate([[grid_pts[0]], grid_pts, [grid_pts[-1]]])
|
|
1235
|
+
px = np.concatenate([[0.0], dv * joyplot_scale, [0.0]])
|
|
1236
|
+
grid_polygon(px, py, gp=sub_gp, default_units="native")
|
|
1237
|
+
elif type == "violin":
|
|
1238
|
+
d_norm = 0.45 * dv / max(float(np.max(dv)), 1e-12)
|
|
1239
|
+
py = np.concatenate([grid_pts, grid_pts[::-1]])
|
|
1240
|
+
px = np.concatenate([0.5 + d_norm, 0.5 - d_norm[::-1]])
|
|
1241
|
+
grid_polygon(px, py, gp=sub_gp, default_units="native")
|
|
1242
|
+
sf = series[orig_i][np.isfinite(series[orig_i])]
|
|
1243
|
+
if len(sf):
|
|
1244
|
+
q1, med, q3 = np.quantile(sf, [0.25, 0.5, 0.75])
|
|
1245
|
+
grid_segments([0.5], [q1], [0.5], [q3], gp=gpar(col="black", lwd=2), default_units="native")
|
|
1246
|
+
grid_points([0.5], [med], pch=16, size=unit(2, "mm"), gp=gpar(col="white"), default_units="native")
|
|
1247
|
+
elif type == "heatmap":
|
|
1248
|
+
cols_h = list(col_fun(dv))
|
|
1249
|
+
step = (data_scale[1] - data_scale[0]) / len(dv)
|
|
1250
|
+
grid_rect(x=np.full(len(dv), 0.5), y=grid_pts, width=np.ones(len(dv)), height=np.full(len(dv), step * 1.05), gp=gpar(fill=cols_h, col=None), default_units="native")
|
|
1251
|
+
if border:
|
|
1252
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
1253
|
+
finally:
|
|
1254
|
+
popViewport()
|
|
1255
|
+
pushViewport(Viewport(yscale=data_scale))
|
|
1256
|
+
try:
|
|
1257
|
+
if axis and ax_grob is not None and ((ap["side"] == "left" and k == 1) or (ap["side"] == "right" and k == n_slices)):
|
|
1258
|
+
grid_draw(ax_grob)
|
|
1259
|
+
finally:
|
|
1260
|
+
popViewport()
|
|
1261
|
+
|
|
1262
|
+
anno = AnnotationFunction(
|
|
1263
|
+
fun=_draw,
|
|
1264
|
+
fun_name="anno_density",
|
|
1265
|
+
which=target_which,
|
|
1266
|
+
width=sz["width"],
|
|
1267
|
+
height=sz["height"],
|
|
1268
|
+
n=n,
|
|
1269
|
+
data_scale=data_scale,
|
|
1270
|
+
var_import={"value": series, "gp": gp_rec},
|
|
1271
|
+
subset_rule={"value": subset_vector, "gp": subset_gp},
|
|
1272
|
+
subsettable=True,
|
|
1273
|
+
_which_explicit=which_explicit,
|
|
1274
|
+
_reorient_fn=_build,
|
|
1275
|
+
)
|
|
1276
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
1277
|
+
return anno
|
|
1278
|
+
|
|
1279
|
+
return _build(eff_which)
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
# ---- 9. anno_joyplot ----
|
|
1283
|
+
|
|
1284
|
+
def _normalize_xy_series(x: Any) -> list[np.ndarray]:
|
|
1285
|
+
if isinstance(x, pd.DataFrame):
|
|
1286
|
+
arr = x.to_numpy(dtype=float)
|
|
1287
|
+
return [np.column_stack([np.arange(1, arr.shape[0] + 1, dtype=float), arr[:, c]]) for c in range(arr.shape[1])]
|
|
1288
|
+
if isinstance(x, np.ndarray) and x.ndim == 2:
|
|
1289
|
+
arr = x.astype(float)
|
|
1290
|
+
return [np.column_stack([np.arange(1, arr.shape[0] + 1, dtype=float), arr[:, c]]) for c in range(arr.shape[1])]
|
|
1291
|
+
items = list(x.values()) if isinstance(x, dict) else list(x)
|
|
1292
|
+
out: list[np.ndarray] = []
|
|
1293
|
+
for it in items:
|
|
1294
|
+
if isinstance(it, dict) and "x" in it and "y" in it:
|
|
1295
|
+
out.append(np.column_stack([np.asarray(it["x"], dtype=float), np.asarray(it["y"], dtype=float)]))
|
|
1296
|
+
elif isinstance(it, pd.DataFrame) and it.shape[1] >= 2:
|
|
1297
|
+
out.append(it.iloc[:, :2].to_numpy(dtype=float))
|
|
1298
|
+
else:
|
|
1299
|
+
a = np.asarray(it, dtype=float)
|
|
1300
|
+
if a.ndim == 2 and a.shape[1] >= 2:
|
|
1301
|
+
out.append(a[:, :2])
|
|
1302
|
+
else:
|
|
1303
|
+
out.append(np.column_stack([np.arange(1, len(a) + 1, dtype=float), a.ravel()]))
|
|
1304
|
+
return out
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
def anno_joyplot(
|
|
1308
|
+
x: Any,
|
|
1309
|
+
which: str | None = None,
|
|
1310
|
+
gp: dict[str, Any] | None = None,
|
|
1311
|
+
scale: float = 2.0,
|
|
1312
|
+
transparency: float = 0.6,
|
|
1313
|
+
axis: bool = True,
|
|
1314
|
+
axis_param: dict[str, Any] | None = None,
|
|
1315
|
+
width: Unit | None = None,
|
|
1316
|
+
height: Unit | None = None,
|
|
1317
|
+
) -> AnnotationFunction:
|
|
1318
|
+
which_explicit = which is not None
|
|
1319
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
1320
|
+
|
|
1321
|
+
value = _normalize_xy_series(x)
|
|
1322
|
+
n = len(value)
|
|
1323
|
+
all_x = np.concatenate([v[:, 0] for v in value]) if n else np.array([0.0, 1.0])
|
|
1324
|
+
all_y = np.concatenate([v[:, 1] for v in value]) if n else np.array([0.0, 1.0])
|
|
1325
|
+
x0, x1 = float(np.nanmin(all_x)), float(np.nanmax(all_x))
|
|
1326
|
+
xscale = (x0 - 0.025 * (x1 - x0), x1 + 0.025 * (x1 - x0))
|
|
1327
|
+
yscale = (0.0, max(1e-12, float(np.nanmax(all_y)) * 1.05))
|
|
1328
|
+
|
|
1329
|
+
gp_d = check_gp(gp)
|
|
1330
|
+
if "fill" not in gp_d:
|
|
1331
|
+
gp_d["fill"] = "#000000"
|
|
1332
|
+
gp_rec = recycle_gp(gp_d, n)
|
|
1333
|
+
gp_rec["fill"] = add_transparency(gp_rec["fill"], transparency)
|
|
1334
|
+
|
|
1335
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
1336
|
+
sz = anno_width_and_height(target_which, width, height, unit(4.0, "cm"))
|
|
1337
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
1338
|
+
ap["direction"] = "normal"
|
|
1339
|
+
ax_grob = construct_axis_grob(ap, target_which, xscale) if axis else None
|
|
1340
|
+
|
|
1341
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1342
|
+
val = env["value"]
|
|
1343
|
+
m = len(index)
|
|
1344
|
+
if m == 0:
|
|
1345
|
+
return
|
|
1346
|
+
if target_which == "row":
|
|
1347
|
+
for pos_i, orig_i in enumerate(index):
|
|
1348
|
+
pushViewport(Viewport(x=unit(0.0, "npc"), y=unit((m - pos_i - 1) / m, "npc"), just=("left", "bottom"), height=unit(1.0 / m, "npc"), xscale=xscale, yscale=yscale))
|
|
1349
|
+
try:
|
|
1350
|
+
arr_xy = val[orig_i]
|
|
1351
|
+
px = np.concatenate([[arr_xy[0, 0]], arr_xy[:, 0], [arr_xy[-1, 0]]])
|
|
1352
|
+
py = np.concatenate([[0.0], arr_xy[:, 1] * scale, [0.0]])
|
|
1353
|
+
sgp = subset_gp(env["gp"], orig_i)
|
|
1354
|
+
gppp = sgp.copy()
|
|
1355
|
+
gppp["col"] = "#00000000"
|
|
1356
|
+
grid_polygon(px, py, gp=gppp, default_units="native")
|
|
1357
|
+
grid_lines(px, py, gp=sgp, default_units="native")
|
|
1358
|
+
finally:
|
|
1359
|
+
popViewport()
|
|
1360
|
+
pushViewport(Viewport(xscale=xscale))
|
|
1361
|
+
try:
|
|
1362
|
+
if axis and ax_grob is not None and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices)):
|
|
1363
|
+
grid_draw(ax_grob)
|
|
1364
|
+
finally:
|
|
1365
|
+
popViewport()
|
|
1366
|
+
else:
|
|
1367
|
+
for pos_i, orig_i in enumerate(index):
|
|
1368
|
+
pushViewport(Viewport(y=unit(0.0, "npc"), x=unit((pos_i + 1) / m, "npc"), width=unit(1.0 / m, "npc"), just=("right", "bottom"), xscale=yscale, yscale=xscale))
|
|
1369
|
+
try:
|
|
1370
|
+
arr_xy = val[orig_i]
|
|
1371
|
+
py = np.concatenate([[arr_xy[0, 0]], arr_xy[:, 0], [arr_xy[-1, 0]]])
|
|
1372
|
+
px = np.concatenate([[0.0], arr_xy[:, 1] * scale, [0.0]])
|
|
1373
|
+
sgp = subset_gp(env["gp"], orig_i)
|
|
1374
|
+
gppp = sgp.copy()
|
|
1375
|
+
gppp["col"] = "#00000000"
|
|
1376
|
+
grid_polygon(px, py, gp=gppp, default_units="native")
|
|
1377
|
+
grid_lines(px, py, gp=sgp, default_units="native")
|
|
1378
|
+
finally:
|
|
1379
|
+
popViewport()
|
|
1380
|
+
pushViewport(Viewport(yscale=xscale))
|
|
1381
|
+
try:
|
|
1382
|
+
if axis and ax_grob is not None and ((ap["side"] == "left" and k == 1) or (ap["side"] == "right" and k == n_slices)):
|
|
1383
|
+
grid_draw(ax_grob)
|
|
1384
|
+
finally:
|
|
1385
|
+
popViewport()
|
|
1386
|
+
|
|
1387
|
+
anno = AnnotationFunction(
|
|
1388
|
+
fun=_draw,
|
|
1389
|
+
fun_name="anno_joyplot",
|
|
1390
|
+
which=target_which,
|
|
1391
|
+
width=sz["width"],
|
|
1392
|
+
height=sz["height"],
|
|
1393
|
+
n=n,
|
|
1394
|
+
data_scale=xscale,
|
|
1395
|
+
var_import={"value": value, "gp": gp_rec},
|
|
1396
|
+
subset_rule={"value": subset_vector, "gp": subset_gp},
|
|
1397
|
+
subsettable=True,
|
|
1398
|
+
_which_explicit=which_explicit,
|
|
1399
|
+
_reorient_fn=_build,
|
|
1400
|
+
)
|
|
1401
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
1402
|
+
return anno
|
|
1403
|
+
|
|
1404
|
+
return _build(eff_which)
|
|
1405
|
+
|
|
1406
|
+
|
|
1407
|
+
# ---- 10. anno_horizon ----
|
|
1408
|
+
|
|
1409
|
+
def anno_horizon(
|
|
1410
|
+
x: Any,
|
|
1411
|
+
which: str = "row",
|
|
1412
|
+
gp: dict[str, Any] | None = None,
|
|
1413
|
+
n_slice: int = 4,
|
|
1414
|
+
slice_size: float | None = None,
|
|
1415
|
+
negative_from_top: bool = False,
|
|
1416
|
+
normalize: bool = True,
|
|
1417
|
+
gap: Any = unit(0, "mm"),
|
|
1418
|
+
axis: bool = True,
|
|
1419
|
+
axis_param: dict[str, Any] | None = None,
|
|
1420
|
+
width: Unit | None = None,
|
|
1421
|
+
height: Unit | None = None,
|
|
1422
|
+
) -> AnnotationFunction:
|
|
1423
|
+
which = which.lower()
|
|
1424
|
+
if which == "column":
|
|
1425
|
+
raise ValueError("`anno_horizon()` does not support column annotation.")
|
|
1426
|
+
|
|
1427
|
+
value = _normalize_xy_series(x)
|
|
1428
|
+
n = len(value)
|
|
1429
|
+
gp_d = gpar(pos_fill="#D73027", neg_fill="#313695") if gp is None else check_gp(gp)
|
|
1430
|
+
if "pos_fill" not in gp_d:
|
|
1431
|
+
gp_d["pos_fill"] = "#D73027"
|
|
1432
|
+
if "neg_fill" not in gp_d:
|
|
1433
|
+
gp_d["neg_fill"] = "#313695"
|
|
1434
|
+
gp_rec = recycle_gp(gp_d, n)
|
|
1435
|
+
|
|
1436
|
+
if normalize:
|
|
1437
|
+
norm_val = []
|
|
1438
|
+
for arr_xy in value:
|
|
1439
|
+
mx = float(np.nanmax(np.abs(arr_xy[:, 1])))
|
|
1440
|
+
out_arr = arr_xy.copy()
|
|
1441
|
+
if mx > 0:
|
|
1442
|
+
out_arr[:, 1] = out_arr[:, 1] / mx
|
|
1443
|
+
norm_val.append(out_arr)
|
|
1444
|
+
value = norm_val
|
|
1445
|
+
|
|
1446
|
+
all_x = np.concatenate([v[:, 0] for v in value]) if n else np.array([0.0, 1.0])
|
|
1447
|
+
all_y = np.concatenate([np.abs(v[:, 1]) for v in value]) if n else np.array([0.0, 1.0])
|
|
1448
|
+
xscale = (float(np.nanmin(all_x)), float(np.nanmax(all_x)))
|
|
1449
|
+
ymax = max(1e-12, float(np.nanmax(all_y)))
|
|
1450
|
+
|
|
1451
|
+
sz = anno_width_and_height("row", width, height, unit(4.0, "cm"))
|
|
1452
|
+
ap = validate_axis_param(axis_param, "row")
|
|
1453
|
+
ap["direction"] = "normal"
|
|
1454
|
+
ax_grob = construct_axis_grob(ap, "row", xscale) if axis else None
|
|
1455
|
+
gap_u = as_unit(gap, "mm")
|
|
1456
|
+
|
|
1457
|
+
def _draw_horizon_chart(xv: np.ndarray, yv: np.ndarray, sl_size: float, n_sl: int, pos_fill: Any, neg_fill: Any) -> None:
|
|
1458
|
+
pos_cf = colorRamp2([0.0, float(n_sl)], ["white", pos_fill])
|
|
1459
|
+
neg_cf = colorRamp2([0.0, float(n_sl)], ["white", neg_fill])
|
|
1460
|
+
pushViewport(Viewport(xscale=(float(np.min(xv)), float(np.max(xv))), yscale=(0.0, sl_size)))
|
|
1461
|
+
try:
|
|
1462
|
+
for sign_v, cf, from_top in ((1.0, pos_cf, False), (-1.0, neg_cf, negative_from_top)):
|
|
1463
|
+
ys = sign_v * yv
|
|
1464
|
+
for i in range(1, n_sl + 1):
|
|
1465
|
+
lo_b = (i - 1) * sl_size
|
|
1466
|
+
hi_b = i * sl_size
|
|
1467
|
+
active = ys >= lo_b
|
|
1468
|
+
if not np.any(active):
|
|
1469
|
+
continue
|
|
1470
|
+
y_band = np.where(ys >= hi_b, sl_size, np.where(ys >= lo_b, ys - lo_b, np.nan))
|
|
1471
|
+
# Split into contiguous non-NaN segments
|
|
1472
|
+
valid = np.isfinite(y_band)
|
|
1473
|
+
idx = 0
|
|
1474
|
+
while idx < len(valid):
|
|
1475
|
+
while idx < len(valid) and not valid[idx]:
|
|
1476
|
+
idx += 1
|
|
1477
|
+
j = idx
|
|
1478
|
+
while j < len(valid) and valid[j]:
|
|
1479
|
+
j += 1
|
|
1480
|
+
if j > idx:
|
|
1481
|
+
sx = xv[idx:j]
|
|
1482
|
+
sy = y_band[idx:j]
|
|
1483
|
+
px = np.concatenate([[sx[0]], sx, [sx[-1]]])
|
|
1484
|
+
if from_top:
|
|
1485
|
+
py = np.concatenate([[sl_size], sl_size - sy, [sl_size]])
|
|
1486
|
+
else:
|
|
1487
|
+
py = np.concatenate([[0.0], sy, [0.0]])
|
|
1488
|
+
grid_polygon(px, py, gp=gpar(fill=cf(i), col=None), default_units="native")
|
|
1489
|
+
idx = j
|
|
1490
|
+
finally:
|
|
1491
|
+
popViewport()
|
|
1492
|
+
|
|
1493
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1494
|
+
val = env["value"]
|
|
1495
|
+
m = len(index)
|
|
1496
|
+
if m == 0:
|
|
1497
|
+
return
|
|
1498
|
+
sl_sz = float(slice_size) if slice_size is not None else ymax / n_slice
|
|
1499
|
+
n_sl = max(1, int(np.ceil(ymax / sl_sz)))
|
|
1500
|
+
for pos_i, orig_i in enumerate(index):
|
|
1501
|
+
pushViewport(Viewport(x=unit(0.0, "npc"), y=unit((m - pos_i - 1) / m, "npc"), just=("left", "bottom"), height=unit(1.0 / m, "npc") - gap_u))
|
|
1502
|
+
try:
|
|
1503
|
+
sgp = subset_gp(env["gp"], orig_i)
|
|
1504
|
+
_draw_horizon_chart(val[orig_i][:, 0], val[orig_i][:, 1], sl_sz, n_sl, sgp["pos_fill"], sgp["neg_fill"])
|
|
1505
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
1506
|
+
finally:
|
|
1507
|
+
popViewport()
|
|
1508
|
+
pushViewport(Viewport(xscale=xscale))
|
|
1509
|
+
try:
|
|
1510
|
+
if axis and ax_grob is not None and ((ap["side"] == "top" and k == 1) or (ap["side"] == "bottom" and k == n_slices)):
|
|
1511
|
+
grid_draw(ax_grob)
|
|
1512
|
+
finally:
|
|
1513
|
+
popViewport()
|
|
1514
|
+
|
|
1515
|
+
anno = AnnotationFunction(
|
|
1516
|
+
fun=_draw,
|
|
1517
|
+
fun_name="anno_horizon",
|
|
1518
|
+
which="row",
|
|
1519
|
+
width=sz["width"],
|
|
1520
|
+
height=sz["height"],
|
|
1521
|
+
n=n,
|
|
1522
|
+
data_scale=xscale,
|
|
1523
|
+
var_import={"value": value, "gp": gp_rec},
|
|
1524
|
+
subset_rule={"value": subset_vector, "gp": subset_gp},
|
|
1525
|
+
subsettable=True,
|
|
1526
|
+
_which_explicit=True,
|
|
1527
|
+
)
|
|
1528
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
1529
|
+
return anno
|
|
1530
|
+
|
|
1531
|
+
|
|
1532
|
+
# ---- 11. anno_text ----
|
|
1533
|
+
|
|
1534
|
+
def anno_text(
|
|
1535
|
+
x: Any,
|
|
1536
|
+
which: str | None = None,
|
|
1537
|
+
gp: dict[str, Any] | None = None,
|
|
1538
|
+
rot: float | None = None,
|
|
1539
|
+
just: Any = None,
|
|
1540
|
+
offset: Any = None,
|
|
1541
|
+
location: Any = None,
|
|
1542
|
+
width: Unit | None = None,
|
|
1543
|
+
height: Unit | None = None,
|
|
1544
|
+
show_name: bool = False,
|
|
1545
|
+
) -> AnnotationFunction:
|
|
1546
|
+
which_explicit = which is not None
|
|
1547
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
1548
|
+
|
|
1549
|
+
from .text import GridText
|
|
1550
|
+
is_gt = isinstance(x, GridText)
|
|
1551
|
+
n = len(x)
|
|
1552
|
+
gp_rec = recycle_gp(gp or gpar(), n)
|
|
1553
|
+
|
|
1554
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
1555
|
+
eff_rot = (90.0 if target_which == "column" else 0.0) if rot is None else float(rot)
|
|
1556
|
+
eff_just = ("right" if target_which == "column" else "left") if just is None else just
|
|
1557
|
+
loc_raw = offset if location is None and offset is not None else location
|
|
1558
|
+
if loc_raw is None:
|
|
1559
|
+
eff_loc = unit(1.0, "npc") if target_which == "column" else unit(0.0, "npc")
|
|
1560
|
+
else:
|
|
1561
|
+
eff_loc = as_unit(loc_raw, "npc")
|
|
1562
|
+
|
|
1563
|
+
if target_which == "column":
|
|
1564
|
+
h_u = height if height is not None else max_text_height(x, gp=gp_rec, rot=eff_rot) + unit(2.0, "mm")
|
|
1565
|
+
w_u = width
|
|
1566
|
+
else:
|
|
1567
|
+
w_u = width if width is not None else max_text_width(x, gp=gp_rec, rot=eff_rot) + unit(2.0, "mm")
|
|
1568
|
+
h_u = height
|
|
1569
|
+
sz = anno_width_and_height(target_which, w_u, h_u, unit(1.0, "cm"))
|
|
1570
|
+
|
|
1571
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1572
|
+
val = env["value"]
|
|
1573
|
+
sub_val = val[index] if isinstance(val, GridText) else [val[i] for i in index]
|
|
1574
|
+
sub_gp = subset_gp(env["gp"], index)
|
|
1575
|
+
m = len(index)
|
|
1576
|
+
if m == 0:
|
|
1577
|
+
return
|
|
1578
|
+
has_bg = "fill" in sub_gp or "border" in sub_gp
|
|
1579
|
+
if target_which == "column":
|
|
1580
|
+
xs = unit((np.arange(m) + 0.5) / m, "npc")
|
|
1581
|
+
ys = eff_loc
|
|
1582
|
+
if has_bg:
|
|
1583
|
+
grid_rect(x=xs, y=unit(np.full(m, 0.5), "npc"), width=unit(np.full(m, 1.0 / m), "npc"), height=unit(np.ones(m), "npc"), gp=gpar(fill=sub_gp.get("fill", "transparent"), col=sub_gp.get("border", None)))
|
|
1584
|
+
grid_text(sub_val, x=xs, y=ys, just=eff_just, rot=eff_rot, gp=sub_gp)
|
|
1585
|
+
else:
|
|
1586
|
+
ys = unit((m - np.arange(m) - 0.5) / m, "npc")
|
|
1587
|
+
xs = eff_loc
|
|
1588
|
+
if has_bg:
|
|
1589
|
+
grid_rect(x=unit(np.full(m, 0.5), "npc"), y=ys, width=unit(np.ones(m), "npc"), height=unit(np.full(m, 1.0 / m), "npc"), gp=gpar(fill=sub_gp.get("fill", "transparent"), col=sub_gp.get("border", None)))
|
|
1590
|
+
grid_text(sub_val, x=xs, y=ys, just=eff_just, rot=eff_rot, gp=sub_gp)
|
|
1591
|
+
|
|
1592
|
+
val_store = x if is_gt else [str(v) for v in x]
|
|
1593
|
+
return AnnotationFunction(
|
|
1594
|
+
fun=_draw,
|
|
1595
|
+
fun_name="anno_text",
|
|
1596
|
+
which=target_which,
|
|
1597
|
+
width=sz["width"],
|
|
1598
|
+
height=sz["height"],
|
|
1599
|
+
n=n,
|
|
1600
|
+
var_import={"value": val_store, "gp": gp_rec},
|
|
1601
|
+
subset_rule={"value": (lambda v, i: v[i]) if is_gt else subset_vector, "gp": subset_gp},
|
|
1602
|
+
subsettable=True,
|
|
1603
|
+
show_name=show_name,
|
|
1604
|
+
_which_explicit=which_explicit,
|
|
1605
|
+
_reorient_fn=_build,
|
|
1606
|
+
)
|
|
1607
|
+
|
|
1608
|
+
return _build(eff_which)
|
|
1609
|
+
|
|
1610
|
+
|
|
1611
|
+
# ---- 12. anno_numeric ----
|
|
1612
|
+
|
|
1613
|
+
def anno_numeric(
|
|
1614
|
+
x: Sequence[float],
|
|
1615
|
+
rg: Sequence[float] | None = None,
|
|
1616
|
+
labels_gp: dict[str, Any] | None = None,
|
|
1617
|
+
x_convert: Callable[[np.ndarray], np.ndarray] | None = None,
|
|
1618
|
+
labels_format: Callable[[Sequence[float]], Sequence[str]] | None = None,
|
|
1619
|
+
labels_offset: Any = unit(4, "pt"),
|
|
1620
|
+
bg_gp: dict[str, Any] | None = None,
|
|
1621
|
+
bar_width: Any = None,
|
|
1622
|
+
round_corners: bool = True,
|
|
1623
|
+
r: Any = unit(0.05, "snpc"),
|
|
1624
|
+
which: str = "row",
|
|
1625
|
+
align_to: str | float | None = None,
|
|
1626
|
+
width: Unit | None = None,
|
|
1627
|
+
) -> AnnotationFunction:
|
|
1628
|
+
which = which.lower()
|
|
1629
|
+
if which == "column":
|
|
1630
|
+
raise ValueError("`anno_numeric()` can only be used as row annotation.")
|
|
1631
|
+
arr = np.asarray(x, dtype=float)
|
|
1632
|
+
n = len(arr)
|
|
1633
|
+
lbls = [str(v) for v in (labels_format(arr) if labels_format is not None else np.round(arr, 2))]
|
|
1634
|
+
|
|
1635
|
+
if rg is None:
|
|
1636
|
+
r_lo, r_hi = float(np.nanmin(arr)), float(np.nanmax(arr))
|
|
1637
|
+
else:
|
|
1638
|
+
r_lo, r_hi = float(rg[0]), float(rg[1])
|
|
1639
|
+
if x_convert is not None:
|
|
1640
|
+
arr = np.asarray(x_convert(arr), dtype=float)
|
|
1641
|
+
conv_rg = np.asarray(x_convert(np.array([r_lo, r_hi], dtype=float)), dtype=float)
|
|
1642
|
+
r_lo, r_hi = float(np.min(conv_rg)), float(np.max(conv_rg))
|
|
1643
|
+
if r_lo == r_hi:
|
|
1644
|
+
r_hi = r_lo + 1e-6
|
|
1645
|
+
arr = np.clip(arr, r_lo, r_hi)
|
|
1646
|
+
|
|
1647
|
+
if align_to is None:
|
|
1648
|
+
align_to = 0 if (np.any(arr > 0) and np.any(arr < 0)) else "left"
|
|
1649
|
+
|
|
1650
|
+
lgp_rec = recycle_gp(labels_gp or gpar(fontsize=10), n)
|
|
1651
|
+
bgp_rec = recycle_gp(bg_gp or gpar(fill="#8080FF", col="#8080FF"), n)
|
|
1652
|
+
bw_u = (unit(1.0, "npc") - unit(4.0, "pt")) if bar_width is None else as_unit(bar_width, "npc")
|
|
1653
|
+
off_u = as_unit(labels_offset, "pt")
|
|
1654
|
+
r_u = as_unit(r, "snpc")
|
|
1655
|
+
|
|
1656
|
+
if width is None:
|
|
1657
|
+
if align_to == 0:
|
|
1658
|
+
pos_lbls = [lb for v, lb in zip(arr, lbls) if v >= 0] or ["0"]
|
|
1659
|
+
neg_lbls = [lb for v, lb in zip(arr, lbls) if v < 0] or ["0"]
|
|
1660
|
+
w_mm = max(20.0, max_text_width(pos_lbls, gp=lgp_rec).to_mm_scalar() + max_text_width(neg_lbls, gp=lgp_rec).to_mm_scalar() + 6.0)
|
|
1661
|
+
else:
|
|
1662
|
+
w_mm = max(20.0, max_text_width(lbls, gp=lgp_rec).to_mm_scalar() + 4.0)
|
|
1663
|
+
w_u = unit(w_mm, "mm")
|
|
1664
|
+
else:
|
|
1665
|
+
w_u = as_unit(width, "mm")
|
|
1666
|
+
|
|
1667
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1668
|
+
vals = env["value"]
|
|
1669
|
+
lb_list = env["labels"]
|
|
1670
|
+
m = len(index)
|
|
1671
|
+
for pos_i, orig_i in enumerate(index):
|
|
1672
|
+
pushViewport(Viewport(y=unit(1.0 - (pos_i + 1) / m, "npc"), height=unit(1.0 / m, "npc"), just="bottom", xscale=(r_lo, r_hi)))
|
|
1673
|
+
try:
|
|
1674
|
+
xv = float(vals[orig_i])
|
|
1675
|
+
lb = lb_list[orig_i]
|
|
1676
|
+
bgp_i = subset_gp(env["bg_gp"], orig_i)
|
|
1677
|
+
lgp_i = subset_gp(env["labels_gp"], orig_i)
|
|
1678
|
+
if align_to == "right":
|
|
1679
|
+
w_bar = unit(xv - r_lo, "native")
|
|
1680
|
+
if round_corners:
|
|
1681
|
+
grid_roundrect(x=unit(1, "npc"), width=w_bar, height=bw_u, r=r_u, just="right", gp=bgp_i)
|
|
1682
|
+
else:
|
|
1683
|
+
grid_rect(x=unit(1, "npc"), width=w_bar, height=bw_u, just="right", gp=bgp_i)
|
|
1684
|
+
grid_text(lb, x=unit(1, "npc") - off_u, just="right", gp=lgp_i)
|
|
1685
|
+
elif align_to == "left":
|
|
1686
|
+
w_bar = unit(xv - r_lo, "native")
|
|
1687
|
+
if round_corners:
|
|
1688
|
+
grid_roundrect(x=unit(0, "npc"), width=w_bar, height=bw_u, r=r_u, just="left", gp=bgp_i)
|
|
1689
|
+
else:
|
|
1690
|
+
grid_rect(x=unit(0, "npc"), width=w_bar, height=bw_u, just="left", gp=bgp_i)
|
|
1691
|
+
grid_text(lb, x=unit(0, "npc") + off_u, just="left", gp=lgp_i)
|
|
1692
|
+
else: # diverging around 0
|
|
1693
|
+
if xv >= 0:
|
|
1694
|
+
if round_corners:
|
|
1695
|
+
grid_roundrect(x=unit(0.0, "native"), width=unit(xv, "native"), height=bw_u, r=r_u, just="left", gp=bgp_i)
|
|
1696
|
+
else:
|
|
1697
|
+
grid_rect(x=unit(0.0, "native"), width=unit(xv, "native"), height=bw_u, just="left", gp=bgp_i)
|
|
1698
|
+
grid_text(lb, x=unit(0.0, "native") + off_u, just="left", gp=lgp_i)
|
|
1699
|
+
else:
|
|
1700
|
+
if round_corners:
|
|
1701
|
+
grid_roundrect(x=unit(0.0, "native"), width=unit(abs(xv), "native"), height=bw_u, r=r_u, just="right", gp=bgp_i)
|
|
1702
|
+
else:
|
|
1703
|
+
grid_rect(x=unit(0.0, "native"), width=unit(abs(xv), "native"), height=bw_u, just="right", gp=bgp_i)
|
|
1704
|
+
grid_text(lb, x=unit(0.0, "native") - off_u, just="right", gp=lgp_i)
|
|
1705
|
+
finally:
|
|
1706
|
+
popViewport()
|
|
1707
|
+
|
|
1708
|
+
return AnnotationFunction(
|
|
1709
|
+
fun=_draw,
|
|
1710
|
+
fun_name="anno_numeric",
|
|
1711
|
+
which="row",
|
|
1712
|
+
width=w_u,
|
|
1713
|
+
height=unit(1.0, "npc"),
|
|
1714
|
+
n=n,
|
|
1715
|
+
var_import={"value": arr, "labels": lbls, "bg_gp": bgp_rec, "labels_gp": lgp_rec},
|
|
1716
|
+
subset_rule={"value": subset_vector, "labels": subset_vector, "bg_gp": subset_gp, "labels_gp": subset_gp},
|
|
1717
|
+
subsettable=True,
|
|
1718
|
+
show_name=False,
|
|
1719
|
+
_which_explicit=True,
|
|
1720
|
+
)
|
|
1721
|
+
|
|
1722
|
+
|
|
1723
|
+
# ---- 13. anno_mark ----
|
|
1724
|
+
|
|
1725
|
+
def anno_mark(
|
|
1726
|
+
at: Sequence[int] | Sequence[bool],
|
|
1727
|
+
labels: Sequence[str],
|
|
1728
|
+
which: str | None = None,
|
|
1729
|
+
side: str | None = None,
|
|
1730
|
+
lines_gp: dict[str, Any] | None = None,
|
|
1731
|
+
labels_gp: dict[str, Any] | None = None,
|
|
1732
|
+
labels_rot: float | None = None,
|
|
1733
|
+
padding: Any = unit(1, "mm"),
|
|
1734
|
+
link_width: Any = unit(5, "mm"),
|
|
1735
|
+
link_height: Any = None,
|
|
1736
|
+
link_gp: dict[str, Any] | None = None,
|
|
1737
|
+
extend: Any = unit(0, "mm"),
|
|
1738
|
+
) -> AnnotationFunction:
|
|
1739
|
+
which_explicit = which is not None
|
|
1740
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
1741
|
+
|
|
1742
|
+
at_arr = np.asarray(at)
|
|
1743
|
+
if at_arr.dtype == bool:
|
|
1744
|
+
at_idx = np.where(at_arr)[0].tolist()
|
|
1745
|
+
else:
|
|
1746
|
+
at_idx = [int(v) for v in at_arr]
|
|
1747
|
+
|
|
1748
|
+
n = len(at_idx)
|
|
1749
|
+
if n < 1:
|
|
1750
|
+
return anno_empty(which=eff_which, border=False)
|
|
1751
|
+
|
|
1752
|
+
lbl_list = [str(v) for v in labels]
|
|
1753
|
+
lgp_base = check_gp(link_gp if link_gp is not None else (lines_gp or gpar()))
|
|
1754
|
+
lbl_gp_base = check_gp(labels_gp or gpar())
|
|
1755
|
+
lgp_rec = recycle_gp(lgp_base, n)
|
|
1756
|
+
lbl_gp_rec = recycle_gp(lbl_gp_base, n)
|
|
1757
|
+
|
|
1758
|
+
od = np.argsort(at_idx)
|
|
1759
|
+
at_sorted = [at_idx[i] for i in od]
|
|
1760
|
+
lbl_sorted = [lbl_list[i] for i in od]
|
|
1761
|
+
lgp_sorted = subset_gp(lgp_rec, od)
|
|
1762
|
+
lbl_gp_sorted = subset_gp(lbl_gp_rec, od)
|
|
1763
|
+
at2index = {a: i for i, a in enumerate(at_sorted)}
|
|
1764
|
+
at2label = dict(zip(at_sorted, lbl_sorted))
|
|
1765
|
+
|
|
1766
|
+
lw_u = as_unit(link_width, "mm")
|
|
1767
|
+
lh_u = lw_u if link_height is None else as_unit(link_height, "mm")
|
|
1768
|
+
ext_u = as_unit(extend, "npc")
|
|
1769
|
+
if len(ext_u) == 1:
|
|
1770
|
+
ext_u = unit_c(ext_u, ext_u)
|
|
1771
|
+
else:
|
|
1772
|
+
ext_u = ext_u[:2]
|
|
1773
|
+
pad_u = as_unit(padding, "mm") if isinstance(padding, Unit) else unit(float(padding) * textGrob("a", gp=subset_gp(lbl_gp_sorted, 0)).height_mm(), "mm")
|
|
1774
|
+
|
|
1775
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
1776
|
+
eff_side = ("top" if target_which == "column" else "right") if side is None else side
|
|
1777
|
+
eff_rot = (90.0 if target_which == "column" else 0.0) if labels_rot is None else float(labels_rot) % 360.0
|
|
1778
|
+
|
|
1779
|
+
if target_which == "row":
|
|
1780
|
+
w_u = lw_u + max_text_width(lbl_sorted, gp=lbl_gp_sorted, rot=eff_rot)
|
|
1781
|
+
h_u = unit(1.0, "npc")
|
|
1782
|
+
else:
|
|
1783
|
+
w_u = unit(1.0, "npc")
|
|
1784
|
+
h_u = lh_u + max_text_height(lbl_sorted, gp=lbl_gp_sorted, rot=eff_rot)
|
|
1785
|
+
|
|
1786
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1787
|
+
at_cur = env["at"]
|
|
1788
|
+
idx_list = [int(v) for v in index]
|
|
1789
|
+
m = len(idx_list)
|
|
1790
|
+
present = [a for a in idx_list if a in at2index]
|
|
1791
|
+
if not present:
|
|
1792
|
+
return
|
|
1793
|
+
pos_map_in_index = {a: i for i, a in enumerate(idx_list)}
|
|
1794
|
+
dot_pos = env.get(".pos")
|
|
1795
|
+
dot_scale = env.get(".scale")
|
|
1796
|
+
|
|
1797
|
+
if target_which == "row":
|
|
1798
|
+
# Reverse order so smartAlign runs bottom-to-top
|
|
1799
|
+
sel = sorted(present, key=lambda a: pos_map_in_index[a], reverse=True)
|
|
1800
|
+
sel_lbls = [at2label[a] for a in sel]
|
|
1801
|
+
sel_order = [at2index[a] for a in sel]
|
|
1802
|
+
sel_lbl_gp = subset_gp(lbl_gp_sorted, sel_order)
|
|
1803
|
+
sel_link_gp = subset_gp(lgp_sorted, sel_order)
|
|
1804
|
+
sc = dot_scale if dot_scale is not None else (0.5, m + 0.5)
|
|
1805
|
+
pushViewport(Viewport(xscale=(0.0, 1.0), yscale=sc))
|
|
1806
|
+
try:
|
|
1807
|
+
ext_n = ext_u.to_mm("y", current_viewport()) / max(1e-9, current_viewport().h_mm) * (sc[1] - sc[0]) if ext_u.is_abs() else ext_u._values * (sc[1] - sc[0])
|
|
1808
|
+
if dot_pos is not None:
|
|
1809
|
+
pos = np.array([dot_pos[pos_map_in_index[a]] for a in sel], dtype=float)
|
|
1810
|
+
else:
|
|
1811
|
+
pos = np.array([m - pos_map_in_index[a] for a in sel], dtype=float)
|
|
1812
|
+
pad_mm = convertHeight(pad_u, "mm", valueOnly=True)
|
|
1813
|
+
nat_per_mm = (sc[1] - sc[0]) / max(1e-9, current_viewport().h_mm)
|
|
1814
|
+
th = np.array([
|
|
1815
|
+
(textGrob(lb, gp=subset_gp(sel_lbl_gp, ii)).width_mm() if eff_rot in (90.0, 270.0) else textGrob(lb, gp=subset_gp(sel_lbl_gp, ii)).height_mm() + pad_mm) * nat_per_mm
|
|
1816
|
+
for ii, lb in enumerate(sel_lbls)
|
|
1817
|
+
])
|
|
1818
|
+
aligned = smartAlign(pos - 0.5 * th, pos + 0.5 * th, (sc[0] - ext_n[0], sc[1] + ext_n[1]))
|
|
1819
|
+
h_adj = 0.5 * (aligned[:, 0] + aligned[:, 1])
|
|
1820
|
+
|
|
1821
|
+
if eff_side == "right":
|
|
1822
|
+
just = ("center", "top") if eff_rot == 90 else (("center", "bottom") if eff_rot == 270 else ("left", "center"))
|
|
1823
|
+
for ii in range(len(sel)):
|
|
1824
|
+
grid_text(sel_lbls[ii], x=lw_u, y=unit(h_adj[ii], "native"), just=just, rot=eff_rot, gp=subset_gp(sel_lbl_gp, ii))
|
|
1825
|
+
lw_eff = lw_u - unit(1.0, "mm")
|
|
1826
|
+
grid_segments(unit(np.zeros(len(sel)), "npc"), unit(pos, "native"), lw_eff * (1 / 3), unit(pos, "native"), gp=sel_link_gp)
|
|
1827
|
+
grid_segments(lw_eff * (1 / 3), unit(pos, "native"), lw_eff * (2 / 3), unit(h_adj, "native"), gp=sel_link_gp)
|
|
1828
|
+
grid_segments(lw_eff * (2 / 3), unit(h_adj, "native"), lw_eff, unit(h_adj, "native"), gp=sel_link_gp)
|
|
1829
|
+
else:
|
|
1830
|
+
just = ("center", "bottom") if eff_rot == 90 else (("center", "top") if eff_rot == 270 else ("right", "center"))
|
|
1831
|
+
for ii in range(len(sel)):
|
|
1832
|
+
grid_text(sel_lbls[ii], x=unit(1.0, "npc") - lw_u, y=unit(h_adj[ii], "native"), just=just, rot=eff_rot, gp=subset_gp(sel_lbl_gp, ii))
|
|
1833
|
+
lw_eff = lw_u - unit(1.0, "mm")
|
|
1834
|
+
grid_segments(unit(np.ones(len(sel)), "npc"), unit(pos, "native"), unit(1.0, "npc") - lw_eff * (1 / 3), unit(pos, "native"), gp=sel_link_gp)
|
|
1835
|
+
grid_segments(unit(1.0, "npc") - lw_eff * (1 / 3), unit(pos, "native"), unit(1.0, "npc") - lw_eff * (2 / 3), unit(h_adj, "native"), gp=sel_link_gp)
|
|
1836
|
+
grid_segments(unit(1.0, "npc") - lw_eff * (2 / 3), unit(h_adj, "native"), unit(1.0, "npc") - lw_eff, unit(h_adj, "native"), gp=sel_link_gp)
|
|
1837
|
+
finally:
|
|
1838
|
+
popViewport()
|
|
1839
|
+
else:
|
|
1840
|
+
sel = sorted(present, key=lambda a: pos_map_in_index[a])
|
|
1841
|
+
sel_lbls = [at2label[a] for a in sel]
|
|
1842
|
+
sel_order = [at2index[a] for a in sel]
|
|
1843
|
+
sel_lbl_gp = subset_gp(lbl_gp_sorted, sel_order)
|
|
1844
|
+
sel_link_gp = subset_gp(lgp_sorted, sel_order)
|
|
1845
|
+
sc = dot_scale if dot_scale is not None else (0.5, m + 0.5)
|
|
1846
|
+
pushViewport(Viewport(xscale=sc, yscale=(0.0, 1.0)))
|
|
1847
|
+
try:
|
|
1848
|
+
ext_n = ext_u.to_mm("x", current_viewport()) / max(1e-9, current_viewport().w_mm) * (sc[1] - sc[0]) if ext_u.is_abs() else ext_u._values * (sc[1] - sc[0])
|
|
1849
|
+
if dot_pos is not None:
|
|
1850
|
+
pos = np.array([dot_pos[pos_map_in_index[a]] for a in sel], dtype=float)
|
|
1851
|
+
else:
|
|
1852
|
+
pos = np.array([pos_map_in_index[a] + 1 for a in sel], dtype=float)
|
|
1853
|
+
pad_mm = convertWidth(pad_u, "mm", valueOnly=True)
|
|
1854
|
+
nat_per_mm = (sc[1] - sc[0]) / max(1e-9, current_viewport().w_mm)
|
|
1855
|
+
tw = np.array([
|
|
1856
|
+
(textGrob(lb, gp=subset_gp(sel_lbl_gp, ii)).width_mm() if eff_rot in (0.0, 180.0) else textGrob(lb, gp=subset_gp(sel_lbl_gp, ii)).height_mm() + pad_mm) * nat_per_mm
|
|
1857
|
+
for ii, lb in enumerate(sel_lbls)
|
|
1858
|
+
])
|
|
1859
|
+
aligned = smartAlign(pos - 0.5 * tw, pos + 0.5 * tw, (sc[0] - ext_n[0], sc[1] + ext_n[1]))
|
|
1860
|
+
h_adj = 0.5 * (aligned[:, 0] + aligned[:, 1])
|
|
1861
|
+
|
|
1862
|
+
if eff_side == "top":
|
|
1863
|
+
just = ("center", "bottom") if eff_rot == 0 else ("left", "center")
|
|
1864
|
+
for ii in range(len(sel)):
|
|
1865
|
+
grid_text(sel_lbls[ii], x=unit(h_adj[ii], "native"), y=lh_u, just=just, rot=eff_rot, gp=subset_gp(sel_lbl_gp, ii))
|
|
1866
|
+
lh_eff = lh_u - unit(1.0, "mm")
|
|
1867
|
+
grid_segments(unit(pos, "native"), unit(np.zeros(len(sel)), "npc"), unit(pos, "native"), lh_eff * (1 / 3), gp=sel_link_gp)
|
|
1868
|
+
grid_segments(unit(pos, "native"), lh_eff * (1 / 3), unit(h_adj, "native"), lh_eff * (2 / 3), gp=sel_link_gp)
|
|
1869
|
+
grid_segments(unit(h_adj, "native"), lh_eff * (2 / 3), unit(h_adj, "native"), lh_eff, gp=sel_link_gp)
|
|
1870
|
+
else:
|
|
1871
|
+
just = ("center", "top") if eff_rot == 0 else ("right", "center")
|
|
1872
|
+
for ii in range(len(sel)):
|
|
1873
|
+
grid_text(sel_lbls[ii], x=unit(h_adj[ii], "native"), y=unit(1.0, "npc") - lh_u, just=just, rot=eff_rot, gp=subset_gp(sel_lbl_gp, ii))
|
|
1874
|
+
lh_eff = lh_u - unit(1.0, "mm")
|
|
1875
|
+
grid_segments(unit(pos, "native"), unit(np.ones(len(sel)), "npc"), unit(pos, "native"), unit(1.0, "npc") - lh_eff * (1 / 3), gp=sel_link_gp)
|
|
1876
|
+
grid_segments(unit(pos, "native"), unit(1.0, "npc") - lh_eff * (1 / 3), unit(h_adj, "native"), unit(1.0, "npc") - lh_eff * (2 / 3), gp=sel_link_gp)
|
|
1877
|
+
grid_segments(unit(h_adj, "native"), unit(1.0, "npc") - lh_eff * (2 / 3), unit(h_adj, "native"), unit(1.0, "npc") - lh_eff, gp=sel_link_gp)
|
|
1878
|
+
finally:
|
|
1879
|
+
popViewport()
|
|
1880
|
+
|
|
1881
|
+
anno = AnnotationFunction(
|
|
1882
|
+
fun=_draw,
|
|
1883
|
+
fun_name="anno_mark",
|
|
1884
|
+
which=target_which,
|
|
1885
|
+
width=w_u,
|
|
1886
|
+
height=h_u,
|
|
1887
|
+
n=-1,
|
|
1888
|
+
var_import={"at": at_sorted, ".pos": None, ".scale": None},
|
|
1889
|
+
subset_rule={"at": subset_by_intersect},
|
|
1890
|
+
subsettable=True,
|
|
1891
|
+
show_name=False,
|
|
1892
|
+
_which_explicit=which_explicit,
|
|
1893
|
+
_reorient_fn=_build,
|
|
1894
|
+
)
|
|
1895
|
+
anno._called_args = {
|
|
1896
|
+
"at": at_sorted, "labels": lbl_sorted, "which": target_which, "side": eff_side,
|
|
1897
|
+
"labels_gp": lbl_gp_sorted, "labels_rot": eff_rot, "padding": pad_u,
|
|
1898
|
+
"link_width": lw_u, "link_height": lh_u, "link_gp": lgp_sorted, "extend": ext_u,
|
|
1899
|
+
}
|
|
1900
|
+
return anno
|
|
1901
|
+
|
|
1902
|
+
return _build(eff_which)
|
|
1903
|
+
|
|
1904
|
+
|
|
1905
|
+
# ---- 14 & 15. anno_zoom & anno_link ----
|
|
1906
|
+
|
|
1907
|
+
def _contiguous_runs(positions: list[int]) -> list[tuple[int, int]]:
|
|
1908
|
+
if not positions:
|
|
1909
|
+
return []
|
|
1910
|
+
runs: list[tuple[int, int]] = []
|
|
1911
|
+
s = positions[0]
|
|
1912
|
+
prev = positions[0]
|
|
1913
|
+
for p in positions[1:]:
|
|
1914
|
+
if p == prev + 1:
|
|
1915
|
+
prev = p
|
|
1916
|
+
else:
|
|
1917
|
+
runs.append((s, prev))
|
|
1918
|
+
s = prev = p
|
|
1919
|
+
runs.append((s, prev))
|
|
1920
|
+
return runs
|
|
1921
|
+
|
|
1922
|
+
|
|
1923
|
+
def anno_zoom(
|
|
1924
|
+
align_to: Any,
|
|
1925
|
+
panel_fun: Callable | None = None,
|
|
1926
|
+
which: str | None = None,
|
|
1927
|
+
side: str | None = None,
|
|
1928
|
+
size: Any = None,
|
|
1929
|
+
gap: Any = unit(1, "mm"),
|
|
1930
|
+
link_width: Any = unit(5, "mm"),
|
|
1931
|
+
link_height: Any = None,
|
|
1932
|
+
link_gp: dict[str, Any] | None = None,
|
|
1933
|
+
extend: Any = unit(0, "mm"),
|
|
1934
|
+
width: Unit | None = None,
|
|
1935
|
+
height: Unit | None = None,
|
|
1936
|
+
internal_line: bool = True,
|
|
1937
|
+
) -> AnnotationFunction:
|
|
1938
|
+
which_explicit = which is not None
|
|
1939
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
1940
|
+
|
|
1941
|
+
if panel_fun is None:
|
|
1942
|
+
def panel_fun(index, nm=None):
|
|
1943
|
+
grid_rect()
|
|
1944
|
+
|
|
1945
|
+
import inspect
|
|
1946
|
+
pf_params = len(inspect.signature(panel_fun).parameters)
|
|
1947
|
+
|
|
1948
|
+
lw_u = as_unit(link_width, "mm")
|
|
1949
|
+
lh_u = lw_u if link_height is None else as_unit(link_height, "mm")
|
|
1950
|
+
gap_u = as_unit(gap, "mm")
|
|
1951
|
+
ext_u = as_unit(extend, "npc")
|
|
1952
|
+
if len(ext_u) == 1:
|
|
1953
|
+
ext_u = unit_c(ext_u, ext_u)
|
|
1954
|
+
else:
|
|
1955
|
+
ext_u = ext_u[:2]
|
|
1956
|
+
|
|
1957
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
1958
|
+
eff_side = ("top" if target_which == "column" else "right") if side is None else side
|
|
1959
|
+
default_sz = unit(2.0, "cm") + (lw_u if target_which == "row" else lh_u)
|
|
1960
|
+
sz = anno_width_and_height(target_which, width, height, default_sz)
|
|
1961
|
+
|
|
1962
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
1963
|
+
idx_list = [int(v) for v in index]
|
|
1964
|
+
m = len(idx_list)
|
|
1965
|
+
if m == 0:
|
|
1966
|
+
return
|
|
1967
|
+
aln_raw = env["align_to"]
|
|
1968
|
+
if isinstance(aln_raw, dict):
|
|
1969
|
+
aln_dict = {str(k_nm): [int(v) for v in vs] for k_nm, vs in aln_raw.items()}
|
|
1970
|
+
else:
|
|
1971
|
+
seq = list(aln_raw)
|
|
1972
|
+
if seq and isinstance(seq[0], (list, tuple, np.ndarray, set)):
|
|
1973
|
+
aln_dict = {str(i): [int(v) for v in vs] for i, vs in enumerate(seq)}
|
|
1974
|
+
elif all(isinstance(v, (int, np.integer)) for v in seq) and len(seq) != m:
|
|
1975
|
+
aln_dict = {"": [int(v) for v in seq]}
|
|
1976
|
+
else:
|
|
1977
|
+
# Categorical vector matching m observations
|
|
1978
|
+
if len(seq) != m:
|
|
1979
|
+
raise ValueError("Categorical `align_to` length must equal number of heatmap observations.")
|
|
1980
|
+
# Order groups in appearance order along `index`
|
|
1981
|
+
groups: dict[str, list[int]] = {}
|
|
1982
|
+
for orig_i in idx_list:
|
|
1983
|
+
lbl = str(seq[orig_i])
|
|
1984
|
+
groups.setdefault(lbl, []).append(orig_i)
|
|
1985
|
+
aln_dict = groups
|
|
1986
|
+
|
|
1987
|
+
idx_set = set(idx_list)
|
|
1988
|
+
aln_dict = {nm: [v for v in vs if v in idx_set] for nm, vs in aln_dict.items()}
|
|
1989
|
+
aln_dict = {nm: vs for nm, vs in aln_dict.items() if len(vs) > 0}
|
|
1990
|
+
if not aln_dict:
|
|
1991
|
+
return
|
|
1992
|
+
|
|
1993
|
+
box_names = list(aln_dict.keys())
|
|
1994
|
+
box_lists = list(aln_dict.values())
|
|
1995
|
+
n_boxes = len(box_lists)
|
|
1996
|
+
pos_in_idx = {orig: p for p, orig in enumerate(idx_list)}
|
|
1997
|
+
runs_per_box = [_contiguous_runs(sorted(pos_in_idx[v] for v in vs)) for vs in box_lists]
|
|
1998
|
+
|
|
1999
|
+
dot_pos = env.get(".pos")
|
|
2000
|
+
if target_which == "row":
|
|
2001
|
+
pos = np.asarray(dot_pos, dtype=float) if dot_pos is not None else (m - np.arange(m, dtype=float) - 0.5) / m
|
|
2002
|
+
half_cell = 0.5 / m if dot_pos is None else max(1e-4, 0.5 * abs(pos[0] - pos[-1]) / max(1, m - 1))
|
|
2003
|
+
sc = (0.0, 1.0)
|
|
2004
|
+
pushViewport(Viewport(xscale=(0.0, 1.0), yscale=sc))
|
|
2005
|
+
try:
|
|
2006
|
+
ext_n = ext_u.to_mm("y", current_viewport()) / max(1e-9, current_viewport().h_mm) if ext_u.is_abs() else ext_u._values
|
|
2007
|
+
gap_n = convertHeight(gap_u, "mm", valueOnly=True) / max(1e-9, current_viewport().h_mm)
|
|
2008
|
+
if size is None:
|
|
2009
|
+
sz_arg = [len(vs) for vs in box_lists]
|
|
2010
|
+
is_sz_unit = False
|
|
2011
|
+
elif isinstance(size, Unit):
|
|
2012
|
+
sz_arg = size
|
|
2013
|
+
is_sz_unit = True
|
|
2014
|
+
else:
|
|
2015
|
+
sz_arg = [float(size)] * n_boxes if np.ndim(size) == 0 else [float(v) for v in size]
|
|
2016
|
+
is_sz_unit = False
|
|
2017
|
+
|
|
2018
|
+
if not is_sz_unit:
|
|
2019
|
+
if n_boxes == 1:
|
|
2020
|
+
tops = np.array([1.0 + ext_n[1]])
|
|
2021
|
+
bots = np.array([0.0 - ext_n[0]])
|
|
2022
|
+
else:
|
|
2023
|
+
sz_arr = np.asarray(sz_arg, dtype=float)
|
|
2024
|
+
bh = sz_arr / np.sum(sz_arr) * (1.0 + np.sum(ext_n) - gap_n * (n_boxes - 1))
|
|
2025
|
+
tops_rev = np.cumsum(bh) + np.arange(n_boxes) * gap_n - ext_n[0]
|
|
2026
|
+
bots_rev = tops_rev - bh
|
|
2027
|
+
tops = 1.0 - bots_rev
|
|
2028
|
+
bots = 1.0 - tops_rev
|
|
2029
|
+
else:
|
|
2030
|
+
bh_mm = sz_arg.to_mm("y", current_viewport())
|
|
2031
|
+
if len(bh_mm) == 1:
|
|
2032
|
+
bh_mm = np.repeat(bh_mm[0], n_boxes)
|
|
2033
|
+
bh_n = bh_mm / max(1e-9, current_viewport().h_mm)
|
|
2034
|
+
bh2 = bh_n + gap_n
|
|
2035
|
+
if n_boxes > 1:
|
|
2036
|
+
bh2[0] -= 0.5 * gap_n
|
|
2037
|
+
bh2[-1] -= 0.5 * gap_n
|
|
2038
|
+
else:
|
|
2039
|
+
bh2[0] -= gap_n
|
|
2040
|
+
means = np.array([np.mean([0.5 * (pos[s] + pos[e]) for s, e in runs]) for runs in runs_per_box])
|
|
2041
|
+
aligned = smartAlign2((means - 0.5 * bh2)[::-1], (means + 0.5 * bh2)[::-1], (0.0 - ext_n[0], 1.0 + ext_n[1]))
|
|
2042
|
+
aligned = aligned[::-1]
|
|
2043
|
+
bots = aligned[:, 0].copy()
|
|
2044
|
+
tops = aligned[:, 1].copy()
|
|
2045
|
+
if n_boxes > 1:
|
|
2046
|
+
bots[0] += 0.5 * gap_n
|
|
2047
|
+
tops[-1] -= 0.5 * gap_n
|
|
2048
|
+
for bi in range(1, n_boxes - 1):
|
|
2049
|
+
bots[bi] += 0.5 * gap_n
|
|
2050
|
+
tops[bi] -= 0.5 * gap_n
|
|
2051
|
+
finally:
|
|
2052
|
+
popViewport()
|
|
2053
|
+
|
|
2054
|
+
# Draw boxes
|
|
2055
|
+
box_x = lw_u if eff_side == "right" else unit(0.0, "npc")
|
|
2056
|
+
pushViewport(Viewport(x=box_x, just="left", width=sz["width"] - lw_u))
|
|
2057
|
+
try:
|
|
2058
|
+
for bi in range(n_boxes):
|
|
2059
|
+
pushViewport(Viewport(y=unit(0.5 * (tops[bi] + bots[bi]), "native"), height=unit(max(1e-6, tops[bi] - bots[bi]), "native")))
|
|
2060
|
+
try:
|
|
2061
|
+
if pf_params <= 1:
|
|
2062
|
+
panel_fun(box_lists[bi])
|
|
2063
|
+
else:
|
|
2064
|
+
panel_fun(box_lists[bi], box_names[bi])
|
|
2065
|
+
finally:
|
|
2066
|
+
popViewport()
|
|
2067
|
+
finally:
|
|
2068
|
+
popViewport()
|
|
2069
|
+
|
|
2070
|
+
# Draw ribbons
|
|
2071
|
+
lgp = check_gp(link_gp or gpar())
|
|
2072
|
+
if "fill" not in lgp:
|
|
2073
|
+
lgp["fill"] = "transparent"
|
|
2074
|
+
lgp_rec = recycle_gp(lgp, n_boxes)
|
|
2075
|
+
lx = unit(0.0, "npc") if eff_side == "right" else unit(1.0, "npc")
|
|
2076
|
+
ljust = "left" if eff_side == "right" else "right"
|
|
2077
|
+
pushViewport(Viewport(x=lx, just=ljust, width=lw_u))
|
|
2078
|
+
try:
|
|
2079
|
+
for bi in range(n_boxes):
|
|
2080
|
+
gp_i = subset_gp(lgp_rec, bi)
|
|
2081
|
+
for s_pos, e_pos in runs_per_box[bi]:
|
|
2082
|
+
y_hi = pos[s_pos] + half_cell
|
|
2083
|
+
y_lo = pos[e_pos] - half_cell
|
|
2084
|
+
xs_poly = unit_c(unit([0, 0], "npc"), lw_u, lw_u) if eff_side == "right" else unit_c(lw_u, lw_u, unit([0, 0], "npc"))
|
|
2085
|
+
ys_poly = unit([y_lo, y_hi, tops[bi], bots[bi]], "native")
|
|
2086
|
+
if not internal_line:
|
|
2087
|
+
gp_poly = gp_i.copy()
|
|
2088
|
+
gp_poly["col"] = gp_i.get("fill", "transparent")
|
|
2089
|
+
gp_poly.pop("lty", None)
|
|
2090
|
+
grid_polygon(xs_poly, ys_poly, gp=gp_poly)
|
|
2091
|
+
gp_line = gp_i.copy()
|
|
2092
|
+
gp_line["fill"] = "transparent"
|
|
2093
|
+
xs_ln = unit_c(lw_u, unit([0, 0], "npc"), lw_u) if eff_side == "right" else unit_c(unit(0, "npc"), lw_u, lw_u, unit(0, "npc"))
|
|
2094
|
+
grid_lines(xs_ln, unit([bots[bi], y_lo, y_hi, tops[bi]], "native"), gp=gp_line)
|
|
2095
|
+
else:
|
|
2096
|
+
grid_polygon(xs_poly, ys_poly, gp=gp_i)
|
|
2097
|
+
finally:
|
|
2098
|
+
popViewport()
|
|
2099
|
+
else:
|
|
2100
|
+
pos = np.asarray(dot_pos, dtype=float) if dot_pos is not None else (np.arange(m, dtype=float) + 0.5) / m
|
|
2101
|
+
half_cell = 0.5 / m if dot_pos is None else max(1e-4, 0.5 * abs(pos[-1] - pos[0]) / max(1, m - 1))
|
|
2102
|
+
sc = (0.0, 1.0)
|
|
2103
|
+
pushViewport(Viewport(xscale=sc, yscale=(0.0, 1.0)))
|
|
2104
|
+
try:
|
|
2105
|
+
ext_n = ext_u.to_mm("x", current_viewport()) / max(1e-9, current_viewport().w_mm) if ext_u.is_abs() else ext_u._values
|
|
2106
|
+
gap_n = convertWidth(gap_u, "mm", valueOnly=True) / max(1e-9, current_viewport().w_mm)
|
|
2107
|
+
if size is None:
|
|
2108
|
+
sz_arg = [len(vs) for vs in box_lists]
|
|
2109
|
+
is_sz_unit = False
|
|
2110
|
+
elif isinstance(size, Unit):
|
|
2111
|
+
sz_arg = size
|
|
2112
|
+
is_sz_unit = True
|
|
2113
|
+
else:
|
|
2114
|
+
sz_arg = [float(size)] * n_boxes if np.ndim(size) == 0 else [float(v) for v in size]
|
|
2115
|
+
is_sz_unit = False
|
|
2116
|
+
|
|
2117
|
+
if not is_sz_unit:
|
|
2118
|
+
if n_boxes == 1:
|
|
2119
|
+
lefts = np.array([0.0 - ext_n[0]])
|
|
2120
|
+
rights = np.array([1.0 + ext_n[1]])
|
|
2121
|
+
else:
|
|
2122
|
+
sz_arr = np.asarray(sz_arg, dtype=float)
|
|
2123
|
+
bw = sz_arr / np.sum(sz_arr) * (1.0 + np.sum(ext_n) - gap_n * (n_boxes - 1))
|
|
2124
|
+
rights = np.cumsum(bw) + np.arange(n_boxes) * gap_n - ext_n[0]
|
|
2125
|
+
lefts = rights - bw
|
|
2126
|
+
else:
|
|
2127
|
+
bw_mm = sz_arg.to_mm("x", current_viewport())
|
|
2128
|
+
if len(bw_mm) == 1:
|
|
2129
|
+
bw_mm = np.repeat(bw_mm[0], n_boxes)
|
|
2130
|
+
bw_n = bw_mm / max(1e-9, current_viewport().w_mm)
|
|
2131
|
+
bw2 = bw_n + gap_n
|
|
2132
|
+
if n_boxes > 1:
|
|
2133
|
+
bw2[0] -= 0.5 * gap_n
|
|
2134
|
+
bw2[-1] -= 0.5 * gap_n
|
|
2135
|
+
else:
|
|
2136
|
+
bw2[0] -= gap_n
|
|
2137
|
+
means = np.array([np.mean([0.5 * (pos[s] + pos[e]) for s, e in runs]) for runs in runs_per_box])
|
|
2138
|
+
aligned = smartAlign2(means - 0.5 * bw2, means + 0.5 * bw2, (0.0 - ext_n[0], 1.0 + ext_n[1]))
|
|
2139
|
+
lefts = aligned[:, 0].copy()
|
|
2140
|
+
rights = aligned[:, 1].copy()
|
|
2141
|
+
if n_boxes > 1:
|
|
2142
|
+
lefts[0] += 0.5 * gap_n
|
|
2143
|
+
rights[-1] -= 0.5 * gap_n
|
|
2144
|
+
for bi in range(1, n_boxes - 1):
|
|
2145
|
+
lefts[bi] += 0.5 * gap_n
|
|
2146
|
+
rights[bi] -= 0.5 * gap_n
|
|
2147
|
+
finally:
|
|
2148
|
+
popViewport()
|
|
2149
|
+
|
|
2150
|
+
box_y = lh_u if eff_side == "top" else unit(0.0, "npc")
|
|
2151
|
+
pushViewport(Viewport(y=box_y, just="bottom", height=sz["height"] - lh_u))
|
|
2152
|
+
try:
|
|
2153
|
+
for bi in range(n_boxes):
|
|
2154
|
+
pushViewport(Viewport(x=unit(0.5 * (lefts[bi] + rights[bi]), "native"), width=unit(max(1e-6, rights[bi] - lefts[bi]), "native")))
|
|
2155
|
+
try:
|
|
2156
|
+
if pf_params <= 1:
|
|
2157
|
+
panel_fun(box_lists[bi])
|
|
2158
|
+
else:
|
|
2159
|
+
panel_fun(box_lists[bi], box_names[bi])
|
|
2160
|
+
finally:
|
|
2161
|
+
popViewport()
|
|
2162
|
+
finally:
|
|
2163
|
+
popViewport()
|
|
2164
|
+
|
|
2165
|
+
lgp = check_gp(link_gp or gpar())
|
|
2166
|
+
if "fill" not in lgp:
|
|
2167
|
+
lgp["fill"] = "transparent"
|
|
2168
|
+
lgp_rec = recycle_gp(lgp, n_boxes)
|
|
2169
|
+
ly = unit(0.0, "npc") if eff_side == "top" else unit(1.0, "npc")
|
|
2170
|
+
ljust = "bottom" if eff_side == "top" else "top"
|
|
2171
|
+
pushViewport(Viewport(y=ly, just=ljust, height=lh_u))
|
|
2172
|
+
try:
|
|
2173
|
+
for bi in range(n_boxes):
|
|
2174
|
+
gp_i = subset_gp(lgp_rec, bi)
|
|
2175
|
+
for s_pos, e_pos in runs_per_box[bi]:
|
|
2176
|
+
x_lo = pos[s_pos] - half_cell
|
|
2177
|
+
x_hi = pos[e_pos] + half_cell
|
|
2178
|
+
xs_poly = unit([x_hi, x_lo, lefts[bi], rights[bi]], "native")
|
|
2179
|
+
ys_poly = unit_c(unit([0, 0], "npc"), lh_u, lh_u) if eff_side == "top" else unit_c(lh_u, lh_u, unit([0, 0], "npc"))
|
|
2180
|
+
grid_polygon(xs_poly, ys_poly, gp=gp_i)
|
|
2181
|
+
finally:
|
|
2182
|
+
popViewport()
|
|
2183
|
+
|
|
2184
|
+
def _subset_align_to(x_val: Any, idx: Sequence[int]) -> Any:
|
|
2185
|
+
s_idx = set(int(v) for v in idx)
|
|
2186
|
+
if isinstance(x_val, dict):
|
|
2187
|
+
return {k: [v for v in vs if v in s_idx] for k, vs in x_val.items() if any(v in s_idx for v in vs)}
|
|
2188
|
+
return [x_val[i] for i in idx]
|
|
2189
|
+
|
|
2190
|
+
return AnnotationFunction(
|
|
2191
|
+
fun=_draw,
|
|
2192
|
+
fun_name="anno_zoom",
|
|
2193
|
+
which=target_which,
|
|
2194
|
+
width=sz["width"],
|
|
2195
|
+
height=sz["height"],
|
|
2196
|
+
n=-1,
|
|
2197
|
+
var_import={"align_to": align_to, ".pos": None},
|
|
2198
|
+
subset_rule={"align_to": _subset_align_to},
|
|
2199
|
+
subsettable=True,
|
|
2200
|
+
show_name=False,
|
|
2201
|
+
_which_explicit=which_explicit,
|
|
2202
|
+
_reorient_fn=_build,
|
|
2203
|
+
)
|
|
2204
|
+
|
|
2205
|
+
return _build(eff_which)
|
|
2206
|
+
|
|
2207
|
+
|
|
2208
|
+
def anno_link(*args: Any, **kwargs: Any) -> AnnotationFunction:
|
|
2209
|
+
"""Alias for `anno_zoom`."""
|
|
2210
|
+
return anno_zoom(*args, **kwargs)
|
|
2211
|
+
|
|
2212
|
+
|
|
2213
|
+
# ---- 16. anno_block ----
|
|
2214
|
+
|
|
2215
|
+
def anno_block(
|
|
2216
|
+
align_to: Any = None,
|
|
2217
|
+
gp: dict[str, Any] | None = None,
|
|
2218
|
+
labels: Sequence[str] | None = None,
|
|
2219
|
+
labels_gp: dict[str, Any] | None = None,
|
|
2220
|
+
labels_rot: float | None = None,
|
|
2221
|
+
labels_offset: Any = unit(0.5, "npc"),
|
|
2222
|
+
labels_just: Any = "center",
|
|
2223
|
+
which: str | None = None,
|
|
2224
|
+
width: Unit | None = None,
|
|
2225
|
+
height: Unit | None = None,
|
|
2226
|
+
show_name: bool = False,
|
|
2227
|
+
panel_fun: Callable | None = None,
|
|
2228
|
+
) -> AnnotationFunction:
|
|
2229
|
+
which_explicit = which is not None
|
|
2230
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
2231
|
+
|
|
2232
|
+
if align_to is not None:
|
|
2233
|
+
if isinstance(align_to, (list, tuple, np.ndarray)) and align_to and isinstance(align_to[0], (int, np.integer)):
|
|
2234
|
+
align_to = {"v": [int(v) for v in align_to]}
|
|
2235
|
+
elif not isinstance(align_to, dict):
|
|
2236
|
+
raise ValueError("`align_to` must be a dict mapping names to index lists, or a list of indices.")
|
|
2237
|
+
|
|
2238
|
+
gp_d = check_gp(gp)
|
|
2239
|
+
lbl_gp_d = check_gp(labels_gp)
|
|
2240
|
+
off_u = as_unit(labels_offset, "npc")
|
|
2241
|
+
|
|
2242
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
2243
|
+
eff_rot = (90.0 if target_which == "row" else 0.0) if labels_rot is None else float(labels_rot)
|
|
2244
|
+
w_u, h_u = width, height
|
|
2245
|
+
if labels is not None:
|
|
2246
|
+
if target_which == "column" and h_u is None:
|
|
2247
|
+
h_u = max_text_height(labels, gp=lbl_gp_d, rot=eff_rot) + unit(5.0, "mm")
|
|
2248
|
+
elif target_which == "row" and w_u is None:
|
|
2249
|
+
w_u = max_text_width(labels, gp=lbl_gp_d, rot=eff_rot) + unit(5.0, "mm")
|
|
2250
|
+
sz = anno_width_and_height(target_which, w_u, h_u, unit(5.0, "mm"))
|
|
2251
|
+
|
|
2252
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
2253
|
+
idx_list = [int(v) for v in index]
|
|
2254
|
+
ni = len(idx_list)
|
|
2255
|
+
if align_to is not None:
|
|
2256
|
+
for nm, grp in align_to.items():
|
|
2257
|
+
positions = [pos for pos, orig in enumerate(idx_list) if orig in grp]
|
|
2258
|
+
if not positions:
|
|
2259
|
+
continue
|
|
2260
|
+
if any(positions[i + 1] - positions[i] > 1 for i in range(len(positions) - 1)):
|
|
2261
|
+
raise ValueError("Indices in `align_to` must be continuously adjacent in the heatmap.")
|
|
2262
|
+
if target_which == "row":
|
|
2263
|
+
pushViewport(Viewport(y=unit((ni - positions[-1] - 1) / ni, "npc"), height=unit(len(positions) / ni, "npc"), just="bottom"))
|
|
2264
|
+
else:
|
|
2265
|
+
pushViewport(Viewport(x=unit((positions[-1] + 1) / ni, "npc"), width=unit(len(positions) / ni, "npc"), just="right"))
|
|
2266
|
+
try:
|
|
2267
|
+
if panel_fun is not None:
|
|
2268
|
+
panel_fun([idx_list[p] for p in positions], nm)
|
|
2269
|
+
finally:
|
|
2270
|
+
popViewport()
|
|
2271
|
+
elif panel_fun is None:
|
|
2272
|
+
grid_rect(gp=subset_gp(recycle_gp(gp_d, n_slices), k - 1))
|
|
2273
|
+
if labels is not None:
|
|
2274
|
+
if len(labels) != n_slices:
|
|
2275
|
+
raise ValueError(f"Length of `labels` ({len(labels)}) must equal number of slices ({n_slices}).")
|
|
2276
|
+
lbl = labels[k - 1]
|
|
2277
|
+
lgp = subset_gp(recycle_gp(lbl_gp_d, n_slices), k - 1)
|
|
2278
|
+
tx = off_u if target_which == "row" else unit(0.5, "npc")
|
|
2279
|
+
ty = off_u if target_which == "column" else unit(0.5, "npc")
|
|
2280
|
+
grid_text(lbl, x=tx, y=ty, gp=lgp, rot=eff_rot, just=labels_just)
|
|
2281
|
+
else:
|
|
2282
|
+
ht = _ENV.current_heatmap
|
|
2283
|
+
levels = None
|
|
2284
|
+
if ht is not None:
|
|
2285
|
+
sp = ht._row_split_df if target_which == "row" else ht._column_split_df
|
|
2286
|
+
ol = ht.row_order_list if target_which == "row" else ht.column_order_list
|
|
2287
|
+
if sp is not None and k - 1 < len(ol):
|
|
2288
|
+
row_i = ol[k - 1][0]
|
|
2289
|
+
levels = [str(v) for v in sp.iloc[row_i].tolist()]
|
|
2290
|
+
panel_fun(idx_list, levels)
|
|
2291
|
+
|
|
2292
|
+
return AnnotationFunction(
|
|
2293
|
+
fun=_draw,
|
|
2294
|
+
fun_name="anno_block",
|
|
2295
|
+
which=target_which,
|
|
2296
|
+
width=sz["width"],
|
|
2297
|
+
height=sz["height"],
|
|
2298
|
+
n=None,
|
|
2299
|
+
var_import={},
|
|
2300
|
+
subset_rule={},
|
|
2301
|
+
subsettable=True,
|
|
2302
|
+
show_name=show_name,
|
|
2303
|
+
_which_explicit=which_explicit,
|
|
2304
|
+
_reorient_fn=_build,
|
|
2305
|
+
)
|
|
2306
|
+
|
|
2307
|
+
return _build(eff_which)
|
|
2308
|
+
|
|
2309
|
+
|
|
2310
|
+
# ---- 17. anno_summary ----
|
|
2311
|
+
|
|
2312
|
+
def anno_summary(
|
|
2313
|
+
which: str | None = None,
|
|
2314
|
+
border: bool = True,
|
|
2315
|
+
bar_width: float = 0.8,
|
|
2316
|
+
axis: bool = True,
|
|
2317
|
+
axis_param: dict[str, Any] | None = None,
|
|
2318
|
+
ylim: Sequence[float] | None = None,
|
|
2319
|
+
extend: float = 0.05,
|
|
2320
|
+
outline: bool = True,
|
|
2321
|
+
box_width: float = 0.6,
|
|
2322
|
+
pch: Any = 1,
|
|
2323
|
+
size: Any = unit(2, "mm"),
|
|
2324
|
+
gp: dict[str, Any] | None = None,
|
|
2325
|
+
width: Unit | None = None,
|
|
2326
|
+
height: Unit | None = None,
|
|
2327
|
+
) -> AnnotationFunction:
|
|
2328
|
+
which_explicit = which is not None
|
|
2329
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
2330
|
+
gp_d = check_gp(gp)
|
|
2331
|
+
sz_u = as_unit(size, "mm")
|
|
2332
|
+
|
|
2333
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
2334
|
+
sz = anno_width_and_height(target_which, width, height, unit(2.0, "cm"))
|
|
2335
|
+
ap = validate_axis_param(axis_param, target_which)
|
|
2336
|
+
|
|
2337
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
2338
|
+
ht = _ENV.current_heatmap
|
|
2339
|
+
if ht is None:
|
|
2340
|
+
return
|
|
2341
|
+
mat = ht._matrix
|
|
2342
|
+
cm = ht._matrix_color_mapping
|
|
2343
|
+
order_list = ht.row_order_list if target_which == "column" else ht.column_order_list
|
|
2344
|
+
ng = len(order_list)
|
|
2345
|
+
if cm.type == "discrete":
|
|
2346
|
+
if ylim is not None:
|
|
2347
|
+
raise ValueError("`ylim` cannot be set for discrete matrix in `anno_summary`.")
|
|
2348
|
+
ax_grob = construct_axis_grob(ap, target_which, (0.0, 1.0)) if axis else None
|
|
2349
|
+
if target_which == "column":
|
|
2350
|
+
pushViewport(Viewport(xscale=(0.5, ng + 0.5), yscale=(0.0, 1.0)))
|
|
2351
|
+
else:
|
|
2352
|
+
pushViewport(Viewport(xscale=(0.0, 1.0), yscale=(0.5, ng + 0.5)))
|
|
2353
|
+
try:
|
|
2354
|
+
for gi, od in enumerate(order_list):
|
|
2355
|
+
vals = mat[od, 0] if target_which == "column" else mat[0, od]
|
|
2356
|
+
uniq, cnts = np.unique([str(v) for v in vals], return_counts=True)
|
|
2357
|
+
props = cnts / np.sum(cnts)
|
|
2358
|
+
cum = np.cumsum(props)
|
|
2359
|
+
cols = [cm.map_to_colors(u) for u in uniq]
|
|
2360
|
+
if target_which == "column":
|
|
2361
|
+
grid_rect(x=np.full(len(uniq), gi + 1.0), y=cum, width=np.full(len(uniq), bar_width), height=props, just="top", gp=gpar(fill=cols), default_units="native")
|
|
2362
|
+
else:
|
|
2363
|
+
grid_rect(x=cum, y=np.full(len(uniq), ng - gi), width=props, height=np.full(len(uniq), bar_width), just="right", gp=gpar(fill=cols), default_units="native")
|
|
2364
|
+
if axis and ax_grob is not None:
|
|
2365
|
+
grid_draw(ax_grob)
|
|
2366
|
+
if border:
|
|
2367
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
2368
|
+
finally:
|
|
2369
|
+
popViewport()
|
|
2370
|
+
else:
|
|
2371
|
+
vl = [mat[od, 0].astype(float) if target_which == "column" else mat[0, od].astype(float) for od in order_list]
|
|
2372
|
+
if ylim is None:
|
|
2373
|
+
all_v = np.concatenate(vl)
|
|
2374
|
+
lo, hi = float(np.nanmin(all_v)), float(np.nanmax(all_v))
|
|
2375
|
+
else:
|
|
2376
|
+
lo, hi = float(ylim[0]), float(ylim[1])
|
|
2377
|
+
span = max(1e-9, hi - lo)
|
|
2378
|
+
ds = (lo - extend * span, hi + extend * span)
|
|
2379
|
+
ax_grob = construct_axis_grob(ap, target_which, ds) if axis else None
|
|
2380
|
+
gp_rec = recycle_gp(gp_d, ng)
|
|
2381
|
+
if target_which == "column":
|
|
2382
|
+
pushViewport(Viewport(xscale=(0.5, ng + 0.5), yscale=ds))
|
|
2383
|
+
else:
|
|
2384
|
+
pushViewport(Viewport(xscale=ds, yscale=(0.5, ng + 0.5)))
|
|
2385
|
+
try:
|
|
2386
|
+
for gi, v in enumerate(vl):
|
|
2387
|
+
grid_boxplot(
|
|
2388
|
+
v,
|
|
2389
|
+
pos=float(gi + 1) if target_which == "column" else float(ng - gi),
|
|
2390
|
+
box_width=box_width,
|
|
2391
|
+
gp=subset_gp(gp_rec, gi),
|
|
2392
|
+
pch=pch,
|
|
2393
|
+
size=sz_u,
|
|
2394
|
+
outline=outline,
|
|
2395
|
+
direction="vertical" if target_which == "column" else "horizontal",
|
|
2396
|
+
)
|
|
2397
|
+
if axis and ax_grob is not None:
|
|
2398
|
+
grid_draw(ax_grob)
|
|
2399
|
+
if border:
|
|
2400
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
2401
|
+
finally:
|
|
2402
|
+
popViewport()
|
|
2403
|
+
|
|
2404
|
+
ax0 = construct_axis_grob(ap, target_which, ylim or (0.0, 1.0)) if axis else None
|
|
2405
|
+
anno = AnnotationFunction(
|
|
2406
|
+
fun=_draw,
|
|
2407
|
+
fun_name="anno_summary",
|
|
2408
|
+
which=target_which,
|
|
2409
|
+
width=sz["width"],
|
|
2410
|
+
height=sz["height"],
|
|
2411
|
+
n=1,
|
|
2412
|
+
var_import={},
|
|
2413
|
+
subset_rule={},
|
|
2414
|
+
subsettable=False,
|
|
2415
|
+
show_name=False,
|
|
2416
|
+
_which_explicit=which_explicit,
|
|
2417
|
+
_reorient_fn=_build,
|
|
2418
|
+
)
|
|
2419
|
+
anno.extended = update_anno_extend(anno, ax0, ap)
|
|
2420
|
+
return anno
|
|
2421
|
+
|
|
2422
|
+
return _build(eff_which)
|
|
2423
|
+
|
|
2424
|
+
|
|
2425
|
+
# ---- 18. anno_image ----
|
|
2426
|
+
|
|
2427
|
+
def anno_image(
|
|
2428
|
+
image: Sequence[str | None],
|
|
2429
|
+
which: str | None = None,
|
|
2430
|
+
border: bool | str = True,
|
|
2431
|
+
gp: dict[str, Any] | None = None,
|
|
2432
|
+
space: Any = unit(1, "mm"),
|
|
2433
|
+
width: Unit | None = None,
|
|
2434
|
+
height: Unit | None = None,
|
|
2435
|
+
) -> AnnotationFunction:
|
|
2436
|
+
which_explicit = which is not None
|
|
2437
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
2438
|
+
|
|
2439
|
+
paths = [None if p is None or str(p).strip() == "" else str(p) for p in image]
|
|
2440
|
+
n = len(paths)
|
|
2441
|
+
gp_rec = recycle_gp(gp or gpar(fill=None, col=None), n)
|
|
2442
|
+
sp_u = as_unit(space, "mm")
|
|
2443
|
+
|
|
2444
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
2445
|
+
sz = anno_width_and_height(target_which, width, height, unit(1.0, "cm"))
|
|
2446
|
+
|
|
2447
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
2448
|
+
m = len(index)
|
|
2449
|
+
if m == 0:
|
|
2450
|
+
return
|
|
2451
|
+
p_list = env["image"]
|
|
2452
|
+
for pos_i, orig_i in enumerate(index):
|
|
2453
|
+
if target_which == "column":
|
|
2454
|
+
pushViewport(Viewport(x=unit((pos_i + 0.5) / m, "npc"), width=unit(1.0 / m, "npc"), height=unit(1.0, "npc")))
|
|
2455
|
+
else:
|
|
2456
|
+
pushViewport(Viewport(y=unit((m - pos_i - 0.5) / m, "npc"), height=unit(1.0 / m, "npc"), width=unit(1.0, "npc")))
|
|
2457
|
+
try:
|
|
2458
|
+
grid_rect(gp=subset_gp(env["gp"], orig_i))
|
|
2459
|
+
pth = p_list[orig_i]
|
|
2460
|
+
if pth and os.path.exists(pth):
|
|
2461
|
+
im = Image.open(pth).convert("RGBA")
|
|
2462
|
+
arr = np.asarray(im)
|
|
2463
|
+
ih, iw = arr.shape[:2]
|
|
2464
|
+
from .grid import current_viewport
|
|
2465
|
+
cvp = current_viewport()
|
|
2466
|
+
sp_mm = convertWidth(sp_u, "mm", valueOnly=True)
|
|
2467
|
+
avail_w = max(0.5, cvp.w_mm - 2.0 * sp_mm)
|
|
2468
|
+
avail_h = max(0.5, cvp.h_mm - 2.0 * sp_mm)
|
|
2469
|
+
scale = min(avail_w / max(1, iw), avail_h / max(1, ih))
|
|
2470
|
+
grid_raster(arr, width=unit(iw * scale, "mm"), height=unit(ih * scale, "mm"))
|
|
2471
|
+
if border:
|
|
2472
|
+
grid_rect(gp=gpar(fill="transparent", col="black" if border is True else border))
|
|
2473
|
+
finally:
|
|
2474
|
+
popViewport()
|
|
2475
|
+
|
|
2476
|
+
return AnnotationFunction(
|
|
2477
|
+
fun=_draw,
|
|
2478
|
+
fun_name="anno_image",
|
|
2479
|
+
which=target_which,
|
|
2480
|
+
width=sz["width"],
|
|
2481
|
+
height=sz["height"],
|
|
2482
|
+
n=n,
|
|
2483
|
+
var_import={"image": paths, "gp": gp_rec},
|
|
2484
|
+
subset_rule={"image": subset_vector, "gp": subset_gp},
|
|
2485
|
+
subsettable=True,
|
|
2486
|
+
_which_explicit=which_explicit,
|
|
2487
|
+
_reorient_fn=_build,
|
|
2488
|
+
)
|
|
2489
|
+
|
|
2490
|
+
return _build(eff_which)
|
|
2491
|
+
|
|
2492
|
+
|
|
2493
|
+
# ---- 19. anno_customize ----
|
|
2494
|
+
|
|
2495
|
+
def anno_customize(
|
|
2496
|
+
x: Sequence[Any],
|
|
2497
|
+
graphics: dict[str, Callable] | None = None,
|
|
2498
|
+
which: str | None = None,
|
|
2499
|
+
border: bool = True,
|
|
2500
|
+
width: Unit | None = None,
|
|
2501
|
+
height: Unit | None = None,
|
|
2502
|
+
verbose: bool = True,
|
|
2503
|
+
) -> AnnotationFunction:
|
|
2504
|
+
which_explicit = which is not None
|
|
2505
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
2506
|
+
|
|
2507
|
+
vals = [str(v) for v in x]
|
|
2508
|
+
n = len(vals)
|
|
2509
|
+
g_map = dict(graphics or {})
|
|
2510
|
+
|
|
2511
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
2512
|
+
sz = anno_width_and_height(target_which, width, height, unit(5.0, "mm"))
|
|
2513
|
+
|
|
2514
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
2515
|
+
vs = env["value"]
|
|
2516
|
+
m = len(index)
|
|
2517
|
+
if m == 0:
|
|
2518
|
+
return
|
|
2519
|
+
if target_which == "row":
|
|
2520
|
+
pushViewport(Viewport(yscale=(0.5, m + 0.5)))
|
|
2521
|
+
try:
|
|
2522
|
+
for pos_i, orig_i in enumerate(index):
|
|
2523
|
+
fn = g_map.get(vs[orig_i])
|
|
2524
|
+
if fn is not None:
|
|
2525
|
+
pushViewport(Viewport(y=unit(m - pos_i, "native"), height=unit(1.0, "native")))
|
|
2526
|
+
try:
|
|
2527
|
+
fn(unit(0.5, "npc"), unit(0.5, "npc"), unit(1.0, "npc"), unit(1.0, "npc"))
|
|
2528
|
+
finally:
|
|
2529
|
+
popViewport()
|
|
2530
|
+
if border:
|
|
2531
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
2532
|
+
finally:
|
|
2533
|
+
popViewport()
|
|
2534
|
+
else:
|
|
2535
|
+
pushViewport(Viewport(xscale=(0.5, m + 0.5)))
|
|
2536
|
+
try:
|
|
2537
|
+
for pos_i, orig_i in enumerate(index):
|
|
2538
|
+
fn = g_map.get(vs[orig_i])
|
|
2539
|
+
if fn is not None:
|
|
2540
|
+
pushViewport(Viewport(x=unit(pos_i + 1, "native"), width=unit(1.0, "native")))
|
|
2541
|
+
try:
|
|
2542
|
+
fn(unit(0.5, "npc"), unit(0.5, "npc"), unit(1.0, "npc"), unit(1.0, "npc"))
|
|
2543
|
+
finally:
|
|
2544
|
+
popViewport()
|
|
2545
|
+
if border:
|
|
2546
|
+
grid_rect(gp=gpar(fill="transparent", col="black"))
|
|
2547
|
+
finally:
|
|
2548
|
+
popViewport()
|
|
2549
|
+
|
|
2550
|
+
return AnnotationFunction(
|
|
2551
|
+
fun=_draw,
|
|
2552
|
+
fun_name="anno_customize",
|
|
2553
|
+
which=target_which,
|
|
2554
|
+
width=sz["width"],
|
|
2555
|
+
height=sz["height"],
|
|
2556
|
+
n=n,
|
|
2557
|
+
var_import={"value": vals},
|
|
2558
|
+
subset_rule={"value": subset_vector},
|
|
2559
|
+
subsettable=True,
|
|
2560
|
+
_which_explicit=which_explicit,
|
|
2561
|
+
_reorient_fn=_build,
|
|
2562
|
+
)
|
|
2563
|
+
|
|
2564
|
+
return _build(eff_which)
|
|
2565
|
+
|
|
2566
|
+
|
|
2567
|
+
# ---- 20. anno_textbox ----
|
|
2568
|
+
|
|
2569
|
+
def anno_textbox(
|
|
2570
|
+
align_to: Any,
|
|
2571
|
+
text: Any,
|
|
2572
|
+
background_gp: dict[str, Any] | None = None,
|
|
2573
|
+
which: str = "row",
|
|
2574
|
+
by: str = "anno_link",
|
|
2575
|
+
side: str = "right",
|
|
2576
|
+
**textbox_kwargs: Any,
|
|
2577
|
+
) -> AnnotationFunction:
|
|
2578
|
+
which = which.lower()
|
|
2579
|
+
if which == "column":
|
|
2580
|
+
raise ValueError("`anno_textbox()` can only be used as row annotation.")
|
|
2581
|
+
|
|
2582
|
+
bg_gp = gpar(fill="#DDDDDD", col="#AAAAAA", lty=1, lwd=1)
|
|
2583
|
+
if background_gp:
|
|
2584
|
+
bg_gp.update(check_gp(background_gp))
|
|
2585
|
+
|
|
2586
|
+
if isinstance(align_to, (list, tuple, np.ndarray)) and isinstance(text, (list, tuple, pd.DataFrame)) and not isinstance(text, dict):
|
|
2587
|
+
if all(isinstance(v, (int, np.integer)) for v in align_to):
|
|
2588
|
+
aln_dict = {"v": [int(v) for v in align_to]}
|
|
2589
|
+
txt_dict = {"v": text}
|
|
2590
|
+
else:
|
|
2591
|
+
raise ValueError("Invalid `align_to` and `text` combination.")
|
|
2592
|
+
elif isinstance(align_to, dict) and isinstance(text, dict):
|
|
2593
|
+
aln_dict = {str(k): [int(v) for v in vs] for k, vs in align_to.items()}
|
|
2594
|
+
txt_dict = {str(k): text[k] for k in align_to.keys()}
|
|
2595
|
+
elif isinstance(text, dict):
|
|
2596
|
+
# align_to is categorical vector
|
|
2597
|
+
groups: dict[str, list[int]] = {}
|
|
2598
|
+
for idx, cat in enumerate(align_to):
|
|
2599
|
+
groups.setdefault(str(cat), []).append(idx)
|
|
2600
|
+
common = [k for k in groups.keys() if k in text]
|
|
2601
|
+
if not common:
|
|
2602
|
+
raise ValueError("Names of `text` must overlap with levels in `align_to`.")
|
|
2603
|
+
aln_dict = {k: groups[k] for k in common}
|
|
2604
|
+
txt_dict = {k: text[k] for k in common}
|
|
2605
|
+
else:
|
|
2606
|
+
raise ValueError("Format of `align_to` or `text` is invalid.")
|
|
2607
|
+
|
|
2608
|
+
gbl: dict[str, Any] = {}
|
|
2609
|
+
for k, val in txt_dict.items():
|
|
2610
|
+
if isinstance(val, pd.DataFrame):
|
|
2611
|
+
words = val.iloc[:, 0].astype(str).tolist()
|
|
2612
|
+
gp_args: dict[str, Any] = {}
|
|
2613
|
+
for col_nm in ("col", "fontsize", "fontfamily", "fontface"):
|
|
2614
|
+
if col_nm in val.columns:
|
|
2615
|
+
gp_args[col_nm] = val[col_nm].tolist()
|
|
2616
|
+
gbl[k] = textbox_grob(words, gp=gpar(**gp_args), background_gp=gpar(col=None, fill="transparent"), **textbox_kwargs)
|
|
2617
|
+
else:
|
|
2618
|
+
gbl[k] = textbox_grob(list(val), background_gp=gpar(col=None, fill="transparent"), **textbox_kwargs)
|
|
2619
|
+
|
|
2620
|
+
gbl_h = unit([gb.height_mm() for gb in gbl.values()], "mm")
|
|
2621
|
+
gbl_w_max = max((gb.width_mm() for gb in gbl.values()), default=10.0)
|
|
2622
|
+
|
|
2623
|
+
if by in ("anno_link", "anno_zoom"):
|
|
2624
|
+
def _panel(index, nm):
|
|
2625
|
+
pushViewport(Viewport())
|
|
2626
|
+
try:
|
|
2627
|
+
grid_rect(gp=gpar(fill=bg_gp.get("fill", "#DDDDDD"), col=bg_gp.get("fill", "#DDDDDD"), lty=bg_gp.get("lty", 1), lwd=bg_gp.get("lwd", 1)))
|
|
2628
|
+
if side == "right":
|
|
2629
|
+
grid_lines([0, 1, 1, 0], [0, 0, 1, 1], gp=gpar(col=bg_gp.get("col", "#AAAAAA"), lty=bg_gp.get("lty", 1), lwd=bg_gp.get("lwd", 1)), default_units="npc")
|
|
2630
|
+
else:
|
|
2631
|
+
grid_lines([1, 0, 0, 1], [0, 0, 1, 1], gp=gpar(col=bg_gp.get("col", "#AAAAAA"), lty=bg_gp.get("lty", 1), lwd=bg_gp.get("lwd", 1)), default_units="npc")
|
|
2632
|
+
gb = gbl[nm]
|
|
2633
|
+
gb.vp.x = unit(0.5 * gb.width_mm(), "mm")
|
|
2634
|
+
gb.vp.y = unit(0.5 * gb.height_mm(), "mm")
|
|
2635
|
+
gb.draw()
|
|
2636
|
+
finally:
|
|
2637
|
+
popViewport()
|
|
2638
|
+
|
|
2639
|
+
return anno_link(
|
|
2640
|
+
align_to=aln_dict,
|
|
2641
|
+
which="row",
|
|
2642
|
+
panel_fun=_panel,
|
|
2643
|
+
size=gbl_h,
|
|
2644
|
+
gap=unit(2.0, "mm"),
|
|
2645
|
+
width=unit(gbl_w_max + 5.0, "mm"),
|
|
2646
|
+
link_gp=bg_gp,
|
|
2647
|
+
internal_line=False,
|
|
2648
|
+
side=side,
|
|
2649
|
+
)
|
|
2650
|
+
else:
|
|
2651
|
+
def _panel_blk(index, nm):
|
|
2652
|
+
pushViewport(Viewport())
|
|
2653
|
+
try:
|
|
2654
|
+
grid_rect(gp=bg_gp)
|
|
2655
|
+
gb = gbl[nm]
|
|
2656
|
+
gb.vp.x = unit(0.0, "npc")
|
|
2657
|
+
gb.vp.just = (0.0, 0.5)
|
|
2658
|
+
gb.draw()
|
|
2659
|
+
finally:
|
|
2660
|
+
popViewport()
|
|
2661
|
+
|
|
2662
|
+
return anno_block(align_to=aln_dict, which="row", panel_fun=_panel_blk, width=unit(gbl_w_max + 5.0, "mm"))
|
|
2663
|
+
|
|
2664
|
+
|
|
2665
|
+
# ---- 21. anno_oncoprint_barplot ----
|
|
2666
|
+
|
|
2667
|
+
def anno_oncoprint_barplot(
|
|
2668
|
+
type: Sequence[str] | None = None,
|
|
2669
|
+
which: str | None = None,
|
|
2670
|
+
bar_width: float = 0.6,
|
|
2671
|
+
beside: bool = False,
|
|
2672
|
+
ylim: Sequence[float] | None = None,
|
|
2673
|
+
show_fraction: bool = False,
|
|
2674
|
+
axis: bool = True,
|
|
2675
|
+
axis_param: dict[str, Any] | None = None,
|
|
2676
|
+
width: Unit | None = None,
|
|
2677
|
+
height: Unit | None = None,
|
|
2678
|
+
border: bool = False,
|
|
2679
|
+
) -> AnnotationFunction:
|
|
2680
|
+
which_explicit = which is not None
|
|
2681
|
+
eff_which = (which or _ENV.current_annotation_which or "column").lower()
|
|
2682
|
+
|
|
2683
|
+
def _build(target_which: str) -> AnnotationFunction:
|
|
2684
|
+
sz = anno_width_and_height(target_which, width, height, unit(2.0, "cm"))
|
|
2685
|
+
ap_default = default_axis_param("column") if target_which == "column" else validate_axis_param({"side": "top", "labels_rot": 0}, "row")
|
|
2686
|
+
ap = validate_axis_param(axis_param if axis_param is not None else ap_default, target_which)
|
|
2687
|
+
|
|
2688
|
+
def _draw(index, k=1, n_slices=1, env=None):
|
|
2689
|
+
ht = _ENV.current_heatmap
|
|
2690
|
+
if ht is None or not hasattr(ht, "_oncoprint_env") or ht._oncoprint_env is None:
|
|
2691
|
+
return
|
|
2692
|
+
op = ht._oncoprint_env
|
|
2693
|
+
arr = op["arr"] # shape (n_genes, n_samples, n_types)
|
|
2694
|
+
all_type = list(op["all_type"])
|
|
2695
|
+
col_map = op["col"]
|
|
2696
|
+
|
|
2697
|
+
sel_types = list(col_map.keys()) if type is None else list(type)
|
|
2698
|
+
use_types = [t for t in all_type if t in sel_types and t in col_map and col_map[t] is not None]
|
|
2699
|
+
if not use_types:
|
|
2700
|
+
return
|
|
2701
|
+
type_indices = [all_type.index(t) for t in use_types]
|
|
2702
|
+
sub_arr = arr[:, :, type_indices]
|
|
2703
|
+
cols = [col_map[t] for t in use_types]
|
|
2704
|
+
|
|
2705
|
+
if target_which == "column":
|
|
2706
|
+
v = np.sum(sub_arr, axis=0).astype(float) # (n_samples, n_use_types)
|
|
2707
|
+
if show_fraction:
|
|
2708
|
+
v = v / max(1, arr.shape[0])
|
|
2709
|
+
else:
|
|
2710
|
+
v = np.sum(sub_arr, axis=1).astype(float) # (n_genes, n_use_types)
|
|
2711
|
+
if show_fraction:
|
|
2712
|
+
v = v / max(1, arr.shape[1])
|
|
2713
|
+
|
|
2714
|
+
bp = anno_barplot(
|
|
2715
|
+
v,
|
|
2716
|
+
gp=gpar(fill=cols, col=None),
|
|
2717
|
+
which=target_which,
|
|
2718
|
+
ylim=ylim,
|
|
2719
|
+
baseline=0.0,
|
|
2720
|
+
width=sz["width"] if target_which == "row" else None,
|
|
2721
|
+
height=sz["height"] if target_which == "column" else None,
|
|
2722
|
+
border=border,
|
|
2723
|
+
bar_width=bar_width,
|
|
2724
|
+
beside=beside,
|
|
2725
|
+
axis=axis,
|
|
2726
|
+
axis_param=ap,
|
|
2727
|
+
)
|
|
2728
|
+
bp.fun(index, k, n_slices, env=bp.var_env)
|
|
2729
|
+
|
|
2730
|
+
data_scale = (0.0, 1.0 if show_fraction else 10.0)
|
|
2731
|
+
ax_grob = construct_axis_grob(ap, target_which, ylim or data_scale) if axis else None
|
|
2732
|
+
anno = AnnotationFunction(
|
|
2733
|
+
fun=_draw,
|
|
2734
|
+
fun_name="anno_oncoprint_barplot",
|
|
2735
|
+
which=target_which,
|
|
2736
|
+
width=sz["width"],
|
|
2737
|
+
height=sz["height"],
|
|
2738
|
+
n=None,
|
|
2739
|
+
var_import={"border": border, "type": type, "bar_width": bar_width, "beside": beside, "axis": axis, "axis_param": ap, "ylim": ylim, "show_fraction": show_fraction},
|
|
2740
|
+
subset_rule={},
|
|
2741
|
+
subsettable=True,
|
|
2742
|
+
show_name=False,
|
|
2743
|
+
_which_explicit=which_explicit,
|
|
2744
|
+
_reorient_fn=_build,
|
|
2745
|
+
)
|
|
2746
|
+
anno.extended = update_anno_extend(anno, ax_grob, ap)
|
|
2747
|
+
return anno
|
|
2748
|
+
|
|
2749
|
+
return _build(eff_which)
|
|
2750
|
+
|
|
2751
|
+
|
|
2752
|
+
# ---- Row Aliases ----
|
|
2753
|
+
|
|
2754
|
+
def row_anno_points(*args: Any, **kwargs: Any) -> AnnotationFunction:
|
|
2755
|
+
kwargs["which"] = "row"
|
|
2756
|
+
return anno_points(*args, **kwargs)
|
|
2757
|
+
|
|
2758
|
+
|
|
2759
|
+
def row_anno_barplot(*args: Any, **kwargs: Any) -> AnnotationFunction:
|
|
2760
|
+
kwargs["which"] = "row"
|
|
2761
|
+
return anno_barplot(*args, **kwargs)
|
|
2762
|
+
|
|
2763
|
+
|
|
2764
|
+
def row_anno_boxplot(*args: Any, **kwargs: Any) -> AnnotationFunction:
|
|
2765
|
+
kwargs["which"] = "row"
|
|
2766
|
+
return anno_boxplot(*args, **kwargs)
|
|
2767
|
+
|
|
2768
|
+
|
|
2769
|
+
def row_anno_histogram(*args: Any, **kwargs: Any) -> AnnotationFunction:
|
|
2770
|
+
kwargs["which"] = "row"
|
|
2771
|
+
return anno_histogram(*args, **kwargs)
|
|
2772
|
+
|
|
2773
|
+
|
|
2774
|
+
def row_anno_density(*args: Any, **kwargs: Any) -> AnnotationFunction:
|
|
2775
|
+
kwargs["which"] = "row"
|
|
2776
|
+
return anno_density(*args, **kwargs)
|
|
2777
|
+
|
|
2778
|
+
|
|
2779
|
+
def row_anno_text(*args: Any, **kwargs: Any) -> AnnotationFunction:
|
|
2780
|
+
kwargs["which"] = "row"
|
|
2781
|
+
return anno_text(*args, **kwargs)
|