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.
Files changed (94) hide show
  1. tilesig/__init__.py +124 -0
  2. tilesig/_bundle_data.py +76 -0
  3. tilesig/_bundle_metadata.py +199 -0
  4. tilesig/_gpu_linkage_worker.py +147 -0
  5. tilesig/_version.py +2 -0
  6. tilesig/algorithm_adapters.py +130 -0
  7. tilesig/algorithm_binding.py +157 -0
  8. tilesig/algorithm_types.py +251 -0
  9. tilesig/algorithms.py +55 -0
  10. tilesig/annotation.py +1152 -0
  11. tilesig/annotation_layout.py +104 -0
  12. tilesig/annotation_names.py +174 -0
  13. tilesig/annotation_ops.py +199 -0
  14. tilesig/annotations_extra.py +1573 -0
  15. tilesig/api.py +861 -0
  16. tilesig/appearance.py +707 -0
  17. tilesig/axes.py +146 -0
  18. tilesig/barplot.py +337 -0
  19. tilesig/block_heatmap.py +158 -0
  20. tilesig/block_summary.py +231 -0
  21. tilesig/bundle_io.py +92 -0
  22. tilesig/cell_labels.py +68 -0
  23. tilesig/cell_mask.py +70 -0
  24. tilesig/clustering.py +39 -0
  25. tilesig/comparison.py +158 -0
  26. tilesig/compatibility.py +199 -0
  27. tilesig/compatibility_extra.py +111 -0
  28. tilesig/composition_controls.py +132 -0
  29. tilesig/composition_layout.py +121 -0
  30. tilesig/config.py +343 -0
  31. tilesig/decoration_context.py +53 -0
  32. tilesig/decoration_selection.py +56 -0
  33. tilesig/decorations.py +166 -0
  34. tilesig/dendrograms.py +299 -0
  35. tilesig/diagonal.py +213 -0
  36. tilesig/distribution_heatmaps.py +164 -0
  37. tilesig/dot_heatmap.py +274 -0
  38. tilesig/genomic.py +87 -0
  39. tilesig/gpu_bridge.py +214 -0
  40. tilesig/gpu_raster.py +128 -0
  41. tilesig/graphics.py +92 -0
  42. tilesig/grouped_textboxes.py +133 -0
  43. tilesig/h5ad.py +742 -0
  44. tilesig/h5ad_subset.py +245 -0
  45. tilesig/helpers.py +246 -0
  46. tilesig/interval_sets.py +120 -0
  47. tilesig/item_display_tree.py +81 -0
  48. tilesig/legend_ticks.py +60 -0
  49. tilesig/legends.py +607 -0
  50. tilesig/matplotlib_integration.py +50 -0
  51. tilesig/matrix_scaling.py +40 -0
  52. tilesig/matrix_source.py +180 -0
  53. tilesig/name_layout.py +93 -0
  54. tilesig/object_ops.py +505 -0
  55. tilesig/options.py +44 -0
  56. tilesig/ordering_policy.py +91 -0
  57. tilesig/palettes.py +101 -0
  58. tilesig/parent_dendrogram.py +199 -0
  59. tilesig/pdf_renderer.py +717 -0
  60. tilesig/png_renderer.py +559 -0
  61. tilesig/preparation_cache.py +94 -0
  62. tilesig/prepared.py +179 -0
  63. tilesig/r_cluster_controls.py +138 -0
  64. tilesig/r_layout_controls.py +92 -0
  65. tilesig/r_raster.py +235 -0
  66. tilesig/renderer.py +3611 -0
  67. tilesig/renderer_old.py +2060 -0
  68. tilesig/reproducibility.py +88 -0
  69. tilesig/sets.py +407 -0
  70. tilesig/signal_heatmap.py +453 -0
  71. tilesig/single_cell.py +251 -0
  72. tilesig/slice_drawing.py +100 -0
  73. tilesig/slice_geometry.py +48 -0
  74. tilesig/slice_summary.py +80 -0
  75. tilesig/source_render.py +252 -0
  76. tilesig/specialized.py +520 -0
  77. tilesig/specialized_support.py +172 -0
  78. tilesig/streaming_pdf.py +118 -0
  79. tilesig/streaming_svg.py +72 -0
  80. tilesig/style.py +148 -0
  81. tilesig/text_boxes.py +158 -0
  82. tilesig/text_layout.py +45 -0
  83. tilesig/text_styles.py +83 -0
  84. tilesig/titles.py +191 -0
  85. tilesig/tree_styles.py +45 -0
  86. tilesig/unicode_pdf.py +119 -0
  87. tilesig/upset_annotations.py +58 -0
  88. tilesig/vector_grid.py +13 -0
  89. tilesig/within_block_order.py +167 -0
  90. tilesig-0.1.0.dev0.dist-info/METADATA +107 -0
  91. tilesig-0.1.0.dev0.dist-info/RECORD +94 -0
  92. tilesig-0.1.0.dev0.dist-info/WHEEL +5 -0
  93. tilesig-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
  94. tilesig-0.1.0.dev0.dist-info/top_level.txt +1 -0
tilesig/annotation.py ADDED
@@ -0,0 +1,1152 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ from .slice_geometry import gap_at,gap_total as total_slice_gap,slice_gaps
4
+ import cv2
5
+ import base64
6
+
7
+ BOXPLOT_MAX_ITEMS = 500
8
+
9
+ def _escape_xml(s):
10
+ if s is None:
11
+ return ''
12
+ s = str(s)
13
+ s = s.replace('&', '&')
14
+ s = s.replace('<', '&lt;')
15
+ s = s.replace('>', '&gt;')
16
+ s = s.replace('"', '&quot;')
17
+ s = s.replace("'", '&apos;')
18
+ return s
19
+
20
+ def _canvas_w(renderer):
21
+ """Canvas width used for label fitting — prefers the final layout width."""
22
+ w = getattr(renderer, 'canvas_width', None)
23
+ if w:
24
+ return w
25
+ return getattr(renderer, 'output_width', 0)
26
+
27
+
28
+ def _resolve_fontsize(renderer, explicit):
29
+ """Resolve an annotation text size.
30
+
31
+ An explicit ``fontsize`` (set on the annotation) always wins; otherwise the
32
+ size is auto-scaled by the renderer from the rendered heatmap scale.
33
+ """
34
+ if explicit is not None:
35
+ return int(explicit)
36
+ fn = getattr(renderer, '_auto_font', None)
37
+ if fn is not None:
38
+ return int(fn(None))
39
+ return 10
40
+
41
+
42
+ def _resolve_border_width(renderer, explicit, default=0.5):
43
+ """Resolve an annotation border width.
44
+
45
+ An explicit width always wins; otherwise it falls back to the heatmap's
46
+ element border width (scaled), so annotation borders match the heatmap by
47
+ default.
48
+ """
49
+ fn = getattr(renderer, '_resolve_border_width', None)
50
+ if fn is not None:
51
+ return fn(explicit)
52
+ if explicit is None:
53
+ return default
54
+ return float(explicit)
55
+
56
+
57
+ def _resolve_border_color(renderer, explicit, default='#000000'):
58
+ """Resolve a border color: explicit wins, else the heatmap element color."""
59
+ if explicit:
60
+ return explicit
61
+ return getattr(renderer, 'heatmap_element_border_color', default) or default
62
+
63
+
64
+ def _resolve_height(renderer, annotation):
65
+ """Resolve an annotation band thickness.
66
+
67
+ An explicit ``height`` (set on the annotation) always wins; otherwise the
68
+ band thickness is auto-scaled by the renderer together with the text.
69
+ """
70
+ explicit = getattr(annotation, 'height', None)
71
+ if explicit is not None:
72
+ return int(explicit)
73
+ fn = getattr(renderer, '_auto_annot_height', None)
74
+ if fn is not None:
75
+ return int(fn(annotation))
76
+ return 30
77
+
78
+
79
+ def _truncate_text(text, max_px, fontsize):
80
+ """Roughly truncate `text` so it fits within `max_px` pixels.
81
+
82
+ Uses a heuristic char width = fontsize * 0.6. Returns truncated string
83
+ with ellipsis if needed.
84
+ """
85
+ if text is None:
86
+ return ''
87
+ try:
88
+ max_px = int(max_px)
89
+ fontsize = int(fontsize)
90
+ except:
91
+ return text
92
+
93
+ char_w = max(1, fontsize * 0.6)
94
+ max_chars = max(1, int(max_px / char_w))
95
+ if len(text) <= max_chars:
96
+ return text
97
+ if max_chars <= 3:
98
+ return text[:max_chars]
99
+ return text[: max_chars - 3] + '...'
100
+
101
+ class AnnotationBase:
102
+ """Base class for all annotation types."""
103
+ def __init__(self, df=None, side='top', height=None, fontsize=None, label=None, **kwargs):
104
+ self.df = df
105
+ self.label = label
106
+ self.side = side if side in ['top', 'bottom', 'left', 'right'] else 'top'
107
+ # None = auto-scale together with the heatmap (see _resolve_height).
108
+ self.height = None if height is None else int(height)
109
+ # None = auto-scale from the rendered heatmap (see _resolve_fontsize).
110
+ self.fontsize = None if fontsize is None else int(fontsize)
111
+
112
+ def _bind_item_ids(self,names):
113
+ """Bind positional data and its per-item graphical metadata together."""
114
+ index=pd.Index(names).map(str)
115
+ self.df.index=index
116
+ if getattr(self,'_graphical_ids',None) is not None:
117
+ self._graphical_ids=pd.Series(self._graphical_ids.to_numpy(copy=True),index=index)
118
+
119
+ def draw(self, f, start_x, start_y, pixel_size, bounds, gap_pixels, direction, renderer):
120
+ """
121
+ Abstract method: Each annotation type must implement this.
122
+
123
+ Parameters:
124
+ - f: File object for SVG output
125
+ - start_x, start_y: Starting coordinates
126
+ - pixel_size: Cell size (cw or ch)
127
+ - bounds: Break points (col_bounds or row_bounds)
128
+ - gap_pixels: Gap between clusters
129
+ - direction: 'up', 'down', 'left', 'right'
130
+ - renderer: Reference to renderer (e.g. for color conversion)
131
+ """
132
+ raise NotImplementedError("Subclass must implement this method!")
133
+
134
+
135
+ class SimpleAnnotation(AnnotationBase):
136
+ """Simple color-coded categorical annotation."""
137
+ def __init__(self, df=None, colors=None, cmap="auto", **kwargs):
138
+ if df is not None and not isinstance(df, (pd.DataFrame, pd.Series)):
139
+ df = pd.DataFrame({kwargs.get('label', 'value'): list(df)})
140
+ elif isinstance(df, pd.Series):
141
+ df = df.to_frame(kwargs.get('label', 'value'))
142
+ super().__init__(df=df, **kwargs)
143
+ self.colors = colors if colors is not None else {}
144
+ from .palettes import resolve_palette
145
+ self.cmap = resolve_palette(cmap)
146
+ # Optional per-element border (small border around each cell)
147
+ self.element_border = bool(kwargs.get('element_border', False))
148
+ self.border = bool(kwargs.get('border', False))
149
+ # None = match the heatmap element border color (resolved at draw time).
150
+ self.element_border_color = kwargs.get('element_border_color')
151
+ # None = match the heatmap element border width (resolved at draw time).
152
+ _ebw = kwargs.get('element_border_width')
153
+ try:
154
+ self.element_border_width = None if _ebw is None else float(_ebw)
155
+ except Exception:
156
+ self.element_border_width = None
157
+
158
+ def draw(self, f, start_x, start_y, pixel_size, bounds, gap_pixels, direction, renderer):
159
+ if getattr(self,'_simple_physical_size',False) and getattr(renderer,'style','legacy')!='complexheatmap':
160
+ raise ValueError('physical simple annotation size requires complexheatmap style')
161
+ if getattr(renderer, 'style', 'legacy') == 'complexheatmap':
162
+ from .appearance import draw_simple_annotation
163
+ return draw_simple_annotation(self, f, start_x, start_y, pixel_size, bounds, gap_pixels, direction, renderer)
164
+ # Direction-dependent variable setup
165
+ is_vertical = direction in ['left', 'right']
166
+ BAR_SIZE = _resolve_height(renderer, self) # Bar thickness
167
+ TEXT_GAP = getattr(renderer, '_annot_gap_px', 5)
168
+ fontsize = _resolve_fontsize(renderer, self.fontsize)
169
+ elem_bw = _resolve_border_width(renderer, self.element_border_width)
170
+ elem_col = self.element_border_color or getattr(renderer, 'heatmap_element_border_color', '#000000')
171
+
172
+ current_cursor = start_x if is_vertical else start_y
173
+
174
+ # Iterate through columns (annotation rows)
175
+ if getattr(self, 'df', None) is not None:
176
+ cols_iter = list(self.df.columns)
177
+ else:
178
+ cols_iter = [None]
179
+ # If 'up' or 'left': reverse draw order
180
+ if direction in ['up', 'left']:
181
+ cols_iter = reversed(cols_iter)
182
+
183
+ for col_name in cols_iter:
184
+ display_name = col_name if col_name is not None else (self.label or '')
185
+ if getattr(self, 'df', None) is not None and col_name is not None:
186
+ vals = self.df[col_name].values
187
+ else:
188
+ try:
189
+ if is_vertical:
190
+ vals = np.nanmean(renderer._matrix_sorted, axis=1)
191
+ else:
192
+ vals = np.nanmean(renderer._matrix_sorted, axis=0)
193
+ except Exception:
194
+ vals = np.array([np.nan])
195
+
196
+ # Label (category name)
197
+ if is_vertical: # Left/Right
198
+ horiz_gap = renderer.col_gap_pixels if hasattr(renderer, 'col_gap_pixels') else 0
199
+ text_x = int(current_cursor + BAR_SIZE/2) if direction == 'right' else int(current_cursor - BAR_SIZE/2 - horiz_gap)
200
+ # Calculate total display height for the annotation span
201
+ total_h = sum([(b_end - b_start) * pixel_size for (b_start, b_end) in bounds])
202
+ gap_total = (total_slice_gap(slice_gaps(renderer,'row'),len(renderer.row_breaks))) if hasattr(renderer, 'row_breaks') else 0
203
+ total_h += gap_total
204
+
205
+ # Allocate more space for the rotated label to avoid truncation
206
+ if _canvas_w(renderer):
207
+ avail_px = max(300, _canvas_w(renderer) - (text_x + 100))
208
+ else:
209
+ avail_px = 300
210
+ t = _truncate_text(str(display_name), avail_px, fontsize)
211
+
212
+ if direction == 'left':
213
+ # Rotated -90° text extends upwards from `text_y`; anchor it
214
+ # just below the heatmap (offset by its own length) so it
215
+ # sits beside the bottom bands without covering anything.
216
+ lw = int(len(t) * fontsize * 0.6)
217
+ text_y = int(start_y + total_h + 10 + lw)
218
+ else:
219
+ text_y = int(start_y - 10)
220
+
221
+ f.write(f'<text x="{text_x}" y="{text_y}" transform="rotate(-90, {text_x}, {text_y})" font-family="Arial" font-size="{fontsize}" text-anchor="start" dominant-baseline="middle">{_escape_xml(t)}</text>')
222
+ else: # Top/Bottom
223
+ # Account for the renderer-provided gap so labels align with
224
+ # annotation content that may be shifted by `gap_pixels`.
225
+ if direction in ['bottom', 'down']:
226
+ # Place label to the right of the annotation span
227
+ total_w = sum([(b_end - b_start) * pixel_size for (b_start, b_end) in bounds])
228
+ gap_total = (total_slice_gap(slice_gaps(renderer,'column'),len(renderer.col_breaks))) if hasattr(renderer, 'col_breaks') else 0
229
+ total_w += gap_total
230
+ text_x = int(start_x + total_w + 10)
231
+ # Per-column label position follows current_cursor so
232
+ # labels in multi-column annotations don't overlap.
233
+ text_y = int(current_cursor + BAR_SIZE / 2)
234
+ # Allocate more horizontal space for the right-side label
235
+ if _canvas_w(renderer):
236
+ avail_px = max(300, _canvas_w(renderer) - text_x - 40)
237
+ else:
238
+ avail_px = 300
239
+ t = _truncate_text(str(display_name), avail_px, fontsize)
240
+ f.write(f'<text x="{text_x}" y="{text_y}" font-family="Arial" font-size="{fontsize}" text-anchor="start" dominant-baseline="middle">{_escape_xml(t)}</text>')
241
+ else:
242
+ # Per-column label position follows current_cursor so
243
+ # labels in multi-column annotations don't overlap.
244
+ text_y = int(current_cursor - (BAR_SIZE / 2))
245
+ f.write(f'<text x="{int(start_x - 10)}" y="{text_y}" font-family="Arial" font-size="{fontsize}" text-anchor="end" dominant-baseline="middle">{_escape_xml(display_name)}</text>')
246
+
247
+ # Color mapping
248
+ clean_vals = np.asarray(vals).astype(str)
249
+ clean_vals = np.char.strip(clean_vals)
250
+ # Call renderer's color mapping method
251
+ colors = renderer._map_colors(clean_vals, self.colors,palette=self.cmap)
252
+
253
+ # Render bars
254
+ draw_pos = start_y if is_vertical else start_x
255
+
256
+ for slice_index,(b_start, b_end) in enumerate(bounds):
257
+ display_size = int((b_end - b_start) * pixel_size)
258
+ if display_size == 0: continue
259
+
260
+ slice_cols = colors[b_start:b_end]
261
+
262
+ # Render annotation: either raster (PNG) or vector (rects)
263
+ raster_mode = getattr(renderer, 'rasterized', False)
264
+ raster_full = (raster_mode is True) or (isinstance(raster_mode, str) and str(raster_mode).lower() == 'full')
265
+
266
+ if raster_full:
267
+ # Generate PNG image (existing behavior)
268
+ if is_vertical:
269
+ bgr_data = np.array([slice_cols], dtype=np.uint8).transpose(1, 0, 2)
270
+ w, h = BAR_SIZE, display_size
271
+ if direction == 'right':
272
+ x = current_cursor
273
+ else:
274
+ gap_x = renderer.col_gap_pixels if hasattr(renderer, 'col_gap_pixels') else 0
275
+ x = current_cursor - BAR_SIZE - gap_x
276
+ y = draw_pos
277
+ else:
278
+ bgr_data = np.array([slice_cols], dtype=np.uint8)
279
+ w, h = display_size, BAR_SIZE
280
+ x, y = draw_pos, (current_cursor if direction in ['bottom', 'down'] else current_cursor - BAR_SIZE)
281
+
282
+ _, buf = cv2.imencode('.png', bgr_data, [int(cv2.IMWRITE_PNG_COMPRESSION), 1])
283
+ b64 = base64.b64encode(buf).decode('utf-8')
284
+
285
+ f.write(f'<image x="{int(x)}" y="{int(y)}" width="{w}" height="{h}" preserveAspectRatio="none" style="image-rendering:pixelated" shape-rendering="crispEdges" xlink:href="data:image/png;base64,{b64}" href="data:image/png;base64,{b64}" />')
286
+ # Outer border for the span
287
+ if getattr(renderer, 'style', 'legacy') == 'legacy' or self.border:
288
+ f.write(f'<rect x="{x - 0.5}" y="{y - 0.5}" width="{w + 1}" height="{h + 1}" fill="none" stroke="black" stroke-width="1" shape-rendering="crispEdges"/>')
289
+ # Optional per-element borders overlayed on the raster image
290
+ if self.element_border:
291
+ # compute per-cell rects and draw transparent fills with stroke
292
+ if is_vertical:
293
+ for idx in range(display_size // int(pixel_size) if pixel_size>0 else 0):
294
+ rect_y = int(y + idx * pixel_size)
295
+ f.write(f'<rect x="{int(x)}" y="{rect_y}" width="{w}" height="{int(pixel_size)}" fill="none" stroke="{elem_col}" stroke-width="{elem_bw}" />')
296
+ else:
297
+ for idx in range(display_size // int(pixel_size) if pixel_size>0 else 0):
298
+ rect_x = int(x + idx * pixel_size)
299
+ f.write(f'<rect x="{rect_x}" y="{int(y)}" width="{int(pixel_size)}" height="{h}" fill="none" stroke="{elem_col}" stroke-width="{elem_bw}" />')
300
+ else:
301
+ # Vectorized: draw one rect per cell with fill color
302
+ if is_vertical:
303
+ w = BAR_SIZE
304
+ x = current_cursor if direction == 'right' else current_cursor - BAR_SIZE - (renderer.col_gap_pixels if hasattr(renderer, 'col_gap_pixels') else 0)
305
+ y = draw_pos
306
+ for idx, col in enumerate(slice_cols):
307
+ # col is BGR tuple -> convert to RGB
308
+ try:
309
+ r, g, b = int(col[2]), int(col[1]), int(col[0])
310
+ except Exception:
311
+ r, g, b = 0, 0, 0
312
+ rect_y = int(y + idx * pixel_size)
313
+ if self.element_border:
314
+ f.write(f'<rect x="{int(x)}" y="{rect_y}" width="{w}" height="{int(pixel_size)}" fill="rgb({r},{g},{b})" stroke="{elem_col}" stroke-width="{elem_bw}" shape-rendering="crispEdges"/>')
315
+ else:
316
+ f.write(f'<rect x="{int(x)}" y="{rect_y}" width="{w}" height="{int(pixel_size)}" fill="rgb({r},{g},{b})" stroke="none" shape-rendering="crispEdges"/>')
317
+ # Border around span
318
+ total_h = display_size
319
+ f.write(f'<rect x="{x - 0.5}" y="{y - 0.5}" width="{w + 1}" height="{total_h + 1}" fill="none" stroke="black" stroke-width="1" shape-rendering="crispEdges"/>')
320
+ else:
321
+ h = BAR_SIZE
322
+ x = draw_pos
323
+ y = (current_cursor if direction in ['bottom', 'down'] else current_cursor - BAR_SIZE)
324
+ for idx, col in enumerate(slice_cols):
325
+ try:
326
+ r, g, b = int(col[2]), int(col[1]), int(col[0])
327
+ except Exception:
328
+ r, g, b = 0, 0, 0
329
+ rect_x = int(x + idx * pixel_size)
330
+ if self.element_border:
331
+ f.write(f'<rect x="{rect_x}" y="{int(y)}" width="{int(pixel_size)}" height="{h}" fill="rgb({r},{g},{b})" stroke="{elem_col}" stroke-width="{elem_bw}" shape-rendering="crispEdges"/>')
332
+ else:
333
+ f.write(f'<rect x="{rect_x}" y="{int(y)}" width="{int(pixel_size)}" height="{h}" fill="rgb({r},{g},{b})" stroke="none" shape-rendering="crispEdges"/>')
334
+ total_w = display_size
335
+ f.write(f'<rect x="{x - 0.5}" y="{y - 0.5}" width="{total_w + 1}" height="{h + 1}" fill="none" stroke="black" stroke-width="1"/>')
336
+
337
+ draw_pos += display_size + gap_at(gap_pixels,slice_index)
338
+
339
+ # Step cursor for next annotation column
340
+ step = BAR_SIZE + TEXT_GAP
341
+ if direction in ['up', 'left']:
342
+ current_cursor -= step
343
+ else:
344
+ current_cursor += step
345
+
346
+
347
+ class ColorAnnotation(SimpleAnnotation):
348
+ """Continuous numeric annotation track with explicit color mappings."""
349
+ def __init__(self, df, color_mappings=None, **kwargs):
350
+ from .style import ColorMapping
351
+ super().__init__(df=df, **kwargs)
352
+ self.color_mappings={}
353
+ for col in self.df:
354
+ vals=pd.to_numeric(self.df[col],errors='raise').to_numpy(dtype=float)
355
+ finite=vals[np.isfinite(vals)]
356
+ mapping=(color_mappings or {}).get(col)
357
+ if mapping is None:
358
+ lo,hi=(float(finite.min()),float(finite.max())) if len(finite) else (0.,1.)
359
+ if lo==hi:lo-=.5;hi+=.5
360
+ mapping=ColorMapping([lo,hi],['white','#4682b4'])
361
+ if not isinstance(mapping,ColorMapping):raise TypeError('numeric annotation colors require ColorMapping / colorRamp2')
362
+ self.color_mappings[col]=mapping
363
+
364
+
365
+ class ExpressionAnnotation(AnnotationBase):
366
+ """
367
+ Numeric barplot annotation (Pixel-Perfect Vectorized).
368
+ Supports dynamic scaling, 4 directions (top, bottom, left, right),
369
+ and fast vectorized rendering.
370
+
371
+ If `agg` is set ('avg', 'median', 'min', 'max') and `df` is a matrix
372
+ (multiple rows), the values are aggregated per column using the given
373
+ function before rendering. This allows passing a raw expression matrix
374
+ and automatically summarizing it (e.g. average expression per sample).
375
+ """
376
+ # Barplots get a bit more room than the default auto band thickness.
377
+ auto_height_ratio = 2.1
378
+
379
+ def __init__(self, df=None, plot_color='steelblue', background_color='#f0f0f0', ylim=None, force_zero=False, show_border=True, border_color=None, border_width=None, element_border=None, agg=None, show_values=True, **kwargs):
380
+ if df is not None and not isinstance(df, (pd.DataFrame, pd.Series)):
381
+ df = pd.DataFrame({kwargs.get('label', 'value'): list(df)})
382
+ elif isinstance(df, pd.Series):
383
+ df = df.to_frame(kwargs.get('label', 'value'))
384
+ if agg is not None and df is not None and df.shape[0] > 1:
385
+ if kwargs.get('side') in ('top', 'bottom'):
386
+ df = df.T
387
+ if agg == 'avg':
388
+ df = df.agg('mean', axis=1).to_frame(kwargs.get('label', 'value'))
389
+ elif agg == 'median':
390
+ df = df.agg('median', axis=1).to_frame(kwargs.get('label', 'value'))
391
+ elif agg == 'min':
392
+ df = df.agg('min', axis=1).to_frame(kwargs.get('label', 'value'))
393
+ elif agg == 'max':
394
+ df = df.agg('max', axis=1).to_frame(kwargs.get('label', 'value'))
395
+ elif agg == 'std':
396
+ df = df.agg('std', axis=1).to_frame(kwargs.get('label', 'value'))
397
+ elif agg == 'mode':
398
+ df = df.mode(axis=1).iloc[:, 0].to_frame(kwargs.get('label', 'value'))
399
+ df.index = df.index.map(str)
400
+ super().__init__(df=df, **kwargs)
401
+ self.agg = agg
402
+ self.plot_color = plot_color
403
+ self.background_color = background_color
404
+ self.ylim = ylim
405
+ self.force_zero = force_zero
406
+ self.show_values = bool(show_values)
407
+ self.show_border = bool(show_border)
408
+ self.border_color = border_color
409
+ self.border_width = None if border_width is None else float(border_width)
410
+ # None = follow the heatmap's element border setting (per-cell grid).
411
+ self.element_border = element_border
412
+
413
+ def _get_bgr(self, color_str):
414
+ """Convert color (Hex/Name -> BGR tuple for OpenCV)."""
415
+ try:
416
+ from matplotlib.colors import to_rgb
417
+ rgb = to_rgb(color_str)
418
+ return (int(rgb[2]*255), int(rgb[1]*255), int(rgb[0]*255))
419
+ except:
420
+ return (128, 128, 128) # Default gray
421
+
422
+ def draw(self, f, start_x, start_y, pixel_size, bounds, gap_pixels, direction, renderer):
423
+ is_vertical = direction in ['left', 'right']
424
+ BAR_SIZE = _resolve_height(renderer, self)
425
+ fontsize = _resolve_fontsize(renderer, self.fontsize)
426
+ band_bw = _resolve_border_width(renderer, self.border_width)
427
+ band_col = _resolve_border_color(renderer, self.border_color)
428
+ use_elem = self.element_border if self.element_border is not None else bool(getattr(renderer, 'heatmap_element_border', False))
429
+ elem_bw = _resolve_border_width(renderer, None)
430
+ elem_col = _resolve_border_color(renderer, None)
431
+
432
+
433
+ fg_bgr = self._get_bgr(self.plot_color)
434
+ bg_bgr = self._get_bgr(self.background_color)
435
+
436
+ current_cursor = start_x if is_vertical else start_y
437
+
438
+ # Outer loop represents annotation columns. If no backing DataFrame
439
+ # is provided, iterate a single placeholder so rendering can derive
440
+ # values from the renderer matrix.
441
+ if getattr(self, 'df', None) is not None:
442
+ cols_iter = list(self.df.columns)
443
+ else:
444
+ cols_iter = [None]
445
+ if direction in ['up', 'left']:
446
+ cols_iter = reversed(cols_iter)
447
+
448
+ for col_name in cols_iter:
449
+ display_name = col_name if col_name is not None else (self.label or '')
450
+ # Source values: prefer provided DataFrame column, otherwise use
451
+ # per-axis aggregated values from renderer._matrix_sorted as fallback
452
+ if getattr(self, 'df', None) is not None and col_name is not None:
453
+ vals = self.df[col_name].values
454
+ else:
455
+ try:
456
+ agg_func = self.agg or 'avg'
457
+ src = getattr(renderer, '_matrix_raw_sorted', renderer._matrix_sorted)
458
+ if agg_func == 'mode':
459
+ from scipy.stats import mode as sp_mode
460
+ vals = sp_mode(src, axis=1 if is_vertical else 0, keepdims=False)[0]
461
+ else:
462
+ fn = {'avg': np.nanmean, 'mean': np.nanmean, 'median': np.nanmedian, 'min': np.nanmin, 'max': np.nanmax, 'std': lambda x, axis: np.nanstd(x, axis=axis, ddof=1)}[agg_func]
463
+ vals = fn(src, axis=1 if is_vertical else 0)
464
+ except Exception:
465
+ vals = np.array([np.nan])
466
+
467
+ # Label (Gene/Sample name)
468
+ if is_vertical:
469
+ horiz_gap = renderer.col_gap_pixels if hasattr(renderer, 'col_gap_pixels') else 0
470
+ text_x = int(current_cursor + BAR_SIZE/2) if direction == 'right' else int(current_cursor - BAR_SIZE/2 - horiz_gap)
471
+ total_h = sum([(b_end - b_start) * pixel_size for (b_start, b_end) in bounds])
472
+ gap_total = (total_slice_gap(slice_gaps(renderer,'row'),len(renderer.row_breaks))) if hasattr(renderer, 'row_breaks') else 0
473
+ total_h += gap_total
474
+
475
+ # allocate more horizontal space to avoid truncation of rotated label
476
+ if _canvas_w(renderer):
477
+ avail_px = max(300, _canvas_w(renderer) - (text_x + 100))
478
+ else:
479
+ avail_px = 300
480
+ t = _truncate_text(str(display_name), avail_px, fontsize)
481
+
482
+ if direction == 'left':
483
+ # Anchor just below the heatmap, offset by the rotated
484
+ # label's own length (text extends upwards from `text_y`).
485
+ lw = int(len(t) * fontsize * 0.6)
486
+ text_y = int(start_y + total_h + 10 + lw)
487
+ else:
488
+ text_y = int(start_y - 10)
489
+
490
+ f.write(f'<text x="{text_x}" y="{text_y}" transform="rotate(-90, {text_x}, {text_y})" font-family="Arial" font-size="{fontsize}" text-anchor="start" dominant-baseline="middle">{_escape_xml(t)}</text>')
491
+ else:
492
+ if direction in ['bottom', 'down']:
493
+ total_w = sum([(b_end - b_start) * pixel_size for (b_start, b_end) in bounds])
494
+ gap_total = (total_slice_gap(slice_gaps(renderer,'column'),len(renderer.col_breaks))) if hasattr(renderer, 'col_breaks') else 0
495
+ total_w += gap_total
496
+ text_x = int(start_x + total_w + 10)
497
+ base_y = getattr(self, '_band_pre_y', start_y)
498
+ band_h = getattr(self, '_band_annot_size', BAR_SIZE)
499
+ text_y = int(base_y + band_h / 2)
500
+ if _canvas_w(renderer):
501
+ avail_px = max(300, _canvas_w(renderer) - text_x - 40)
502
+ else:
503
+ avail_px = 300
504
+ t = _truncate_text(str(display_name), avail_px, fontsize)
505
+ f.write(f'<text x="{text_x}" y="{text_y}" font-family="Arial" font-size="{fontsize}" text-anchor="start" dominant-baseline="middle">{_escape_xml(t)}</text>')
506
+ else:
507
+ # Top annotations: center label inside the reserved band above
508
+ base_top = getattr(self, '_band_pre_y', start_y)
509
+ band_h = getattr(self, '_band_annot_size', BAR_SIZE)
510
+ text_y = int(base_top - band_h / 2)
511
+ f.write(f'<text x="{int(start_x - 10)}" y="{text_y}" font-family="Arial" font-size="{fontsize}" text-anchor="end" dominant-baseline="middle">{_escape_xml(display_name)}</text>')
512
+
513
+ # Data preparation
514
+ try: num_vals = vals.astype(float)
515
+ except: num_vals = np.zeros(len(vals))
516
+
517
+ # Scaling (Min-Max)
518
+ if np.all(np.isnan(num_vals)):
519
+ v_min, v_max = 0, 1
520
+ else:
521
+ d_min, d_max = np.nanmin(num_vals), np.nanmax(num_vals)
522
+ if self.ylim: v_min, v_max = self.ylim
523
+ else:
524
+ # Dynamic scale
525
+ span = d_max - d_min
526
+ v_min = d_min - (span * 0.05) if span > 0 else d_min
527
+ v_max = d_max
528
+
529
+ if self.force_zero and self.ylim is None:
530
+ v_min = min(0, v_min)
531
+ v_max = max(0, v_max)
532
+ if v_min == v_max: v_max += 1e-9
533
+ norm_vals = (num_vals - v_min) / (v_max - v_min)
534
+ norm_vals = np.nan_to_num(np.clip(norm_vals, 0, 1))
535
+
536
+ draw_pos = start_y if is_vertical else start_x
537
+
538
+ for slice_index, (b_start, b_end) in enumerate(bounds):
539
+ i=slice_index
540
+ chunk = norm_vals[b_start:b_end]
541
+ orig_chunk = num_vals[b_start:b_end] # Original values for display
542
+
543
+ n_items = len(chunk)
544
+ if n_items == 0: continue
545
+
546
+ display_len_px = int(n_items * pixel_size)
547
+ if display_len_px == 0: continue
548
+
549
+ # Pixel indexing
550
+ pixel_indices = np.arange(display_len_px)
551
+ data_indices = np.floor(pixel_indices / pixel_size).astype(int)
552
+ data_indices = np.clip(data_indices, 0, n_items - 1)
553
+
554
+ expanded_vals = chunk[data_indices]
555
+ bar_lens = (expanded_vals * BAR_SIZE).astype(int)
556
+
557
+ # Draw bars (render to PNG)
558
+ if is_vertical:
559
+ canvas = np.full((display_len_px, BAR_SIZE, 3), bg_bgr, dtype=np.uint8)
560
+ X_grid = np.arange(BAR_SIZE).reshape(1, -1)
561
+ bar_lens_col = bar_lens.reshape(-1, 1)
562
+
563
+ mask = X_grid < bar_lens_col
564
+ else:
565
+ canvas = np.full((BAR_SIZE, display_len_px, 3), bg_bgr, dtype=np.uint8)
566
+ Y_grid = np.arange(BAR_SIZE).reshape(-1, 1)
567
+ bar_lens_row = bar_lens.reshape(1, -1)
568
+
569
+ if direction == 'up': mask = Y_grid >= (BAR_SIZE - bar_lens_row)
570
+ else: mask = Y_grid < bar_lens_row
571
+
572
+ canvas[mask] = fg_bgr
573
+ raster_mode = getattr(renderer, 'rasterized', False)
574
+ raster_full = (raster_mode is True) or (isinstance(raster_mode, str) and str(raster_mode).lower() == 'full')
575
+
576
+ if raster_full:
577
+ _, buf = cv2.imencode('.png', canvas, [int(cv2.IMWRITE_PNG_COMPRESSION), 1])
578
+ b64 = base64.b64encode(buf).decode('utf-8')
579
+ # Coordinates
580
+ if is_vertical:
581
+ gap_x = renderer.col_gap_pixels if hasattr(renderer, 'col_gap_pixels') else 0
582
+ final_x = int(current_cursor - BAR_SIZE - gap_x) if direction == 'left' else int(current_cursor)
583
+ final_y = int(draw_pos)
584
+ w, h = BAR_SIZE, display_len_px
585
+ else:
586
+ final_x = int(draw_pos)
587
+ final_y = int(current_cursor - BAR_SIZE) if direction == 'up' else int(current_cursor)
588
+ w, h = display_len_px, BAR_SIZE
589
+
590
+ f.write(f'<image x="{final_x}" y="{final_y}" width="{w}" height="{h}" preserveAspectRatio="none" style="image-rendering:pixelated" shape-rendering="crispEdges" xlink:href="data:image/png;base64,{b64}" href="data:image/png;base64,{b64}" />')
591
+ if self.show_border:
592
+ f.write(f'<rect x="{final_x - band_bw/2}" y="{final_y - band_bw/2}" width="{w + band_bw}" height="{h + band_bw}" fill="none" stroke="{band_col}" stroke-width="{band_bw}"/>')
593
+ else:
594
+ # Vectorized rendering: draw per-data-cell background + filled portion
595
+ if is_vertical:
596
+ gap_x = renderer.col_gap_pixels if hasattr(renderer, 'col_gap_pixels') else 0
597
+ final_x = int(current_cursor - BAR_SIZE - gap_x) if direction == 'left' else int(current_cursor)
598
+ final_y = int(draw_pos)
599
+ w = BAR_SIZE
600
+ for j in range(n_items):
601
+ # background rect for this data cell
602
+ rect_y = int(final_y + j * pixel_size)
603
+ br, bg, bb = int(bg_bgr[2]), int(bg_bgr[1]), int(bg_bgr[0])
604
+ f.write(f'<rect x="{final_x}" y="{rect_y}" width="{w}" height="{int(pixel_size)}" fill="rgb({br},{bg},{bb})" stroke="none" shape-rendering="crispEdges"/>')
605
+ # filled portion
606
+ fill_len = int(bar_lens[j])
607
+ if fill_len > 0:
608
+ fx = final_x
609
+ fr, fg, fb = int(fg_bgr[2]), int(fg_bgr[1]), int(fg_bgr[0])
610
+ f.write(f'<rect x="{int(fx)}" y="{rect_y}" width="{int(fill_len)}" height="{int(pixel_size)}" fill="rgb({fr},{fg},{fb})" stroke="none" shape-rendering="crispEdges"/>')
611
+ # Internal grid line only (drawn on top of the
612
+ # fill); the outer edges come from the band border
613
+ # so the first/last row is never reduced.
614
+ if use_elem and j < n_items - 1:
615
+ yline = int(final_y + (j + 1) * pixel_size)
616
+ f.write(f'<line x1="{final_x}" y1="{yline}" x2="{final_x + w}" y2="{yline}" stroke="{elem_col}" stroke-width="{elem_bw}" shape-rendering="crispEdges"/>')
617
+ # border
618
+ if self.show_border:
619
+ f.write(f'<rect x="{final_x - band_bw/2}" y="{final_y - band_bw/2}" width="{w + band_bw}" height="{display_len_px + band_bw}" fill="none" stroke="{band_col}" stroke-width="{band_bw}"/>')
620
+ else:
621
+ final_x = int(draw_pos)
622
+ final_y = int(current_cursor - BAR_SIZE) if direction == 'up' else int(current_cursor)
623
+ h = BAR_SIZE
624
+ for j in range(n_items):
625
+ rect_x = int(final_x + j * pixel_size)
626
+ br, bg, bb = int(bg_bgr[2]), int(bg_bgr[1]), int(bg_bgr[0])
627
+ f.write(f'<rect x="{rect_x}" y="{final_y}" width="{int(pixel_size)}" height="{h}" fill="rgb({br},{bg},{bb})" stroke="none" shape-rendering="crispEdges"/>')
628
+ fill_len = int(bar_lens[j])
629
+ if fill_len > 0:
630
+ if direction == 'up':
631
+ fy = final_y + (h - fill_len)
632
+ else:
633
+ fy = final_y
634
+ fr, fg, fb = int(fg_bgr[2]), int(fg_bgr[1]), int(fg_bgr[0])
635
+ f.write(f'<rect x="{rect_x}" y="{int(fy)}" width="{int(pixel_size)}" height="{int(fill_len)}" fill="rgb({fr},{fg},{fb})" stroke="none" shape-rendering="crispEdges"/>')
636
+ # Internal grid line only (drawn on top of the
637
+ # fill); the outer edges come from the band border
638
+ # so the first/last column is never reduced.
639
+ if use_elem and j < n_items - 1:
640
+ xline = int(final_x + (j + 1) * pixel_size)
641
+ f.write(f'<line x1="{xline}" y1="{final_y}" x2="{xline}" y2="{final_y + h}" stroke="{elem_col}" stroke-width="{elem_bw}" shape-rendering="crispEdges"/>')
642
+ # border
643
+ if self.show_border:
644
+ f.write(f'<rect x="{final_x - band_bw/2}" y="{final_y - band_bw/2}" width="{display_len_px + band_bw}" height="{h + band_bw}" fill="none" stroke="{band_col}" stroke-width="{band_bw}"/>')
645
+
646
+ # Render numeric labels (only if enough space)
647
+ # Only write if pixel_size > 10
648
+ if self.show_values and pixel_size > 12:
649
+ for idx, val in enumerate(orig_chunk):
650
+ # Calculate position
651
+ center_pos = draw_pos + (idx * pixel_size) + (pixel_size / 2)
652
+
653
+ val_str = f"{val:.1f}"
654
+ if is_vertical:
655
+ # Right-side bar: text at bar center
656
+ txt_x = final_x + (BAR_SIZE / 2)
657
+ txt_y = center_pos
658
+ f.write(f'<text x="{txt_x}" y="{txt_y}" font-family="Arial" font-size="{fontsize}" fill="black" text-anchor="middle" dominant-baseline="middle">{_escape_xml(val_str)}</text>')
659
+ else:
660
+ # Bottom bar
661
+ txt_x = center_pos
662
+ txt_y = final_y + (BAR_SIZE / 2)
663
+ # Rotated 90 degrees if too dense
664
+ f.write(f'<text x="{txt_x}" y="{txt_y}" transform="rotate(-90, {txt_x}, {txt_y})" font-family="Arial" font-size="{fontsize}" fill="black" text-anchor="middle" dominant-baseline="middle">{_escape_xml(val_str)}</text>')
665
+
666
+ draw_pos += (n_items * pixel_size) + gap_at(gap_pixels,slice_index)
667
+
668
+ # Step cursor for next annotation column
669
+ step = BAR_SIZE + getattr(renderer, '_annot_gap_px', 5)
670
+ if direction in ['up', 'left']: current_cursor -= step
671
+ else: current_cursor += step
672
+
673
+
674
+ class BoxplotAnnotation(AnnotationBase):
675
+ """Boxplot-style annotation.
676
+
677
+ Renders a compact boxplot for each `bounds` block for every column in
678
+ `self.df`. For top/bottom the boxplot is drawn vertically within the
679
+ annotation height; for left/right it is drawn horizontally.
680
+ """
681
+ # Boxplots get a bit more room than the default auto band thickness.
682
+ auto_height_ratio = 1.9
683
+
684
+ def __init__(self, df=None, box_data=None, box_color='#444444', whisker_color='#222222', outlier_color='#cc0000', width_frac=0.5, show_outliers=True, outlier_radius='auto', ylim=None, border=True, border_color=None, border_width=None, border_padding=2, whisker_padding=8, inner_spacing=4, **kwargs):
685
+ # Ensure BoxplotAnnotation is always rendered on the bottom side.
686
+ # Remove any user-supplied `side` in kwargs to prevent accidental overrides
687
+ # or duplicate-key errors when calling the base initializer.
688
+ kwargs.pop('side', None)
689
+ if df is not None and not isinstance(df, (pd.DataFrame, pd.Series)):
690
+ df = pd.DataFrame({kwargs.get('label', 'value'): list(df)})
691
+ elif isinstance(df, pd.Series):
692
+ df = df.to_frame(kwargs.get('label', 'value'))
693
+ super().__init__(df=df, side="bottom", **kwargs)
694
+ # Optional custom data source for boxplot distributions.
695
+ # If None, renderer._matrix_sorted is used (current default behavior).
696
+ self.box_data = box_data
697
+ self.box_color = box_color
698
+ self.whisker_color = whisker_color
699
+ self.outlier_color = outlier_color
700
+ self.width_frac = float(width_frac)
701
+ self.show_outliers = bool(show_outliers)
702
+ # `auto` => radius scales with annotation column width (`pixel_size`).
703
+ self.outlier_radius = outlier_radius
704
+ self.ylim = ylim
705
+ self.border = bool(border)
706
+ self.border_color = border_color
707
+ self.border_width = None if border_width is None else float(border_width)
708
+ self.border_padding = int(border_padding)
709
+ self.whisker_padding = int(whisker_padding)
710
+ self.inner_spacing = int(inner_spacing)
711
+
712
+ def _get_rgb(self, color_str):
713
+ try:
714
+ from matplotlib.colors import to_rgb
715
+ rgb = to_rgb(color_str)
716
+ return (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255))
717
+ except:
718
+ return (68, 68, 68)
719
+
720
+ def _get_box_col_values(self, renderer, col_idx):
721
+ """Return values for one boxplot column from custom `box_data` or renderer matrix."""
722
+ if self.box_data is not None:
723
+ try:
724
+ # Prefer label-based access when DataFrame columns match heatmap columns.
725
+ sorted_cols = np.array(renderer.col_names)[renderer._col_order]
726
+ col_key = sorted_cols[col_idx] if col_idx < len(sorted_cols) else None
727
+ except Exception:
728
+ col_key = None
729
+
730
+ if isinstance(self.box_data, pd.DataFrame):
731
+ try:
732
+ if col_key is not None and col_key in self.box_data.columns:
733
+ return np.asarray(self.box_data[col_key].values, dtype=float)
734
+ return np.asarray(self.box_data.iloc[:, col_idx].values, dtype=float)
735
+ except Exception:
736
+ pass
737
+ else:
738
+ try:
739
+ arr = np.asarray(self.box_data, dtype=float)
740
+ if arr.ndim == 2:
741
+ return arr[:, col_idx]
742
+ if arr.ndim == 1 and col_idx < len(arr):
743
+ return np.asarray([arr[col_idx]], dtype=float)
744
+ except Exception:
745
+ pass
746
+
747
+ # Fallback: existing behavior from heatmap matrix
748
+ try:
749
+ return np.asarray(renderer._matrix_sorted[:, col_idx], dtype=float)
750
+ except Exception:
751
+ return np.asarray([np.nan], dtype=float)
752
+
753
+ def _resolve_outlier_radius(self, pixel_size):
754
+ """Resolve outlier radius: auto scales with pixel size, numeric stays fixed."""
755
+ if isinstance(self.outlier_radius, str) and self.outlier_radius.lower() == 'auto':
756
+ # Dynamic radius tied to column width.
757
+ # - keep tiny minimum for very narrow columns
758
+ # - grow the radius for wider columns so large columns show larger points
759
+ try:
760
+ p = float(pixel_size)
761
+ except Exception:
762
+ p = 8.0
763
+ if p <= 8:
764
+ r = p * 0.09
765
+ elif p <= 24:
766
+ r = p * 0.12
767
+ else:
768
+ # For wide columns reduce radius to approx. 50% of previous wide multiplier
769
+ r = p * 0.08
770
+ # clamp to reasonable visual bounds
771
+ return max(0.08, min(r, max(6.0, p * 0.5)))
772
+ try:
773
+ return max(0.1, float(self.outlier_radius))
774
+ except Exception:
775
+ return 1.0
776
+
777
+
778
+ def draw(self, f, start_x, start_y, pixel_size, bounds, gap_pixels, direction, renderer):
779
+ # Force boxplots to render as bottom (horizontal) annotation band.
780
+ # Ignore incoming `direction` and treat as 'bottom'. This fixes cases
781
+ # where caller accidentally requests a different side.
782
+ direction = 'bottom'
783
+ is_vertical = False
784
+ BAR_SIZE = _resolve_height(renderer, self)
785
+ fontsize = _resolve_fontsize(renderer, self.fontsize)
786
+ box_bw = _resolve_border_width(renderer, self.border_width)
787
+ box_col = _resolve_border_color(renderer, self.border_color)
788
+ box_w_frac = max(0.05, min(0.95, self.width_frac))
789
+
790
+ box_rgb = self._get_rgb(self.box_color)
791
+ whisker_rgb = self._get_rgb(self.whisker_color)
792
+ out_rgb = self._get_rgb(self.outlier_color)
793
+ outlier_r = self._resolve_outlier_radius(pixel_size)
794
+
795
+ current_cursor = start_x if is_vertical else start_y
796
+ # If the underlying matrix is very large, do not attempt to draw
797
+ # boxplots (expensive). Abort early for >1000 items.
798
+ try:
799
+ if is_vertical:
800
+ n_items_total = renderer._matrix_sorted.shape[0]
801
+ else:
802
+ n_items_total = renderer._matrix_sorted.shape[1]
803
+ except Exception:
804
+ n_items_total = 0
805
+ if n_items_total > BOXPLOT_MAX_ITEMS:
806
+ try:
807
+ warn_x = int(start_x + 4)
808
+ warn_y = int(start_y + (BAR_SIZE // 2))
809
+ f.write(f'<text x="{warn_x}" y="{warn_y}" font-family="Arial" font-size="{max(8, fontsize)}" fill="red">Boxplot disabled for &gt;{BOXPLOT_MAX_ITEMS} genes</text>')
810
+ except Exception:
811
+ pass
812
+ return
813
+ # Outer loop represents annotation columns (usually 1). If a backing
814
+ # DataFrame was provided, keep its columns; otherwise use a single
815
+ # placeholder so the annotation still renders while deriving values
816
+ # exclusively from the renderer's matrix.
817
+ if getattr(self, 'df', None) is not None:
818
+ cols_iter = list(self.df.columns)
819
+ else:
820
+ cols_iter = [None]
821
+ if direction in ['up', 'left']:
822
+ cols_iter = reversed(cols_iter)
823
+
824
+ for col_name in cols_iter:
825
+ display_name = col_name if col_name is not None else (self.label or '')
826
+ if getattr(self, 'df', None) is not None and col_name is not None:
827
+ vals = self.df[col_name].values
828
+ else:
829
+ try:
830
+ if is_vertical:
831
+ vals = np.nanmean(renderer._matrix_sorted, axis=1)
832
+ else:
833
+ vals = np.nanmean(renderer._matrix_sorted, axis=0)
834
+ except Exception:
835
+ vals = np.array([np.nan])
836
+ # Determine global scale for this column (vmin/vmax)
837
+ try:
838
+ num_vals = vals.astype(float)
839
+ except:
840
+ num_vals = np.array([np.nan])
841
+
842
+ if self.ylim:
843
+ v_min, v_max = self.ylim
844
+ else:
845
+ if np.all(np.isnan(num_vals)):
846
+ v_min, v_max = 0.0, 1.0
847
+ else:
848
+ dmin = np.nanmin(num_vals)
849
+ dmax = np.nanmax(num_vals)
850
+ if dmin == dmax:
851
+ v_min, v_max = dmin - 0.5, dmax + 0.5
852
+ else:
853
+ v_min, v_max = dmin, dmax
854
+
855
+ if v_min == v_max:
856
+ v_max = v_min + 1e-9
857
+
858
+ # Apply a vertical offset equal to the incoming gap so that the
859
+ # border and the actual boxplot are rendered after that gap.
860
+ # This makes the gap appear between the heatmap and the annotation
861
+ # content (vertical shift). For 'down'/'bottom' we shift positively,
862
+ # for 'up'/'top' negatively. For left/right (vertical bands) we
863
+ # still apply the same vertical offset so gaps align with rows.
864
+ base_start_y = start_y
865
+ if direction in ['down', 'bottom']:
866
+ base_start_y = int(start_y + gap_at(gap_pixels,0))
867
+ elif direction in ['up', 'top']:
868
+ base_start_y = int(start_y - gap_at(gap_pixels,0))
869
+
870
+ # Iterate over bounds and render a boxplot per block
871
+ draw_pos = base_start_y if is_vertical else start_x
872
+
873
+ # Track overall extents so outer border can enclose whiskers.
874
+ if not is_vertical:
875
+ overall_xmin = float('inf')
876
+ overall_xmax = float('-inf')
877
+ overall_ymin = float('inf')
878
+ overall_ymax = float('-inf')
879
+
880
+ for slice_index,(b_start, b_end) in enumerate(bounds):
881
+ chunk = num_vals[b_start:b_end]
882
+ clean = chunk[~np.isnan(chunk)]
883
+ n_items = len(clean)
884
+ if n_items == 0:
885
+ # advance and continue
886
+ draw_pos += max(1, (b_end - b_start) * pixel_size) + gap_at(gap_pixels,slice_index)
887
+ continue
888
+
889
+ q1, q2, q3 = np.percentile(clean, [25, 50, 75])
890
+ iqr = q3 - q1
891
+ whisk_low = np.min(clean)
892
+ whisk_high = np.max(clean)
893
+ # Tukey-style whiskers (within 1.5 IQR)
894
+ if iqr > 0:
895
+ w_low = q1 - 1.5 * iqr
896
+ w_high = q3 + 1.5 * iqr
897
+ whisk_low = np.max([whisk_low, w_low])
898
+ whisk_high = np.min([whisk_high, w_high])
899
+
900
+ # Map a value to pixel coordinate inside BAR_SIZE
901
+ def map_to_px(v):
902
+ t = (v - v_min) / (v_max - v_min)
903
+ t = np.clip(t, 0.0, 1.0)
904
+ # For top/bottom (vertical plotting) 0 -> bottom, 1 -> top
905
+ return t
906
+
907
+ # Display span in pixels
908
+ display_len_px = int((b_end - b_start) * pixel_size)
909
+ if display_len_px <= 0:
910
+ draw_pos += gap_at(gap_pixels,slice_index)
911
+ continue
912
+
913
+ # Always render per-column boxplots for horizontal annotations
914
+ if not is_vertical:
915
+ # Use external box_data or renderer matrix to build per-column matrix
916
+ if hasattr(renderer, '_matrix_sorted'):
917
+ try:
918
+ if self.box_data is not None:
919
+ # Build per-column matrix from external box_data
920
+ cols = np.arange(b_start, b_end)
921
+ sorted_cols = np.array(renderer.col_names)[renderer._col_order]
922
+ col_list = [np.asarray(
923
+ self._get_box_col_values(renderer, c), dtype=float
924
+ ) for c in cols]
925
+ # Pad to same length
926
+ max_len = max(len(c) for c in col_list)
927
+ M = np.column_stack([
928
+ np.pad(c, (0, max_len - len(c)),
929
+ constant_values=np.nan)
930
+ for c in col_list
931
+ ])
932
+ else:
933
+ mat = np.asarray(renderer._matrix_sorted, dtype=float)
934
+ if mat.ndim == 1:
935
+ mat = mat.reshape(-1, 1)
936
+ cols = np.arange(b_start, b_end)
937
+ M = mat[:, cols]
938
+ # per-column stats
939
+ q1s = np.nanpercentile(M, 25, axis=0)
940
+ q2s = np.nanpercentile(M, 50, axis=0)
941
+ q3s = np.nanpercentile(M, 75, axis=0)
942
+ except Exception:
943
+ q1s = q2s = q3s = np.array([np.nan] * (b_end - b_start))
944
+
945
+ # global vmin/vmax for mapping (fast path)
946
+ if self.ylim is not None:
947
+ vmin_global, vmax_global = self.ylim
948
+ else:
949
+ try:
950
+ src = self.box_data if self.box_data is not None else renderer._matrix_sorted
951
+ vmin_global = float(np.nanmin(np.asarray(src, dtype=float)))
952
+ vmax_global = float(np.nanmax(np.asarray(src, dtype=float)))
953
+ except Exception:
954
+ vmin_global, vmax_global = 0.0, 1.0
955
+ if vmin_global == vmax_global:
956
+ vmax_global = vmin_global + 1e-9
957
+
958
+ def map_to_t_global(v):
959
+ t = (v - vmin_global) / (vmax_global - vmin_global)
960
+ return np.clip(t, 0.0, 1.0)
961
+
962
+ for j in range(b_end - b_start):
963
+ col = M[:, j]
964
+ clean_col = col[~np.isnan(col)]
965
+ if clean_col.size == 0:
966
+ continue
967
+ q1 = q1s[j]
968
+ q2 = q2s[j]
969
+ q3 = q3s[j]
970
+ iqr = q3 - q1
971
+ whisk_low = np.min(clean_col)
972
+ whisk_high = np.max(clean_col)
973
+ if iqr > 0:
974
+ w_low = q1 - 1.5 * iqr
975
+ w_high = q3 + 1.5 * iqr
976
+ whisk_low = np.max([whisk_low, w_low])
977
+ whisk_high = np.min([whisk_high, w_high])
978
+
979
+ final_x = int(draw_pos + j * pixel_size)
980
+ if direction == 'up':
981
+ band_top = int(base_start_y - BAR_SIZE)
982
+ else:
983
+ band_top = int(base_start_y)
984
+ inner_v = max(0, int(self.inner_spacing))
985
+ usable_h = max(2, int(BAR_SIZE - (2 * inner_v)))
986
+ final_y = int(band_top + inner_v)
987
+ box_w = max(1, int(pixel_size * box_w_frac))
988
+ cx = int(final_x + pixel_size / 2)
989
+
990
+ y_q1 = int(final_y + (1.0 - map_to_t_global(q1)) * usable_h)
991
+ y_q2 = int(final_y + (1.0 - map_to_t_global(q2)) * usable_h)
992
+ y_q3 = int(final_y + (1.0 - map_to_t_global(q3)) * usable_h)
993
+ y_wlow = int(final_y + (1.0 - map_to_t_global(whisk_low)) * usable_h)
994
+ y_whigh = int(final_y + (1.0 - map_to_t_global(whisk_high)) * usable_h)
995
+
996
+ br, bg, bb = box_rgb
997
+ x0 = int(cx - box_w / 2)
998
+ f.write(f'<rect x="{x0}" y="{min(y_q1,y_q3)}" width="{box_w}" height="{abs(y_q3 - y_q1)}" fill="rgb({br},{bg},{bb})" fill-opacity="0.9" stroke="{self.whisker_color}" stroke-width="0.6" />')
999
+ f.write(f'<line x1="{x0}" y1="{y_q2}" x2="{x0+box_w}" y2="{y_q2}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1000
+ f.write(f'<line x1="{cx}" y1="{y_q3}" x2="{cx}" y2="{y_whigh}" stroke="{self.whisker_color}" stroke-width="0.6" />')
1001
+ f.write(f'<line x1="{cx}" y1="{y_q1}" x2="{cx}" y2="{y_wlow}" stroke="{self.whisker_color}" stroke-width="0.6" />')
1002
+ cap_w = max(1, int(box_w * 0.5))
1003
+ f.write(f'<line x1="{cx - cap_w//2}" y1="{y_whigh}" x2="{cx + cap_w//2}" y2="{y_whigh}" stroke="{self.whisker_color}" stroke-width="0.6" />')
1004
+ f.write(f'<line x1="{cx - cap_w//2}" y1="{y_wlow}" x2="{cx + cap_w//2}" y2="{y_wlow}" stroke="{self.whisker_color}" stroke-width="0.6" />')
1005
+
1006
+ if self.show_outliers:
1007
+ outliers = clean_col[(clean_col < whisk_low) | (clean_col > whisk_high)]
1008
+ for o in outliers:
1009
+ oy = int(final_y + (1.0 - map_to_t_global(o)) * usable_h)
1010
+ or_, og, ob = out_rgb
1011
+ f.write(f'<circle cx="{cx}" cy="{oy}" r="{outlier_r}" fill="rgb({or_},{og},{ob})" />')
1012
+ # advance draw_pos by the span
1013
+ draw_pos += display_len_px + gap_at(gap_pixels,slice_index)
1014
+ continue
1015
+ # else fall through to existing per-column path
1016
+
1017
+ # Center position for the boxplot within the span
1018
+ center_pos = draw_pos + display_len_px / 2
1019
+
1020
+ if is_vertical:
1021
+ # Vertical layout: box extends horizontally (width) and values mapped along vertical BAR_SIZE
1022
+ box_w = max(2, int(display_len_px * box_w_frac))
1023
+ # x coordinate (centered)
1024
+ x0 = int(center_pos - box_w / 2)
1025
+ # y coordinate mapping (pixel positions inside BAR_SIZE)
1026
+ # Top baseline for annotation area
1027
+ y_top = int(base_start_y)
1028
+ # Map values to offset inside BAR_SIZE (0..BAR_SIZE)
1029
+ def vpx(v):
1030
+ return int(y_top + (1.0 - map_to_px(v)) * BAR_SIZE)
1031
+
1032
+ y_q1 = vpx(q1)
1033
+ y_q2 = vpx(q2)
1034
+ y_q3 = vpx(q3)
1035
+ y_wlow = vpx(whisk_low)
1036
+ y_whigh = vpx(whisk_high)
1037
+
1038
+ # Draw box (q1..q3)
1039
+ br, bg, bb = box_rgb
1040
+ f.write(f'<rect x="{x0}" y="{min(y_q1,y_q3)}" width="{box_w}" height="{abs(y_q3 - y_q1)}" fill="rgb({br},{bg},{bb})" fill-opacity="0.9" stroke="{self.whisker_color}" stroke-width="0.8" />')
1041
+ # Median line
1042
+ f.write(f'<line x1="{x0}" y1="{y_q2}" x2="{x0+box_w}" y2="{y_q2}" stroke="{self.whisker_color}" stroke-width="1.2" />')
1043
+ # Whiskers
1044
+ cx = int(x0 + box_w/2)
1045
+ f.write(f'<line x1="{cx}" y1="{y_q3}" x2="{cx}" y2="{y_whigh}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1046
+ f.write(f'<line x1="{cx}" y1="{y_q1}" x2="{cx}" y2="{y_wlow}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1047
+ # Whisker caps
1048
+ cap_w = max(2, int(box_w * 0.6))
1049
+ f.write(f'<line x1="{cx - cap_w//2}" y1="{y_whigh}" x2="{cx + cap_w//2}" y2="{y_whigh}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1050
+ f.write(f'<line x1="{cx - cap_w//2}" y1="{y_wlow}" x2="{cx + cap_w//2}" y2="{y_wlow}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1051
+
1052
+ # Outliers
1053
+ if self.show_outliers:
1054
+ outliers = clean[(clean < whisk_low) | (clean > whisk_high)]
1055
+ for o in outliers:
1056
+ oy = vpx(o)
1057
+ or_, og, ob = out_rgb
1058
+ f.write(f'<circle cx="{cx}" cy="{oy}" r="{outlier_r}" fill="rgb({or_},{og},{ob})" />')
1059
+
1060
+ # Surrounding border for the vertical boxplot span
1061
+ if self.border:
1062
+ pad = max(0, int(self.border_padding))
1063
+ extra = max(0, int(self.whisker_padding))
1064
+ # Include whisker extents in the span and add extra
1065
+ # whisker padding so whiskers don't touch the border.
1066
+ ymin = min(y_q1, y_q3, y_wlow, y_whigh)
1067
+ ymax = max(y_q1, y_q3, y_wlow, y_whigh)
1068
+ inset = pad + extra + self.inner_spacing
1069
+ span_x = x0 - inset
1070
+ span_y = ymin - inset
1071
+ span_w = box_w + (inset * 2)
1072
+ span_h = max(1, (ymax - ymin) + (inset * 2))
1073
+ f.write(f'<rect x="{span_x}" y="{span_y}" width="{span_w}" height="{span_h}" fill="none" stroke="{box_col}" stroke-width="{box_bw}" />')
1074
+
1075
+ else:
1076
+ # Horizontal layout: values mapped along x-axis, box vertically centered in BAR_SIZE
1077
+ box_h = max(2, int(BAR_SIZE * box_w_frac))
1078
+ y0 = int(base_start_y + (BAR_SIZE / 2) - box_h / 2)
1079
+
1080
+ def vpx_x(v):
1081
+ return int(draw_pos + map_to_px(v) * display_len_px)
1082
+
1083
+ x_q1 = vpx_x(q1)
1084
+ x_q2 = vpx_x(q2)
1085
+ x_q3 = vpx_x(q3)
1086
+ x_wlow = vpx_x(whisk_low)
1087
+ x_whigh = vpx_x(whisk_high)
1088
+
1089
+ br, bg, bb = box_rgb
1090
+ f.write(f'<rect x="{min(x_q1,x_q3)}" y="{y0}" width="{abs(x_q3 - x_q1)}" height="{box_h}" fill="rgb({br},{bg},{bb})" fill-opacity="0.9" stroke="{self.whisker_color}" stroke-width="0.8" />')
1091
+ # Median
1092
+ mx = x_q2
1093
+ f.write(f'<line x1="{mx}" y1="{y0}" x2="{mx}" y2="{y0+box_h}" stroke="{self.whisker_color}" stroke-width="1.2" />')
1094
+ # Whiskers
1095
+ cy = int(y0 + box_h/2)
1096
+ f.write(f'<line x1="{x_q3}" y1="{cy}" x2="{x_whigh}" y2="{cy}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1097
+ f.write(f'<line x1="{x_q1}" y1="{cy}" x2="{x_wlow}" y2="{cy}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1098
+ # Caps
1099
+ cap_h = max(2, int(box_h * 0.6))
1100
+ f.write(f'<line x1="{x_whigh}" y1="{cy - cap_h//2}" x2="{x_whigh}" y2="{cy + cap_h//2}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1101
+ f.write(f'<line x1="{x_wlow}" y1="{cy - cap_h//2}" x2="{x_wlow}" y2="{cy + cap_h//2}" stroke="{self.whisker_color}" stroke-width="0.9" />')
1102
+
1103
+ if self.show_outliers:
1104
+ outliers = clean[(clean < whisk_low) | (clean > whisk_high)]
1105
+ for o in outliers:
1106
+ ox = vpx_x(o)
1107
+ or_, og, ob = out_rgb
1108
+ f.write(f'<circle cx="{ox}" cy="{cy}" r="{outlier_r}" fill="rgb({or_},{og},{ob})" />')
1109
+
1110
+ # Surrounding border for horizontal boxplot span (per-block)
1111
+ if self.border:
1112
+ pad = max(0, int(self.border_padding))
1113
+ extra = max(0, int(self.whisker_padding))
1114
+ xmin = min(x_q1, x_q3, x_wlow, x_whigh)
1115
+ xmax = max(x_q1, x_q3, x_wlow, x_whigh)
1116
+ # Update overall extents for the whole annotation band
1117
+ try:
1118
+ overall_xmin = min(overall_xmin, xmin)
1119
+ overall_xmax = max(overall_xmax, xmax)
1120
+ overall_ymin = min(overall_ymin, y0)
1121
+ overall_ymax = max(overall_ymax, y0 + box_h)
1122
+ except NameError:
1123
+ overall_xmin = xmin
1124
+ overall_xmax = xmax
1125
+ overall_ymin = y0
1126
+ overall_ymax = y0 + box_h
1127
+ # Draw per-span inner border (pad only)
1128
+ inset = pad + self.inner_spacing
1129
+ span_x = xmin - inset
1130
+ span_y = y0 - inset
1131
+ span_w = max(1, (xmax - xmin) + (inset * 2))
1132
+ span_h = box_h + (inset * 2)
1133
+ f.write(f'<rect x="{span_x}" y="{span_y}" width="{span_w}" height="{span_h}" fill="none" stroke="{box_col}" stroke-width="{box_bw}" />')
1134
+
1135
+ # advance draw_pos
1136
+ draw_pos += display_len_px + gap_at(gap_pixels,slice_index)
1137
+
1138
+ # Label text at the right side of the boxplot band
1139
+ if direction in ['down', 'bottom']:
1140
+ total_w = sum([(b_end - b_start) * pixel_size for (b_start, b_end) in bounds])
1141
+ gap_total = (total_slice_gap(slice_gaps(renderer,'column'),len(renderer.col_breaks))) if hasattr(renderer, 'col_breaks') else 0
1142
+ total_w += gap_total
1143
+ text_x = int(start_x + total_w + 10)
1144
+ avail_px = max(300, (_canvas_w(renderer) or 3000) - text_x - 40)
1145
+ t = _truncate_text(str(display_name), avail_px, fontsize)
1146
+ label_y = int(base_start_y + BAR_SIZE / 2)
1147
+ f.write(f'<text x="{text_x}" y="{label_y}" font-family="Arial" font-size="{fontsize}" text-anchor="start" dominant-baseline="middle">{_escape_xml(t)}</text>')
1148
+
1149
+ # step cursor for next annotation column
1150
+ step = BAR_SIZE + getattr(renderer, '_annot_gap_px', 5)
1151
+ if direction in ['up', 'left']: current_cursor -= step
1152
+ else: current_cursor += step