tilesig 0.1.0.dev0__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.
- tilesig/__init__.py +124 -0
- tilesig/_bundle_data.py +76 -0
- tilesig/_bundle_metadata.py +199 -0
- tilesig/_gpu_linkage_worker.py +147 -0
- tilesig/_version.py +2 -0
- tilesig/algorithm_adapters.py +130 -0
- tilesig/algorithm_binding.py +157 -0
- tilesig/algorithm_types.py +251 -0
- tilesig/algorithms.py +55 -0
- tilesig/annotation.py +1152 -0
- tilesig/annotation_layout.py +104 -0
- tilesig/annotation_names.py +174 -0
- tilesig/annotation_ops.py +199 -0
- tilesig/annotations_extra.py +1573 -0
- tilesig/api.py +861 -0
- tilesig/appearance.py +707 -0
- tilesig/axes.py +146 -0
- tilesig/barplot.py +337 -0
- tilesig/block_heatmap.py +158 -0
- tilesig/block_summary.py +231 -0
- tilesig/bundle_io.py +92 -0
- tilesig/cell_labels.py +68 -0
- tilesig/cell_mask.py +70 -0
- tilesig/clustering.py +39 -0
- tilesig/comparison.py +158 -0
- tilesig/compatibility.py +199 -0
- tilesig/compatibility_extra.py +111 -0
- tilesig/composition_controls.py +132 -0
- tilesig/composition_layout.py +121 -0
- tilesig/config.py +343 -0
- tilesig/decoration_context.py +53 -0
- tilesig/decoration_selection.py +56 -0
- tilesig/decorations.py +166 -0
- tilesig/dendrograms.py +299 -0
- tilesig/diagonal.py +213 -0
- tilesig/distribution_heatmaps.py +164 -0
- tilesig/dot_heatmap.py +274 -0
- tilesig/genomic.py +87 -0
- tilesig/gpu_bridge.py +214 -0
- tilesig/gpu_raster.py +128 -0
- tilesig/graphics.py +92 -0
- tilesig/grouped_textboxes.py +133 -0
- tilesig/h5ad.py +742 -0
- tilesig/h5ad_subset.py +245 -0
- tilesig/helpers.py +246 -0
- tilesig/interval_sets.py +120 -0
- tilesig/item_display_tree.py +81 -0
- tilesig/legend_ticks.py +60 -0
- tilesig/legends.py +607 -0
- tilesig/matplotlib_integration.py +50 -0
- tilesig/matrix_scaling.py +40 -0
- tilesig/matrix_source.py +180 -0
- tilesig/name_layout.py +93 -0
- tilesig/object_ops.py +505 -0
- tilesig/options.py +44 -0
- tilesig/ordering_policy.py +91 -0
- tilesig/palettes.py +101 -0
- tilesig/parent_dendrogram.py +199 -0
- tilesig/pdf_renderer.py +717 -0
- tilesig/png_renderer.py +559 -0
- tilesig/preparation_cache.py +94 -0
- tilesig/prepared.py +179 -0
- tilesig/r_cluster_controls.py +138 -0
- tilesig/r_layout_controls.py +92 -0
- tilesig/r_raster.py +235 -0
- tilesig/renderer.py +3611 -0
- tilesig/renderer_old.py +2060 -0
- tilesig/reproducibility.py +88 -0
- tilesig/sets.py +407 -0
- tilesig/signal_heatmap.py +453 -0
- tilesig/single_cell.py +251 -0
- tilesig/slice_drawing.py +100 -0
- tilesig/slice_geometry.py +48 -0
- tilesig/slice_summary.py +80 -0
- tilesig/source_render.py +252 -0
- tilesig/specialized.py +520 -0
- tilesig/specialized_support.py +172 -0
- tilesig/streaming_pdf.py +118 -0
- tilesig/streaming_svg.py +72 -0
- tilesig/style.py +148 -0
- tilesig/text_boxes.py +158 -0
- tilesig/text_layout.py +45 -0
- tilesig/text_styles.py +83 -0
- tilesig/titles.py +191 -0
- tilesig/tree_styles.py +45 -0
- tilesig/unicode_pdf.py +119 -0
- tilesig/upset_annotations.py +58 -0
- tilesig/vector_grid.py +13 -0
- tilesig/within_block_order.py +167 -0
- tilesig-0.1.0.dev0.dist-info/METADATA +107 -0
- tilesig-0.1.0.dev0.dist-info/RECORD +94 -0
- tilesig-0.1.0.dev0.dist-info/WHEEL +5 -0
- tilesig-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
- tilesig-0.1.0.dev0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1573 @@
|
|
|
1
|
+
"""Additional annotation tracks rendered through the existing SVG sink protocol.
|
|
2
|
+
|
|
3
|
+
These are explicit Python mappings, not complete R argument compatibility. Numeric
|
|
4
|
+
matrices have *items in rows* and series/replicates in columns. Series/DataFrame
|
|
5
|
+
indices identify heatmap rows/columns; unnamed sequences are positional (the
|
|
6
|
+
renderer must bind them to heatmap identifiers before reindexing). One annotation
|
|
7
|
+
reserves one band, including multiseries/distribution input. Distances, font sizes
|
|
8
|
+
and ``height`` use the renderer's SVG coordinate units, not R ``grid::unit``.
|
|
9
|
+
|
|
10
|
+
Factories accept ``side`` or ``which='row'/'column'``, plus ``height``, ``fontsize``
|
|
11
|
+
and ``label``. Supported Python ``gp`` dictionaries, point symbols and numeric
|
|
12
|
+
``axis_param`` are explicit; unknown options raise TypeError. Direct font/height
|
|
13
|
+
arguments retain canvas units, while gp font sizes and named annotation styles
|
|
14
|
+
use physical points. Density heatmap strips and overlapping joyplot ridges share
|
|
15
|
+
the native sinks. Exact R KDE/grid viewport semantics remain partial. Custom
|
|
16
|
+
callbacks receive an :class:`AnnotationPanel` with portable primitive helpers.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import base64
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from io import BytesIO
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Callable
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
from .slice_geometry import gap_at,gap_total,slice_gaps
|
|
28
|
+
import pandas as pd
|
|
29
|
+
from PIL import Image
|
|
30
|
+
|
|
31
|
+
from .annotation import AnnotationBase, _escape_xml, _resolve_fontsize, _resolve_height
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
'DistributionBoxplotAnnotation', 'PointsAnnotation', 'LinesAnnotation', 'HistogramAnnotation', 'DensityAnnotation',
|
|
36
|
+
'JoyplotAnnotation', 'TextAnnotation', 'MarkAnnotation', 'BlockAnnotation',
|
|
37
|
+
'NumericAnnotation', 'SummaryAnnotation', 'ImageAnnotation', 'EmptyAnnotation',
|
|
38
|
+
'CustomAnnotation', 'ZoomAnnotation', 'HorizonAnnotation', 'TextboxAnnotation',
|
|
39
|
+
'AnnotationPanel', 'anno_points', 'anno_lines', 'anno_histogram', 'anno_density',
|
|
40
|
+
'anno_joyplot', 'anno_text', 'anno_mark', 'anno_block', 'anno_numeric',
|
|
41
|
+
'anno_summary', 'anno_image', 'anno_empty', 'anno_customize', 'anno_link',
|
|
42
|
+
'anno_zoom', 'anno_horizon', 'anno_textbox', 'row_anno_points',
|
|
43
|
+
'row_anno_density', 'row_anno_histogram', 'row_anno_text',
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _num(value):
|
|
48
|
+
"""Finite samples only; missing/scalar values become empty/singleton arrays."""
|
|
49
|
+
try:
|
|
50
|
+
x = np.asarray(value, dtype=float).ravel()
|
|
51
|
+
except (TypeError, ValueError):
|
|
52
|
+
return np.empty(0)
|
|
53
|
+
return x[np.isfinite(x)]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _limits(values, explicit=None, name='ylim'):
|
|
57
|
+
if explicit is not None:
|
|
58
|
+
x = np.asarray(explicit, dtype=float)
|
|
59
|
+
if x.shape != (2,) or not np.all(np.isfinite(x)) or x[1] <= x[0]:
|
|
60
|
+
raise ValueError(f'{name} must contain two increasing finite numbers')
|
|
61
|
+
return float(x[0]), float(x[1])
|
|
62
|
+
chunks = [_num(v) for v in values]
|
|
63
|
+
x = np.concatenate(chunks) if chunks else np.empty(0)
|
|
64
|
+
lo, hi = (float(x.min()), float(x.max())) if x.size else (0., 1.)
|
|
65
|
+
if lo == hi:
|
|
66
|
+
pad = max(abs(lo) * .05, .5)
|
|
67
|
+
lo, hi = lo - pad, hi + pad
|
|
68
|
+
return lo, hi
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _svg(f, tag, **attrs):
|
|
72
|
+
f.write('<' + tag + ' ' + ' '.join(f'{k.replace("_", "-")}="{_escape_xml(v)}"'
|
|
73
|
+
for k, v in attrs.items()) + '/>')
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _text(f,x,y,text,fontsize=10,color='#222222',rotate=0,*,bold=False,italic=False,family='Arial'):
|
|
77
|
+
transform = f' transform="rotate({float(rotate)} {x} {y})"' if rotate else ''
|
|
78
|
+
f.write(f'<text x="{x}" y="{y}" fill="{_escape_xml(color)}" '
|
|
79
|
+
f'font-family="{_escape_xml(family)}" font-size="{fontsize}" font-weight="{"bold" if bold else "normal"}" font-style="{"italic" if italic else "normal"}" '
|
|
80
|
+
f'text-anchor="middle" dominant-baseline="middle"{transform}>'
|
|
81
|
+
f'{_escape_xml(text)}</text>')
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class AnnotationPanel:
|
|
86
|
+
"""Callback panel in final canvas coordinates; indices are zero-based display positions.
|
|
87
|
+
|
|
88
|
+
``names`` are item identifiers and ``values`` follow the same order. ``rect``
|
|
89
|
+
fills the whole panel; ``text`` places a centered escaped label; ``line`` takes
|
|
90
|
+
canvas coordinates. ``sink.write`` is available for advanced SVG primitives,
|
|
91
|
+
but only primitives supported by the native sinks are portable to all formats.
|
|
92
|
+
"""
|
|
93
|
+
sink: object
|
|
94
|
+
x: float
|
|
95
|
+
y: float
|
|
96
|
+
width: float
|
|
97
|
+
height: float
|
|
98
|
+
indices: tuple
|
|
99
|
+
names: tuple
|
|
100
|
+
values: tuple
|
|
101
|
+
direction: str
|
|
102
|
+
fontsize: float
|
|
103
|
+
group: object = None
|
|
104
|
+
fontfamily: str = 'Arial'
|
|
105
|
+
|
|
106
|
+
def rect(self, fill='none', stroke='none', stroke_width=1):
|
|
107
|
+
_svg(self.sink, 'rect', x=self.x, y=self.y, width=self.width,
|
|
108
|
+
height=self.height, fill=fill, stroke=stroke, stroke_width=stroke_width)
|
|
109
|
+
|
|
110
|
+
def text(self, text, color='#222222'):
|
|
111
|
+
_text(self.sink, self.x + self.width / 2, self.y + self.height / 2,
|
|
112
|
+
text, self.fontsize, color,family=self.fontfamily)
|
|
113
|
+
|
|
114
|
+
def line(self, x1, y1, x2, y2, color='#222222', width=1):
|
|
115
|
+
_svg(self.sink, 'line', x1=x1, y1=y1, x2=x2, y2=y2,
|
|
116
|
+
stroke=color, stroke_width=width)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class _Track(AnnotationBase):
|
|
120
|
+
_draws_own_border = True
|
|
121
|
+
auto_height_ratio = 2.0
|
|
122
|
+
|
|
123
|
+
def __init__(self, x=None, *, side=None, which=None, height=None, fontsize=None,
|
|
124
|
+
label=None, color='#4682b4', border=False, axis=False, axis_param=None, gp=None,width=None):
|
|
125
|
+
if which not in (None, 'row', 'column'):
|
|
126
|
+
raise ValueError("which must be 'row' or 'column'")
|
|
127
|
+
side = side or ('left' if which == 'row' else 'top')
|
|
128
|
+
if side not in ('top', 'bottom', 'left', 'right'):
|
|
129
|
+
raise ValueError('side must be top, bottom, left or right')
|
|
130
|
+
if which is not None and ((side in ('left', 'right')) != (which == 'row')):
|
|
131
|
+
raise ValueError('side conflicts with which')
|
|
132
|
+
if width is not None:
|
|
133
|
+
if side not in ('left','right'):raise ValueError('width is a physical row annotation thickness; use height for column tracks')
|
|
134
|
+
if height is not None:raise ValueError('width conflicts with native canvas-unit height')
|
|
135
|
+
if isinstance(width,(bool,np.bool_)) or not isinstance(width,(int,float,np.integer,np.floating)) or not np.isfinite(width) or width<=0:
|
|
136
|
+
raise ValueError('width must be positive finite mm')
|
|
137
|
+
if height is not None and (not np.isfinite(height) or height < 0):
|
|
138
|
+
raise ValueError('height must be finite and nonnegative')
|
|
139
|
+
self._positional = x is not None and not isinstance(x, (pd.Series, pd.DataFrame))
|
|
140
|
+
self._positional_input = self._positional
|
|
141
|
+
if isinstance(x, pd.DataFrame):
|
|
142
|
+
values = [row[0] if x.shape[1] == 1 else row for row in x.to_numpy()]
|
|
143
|
+
index = x.index.copy()
|
|
144
|
+
elif isinstance(x, pd.Series):
|
|
145
|
+
values, index = list(x), x.index.copy()
|
|
146
|
+
elif x is not None:
|
|
147
|
+
values, index = list(x), None
|
|
148
|
+
else:
|
|
149
|
+
values, index = None, None
|
|
150
|
+
if index is not None:
|
|
151
|
+
index = index.map(str)
|
|
152
|
+
if index.has_duplicates:
|
|
153
|
+
raise ValueError('duplicate item identifiers are not supported')
|
|
154
|
+
frame = None if values is None else pd.DataFrame(
|
|
155
|
+
{label or 'value': pd.Series(values, index=index, dtype=object).infer_objects()})
|
|
156
|
+
super().__init__(df=frame, side=side, height=height, fontsize=fontsize, label=label)
|
|
157
|
+
if width is not None:self._fixed_height_mm=self._r_width_mm=float(width)
|
|
158
|
+
self._graphical_ids=None if frame is None else pd.Series(np.arange(len(frame)),index=frame.index.map(str))
|
|
159
|
+
from .graphics import validate_gp,gp_value
|
|
160
|
+
if gp is not None and 'fontfamily' in gp and (not isinstance(gp['fontfamily'],str) or not gp['fontfamily'].strip()):
|
|
161
|
+
raise ValueError('gp fontfamily must be a nonempty scalar family name')
|
|
162
|
+
self.gp=validate_gp(gp,{'col','fill','lwd','fontsize','fontface','fontfamily'})
|
|
163
|
+
self.color=gp_value(self.gp,'col',0,gp_value(self.gp,'fill',0,color))
|
|
164
|
+
self.border,self.axis=bool(border),bool(axis)
|
|
165
|
+
self._multiseries=False
|
|
166
|
+
if values is not None:
|
|
167
|
+
self._multiseries=any(isinstance(v,(list,tuple,np.ndarray,pd.Series)) and np.ndim(v)>0 and len(v)>1 for v in values)
|
|
168
|
+
from .axes import axis_parameters
|
|
169
|
+
self.axis_param=dict(axis_param or {})
|
|
170
|
+
axis_parameters(self.axis_param,'row' if side in ('left','right') else 'column')
|
|
171
|
+
|
|
172
|
+
def _font_family(self,default='Arial'):
|
|
173
|
+
if 'fontfamily' not in self.gp:return default
|
|
174
|
+
from .style import resolved_font_family
|
|
175
|
+
return resolved_font_family(self.gp['fontfamily'])
|
|
176
|
+
|
|
177
|
+
def _style_index(self,i):
|
|
178
|
+
if self._graphical_ids is None or self.df is None:return i
|
|
179
|
+
return int(self._graphical_ids.get(str(self.df.index[i]),i))
|
|
180
|
+
|
|
181
|
+
def _items(self, renderer, vertical, n):
|
|
182
|
+
if self.df is not None:
|
|
183
|
+
return list(self.df.iloc[:, 0]), tuple(self.df.index)
|
|
184
|
+
matrix = np.asarray(renderer._matrix_sorted)
|
|
185
|
+
arr = matrix if vertical else matrix.T
|
|
186
|
+
names = getattr(renderer, 'row_names' if vertical else 'col_names', None)
|
|
187
|
+
if names is None:
|
|
188
|
+
names = range(len(arr))
|
|
189
|
+
if len(names) != len(arr):
|
|
190
|
+
raise ValueError('finalized names do not match annotation data length')
|
|
191
|
+
return list(arr), tuple(names)
|
|
192
|
+
|
|
193
|
+
def draw(self, f, start_x, start_y, pixel_size, bounds, gap_pixels, direction, renderer):
|
|
194
|
+
if direction not in ('up', 'down', 'left', 'right'):
|
|
195
|
+
raise ValueError('direction must be up, down, left or right')
|
|
196
|
+
vertical = direction in ('left', 'right')
|
|
197
|
+
height = float(getattr(self,'_zoom_height_float',_resolve_height(renderer, self)))
|
|
198
|
+
if hasattr(self,'_r_width_mm'):
|
|
199
|
+
if getattr(renderer,'style','complexheatmap')!='complexheatmap':raise ValueError('physical annotation width requires native complexheatmap style')
|
|
200
|
+
if self.height is None:height=renderer._appearance.mm(self._fixed_height_mm)
|
|
201
|
+
font = self.resolved_fontsize(renderer)
|
|
202
|
+
n = max((b for _, b in bounds), default=0)
|
|
203
|
+
values, names = self._items(renderer, vertical, n)
|
|
204
|
+
if len(values) < n:
|
|
205
|
+
raise ValueError('annotation has fewer items than rendered bounds')
|
|
206
|
+
positions = {}
|
|
207
|
+
panels = []
|
|
208
|
+
cursor = float(start_y if vertical else start_x)
|
|
209
|
+
cross = float(start_x if vertical else start_y)
|
|
210
|
+
for slice_index,(start, end) in enumerate(bounds):
|
|
211
|
+
if end <= start:
|
|
212
|
+
continue
|
|
213
|
+
span = (end - start) * pixel_size
|
|
214
|
+
near = cross - height if direction in ('up', 'left') else cross
|
|
215
|
+
box = (near, cursor, height, span) if vertical else (cursor, near, span, height)
|
|
216
|
+
panel = AnnotationPanel(f, *box, tuple(range(start, end)),
|
|
217
|
+
tuple(names[start:end]), tuple(values[start:end]),
|
|
218
|
+
direction, font,fontfamily=self._font_family())
|
|
219
|
+
panels.append(panel)
|
|
220
|
+
for i in range(start, end):
|
|
221
|
+
positions[i] = cursor + (i - start + .5) * pixel_size
|
|
222
|
+
cursor += span + gap_at(gap_pixels,slice_index)
|
|
223
|
+
if not panels or height == 0:
|
|
224
|
+
return
|
|
225
|
+
if getattr(self,'background',False):self._draw_background(f,values,panels,positions,cross,height,direction)
|
|
226
|
+
self._render(f, values, panels, positions, cross, height, pixel_size, direction, font)
|
|
227
|
+
if self.label and getattr(self,'_show_annotation_name',True):
|
|
228
|
+
if getattr(renderer,'style','legacy')=='complexheatmap':
|
|
229
|
+
from .annotation_names import draw_name
|
|
230
|
+
near=cross-height if direction in ('up','left') else cross
|
|
231
|
+
start=panels[0].y if vertical else panels[0].x
|
|
232
|
+
end=panels[-1].y+panels[-1].height if vertical else panels[-1].x+panels[-1].width
|
|
233
|
+
draw_name(self,f,renderer,start,end,near,height,vertical)
|
|
234
|
+
else:
|
|
235
|
+
if vertical:label_x,label_y=panels[0].x+height/2,panels[0].y-font
|
|
236
|
+
else:
|
|
237
|
+
label_x=panels[-1].x+panels[-1].width+font+len(str(self.label))*font*.3
|
|
238
|
+
label_y=panels[-1].y+height/2
|
|
239
|
+
_text(f,label_x,label_y,self.label,font,family=self._font_family())
|
|
240
|
+
for panel in panels:
|
|
241
|
+
if self.border:
|
|
242
|
+
panel.rect(stroke='#333333', stroke_width=.5)
|
|
243
|
+
if self.axis:
|
|
244
|
+
from .style import Appearance
|
|
245
|
+
axis=self._axis_model(values,vertical)
|
|
246
|
+
panel=panels[0] if axis.side in ('left','top') else panels[-1]
|
|
247
|
+
coordinate=panel.y if axis.side=='top' else panel.y+panel.height if axis.side=='bottom' else panel.x if axis.side=='left' else panel.x+panel.width
|
|
248
|
+
p0=self._point(0,0,cross,height,direction,reverse=False)
|
|
249
|
+
p1=self._point(0,1,cross,height,direction,reverse=False)
|
|
250
|
+
start,end=(p0[0],p1[0]) if vertical else (p0[1],p1[1])
|
|
251
|
+
axis.draw_at(f,start,end,coordinate,getattr(renderer,'_appearance',Appearance(96)))
|
|
252
|
+
|
|
253
|
+
def resolved_fontsize(self,renderer):
|
|
254
|
+
if self.fontsize is not None:return float(self.fontsize)
|
|
255
|
+
if 'fontsize' in self.gp:
|
|
256
|
+
from .style import Appearance
|
|
257
|
+
from .graphics import gp_value
|
|
258
|
+
return getattr(renderer,'_appearance',Appearance(96)).pt(float(gp_value(self.gp,'fontsize')))
|
|
259
|
+
return _resolve_fontsize(renderer,None)
|
|
260
|
+
|
|
261
|
+
def _data_limits(self,values,explicit=None):
|
|
262
|
+
lo,hi=_limits(values,explicit)
|
|
263
|
+
margin=(hi-lo)*getattr(self,'extend',0)
|
|
264
|
+
return lo-margin,hi+margin
|
|
265
|
+
|
|
266
|
+
def _axis_model(self,values,vertical):
|
|
267
|
+
from .axes import AnnotationAxis,axis_parameters
|
|
268
|
+
explicit=next((getattr(self,k) for k in ('ylim','xlim','rg') if getattr(self,k,None) is not None),None)
|
|
269
|
+
lo,hi=self._data_limits(values,explicit)
|
|
270
|
+
return AnnotationAxis(scale=(lo,hi),**axis_parameters(self.axis_param,'row' if vertical else 'column'))
|
|
271
|
+
|
|
272
|
+
def axis_padding(self,renderer):
|
|
273
|
+
if not self.axis:return {}
|
|
274
|
+
from .style import Appearance
|
|
275
|
+
vertical=self.side in ('left','right')
|
|
276
|
+
n=len(renderer.row_names if vertical else renderer.col_names)
|
|
277
|
+
values,_=self._items(renderer,vertical,n)
|
|
278
|
+
axis=self._axis_model(values,vertical)
|
|
279
|
+
return {axis.side:axis.padding(getattr(renderer,'_appearance',Appearance(96)))}
|
|
280
|
+
|
|
281
|
+
def _point(self,along, fraction, cross, height, direction,reverse=True):
|
|
282
|
+
# Four units of padding prevent strokes/points touching adjacent bands.
|
|
283
|
+
if reverse and self.axis_param.get('direction')=='reverse':fraction=1-fraction
|
|
284
|
+
pad = min(4., height / 4)
|
|
285
|
+
offset = pad + np.clip(fraction, 0, 1) * max(0, height - 2 * pad)
|
|
286
|
+
offset *= -1 if direction in ('up', 'left') else 1
|
|
287
|
+
return (cross + offset, along) if direction in ('left', 'right') else (along, cross + offset)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _boxplot_statistics(values):
|
|
291
|
+
"""R/Tukey hinges, 1.5-IQR whiskers and outliers for finite observations."""
|
|
292
|
+
v=np.sort(_num(values))
|
|
293
|
+
if not len(v):return np.full(5,np.nan),np.empty(0)
|
|
294
|
+
n=len(v);hinge=np.floor((n+3)/2)/2
|
|
295
|
+
positions=np.array([1,hinge,(n+1)/2,n+1-hinge,n])-1
|
|
296
|
+
stats=(v[np.floor(positions).astype(int)]+v[np.ceil(positions).astype(int)])/2
|
|
297
|
+
iqr=stats[3]-stats[1]
|
|
298
|
+
outside=(v<stats[1]-1.5*iqr)|(v>stats[3]+1.5*iqr)
|
|
299
|
+
stats[0]=v[~outside].min();stats[4]=v[~outside].max()
|
|
300
|
+
return stats,v[outside]
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class DistributionBoxplotAnnotation(_Track):
|
|
304
|
+
"""Tukey boxplots in every orientation; one finite distribution per item."""
|
|
305
|
+
def __init__(self,x=None,*,ylim=None,box_color='#cccccc',whisker_color='#222222',outlier_color='#222222',width_frac=None,show_outliers=None,outlier_radius=1.5,extend=.05,axis=True,border=True,outline=None,box_width=None,add_points=False,pch=None,size=None,pt_gp=None,**kwargs):
|
|
306
|
+
from .graphics import validate_gp,draw_marker
|
|
307
|
+
if outline is not None:
|
|
308
|
+
if not isinstance(outline,(bool,np.bool_)):raise TypeError('outline must be boolean')
|
|
309
|
+
if show_outliers is not None:raise TypeError('outline and show_outliers both supplied')
|
|
310
|
+
show_outliers=outline
|
|
311
|
+
if box_width is not None:
|
|
312
|
+
if width_frac is not None:raise TypeError('box_width and width_frac both supplied')
|
|
313
|
+
width_frac=box_width
|
|
314
|
+
width_frac=.6 if width_frac is None else width_frac
|
|
315
|
+
show_outliers=True if show_outliers is None else show_outliers
|
|
316
|
+
if not isinstance(add_points,(bool,np.bool_)):raise TypeError('add_points must be boolean')
|
|
317
|
+
self.add_points=bool(add_points)
|
|
318
|
+
self._styled_points=pch is not None or size is not None or pt_gp is not None or self.add_points
|
|
319
|
+
self.pt_gp=validate_gp(pt_gp,{'col','fill','lwd'})
|
|
320
|
+
self._point_symbols=list(np.atleast_1d(16 if pch is None else pch))
|
|
321
|
+
self._point_sizes=np.atleast_1d(2 if size is None else size).astype(float)
|
|
322
|
+
if not len(self._point_sizes) or not np.isfinite(self._point_sizes).all() or np.any(self._point_sizes<=0):raise ValueError('size must contain positive finite mm')
|
|
323
|
+
if not self._point_symbols:raise ValueError('pch must not be empty')
|
|
324
|
+
from io import StringIO
|
|
325
|
+
for marker in self._point_symbols:draw_marker(StringIO(),0,0,1,marker)
|
|
326
|
+
if not np.isfinite(extend) or extend<0:raise ValueError('extend must be finite and nonnegative')
|
|
327
|
+
self.extend=float(extend)
|
|
328
|
+
super().__init__(x,axis=axis,border=border,**kwargs)
|
|
329
|
+
if not 0<width_frac<=1:raise ValueError('width_frac must be in (0,1]')
|
|
330
|
+
if outlier_radius=='auto':outlier_radius=1.5
|
|
331
|
+
if not np.isfinite(outlier_radius) or outlier_radius<0:raise ValueError('outlier_radius must be finite and nonnegative')
|
|
332
|
+
_limits([],ylim)
|
|
333
|
+
self.ylim=ylim;self.box_color=box_color;self.whisker_color=whisker_color
|
|
334
|
+
self.outlier_color=outlier_color;self.width_frac=width_frac
|
|
335
|
+
self.show_outliers=bool(show_outliers);self.outlier_radius=outlier_radius
|
|
336
|
+
def _data_limits(self,values,explicit=None):
|
|
337
|
+
if explicit is None and not self.show_outliers:
|
|
338
|
+
values=[_boxplot_statistics(v)[0][[0,4]] for v in values if _num(v).size]
|
|
339
|
+
return super()._data_limits(values,explicit)
|
|
340
|
+
|
|
341
|
+
def _render(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
342
|
+
from .graphics import gp_value
|
|
343
|
+
lo,hi=self._data_limits(values,self.ylim)
|
|
344
|
+
vertical=direction in ('left','right')
|
|
345
|
+
for i,along in positions.items():
|
|
346
|
+
fill=gp_value(self.gp,"fill",self._style_index(i),self.box_color)
|
|
347
|
+
stroke=gp_value(self.gp,"col",self._style_index(i),self.whisker_color)
|
|
348
|
+
linewidth=gp_value(self.gp,"lwd",self._style_index(i),.75)
|
|
349
|
+
v=_num(values[i])
|
|
350
|
+
if not len(v):continue
|
|
351
|
+
(low,q1,median,q3,high),outliers=_boxplot_statistics(v)
|
|
352
|
+
def point(value,offset=0):return self._point(along+offset,(value-lo)/(hi-lo),cross,height,direction)
|
|
353
|
+
def line(a,b):_svg(f,'line',x1=a[0],y1=a[1],x2=b[0],y2=b[1],stroke=stroke,stroke_width=linewidth)
|
|
354
|
+
half=pixel*self.width_frac/2
|
|
355
|
+
line(point(low),point(high))
|
|
356
|
+
for value in (low,high):line(point(value,-half/2),point(value,half/2))
|
|
357
|
+
a,b=point(q1,-half),point(q3,half)
|
|
358
|
+
_svg(f,'rect',x=min(a[0],b[0]),y=min(a[1],b[1]),width=abs(b[0]-a[0]),height=abs(b[1]-a[1]),fill=fill,stroke=stroke,stroke_width=linewidth)
|
|
359
|
+
line(point(median,-half),point(median,half))
|
|
360
|
+
if self.show_outliers:
|
|
361
|
+
samples=v if self.add_points else outliers
|
|
362
|
+
if self._styled_points:
|
|
363
|
+
from .graphics import draw_marker
|
|
364
|
+
from .style import Appearance
|
|
365
|
+
app=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
366
|
+
index=self._style_index(i)
|
|
367
|
+
radius=app.mm(self._point_sizes[index%len(self._point_sizes)])/2
|
|
368
|
+
offsets=np.linspace(-pixel*self.width_frac/4,pixel*self.width_frac/4,len(samples)) if self.add_points and len(samples)>1 else np.zeros(len(samples))
|
|
369
|
+
for value,offset in zip(samples,offsets):
|
|
370
|
+
x,y=point(value,offset)
|
|
371
|
+
draw_marker(f,x,y,radius,self._point_symbols[index%len(self._point_symbols)],
|
|
372
|
+
gp_value(self.pt_gp,'col',index,self.outlier_color),gp_value(self.pt_gp,'fill',index),gp_value(self.pt_gp,'lwd',index,.75))
|
|
373
|
+
else:
|
|
374
|
+
for value in samples:
|
|
375
|
+
x,y=point(value);_svg(f,'circle',cx=x,cy=y,r=self.outlier_radius,fill=self.outlier_color)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
class PointsAnnotation(_Track):
|
|
379
|
+
"""Scatter track, with each item's scalar/vector drawn at that item's center.
|
|
380
|
+
|
|
381
|
+
``ylim`` clips values to the stated range; missing/nonfinite points are omitted.
|
|
382
|
+
Matrix series share a scale and color. Marker radius uses canvas units.
|
|
383
|
+
"""
|
|
384
|
+
def __init__(self,x,*,ylim=None,radius=None,size=2,pch=16,extend=.05,axis=True,border=True,background=False,**kwargs):
|
|
385
|
+
if not isinstance(background,(bool,np.bool_)):raise TypeError('background must be boolean')
|
|
386
|
+
self.background=bool(background)
|
|
387
|
+
_limits([],ylim)
|
|
388
|
+
if radius is not None and (not np.isfinite(radius) or radius<0):raise ValueError('radius must be finite and nonnegative')
|
|
389
|
+
if not np.isfinite([size,extend]).all() or size<=0 or extend<0:raise ValueError('size must be positive and extend nonnegative')
|
|
390
|
+
super().__init__(x,axis=axis,border=border,**kwargs)
|
|
391
|
+
self.ylim,self.radius=ylim,None if radius is None else float(radius)
|
|
392
|
+
self.size_mm,self.extend=float(size),float(extend)
|
|
393
|
+
markers=list(pch) if isinstance(pch,(list,tuple,np.ndarray)) else [pch]
|
|
394
|
+
from .graphics import draw_marker
|
|
395
|
+
class Null:
|
|
396
|
+
def write(self,text):pass
|
|
397
|
+
if not markers:raise ValueError('pch must not be empty')
|
|
398
|
+
for marker in markers:draw_marker(Null(),0,0,1,marker)
|
|
399
|
+
self.pch=markers
|
|
400
|
+
|
|
401
|
+
def _draw_background(self,f,values,panels,positions,cross,height,direction):
|
|
402
|
+
vertical=direction in ('left','right')
|
|
403
|
+
axis=self._axis_model(values,vertical)
|
|
404
|
+
lo,hi=axis.scale
|
|
405
|
+
for panel in panels:
|
|
406
|
+
panel.rect(fill='#dddddd')
|
|
407
|
+
start=panel.y if vertical else panel.x
|
|
408
|
+
end=start+(panel.height if vertical else panel.width)
|
|
409
|
+
for i in panel.indices:
|
|
410
|
+
a=self._point(positions[i],0,cross,height,direction)
|
|
411
|
+
b=self._point(positions[i],1,cross,height,direction)
|
|
412
|
+
_svg(f,'line',x1=a[0],y1=a[1],x2=b[0],y2=b[1],stroke='#ffffff',stroke_width=1)
|
|
413
|
+
for tick in axis.at:
|
|
414
|
+
if not lo<=tick<=hi:continue
|
|
415
|
+
fraction=(tick-lo)/(hi-lo)
|
|
416
|
+
a=self._point(start,fraction,cross,height,direction)
|
|
417
|
+
b=self._point(end,fraction,cross,height,direction)
|
|
418
|
+
_svg(f,'line',x1=a[0],y1=a[1],x2=b[0],y2=b[1],stroke='#ffffff',stroke_width=1)
|
|
419
|
+
|
|
420
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
421
|
+
lo, hi = self._data_limits(values, self.ylim)
|
|
422
|
+
from .graphics import gp_value,draw_marker
|
|
423
|
+
from .style import Appearance
|
|
424
|
+
appearance=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
425
|
+
radius=self.radius if self.radius is not None else appearance.mm(self.size_mm)/2
|
|
426
|
+
for i,along in positions.items():
|
|
427
|
+
try:samples=np.asarray(values[i],dtype=float).ravel()
|
|
428
|
+
except (TypeError,ValueError):continue
|
|
429
|
+
for series,v in enumerate(samples):
|
|
430
|
+
if not np.isfinite(v):continue
|
|
431
|
+
index=series if self._multiseries else self._style_index(i)
|
|
432
|
+
x,y=self._point(along,(v-lo)/(hi-lo),cross,height,direction)
|
|
433
|
+
draw_marker(f,x,y,radius,self.pch[index%len(self.pch)],
|
|
434
|
+
gp_value(self.gp,'col',index,self.color),gp_value(self.gp,'fill',index),
|
|
435
|
+
float(gp_value(self.gp,'lwd',index,.75)))
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
class LinesAnnotation(PointsAnnotation):
|
|
439
|
+
"""Series lines; optional local quadratic smoothing, independent marker gp.
|
|
440
|
+
|
|
441
|
+
Smoothing fits 100 points per finite run with a .75 span and tricube
|
|
442
|
+
weights. This native direct local fit does not reproduce R loess's
|
|
443
|
+
interpolated kd-tree surface. Split gaps and missing runs remain separate.
|
|
444
|
+
"""
|
|
445
|
+
def __init__(self, x, *, linewidth=1, add_points=None, smooth=False, pt_gp=None, **kwargs):
|
|
446
|
+
if not isinstance(smooth,(bool,np.bool_)):
|
|
447
|
+
raise TypeError('smooth must be boolean')
|
|
448
|
+
from .graphics import validate_gp
|
|
449
|
+
self.pt_gp=None if pt_gp is None else validate_gp(pt_gp,{'col','fill','lwd'})
|
|
450
|
+
super().__init__(x, **kwargs)
|
|
451
|
+
self.smooth=bool(smooth)
|
|
452
|
+
self.linewidth=float(linewidth)
|
|
453
|
+
self.add_points=self.smooth if add_points is None else bool(add_points)
|
|
454
|
+
|
|
455
|
+
@staticmethod
|
|
456
|
+
def _smooth_run(along, values):
|
|
457
|
+
"""Bounded direct quadratic LOESS; short runs retain straight segments."""
|
|
458
|
+
x=np.asarray(along,dtype=float);y=np.asarray(values,dtype=float)
|
|
459
|
+
if len(x)<3:return x,y
|
|
460
|
+
# Fit in item-space, independent of canvas DPI and orientation.
|
|
461
|
+
origin=x[0];scale=x[-1]-origin
|
|
462
|
+
if scale<=0:return x,y
|
|
463
|
+
x=(x-origin)/scale
|
|
464
|
+
target=np.linspace(0.,1.,100);result=np.empty(100)
|
|
465
|
+
count=min(len(x),max(3,int(np.ceil(.75*len(x)))))
|
|
466
|
+
for i,value in enumerate(target):
|
|
467
|
+
distances=np.abs(x-value)
|
|
468
|
+
width=np.partition(distances,count-1)[count-1]
|
|
469
|
+
width=max(width, np.finfo(float).eps)*(1+1e-5)
|
|
470
|
+
weight=np.maximum(0.,1-(distances/width)**3)**3
|
|
471
|
+
keep=weight>1e-20
|
|
472
|
+
local=x[keep]-value
|
|
473
|
+
design=np.column_stack((np.ones(len(local)),local,local*local))
|
|
474
|
+
root=np.sqrt(weight[keep])
|
|
475
|
+
result[i]=np.linalg.lstsq(design*root[:,None],y[keep]*root,rcond=None)[0][0]
|
|
476
|
+
return origin+target*scale,result
|
|
477
|
+
|
|
478
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
479
|
+
lo, hi = self._data_limits(values, self.ylim)
|
|
480
|
+
from .graphics import gp_value
|
|
481
|
+
arrays = []
|
|
482
|
+
for v in values:
|
|
483
|
+
try:
|
|
484
|
+
arrays.append(np.asarray(v, dtype=float).ravel())
|
|
485
|
+
except (TypeError, ValueError):
|
|
486
|
+
arrays.append(np.empty(0))
|
|
487
|
+
for panel in panels:
|
|
488
|
+
for series in range(max((len(arrays[i]) for i in panel.indices), default=0)):
|
|
489
|
+
points = []
|
|
490
|
+
raw_along,raw_values=[],[]
|
|
491
|
+
def flush():
|
|
492
|
+
if self.smooth and len(raw_values)>=3:
|
|
493
|
+
xx,yy=self._smooth_run(raw_along,raw_values)
|
|
494
|
+
points[:]=[self._point(a,(v-lo)/(hi-lo),cross,height,direction) for a,v in zip(xx,yy)]
|
|
495
|
+
if len(points) >= 2:
|
|
496
|
+
_svg(f, 'polyline', points=' '.join(f'{x},{y}' for x, y in points),
|
|
497
|
+
fill='none', stroke=gp_value(self.gp,'col',series,self.color), stroke_width=gp_value(self.gp,'lwd',series,self.linewidth))
|
|
498
|
+
points.clear();raw_along.clear();raw_values.clear()
|
|
499
|
+
for i in panel.indices:
|
|
500
|
+
if series >= len(arrays[i]) or not np.isfinite(arrays[i][series]):
|
|
501
|
+
flush()
|
|
502
|
+
else:
|
|
503
|
+
raw_along.append(positions[i]);raw_values.append(arrays[i][series])
|
|
504
|
+
points.append(self._point(positions[i], (arrays[i][series]-lo)/(hi-lo),
|
|
505
|
+
cross, height, direction))
|
|
506
|
+
flush()
|
|
507
|
+
if self.add_points:
|
|
508
|
+
if self.pt_gp is None:
|
|
509
|
+
super()._render(f, values, panels, positions, cross, height, pixel, direction, font)
|
|
510
|
+
else:
|
|
511
|
+
import copy
|
|
512
|
+
markers=copy.copy(self);markers.gp=self.pt_gp;markers.color='black'
|
|
513
|
+
PointsAnnotation._render(markers,f,values,panels,positions,cross,height,pixel,direction,font)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
class HistogramAnnotation(_Track):
|
|
517
|
+
"""Per-item sample histograms: shared bin edges and globally scaled counts.
|
|
518
|
+
|
|
519
|
+
Samples lie along band depth; count controls width within each item slot.
|
|
520
|
+
``bins``/``n_breaks`` specify an integer number of equal-width bins.
|
|
521
|
+
"""
|
|
522
|
+
auto_height_ratio = 3.0
|
|
523
|
+
|
|
524
|
+
def __init__(self,x,*,bins=10,n_breaks=None,xlim=None,breaks=None,right=False,include_lowest=True,axis=True,**kwargs):
|
|
525
|
+
super().__init__(x,axis=axis,**kwargs)
|
|
526
|
+
self.bins = int(n_breaks)-1 if n_breaks is not None else int(bins)
|
|
527
|
+
if self.bins <= 0:
|
|
528
|
+
raise ValueError('bins must be positive')
|
|
529
|
+
_limits([], xlim, 'xlim')
|
|
530
|
+
self.xlim = xlim
|
|
531
|
+
self.breaks=None if breaks is None else np.asarray(breaks,float)
|
|
532
|
+
if self.breaks is not None and (self.breaks.ndim!=1 or len(self.breaks)<2 or not np.isfinite(self.breaks).all() or np.any(np.diff(self.breaks)<=0)):raise ValueError('breaks must be increasing finite edges')
|
|
533
|
+
self.right=bool(right);self.include_lowest=bool(include_lowest)
|
|
534
|
+
|
|
535
|
+
def _data_limits(self,values,explicit=None):
|
|
536
|
+
if self.breaks is not None:return float(self.breaks[0]),float(self.breaks[-1])
|
|
537
|
+
return _limits(values,self.xlim if explicit is None else explicit,'xlim')
|
|
538
|
+
|
|
539
|
+
def histogram_data(self,values=None):
|
|
540
|
+
values=list(self.df.iloc[:,0]) if values is None else values
|
|
541
|
+
lo,hi=_limits(values,self.xlim,'xlim')
|
|
542
|
+
edges=np.linspace(lo,hi,self.bins+1) if self.breaks is None else self.breaks.copy()
|
|
543
|
+
counts=[]
|
|
544
|
+
for value in values:
|
|
545
|
+
samples=_num(value)
|
|
546
|
+
if self.right:
|
|
547
|
+
ids=np.searchsorted(edges,samples,side='left')-1
|
|
548
|
+
if self.include_lowest:ids[samples==edges[0]]=0
|
|
549
|
+
ids=ids[(ids>=0)&(ids<len(edges)-1)]
|
|
550
|
+
count=np.bincount(ids,minlength=len(edges)-1)
|
|
551
|
+
else:count=np.histogram(samples,bins=edges)[0]
|
|
552
|
+
counts.append(count)
|
|
553
|
+
return {'breaks':edges,'counts':np.asarray(counts,dtype=int).reshape(len(values),len(edges)-1)}
|
|
554
|
+
|
|
555
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
556
|
+
from .graphics import gp_value
|
|
557
|
+
data=self.histogram_data(values);edges=data['breaks'];lo,hi=edges[[0,-1]]
|
|
558
|
+
counts={i:data['counts'][i] for i in positions}
|
|
559
|
+
maximum = max((int(c.max()) for c in counts.values()), default=1) or 1
|
|
560
|
+
for i, counts_i in counts.items():
|
|
561
|
+
for j, count in enumerate(counts_i):
|
|
562
|
+
if count == 0:
|
|
563
|
+
continue
|
|
564
|
+
p1 = self._point(positions[i] - .4 * pixel * count/maximum,
|
|
565
|
+
(edges[j]-lo)/(hi-lo), cross, height, direction)
|
|
566
|
+
p2 = self._point(positions[i] + .4 * pixel * count/maximum,
|
|
567
|
+
(edges[j+1]-lo)/(hi-lo), cross, height, direction)
|
|
568
|
+
_svg(f, 'rect', x=min(p1[0], p2[0]), y=min(p1[1], p2[1]),
|
|
569
|
+
width=abs(p2[0]-p1[0]), height=abs(p2[1]-p1[1]), fill=gp_value(self.gp,'fill',self._style_index(i),self.color),stroke=gp_value(self.gp,'col',self._style_index(i),'none'),stroke_width=gp_value(self.gp,'lwd',self._style_index(i),.5))
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
class DensityAnnotation(_Track):
|
|
573
|
+
"""Gaussian KDE curves per item; ``type='lines'`` or filled ``'violin'``.
|
|
574
|
+
|
|
575
|
+
KDE is evaluated on 64 shared support points; singleton/constant samples use
|
|
576
|
+
an explicit Gaussian fallback of 5% of the common range. No random jitter.
|
|
577
|
+
"""
|
|
578
|
+
auto_height_ratio = 3.0
|
|
579
|
+
|
|
580
|
+
def __init__(self,x,*,xlim=None,type='lines',bandwidth=None,axis=True,border=True,max_density=None,heatmap_colors=None,joyplot_scale=None,**kwargs):
|
|
581
|
+
if joyplot_scale is not None:
|
|
582
|
+
if isinstance(joyplot_scale,(bool,np.bool_)) or not isinstance(joyplot_scale,(int,float,np.integer,np.floating)) or not np.isfinite(joyplot_scale) or joyplot_scale<=0:raise ValueError('joyplot_scale must be positive finite')
|
|
583
|
+
if type!='lines' and joyplot_scale!=1:raise ValueError('joyplot_scale applies to density lines only')
|
|
584
|
+
self.joyplot_scale=None if joyplot_scale is None else float(joyplot_scale)
|
|
585
|
+
if type not in ('lines','violin','heatmap'):raise ValueError("type must be lines, violin or heatmap")
|
|
586
|
+
if max_density is not None and (not np.isfinite(max_density) or max_density<=0):raise ValueError('max_density must be positive and finite')
|
|
587
|
+
self.max_density=max_density
|
|
588
|
+
self.heatmap_colors=list(heatmap_colors) if heatmap_colors is not None else ['#313695','#4575b4','#74add1','#abd9e9','#e0f3f8','#ffffbf','#fee090','#fdae61','#f46d43','#d73027','#a50026']
|
|
589
|
+
if len(self.heatmap_colors)<2:raise ValueError('heatmap_colors needs at least two colors')
|
|
590
|
+
_limits([], xlim, 'xlim')
|
|
591
|
+
if bandwidth is not None and (not np.isfinite(bandwidth) or bandwidth <= 0):
|
|
592
|
+
raise ValueError('bandwidth must be finite and positive')
|
|
593
|
+
super().__init__(x,axis=axis,border=border,**kwargs)
|
|
594
|
+
self.xlim, self.type, self.bandwidth = xlim, type, bandwidth
|
|
595
|
+
|
|
596
|
+
def _estimate(self,values,positions):
|
|
597
|
+
from scipy.stats import gaussian_kde
|
|
598
|
+
lo,hi=_limits(values,self.xlim)
|
|
599
|
+
support=np.linspace(lo,hi,64)
|
|
600
|
+
densities={}
|
|
601
|
+
for i in positions:
|
|
602
|
+
samples=_num(values[i])
|
|
603
|
+
if not samples.size:continue
|
|
604
|
+
if samples.size>1 and np.ptp(samples)>0:
|
|
605
|
+
density=gaussian_kde(samples,bw_method=self.bandwidth)(support)
|
|
606
|
+
else:
|
|
607
|
+
sigma=self.bandwidth or (hi-lo)*.05
|
|
608
|
+
density=np.exp(-.5*((support-samples[0])/sigma)**2)/(sigma*np.sqrt(2*np.pi))
|
|
609
|
+
densities[i]=density
|
|
610
|
+
maximum=self.max_density or max((float(d.max()) for d in densities.values()),default=1) or 1
|
|
611
|
+
return support,densities,maximum
|
|
612
|
+
|
|
613
|
+
def _render(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
614
|
+
from .graphics import gp_value
|
|
615
|
+
support,densities,maximum=self._estimate(values,positions)
|
|
616
|
+
if self.type=='heatmap':
|
|
617
|
+
self._heatmap(f,panels,positions,densities,maximum,cross,height,pixel,direction)
|
|
618
|
+
return
|
|
619
|
+
for i,density in densities.items():
|
|
620
|
+
widths=.4*pixel*np.clip(density/maximum,0,1)
|
|
621
|
+
fill=gp_value(self.gp,'fill',self._style_index(i),self.color)
|
|
622
|
+
stroke=gp_value(self.gp,'col',self._style_index(i),self.color)
|
|
623
|
+
if self.type=='violin':
|
|
624
|
+
points=[self._point(positions[i]-widths[j],j/63,cross,height,direction) for j in range(64)]
|
|
625
|
+
points += [self._point(positions[i]+widths[j],j/63,cross,height,direction) for j in range(63,-1,-1)]
|
|
626
|
+
_svg(f,'polygon',points=' '.join(f'{x},{y}' for x,y in points),fill=fill,stroke=stroke,stroke_width=gp_value(self.gp,'lwd',self._style_index(i),.5))
|
|
627
|
+
else:
|
|
628
|
+
if self.joyplot_scale is not None:
|
|
629
|
+
widths=widths*self.joyplot_scale
|
|
630
|
+
owner=next((panel for panel in panels if i in panel.indices),None)
|
|
631
|
+
if owner is not None:
|
|
632
|
+
far=owner.y+owner.height if direction in ('left','right') else owner.x+owner.width
|
|
633
|
+
widths=np.minimum(widths,max(0,far-positions[i]))
|
|
634
|
+
points=[self._point(positions[i]+w,j/63,cross,height,direction) for j,w in enumerate(widths)]
|
|
635
|
+
_svg(f,'polyline',points=' '.join(f'{x},{y}' for x,y in points),stroke=stroke,fill='none',stroke_width=gp_value(self.gp,'lwd',self._style_index(i),1))
|
|
636
|
+
|
|
637
|
+
def _heatmap(self,f,panels,positions,densities,maximum,cross,height,pixel,direction):
|
|
638
|
+
import cv2
|
|
639
|
+
from .style import ColorMapping
|
|
640
|
+
minimum=0. if self.max_density is not None else min((float(d.min()) for d in densities.values()),default=0.)
|
|
641
|
+
if maximum<=minimum:maximum=minimum+1
|
|
642
|
+
cmap=ColorMapping(np.linspace(minimum,maximum,len(self.heatmap_colors)),self.heatmap_colors)
|
|
643
|
+
vertical=direction in ('left','right')
|
|
644
|
+
p0=self._point(0,0,cross,height,direction);p1=self._point(0,1,cross,height,direction)
|
|
645
|
+
low=min(p0[0],p1[0]) if vertical else min(p0[1],p1[1])
|
|
646
|
+
depth=abs(p1[0]-p0[0]) if vertical else abs(p1[1]-p0[1])
|
|
647
|
+
flip=(p1[0]<p0[0]) if vertical else (p1[1]<p0[1])
|
|
648
|
+
for panel in panels:
|
|
649
|
+
along=panel.y if vertical else panel.x
|
|
650
|
+
span=panel.height if vertical else panel.width
|
|
651
|
+
display=max(1,int(np.ceil(span)))
|
|
652
|
+
for tile in range(0,display,1024):
|
|
653
|
+
size=min(1024,display-tile)
|
|
654
|
+
selected=np.minimum(len(panel.indices)-1,((np.arange(tile,tile+size)+.5)*len(panel.indices)/display).astype(int))
|
|
655
|
+
profiles=np.asarray([densities.get(panel.indices[k],np.full(64,np.nan)) for k in selected])
|
|
656
|
+
if flip:profiles=profiles[:,::-1]
|
|
657
|
+
rgb=cmap(profiles,bytes=True)
|
|
658
|
+
if not vertical:rgb=rgb.transpose(1,0,2)
|
|
659
|
+
_,encoded=cv2.imencode('.png',np.ascontiguousarray(rgb[:,:,::-1]))
|
|
660
|
+
pos=along+tile*span/display;length=size*span/display
|
|
661
|
+
x,y,w,h=(low,pos,depth,length) if vertical else (pos,low,length,depth)
|
|
662
|
+
if hasattr(f,'write_image'):f.write_image(x,y,w,h,encoded.tobytes())
|
|
663
|
+
else:
|
|
664
|
+
data=base64.b64encode(encoded).decode()
|
|
665
|
+
f.write(f'<image x="{x}" y="{y}" width="{w}" height="{h}" preserveAspectRatio="none" href="data:image/png;base64,{data}"/>')
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
class JoyplotAnnotation(DensityAnnotation):
|
|
669
|
+
"""Filled overlapping KDE ridges, clipped at their heatmap slice boundary."""
|
|
670
|
+
def __init__(self,x,*,scale=2,transparency=.6,**kwargs):
|
|
671
|
+
if 'joyplot_scale' in kwargs:raise TypeError('joyplot_scale belongs to anno_density; use native joyplot scale')
|
|
672
|
+
if not np.isfinite(scale) or scale<=0:raise ValueError('scale must be positive and finite')
|
|
673
|
+
if not np.isfinite(transparency) or not 0<=transparency<=1:raise ValueError('transparency must lie in [0,1]')
|
|
674
|
+
self.scale=float(scale);self.transparency=float(transparency)
|
|
675
|
+
kwargs.setdefault('color','black');kwargs.setdefault('border',False)
|
|
676
|
+
super().__init__(x,**kwargs)
|
|
677
|
+
def _render(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
678
|
+
if self.type!='lines':return super()._render(f,values,panels,positions,cross,height,pixel,direction,font)
|
|
679
|
+
from .graphics import gp_value
|
|
680
|
+
_,densities,maximum=self._estimate(values,positions)
|
|
681
|
+
vertical=direction in ('left','right')
|
|
682
|
+
for panel in panels:
|
|
683
|
+
far=panel.y+panel.height if vertical else panel.x+panel.width
|
|
684
|
+
for i in panel.indices:
|
|
685
|
+
if i not in densities:continue
|
|
686
|
+
baseline=positions[i]-.4*pixel
|
|
687
|
+
widths=.8*pixel*self.scale*np.clip(densities[i]/maximum,0,1)
|
|
688
|
+
points=[self._point(baseline,0,cross,height,direction)]
|
|
689
|
+
points += [self._point(min(far,baseline+w),j/63,cross,height,direction) for j,w in enumerate(widths)]
|
|
690
|
+
points += [self._point(baseline,1,cross,height,direction)]
|
|
691
|
+
fill=gp_value(self.gp,'fill',self._style_index(i),self.color)
|
|
692
|
+
_svg(f,'polygon',points=' '.join(f'{x},{y}' for x,y in points),fill=fill,fill_opacity=1-self.transparency,stroke=gp_value(self.gp,'col',self._style_index(i),'none'),stroke_width=gp_value(self.gp,'lwd',self._style_index(i),1))
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
class TextAnnotation(_Track):
|
|
696
|
+
"""One escaped label per item, retaining centered native defaults.
|
|
697
|
+
|
|
698
|
+
``location`` is a cross-band fraction: left-to-right for row annotations,
|
|
699
|
+
bottom-to-top for column annotations. ``offset`` is its deprecated alias;
|
|
700
|
+
explicit location wins. ``just`` is a grid-style name or local x/y fraction
|
|
701
|
+
pair. Existing ``rot`` remains clockwise canvas degrees, not R grid degrees.
|
|
702
|
+
Locations can extend outside a band; its automatic thickness is unchanged.
|
|
703
|
+
"""
|
|
704
|
+
auto_height_ratio = 1.0
|
|
705
|
+
|
|
706
|
+
def __init__(self,x,*,rot=0,just=None,offset=None,location=None,**kwargs):
|
|
707
|
+
if type(self)._render is not TextAnnotation._render and any(v is not None for v in (just,offset,location)):
|
|
708
|
+
raise TypeError('just/offset/location apply to anno_text; this specialized text annotation uses its own positioning')
|
|
709
|
+
kwargs.setdefault('color','black')
|
|
710
|
+
super().__init__(x,**kwargs)
|
|
711
|
+
self.rot=float(rot)
|
|
712
|
+
if not np.isfinite(self.rot):raise ValueError('rot must be finite')
|
|
713
|
+
self.just=self._justification('center' if just is None else just)
|
|
714
|
+
self._text_just_side=just if isinstance(just,str) and just in ('left','right') else None
|
|
715
|
+
if offset is not None:self._fraction(offset,'offset')
|
|
716
|
+
self.location=self._fraction(location if location is not None else offset if offset is not None else .5,'location')
|
|
717
|
+
|
|
718
|
+
@staticmethod
|
|
719
|
+
def _fraction(value,label):
|
|
720
|
+
if isinstance(value,(bool,np.bool_)) or not isinstance(value,(int,float,np.integer,np.floating)) or not np.isfinite(value):
|
|
721
|
+
raise ValueError(label+' must be a finite numeric band fraction')
|
|
722
|
+
return float(value)
|
|
723
|
+
|
|
724
|
+
@staticmethod
|
|
725
|
+
def _justification(value):
|
|
726
|
+
"""Grid-style local text anchoring: left/bottom0, center.5, right/top1."""
|
|
727
|
+
if isinstance(value,str):
|
|
728
|
+
options={'left':(0.,.5),'right':(1.,.5),'bottom':(.5,0.),'top':(.5,1.),'center':(.5,.5),'centre':(.5,.5)}
|
|
729
|
+
if value not in options:raise ValueError('unknown text justification: '+value)
|
|
730
|
+
return options[value]
|
|
731
|
+
values=np.atleast_1d(value)
|
|
732
|
+
if values.ndim!=1 or len(values) not in (1,2):raise ValueError('justification must have one or two entries')
|
|
733
|
+
if all(isinstance(v,str) for v in values):
|
|
734
|
+
if len(values)!=2:raise ValueError('justification needs horizontal and vertical names')
|
|
735
|
+
horizontal={'left':0.,'center':.5,'centre':.5,'right':1.}
|
|
736
|
+
vertical={'bottom':0.,'center':.5,'centre':.5,'top':1.}
|
|
737
|
+
if values[0] not in horizontal or values[1] not in vertical:raise ValueError('invalid horizontal/vertical justification')
|
|
738
|
+
return horizontal[values[0]],vertical[values[1]]
|
|
739
|
+
result=[TextAnnotation._fraction(v,'justification') for v in values]
|
|
740
|
+
return (result[0],result[0]) if len(result)==1 else tuple(result)
|
|
741
|
+
|
|
742
|
+
@staticmethod
|
|
743
|
+
def _justify_position(x,y,text,size,just,rotation,a,bold=False,italic=False,family=None):
|
|
744
|
+
from .style import text_width
|
|
745
|
+
width=text_width(text,size,bold,family=family or a.font_family,italic=italic)
|
|
746
|
+
# Centered native glyphs shifted in their rotated local coordinate frame.
|
|
747
|
+
dx=(.5-just[0])*width;dy=(just[1]-.5)*size
|
|
748
|
+
theta=np.deg2rad(rotation)
|
|
749
|
+
return x+dx*np.cos(theta)-dy*np.sin(theta),y+dx*np.sin(theta)+dy*np.cos(theta)
|
|
750
|
+
|
|
751
|
+
def _text_style(self,i,a,font):
|
|
752
|
+
from .graphics import gp_value,font_face
|
|
753
|
+
index=self._style_index(i)
|
|
754
|
+
size=a.pt(float(gp_value(self.gp,'fontsize',index))) if self.fontsize is None and 'fontsize' in self.gp else font
|
|
755
|
+
bold,italic=font_face(gp_value(self.gp,'fontface',index,'plain'))
|
|
756
|
+
return size,gp_value(self.gp,'col',index,self.color),bold,italic
|
|
757
|
+
|
|
758
|
+
def _preferred_thickness(self,p):
|
|
759
|
+
from .text_boxes import _text_size
|
|
760
|
+
vertical=self.side in ('left','right');theta=np.deg2rad(self.rot)
|
|
761
|
+
font=self.resolved_fontsize(p);depth=0
|
|
762
|
+
if self.df is not None:
|
|
763
|
+
for i,value in enumerate(self.df.iloc[:,0]):
|
|
764
|
+
if value is None or pd.isna(value):continue
|
|
765
|
+
size,_,bold,italic=self._text_style(i,p._appearance,font)
|
|
766
|
+
width,h=_text_size(value,size,self._font_family(p._appearance.font_family),bold,italic);h=max(h,size)
|
|
767
|
+
depth=max(depth,abs(np.cos(theta))*width+abs(np.sin(theta))*h if vertical else abs(np.sin(theta))*width+abs(np.cos(theta))*h)
|
|
768
|
+
return max(depth,font)+p._appearance.mm(2)
|
|
769
|
+
|
|
770
|
+
def _render(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
771
|
+
from .style import Appearance
|
|
772
|
+
a=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
773
|
+
for i,along in positions.items():
|
|
774
|
+
v=values[i]
|
|
775
|
+
if v is None or pd.isna(v):continue
|
|
776
|
+
near=cross-height if direction in ('up','left') else cross
|
|
777
|
+
x,y=(near+self.location*height,along) if direction in ('left','right') else (along,near+(1-self.location)*height)
|
|
778
|
+
size,rgb,bold,italic=self._text_style(i,a,font)
|
|
779
|
+
if direction not in ('left','right') and self._text_just_side is not None:
|
|
780
|
+
# R anno_text adjusts the column location for the glyph height
|
|
781
|
+
# before applying named left/right justification. Native rot
|
|
782
|
+
# remains canvas-clockwise; convert only for this grid rule.
|
|
783
|
+
r_rotation=(-self.rot)%360
|
|
784
|
+
sign=(1 if self._text_just_side=='right' else -1)*(1 if r_rotation<180 else -1)
|
|
785
|
+
y+=sign*.5*size*abs(np.cos(np.deg2rad(r_rotation)))
|
|
786
|
+
x,y=self._justify_position(x,y,v,size,self.just,self.rot,a,bold,italic,family=self._font_family(a.font_family))
|
|
787
|
+
_text(f,x,y,v,size,rgb,self.rot,bold=bold,italic=italic,family=self._font_family())
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
class TextboxAnnotation(TextAnnotation):
|
|
791
|
+
"""Explicit newline-separated text; no automatic word wrapping/reflow."""
|
|
792
|
+
def _render(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
793
|
+
from .style import Appearance
|
|
794
|
+
a=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
795
|
+
for i,along in positions.items():
|
|
796
|
+
if values[i] is None or pd.isna(values[i]):continue
|
|
797
|
+
lines=str(values[i]).splitlines()
|
|
798
|
+
x,y=self._point(along,.5,cross,height,direction)
|
|
799
|
+
size,rgb,bold,italic=self._text_style(i,a,font)
|
|
800
|
+
for j,text in enumerate(lines):
|
|
801
|
+
_text(f,x,y+(j-(len(lines)-1)/2)*size*1.15,text,size,rgb,self.rot,bold=bold,italic=italic,family=self._font_family())
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
class MarkAnnotation(TextAnnotation):
|
|
805
|
+
"""Selected labels with bounded collision alignment and identity-safe styles.
|
|
806
|
+
|
|
807
|
+
Integer ``at`` positions are zero-based and require ``n``. Named positions
|
|
808
|
+
bind identifiers. Padding/link sizes/extend use mm; labels_rot follows R's
|
|
809
|
+
counterclockwise convention. Existing rot retains SVG canvas degrees.
|
|
810
|
+
"""
|
|
811
|
+
def __init__(self,at,labels,*,n=None,avoid_overlap=True,labels_gp=None,lines_gp=None,
|
|
812
|
+
link_gp=None,labels_rot=None,padding=1,link_width=5,link_height=None,
|
|
813
|
+
extend=0,**kwargs):
|
|
814
|
+
from .graphics import validate_gp
|
|
815
|
+
if not np.isfinite([padding,link_width,extend]).all() or min(padding,link_width,extend)<0:raise ValueError('mark spacing must be finite and nonnegative')
|
|
816
|
+
if link_height is not None and (not np.isfinite(link_height) or link_height<0):raise ValueError('link_height must be finite and nonnegative')
|
|
817
|
+
at,labels=list(at),list(labels)
|
|
818
|
+
if len(at)!=len(labels) or len(set(at))!=len(at):raise ValueError('at and labels must have equal length and unique positions')
|
|
819
|
+
positional=all(isinstance(v,(int,np.integer)) for v in at)
|
|
820
|
+
if positional:
|
|
821
|
+
if n is None:raise ValueError('n is required for integer positions')
|
|
822
|
+
if any(v<0 or v>=n for v in at):raise ValueError('mark position outside n items')
|
|
823
|
+
values=[None]*n
|
|
824
|
+
for i,text in zip(at,labels):values[i]=text
|
|
825
|
+
else:values=pd.Series(labels,index=at,dtype=object)
|
|
826
|
+
gp=kwargs.pop('gp',None)
|
|
827
|
+
kwargs['gp']=labels_gp if labels_gp is not None else gp if gp is not None else {'fontsize':9}
|
|
828
|
+
super().__init__(values,**kwargs)
|
|
829
|
+
if positional:
|
|
830
|
+
indices=np.zeros(n,dtype=int)
|
|
831
|
+
for k,i in enumerate(at):indices[i]=k
|
|
832
|
+
self._graphical_ids=pd.Series(indices,index=self.df.index.map(str))
|
|
833
|
+
self.avoid_overlap=bool(avoid_overlap);self.padding=float(padding);self.extend=float(extend)
|
|
834
|
+
self.link_width=float(link_width);self.link_height=float(link_width if link_height is None else link_height)
|
|
835
|
+
self.labels_rot=None if labels_rot is None else float(labels_rot)
|
|
836
|
+
if self.labels_rot is not None and not np.isfinite(self.labels_rot):raise ValueError('labels_rot must be finite')
|
|
837
|
+
self._explicit_rot='rot' in kwargs
|
|
838
|
+
self.lines_gp=validate_gp(lines_gp,{'col','lwd'});self.link_gp=validate_gp(link_gp if link_gp is not None else lines_gp,{'col','lwd'})
|
|
839
|
+
|
|
840
|
+
def _rotation(self,vertical):
|
|
841
|
+
if self.labels_rot is not None:return -self.labels_rot
|
|
842
|
+
return self.rot if self._explicit_rot else 0 if vertical else -90
|
|
843
|
+
|
|
844
|
+
def _preferred_thickness(self,p):
|
|
845
|
+
from .style import text_width
|
|
846
|
+
vertical=self.side in ('left','right');theta=np.deg2rad(self._rotation(vertical))
|
|
847
|
+
font=self.resolved_fontsize(p)
|
|
848
|
+
depths=[]
|
|
849
|
+
for i,v in enumerate(self.df.iloc[:,0]):
|
|
850
|
+
if v is None or pd.isna(v):continue
|
|
851
|
+
size,_,bold,italic=self._text_style(i,p._appearance,font)
|
|
852
|
+
width=text_width(v,size,bold,self._font_family(p._appearance.font_family),italic)
|
|
853
|
+
depths.append(abs(np.cos(theta))*width+abs(np.sin(theta))*size if vertical else abs(np.sin(theta))*width+abs(np.cos(theta))*size)
|
|
854
|
+
depth=max(depths,default=font)
|
|
855
|
+
return depth+p._appearance.mm(self.link_width if vertical else self.link_height)+p._appearance.mm(2)
|
|
856
|
+
|
|
857
|
+
def axis_padding(self,p):
|
|
858
|
+
padding=super().axis_padding(p)
|
|
859
|
+
# Fixed-width/height bands may be narrower than the actual mark text.
|
|
860
|
+
# Reserve its outward overflow so neighbouring legends stay clear.
|
|
861
|
+
height=p._annot_height(self)
|
|
862
|
+
if height>0:
|
|
863
|
+
overflow=max(0.,self._preferred_thickness(p)-height)
|
|
864
|
+
if overflow:padding[self.side]=max(padding.get(self.side,0),overflow)
|
|
865
|
+
if self.extend:
|
|
866
|
+
extent=p._appearance.mm(self.extend)
|
|
867
|
+
padding.update({side:max(padding.get(side,0),extent) for side in (('top','bottom') if self.side in ('left','right') else ('left','right'))})
|
|
868
|
+
return padding
|
|
869
|
+
|
|
870
|
+
def _render(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
871
|
+
import warnings
|
|
872
|
+
from .style import Appearance,text_width
|
|
873
|
+
from .graphics import gp_value
|
|
874
|
+
from .appearance import _text as put_text
|
|
875
|
+
from .text_layout import smartAlign2
|
|
876
|
+
p=getattr(f,'plotter',None);a=getattr(p,'_appearance',Appearance(96))
|
|
877
|
+
vertical=direction in ('left','right');rotation=self._rotation(vertical);theta=np.deg2rad(rotation)
|
|
878
|
+
sign=-1 if direction in ('up','left') else 1
|
|
879
|
+
link=a.mm(self.link_width if vertical else self.link_height)
|
|
880
|
+
label_cross=cross+sign*link
|
|
881
|
+
for panel in panels:
|
|
882
|
+
ids=[i for i in panel.indices if values[i] is not None and not pd.isna(values[i])]
|
|
883
|
+
if not ids:continue
|
|
884
|
+
labels=[str(values[i]) for i in ids]
|
|
885
|
+
styles=[self._text_style(i,a,font) for i in ids]
|
|
886
|
+
fonts=np.array([style[0] for style in styles])
|
|
887
|
+
widths=np.array([text_width(label,size,bold,self._font_family(a.font_family),italic) for label,(size,_,bold,italic) in zip(labels,styles)])
|
|
888
|
+
sizes=np.abs(np.sin(theta))*widths+abs(np.cos(theta))*fonts if vertical else abs(np.cos(theta))*widths+abs(np.sin(theta))*fonts
|
|
889
|
+
pad=a.mm(self.padding);ext=a.mm(self.extend)
|
|
890
|
+
start=(panel.y if vertical else panel.x)-ext;end=(panel.y+panel.height if vertical else panel.x+panel.width)+ext
|
|
891
|
+
anchors=np.asarray([positions[i] for i in ids])
|
|
892
|
+
if self.avoid_overlap:
|
|
893
|
+
if np.sum(sizes)+max(0,len(ids)-1)*pad>end-start:warnings.warn('mark labels exceed the available space; increase figure size, extend, or select fewer labels',UserWarning,stacklevel=2)
|
|
894
|
+
bounds=smartAlign2(anchors-(sizes+pad)/2,anchors+(sizes+pad)/2,range=[start,end])
|
|
895
|
+
aligned=bounds.mean(axis=1).to_numpy()
|
|
896
|
+
else:aligned=anchors
|
|
897
|
+
for k,i in enumerate(ids):
|
|
898
|
+
style=self._style_index(i)
|
|
899
|
+
first=self._point(positions[i],0,cross,height,direction)
|
|
900
|
+
middle=(cross+sign*link/2,positions[i]) if vertical else (positions[i],cross+sign*link/2)
|
|
901
|
+
last=(label_cross,aligned[k]) if vertical else (aligned[k],label_cross)
|
|
902
|
+
for begin,finish,gp in ((first,middle,self.lines_gp),(middle,last,self.link_gp)):
|
|
903
|
+
_svg(f,'line',x1=begin[0],y1=begin[1],x2=finish[0],y2=finish[1],stroke=gp_value(gp,'col',style,'black'),stroke_width=a.pt(float(gp_value(gp,'lwd',style,.75))))
|
|
904
|
+
anchor='end' if direction in ('left','down') else 'start'
|
|
905
|
+
size,rgb,bold,italic=styles[k]
|
|
906
|
+
put_text(f,last[0],last[1],labels[k],size,anchor,rotation=rotation or None,color=rgb,bold=bold,italic=italic,family=self._font_family(None))
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
class BlockAnnotation(_Track):
|
|
910
|
+
"""Contiguous groups or heatmap slices, with optional native panel callbacks.
|
|
911
|
+
|
|
912
|
+
Existing group-vector behavior is retained. Omitting groups with n creates
|
|
913
|
+
one block per displayed slice. align_to uses the ZoomAnnotation identity
|
|
914
|
+
mapping but fragmented runs stay separate, never bridging split gaps.
|
|
915
|
+
``labels_offset`` is a cross-band fraction and ``labels_just`` uses local
|
|
916
|
+
text justification. ``labels_rot`` retains counterclockwise R-style degrees.
|
|
917
|
+
"""
|
|
918
|
+
def __init__(self,groups=None,*,n=None,align_to=None,labels=None,colors=None,
|
|
919
|
+
panel_fun=None,labels_gp=None,labels_rot=None,labels_offset=.5,labels_just='center',**kwargs):
|
|
920
|
+
if align_to is not None:
|
|
921
|
+
if groups is not None:raise ValueError('provide groups or align_to')
|
|
922
|
+
groups=ZoomAnnotation(align_to,n=n).df.iloc[:,0]
|
|
923
|
+
if all(isinstance(i,(int,np.integer)) for v in align_to.values() for i in v):groups=groups.tolist()
|
|
924
|
+
self._slice_mode=groups is None
|
|
925
|
+
if groups is None:
|
|
926
|
+
if n is not None and (not isinstance(n,int) or n<0):raise ValueError('n must be a nonnegative integer')
|
|
927
|
+
groups=None if n is None else [0]*n
|
|
928
|
+
if panel_fun is not None and not callable(panel_fun):raise TypeError('panel_fun must be callable')
|
|
929
|
+
self._automatic_labels_rot=labels_rot is None
|
|
930
|
+
if labels_rot is None:labels_rot=90 if kwargs.get('which')=='row' or kwargs.get('side') in ('left','right') else 0
|
|
931
|
+
if not np.isfinite(labels_rot):raise ValueError('labels_rot must be finite')
|
|
932
|
+
from .graphics import validate_gp
|
|
933
|
+
self.labels_gp=validate_gp(labels_gp,{'col','fontsize','fontface'})
|
|
934
|
+
self.labels_rot=float(labels_rot);self.panel_fun=panel_fun
|
|
935
|
+
self.labels_offset=TextAnnotation._fraction(labels_offset,'labels_offset')
|
|
936
|
+
self.labels_just=TextAnnotation._justification(labels_just)
|
|
937
|
+
super().__init__(groups,**kwargs)
|
|
938
|
+
self.labels,self.colors=labels,colors or {}
|
|
939
|
+
self._show_legend=False
|
|
940
|
+
|
|
941
|
+
def _render(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
942
|
+
from .graphics import gp_value,font_face
|
|
943
|
+
from .style import Appearance
|
|
944
|
+
a=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
945
|
+
run_number=0
|
|
946
|
+
for slice_number,panel in enumerate(panels):
|
|
947
|
+
runs=[]
|
|
948
|
+
if self._slice_mode:runs=[list(panel.indices)]
|
|
949
|
+
else:
|
|
950
|
+
for i in panel.indices:
|
|
951
|
+
if pd.isna(values[i]):continue
|
|
952
|
+
if runs and runs[-1][-1]==i-1 and values[runs[-1][0]]==values[i]:runs[-1].append(i)
|
|
953
|
+
else:runs.append([i])
|
|
954
|
+
lookup=dict(zip(panel.indices,panel.names))
|
|
955
|
+
for run in runs:
|
|
956
|
+
group=slice_number if self._slice_mode else values[run[0]]
|
|
957
|
+
start=positions[run[0]]-pixel/2;span=len(run)*pixel
|
|
958
|
+
near=cross-height if direction in ('up','left') else cross
|
|
959
|
+
box=(near,start,height,span) if direction in ('left','right') else (start,near,span,height)
|
|
960
|
+
ctx=AnnotationPanel(f,*box,tuple(run),tuple(lookup[i] for i in run),tuple(values[i] for i in run),direction,font,group,fontfamily=self._font_family())
|
|
961
|
+
if self.panel_fun is not None:self.panel_fun(ctx)
|
|
962
|
+
else:
|
|
963
|
+
fill=gp_value(self.gp,'fill',run_number,self.colors.get(group,self.color))
|
|
964
|
+
ctx.rect(fill=fill,stroke=gp_value(self.gp,'col',run_number,'none'),stroke_width=gp_value(self.gp,'lwd',run_number,1))
|
|
965
|
+
if self.labels is not False:
|
|
966
|
+
if isinstance(self.labels,dict):label=self.labels.get(group,group)
|
|
967
|
+
elif isinstance(self.labels,(list,tuple,np.ndarray)):
|
|
968
|
+
if run_number>=len(self.labels):raise ValueError('block labels need one entry per displayed block')
|
|
969
|
+
label=self.labels[run_number]
|
|
970
|
+
else:label=group
|
|
971
|
+
bold,italic=font_face(gp_value(self.labels_gp,'fontface',run_number,'plain'))
|
|
972
|
+
size=a.pt(float(gp_value(self.labels_gp,'fontsize',run_number))) if 'fontsize' in self.labels_gp else font
|
|
973
|
+
x,y=(ctx.x+self.labels_offset*ctx.width,ctx.y+ctx.height/2) if direction in ('left','right') else (ctx.x+ctx.width/2,ctx.y+(1-self.labels_offset)*ctx.height)
|
|
974
|
+
rotation=(90 if direction in ('left','right') else 0) if self._automatic_labels_rot else self.labels_rot
|
|
975
|
+
x,y=TextAnnotation._justify_position(x,y,label,size,self.labels_just,-rotation,a,bold,italic,family=self._font_family(a.font_family))
|
|
976
|
+
_text(f,x,y,label,size,gp_value(self.labels_gp,'col',run_number,'#222222'),-rotation,bold=bold,italic=italic,family=self._font_family())
|
|
977
|
+
run_number+=1
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
class NumericAnnotation(PointsAnnotation):
|
|
981
|
+
"""Per-item numeric bars and labels (also supports columns as a Python extension).
|
|
982
|
+
|
|
983
|
+
``rg`` maps to the bar scale; ``formatter`` takes a scalar and returns text.
|
|
984
|
+
Explicit x_convert/labels_format receive private vectors of native per-item
|
|
985
|
+
means; labels format original values before conversion. align_to chooses
|
|
986
|
+
left/right/zero anchoring. labels_offset and r use mm; bar_width is an item
|
|
987
|
+
fraction. Omitted controls retain the native zero-baseline centered labels.
|
|
988
|
+
"""
|
|
989
|
+
def __init__(self, x, *, rg=None, formatter=None, x_convert=None, labels_gp=None,
|
|
990
|
+
labels_format=None, labels_offset=None, bg_gp=None, bar_width=None,
|
|
991
|
+
round_corners=None, r=None, align_to=None, **kwargs):
|
|
992
|
+
controls=(x_convert,labels_gp,labels_format,labels_offset,bg_gp,bar_width,round_corners,r,align_to)
|
|
993
|
+
if type(self)._render is not NumericAnnotation._render and any(v is not None for v in controls):
|
|
994
|
+
raise TypeError('numeric controls apply to anno_numeric; specialized summary rendering uses its own controls')
|
|
995
|
+
if x_convert is not None and not callable(x_convert):raise TypeError('x_convert must be callable(vector)')
|
|
996
|
+
if labels_format is not None and not callable(labels_format):raise TypeError('labels_format must be callable(vector)')
|
|
997
|
+
if formatter is not None and not callable(formatter):raise TypeError('formatter must be callable(scalar)')
|
|
998
|
+
if formatter is not None and labels_format is not None:raise TypeError('formatter and labels_format conflict')
|
|
999
|
+
from .graphics import validate_gp
|
|
1000
|
+
self.labels_gp=validate_gp(labels_gp,{'col','fontsize','fontface'})
|
|
1001
|
+
self.bg_gp=validate_gp(bg_gp,{'fill','col','lwd'})
|
|
1002
|
+
self._numeric_controls=any(v is not None for v in controls)
|
|
1003
|
+
self.x_convert,self.labels_format=x_convert,labels_format
|
|
1004
|
+
self.labels_offset=None if labels_offset is None else TextAnnotation._fraction(labels_offset,'labels_offset')
|
|
1005
|
+
if self.labels_offset is not None and self.labels_offset<0:raise ValueError('labels_offset must be nonnegative mm')
|
|
1006
|
+
self.bar_width=.7 if bar_width is None else TextAnnotation._fraction(bar_width,'bar_width')
|
|
1007
|
+
if not 0<self.bar_width<=1:raise ValueError('bar_width must be an item fraction in (0,1]')
|
|
1008
|
+
if round_corners is not None and not isinstance(round_corners,(bool,np.bool_)):raise TypeError('round_corners must be boolean')
|
|
1009
|
+
if r is not None and round_corners is not None and not round_corners:raise ValueError('r conflicts with round_corners=False')
|
|
1010
|
+
self.round_corners=bool(round_corners) if round_corners is not None else r is not None
|
|
1011
|
+
self.corner_radius=.5 if r is None else TextAnnotation._fraction(r,'r')
|
|
1012
|
+
if self.corner_radius<0:raise ValueError('r must be nonnegative mm')
|
|
1013
|
+
if align_to is not None and (isinstance(align_to,(bool,np.bool_)) or align_to not in ('left','right',0)):raise ValueError('align_to must be left, right or numeric zero')
|
|
1014
|
+
self.align_to=align_to
|
|
1015
|
+
kwargs.setdefault('axis',False);kwargs.setdefault('border',False);kwargs.setdefault('extend',0)
|
|
1016
|
+
super().__init__(x, ylim=rg, **kwargs)
|
|
1017
|
+
if self._numeric_controls and (self.axis or self.background) and (self.align_to is not None or self.x_convert is not None):
|
|
1018
|
+
raise ValueError('transformed/aligned numeric bars do not support the inherited point-axis scale')
|
|
1019
|
+
self.formatter = formatter or (lambda v: f'{v:g}')
|
|
1020
|
+
|
|
1021
|
+
def _converted_values(self,values):
|
|
1022
|
+
original=np.asarray([float(v.mean()) if len(v) else np.nan for v in map(_num,values)])
|
|
1023
|
+
lo,hi=self._data_limits(values,self.ylim)
|
|
1024
|
+
converted=original.copy()
|
|
1025
|
+
if self.x_convert is not None:
|
|
1026
|
+
def convert(vector):
|
|
1027
|
+
result=np.asarray(self.x_convert(vector.copy()),dtype=float)
|
|
1028
|
+
if result.shape!=vector.shape or np.any(~np.isfinite(result[np.isfinite(vector)])):
|
|
1029
|
+
raise ValueError('x_convert must return a finite same-length numeric vector for finite inputs')
|
|
1030
|
+
return result
|
|
1031
|
+
converted=convert(original)
|
|
1032
|
+
limits=convert(np.array([lo,hi]));lo,hi=float(limits.min()),float(limits.max())
|
|
1033
|
+
if hi<=lo:raise ValueError('x_convert must give distinct transformed rg endpoints')
|
|
1034
|
+
if self.align_to==0 and not lo<=0<=hi:raise ValueError('align_to=0 requires a range containing zero')
|
|
1035
|
+
return original,converted,lo,hi
|
|
1036
|
+
|
|
1037
|
+
def _labels(self,original):
|
|
1038
|
+
if self.labels_format is None:return [self.formatter(v) if np.isfinite(v) else None for v in original]
|
|
1039
|
+
labels=self.labels_format(original.copy())
|
|
1040
|
+
if isinstance(labels,(str,bytes)) or np.ndim(labels)!=1 or len(labels)!=len(original):raise ValueError('labels_format must return one label per input value')
|
|
1041
|
+
return list(labels)
|
|
1042
|
+
|
|
1043
|
+
def _preferred_thickness(self,p):
|
|
1044
|
+
# Defining this hook must retain the original automatic 10mm band when
|
|
1045
|
+
# all new controls are omitted, including specialized summary tracks.
|
|
1046
|
+
a=p._appearance
|
|
1047
|
+
if not self._numeric_controls:return a.mm(getattr(self,'_default_height_mm',10))
|
|
1048
|
+
from .graphics import gp_value,font_face
|
|
1049
|
+
from .style import text_width
|
|
1050
|
+
values=[] if self.df is None else list(self.df.iloc[:,0])
|
|
1051
|
+
original=np.asarray([float(v.mean()) if len(v) else np.nan for v in map(_num,values)])
|
|
1052
|
+
labels=self._labels(original);font=self.resolved_fontsize(p);extent=0.
|
|
1053
|
+
for i,label in enumerate(labels):
|
|
1054
|
+
if not np.isfinite(original[i]):continue
|
|
1055
|
+
index=self._style_index(i)
|
|
1056
|
+
size=a.pt(float(gp_value(self.labels_gp,'fontsize',index))) if 'fontsize' in self.labels_gp else font
|
|
1057
|
+
bold,italic=font_face(gp_value(self.labels_gp,'fontface',index,'plain'))
|
|
1058
|
+
extent=max(extent,text_width(label,size,bold,family=self._font_family(a.font_family),italic=italic) if self.side in ('left','right') else size)
|
|
1059
|
+
offset=0 if self.labels_offset is None and self.align_to is None else a.mm(self.labels_offset if self.labels_offset is not None else 4*25.4/72)
|
|
1060
|
+
# Zero-aligned labels can occupy opposite halves of the band.
|
|
1061
|
+
needed=(2*extent+4*offset) if self.align_to==0 else extent+2*offset
|
|
1062
|
+
return max(a.mm(getattr(self,'_default_height_mm',10)),needed)
|
|
1063
|
+
|
|
1064
|
+
@staticmethod
|
|
1065
|
+
def _rounded_bar(f,x,y,w,h,r,style):
|
|
1066
|
+
radius=min(r,w/2,h/2)
|
|
1067
|
+
if radius<=0:
|
|
1068
|
+
_svg(f,'rect',x=x,y=y,width=w,height=h,**style);return
|
|
1069
|
+
points=[]
|
|
1070
|
+
for cx,cy,start in ((x+radius,y+radius,270),(x+w-radius,y+radius,270),(x+w-radius,y+h-radius,0),(x+radius,y+h-radius,90),(x+radius,y+radius,180)):
|
|
1071
|
+
angles=[start] if not points else np.linspace(start,start+90,9)
|
|
1072
|
+
points.extend((cx+radius*np.cos(np.deg2rad(theta)),cy+radius*np.sin(np.deg2rad(theta))) for theta in angles)
|
|
1073
|
+
_svg(f,'polygon',points=' '.join(f'{xx},{yy}' for xx,yy in points),**style)
|
|
1074
|
+
|
|
1075
|
+
def _render_controls(self,f,values,panels,positions,cross,height,pixel,direction,font):
|
|
1076
|
+
from .graphics import gp_value,font_face
|
|
1077
|
+
from .style import Appearance
|
|
1078
|
+
a=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
1079
|
+
original,converted,lo,hi=self._converted_values(values)
|
|
1080
|
+
labels=self._labels(original)
|
|
1081
|
+
vertical=direction in ('left','right');near=cross-height if direction in ('left','up') else cross
|
|
1082
|
+
def point(along,fraction):
|
|
1083
|
+
if self.align_to is None:return self._point(along,fraction,cross,height,direction)
|
|
1084
|
+
coordinate=near+np.clip(fraction,0,1)*height
|
|
1085
|
+
return (coordinate,along) if vertical else (along,near+(1-np.clip(fraction,0,1))*height)
|
|
1086
|
+
for i,along in positions.items():
|
|
1087
|
+
if not np.isfinite(original[i]):continue
|
|
1088
|
+
value=np.clip(converted[i],lo,hi);fraction=(value-lo)/(hi-lo)
|
|
1089
|
+
if self.align_to=='left':start,end=0,fraction
|
|
1090
|
+
elif self.align_to=='right':start,end=1-fraction,1
|
|
1091
|
+
else:start,end=(np.clip(0,lo,hi)-lo)/(hi-lo),fraction
|
|
1092
|
+
p1=point(along-self.bar_width*pixel/2,start);p2=point(along+self.bar_width*pixel/2,end)
|
|
1093
|
+
x,y=min(p1[0],p2[0]),min(p1[1],p2[1]);w,h=abs(p1[0]-p2[0]),abs(p1[1]-p2[1])
|
|
1094
|
+
index=self._style_index(i)
|
|
1095
|
+
style=dict(fill=gp_value(self.bg_gp,'fill',index,self.color),stroke=gp_value(self.bg_gp,'col',index,'none'),stroke_width=gp_value(self.bg_gp,'lwd',index,1))
|
|
1096
|
+
if self.round_corners:self._rounded_bar(f,x,y,w,h,a.mm(self.corner_radius),style)
|
|
1097
|
+
else:_svg(f,'rect',x=x,y=y,width=w,height=h,**style)
|
|
1098
|
+
size=a.pt(float(gp_value(self.labels_gp,'fontsize',index))) if 'fontsize' in self.labels_gp else font
|
|
1099
|
+
bold,italic=font_face(gp_value(self.labels_gp,'fontface',index,'plain'))
|
|
1100
|
+
anchor=(.5,.5)
|
|
1101
|
+
if self.align_to is None and self.labels_offset is None:x,y=self._point(along,.5,cross,height,direction)
|
|
1102
|
+
else:
|
|
1103
|
+
offset=a.mm(self.labels_offset if self.labels_offset is not None else 4*25.4/72)
|
|
1104
|
+
target=0 if self.align_to=='left' else 1 if self.align_to=='right' else (np.clip(0,lo,hi)-lo)/(hi-lo)
|
|
1105
|
+
x,y=point(along,target);sign=-1 if self.align_to=='right' or self.align_to not in ('left','right') and value<=0 else 1
|
|
1106
|
+
if self.align_to is None:
|
|
1107
|
+
# Native growth direction depends on band side *and* axis
|
|
1108
|
+
# reversal. Anchor the label toward the bar from zero using
|
|
1109
|
+
# the actual coordinate derivative, not a fixed direction.
|
|
1110
|
+
coordinate=0 if vertical else 1
|
|
1111
|
+
derivative=point(along,1)[coordinate]-point(along,0)[coordinate]
|
|
1112
|
+
movement=sign*np.sign(derivative)
|
|
1113
|
+
if vertical:x+=movement*offset;anchor=(1.,.5) if movement<0 else (0.,.5)
|
|
1114
|
+
else:y+=movement*offset;anchor=(.5,0.) if movement<0 else (.5,1.)
|
|
1115
|
+
elif vertical:x+=sign*offset;anchor=(1.,.5) if sign<0 else (0.,.5)
|
|
1116
|
+
else:y-=sign*offset;anchor=(.5,0.) if sign<0 else (.5,1.)
|
|
1117
|
+
label=labels[i]
|
|
1118
|
+
x,y=TextAnnotation._justify_position(x,y,label,size,anchor,0,a,bold,italic,family=self._font_family(a.font_family))
|
|
1119
|
+
_text(f,x,y,label,size,gp_value(self.labels_gp,'col',index,'#222222'),bold=bold,italic=italic,family=self._font_family())
|
|
1120
|
+
|
|
1121
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
1122
|
+
if self._numeric_controls:return self._render_controls(f,values,panels,positions,cross,height,pixel,direction,font)
|
|
1123
|
+
lo, hi = self._data_limits(values, self.ylim)
|
|
1124
|
+
for i, along in positions.items():
|
|
1125
|
+
samples = _num(values[i])
|
|
1126
|
+
if samples.size == 0:
|
|
1127
|
+
continue
|
|
1128
|
+
v = float(samples.mean())
|
|
1129
|
+
p1 = self._point(along-.35*pixel, (np.clip(0,lo,hi)-lo)/(hi-lo), cross, height, direction)
|
|
1130
|
+
p2 = self._point(along+.35*pixel, (v-lo)/(hi-lo), cross, height, direction)
|
|
1131
|
+
_svg(f, 'rect', x=min(p1[0],p2[0]), y=min(p1[1],p2[1]),
|
|
1132
|
+
width=abs(p2[0]-p1[0]), height=abs(p2[1]-p1[1]), fill=self.color)
|
|
1133
|
+
x, y = self._point(along, .5, cross, height, direction)
|
|
1134
|
+
_text(f, x, y, self.formatter(v), font, '#222222',family=self._font_family())
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
class SummaryAnnotation(NumericAnnotation):
|
|
1138
|
+
"""Mean/median/min/max/sum bars from explicit item samples or finalized heatmap.
|
|
1139
|
+
|
|
1140
|
+
This is a numeric item summary, not R's categorical within-slice proportions
|
|
1141
|
+
or its within-slice boxplot summary. Those semantics remain unsupported.
|
|
1142
|
+
"""
|
|
1143
|
+
def __init__(self, x=None, *, agg='mean', show_labels=False, **kwargs):
|
|
1144
|
+
if agg not in ('mean', 'median', 'min', 'max', 'sum'):
|
|
1145
|
+
raise ValueError('unsupported agg')
|
|
1146
|
+
super().__init__(x, **kwargs)
|
|
1147
|
+
self.agg, self.show_labels = agg, show_labels
|
|
1148
|
+
|
|
1149
|
+
def _items(self, renderer, vertical, n):
|
|
1150
|
+
values, names = super()._items(renderer, vertical, n)
|
|
1151
|
+
result = []
|
|
1152
|
+
for v in values:
|
|
1153
|
+
samples = _num(v)
|
|
1154
|
+
result.append(getattr(np, self.agg)(samples) if samples.size else np.nan)
|
|
1155
|
+
return result, names
|
|
1156
|
+
|
|
1157
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
1158
|
+
if self.show_labels:
|
|
1159
|
+
return super()._render(f, values, panels, positions, cross, height, pixel, direction, font)
|
|
1160
|
+
# Reuse the numeric drawing while omitting its label fragments.
|
|
1161
|
+
class NoText:
|
|
1162
|
+
def write(_, fragment):
|
|
1163
|
+
if not fragment.startswith('<text'):
|
|
1164
|
+
f.write(fragment)
|
|
1165
|
+
super()._render(NoText(), values, panels, positions, cross, height, pixel, direction, font)
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
class ImageAnnotation(_Track):
|
|
1169
|
+
"""Embed local paths or Pillow images as PNG; missing items reserve empty slots.
|
|
1170
|
+
|
|
1171
|
+
Images preserve aspect ratio via explicit fitted geometry; no remote fetch or
|
|
1172
|
+
image format pass-through is performed. Pillow supported local formats work.
|
|
1173
|
+
Explicit ``space`` reserves physical mm on every slot edge before fitting;
|
|
1174
|
+
a four-vector selects top, right, bottom and left margins independently.
|
|
1175
|
+
the native omitted default remains zero. Infeasible margins raise at draw.
|
|
1176
|
+
"""
|
|
1177
|
+
def __init__(self, image, *, space=0, **kwargs):
|
|
1178
|
+
super().__init__(image, **kwargs)
|
|
1179
|
+
if np.ndim(space)==0:
|
|
1180
|
+
self.space=TextAnnotation._fraction(space,'space')
|
|
1181
|
+
margins=(self.space,)*4
|
|
1182
|
+
else:
|
|
1183
|
+
if np.ndim(space)!=1 or len(space)!=4:
|
|
1184
|
+
raise ValueError('space must be a scalar or four top/right/bottom/left margins in mm')
|
|
1185
|
+
margins=tuple(TextAnnotation._fraction(v,'space') for v in space)
|
|
1186
|
+
self.space=margins
|
|
1187
|
+
if any(v<0 for v in margins):raise ValueError('space must be nonnegative physical mm')
|
|
1188
|
+
|
|
1189
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
1190
|
+
for i, along in positions.items():
|
|
1191
|
+
value = values[i]
|
|
1192
|
+
if value is None or (isinstance(value, float) and np.isnan(value)):
|
|
1193
|
+
continue
|
|
1194
|
+
if isinstance(value, Image.Image):
|
|
1195
|
+
image = value.copy()
|
|
1196
|
+
else:
|
|
1197
|
+
with Image.open(Path(value)) as loaded:
|
|
1198
|
+
image = loaded.copy()
|
|
1199
|
+
limit_w, limit_h = (height, pixel) if direction in ('left', 'right') else (pixel, height)
|
|
1200
|
+
from .style import Appearance
|
|
1201
|
+
a=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
1202
|
+
margins=(self.space,)*4 if np.ndim(self.space)==0 else self.space
|
|
1203
|
+
top,right,bottom,left=map(a.mm,margins)
|
|
1204
|
+
limit_w-=left+right;limit_h-=top+bottom
|
|
1205
|
+
if min(limit_w,limit_h)<=0:raise ValueError('image space leaves no positive area in the annotation slot')
|
|
1206
|
+
scale = min(limit_w / image.width, limit_h / image.height)
|
|
1207
|
+
w, h = image.width*scale, image.height*scale
|
|
1208
|
+
x, y = self._point(along, .5, cross, height, direction)
|
|
1209
|
+
x+=(left-right)/2;y+=(top-bottom)/2
|
|
1210
|
+
buf = BytesIO()
|
|
1211
|
+
image.save(buf, format='PNG')
|
|
1212
|
+
uri = 'data:image/png;base64,' + base64.b64encode(buf.getvalue()).decode('ascii')
|
|
1213
|
+
_svg(f, 'image', x=x-w/2, y=y-h/2, width=w, height=h, href=uri)
|
|
1214
|
+
|
|
1215
|
+
|
|
1216
|
+
class EmptyAnnotation(_Track):
|
|
1217
|
+
"""Reserve a band; explicit zoom equalizes slice panels with native links.
|
|
1218
|
+
|
|
1219
|
+
Zoom reserves 35% of the band for correspondence lines, retaining the total
|
|
1220
|
+
thickness and along-axis gap. Omitted/False uses the original geometry.
|
|
1221
|
+
"""
|
|
1222
|
+
def __init__(self,*args,zoom=False,**kwargs):
|
|
1223
|
+
if not isinstance(zoom,(bool,np.bool_)):raise TypeError('zoom must be boolean')
|
|
1224
|
+
super().__init__(*args,**kwargs)
|
|
1225
|
+
self.zoom=bool(zoom)
|
|
1226
|
+
|
|
1227
|
+
def draw(self,f,start_x,start_y,pixel_size,bounds,gap_pixels,direction,renderer):
|
|
1228
|
+
active=[(a,b) for a,b in bounds if b>a]
|
|
1229
|
+
if not self.zoom or len(active)<2:
|
|
1230
|
+
return super().draw(f,start_x,start_y,pixel_size,bounds,gap_pixels,direction,renderer)
|
|
1231
|
+
if direction not in ('up','down','left','right'):raise ValueError('invalid empty zoom direction')
|
|
1232
|
+
import copy
|
|
1233
|
+
height=float(self.height if self.height is not None else renderer._auto_annot_height(self) if hasattr(renderer,'_auto_annot_height') else _resolve_height(renderer,self))
|
|
1234
|
+
if height==0:return
|
|
1235
|
+
vertical=direction in ('left','right');sign=-1 if direction in ('up','left') else 1
|
|
1236
|
+
cross=float(start_x if vertical else start_y);along=float(start_y if vertical else start_x)
|
|
1237
|
+
span=sum(b-a for a,b in active)*pixel_size/len(active)
|
|
1238
|
+
shadow=copy.copy(self);shadow.height=height*.65;shadow._zoom_height_float=shadow.height
|
|
1239
|
+
near=cross+sign*height*.35
|
|
1240
|
+
# Base draw handles borders, names and physical styles on a private copy.
|
|
1241
|
+
super(EmptyAnnotation,shadow).draw(f,near if vertical else start_x,
|
|
1242
|
+
start_y if vertical else near,span,[(i,i+1) for i in range(len(active))],
|
|
1243
|
+
gap_pixels,direction,renderer)
|
|
1244
|
+
source=target=along
|
|
1245
|
+
for slice_index,(a,b) in enumerate(active):
|
|
1246
|
+
length=(b-a)*pixel_size
|
|
1247
|
+
for origin,destination in ((source,target),(source+length,target+span)):
|
|
1248
|
+
_svg(f,'line',x1=cross if vertical else origin,y1=origin if vertical else cross,
|
|
1249
|
+
x2=near if vertical else destination,y2=destination if vertical else near,
|
|
1250
|
+
stroke=self.color,stroke_width=.75)
|
|
1251
|
+
source+=length+gap_at(gap_pixels,slice_index);target+=span+gap_at(gap_pixels,slice_index)
|
|
1252
|
+
|
|
1253
|
+
def _items(self, renderer, vertical, n):
|
|
1254
|
+
return [None]*n, tuple(range(n))
|
|
1255
|
+
|
|
1256
|
+
def _render(self, *args):
|
|
1257
|
+
pass
|
|
1258
|
+
|
|
1259
|
+
|
|
1260
|
+
class CustomAnnotation(_Track):
|
|
1261
|
+
"""Run ``panel_fun(context)`` once per item, with no hidden viewport state."""
|
|
1262
|
+
def __init__(self, x=None, *, panel_fun: Callable=None, graphics=None, **kwargs):
|
|
1263
|
+
if graphics is not None:
|
|
1264
|
+
from collections.abc import Mapping
|
|
1265
|
+
if panel_fun is not None:raise TypeError('graphics conflicts with panel_fun')
|
|
1266
|
+
if not isinstance(graphics,Mapping):raise TypeError('graphics must be a mapping of categories to callable functions')
|
|
1267
|
+
if any(not callable(fun) for fun in graphics.values()):raise TypeError('every graphics entry must be callable')
|
|
1268
|
+
self.graphics=dict(graphics)
|
|
1269
|
+
panel_fun=self._category_panel
|
|
1270
|
+
if not callable(panel_fun):
|
|
1271
|
+
raise TypeError('panel_fun must be callable')
|
|
1272
|
+
super().__init__(x, **kwargs)
|
|
1273
|
+
self.panel_fun = panel_fun
|
|
1274
|
+
|
|
1275
|
+
def _category_panel(self,context):
|
|
1276
|
+
value=context.values[0]
|
|
1277
|
+
try:callback=self.graphics.get(value)
|
|
1278
|
+
except TypeError:raise TypeError('graphics category values must be hashable scalars') from None
|
|
1279
|
+
if callback is not None:callback(context)
|
|
1280
|
+
|
|
1281
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
1282
|
+
for panel in panels:
|
|
1283
|
+
for j, i in enumerate(panel.indices):
|
|
1284
|
+
along = positions[i]-pixel/2
|
|
1285
|
+
near = cross-height if direction in ('up', 'left') else cross
|
|
1286
|
+
box = (near, along, height, pixel) if direction in ('left', 'right') else (along, near, pixel, height)
|
|
1287
|
+
self.panel_fun(AnnotationPanel(f, *box, (i,), (panel.names[j],),
|
|
1288
|
+
(values[i],), direction, font,fontfamily=self._font_family()))
|
|
1289
|
+
|
|
1290
|
+
|
|
1291
|
+
class ZoomAnnotation(_Track):
|
|
1292
|
+
"""Connect selected items to disjoint group panels and run a panel callback.
|
|
1293
|
+
|
|
1294
|
+
``align_to`` maps group names to zero-based indices (requires ``n``), or to
|
|
1295
|
+
item identifiers. Groups may be noncontiguous, but cannot overlap. Each panel
|
|
1296
|
+
gets equal along-axis space; automatic label/panel collision solving, external
|
|
1297
|
+
panel placement and R viewport units are not supported. ``anno_link`` is an
|
|
1298
|
+
alias for this mapping, matching R's shared implementation family.
|
|
1299
|
+
"""
|
|
1300
|
+
auto_height_ratio = 3.0
|
|
1301
|
+
|
|
1302
|
+
def __init__(self,align_to,*,n=None,panel_fun=None,size=None,gap=None,link_width=None,link_gp=None,link_height=None,extend=None,internal_line=None,**kwargs):
|
|
1303
|
+
if internal_line is not None and not isinstance(internal_line,(bool,np.bool_)):raise TypeError('internal_line must be boolean')
|
|
1304
|
+
self.internal_line=None if internal_line is None else bool(internal_line)
|
|
1305
|
+
self.zoom_extend=None if extend is None else np.atleast_1d(extend).astype(float)
|
|
1306
|
+
if self.zoom_extend is not None:
|
|
1307
|
+
if self.zoom_extend.shape not in ((1,),(2,)) or not np.isfinite(self.zoom_extend).all() or np.any(self.zoom_extend<0):raise ValueError('extend must contain one or two finite nonnegative fractions')
|
|
1308
|
+
if len(self.zoom_extend)==1:self.zoom_extend=np.repeat(self.zoom_extend,2)
|
|
1309
|
+
if link_height is not None and (isinstance(link_height,(bool,np.bool_)) or not np.isscalar(link_height) or not np.isfinite(link_height) or link_height<0):raise ValueError('link_height must be finite nonnegative mm')
|
|
1310
|
+
self.link_height=link_height
|
|
1311
|
+
if not isinstance(align_to, dict):
|
|
1312
|
+
raise TypeError('align_to must map names to item lists')
|
|
1313
|
+
from .graphics import validate_gp
|
|
1314
|
+
self.link_gp=validate_gp(link_gp,{'col','lwd'})
|
|
1315
|
+
for value,name in ((gap,'gap'),(link_width,'link_width')):
|
|
1316
|
+
if value is not None and (not np.isscalar(value) or not np.isfinite(value) or value<0):raise ValueError(name+' must be finite nonnegative mm')
|
|
1317
|
+
self.panel_size=None if size is None else np.atleast_1d(size).astype(float)
|
|
1318
|
+
if self.panel_size is not None and (not len(self.panel_size) or not np.isfinite(self.panel_size).all() or np.any(self.panel_size<=0)):raise ValueError('size must contain positive finite mm')
|
|
1319
|
+
if self.panel_size is not None and len(self.panel_size) not in (1,len(align_to)):raise ValueError('size must be scalar or one value per group')
|
|
1320
|
+
self.panel_gap=gap;self.link_width=link_width;self._group_order=list(align_to)
|
|
1321
|
+
groups, at = [], []
|
|
1322
|
+
for group, indices in align_to.items():
|
|
1323
|
+
for index in indices:
|
|
1324
|
+
at.append(index)
|
|
1325
|
+
groups.append(group)
|
|
1326
|
+
if len(set(at)) != len(at):
|
|
1327
|
+
raise ValueError('groups cannot overlap')
|
|
1328
|
+
if all(isinstance(i, (int, np.integer)) for i in at):
|
|
1329
|
+
if n is None:
|
|
1330
|
+
raise ValueError('n is required for integer positions')
|
|
1331
|
+
if any(i < 0 or i >= n for i in at):
|
|
1332
|
+
raise ValueError('group position outside n items')
|
|
1333
|
+
values = [None]*n
|
|
1334
|
+
for i, group in zip(at, groups):
|
|
1335
|
+
values[i] = group
|
|
1336
|
+
else:
|
|
1337
|
+
values = pd.Series(groups, index=at, dtype=object)
|
|
1338
|
+
super().__init__(values, **kwargs)
|
|
1339
|
+
if link_height is not None and self.side in ('left','right'):raise ValueError('link_height is a column annotation control; use link_width for rows')
|
|
1340
|
+
self.panel_fun = panel_fun or (lambda ctx: ctx.rect(stroke='#333333'))
|
|
1341
|
+
if not callable(self.panel_fun):
|
|
1342
|
+
raise TypeError('panel_fun must be callable')
|
|
1343
|
+
|
|
1344
|
+
def axis_padding(self,renderer):
|
|
1345
|
+
padding=super().axis_padding(renderer)
|
|
1346
|
+
if self.zoom_extend is not None:
|
|
1347
|
+
vertical=self.side in ('left','right')
|
|
1348
|
+
n=len(renderer.row_names if vertical else renderer.col_names)
|
|
1349
|
+
cell=renderer._cell_h if vertical else renderer._cell_w
|
|
1350
|
+
breaks=renderer.row_breaks if vertical else renderer.col_breaks
|
|
1351
|
+
gap=slice_gaps(renderer,'row' if vertical else 'column')
|
|
1352
|
+
span=n*cell+gap_total(gap,len(breaks))
|
|
1353
|
+
for side,fraction in zip(('top','bottom') if vertical else ('left','right'),self.zoom_extend):
|
|
1354
|
+
padding[side]=max(padding.get(side,0),span*fraction)
|
|
1355
|
+
return padding
|
|
1356
|
+
|
|
1357
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
1358
|
+
from .graphics import gp_value
|
|
1359
|
+
active = {}
|
|
1360
|
+
name_lookup = {i: name for p in panels for i, name in zip(p.indices, p.names)}
|
|
1361
|
+
for i in positions:
|
|
1362
|
+
if values[i] is not None and not pd.isna(values[i]):
|
|
1363
|
+
active.setdefault(values[i], []).append(i)
|
|
1364
|
+
if not active:
|
|
1365
|
+
return
|
|
1366
|
+
if self.panel_size is not None or self.panel_gap is not None or self.link_width is not None or self.link_height is not None or self.zoom_extend is not None or self.internal_line is not None:
|
|
1367
|
+
return self._render_sized(f,values,active,name_lookup,positions,cross,height,pixel,direction,font)
|
|
1368
|
+
start = min(positions.values())-pixel/2
|
|
1369
|
+
end = max(positions.values())+pixel/2
|
|
1370
|
+
span = (end-start)/len(active)
|
|
1371
|
+
for j, (group, indices) in enumerate(active.items()):
|
|
1372
|
+
along = start+j*span
|
|
1373
|
+
far = cross-height if direction in ('up', 'left') else cross+height*.35
|
|
1374
|
+
depth = height*.65
|
|
1375
|
+
box = (far, along+1, depth, max(0,span-2)) if direction in ('left','right') else (along+1, far, max(0,span-2), depth)
|
|
1376
|
+
ctx = AnnotationPanel(f, *box, tuple(indices), tuple(name_lookup[i] for i in indices),
|
|
1377
|
+
tuple(values[i] for i in indices), direction, font, group,fontfamily=self._font_family())
|
|
1378
|
+
target = along+span/2
|
|
1379
|
+
for i in indices:
|
|
1380
|
+
p1 = self._point(positions[i], 0, cross, height, direction)
|
|
1381
|
+
p2 = self._point(target, .3, cross, height, direction)
|
|
1382
|
+
_svg(f, 'line', x1=p1[0], y1=p1[1], x2=p2[0], y2=p2[1], stroke=gp_value(self.link_gp,'col',j,self.color), stroke_width=gp_value(self.link_gp,'lwd',j,.75))
|
|
1383
|
+
self.panel_fun(ctx)
|
|
1384
|
+
|
|
1385
|
+
def _render_sized(self,f,values,active,names,positions,cross,height,pixel,direction,font):
|
|
1386
|
+
from .style import Appearance
|
|
1387
|
+
from .graphics import gp_value
|
|
1388
|
+
a=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
1389
|
+
start=min(positions.values())-pixel/2;end=max(positions.values())+pixel/2
|
|
1390
|
+
if self.zoom_extend is not None:
|
|
1391
|
+
original=end-start
|
|
1392
|
+
start-=original*self.zoom_extend[0];end+=original*self.zoom_extend[1]
|
|
1393
|
+
groups=[g for g in self._group_order if g in active]
|
|
1394
|
+
gap=a.mm(1 if self.panel_gap is None else self.panel_gap)
|
|
1395
|
+
available=end-start-gap*max(0,len(groups)-1)
|
|
1396
|
+
sizes=np.repeat(available/len(groups),len(groups)) if self.panel_size is None else np.array([a.mm(self.panel_size[self._group_order.index(g)%len(self.panel_size)]) for g in groups])
|
|
1397
|
+
depth_option=self.link_height if direction in ('up','down') and self.link_height is not None else self.link_width
|
|
1398
|
+
link=a.mm(5 if depth_option is None else depth_option)
|
|
1399
|
+
if available<=0 or sizes.sum()>available+1e-7 or link>=height:raise ValueError('zoom panel sizes/gaps/link_width do not fit available annotation space; increase heatmap/track dimensions or reduce size')
|
|
1400
|
+
along=start+(available-sizes.sum())/2
|
|
1401
|
+
for j,(group,span) in enumerate(zip(groups,sizes)):
|
|
1402
|
+
indices=active[group];near=cross-height if direction in ('up','left') else cross+link
|
|
1403
|
+
depth=height-link
|
|
1404
|
+
box=(near,along,depth,span) if direction in ('left','right') else (along,near,span,depth)
|
|
1405
|
+
ctx=AnnotationPanel(f,*box,tuple(indices),tuple(names[i] for i in indices),tuple(values[i] for i in indices),direction,font,group,fontfamily=self._font_family())
|
|
1406
|
+
target=along+span/2
|
|
1407
|
+
if self.internal_line is None:
|
|
1408
|
+
for i in indices:
|
|
1409
|
+
p1=self._point(positions[i],0,cross,height,direction)
|
|
1410
|
+
edge=(cross-link,target) if direction=='left' else (cross+link,target) if direction=='right' else (target,cross-link) if direction=='up' else (target,cross+link)
|
|
1411
|
+
_svg(f,'line',x1=p1[0],y1=p1[1],x2=edge[0],y2=edge[1],stroke=gp_value(self.link_gp,'col',j,self.color),stroke_width=a.pt(float(gp_value(self.link_gp,'lwd',j,.75))))
|
|
1412
|
+
else:
|
|
1413
|
+
runs=[]
|
|
1414
|
+
for i in indices:
|
|
1415
|
+
if runs and i==runs[-1][-1]+1 and np.isclose(positions[i]-positions[runs[-1][-1]],pixel):runs[-1].append(i)
|
|
1416
|
+
else:runs.append([i])
|
|
1417
|
+
edge=cross+(-link if direction in ('up','left') else link)
|
|
1418
|
+
for run in runs:
|
|
1419
|
+
first=positions[run[0]]-pixel/2;last=positions[run[-1]]+pixel/2
|
|
1420
|
+
pts=[(along,edge),(first,cross),(last,cross),(along+span,edge)]
|
|
1421
|
+
if direction in ('left','right'):pts=[(y,x) for x,y in pts]
|
|
1422
|
+
if self.internal_line:pts.append(pts[0])
|
|
1423
|
+
_svg(f,'polyline',points=' '.join(f'{x},{y}' for x,y in pts),fill='none',stroke=gp_value(self.link_gp,'col',j,self.color),stroke_width=a.pt(float(gp_value(self.link_gp,'lwd',j,.75))))
|
|
1424
|
+
self.panel_fun(ctx);along+=span+gap
|
|
1425
|
+
|
|
1426
|
+
|
|
1427
|
+
class HorizonAnnotation(_Track):
|
|
1428
|
+
"""Native compact folded-amplitude strips, with opt-in R-like controls.
|
|
1429
|
+
|
|
1430
|
+
Items are rows and ordered samples occupy subdivisions along each item slot.
|
|
1431
|
+
Omitted normalization retains the shared amplitude scale and three bands.
|
|
1432
|
+
Unlike R's interpolated area horizon charts this engine draws sample tiles;
|
|
1433
|
+
its optional axis remains the native cross-band amplitude axis.
|
|
1434
|
+
``gap`` is physical mm between item slots; slice_size is amplitude units
|
|
1435
|
+
after optional per-item normalization. Negative folds can start at the top.
|
|
1436
|
+
"""
|
|
1437
|
+
def __init__(self, x, *, bands=None, positive='#b2182b', negative='#2166ac',
|
|
1438
|
+
n_slice=None, slice_size=None, normalize=False,
|
|
1439
|
+
negative_from_top=False, gap=0, gp=None, **kwargs):
|
|
1440
|
+
from .graphics import validate_gp,gp_value
|
|
1441
|
+
if n_slice is not None:
|
|
1442
|
+
if isinstance(n_slice,(bool,np.bool_)) or not isinstance(n_slice,(int,np.integer)) or n_slice<1:
|
|
1443
|
+
raise ValueError('n_slice must be a positive integer')
|
|
1444
|
+
if bands is not None and bands!=n_slice:raise ValueError('bands conflicts with n_slice')
|
|
1445
|
+
bands=n_slice
|
|
1446
|
+
bands=3 if bands is None else bands
|
|
1447
|
+
if isinstance(bands,(bool,np.bool_)) or not isinstance(bands,(int,np.integer)) or bands<1 or bands>4096:
|
|
1448
|
+
raise ValueError('bands/n_slice must be an integer in [1,4096]')
|
|
1449
|
+
for key,value in [('normalize',normalize),('negative_from_top',negative_from_top)]:
|
|
1450
|
+
if not isinstance(value,(bool,np.bool_)):raise TypeError(key+' must be boolean')
|
|
1451
|
+
if slice_size is not None and (isinstance(slice_size,(bool,np.bool_)) or not np.isscalar(slice_size) or not np.isfinite(slice_size) or slice_size<=0):
|
|
1452
|
+
raise ValueError('slice_size must be finite and positive')
|
|
1453
|
+
if isinstance(gap,(bool,np.bool_)) or not np.isscalar(gap) or not np.isfinite(gap) or gap<0:
|
|
1454
|
+
raise ValueError('gap must be finite nonnegative mm')
|
|
1455
|
+
special={k:v for k,v in dict(gp or {}).items() if k in ('pos_fill','neg_fill')}
|
|
1456
|
+
self._sign_gp=validate_gp(special,{'pos_fill','neg_fill'})
|
|
1457
|
+
from .style import to_rgb
|
|
1458
|
+
for key in self._sign_gp:
|
|
1459
|
+
value=self._sign_gp[key]
|
|
1460
|
+
vector=not isinstance(value,str) and not np.isscalar(value)
|
|
1461
|
+
colors=list(value) if vector else [value]
|
|
1462
|
+
if not colors:raise ValueError('gp '+key+' must not be empty')
|
|
1463
|
+
for c in colors:to_rgb(c)
|
|
1464
|
+
ordinary={k:v for k,v in dict(gp or {}).items() if k not in special}
|
|
1465
|
+
super().__init__(x,gp=ordinary,**kwargs)
|
|
1466
|
+
self.bands=int(bands);self.slice_size=None if slice_size is None else float(slice_size)
|
|
1467
|
+
self.normalize=bool(normalize);self.negative_from_top=bool(negative_from_top);self.gap=float(gap)
|
|
1468
|
+
self.positive,self.negative=positive,negative
|
|
1469
|
+
|
|
1470
|
+
def _axis_model(self,values,vertical):
|
|
1471
|
+
if not self.normalize and self.slice_size is None:return super()._axis_model(values,vertical)
|
|
1472
|
+
from .axes import AnnotationAxis,axis_parameters
|
|
1473
|
+
maximum=max((float(np.max(np.abs(_num(v)))) for v in values if _num(v).size),default=1) or 1
|
|
1474
|
+
step=self.slice_size if self.slice_size is not None else (1 if self.normalize else maximum)/self.bands
|
|
1475
|
+
return AnnotationAxis(scale=(0,step),**axis_parameters(self.axis_param,'row' if vertical else 'column'))
|
|
1476
|
+
|
|
1477
|
+
def _render(self, f, values, panels, positions, cross, height, pixel, direction, font):
|
|
1478
|
+
from .graphics import gp_value
|
|
1479
|
+
from .style import Appearance
|
|
1480
|
+
maximum = max((np.max(np.abs(_num(v))) for v in values if _num(v).size), default=1) or 1
|
|
1481
|
+
single_sign=False
|
|
1482
|
+
if 'fill' in self.gp:
|
|
1483
|
+
nonnegative=nonpositive=True
|
|
1484
|
+
for item in values:
|
|
1485
|
+
finite=_num(item)
|
|
1486
|
+
nonnegative=nonnegative and bool(np.all(finite>=0))
|
|
1487
|
+
nonpositive=nonpositive and bool(np.all(finite<=0))
|
|
1488
|
+
single_sign=nonnegative or nonpositive
|
|
1489
|
+
app=getattr(getattr(f,'plotter',None),'_appearance',Appearance(96))
|
|
1490
|
+
gap=app.mm(self.gap)
|
|
1491
|
+
if gap>=pixel:raise ValueError('horizon gap leaves no drawable item width')
|
|
1492
|
+
for i, along in positions.items():
|
|
1493
|
+
try:samples=np.asarray(values[i],dtype=float).ravel()
|
|
1494
|
+
except (TypeError,ValueError):samples=np.empty(0)
|
|
1495
|
+
finite=samples[np.isfinite(samples)]
|
|
1496
|
+
local_max=np.max(np.abs(finite)) if finite.size else 0
|
|
1497
|
+
if self.normalize and local_max:samples=samples/local_max
|
|
1498
|
+
scale=(1 if self.normalize else maximum)
|
|
1499
|
+
step=self.slice_size if self.slice_size is not None else scale/self.bands
|
|
1500
|
+
if self.slice_size is not None and scale>4096*step:raise ValueError('horizon slice_size requires more than4096folds')
|
|
1501
|
+
shared_folds=self.bands if self.slice_size is None else max(1,int(np.ceil(scale/step)))
|
|
1502
|
+
folds=int(np.ceil((1 if self.normalize and local_max else local_max)/step)) if step else 0
|
|
1503
|
+
if folds>4096:raise ValueError('horizon slice_size requires more than4096folds')
|
|
1504
|
+
for k,v in enumerate(samples):
|
|
1505
|
+
if not np.isfinite(v):continue
|
|
1506
|
+
subpixel=(pixel-gap)/len(samples)
|
|
1507
|
+
# The omitted path retains exactly the original band iteration.
|
|
1508
|
+
for band in range(self.bands if self.slice_size is None else folds):
|
|
1509
|
+
amplitude=abs(v)/maximum*self.bands if self.slice_size is None and not self.normalize else abs(v)/step
|
|
1510
|
+
fraction=np.clip(amplitude-band,0,1)
|
|
1511
|
+
if fraction==0:continue
|
|
1512
|
+
a=along-pixel/2+gap/2+k*subpixel
|
|
1513
|
+
flipped=v<0 and self.negative_from_top
|
|
1514
|
+
p1=self._point(a,1 if flipped else 0,cross,height,direction)
|
|
1515
|
+
p2=self._point(a+subpixel,1-fraction if flipped else fraction,cross,height,direction)
|
|
1516
|
+
key='pos_fill' if v>=0 else 'neg_fill'
|
|
1517
|
+
color=gp_value(self._sign_gp,key,self._style_index(i),self.positive if v>=0 else self.negative)
|
|
1518
|
+
if key not in self._sign_gp and 'fill' in self.gp and single_sign:
|
|
1519
|
+
color=gp_value(self.gp,'fill',self._style_index(i),color)
|
|
1520
|
+
_svg(f,'rect',x=min(p1[0],p2[0]),y=min(p1[1],p2[1]),
|
|
1521
|
+
width=abs(p2[0]-p1[0]),height=abs(p2[1]-p1[1]),fill=color,
|
|
1522
|
+
fill_opacity=(band+1)/(self.bands if self.slice_size is None else shared_folds))
|
|
1523
|
+
|
|
1524
|
+
|
|
1525
|
+
# Factories intentionally share explicit class constructors. Unknown R kwargs
|
|
1526
|
+
# flow to _Track and raise TypeError rather than being silently discarded.
|
|
1527
|
+
anno_points = PointsAnnotation
|
|
1528
|
+
anno_lines = LinesAnnotation
|
|
1529
|
+
anno_histogram = HistogramAnnotation
|
|
1530
|
+
anno_density = DensityAnnotation
|
|
1531
|
+
anno_joyplot = JoyplotAnnotation
|
|
1532
|
+
anno_text = TextAnnotation
|
|
1533
|
+
anno_mark = MarkAnnotation
|
|
1534
|
+
anno_block = BlockAnnotation
|
|
1535
|
+
anno_numeric = NumericAnnotation
|
|
1536
|
+
def anno_summary(x=None,*,mode='item',**kwargs):
|
|
1537
|
+
if mode=='item':return SummaryAnnotation(x,**kwargs)
|
|
1538
|
+
if mode!='slice':raise ValueError('summary mode must be item or slice')
|
|
1539
|
+
if x is not None:raise ValueError('slice summaries read the owning heatmap; omit x')
|
|
1540
|
+
from .slice_summary import SliceSummaryAnnotation
|
|
1541
|
+
return SliceSummaryAnnotation(**kwargs)
|
|
1542
|
+
anno_image = ImageAnnotation
|
|
1543
|
+
anno_empty = EmptyAnnotation
|
|
1544
|
+
anno_customize = CustomAnnotation
|
|
1545
|
+
anno_zoom = ZoomAnnotation
|
|
1546
|
+
anno_link = ZoomAnnotation
|
|
1547
|
+
anno_horizon = HorizonAnnotation
|
|
1548
|
+
def anno_textbox(x=None,text=None,*,align_to=None,**kwargs):
|
|
1549
|
+
"""One argument retains item text; group + text creates wrapped row boxes."""
|
|
1550
|
+
if text is None and align_to is None:return TextboxAnnotation(x,**kwargs)
|
|
1551
|
+
if align_to is not None and x is not None:raise ValueError('provide x or align_to, not both')
|
|
1552
|
+
from .grouped_textboxes import GroupedTextboxAnnotation
|
|
1553
|
+
return GroupedTextboxAnnotation(align_to if align_to is not None else x,text,**kwargs)
|
|
1554
|
+
|
|
1555
|
+
|
|
1556
|
+
def row_anno_points(x, **kwargs):
|
|
1557
|
+
"""Row counterpart of :func:`anno_points`; default side is left."""
|
|
1558
|
+
return PointsAnnotation(x, which='row', **kwargs)
|
|
1559
|
+
|
|
1560
|
+
|
|
1561
|
+
def row_anno_histogram(x, **kwargs):
|
|
1562
|
+
"""Row counterpart of :func:`anno_histogram`; default side is left."""
|
|
1563
|
+
return HistogramAnnotation(x, which='row', **kwargs)
|
|
1564
|
+
|
|
1565
|
+
|
|
1566
|
+
def row_anno_density(x, **kwargs):
|
|
1567
|
+
"""Row counterpart of :func:`anno_density`; default side is left."""
|
|
1568
|
+
return DensityAnnotation(x, which='row', **kwargs)
|
|
1569
|
+
|
|
1570
|
+
|
|
1571
|
+
def row_anno_text(x, **kwargs):
|
|
1572
|
+
"""Row counterpart of :func:`anno_text`; default side is left."""
|
|
1573
|
+
return TextAnnotation(x, which='row', **kwargs)
|