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
complexheatmap/text.py
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
"""Rich text (`gt_render`), multi-phrase `textbox_grob`, and interval alignment (`smartAlign2`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from builtins import range as _range
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any, Sequence
|
|
10
|
+
|
|
11
|
+
import matplotlib.pyplot as plt
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from .colors import add_transparency, rand_color, to_hex_rgba, to_rgba_tuple
|
|
15
|
+
from .grid import (
|
|
16
|
+
GTree,
|
|
17
|
+
Grob,
|
|
18
|
+
RectGrob,
|
|
19
|
+
RoundRectGrob,
|
|
20
|
+
TextGrob,
|
|
21
|
+
Viewport,
|
|
22
|
+
current_device,
|
|
23
|
+
grid_newpage,
|
|
24
|
+
parse_just,
|
|
25
|
+
rectGrob,
|
|
26
|
+
roundrectGrob,
|
|
27
|
+
textGrob,
|
|
28
|
+
)
|
|
29
|
+
from .units import (
|
|
30
|
+
Gpar,
|
|
31
|
+
Unit,
|
|
32
|
+
_MM_PER_BIGPT,
|
|
33
|
+
_text_dims_mm,
|
|
34
|
+
as_unit,
|
|
35
|
+
check_gp,
|
|
36
|
+
convertHeight,
|
|
37
|
+
convertWidth,
|
|
38
|
+
gpar,
|
|
39
|
+
recycle_gp,
|
|
40
|
+
subset_gp,
|
|
41
|
+
unit,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class GridText:
|
|
46
|
+
"""Wrapper marking labels for rich-text (HTML/Markdown) rendering via `gt_render`."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, x: Any, **param: Any) -> None:
|
|
49
|
+
if isinstance(x, str):
|
|
50
|
+
self._items = [x]
|
|
51
|
+
self._scalar = True
|
|
52
|
+
else:
|
|
53
|
+
self._items = [str(v) for v in x]
|
|
54
|
+
self._scalar = False
|
|
55
|
+
self.param = dict(param)
|
|
56
|
+
|
|
57
|
+
def __len__(self) -> int:
|
|
58
|
+
return len(self._items)
|
|
59
|
+
|
|
60
|
+
def __getitem__(self, idx: Any) -> Any:
|
|
61
|
+
if isinstance(idx, (int, np.integer)):
|
|
62
|
+
return GridText([self._items[int(idx)]], **self.param)
|
|
63
|
+
if isinstance(idx, slice):
|
|
64
|
+
return GridText(self._items[idx], **self.param)
|
|
65
|
+
arr = np.asarray(idx)
|
|
66
|
+
if arr.dtype == bool:
|
|
67
|
+
sel = [v for v, f in zip(self._items, arr) if f]
|
|
68
|
+
else:
|
|
69
|
+
sel = [self._items[int(i)] for i in arr]
|
|
70
|
+
return GridText(sel, **self.param)
|
|
71
|
+
|
|
72
|
+
def __iter__(self):
|
|
73
|
+
return iter(self._items)
|
|
74
|
+
|
|
75
|
+
def as_list(self) -> list[str]:
|
|
76
|
+
return list(self._items)
|
|
77
|
+
|
|
78
|
+
def __repr__(self) -> str:
|
|
79
|
+
return f"GridText({self._items!r}, param={self.param!r})"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def gt_render(x: Any, **kwargs: Any) -> GridText:
|
|
83
|
+
"""Mark text string(s) for Markdown/HTML rendering (ComplexHeatmap `gt_render`)."""
|
|
84
|
+
return GridText(x, **kwargs)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class _Run:
|
|
89
|
+
text: str
|
|
90
|
+
bold: bool = False
|
|
91
|
+
italic: bool = False
|
|
92
|
+
color: str | None = None
|
|
93
|
+
fontsize: float | None = None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
_STYLE_RE = re.compile(r"([a-zA-Z\-]+)\s*:\s*([^;]+)")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _parse_richtext_lines(s: str) -> list[list[_Run]]:
|
|
100
|
+
"""Parse simplified HTML/Markdown (`<br>`, `<span style='...'>`, `**bold**`, `*italic*`)."""
|
|
101
|
+
# Normalize <br> tags to newline
|
|
102
|
+
s = re.sub(r"<br\s*/?>", "\n", str(s), flags=re.IGNORECASE)
|
|
103
|
+
raw_lines = s.split("\n")
|
|
104
|
+
parsed_lines: list[list[_Run]] = []
|
|
105
|
+
|
|
106
|
+
token_re = re.compile(
|
|
107
|
+
r"(<span\s+style=['\"][^'\"]*['\"]\s*>|</span>|\*\*[^*]+\*\*|\*[^*]+\*)",
|
|
108
|
+
flags=re.IGNORECASE,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
for ln in raw_lines:
|
|
112
|
+
runs: list[_Run] = []
|
|
113
|
+
style_stack: list[dict[str, Any]] = [{}]
|
|
114
|
+
pos = 0
|
|
115
|
+
for m in token_re.finditer(ln):
|
|
116
|
+
if m.start() > pos:
|
|
117
|
+
chunk = ln[pos:m.start()]
|
|
118
|
+
cur = style_stack[-1]
|
|
119
|
+
runs.append(_Run(chunk, bold=cur.get("bold", False), italic=cur.get("italic", False), color=cur.get("color"), fontsize=cur.get("fontsize")))
|
|
120
|
+
tok = m.group(0)
|
|
121
|
+
low = tok.lower()
|
|
122
|
+
if low.startswith("<span"):
|
|
123
|
+
cur = dict(style_stack[-1])
|
|
124
|
+
sm = re.search(r"style=['\"]([^'\"]*)['\"]", tok, flags=re.IGNORECASE)
|
|
125
|
+
if sm:
|
|
126
|
+
for k, v in _STYLE_RE.findall(sm.group(1)):
|
|
127
|
+
kl = k.strip().lower()
|
|
128
|
+
vl = v.strip()
|
|
129
|
+
if kl == "color":
|
|
130
|
+
cur["color"] = vl
|
|
131
|
+
elif kl == "font-size":
|
|
132
|
+
fs_m = re.match(r"([0-9.]+)\s*(pt|px)?", vl, flags=re.IGNORECASE)
|
|
133
|
+
if fs_m:
|
|
134
|
+
cur["fontsize"] = float(fs_m.group(1))
|
|
135
|
+
elif kl == "font-weight" and "bold" in vl.lower():
|
|
136
|
+
cur["bold"] = True
|
|
137
|
+
style_stack.append(cur)
|
|
138
|
+
elif low == "</span>":
|
|
139
|
+
if len(style_stack) > 1:
|
|
140
|
+
style_stack.pop()
|
|
141
|
+
elif tok.startswith("**") and tok.endswith("**"):
|
|
142
|
+
inner = tok[2:-2]
|
|
143
|
+
cur = style_stack[-1]
|
|
144
|
+
runs.append(_Run(inner, bold=True, italic=cur.get("italic", False), color=cur.get("color"), fontsize=cur.get("fontsize")))
|
|
145
|
+
elif tok.startswith("*") and tok.endswith("*"):
|
|
146
|
+
inner = tok[1:-1]
|
|
147
|
+
cur = style_stack[-1]
|
|
148
|
+
runs.append(_Run(inner, bold=cur.get("bold", False), italic=True, color=cur.get("color"), fontsize=cur.get("fontsize")))
|
|
149
|
+
pos = m.end()
|
|
150
|
+
if pos < len(ln):
|
|
151
|
+
cur = style_stack[-1]
|
|
152
|
+
runs.append(_Run(ln[pos:], bold=cur.get("bold", False), italic=cur.get("italic", False), color=cur.get("color"), fontsize=cur.get("fontsize")))
|
|
153
|
+
if not runs:
|
|
154
|
+
runs.append(_Run(""))
|
|
155
|
+
parsed_lines.append(runs)
|
|
156
|
+
return parsed_lines
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _extract_padding_mm(param: dict[str, Any]) -> tuple[float, float, float, float]:
|
|
160
|
+
pad = param.get("padding")
|
|
161
|
+
if pad is None:
|
|
162
|
+
return (0.0, 0.0, 0.0, 0.0)
|
|
163
|
+
u = as_unit(pad, "pt")
|
|
164
|
+
vals = u.to_mm("x")
|
|
165
|
+
if len(vals) == 1:
|
|
166
|
+
v = float(vals[0])
|
|
167
|
+
return (v, v, v, v)
|
|
168
|
+
if len(vals) == 2:
|
|
169
|
+
return (float(vals[0]), float(vals[1]), float(vals[0]), float(vals[1]))
|
|
170
|
+
# [top, right, bottom, left] in CSS / gridtext order
|
|
171
|
+
return (float(vals[0]), float(vals[1]), float(vals[2]), float(vals[3]))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _richtext_dims_mm(text: Any, gp: dict[str, Any], param: dict[str, Any], rot: float = 0.0) -> tuple[float, float]:
|
|
175
|
+
s = text._items[0] if isinstance(text, GridText) and len(text) else str(text)
|
|
176
|
+
lines = _parse_richtext_lines(s)
|
|
177
|
+
base_fs = float(gp.get("fontsize", 12.0))
|
|
178
|
+
base_face = gp.get("fontface", "plain")
|
|
179
|
+
ff = gp.get("fontfamily", "sans-serif")
|
|
180
|
+
max_w = 0.0
|
|
181
|
+
total_h = 0.0
|
|
182
|
+
for idx, runs in enumerate(lines):
|
|
183
|
+
lw = 0.0
|
|
184
|
+
lh = base_fs * 0.75 * _MM_PER_BIGPT
|
|
185
|
+
for run in runs:
|
|
186
|
+
fs = run.fontsize if run.fontsize is not None else base_fs
|
|
187
|
+
face = "bold.italic" if (run.bold and run.italic) else ("bold" if run.bold else ("italic" if run.italic else base_face))
|
|
188
|
+
rw, rh = _text_dims_mm(run.text, {"fontsize": fs, "fontface": face, "fontfamily": ff}, 0.0)
|
|
189
|
+
lw += rw
|
|
190
|
+
lh = max(lh, rh)
|
|
191
|
+
max_w = max(max_w, lw)
|
|
192
|
+
total_h += lh + (base_fs * 0.25 * _MM_PER_BIGPT if idx > 0 else 0.0)
|
|
193
|
+
pt, pr, pb, pl = _extract_padding_mm(param)
|
|
194
|
+
w_mm = max_w + pl + pr
|
|
195
|
+
h_mm = total_h + pt + pb
|
|
196
|
+
if rot % 360 != 0:
|
|
197
|
+
rad = math.radians(rot)
|
|
198
|
+
c, sn = abs(math.cos(rad)), abs(math.sin(rad))
|
|
199
|
+
return (w_mm * c + h_mm * sn, w_mm * sn + h_mm * c)
|
|
200
|
+
return (w_mm, h_mm)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def draw_richtext(
|
|
204
|
+
dev: Any,
|
|
205
|
+
label: GridText,
|
|
206
|
+
x: Any = None,
|
|
207
|
+
y: Any = None,
|
|
208
|
+
just: Any = "centre",
|
|
209
|
+
rot: float = 0.0,
|
|
210
|
+
gp: dict[str, Any] | None = None,
|
|
211
|
+
default_units: str = "npc",
|
|
212
|
+
) -> None:
|
|
213
|
+
"""Render `GridText` items with optional box background and inline formatting."""
|
|
214
|
+
gp_raw = check_gp(gp)
|
|
215
|
+
box_gp = Gpar()
|
|
216
|
+
clean_gp = Gpar()
|
|
217
|
+
for k, v in gp_raw.items():
|
|
218
|
+
if k.startswith("box_"):
|
|
219
|
+
box_gp[k[4:]] = v
|
|
220
|
+
else:
|
|
221
|
+
clean_gp[k] = v
|
|
222
|
+
|
|
223
|
+
items = label._items
|
|
224
|
+
n = len(items)
|
|
225
|
+
if n == 0:
|
|
226
|
+
return
|
|
227
|
+
vp = dev.current_vp
|
|
228
|
+
ux = unit(0.5, "npc") if x is None else as_unit(x, default_units)
|
|
229
|
+
uy = unit(0.5, "npc") if y is None else as_unit(y, default_units)
|
|
230
|
+
xmm = vp.x0_mm + ux.to_mm("x", vp, pos_mode=True)
|
|
231
|
+
ymm = vp.y0_mm + uy.to_mm("y", vp, pos_mode=True)
|
|
232
|
+
xmm, ymm = np.broadcast_arrays(xmm, ymm, np.zeros(n))[:2]
|
|
233
|
+
jx, jy = parse_just(just)
|
|
234
|
+
gp_n = recycle_gp(clean_gp, n)
|
|
235
|
+
box_gp_n = recycle_gp(box_gp, n) if box_gp else None
|
|
236
|
+
pt, pr, pb, pl = _extract_padding_mm(label.param)
|
|
237
|
+
rad = math.radians(rot)
|
|
238
|
+
cos_r, sin_r = math.cos(rad), math.sin(rad)
|
|
239
|
+
|
|
240
|
+
align_w = 0.0
|
|
241
|
+
if label.param.get("align_widths", False):
|
|
242
|
+
align_w = max(_richtext_dims_mm(it, subset_gp(gp_n, k), label.param, 0.0)[0] for k, it in enumerate(items))
|
|
243
|
+
|
|
244
|
+
cb = dev._clip_bbox(vp)
|
|
245
|
+
for k in range(n):
|
|
246
|
+
gpk = subset_gp(gp_n, k)
|
|
247
|
+
bgpk = subset_gp(box_gp_n, k) if box_gp_n is not None else {}
|
|
248
|
+
lines = _parse_richtext_lines(items[k])
|
|
249
|
+
base_fs = float(gpk.get("fontsize", 12.0))
|
|
250
|
+
base_col = gpk.get("col", "#000000FF")
|
|
251
|
+
base_face = gpk.get("fontface", "plain")
|
|
252
|
+
ff = gpk.get("fontfamily", "sans-serif") or "sans-serif"
|
|
253
|
+
|
|
254
|
+
line_data = []
|
|
255
|
+
content_w = 0.0
|
|
256
|
+
content_h = 0.0
|
|
257
|
+
line_gap = base_fs * 0.25 * _MM_PER_BIGPT
|
|
258
|
+
for li, runs in enumerate(lines):
|
|
259
|
+
lw = 0.0
|
|
260
|
+
lh = base_fs * 0.75 * _MM_PER_BIGPT
|
|
261
|
+
run_metrics = []
|
|
262
|
+
for r in runs:
|
|
263
|
+
fs = r.fontsize if r.fontsize is not None else base_fs
|
|
264
|
+
face = "bold.italic" if (r.bold and r.italic) else ("bold" if r.bold else ("italic" if r.italic else base_face))
|
|
265
|
+
rw, rh = _text_dims_mm(r.text, {"fontsize": fs, "fontface": face, "fontfamily": ff}, 0.0)
|
|
266
|
+
run_metrics.append((r, rw, rh, fs, face))
|
|
267
|
+
lw += rw
|
|
268
|
+
lh = max(lh, rh)
|
|
269
|
+
content_w = max(content_w, lw)
|
|
270
|
+
content_h += lh + (line_gap if li > 0 else 0.0)
|
|
271
|
+
line_data.append((lw, lh, run_metrics))
|
|
272
|
+
|
|
273
|
+
box_w = max(align_w, content_w + pl + pr)
|
|
274
|
+
box_h = content_h + pt + pb
|
|
275
|
+
ax_k, ay_k = float(xmm[k]), float(ymm[k])
|
|
276
|
+
|
|
277
|
+
# Local frame: bottom-left of unrotated box relative to anchor (ax_k, ay_k)
|
|
278
|
+
bx0 = -jx * box_w
|
|
279
|
+
by0 = -jy * box_h
|
|
280
|
+
|
|
281
|
+
def _rot_pt(lx: float, ly: float) -> tuple[float, float]:
|
|
282
|
+
return (ax_k + lx * cos_r - ly * sin_r, ay_k + lx * sin_r + ly * cos_r)
|
|
283
|
+
|
|
284
|
+
if bgpk:
|
|
285
|
+
corners = [_rot_pt(bx0, by0), _rot_pt(bx0 + box_w, by0), _rot_pt(bx0 + box_w, by0 + box_h), _rot_pt(bx0, by0 + box_h)]
|
|
286
|
+
from matplotlib.patches import Polygon as MplPolygon
|
|
287
|
+
fc = to_rgba_tuple(bgpk.get("fill", "#00000000"))
|
|
288
|
+
ec = to_rgba_tuple(bgpk.get("col", "#00000000" if "fill" in bgpk else "#000000FF"))
|
|
289
|
+
lwd = float(bgpk.get("lwd", 1.0)) * 0.75 if ec[3] > 0 else 0.0
|
|
290
|
+
poly = MplPolygon(corners, closed=True, facecolor=fc, edgecolor=ec, linewidth=lwd)
|
|
291
|
+
if cb is not None:
|
|
292
|
+
poly.set_clip_box(cb)
|
|
293
|
+
dev.ax.add_patch(poly)
|
|
294
|
+
|
|
295
|
+
# Draw lines top-to-bottom inside local box
|
|
296
|
+
cur_top = by0 + box_h - pt
|
|
297
|
+
for li, (lw, lh, run_metrics) in enumerate(line_data):
|
|
298
|
+
cur_y = cur_top - lh * 0.5
|
|
299
|
+
cur_x = bx0 + pl
|
|
300
|
+
for r, rw, rh, fs, face in run_metrics:
|
|
301
|
+
if r.text:
|
|
302
|
+
px, py = _rot_pt(cur_x, cur_y)
|
|
303
|
+
weight = "bold" if "bold" in str(face) else "normal"
|
|
304
|
+
style = "italic" if "italic" in str(face) else "normal"
|
|
305
|
+
col = to_rgba_tuple(r.color if r.color else base_col)
|
|
306
|
+
t = dev.ax.text(
|
|
307
|
+
px, py, r.text,
|
|
308
|
+
fontsize=fs, fontfamily=ff, fontweight=weight, fontstyle=style,
|
|
309
|
+
color=col, rotation=float(rot), rotation_mode="anchor",
|
|
310
|
+
ha="left", va="center",
|
|
311
|
+
)
|
|
312
|
+
if cb is not None:
|
|
313
|
+
t.set_clip_box(cb)
|
|
314
|
+
cur_x += rw
|
|
315
|
+
cur_top -= lh + line_gap
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def textbox_grob(
|
|
319
|
+
text: Sequence[str],
|
|
320
|
+
x: Any = None,
|
|
321
|
+
y: Any = None,
|
|
322
|
+
just: Any = "centre",
|
|
323
|
+
gp: dict[str, Any] | None = None,
|
|
324
|
+
background_gp: dict[str, Any] | None = None,
|
|
325
|
+
round_corners: bool = False,
|
|
326
|
+
r: Any = None,
|
|
327
|
+
line_space: Any = None,
|
|
328
|
+
text_space: Any = None,
|
|
329
|
+
max_width: Any = None,
|
|
330
|
+
padding: Any = None,
|
|
331
|
+
first_text_from: str = "top",
|
|
332
|
+
add_new_line: bool = False,
|
|
333
|
+
word_wrap: bool = False,
|
|
334
|
+
) -> GTree:
|
|
335
|
+
"""Create a multi-line packed word-cloud / phrase box grob (`textbox_grob`)."""
|
|
336
|
+
items = [str(t) for t in text]
|
|
337
|
+
n_text = len(items)
|
|
338
|
+
if n_text == 0:
|
|
339
|
+
return GTree(children=[], cl="textbox", width=unit(0.0, "mm"), height=unit(0.0, "mm"))
|
|
340
|
+
|
|
341
|
+
gp_d = check_gp(gp)
|
|
342
|
+
if "col" not in gp_d:
|
|
343
|
+
gp_d["col"] = rand_color(n_text, friendly=True)
|
|
344
|
+
if "fontsize" not in gp_d:
|
|
345
|
+
gp_d["fontsize"] = [12.0] * n_text
|
|
346
|
+
if "fontfamily" not in gp_d:
|
|
347
|
+
gp_d["fontfamily"] = ["sans-serif"] * n_text
|
|
348
|
+
if "fontface" not in gp_d:
|
|
349
|
+
gp_d["fontface"] = ["plain"] * n_text
|
|
350
|
+
gp_d = recycle_gp(gp_d, n_text)
|
|
351
|
+
|
|
352
|
+
bg_gp = gpar(col="black", fill="transparent") if background_gp is None else check_gp(background_gp)
|
|
353
|
+
vp_x = unit(0.5, "npc") if x is None else as_unit(x, "npc")
|
|
354
|
+
vp_y = unit(0.5, "npc") if y is None else as_unit(y, "npc")
|
|
355
|
+
r_u = unit(0.1, "snpc") if r is None else as_unit(r, "snpc")
|
|
356
|
+
ls_mm = 4.0 * _MM_PER_BIGPT if line_space is None else (float(line_space) if not isinstance(line_space, Unit) else convertHeight(line_space, "mm", valueOnly=True))
|
|
357
|
+
ts_mm = 4.0 * _MM_PER_BIGPT if text_space is None else (float(text_space) if not isinstance(text_space, Unit) else convertWidth(text_space, "mm", valueOnly=True))
|
|
358
|
+
mw_mm = 100.0 if max_width is None else (float(max_width) if not isinstance(max_width, Unit) else convertWidth(max_width, "mm", valueOnly=True))
|
|
359
|
+
|
|
360
|
+
if word_wrap:
|
|
361
|
+
if first_text_from == "bottom":
|
|
362
|
+
items = list(reversed(items))
|
|
363
|
+
gp_d = subset_gp(gp_d, list(range(n_text - 1, -1, -1)))
|
|
364
|
+
first_text_from = "top"
|
|
365
|
+
tokens: list[str] = []
|
|
366
|
+
space_after: list[bool] = []
|
|
367
|
+
new_line_after: list[bool] = []
|
|
368
|
+
col_list, fs_list, ff_list, face_list = [], [], [], []
|
|
369
|
+
for idx, phrase in enumerate(items):
|
|
370
|
+
words = phrase.split()
|
|
371
|
+
if not words:
|
|
372
|
+
words = [""]
|
|
373
|
+
w_tokens: list[str] = []
|
|
374
|
+
for wi, wd in enumerate(words):
|
|
375
|
+
if wi > 0:
|
|
376
|
+
w_tokens.append(" ")
|
|
377
|
+
w_tokens.append(wd)
|
|
378
|
+
tokens.extend(w_tokens)
|
|
379
|
+
for wi in range(len(w_tokens)):
|
|
380
|
+
is_last = wi == len(w_tokens) - 1
|
|
381
|
+
space_after.append(is_last)
|
|
382
|
+
new_line_after.append(bool(add_new_line and is_last))
|
|
383
|
+
sub = subset_gp(gp_d, idx)
|
|
384
|
+
for _ in w_tokens:
|
|
385
|
+
col_list.append(sub["col"])
|
|
386
|
+
fs_list.append(sub["fontsize"])
|
|
387
|
+
ff_list.append(sub["fontfamily"])
|
|
388
|
+
face_list.append(sub["fontface"])
|
|
389
|
+
gp_d = gpar(col=col_list, fontsize=fs_list, fontfamily=ff_list, fontface=face_list)
|
|
390
|
+
else:
|
|
391
|
+
tokens = items
|
|
392
|
+
space_after = [True] * n_text
|
|
393
|
+
new_line_after = [bool(add_new_line)] * n_text
|
|
394
|
+
|
|
395
|
+
n = len(tokens)
|
|
396
|
+
t_widths = np.array([textGrob(tokens[i], gp=subset_gp(gp_d, i)).width_mm() for i in range(n)], dtype=float)
|
|
397
|
+
t_heights = np.array([textGrob(tokens[i], gp=subset_gp(gp_d, i)).height_mm() for i in range(n)], dtype=float)
|
|
398
|
+
|
|
399
|
+
mw_mm = max(mw_mm, float(np.max(t_widths)))
|
|
400
|
+
xs = np.zeros(n, dtype=float)
|
|
401
|
+
ys = np.zeros(n, dtype=float)
|
|
402
|
+
w = float(t_widths[0])
|
|
403
|
+
|
|
404
|
+
if first_text_from == "bottom":
|
|
405
|
+
cur_w = float(t_widths[0])
|
|
406
|
+
h = float(t_heights[0])
|
|
407
|
+
for i in range(1, n):
|
|
408
|
+
if cur_w + t_widths[i] + ts_mm > mw_mm or new_line_after[i - 1]:
|
|
409
|
+
xs[i] = 0.0
|
|
410
|
+
ys[i] = h + ls_mm
|
|
411
|
+
cur_w = float(t_widths[i])
|
|
412
|
+
w = max(w, cur_w)
|
|
413
|
+
h = ys[i] + float(t_heights[i])
|
|
414
|
+
else:
|
|
415
|
+
xs[i] = cur_w + (ts_mm if space_after[i - 1] else 0.0)
|
|
416
|
+
ys[i] = ys[i - 1]
|
|
417
|
+
cur_w = xs[i] + float(t_widths[i])
|
|
418
|
+
w = max(w, cur_w)
|
|
419
|
+
h = max(h, ys[i] + float(t_heights[i]))
|
|
420
|
+
elif first_text_from == "top":
|
|
421
|
+
cur_w = float(t_widths[0])
|
|
422
|
+
h = -float(t_heights[0])
|
|
423
|
+
prev_line = [0]
|
|
424
|
+
for i in range(1, n):
|
|
425
|
+
if cur_w + t_widths[i] + ts_mm > mw_mm or new_line_after[i - 1]:
|
|
426
|
+
for pi in prev_line:
|
|
427
|
+
ys[pi] = h
|
|
428
|
+
prev_line = [i]
|
|
429
|
+
xs[i] = 0.0
|
|
430
|
+
ys[i] = h - ls_mm
|
|
431
|
+
cur_w = float(t_widths[i])
|
|
432
|
+
w = max(w, cur_w)
|
|
433
|
+
h = ys[i] - float(t_heights[i])
|
|
434
|
+
else:
|
|
435
|
+
xs[i] = cur_w + (ts_mm if space_after[i - 1] else 0.0)
|
|
436
|
+
ys[i] = ys[i - 1]
|
|
437
|
+
cur_w = xs[i] + float(t_widths[i])
|
|
438
|
+
w = max(w, cur_w)
|
|
439
|
+
h = min(h, ys[i] - float(t_heights[i]))
|
|
440
|
+
prev_line.append(i)
|
|
441
|
+
for pi in prev_line:
|
|
442
|
+
ys[pi] = h
|
|
443
|
+
ys = ys - h
|
|
444
|
+
h = -h
|
|
445
|
+
else:
|
|
446
|
+
raise ValueError("`first_text_from` must be 'top' or 'bottom'.")
|
|
447
|
+
|
|
448
|
+
pad_u = unit(4.0, "pt") if padding is None else as_unit(padding, "pt")
|
|
449
|
+
pad_vals = pad_u.to_mm("x")
|
|
450
|
+
if len(pad_vals) == 1:
|
|
451
|
+
pb = pl = pt = pr = float(pad_vals[0])
|
|
452
|
+
elif len(pad_vals) == 2:
|
|
453
|
+
pb = pt = float(pad_vals[0])
|
|
454
|
+
pl = pr = float(pad_vals[1])
|
|
455
|
+
else:
|
|
456
|
+
pb, pl, pt, pr = (float(pad_vals[0]), float(pad_vals[1]), float(pad_vals[2]), float(pad_vals[3]))
|
|
457
|
+
|
|
458
|
+
w_tot = w + pl + pr
|
|
459
|
+
h_tot = h + pb + pt
|
|
460
|
+
xs = xs + pl
|
|
461
|
+
ys = ys + pb
|
|
462
|
+
|
|
463
|
+
bg_grob: Grob = roundrectGrob(gp=bg_gp, r=r_u) if round_corners else rectGrob(gp=bg_gp)
|
|
464
|
+
txt_grob = textGrob(tokens, x=xs, y=ys, gp=gp_d, default_units="mm", just=(0.0, 0.0))
|
|
465
|
+
vp = Viewport(x=vp_x, y=vp_y, just=just, width=unit(w_tot, "mm"), height=unit(h_tot, "mm"))
|
|
466
|
+
return GTree(children=[bg_grob, txt_grob], vp=vp, cl="textbox", width=unit(w_tot, "mm"), height=unit(h_tot, "mm"))
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def grid_textbox(text: Sequence[str], x: Any = None, y: Any = None, gp: dict[str, Any] | None = None, **kwargs: Any) -> GTree:
|
|
470
|
+
gb = textbox_grob(text, x=x, y=y, gp=gp, **kwargs)
|
|
471
|
+
gb.draw()
|
|
472
|
+
return gb
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
# ---- Interval alignment (`smartAlign` & `smartAlign2`) ----
|
|
476
|
+
|
|
477
|
+
class _Box:
|
|
478
|
+
def __init__(self, start: float, end: float, orig_idx: int) -> None:
|
|
479
|
+
self.start = float(start)
|
|
480
|
+
self.end = float(end)
|
|
481
|
+
self.new_start = float(start)
|
|
482
|
+
self.new_end = float(end)
|
|
483
|
+
self.height = float(end - start)
|
|
484
|
+
self.mid = 0.5 * (start + end)
|
|
485
|
+
self.orig_idx = orig_idx
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class _BoxCluster:
|
|
489
|
+
def __init__(self) -> None:
|
|
490
|
+
self.start = 0.0
|
|
491
|
+
self.end = 0.0
|
|
492
|
+
self.height = 0.0
|
|
493
|
+
self.mid = 0.0
|
|
494
|
+
self.boxes: list[_Box] = []
|
|
495
|
+
|
|
496
|
+
def add_box(self, box_or_cluster: Any) -> None:
|
|
497
|
+
if isinstance(box_or_cluster, _Box):
|
|
498
|
+
self.boxes.append(box_or_cluster)
|
|
499
|
+
else:
|
|
500
|
+
self.boxes.extend(box_or_cluster.boxes)
|
|
501
|
+
self.start = min(b.start for b in self.boxes)
|
|
502
|
+
self.end = max(b.end for b in self.boxes)
|
|
503
|
+
self.mid = 0.5 * (self.start + self.end)
|
|
504
|
+
self.height = self.end - self.start
|
|
505
|
+
|
|
506
|
+
def flatten(self, rng: tuple[float, float]) -> None:
|
|
507
|
+
s = min(b.start for b in self.boxes)
|
|
508
|
+
e = max(b.end for b in self.boxes)
|
|
509
|
+
self.mid = 0.5 * (s + e)
|
|
510
|
+
self.height = sum(b.height for b in self.boxes)
|
|
511
|
+
s2 = self.mid - self.height * 0.5
|
|
512
|
+
e2 = self.mid + self.height * 0.5
|
|
513
|
+
if s2 < rng[0]:
|
|
514
|
+
s2 = rng[0]
|
|
515
|
+
e2 = s2 + self.height
|
|
516
|
+
elif e2 > rng[1]:
|
|
517
|
+
e2 = rng[1]
|
|
518
|
+
s2 = e2 - self.height
|
|
519
|
+
self.start = s2
|
|
520
|
+
self.end = e2
|
|
521
|
+
self.update_box_new_pos()
|
|
522
|
+
|
|
523
|
+
def update_box_new_pos(self) -> None:
|
|
524
|
+
cur = self.start
|
|
525
|
+
for b in self.boxes:
|
|
526
|
+
b.new_start = cur
|
|
527
|
+
b.new_end = cur + b.height
|
|
528
|
+
cur = b.new_end
|
|
529
|
+
|
|
530
|
+
def move(self, dx: float) -> None:
|
|
531
|
+
self.start += dx
|
|
532
|
+
self.end += dx
|
|
533
|
+
self.mid += dx
|
|
534
|
+
self.update_box_new_pos()
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _clusters_overlap(c1: Any, c2: Any) -> bool:
|
|
538
|
+
return not (c1.end < c2.start - 1e-12 or c2.end < c1.start - 1e-12)
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def smartAlign2(
|
|
542
|
+
start: Any,
|
|
543
|
+
end: Any = None,
|
|
544
|
+
range: Sequence[float] | None = None,
|
|
545
|
+
plot: bool = False,
|
|
546
|
+
) -> np.ndarray:
|
|
547
|
+
"""Resolve overlapping 1D intervals `[start, end]` inside `range` (port of `smartAlign2`)."""
|
|
548
|
+
if end is None:
|
|
549
|
+
arr = np.asarray(start, dtype=float)
|
|
550
|
+
if arr.ndim != 2 or arr.shape[1] != 2:
|
|
551
|
+
raise ValueError("When `end` is None, `start` must be an (N, 2) array.")
|
|
552
|
+
s_arr = arr[:, 0].copy()
|
|
553
|
+
e_arr = arr[:, 1].copy()
|
|
554
|
+
else:
|
|
555
|
+
s_arr = np.atleast_1d(np.asarray(start, dtype=float)).copy()
|
|
556
|
+
e_arr = np.atleast_1d(np.asarray(end, dtype=float)).copy()
|
|
557
|
+
|
|
558
|
+
n = len(s_arr)
|
|
559
|
+
if n == 0:
|
|
560
|
+
return np.zeros((0, 2), dtype=float)
|
|
561
|
+
|
|
562
|
+
if range is None:
|
|
563
|
+
rng = (float(min(np.min(s_arr), np.min(e_arr))), float(max(np.max(s_arr), np.max(e_arr))))
|
|
564
|
+
else:
|
|
565
|
+
rng = (float(range[0]), float(range[1]))
|
|
566
|
+
|
|
567
|
+
if n == 1:
|
|
568
|
+
h = e_arr[0] - s_arr[0]
|
|
569
|
+
ns = max(rng[0], min(s_arr[0], rng[1] - h))
|
|
570
|
+
res = np.array([[ns, ns + h]], dtype=float)
|
|
571
|
+
elif float(np.sum(e_arr - s_arr)) > (rng[1] - rng[0]) + 1e-12:
|
|
572
|
+
mid = 0.5 * (s_arr + e_arr)
|
|
573
|
+
od = np.argsort(mid, kind="mergesort")
|
|
574
|
+
h = e_arr[od] - s_arr[od]
|
|
575
|
+
mid_diff = np.zeros(n, dtype=float)
|
|
576
|
+
mid_diff[1:] = 0.5 * h[1:] + 0.5 * h[:-1]
|
|
577
|
+
mid_radius = float(np.sum(h)) - 0.5 * h[-1] - 0.5 * h[0]
|
|
578
|
+
a_1 = rng[0] + 0.5 * h[0]
|
|
579
|
+
a_n = rng[1] - 0.5 * h[-1]
|
|
580
|
+
if mid_radius <= 1e-12:
|
|
581
|
+
a = np.linspace(a_1, a_n, n)
|
|
582
|
+
else:
|
|
583
|
+
a = a_1 + np.cumsum(mid_diff) / mid_radius * (a_n - a_1)
|
|
584
|
+
ns = a - 0.5 * h
|
|
585
|
+
ne = a + 0.5 * h
|
|
586
|
+
res = np.empty((n, 2), dtype=float)
|
|
587
|
+
res[od, 0] = ns
|
|
588
|
+
res[od, 1] = ne
|
|
589
|
+
else:
|
|
590
|
+
boxes = [_Box(s_arr[i], e_arr[i], i) for i in _range(n)]
|
|
591
|
+
boxes.sort(key=lambda b: b.mid)
|
|
592
|
+
clusters: list[_BoxCluster] = []
|
|
593
|
+
c0 = _BoxCluster()
|
|
594
|
+
c0.add_box(boxes[0])
|
|
595
|
+
clusters.append(c0)
|
|
596
|
+
for b in boxes[1:]:
|
|
597
|
+
if _clusters_overlap(clusters[-1], b):
|
|
598
|
+
clusters[-1].add_box(b)
|
|
599
|
+
else:
|
|
600
|
+
nc = _BoxCluster()
|
|
601
|
+
nc.add_box(b)
|
|
602
|
+
clusters.append(nc)
|
|
603
|
+
for c in clusters:
|
|
604
|
+
c.flatten(rng)
|
|
605
|
+
|
|
606
|
+
def _merge(cl: list[_BoxCluster]) -> list[_BoxCluster]:
|
|
607
|
+
while True:
|
|
608
|
+
merged = False
|
|
609
|
+
i = 1
|
|
610
|
+
while i < len(cl):
|
|
611
|
+
if _clusters_overlap(cl[i], cl[i - 1]):
|
|
612
|
+
cl[i - 1].add_box(cl[i])
|
|
613
|
+
cl.pop(i)
|
|
614
|
+
merged = True
|
|
615
|
+
else:
|
|
616
|
+
i += 1
|
|
617
|
+
if not merged:
|
|
618
|
+
break
|
|
619
|
+
for c in cl:
|
|
620
|
+
c.flatten(rng)
|
|
621
|
+
return cl
|
|
622
|
+
|
|
623
|
+
clusters = _merge(clusters)
|
|
624
|
+
for c in clusters:
|
|
625
|
+
if c.start < rng[0]:
|
|
626
|
+
c.move(rng[0] - c.start)
|
|
627
|
+
if c.end > rng[1]:
|
|
628
|
+
c.move(rng[1] - c.end)
|
|
629
|
+
clusters = _merge(clusters)
|
|
630
|
+
|
|
631
|
+
res = np.empty((n, 2), dtype=float)
|
|
632
|
+
for c in clusters:
|
|
633
|
+
for b in c.boxes:
|
|
634
|
+
res[b.orig_idx, 0] = b.new_start
|
|
635
|
+
res[b.orig_idx, 1] = b.new_end
|
|
636
|
+
|
|
637
|
+
if plot:
|
|
638
|
+
fig, ax = plt.subplots(figsize=(5, 4))
|
|
639
|
+
cols = rand_color(n, transparency=0.5)
|
|
640
|
+
for idx in _range(n):
|
|
641
|
+
col = to_rgba_tuple(cols[idx])
|
|
642
|
+
ax.add_patch(plt.Rectangle((0.5, s_arr[idx]), 1.0, e_arr[idx] - s_arr[idx], facecolor=col, edgecolor="black"))
|
|
643
|
+
ax.add_patch(plt.Rectangle((2.5, res[idx, 0]), 1.0, res[idx, 1] - res[idx, 0], facecolor=col, edgecolor="black"))
|
|
644
|
+
ax.plot([1.5, 2.5], [0.5 * (s_arr[idx] + e_arr[idx]), 0.5 * (res[idx, 0] + res[idx, 1])], color="black", lw=0.8)
|
|
645
|
+
ax.set_xlim(0, 4)
|
|
646
|
+
ax.set_ylim(min(rng[0], float(np.min(s_arr))) - 0.5, max(rng[1], float(np.max(e_arr))) + 0.5)
|
|
647
|
+
ax.set_xticks([1, 3])
|
|
648
|
+
ax.set_xticklabels(["original", "adjusted"])
|
|
649
|
+
|
|
650
|
+
return res
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def smartAlign(x1: Any, x2: Any, xlim: Sequence[float]) -> np.ndarray:
|
|
654
|
+
"""Alias for `smartAlign2(x1, x2, xlim)` matching `circlize::smartAlign`."""
|
|
655
|
+
return smartAlign2(x1, x2, range=xlim, plot=False)
|